Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger change blockchain network request on MetaMask

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?

like image 903
Andrea D_ Avatar asked Jul 05 '21 07:07

Andrea D_


People also ask

How do you auto add networks to MetaMask?

In most instances Instadapp call automatically add any required networks. On Instadapp if you switch to a new network you will find a 'Switch to Network' button towards the top this will add the network if it is not already in your Metamask Wallet.

What information does metamask provide about the target blockchain?

RPC URL: The RPC URL is the address of the set of protocols MetaMask can use for interacting with the target blockchain. Chain ID: Each network has its own unique chain ID, which is used to identify it. Currency symbol: This is the ticker MetaMask uses to display the balance for the network’s native coin, e.g. BNB.

How do I add a network to metamask?

Open the MetaMask wallet To add a MetaMask network, you should open your MetaMask wallet. In order to do that, you should go to your web browser and open your wallet. 2. Go to Settings and select Network Next, click on your profile picture, which you can see on the top right hand corner.

How do I change the network of my Ethereum metamask?

Despite current high gas fees, the Ethereum blockchain still is home to many innovations and dapp developments. If you want to change the network of your Metamask, for example to the Kovan test network, you need to click the ‘down arrow’ next to the current network.

Can I use metamask with non-EVM chains?

You will need to get a separate native wallet to interact with non-EVM chains like Solana, Terra, Waves, or NEAR. By default, MetaMask only supports a handful of Ethereum-based networks, including the Ethereum mainnet and several testnets (Ropsten, Kovan, Rinkeby, and Goerli).


2 Answers

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');
    } 
like image 149
Andrea D_ Avatar answered Oct 22 '22 11:10

Andrea D_


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

like image 20
iwantcheeseburger Avatar answered Oct 22 '22 12:10

iwantcheeseburger