Back to homepage

Automatically adding a blockchain to Metamask with Javascript

Published

In a previous article, I explained how to detect and switch the network in Metamask. That works great if the blockchain we want to connect to is already in the Metamask configuration, but if the user haven't added it already, it'll fail.

In this article, I'm going to explain how to create a button that automatically adds the blockchain we want to Metamask, so the user just needs to click on the button and Metamask will connect to it.

Details required to import network in Metamask

In order to automatically add a blockchain to Metamask with Javascript, we need to provide some details:

  • Chain ID: the unique id of the network. You can find it in Chainlist.
  • Chain Name: the name we want to save the blockchain as.
  • RPC URLs: blockchain node URL. Check out Chainstack to get free access to multiple blockchains.
  • Native currency: which includes name, symbol (2-6 characters), and number of decimals (18)
  • Explorer: the URL of the the blockchain explorer. Optional

For example, the details for Fuse are:

# Chain ID: 0x7a (which is 122)
# Name: Fuse Mainnet
# RPC URL: 'https://rpc.fuse.io'
# Currency name: FUSE
# Currency symbol: FUSE
# Currency decimals: 18
# Explorer: 'https://explorer.fuse.io/'

Add a blockchain to Metamask with Javascript

Once we have all the details of the blockchain we want to add, we can add it to Metamask using the wallet_addEthereumChain method. It the params, we'd need to pass all the network details as shown below:

// FUSE blockchain details
const chainId = '0x7a';
const rpcURL = 'https://rpc.fuse.io';
const networkName = 'Fuse Mainnet';
const currencyName = 'FUSE';
const currencySymbol = 'FUSE';
const explorerURL = 'https://explorer.fuse.io/';

const addNetwork = async () => {
  await window.ethereum.request({
    method: 'wallet_addEthereumChain',
    params: [
      {
        chainId: chainId,
        chainName: networkName,
        rpcUrls: [rpcURL],
        blockExplorerUrls: [explorerURL],
        nativeCurrency: {
          name: currencyName,
          symbol: currencySymbol, // 2-6 characters long
          decimals: 18,
        },
      },
    ],
  });
  // refresh
  window.location.reload();
};

MetaMask - RPC Error codes

MetaMask - RPC Error: Expected null or array with at least one valid string HTTPS URL

{code: -32602, message: "Expected null or array with at least one valid str…ExplorerUrl'. Received: https://explorer.fuse.io/"}

This error occurs when we're adding a blockchain to Metamask using the wallet_addEthereumChain. It's caused because we're passing single strings as parameters in the rpcURLs or blockExplorerUrls attributes. Make sure to pass an array, even if it has just a single URL.

MetaMask - RPC Error: Expected 0x-prefixed, unpadded, non-zero hexadecimal string 'chainId'. Received: 122

{code: -32602, message: "Expected 0x-prefixed, unpadded, non-zero hexadecimal string 'chainId'. Received:\n122"}

This error occurs when we're adding a blockchain to Metamask using the wallet_addEthereumChain method. It's caused because we are passing the chainId as an integer instead of using an hexadecimal string. To transform decimals to 0x formatted hexadecimals, use this tool.

MetaMask - RPC Error: Chain ID returned by RPC URL does not match

{code: -32602, message: 'Chain ID returned by RPC URL https://rpc.fuse.io does not match 0x122', data: {chainId: '0x7a'}}

This error occurs when we're adding a blockchain to Metamask using the wallet_addEthereumChain method. It's caused because the chain id we're passing as a parameter does not match with the chain id returned by the RPC url provided. To fix it, just change the chain id with the one returned by the rpc, which is shown in the error messsage, or make sure that the rpc url corresponds to the chain you're adding.

Web example

Here is a basic web example with a button that triggers Metamask and adds the network:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Adding blockchain to Metamask</title>
  </head>
  <body>
    <script>
      // FUSE blockchain details
      const chainId = '0x7a';
      const rpcURL = 'https://rpc.fuse.io';
      const networkName = 'Fuse Mainnet';
      const currencyName = 'FUSE';
      const currencySymbol = 'FUSE';
      const explorerURL = 'https://explorer.fuse.io/';

      const addNetwork = async () => {
        if (!window.ethereum) {
          console.error('Metamask not detected');
          return;
        }
        await window.ethereum.request({
          method: 'wallet_addEthereumChain',
          params: [
            {
              chainId: chainId,
              chainName: networkName,
              rpcUrls: [rpcURL],
              blockExplorerUrls: [explorerURL],

              nativeCurrency: {
                name: currencyName,
                symbol: currencySymbol, // 2-6 characters long
                decimals: 18,
              },
            },
          ],
        });
        // refresh
        window.location.reload();
      };
    </script>
    <!-- The button  -->
    <button onClick="addNetwork()">Add Fuse</button>
  </body>
</html>

TAGS

If you enjoyed this article consider sharing it on social media or buying me a coffee ✌️

Buy Me A Coffee