简体   繁体   English

"Ethereum.on 如果链还没有添加到元掩码中,如何得到错误"

[英]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尝试在 ethereum.on 之外捕捉到任何东西

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 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:对我来说,最简单的方法似乎是在切换之前先添加链,成功添加 Metamask 后会要求用户将网络切换到新添加的此处示例代码以添加 BSC 网络:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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