Skip to content

Commit

Permalink
Add utility functions for wallet and event
Browse files Browse the repository at this point in the history
handling
  • Loading branch information
Jennievon committed Jul 31, 2024
1 parent eb2b9c4 commit 2b7928c
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 0 deletions.
27 changes: 27 additions & 0 deletions contracts/src/bridge/frontend/src/lib/utils/walletEvents.ts
Original file line number Diff line number Diff line change
@@ -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();
};
37 changes: 37 additions & 0 deletions contracts/src/bridge/frontend/src/lib/utils/walletUtils.ts
Original file line number Diff line number Diff line change
@@ -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),
};

0 comments on commit 2b7928c

Please sign in to comment.