How to get token balance for an address
Learn how to get the balance of a single token being held by a specific contract address.
The token balances for a user address is a critical data point for almost any web3 use case - be it DeFi platforms, wallets, analytics, exchanges and many others. A common use case would be displaying the balances as below in your wallet app
Sample wallet screen displaying coin balances
To fetch this data you have 2 options
  1. 1.
    Fetch the Transaction History for the token’s contract, for example take USDT, which is millions of records. Then search through for your user’s address among those records (will take hours) and then show that to your user. Not to forget, do this indexing process every second forever to keep it updated for every user.
  2. 2.
    OR just use Alchemy’s getTokenBalances endpoint
If you’re like most web3 developers, you probably want to go for the second option!

How to query the token balance of an address

When querying the token balance for a user, you should have couple of key parameters on hand
  • OwnerAddress: This is the blockchain address that owns the tokens in question. Note that this is not the contract address of the token itself.
  • tokenContractAddress : One of the following values:
    • An array of contract addresses of all the token’s you want the balances for
    • The string "DEFAULT_TOKENS" - denotes a query for the top 100 tokens by 24 hour volume.
Example: Get current USDT balance for an Address
For this particular example we're going to fetch the USDT balance for address 0x00000000219ab540356cbb839cbe05303d7705fa (fun fact: this address has the highest ETH balance among all addresses! )

No-Code Example

For a no-code view of the API request, check out the composer tool
Alchemy Web3.js (Recommended)
Node-Fetch
Axios
token_api_javascript_scripts/token-balances-from-alchemyWeb3.js at master · OMGWINNING/token_api_javascript_scripts
GitHub

Step 1: Install Alchemy-Web3 and create a file

Run the below commands in the command line
1
npm install @alch/alchemy-web3
2
touch token-balances-from-alchemyWeb3.js
Copied!

Step 2: Write the token balance querying script

Inside the token-balances-from-alchemyWeb3.js file, paste the below code
1
import { createAlchemyWeb3 } from "@alch/alchemy-web3";
2
3
//Replace with your API Key
4
const apiKey = "demo";
5
6
// Initialize an alchemy-web3 instance:
7
const web3 = createAlchemyWeb3(
8
`https://eth-mainnet.alchemyapi.io/v2/${apiKey}`,
9
);
10
11
//Feel free to switch this wallet address with another address
12
const ownerAddress = "0x00000000219ab540356cbb839cbe05303d7705fa";
13
14
//The below token contract address corresponds to USDT
15
const tokenContractAddresses = ["0xdAC17F958D2ee523a2206206994597C13D831ec7"];
16
17
const data = await web3.alchemy.getTokenBalances( ownerAddress, tokenContractAddresses);
18
19
console.log("Token balance for Address");
20
console.log(data);
Copied!

Step 3: Run the code to get the token balance with alchemy-web3.js

1
node token-balances-from-alchemyWeb3.js
Copied!
You should see the below output
1
Token balance for Address
2
{
3
address: '0x00000000219ab540356cbb839cbe05303d7705fa',
4
tokenBalances: [
5
{
6
contractAddress: '0xdAC17F958D2ee523a2206206994597C13D831ec7',
7
tokenBalance: '4929853276',
8
error: null
9
}
10
]
11
}
Copied!
token_api_javascript_scripts/token-balances-from-fetch.js at master · OMGWINNING/token_api_javascript_scripts
GitHub

Step 1: Create a node-fetch file

Run the below commands in the command line
1
touch token-balances-from-fetch.js
Copied!

Step 2: Write the script for querying token balances!

Inside the token-balances-from-fetch.js file, paste the below code
1
import fetch from 'node-fetch';
2
3
// Replace with your Alchemy API key:
4
const apiKey = "demo";
5
6
const fetchURL = `https://eth-mainnet.g.alchemy.com/v2/${apiKey}`;
7
8
// Replace with the wallet address you want to query:
9
const ownerAddr = "0x00000000219ab540356cbb839cbe05303d7705fa";
10
11
// Replace with the token contract address you want to query:
12
const tokenAddr = "0xdAC17F958D2ee523a2206206994597C13D831ec7";
13
14
var raw = JSON.stringify({
15
"jsonrpc": "2.0",
16
"method": "alchemy_getTokenBalances",
17
"headers": {
18
"Content-Type": "application/json"
19
},
20
"params": [
21
`${ownerAddr}`,
22
[
23
`${tokenAddr}`,
24
]
25
],
26
"id": 42
27
});
28
29
var requestOptions = {
30
method: 'POST',
31
body: raw,
32
redirect: 'follow'
33
};
34
35
// Make the request and print the formatted response:
36
fetch(fetchURL, requestOptions)
37
.then(response => response.json())
38
.then(response => JSON.stringify(response, null, 2))
39
.then(result => console.log(result))
40
.catch(error => console.log('error', error));
Copied!

