Programatically switch the selected Metamask network

Greetings,
This may be a dumb question but is there a way in which using the Moralis library we can programatically switch the selected metamask network, chain id
I found this example where they are doing it through window.ethereum global variable

And I was wondering how to accomplish it using our Web3 provider once we have authenticated and enabled our web3 instance or before enabling our instance. In any case my use case is a modal window which makes the user select the network they want to use 'Binance,Etherium and choose their wallet type metamask or using trust wallet using the walletconnect provider option.

If they have selected metamask and binance i want to be able to switch their network/chain id over to the binance network if they were lastly using the etherium network.

Any suggestions regarding the question and the use case will be highly appreciated, many thanks in advance.

1 Like

Hey @randomw1zard

In all examples I use web3 from Moralis SDK:

const web3 = await Moralis.Web3.enable();

Here is an example how to get chain id in hex and decimal styles

        const chainIdHex = web3.currentProvider.chainId;
        const chainIdDec = await web3.eth.getChainId();
        console.log(chainIdHex);
        console.log(chainIdDec);

Code to change network in Injected providers:

 try {
          await web3.currentProvider.request({
            method: "wallet_switchEthereumChain",
            params: [{ chainId: "0x89" }]
          });
        } catch (error) {
          alert(error.message);
        }

Here is an example for switching network to the Mumbai Testnet. It will add Mumbai Chain if user doesn’t have it:

const switchNetworkMumbai = async () => {
  try {
    await web3.currentProvider.request({
      method: "wallet_switchEthereumChain",
      params: [{ chainId: "0x13881" }],
    });
  } catch (error) {
    if (error.code === 4902) {
      try {
        await web3.currentProvider.request({
          method: "wallet_addEthereumChain",
          params: [
            {
              chainId: "0x13881",
              chainName: "Mumbai",
              rpcUrls: ["https://rpc-mumbai.matic.today"],
              nativeCurrency: {
                name: "Matic",
                symbol: "Matic",
                decimals: 18,
              },
              blockExplorerUrls: ["https://explorer-mumbai.maticvigil.com"],
            },
          ],
        });
      } catch (error) {
        alert(error.message);
      }
    }
  }
}

Hope that will help you :man_mechanic:

3 Likes

:bowing_man: :rocket: :rocket: :rocket:
You’re the man! Thanks a lot.
That’s precisely what I was looking for.

You are welcome! :wink:

Happy BUIDLing :man_mechanic:

1 Like

Trust me I have only just begun haha :smiley: after the web html project is done, next one is going to be on unity.
Image this https://youtu.be/gMPJ38mSkt0 but with newer graphics and a coin for the in the game market. Straight up I’m gonna be inspired from their mechanics :wink:
P.S. The Database feature given by Moralis is freakin’ sweat.

1 Like