How to add a new network to a MetaMask wallet from your dApp web3

In this tutorial, you are going to learn how you can add a network like the Binance Smart chain to the user's wallet using web3.

In this tutorial, you are going to learn how you can add a network like the Binance Smart chain to the user's wallet using web3.

First, if you haven't already, install the web3 dependency using the following command:

npm install web3

Then, to interact with a blockchain (Ethereum or BSC or any other) you need to create an instance of Web3 and give it a provider (like window.ethereum for browser wallets, for example).

After that, you need to connect to the user's wallet using any method you want. You can check out our guides if you want to learn how to connect to a wallet.

Once the user is connected, you can simply run the following code:

// need a Web3 instance initialized with a provider like window.ethereum for browser wallets, in a variable called web3, to use this code stored
// also need a connected wallet using that instance

// then use this:
web3.currentProvider.request({
  method: 'wallet_addEthereumChain',
  params: [{
    chainId: '0x38',
    chainName: 'Binance Smart Chain',
    nativeCurrency: {
      name: 'Binance Coin',
      symbol: 'BNB',
      decimals: 18
    },
    rpcUrls: ['https://bsc-dataseed.binance.org/'],
    blockExplorerUrls: ['https://bscscan.com']
  }]
})
.catch((error) => {
  console.log(error)
}) 

This code will add the Binance Smart Chain network to the user's wallet.

In this code, we call the addEthereumChain method from the wallet and we pass some parameters to this method.

The parameters we pass are:

  • the chain ID, which is a unique identifier for the blockchain in a wallet (full list of the chain IDs: https://chainlist.org/)
  • the chain name, the name in the wallet
  • Information about the currency used for the fees and the transfers in that blockchain (Ethereum for the Ethereum network, BNB for the BSC, MATIC for the Polygon network and so on...)
  • the RPC urls where we can reach the blockchain and use its methods
  • and the block explorer platform, the platform where we can track all the contracts and transactions in a blockchain

You can find all the information about the blockchain you want to add here:

chains/_data/chains at master · ethereum-lists/chains
provides metadata for networkIDs and chainIDs. Contribute to ethereum-lists/chains development by creating an account on GitHub.

You need to search for the chain ID of the blockchain you want to add and in the file that contains your chain ID in its name, you'll get all the information you need.

For example, the Binance Smart Chain ID is 56 so the file that contains information about that blockchain is eip155-56.json:

chains/eip155-56.json at master · ethereum-lists/chains
provides metadata for networkIDs and chainIDs. Contribute to ethereum-lists/chains development by creating an account on GitHub.

Thanks for following this tutorial!