Switch ethereum network automatically when connecting wallet

This commit is contained in:
silverpill 2022-06-22 17:19:16 +00:00
parent 54946e5956
commit 8d140ff95f
2 changed files with 34 additions and 9 deletions

View file

@ -5,7 +5,7 @@ import { useInstanceInfo } from "@/store/instance"
import {
getWallet,
getWeb3Provider,
parseCAIP2_chainId,
parseCAIP2_ChainId,
} from "@/utils/ethereum"
const walletAddress = ref<string | null>(null)
@ -28,16 +28,47 @@ async function connectWallet(): Promise<void> {
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<void> {
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

View file

@ -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")