Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ethereum.on How to get error if chain is not added into metamask yet

With this method app is listening for chain change:

    ethereum.on('chainChanged', (chainId) => {
})

but if the chain to which the user is going is not added yet into metamask it throws :

inpage.js:1 MetaMask - RPC Error: Unrecognized chain ID "0x89".
Try adding the chain using wallet_addEthereumChain first. Object

of course, there is a method to add a new chain into metamask but how to catch this metamask error? try and catch outside ethereum.on gives nothing

Thanks!

like image 997
Mariusz Sidorowicz Avatar asked Oct 16 '25 03:10

Mariusz Sidorowicz


2 Answers

write a mapping for metamask networks:

const NETWORKS = {
  1: "Ethereum Main Network",
  3: "Ropsten Test Network",
  4: "Rinkeby Test Network",
  5: "Goerli Test Network",
  42: "Kovan Test Network",
  56: "Binance Smart Chain",
  1337: "Ganache",
};



const getChainId= async () => {
      const chainId = await web3.eth.getChainId();
      // handle the error here
      if (!chainId) {
        throw new Error(
          "Cannot retrieve an account. Please refresh the browser"
        );
      }
      return NETWORKS[chainId];
    }
  );
like image 67
Yilmaz Avatar answered Oct 18 '25 03:10

Yilmaz


The simplest approach seems for me it is to add chain first before switching and after successful adding Metamask will ask user to switch network to newly added here sample code to add BSC network:

export async function addBSCToMetamask() {
    if (typeof window !== 'undefined') {
        window.ethereum.request({
            jsonrpc: '2.0',
            method: 'wallet_addEthereumChain',
            params: [
                {
                    chainId: '0x38',
                    chainName: 'Binance Smart Chain Mainnet',
                    rpcUrls: ['https://bsc-dataseed.binance.org/'],
                    nativeCurrency: {
                        name: 'BNB',
                        symbol: 'BNB',
                        decimals: 18
                    },
                    blockExplorerUrls: ['https://bscscan.com']
                }
            ],
            id: 0
        })
    }
}
like image 35
Mariusz Sidorowicz Avatar answered Oct 18 '25 04:10

Mariusz Sidorowicz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!