How to add a custom token to the user's wallet using web3

In this tutorial you are going to learn how to add a custom token ERC-20 token to the user's MetaMask wallet using web3.

In this tutorial you are going to learn how to add a custom token ERC-20 token to the user's MetaMask wallet using web3.

To build this, you will need to install web3 if you haven't already:

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.

Next, you need to have the following information of your token:

  • the token address
  • the symbol
  • the decimals (usually 18, you can see it in the contract info)
  • the token image URL (optional)

Once you have that, you can use the "wallet_watchAsset" method:

// 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

const tokenAddress = '0x514910771af9ca656af840dff83e8264ecf986ca';
const tokenSymbol = 'LINK';
const tokenDecimals = 18;

try {
  const isAdded = await web3.currentProvider.request({
    method: 'wallet_watchAsset',
    params: {
      type: 'ERC20',
      options: {
        address: tokenAddress,
        symbol: tokenSymbol,
        decimals: tokenDecimals,
        // image: tokenImage, // if you have the image, it goes here
      },
    },
  });
} catch (error) {
  // handle errors
}

And that's it! 🎉

After that you can check the isAdded variable to see if the token was imported successfully.

Thanks for reading this article!