3

I made a dApp that allows users to collect token rewards on multiple different chains. For the sake of an example say it is Rinkeby and Mumbai.

In order to get signer and provider to execute my contract functions with ethers.js I utilise this code:

    const provider = new ethers.providers.Web3Provider(web3.currentProvider);
    const wallet = new ethers.Wallet(privateKey, provider);
    const signer = wallet.provider.getSigner(wallet.address);

It gets the current provider and using a contract function allows to claim the rewards on user's current chain, Rinkeby. Then if the user wants to collect rewards on the other chain Mumbai, he has to change the network in Metamask. I want it to be done automatically when user presses "Claim" button.

How do I change the user's network programmatically?

2

2 Answers 2

4

This is the code that you need to prompt a switch from the current selected network to Mumbai, using the window.ethereum global API injected directly by MetaMask.

  // Prompt the user to switch to the Mumbai testnet

async function switchNetwork() {
   await window.ethereum.request({
   method: 'wallet_switchEthereumChain',
   params: [{ chainId: '0x13881' }],    // chainId must be in HEX with 0x in front
   });
}

You can use this converter to convert decimals to HEX.

Note that this will give an error if the Network is not yet set up on MetaMask. You can check the MetaMask docs to see how they recommend to handle this :)

1

If anyone is wondering how to do this with ethers js 6, here is how to pass the correct chain id:

Example to prompt the user to switch to sepolia testnet (chain id 11155111)

await (window as any).ethereum.request({
  method: 'wallet_switchEthereumChain',
  params: [{ chainId: toBeHex(11155111) }],
});

use toBeHex utility function: https://docs.ethers.org/v6/api/utils/#toBeHex

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.