Step 3: Run the code to get the token balance with Node-Fetch

1
node token-balances-from-fetch.js
Copied!
You should see the below output
1
Token balance for Address
2
{
3
address: '0x00000000219ab540356cbb839cbe05303d7705fa',
4
tokenBalances: [
5
{
6
contractAddress: '0xdAC17F958D2ee523a2206206994597C13D831ec7',
7
tokenBalance: '4929853276',
8
error: null
9
}
10
]
11
}
Copied!
token_api_javascript_scripts/token-balances-from-axios.js at master · OMGWINNING/token_api_javascript_scripts
GitHub

Step 1: Install axios and create a file

Run the below commands in the command line
1
npm install axios
2
touch token-balances-from-axios.js
Copied!

Step 2: Write the script to query token balances with Axios

Inside the token-balances-from-axios.js file, paste the below code
1
import axios from 'axios';
2
3
// Replace with your Alchemy API key:
4
const apiKey = "demo";
5
6
const baseURL = `https://eth-mainnet.g.alchemy.com/v2/${apiKey}`;
7
8
// Replace with the wallet address you want to query:
9
const ownerAddr = "0x00000000219ab540356cbb839cbe05303d7705fa";
10
11
// Replace with the token contract address you want to query:
12
const tokenAddr = "0xdAC17F958D2ee523a2206206994597C13D831ec7";
13
14
var data = JSON.stringify({
15
"jsonrpc": "2.0",
16
"method": "alchemy_getTokenBalances",
17
"params": [
18
`${ownerAddr}`,
19
[
20
`${tokenAddr}`
21
]
22
],
23
"id": 42
24
});
25
26
var config = {
27
method: 'post',
28
url: baseURL,
29
headers: {
30
'Content-Type': 'application/json'
31
},
32
data : data
33
};
34
35
axios(config)
36
.then(function (response) {
37
//This line converts the tokenBalance values from hex to decimal
38
response.data["result"]["tokenBalances"][0]["tokenBalance"] = parseInt(response.data["result"]["tokenBalances"][0]["tokenBalance"], 16);
39
console.log("Token balance for address\n", JSON.stringify(response.data.result, null, 2))
40
})
41
.catch(function (error) {
42
console.log(error);
43
});
Copied!

Step 4: Run the code to get token balances with Axios

1
node token-balances-from-axios.js
Copied!
You should see output like
1
Token balance for Address
2
{
3
address: '0x00000000219ab540356cbb839cbe05303d7705fa',
4
tokenBalances: [
5
{
6
contractAddress: '0xdAC17F958D2ee523a2206206994597C13D831ec7',
7
tokenBalance: '4929853276',
8
error: null
9
}
10
]
11
}
Copied!
In the above steps, you can replace the ownerAddress with any owner’s address and replace tokenContractAddresses with any array of addresses, to get the right token balance!

How to process the API response

Now that we have made the query and can see the response, let's learn how to handle it.
If you feel like jumping ahead and grabbing some pre-built code, choose and pick a code from the below options that matches your preferred library.
Alchemy Web3 (Recommended)
Node-Fetch
Axios
The below linked Github script is for the Alchemy-Web3.js library and takes the output of the getTokenBalances endpoint, joins it with the output of the getTokenMetadata endpoint and returns a clean output "The balance of Token X is Y"
token_api_javascript_scripts/token-balances-parsed-from-alchemyWeb3.js at master · OMGWINNING/token_api_javascript_scripts
GitHub
The below linked Github script uses Node-fetch and takes the output of the getTokenBalances endpoint, joins it with the output of the getTokenMetadata endpoint and returns a clean output "The balance of Token X is Y"
token_api_javascript_scripts/token-balances-parsed-from-fetch.js at master · OMGWINNING/token_api_javascript_scripts
GitHub
The below linked Github script uses Axios.js and takes the output of the getTokenBalances endpoint, joins it with the output of the getTokenMetadata endpoint and returns a clean output "The balance of Token X is Y"
token_api_javascript_scripts/token-balances-parsed-from-axios.js at master · OMGWINNING/token_api_javascript_scripts
GitHub

Raw API Response:

The usual result looks something like this
1
{
2
"address": "0x00000000219ab540356cbb839cbe05303d7705fa",
3
"tokenBalances": [
4
{
5
"contractAddress": "0xdAC17F958D2ee523a2206206994597C13D831ec7",
6
"tokenBalance": 4929853276,
7
"error": null
8
}
9
]
10
}
Copied!
Understanding the API Response:
  • Address: The address of the owner for whom you want to pull the balance of the token
  • contractAddress: The contract address of the token in question. To pull the actual name of the token and other details, we will use another API getTokenMetadata.
  • tokenBalance: balance of the specific contractAddress for the owner address address
The tokenBalance in its raw form as returned by getTokenBalances is the number in terms of the smallest unit of the token. In the code below, we do a bit of calculation to get the clear quantity of the token in decimal units.

