2

I am using wallet_addEthereumChain RPC function to add the custom network in metamask android app through our Dapp but it is showing an error wrong chainid. The chainid(80001) is correct and the code is working fine in a desktop browser using metamask extension but the same code gives an error in metamask android app. Below is code that I am using:

try {
  const res = await window.ethereum.request({
    method: "wallet_switchEthereumChain",
    params: [{ chainId: "0x13881" }],
  });
} catch (switchError) {
  if (switchError.code === 4902) {
    try {
      await window.ethereum.request({
        id: 1,
        jsonrpc: "2.0",
        method: "wallet_addEthereumChain",
        params: [
          {
            chainId: "0x13881",
            rpcUrls: ["https://rpc-mumbai.maticvigil.com"],
            chainName: "Polygon Testnet Mumbai",
            nativeCurrency: {
              name: "tMATIC",
              symbol: "tMATIC", // 2-6 characters long
              decimals: 18,
            },
            blockExplorerUrls: ["https://mumbai.polygonscan.com/"],
          },
        ],
      });
    } catch (addError) {
    }
  }
}

1 Answer 1

1
const switchMetamaskWalletChain = async () => {
  try {
    await ethereum.request({
      method: "wallet_switchEthereumChain",
      params: [{ chainId: activeChain.hex }]
    });
  } catch (switchError) {
    if (isMobile) {
      const errorCode = switchError.data?.originalError?.code
      if (errorCode && errorCode === 4902) {
        await addChain()
      }
    } else {
      if (switchError.code === 4902) {
      
        await addChain()
      }
    }
    
    // handle other "switch" errors
    console.error(switchError);
  }
};

If you are using mobile metamask, wallet_switchEthereumChain request error is going to be thrown in different error format. In mobile, error code is switchError.data?.originalError?.code.

Hope it works!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.