Switch Metamask Network to chain 1 (Ethereum Mainnet)

This past week Metamask introduced a new function called "wallet_addEthereumChain" which allows the user to automatically add a new Etheruem RPC to their wallet when prompted. This function also allows the user to change the network they are connected to, for example, if I already have Binance Smart Chain connected to metamask, calling wallet_addEthereumChain changes the active network to BSC. However, when trying this for the Ethereum chain, it gives an error that you cannot add mainnet RPC. I have used the following code to change to change from Ethereum Mainnet to Binance Smart Chain, and it works fine: switchToBinance: async function () {

 let ethereum = window.ethereum; const data = [{ chainId: '0x38', chainName: 'Binance Smart Chain', nativeCurrency: { name: 'BNB', symbol: 'BNB', decimals: 18 }, rpcUrls: [' blockExplorerUrls: [' }] /* eslint-disable */ const tx = await ethereum.request({method: 'wallet_addEthereumChain', params:data}).catch() if (tx) { console.log(tx) } },

However when I try the Exact thing, metamask throws an exception saying I cannot add a mainnet RPC: switchToEthereum: async function () {

 let ethereum = window.ethereum; const data = [{ chainId: '0x1', chainName: 'Ethereum', nativeCurrency: { name: 'Ethereum', symbol: 'ETH', decimals: 18, }, rpcUrls: [' blockExplorerUrls: [' }] /* eslint-disable */ const tx = await ethereum.request({method: 'wallet_addEthereumChain', params:data}).catch() if (tx) { console.log(tx) } },

However, the request for adding a new RPC connection, and changing the active RPC connection is the same. So is there a way to change the active Ethereum provider from a custom chain to Mainnet (chain ID-1)

1

3 Answers

as this issue comment point, for security reason wallet_addEthereumChain not support mainnet. But there a new EIP to resolve this issue, follow EIP-3326 to find release info, and this discuss to see draft progrss.

chainId: '0x38' // error because await not decimal
Number('0x38').toString(10) //56 - chain ID of BSC

Right:

chainId: `0x${Number(56).toString(16)}`

OR:

chainId: `0x86`
1

Simply you have to prefix 0x with the chainId.

Example:

 await ethereum.request({ method: 'wallet_switchEthereumChain', params: [{ chainId: '0x1' }], })

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like