The Calculation for tokenBalance

The tokenBalance returned by the 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's getTokenBalances API 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.

How to calculate & print the tokenName and tokenBalance

Two of the many different response objects you may be interested in parsing are: tokenName and tokenBalance (in USD)
Whether we're querying via alchemy-web3, axios, or node-fetch, we'll have to follow the below steps 1. Save the response of getTokenBalances into a constant/variable 2. Get the Token name for the concerned Token Contract address (using getTokenMetadata) 3. Convert the tokenBalance into the correct units (using getTokenMetadata)
Let's walk through the below sample code that parses the returned JSON object.
Alchemy Web3 (Recommended)
Node-Fetch
Axios
1
/*
2
** Fetching the metadata for the token with Alchemy's getTokenMetadata API
3
*/
4
const metadata = await web3.alchemy.getTokenMetadata(
5
tokenContractAddresses[0]
6
);
7
8
//Forming the name of the token that comprises of the Name and the Symbol of the token
9
const tokenName = metadata.name + "(" + metadata.symbol + ")";
10
11
/* Calculating the tokenBalance in decimal. The "decimals" field in the token metadata on line 21 tells us
12
how many digits at the end of the tokenBalance in Line 17 are to the right of the decimal.
13
so we divide the Full tokenBalance with 10 to the power of the decimal value of the token
14
*/
15
const tokenBalance = data["tokenBalances"][0]["tokenBalance"]/Math.pow(10, metadata.decimals)
16
console.log("Token balance for", tokenName, "is", tokenBalance);
Copied!
1
var metadata;
2
3
var metadataRaw = JSON.stringify({
4
"jsonrpc": "2.0",
5
"method": "alchemy_getTokenMetadata",
6
"headers": {
7
"Content-Type": "application/json"
8
},
9
"params": [
10
`${tokenAddr}`
11
],
12
"id": 42
13
});
14
15
var metadataRequestOptions = {
16
method: 'POST',
17
body: metadataRaw,
18
redirect: 'follow'
19
};
20
21
/*
22
** Fetching the metadata for the token with Alchemy's getTokenMetadata API
23
*/
24
fetch(fetchURL, metadataRequestOptions)
25
.then(response => response.json())
26
.then(response => {
27
metadata = response.result;
28
29
//Forming the name of the token that comprises of the Name and the Symbol of the token
30
const tokenName = metadata.name + "(" + metadata.symbol + ")";
31
32
/* Calculating the tokenBalance in decimal. The "decimals" field in the token metadata on line 21 tells us
33
how many digits at the end of the tokenBalance in Line 17 are to the right of the decimal.
34
so we divide the Full tokenBalance with 10 to the power of the decimal value of the token
35
*/
36
const tokenBalance = data["tokenBalances"][0]["tokenBalance"]/Math.pow(10, metadata.decimals)
37
console.log("Token balance for", tokenName, "is", tokenBalance);
38
})
39
.catch(error => console.log('error', error));
40
Copied!
1
/*
2
** Fetching the metadata for the token with Alchemy's getTokenMetadata API
3
*/
4
var metadataParams = JSON.stringify({
5
"jsonrpc": "2.0",
6
"method": "alchemy_getTokenMetadata",
7
"params": [
8
`${tokenAddr}`
9
],
10
"id": 42
11
});
12
13
var metadataConfig = {
14
method: 'post',
15
url: baseURL,
16
headers: {
17
'Content-Type': 'application/json'
18
},
19
data : metadataParams
20
};
21
22
axios(metadataConfig)
23
.then(function (response) {
24
metadata = response.data.result;
25
26
//Forming the name of the token that comprises of the Name and the Symbol of the token
27
const tokenName = metadata.name + "(" + metadata.symbol + ")";
28
29
/* Calculating the tokenBalance in decimal. The "decimals" field in the token metadata on line 21 tells us
30
how many digits at the end of the tokenBalance in Line 17 are to the right of the decimal.
31
so we divide the full tokenBalance with 10 to the power of the decimal value of the token
32
*/
33
const tokenBalance = data["tokenBalances"][0]["tokenBalance"]/Math.pow(10, metadata.decimals)
34
console.log("Token balance for", tokenName, "is", tokenBalance);
35
})
Copied!
The output that you would see from running the above code is
1
Token balance for Tether(USDT) is 4929.853276
Copied!
With this, you're all set to fetch token balances from TokenAPI. This can also be extended to fetching the balance for multiple tokens by passing in an array of token addresses, or using the default list (see example here)! If you enjoyed this tutorial for getting address transaction history on Ethereum, give us a tweet @AlchemyPlatform! (Or if you have any questions/feedback give the author @ankg404 a shoutout!)
Don't forget to join our Discord server to meet other blockchain devs, builders, and entrepreneurs!