diff --git a/contracts/src/bridge/frontend/src/lib/utils.ts b/contracts/src/bridge/frontend/src/lib/utils/index.ts similarity index 100% rename from contracts/src/bridge/frontend/src/lib/utils.ts rename to contracts/src/bridge/frontend/src/lib/utils/index.ts diff --git a/contracts/src/bridge/frontend/src/lib/utils/walletEvents.ts b/contracts/src/bridge/frontend/src/lib/utils/walletEvents.ts new file mode 100644 index 0000000000..a4d810117f --- /dev/null +++ b/contracts/src/bridge/frontend/src/lib/utils/walletEvents.ts @@ -0,0 +1,27 @@ +import { ethers } from "ethers"; + +export const setupEventListeners = ( + provider: any, + setAddress: (address: string) => void +) => { + const handleAccountsChange = (accounts: string[]) => { + setAddress(accounts[0]); + localStorage.setItem("walletAddress", accounts[0]); + }; + + const handleChainChange = () => { + window.location.reload(); + }; + + provider.on("accountsChanged", handleAccountsChange); + provider.on("chainChanged", handleChainChange); + + return () => { + provider.removeListener("accountsChanged", handleAccountsChange); + provider.removeListener("chainChanged", handleChainChange); + }; +}; + +export const initializeSigner = (provider: any) => { + return new ethers.providers.Web3Provider(provider).getSigner(); +}; diff --git a/contracts/src/bridge/frontend/src/lib/utils/walletUtils.ts b/contracts/src/bridge/frontend/src/lib/utils/walletUtils.ts new file mode 100644 index 0000000000..45c63c8b60 --- /dev/null +++ b/contracts/src/bridge/frontend/src/lib/utils/walletUtils.ts @@ -0,0 +1,37 @@ +import detectEthereumProvider from "@metamask/detect-provider"; +import { ToastType, WalletNetwork } from "../../types"; +import { requestMethods } from "../../routes"; +import { toast } from "@/src/components/ui/use-toast"; + +export const getEthereumProvider = async () => { + const provider = await detectEthereumProvider(); + console.log("🚀 ~ getEthereumProvider ~ provider:", provider); + if (!provider) { + throw new Error("No Ethereum provider detected"); + } + return provider; +}; + +export const switchNetwork = async ( + provider: any, + desiredNetwork: WalletNetwork +) => { + if (!provider) { + toast({ + title: "Error", + description: "Please connect to wallet first", + variant: ToastType.DESTRUCTIVE, + }); + return; + } + await provider.request({ + method: requestMethods.switchNetwork, + params: [{ chainId: desiredNetwork }], + }); +}; + +export const handleStorage = { + save: (key: string, value: string) => localStorage.setItem(key, value), + get: (key: string) => localStorage.getItem(key), + remove: (key: string) => localStorage.removeItem(key), +};