cryptocurrency nodejs ethereum etherscan-api smart-contracts token-transfers ethersjs erc-20-tokens blockchain-explorer token-balance
Tutorial: How to Query ERC-20 Token Balances and Transactions Using Ethers.js and Etherscan API
In this tutorial, you will learn how to use Ethers.js and the Etherscan API to query ERC-20 token balances and view token transaction history for a specific Ethereum address. ERC-20 tokens are a standard for fungible tokens on the Ethereum blockchain, and querying their balances and transactions is essential for building decentralized applications (dApps) like wallets, token explorers, and DeFi platforms.
By the end of this tutorial, you will be able to:
- Query the balance of ERC-20 tokens for an Ethereum address.
- Retrieve ERC-20 token transfer histories using the Etherscan API.
Prerequisites
To follow along with this tutorial, you’ll need:
- Node.js installed on your machine.
- A basic understanding of JavaScript.
- An Etherscan API key (explained below).
- Familiarity with Ethers.js for blockchain interaction.
Step 1: Set Up Etherscan and Get an API Key
To use the Etherscan API, you’ll need to get an API key. Here’s how:
- Go to [Etherscan’s website](https://etherscan.io/).
- Sign up for a free account (or log in if you already have one).
- Navigate to the API Keys section and generate a new API key.
- Copy your API key — you’ll use this key to interact with the Etherscan API.
Step 2: Install Ethers.js and Axios
We will use Ethers.js to interact with the Ethereum blockchain and Axios to make HTTP requests to the Etherscan API.
- Navigate to your project folder and run the following commands to install Ethers.js and Axios:
npm install ethers
npm install axios
Step 3: Query ERC-20 Token Balance Using Ethers.js
In this step, we will use Ethers.js to query the balance of an ERC-20 token for a specific Ethereum address.
- Create a new file called
getTokenBalance.js
in your project folder. - Add the following code to query the token balance:
const ethers = require('ethers');
// Replace with your Infura or other Ethereum node provider URL
const provider = new ethers.JsonRpcProvider('https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID');
// Replace with the ERC-20 token contract address (e.g., USDT, DAI)
const contractAddress = '0xTokenContractAddress';
// Replace with the wallet address you want to query
const walletAddress = '0xYourEthereumAddress';
// ERC-20 token ABI (just the balanceOf function)
const abi = [
'function balanceOf(address owner) view returns (uint256)'
];
// Create a contract instance
const contract = new ethers.Contract(contractAddress, abi, provider);
async function getTokenBalance() {
try {
// Query the balance
const balance = await contract.balanceOf(walletAddress);
// Convert balance to a human-readable format (tokens usually have 18 decimals)
const formattedBalance = ethers.utils.formatUnits(balance, 18);
console.log(`Token Balance: ${formattedBalance}`);
} catch (error) {
console.error('Error fetching token balance:', error);
}
}
// Call the function to get the token balance
getTokenBalance();
Explanation:
- Contract Address: Replace
'0xTokenContractAddress'
with the address of the ERC-20 token (e.g., USDT, DAI, or any other ERC-20 token). - Wallet Address: Replace
'0xYourEthereumAddress'
with the wallet address whose token balance you want to query. - ABI: We are using a minimal ABI with just the
balanceOf
function, which is all that’s required to query the token balance.
Running the Script:
Once you’ve added the code, run the script:
node getTokenBalance.js
You should see the token balance printed in the console, in a human-readable format (typically with 18 decimals for ERC-20 tokens).
Step 4: Query ERC-20 Token Transfer History Using Etherscan API
Now let’s query the ERC-20 token transfer history for a specific wallet address using the Etherscan API.
- Create a new file called
getTokenTransactions.js
. - Add the following code to query the token transaction history:
const axios = require('axios');
// Replace with your Etherscan API key
const apiKey = 'YOUR_ETHERSCAN_API_KEY';
// Replace with the wallet address you want to query
const address = '0xYourEthereumAddress';
// Replace with the ERC-20 token contract address
const contractAddress = '0xTokenContractAddress';
// Etherscan API URL to fetch ERC-20 token transactions
const url = `https://api.etherscan.io/api?module=account&action=tokentx&contractaddress=${contractAddress}&address=${address}&startblock=0&endblock=99999999&sort=asc&apikey=${apiKey}`;
async function getTokenTransactions() {
try {
// Make the API request to Etherscan
const response = await axios.get(url);
const transactions = response.data.result;
// Log the token transactions
transactions.forEach(tx => {
console.log(`
From: ${tx.from}
To: ${tx.to}
Value: ${ethers.utils.formatUnits(tx.value, 18)} Tokens
Transaction Hash: ${tx.hash}
`);
});
} catch (error) {
console.error('Error fetching token transactions:', error);
}
}
// Call the function to get the token transactions
getTokenTransactions();
Explanation:
- API Key: Replace
'YOUR_ETHERSCAN_API_KEY'
with the API key you generated from Etherscan. - Wallet Address: Replace
'0xYourEthereumAddress'
with the wallet address you want to query for token transactions. - Token Contract Address: Replace
'0xTokenContractAddress'
with the contract address of the ERC-20 token you want to track.
Running the Script:
Once you’ve added the code, run the script:
node getTokenTransactions.js
You should see a list of token transactions for the specified address, with details including the sender, recipient, value transferred, and transaction hash.
Step 5: Customizing the API Request
You can customize the Etherscan API request to suit your needs. Here are a few options:
- Start and End Block: Adjust the
startblock
andendblock
parameters to limit the range of blocks you want to query. - Sort: Set the
sort
parameter toasc
(ascending) ordesc
(descending) to control the order of the transactions. - Token Transfers for All Tokens: You can modify the API call to query all token transfers for an address, not just a specific token contract, by omitting the
contractaddress
parameter.
Conclusion
In this tutorial, you learned how to use Ethers.js to query ERC-20 token balances and how to leverage the Etherscan API to retrieve token transaction histories. These are essential techniques for building decentralized applications, wallets, or blockchain explorers that interact with ERC-20 tokens on the Ethereum network.
You now have the tools to query token balances and transaction histories programmatically, enabling you to create powerful blockchain-based applications.
Comments
Please log in to leave a comment.