How to Get All Tokens Owned by an Address

Learn how to get balances of all tokens owned by an address using the Alchemy Token API.

This tutorial uses the alchemy_getTokenBalances endpoint.

Most dapps, whether they are exchanges, DeFi protocols, wallets, or analytics platforms, require that their users are able to view all their tokens and token balances at one place.

359

Digital asset wallet interface that shows the token balances of multiple cryptocurrencies.

To get all the tokens owned by a wallet on Ethereum, you would typically have to index the entire blockchain since genesis, track all ERC-20 contracts, and compute token balances of wallets.

This process typically requires a massive amount of engineering resources and time.

However, this effort can be bypassed by using Alchemy’s Token API to get the balances of all tokens owned by a wallet address.

About this Tutorial


We will write a simple script in Node to get the balances of the top 100 tokens (by volume) on the Ethereum blockchain using a free Alchemy developer account and Alchemy’s Token API.

Creating the Token Balances Script


Step 1: Install Node and npm

In case you haven’t already, install node and npm on your local machine.

Make sure that node is at least v14 or higher by typing the following in your terminal:

shell
$node -v

Step 2: Create an Alchemy app


In case you haven’t already, sign up for a free Alchemy account.

880

Alchemy’s account dashboard where developers can create a new app on the Ethereum blockchain.

Next, navigate to the Alchemy Dashboard and create a new app.

Make sure you set the chain to Ethereum and the network to Mainnet.

Once the app is created, click on your app’s View Key button on the dashboard.

Take note of the HTTP URL.

The URL will be in this form: https://eth-mainnet.g.alchemy.com/v2/xxxxxxxxx

You will need this later.


Step 3: Create a node project

Let’s now create an empty repository and install all node dependencies.

To make requests to the Token API, use the Alchemy SDK.

You can also use axios or fetch alternatively.

$mkdir token-balances && cd token-balances
>npm init -y
>npm install --save alchemy-sdk
>touch main.js

This will create a repository named token-balances that holds all your files and dependencies.

Next, open this repo in your favorite code editor.

We will be writing all our code in the main.js file.

Step 4: Get token balances of an address

To get token balances, you will use the getTokenBalances method.

This method takes one argument:

  1. DATA: The wallet address of which we want to get token balances.

Add the following code to the main.js file.

1// Setup: npm install alchemy-sdk
2const { Alchemy, Network } = require("alchemy-sdk");
3
4const config = {
5 apiKey: "<-- ALCHEMY API KEY -->",
6 network: Network.ETH_MAINNET,
7};
8const alchemy = new Alchemy(config);
9
10const main = async () => {
11 // Wallet address
12 const address = "0xd8da6bf26964af9d7eed9e03e53415d37aa96045";
13
14 // Get token balances
15 const balances = await alchemy.core.getTokenBalances(address);
16
17 console.log(`The balances of ${address} address are:`, balances);
18};
19
20const runMain = async () => {
21 try {
22 await main();
23 process.exit(0);
24 } catch (error) {
25 console.log(error);
26 process.exit(1);
27 }
28};
29
30runMain();

Run the script using:

shell
$node main.js

You should obtain an output that looks something like this:

