简体   繁体   中英

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!

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",
};

set your target networK

const targetNetwork = NETWORKS[process.env.TARGET_CHAIN_ID];

const getChainId= async () => {
      const chainId = await web3.eth.getChainId();
      if (!chainId) {
        throw new Error(
          "Cannot retrieve an account. Please refresh the browser"
        );
      }
      return NETWORKS[chainId];
    }
  );

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
        })
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM