[Ethereum] How to automatically add a custom token to MetaMask with ethers.js


I was playing around with creating BEP-20 tokens on cointool.app and noticed that whenever you generate a new token and pay the gas fee to mint it, the website automatically prompts you to add this custom token to your wallet. The dialogue window that pops up looks like this:

enter image description here

I am wondering how I could implement the same functionality into my dapp that is build on ethers.js. Usually when a user trades a custom token for the first time they are being asked to manually copy and paste its address into the Metamask or other web wallet to see its balance. But this is inconvenient and requires more effort than just pressing a Add Token button in a dialogue window. I can't find any documentation on this method, so if anyone knows how to do something similar with ethers.js or other library I'd be grateful to hear your suggestions.

Best Answer

The API for doing this is defined in EIP-747.

You'll need to use the wallet_watchAsset method, something along the lines of the following example code:

const tokenAddress = '0xd00981105e61274c8a5cd5a88fe7e037d935b513';
const tokenSymbol = 'TUT';
const tokenDecimals = 18;
const tokenImage = 'http://placekitten.com/200/300';

try {
  // wasAdded is a boolean. Like any RPC method, an error may be thrown.
  const wasAdded = await ethereum.request({
    method: 'wallet_watchAsset',
    params: {
      type: 'ERC20', // Initially only supports ERC20, but eventually more!
      options: {
        address: tokenAddress, // The address that the token is at.
        symbol: tokenSymbol, // A ticker symbol or shorthand, up to 5 chars.
        decimals: tokenDecimals, // The number of decimals in the token
        image: tokenImage, // A string url of the token logo

  if (wasAdded) {
    console.log('Thanks for your interest!');
  } else {
    console.log('Your loss!');
} catch (error) {
Related Topic