$The balances of 0xd8da6bf26964af9d7eed9e03e53415d37aa96045 address are: {
> address: '0xd8da6bf26964af9d7eed9e03e53415d37aa96045',
> tokenBalances: [
> {
> contractAddress: '0x000000a1a6cb569ee64e1f8c3529390113e34cf8',
> tokenBalance: '0x000000000000000000000000000000000000000078b2ef682a5071579d3e6b16'
> },
> {
> contractAddress: '0x0027449bf0887ca3e431d263ffdefb244d95b555',
> tokenBalance: '0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'
> }

Step 5: Add metadata and parse API output

The output generated in the previous step is not very human-readable. It only gives us information that tells us the contract address of the token and the balance in its smallest unit.

To get more relevant information about the token such as name, symbol, and the number of decimals, we need to leverage another method called getTokenMetadata.

The alchemy_getTokenMetadata method takes a single argument of the contract address and returns data in the following format:

gettokenmetadata.json
1{
2 decimals: 6,
3 logo: 'https://static.g.alchemy.com/images/assets/825.png',
4 name: 'Tether',
5 symbol: 'USDT'
6}

We will use this method in conjunction with getTokenBalances method, to write code that does the following:

  1. Remove all tokens with zero balances.
  2. Loop through all tokens and extract metadata using the getTokenMetadata method.
  3. Convert token balances to a human-readable number.
  4. Print the token’s name, balance, and symbol to the console.

The tokenBalance returned by the Token API is usually a number with several digits.

In this case 4929853276 for USDT.

Every ERC20 token has a metadata information called “decimals” which denotes the divisibility of a token (ranges from 0 to 18).

For USDT, the value of “decimals” is 6.

The response returned by alchemy_getTokenBalances is as below.\

tokenBalance = no. of tokens (quantity) * Math.pow(10, 6)

Hence, the actual quantity of the USDT token in this case will be

4929853276/10^6 = 4,929.853276

The same operation needs to be done to obtain the actual quantity for any token.

We show the calculation in the code below

Replace the contents of main.js with the following:

1// Setup: npm install alchemy-sdk
2import { Alchemy, Network } from "alchemy-sdk";
3
4const config = {
5 apiKey: "<-- ALCHEMY APP API KEY -->",
6 network: Network.ETH_MAINNET,
7};
8const alchemy = new Alchemy(config);
9
10const main = async () => {
11 // Wallet address
12 const address = "0xd8da6bf26964af9d7eed9e03e53415d37aa96045";
13
14 // Get token balances
15 const balances = await alchemy.core.getTokenBalances(address);
16
17 // Remove tokens with zero balance
18 const nonZeroBalances = balances.tokenBalances.filter((token) => {
19 return token.tokenBalance !== "0";
20 });
21
22 console.log(`Token balances of ${address} \n`);
23
24 // Counter for SNo of final output
25 let i = 1;
26
27 // Loop through all tokens with non-zero balance
28 for (let token of nonZeroBalances) {
29 // Get balance of token
30 let balance = token.tokenBalance;
31
32 // Get metadata of token
33 const metadata = await alchemy.core.getTokenMetadata(token.contractAddress);
34
35 // Compute token balance in human-readable format
36 balance = balance / Math.pow(10, metadata.decimals);
37 balance = balance.toFixed(2);
38
39 // Print name, balance, and symbol of token
40 console.log(`${i++}. ${metadata.name}: ${balance} ${metadata.symbol}`);
41 }
42};
43
44const runMain = async () => {
45 try {
46 await main();
47 process.exit(0);
48 } catch (error) {
49 console.log(error);
50 process.exit(1);
51 }
52};
53
54runMain();

Run the script again using:

shell
$node main.js

You should obtain an output that looks something like this:

shell
$Token balances of 0xd8da6bf26964af9d7eed9e03e53415d37aa96045
>
>1. Tether: 0.10 USDT
>2. USD Coin: 5.00 USDC
>3. WETH: 0.05 WETH
>4. ApeCoin: 1.00 APE
>5. Mirror Protocol: 0.00 MIR
>6. Shiba Inu: 3.14 SHIB
>7. Dai: 764324.64 DAI
>8. Loopring: 1000.32 LRC
>9. SushiSwap: 0.00 SUSHI
>10. Axie Infinity: 0.02 AXS
>11. Ethereum Name Service: 1143.54 ENS
>12. OMG Network: 123638.06 OMG
>13. Basic Attention Token: 17.47 BAT
>14. dYdX: 0.52 DYDX
>15. Mask Network: 1.00 MASK
>16. 1inch Network: 5.00 1INCH
>17. Livepeer: 2.26 LPT
>18. Request: 126.00 REQ
>19. HEX: 100.00 HEX

Conclusion


Congratulations! You now know how to use the Alchemy Token API to get all tokens and token balances of any address on the Ethereum blockchain.

If you enjoyed this tutorial on how to get all tokens owned by an address, give us a tweet @Alchemy, or shoutout feedback to the authors @rounak_banik and @ankg404!

Don’t forget to join our Discord server to meet other blockchain devs, builders, and entrepreneurs.

Ready to start using the Alchemy Token API?

Create a free Alchemy account and share your project with us!