Skip to content

Instantly share code, notes, and snippets.

@koolamusic
Created February 18, 2022 13:34
Show Gist options
  • Save koolamusic/0c9b3e748a9ddac376d2c7d9faae1290 to your computer and use it in GitHub Desktop.
Save koolamusic/0c9b3e748a9ddac376d2c7d9faae1290 to your computer and use it in GitHub Desktop.
Add an RPC EVM Supported Network to Metamask
/** @see https://docs.metamask.io/guide/rpc-api.html#other-rpc-methods*/
async function changeNetwork(){
await ethereum.request({ method: 'wallet_addEthereumChain',
params:[
{chainId: "IN_HEXADECIMAL_FORM",
chainName: "CHAIN_NAME",
nativeCurrency: {
name: "NATIVE_CURRENCY_NAME",
symbol: "NATIVE_CURRENCY_SYMBOL",
decimals: NATIVE_CURRENCY_DECIMALS //In number form
},
rpcUrls: ["BLOCKcHAIN_RPC_URL"],
blockExplorerUrls?: ["BLOCKCHAIN_EXPLORER"]
]});
}
const params = {
chainId: toHex(chain.chainId), // A 0x-prefixed hexadecimal string
chainName: chain.name,
nativeCurrency: {
name: chain.nativeCurrency.name,
symbol: chain.nativeCurrency.symbol, // 2-6 characters long
decimals: chain.nativeCurrency.decimals,
},
rpcUrls: chain.rpc,
blockExplorerUrls: [ ((chain.explorers && chain.explorers.length > 0 && chain.explorers[0].url) ? chain.explorers[0].url : chain.infoURL) ]
}
window.web3.eth.getAccounts((error, accounts) => {
window.ethereum.request({
method: 'wallet_addEthereumChain',
params: [params, accounts[0]],
})
.then((result) => {
console.log(result)
})
.catch((error) => {
stores.emitter.emit(ERROR, error.message ? error.message : error)
console.log(error)
});
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment