Skip to content

Instantly share code, notes, and snippets.

@httpJunkie
Created October 18, 2023 19:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save httpJunkie/8687c513b7ee1a8dd97f7cefd00f6616 to your computer and use it in GitHub Desktop.
Save httpJunkie/8687c513b7ee1a8dd97f7cefd00f6616 to your computer and use it in GitHub Desktop.
React Hook (JavaScript/TypeScript) that Switches MetaMask user to desired 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
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment