1

Already connected with metamask wallet with one chain-id, but after doing some transactions now user wants to connect with different chain-id from the UI by clicking the button to trigger the metamask wallet, so how could trigger the metamask wallet to pop-up so user can select different chain-id to connect it.

1 Answer 1

1

Here's some react code which will invoke switch if metamask is on the wrong network, and will invoke add network if the network isn't already configured in metamask. In this case, Polygon's Mumbai testnet

const switchNetwork = async () => {
if (window.ethereum) {
  try {
    // Try to switch to the Mumbai testnet
    await window.ethereum.request({
      method: 'wallet_switchEthereumChain',
      params: [{ chainId: '0x13881' }], // Check networks.js for hexadecimal network ids
    });
  } catch (error) {
    // This error code means that the chain we want has not been added to MetaMask
    // In this case we ask the user to add it to their MetaMask
    if (error.code === 4902) {
      try {
        await window.ethereum.request({
          method: 'wallet_addEthereumChain',
          params: [
            {   
              chainId: '0x13881',
              chainName: 'Polygon Mumbai Testnet',
              rpcUrls: ['https://rpc-mumbai.maticvigil.com/'],
              nativeCurrency: {
                  name: "Mumbai Matic",
                  symbol: "MATIC",
                  decimals: 18
              },
              blockExplorerUrls: ["https://mumbai.polygonscan.com/"]
            },
          ],
        });
      } catch (error) {
        console.log(error);
      }
    }
    console.log(error);
  }
} else {
  // If window.ethereum is not found then MetaMask is not installed
  alert('MetaMask is not installed. Please install it to use this app: https://metamask.io/download.html');
} 
  }
0

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.