Search code examples
ethereummetamask

How to get the tokens the user has imported to his Metamask using the ethereum API?


With Metamask, users have to manually import tokens to their account for these to show up in the Assets section. This is has a neat security feature as dust attack and other "spam" tokens are out of sight from the user. You wallet is usually full of spam as well.

Now I want to relay these user intentions (import of a token) to a custom dApp and filter the tokens according to what the user has imported on his Metamask.

i.e can you access the tokens user has imported to his Metamask and thus see the "whitelisted" contract addresses on users Metamask using the ehtereum or other API?

I have more or less read through the Metamask API docs but didn't find anything.

Only hint I found was in this article saying it cannot be done.

unfortunately we can not get all the tokens the wallet has access to, we need to know first the smart contract addresses.


Solution

  • To best of my knowledge it cannot be done, but what you can do is access the tokens that the user has in their wallet (Not the ones imported into metamask)

    Using the Moralis Web3 SDK you can retrieve all token balances of a current user or specified address using:

    const balances = await Moralis.Web3API.account.getTokenBalances({address: "any_address"});
    

    And you get an object with the number of tokens and the array of token objects Example:

    [
      {
        "token_address": "0x2d30ca6f024dbc1307ac8a1a44ca27de6f797ec22ef20627a1307243b0ab7d09",
        "name": "Kylin Network",
        "symbol": "KYL",
        "logo": "https://cdn.moralis.io/eth/0x67b6d479c7bb412c54e03dca8e1bc6740ce6b99c.png",
        "thumbnail": "https://cdn.moralis.io/eth/0x67b6d479c7bb412c54e03dca8e1bc6740ce6b99c_thumb.png",
        "decimals": "18",
        "balance": "123456789"
      },
      {other tokens}
    ]
    

    To filter out the spam token you could iterate over the result and query the user allowance for each of the token contracts. We could suppose that the tokens with allowance != 0 are the token are not spam