From 8d140ff95f1a96c61fe0c6cd82f41994641edfe5 Mon Sep 17 00:00:00 2001 From: silverpill Date: Wed, 22 Jun 2022 17:19:16 +0000 Subject: [PATCH] Switch ethereum network automatically when connecting wallet --- src/composables/wallet.ts | 41 +++++++++++++++++++++++++++++++-------- src/utils/ethereum.ts | 2 +- 2 files changed, 34 insertions(+), 9 deletions(-) diff --git a/src/composables/wallet.ts b/src/composables/wallet.ts index ec30665..ee9c9c4 100644 --- a/src/composables/wallet.ts +++ b/src/composables/wallet.ts @@ -5,7 +5,7 @@ import { useInstanceInfo } from "@/store/instance" import { getWallet, getWeb3Provider, - parseCAIP2_chainId, + parseCAIP2_ChainId, } from "@/utils/ethereum" const walletAddress = ref(null) @@ -28,16 +28,47 @@ async function connectWallet(): Promise { walletError.value = "Wallet not found" return } + + const instanceChainId = parseCAIP2_ChainId(instance.value.blockchain_id) + try { + // https://eips.ethereum.org/EIPS/eip-3326 + await provider.send( + "wallet_switchEthereumChain", + [{ chainId: instanceChainId }], + ) + } catch (switchError: any) { + // This error code indicates that the chain has not been added to MetaMask + if (switchError.code === 4902) { + try { + // https://eips.ethereum.org/EIPS/eip-3085 + await provider.send( + "wallet_addEthereumChain", + [{ chainId: instanceChainId }], + ) + } catch (addError) { + walletError.value = "Incorrect network" + return + } + } else { + walletError.value = "Incorrect network" + return + } + } + const signer = await getWallet(provider) if (!signer) { walletError.value = "Wallet not connected" return } + // Connected walletAddress.value = await signer.getAddress() + walletError.value = null const walletProvider = provider.provider as any walletProvider.on("chainChanged", (chainId: string) => { - disconnectWallet() + if (chainId !== instanceChainId) { + disconnectWallet() + } }) walletProvider.on("accountsChanged", () => { disconnectWallet() @@ -45,12 +76,6 @@ async function connectWallet(): Promise { walletProvider.on("disconnect", () => { disconnectWallet() }) - - const instanceChainId = parseCAIP2_chainId(instance.value.blockchain_id) - const walletChainId = await provider.send("eth_chainId", []) - if (walletChainId !== instanceChainId) { - walletError.value = "Incorrect network" - } } // Can't use reactive signer object because it doesn't work with ethers.js diff --git a/src/utils/ethereum.ts b/src/utils/ethereum.ts index 3c46bd9..257741d 100644 --- a/src/utils/ethereum.ts +++ b/src/utils/ethereum.ts @@ -1,7 +1,7 @@ import { Signer } from "ethers" import { Web3Provider } from "@ethersproject/providers" -export function parseCAIP2_chainId(chainId: string): string { +export function parseCAIP2_ChainId(chainId: string): string { const match = chainId.match(/eip155:(\d+)/) if (!match) { throw new Error("invalid chain ID")