14

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.

exakoss
  • 141
  • 1
  • 1
  • 5

1 Answers1

19

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) {
  console.log(error);
}

Richard Horrocks
  • 37,835
  • 13
  • 87
  • 144
  • 1
    This looks exactly like what I need, I will try this solution out asap, thx! – exakoss May 20 '21 at 11:08
  • Is ERC721 supported as a type? I am getting an error when I change the type from ERC20 to ERC721 – Slaven Tojić Sep 11 '21 at 10:19
  • @SlavenTojic if you just leave type as ERC20 it will work even if the contract is an ERC721. – Zargoon Mar 07 '22 at 23:54
  • Just a small note, this doesn't come from ethers.js but from web3 which is injected by the wallets extension like metamask. So, you'll get access to the ethereum object through window.ethereum. https://docs.metamask.io/guide/rpc-api.html#wallet-watchasset – redigaffi Apr 22 '22 at 16:01
  • I want to select a custom token from the metamasks when init eth_sendTransaction, and offer to transfer the custom token, not the ether. How do it? – aprinciple May 12 '22 at 06:35