RPC Error: Unrecognized chain ID . Try adding the chain using wallet_addEthereumChain first

Dung Do Tien Jul 08 2022 40

Hello guys. Today i have a small app with javascript, that help me connect from a website to Metamask wallet.  I used the Web3.js to help do it.

Now I want to if current mainnet of Metamask set is not Etherium. I will show prompt confirming switch to Etherium mainnet. I do like this:

window.ethereum.request({
    method: 'wallet_switchEthereumChain',
    params: [{ chainId: '0x1' }], // Ethereum chain.
}).then(() => {
    if (typeof parent.ethereum !== 'undefined') {
        parent.ethereum.enable().then(function () {
            // Do something here
        });
    } else if (typeof ethereum !== 'undefined') {
        ethereum.enable().then(function () {
            // Do something here
        });
    }
});

But when run this code I got an exception MetaMask - RPC Error: Unrecognized chain ID "0x1". Try adding the chain using wallet_addEthereumChain first. Here is detail exception:

MetaMask - RPC Error: Unrecognized chain ID "0x1". Try adding the chain using wallet_addEthereumChain first. {code: -32603, message: 'Unrecognized chain ID "0x1". Try adding the chain using wallet_addEthereumChain first.', data: {…}}
(anonymous) @ inpage.js:1
(anonymous) @ inpage.js:17
_runReturnHandlers @ inpage.js:17
_processRequest @ inpage.js:17
await in _processRequest (async)
_handle @ inpage.js:17
handle @ inpage.js:17
_rpcRequest @ inpage.js:1
(anonymous) @ inpage.js:1
request @ inpage.js:1
initMetamask @ verifiedSignatures:1550
await in initMetamask (async)
(anonymous) @ verifiedSignatures:1712
dispatch @ jquery.min.js?v=22.6.5.0:2
v.handle @ jquery.min.js?v=22.6.5.0:2

Anyone can help me?

Have 1 answer(s) found.
  • C

    CONG TRAN VAN Jul 08 2022

    the Hexa ChainId 0x1 is Ethereum. This error threw because your Metamask extension still does not add Ethereum Mainnet on it.

    In this case, you can use catch to help alert something to the end-user. like this:

    window.ethereum.request({
        method: 'wallet_switchEthereumChain',
        params: [{ chainId: '0x1' }], // Ethereum chain.
    }).then(() => {
        if (typeof parent.ethereum !== 'undefined') {
            parent.ethereum.enable().then(function () {
                // Do something here
            });
        } else if (typeof ethereum !== 'undefined') {
            ethereum.enable().then(function () {
                // Do something here
            });
        }
    }).catch((error) => {
        alert("Please add Ethereum mainnet to your Metamark wallet first.");
    });

    I hope it is useful for you.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close