Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web3 Get All Tokens by Wallet Address

I am trying to pull a list of token contracts held by a wallet address, similar to how bscscan does, except programmatically. bscscan.com/apis does not have an endpoint, and web3 seems to only report the ETH balance.

This is possible to achieve, since bscscan reports the list and many token trackers ( such as farmfol.io ) also seem to pull that information. I am just not finding the correct methodology. Any assistance is appreciated!

like image 853
Nomad Avatar asked Jun 22 '21 14:06

Nomad


2 Answers

ERC-20 (and ERC-20-like such as TRC-20, BEP-20, etc.) token balance of each address is stored in the contract of the token.

Blockchain explorers scan each transaction for Transfer() events and if the emitter is a token contract, they update the token balances in their separate DB. The balance of all tokens per each address (from this separate DB) is then displayed as the token balance on the address detail page.

Etherscan and BSCScan currently don't provide an API that would return the token balances per address.

In order to get all ERC-20 token balances of an address, the easiest solution (apart from finding an API that returns the data) is to loop through all token contracts (or just the tokens that you're interested in), and call their balanceOf(address) function.

const tokenAddresses = [
    '0x123',
    '0x456',
];
const myAddress = '0x789';

for (let tokenAddress of tokenAddresses) {
    const contract = new web3.eth.Contract(erc20AbiJson, tokenAddress);
    const tokenBalance = await contract.methods.balanceOf(myAddress).call();
}
like image 82
Petr Hejda Avatar answered Sep 19 '22 19:09

Petr Hejda


You can call

https://api.bscscan.com/api?module=account&action=tokentx&address=0x7bb89460599dbf32ee3aa50798bbceae2a5f7f6a&page=1&offset=5&startblock=0&endblock=999999999&sort=asc&apikey=YourApiKeyToken

and parse the result. All your tokens you ever touched will be here.

Reference

like image 43
Magno C Avatar answered Sep 20 '22 19:09

Magno C