From 4d8fdd27960f9fb3fa818636413b67030eb81577 Mon Sep 17 00:00:00 2001 From: Jennifer Echenim Date: Tue, 2 Jul 2024 11:46:17 +0400 Subject: [PATCH] wip: refactor provider --- .../src/components/modules/bridge/index.tsx | 457 ++++++++---------- .../components/providers/wallet-provider.tsx | 77 +-- 2 files changed, 260 insertions(+), 274 deletions(-) diff --git a/contracts/src/bridge/frontend/src/components/modules/bridge/index.tsx b/contracts/src/bridge/frontend/src/components/modules/bridge/index.tsx index fc14520010..3ecb6caf54 100644 --- a/contracts/src/bridge/frontend/src/components/modules/bridge/index.tsx +++ b/contracts/src/bridge/frontend/src/components/modules/bridge/index.tsx @@ -8,7 +8,7 @@ import { } from "@/src/components/ui/card"; import { Button } from "@/src/components/ui/button"; import { Skeleton } from "@/src/components/ui/skeleton"; -import { ArrowDownUpIcon, Loader, PlusIcon, Terminal } from "lucide-react"; +import { ArrowDownUpIcon, Loader, PlusIcon } from "lucide-react"; import { Select, SelectContent, @@ -17,7 +17,6 @@ import { SelectValue, } from "../../ui/select"; import { Separator } from "../../ui/separator"; - import { Form, FormControl, @@ -34,8 +33,7 @@ import { L1TOKENS, L2TOKENS, PERCENTAGES } from "@/src/lib/constants"; import { z } from "zod"; import { useFormHook } from "@/src/hooks/useForm"; import { useWalletStore } from "../../providers/wallet-provider"; -import { ToastType, Token } from "@/src/types"; -import { Alert, AlertDescription } from "../../ui/alert"; +import { ToastType, Token, WalletNetwork } from "@/src/types"; import ConnectWalletButton from "../common/connect-wallet"; import TruncatedAddress from "../common/truncated-address"; import { useContract } from "@/src/hooks/useContract"; @@ -52,7 +50,6 @@ export default function Dashboard() { } = useWalletStore(); const { getNativeBalance, getTokenBalance, sendERC20, sendNative } = useContract(); - const { form, FormSchema } = useFormHook(); const [loading, setLoading] = React.useState(false); const [fromTokenBalance, setFromTokenBalance] = React.useState(0); @@ -61,22 +58,21 @@ export default function Dashboard() { const receiver = form.watch("receiver"); const swapTokens = () => { - switchNetwork(isL1ToL2 ? "L2" : "L1"); + switchNetwork( + isL1ToL2 ? WalletNetwork.L2_TEN_TESTNET : WalletNetwork.L1_SEPOLIA + ); }; const [open, setOpen] = React.useState(false); const watchTokenChange = form.watch("token"); + React.useEffect(() => { const tokenBalance = async (value: string, token: Token) => { setLoading(true); try { - tokens.find((t) => t.value === value); - let balance; - if (token.isNative) { - balance = await getNativeBalance(provider, address); - } else { - balance = await getTokenBalance(token.address, address, provider); - } + const balance = token.isNative + ? await getNativeBalance(provider, address) + : await getTokenBalance(token.address, address, provider); setFromTokenBalance(balance); } catch (error) { console.error(error); @@ -91,33 +87,27 @@ export default function Dashboard() { tokenBalance(watchTokenChange, token); } } - // eslint-disable-next-line react-hooks/exhaustive-deps }, [watchTokenChange, address, provider]); async function onSubmit(data: z.infer) { try { setLoading(true); - const d = { - ...data, - receiver: receiver ? receiver : address, - }; + const transactionData = { ...data, receiver: receiver || address }; toast({ title: "Bridge Transaction", description: "Bridge transaction initiated", variant: ToastType.INFO, }); - const token = d.token; - const t = tokens.find((t) => t.value === token); - if (!t) { - throw new Error("Invalid token"); - } + const token = tokens.find((t) => t.value === transactionData.token); + if (!token) throw new Error("Invalid token"); - const sendTransaction = t.isNative ? sendNative : sendERC20; + const sendTransaction = token.isNative ? sendNative : sendERC20; const res = await sendTransaction( - d.receiver ? d.receiver : address, - d.amount, - t.address + transactionData.receiver, + transactionData.amount, + token.address ); + toast({ title: "Bridge Transaction", description: `Bridge transaction completed: ${res.transactionHash}`, @@ -149,33 +139,64 @@ export default function Dashboard() { }); return; } - const roundDown = (num: number) => Math.floor(num * 100) / 100; - const amount = roundDown((fromTokenBalance * value) / 100); + const amount = Math.floor(((fromTokenBalance * value) / 100) * 100) / 100; form.setValue("amount", amount.toString()); }; return ( - <> -
- - - Bridge - - You are currently bridging from {isL1ToL2 ? "L1" : "L2"} to{" "} - {isL1ToL2 ? "L2" : "L1"}. - - - - -
- -
-
- Transfer from - {/* From Chain Select */} +
+ + + Bridge + + You are currently bridging from {isL1ToL2 ? "L1" : "L2"} to{" "} + {isL1ToL2 ? "L2" : "L1"}. + + + + + + +
+
+ Transfer from + {/* From Chain Select */} + ( + + + + + )} + /> +
+ +
+
+ {/* Token Select */} ( - - - - - - - {tokens.map((token) => ( - - {token.value} - - ))} - - - - - )} - /> - - {/* Balance */} -
-

- Balance: -

- - {loading ? : fromTokenBalance || 0} - -
-
- -
- {/* Amount Input */} - ( - - - - - - - )} - /> - -
- {/* Percentage Buttons */} -
- {PERCENTAGES.map((percentage) => ( - - ))} -
-
+ {/* Balance */} +
+

Balance:

+ + {loading ? : fromTokenBalance || 0} +
-
- - {/* Swap Bridge Tokens */} -
- -
- - {/* Transfer to */} -
-
- Transfer to - {/* To Chain Select */} + +
+ {/* Amount Input */} ( - + + + )} /> -
- -
- {/* Destination Address Input */} - -
-
-
- - {form.getValues().token} - - -
-

- You will receive: -

- - {loading ? : form.watch("amount") || 0} - +
+ {/* Percentage Buttons */} +
+ {PERCENTAGES.map((percentage) => ( + + ))}
+
+
-
- Receiver Address -
- {receiver || address ? ( - - ) : null} + {/* Swap Bridge Tokens */} +
+ +
+ + {/* Transfer to */} +
+
+ Transfer to + {/* To Chain Select */} + ( + + + + + )} + /> +
+
+ {/* Destination Address Input */} + +
+
+
+ + {form.getValues().token} + +
+

+ You will receive: +

+ + {loading ? : form.watch("amount") || 0} +
-
- {walletConnected ? ( - - ) : ( - - )} +
+ Receiver Address +
+ {receiver || address ? ( + + ) : null} +
- - - - - -
- +
+ +
+ {walletConnected ? ( + + ) : ( + + )} +
+ + + + + +
); } diff --git a/contracts/src/bridge/frontend/src/components/providers/wallet-provider.tsx b/contracts/src/bridge/frontend/src/components/providers/wallet-provider.tsx index 567aa430e2..ab23513382 100644 --- a/contracts/src/bridge/frontend/src/components/providers/wallet-provider.tsx +++ b/contracts/src/bridge/frontend/src/components/providers/wallet-provider.tsx @@ -18,7 +18,7 @@ const WalletProvider = ({ children }: WalletConnectionProviderProps) => { const [isWalletConnected, setIsWalletConnected] = useState(false); const [signer, setSigner] = useState(null); const [address, setAddress] = useState(""); - const [isL1ToL2, setIsL1ToL2] = React.useState(true); + const [isL1ToL2, setIsL1ToL2] = useState(true); const fromChains = isL1ToL2 ? L1CHAINS : L2CHAINS; const toChains = isL1ToL2 ? L2CHAINS : L1CHAINS; @@ -33,11 +33,11 @@ const WalletProvider = ({ children }: WalletConnectionProviderProps) => { }); if (isL1ToL2 && chainId !== WalletNetwork.L1_SEPOLIA) { - switchNetwork(); + switchNetwork(WalletNetwork.L1_SEPOLIA); } if (!isL1ToL2 && chainId !== WalletNetwork.L2_TEN_TESTNET) { - switchNetwork(); + switchNetwork(WalletNetwork.L2_TEN_TESTNET); } //@ts-ignore @@ -87,40 +87,53 @@ const WalletProvider = ({ children }: WalletConnectionProviderProps) => { }; // Function to switch network - const switchNetwork = async () => { + const switchNetwork = async (desiredNetwork: WalletNetwork) => { + console.log("🚀 ~ switchNetwork ~ desiredNetwork:", desiredNetwork); + if (!provider) { + toast({ + title: "Error", + description: "Please connect to wallet first", + variant: ToastType.DESTRUCTIVE, + }); + return; + } try { await provider.request({ method: requestMethods.switchNetwork, - params: [ - { - chainId: isL1ToL2 - ? WalletNetwork.L2_TEN_TESTNET - : WalletNetwork.L1_SEPOLIA, - }, - ], + params: [{ chainId: desiredNetwork }], + }); + setIsL1ToL2(desiredNetwork === WalletNetwork.L1_SEPOLIA); + toast({ + title: "Network Switched", + description: `Switched to ${ + desiredNetwork === WalletNetwork.L2_TEN_TESTNET + ? "L2 TEN Testnet" + : "L1 Sepolia" + }`, + variant: ToastType.SUCCESS, }); - setIsL1ToL2(!isL1ToL2); } catch (error: any) { console.error("Error switching network:", error); if (error.code === 4902) { toast({ - title: "Wrong Network", - description: isL1ToL2 ? ( - <> - You are not connected to Ten! Connect at: -
-                
-                  https://testnet.ten.xyz/
-                
-              
- - ) : ( - "Please install the network to continue." - ), + title: "Network Not Found", + description: + desiredNetwork === WalletNetwork.L2_TEN_TESTNET ? ( + <> + You are not connected to Ten! Connect at: +
+                  
+                    https://testnet.ten.xyz/
+                  
+                
+ + ) : ( + "Please install the network to continue." + ), variant: ToastType.INFO, }); } else { @@ -157,9 +170,9 @@ const WalletProvider = ({ children }: WalletConnectionProviderProps) => { } }, [provider]); - // useEffect(() => { - // connectWallet(); - // }, []); + useEffect(() => { + connectWallet(); + }, []); // Context value const value = {