When Switching or Adding and then Switching to another Network/Chain within a dapp like React using MetaMask API. You can build a React Hook with the concept in this GitHub Gist included below.
The code between lines 36 and 68 could be used outside of a React Hook in the case you just want to know how to create a single JavaScript/TypeScript function for adding/switching Ethereum chain.
import * as contractAbi from '~/lib/contract-abis/MyCOntract.json' | |
export const config = { | |
// This config assumes you have access to an ABI like we have imported above | |
'0x13881': { | |
name: 'Mumbai', | |
contractAddress: contractAbi.networks[Number('0x13881')]?.address, | |
symbol: 'MATIC', | |
blockExplorer: 'https://mumbai.polygonscan.com', | |
rpcUrl: 'https://rpc-mumbai.maticvigil.com', | |
}, | |
'0xe704': { | |
name: 'Linea', | |
contractAddress: contractAbi.networks[Number('0xe704')]?.address, | |
symbol: 'LineaETH', | |
blockExplorer: 'https://explorer.goerli.linea.build', | |
rpcUrl: 'https://rpc.goerli.linea.build', | |
}, | |
'0x5': { | |
name: 'Goerli', | |
contractAddress: contractAbi.networks[Number('0x5')]?.address, | |
symbol: 'ETH', | |
blockExplorer: 'https://goerli.etherscan.io', | |
rpcUrl: 'https://goerli.infura.io/v3/9aa3d95b3bc440fa88ea12eaa4456161', | |
} | |
} | |
export const useSwitchNetwork = () => { | |
// This hook works assuming you have someway of retrieving a network/chain ID from an env file | |
// As well having some type of configuration file that has the information for supported network based on chainID as key | |
// See above this function for file for example of a config object/file | |
const networkId = import.meta.env.VITE_PUBLIC_NETWORK_ID | |
const switchNetwork = async () => { | |
try { | |
await window.ethereum.request({ | |
method: 'wallet_switchEthereumChain', | |
params: [{ chainId: networkId, }], | |
}) | |
} catch (error) { | |
try { | |
await window.ethereum?.request({ | |
method: 'wallet_addEthereumChain', | |
params: [ | |
{ | |
chainId: networkId, | |
...(config[networkId].blockExplorer ? { | |
blockExplorerUrls: [config[networkId].blockExplorer] | |
} : {}), | |
chainName: config[networkId].name, | |
nativeCurrency: { | |
decimals: 18, | |
name: config[networkId].name, | |
symbol: config[networkId].symbol, | |
}, | |
rpcUrls: [config[networkId].rpcUrl], | |
}, | |
], | |
}) | |
} catch (error) { | |
// user rejects the request to "add chain" or param values are wrong, maybe you didn't use hex above for `chainId`? | |
console.log(`wallet_addEthereumChain Error: ${error.message}`) | |
} | |
// handle other "switch" errors | |
} | |
} | |
return { | |
switchNetwork | |
} | |
} |
Top comments (0)