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.

3 Likes

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:

8 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

Hi, i understand what happens in the code, but why is that async function declared as a const?
I know how to call a function from a button, but what to do with a const?

I have

TEST <button onclick="switchNetworkMumbai()">
  change to mumbai network (add if not present, add it)
</button>

But this gives, as expected:
ReferenceError: switchNetworkMumbai is not defined
at HTMLButtonElement.onclick

I Googled for an hour, but JS changed alot and i have no clue.
Any help appreciated.

I think that you should not call that function directly there, and only write onclick=“switchNetworkMumbai”

you may also need to enable web3 before calling that so that a connection to matamask is created and web3 variable is initialised

The onclick was okay, function now executes, i rewrote to:

switchNetworkMumbai = async function () { try {

Next, hexadecimal chainIDs, will figure it out.

Thanks for your reply!

Hi Yomoo,
Does this code work on mobile?
I’m using Moralis, walletconnect to interact with Metamask app on mobile.
When I request to change network, no error message and nothing happen.