How to trigger change blockchain network request on MetaMask
Asked Answered
F

3

20

I am using web3 for my first dapp test and I'd like to make so MetaMask will prompt the user to change the network to Binance (BSC) network if it is not selected already, just like here:

metamask requesto change network

How to trigger such a request?

Furie answered 5/7, 2021 at 7:43 Comment(0)
F
47

I was finally able to find the answer:

await window.ethereum.request({
  method: 'wallet_switchEthereumChain',
  params: [{ chainId: '0x61' }], // chainId must be in hexadecimal numbers
});

A more comprehensive answer would check if MetaMask is installed and if this one has installed the chain your Dapp wants to connect to, and if it is not install it:

 // Check if MetaMask is installed
 // MetaMask injects the global API into window.ethereum
 if (window.ethereum) {
      try {
        // check if the chain to connect to is installed
        await window.ethereum.request({
          method: 'wallet_switchEthereumChain',
          params: [{ chainId: '0x61' }], // chainId must be in hexadecimal numbers
        });
      } catch (error) {
        // This error code indicates that the chain has not been added to MetaMask
        // if it is not, then install it into the user MetaMask
        if (error.code === 4902) {
          try {
            await window.ethereum.request({
              method: 'wallet_addEthereumChain',
              params: [
                {
                  chainId: '0x61',
                  rpcUrl: 'https://data-seed-prebsc-1-s1.binance.org:8545/',
                },
              ],
            });
          } catch (addError) {
            console.error(addError);
          }
        }
        console.error(error);
      }
    } else {
      // if no window.ethereum then MetaMask is not installed
      alert('MetaMask is not installed. Please consider installing it: https://metamask.io/download.html');
    } 
Furie answered 6/7, 2021 at 9:2 Comment(1)
thanks, I was searching for this there is no clue how to change it finally I found your answer.Koss
P
7
async switchEthereumChain() {
    try {
      await window.ethereum.request({
        method: 'wallet_switchEthereumChain',
        params: [{ chainId: '0x61' }],
      });
    } catch (e: any) {
      if (e.code === 4902) {
        try {
          await window.ethereum.request({
            method: 'wallet_addEthereumChain',
            params: [
              {
                chainId: '0x61',
                chainName: 'Smart Chain - Testnet',
                nativeCurrency: {
                  name: 'Binance',
                  symbol: 'BNB', // 2-6 characters long
                  decimals: 18
                },
                blockExplorerUrls: ['https://testnet.bscscan.com'],
                rpcUrls: ['https://data-seed-prebsc-1-s1.binance.org:8545/'],
              },
            ],
          });
        } catch (addError) {
          console.error(addError);
        }
      }
      // console.error(e)
    }
  }

While the above answer does not work for me, it gives me an error of Unsupported keys:\nrpcUrl" it's because instead of rpcUrl, it should be rpcUrls in an array of string, also take note of blockExplorerUrls.

You can find the docs of metamask here

Patronage answered 18/11, 2021 at 10:0 Comment(0)
V
1

Now even the above code will not work as window.ethereum.request returns promise object. So the above code should be written as follows -->

    async switchEthereumChain() 
          {
            // switch chain to intended one , if that chain is already added
               window.ethereum.request({
                   method: 'wallet_switchEthereumChain',
                   params: [{ chainId: '0x38' }], // chainId 
                }).then(response => {response.json()}).catch(error => {
                    //if network not added then the below code will try to add network
                    if (error.code === 4902) 
                      {
                        window.ethereum.request({
                                method: 'wallet_addEthereumChain',
                                params: [
                                         {
                                          chainId: '0x38',
                                          rpcUrls: ['https://bsc-dataseed1.bnbchain.org'],
                                          chainName: "BNB Smart Chain Mainnet",
                                nativeCurrency: {
                                                   name: "BNB",
                                                   symbol: "BNB",
                                                   decimals: 18
                                                },
                                blockExplorerUrls: ["https://bscscan.com/"]
                                            }
                                          ]
                                                }).then(response => {response.json()}).catch (addError => {
                         console.log("error after trying to add network");
                         console.error(addError);
                                                }) 
                       }
                    }) 
                 }); 
          }
Variate answered 28/1 at 3:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.