8

I make login with metamask on my website (Laravel & Vuejs). I installed Web3 and doing actions such as getAccounts, Sign , getBalance and etc.

But I want to get all tokens(Such as BNB, RARI and etc) balance in metamask. I wrote this code:

//     accounts[0] => default wallet number
window.web3.eth.getBalance(accounts[0], (err, b) => {
  if (err)
      console.log(err);
  let balance = {};
  balance.ether = window.web3.utils.fromWei(b, "ether");
});

But just return ETH Token Balance not all tokens.

How do i get all tokens balance? Can you help me?

miken32
  • 42,008
  • 16
  • 111
  • 154
Amin
  • 387
  • 1
  • 6
  • 17

1 Answers1

5

As you already figured out in the comments, nobody knows all the token balances of your account, not even MetaMask. This is due to the fact that the tokens do not reside in your account, but in the token smart contract which tracks your token balance.

Therefore, you have to check each token's contract for the account you are querying to get the token balance. Which brings us to the next issue: How do we know each token's contract address?

Wallets, such as MyCrypto or MetaMask maintain their own whitelists of well-known token contracts. The ethereum-lists collective has you covered for ERC-20 tokens:

https://github.com/ethereum-lists/tokens

It currently lists more than 2000 tokens for Ethereum and you can either pick your favorites or parse them all. Each token has a JSON spec definition containing the most important parameters, e.g.:

{
  "symbol": "TUSD",
  "name": "TrueUSD",
  "type": "ERC20",
  "address": "0x0000000000085d4780B73119b644AE5ecd22b376",
  "ens_address": "",
  "decimals": 18,
  "website": "https://www.trusttoken.com",
  "logo": {
    "src": "",
    "width": "",
    "height": "",
    "ipfs_hash": ""
  },
  "support": {
    "email": "hello@trusttoken.com",
    "url": ""
  },
  "social": {
    "blog": "https://blog.trusttoken.com",
    "chat": "",
    "facebook": "",
    "forum": "",
    "github": "https://github.com/trusttoken",
    "gitter": "",
    "instagram": "",
    "linkedin": "",
    "reddit": "https://www.reddit.com/r/TrustToken/",
    "slack": "",
    "telegram": "https://t.me/joinchat/HihkMkTja1gIyBRM1J1_vg",
    "twitter": "https://twitter.com/TrustToken",
    "youtube": ""
  }
}

Source: https://github.com/ethereum-lists/tokens/blob/c11d278944dc66e95b3b1c44786676b697c84b0a/tokens/eth/0x0000000000085d4780B73119b644AE5ecd22b376.json

TylerH
  • 20,799
  • 66
  • 75
  • 101
q9f
  • 11,293
  • 8
  • 57
  • 96