cryptocurrency nodejs axios blockchain ethereum etherscan-api smart-contracts token-transfers query-wallet-balance erc-20-tokens
Tutorial: Understanding and Using the Etherscan API to Query Blockchain Data
In this tutorial, you'll learn how to use the Etherscan API to query blockchain data such as Ethereum wallet balances, transaction details, token balances, and more. This guide will help you set up your Etherscan API key, make API requests, and interact with the Ethereum blockchain programmatically.
By the end of this tutorial, you will be able to retrieve blockchain information such as transaction history and token balances through simple API calls.
Prerequisites
Before you begin, you’ll need the following:
- Node.js installed on your machine.
- A basic understanding of JavaScript.
- An Etherscan API key (explained below).
Step 1: Get an Etherscan API Key
To use Etherscan’s API, you first need an API key. Follow these steps to get your API key:
- Go to [Etherscan’s website](https://etherscan.io/).
- Sign up for an account (or log in if you already have one).
- Once logged in, go to the API Keys section.
- Create a new API key and copy it—you will need this key to make API requests.
Step 2: Install Axios
We will use Axios to make HTTP requests to the Etherscan API. To install Axios, run the following command in your project folder:
npm install axios
Step 3: Query the Ethereum Wallet Balance Using Etherscan API
Let’s create a Node.js script to query the balance of an Ethereum wallet using the Etherscan API.
- Create a file called
etherscanBalance.js
in your project folder. - Open the file and write the following code:
const axios = require('axios');
// Replace this with your actual Etherscan API key
const apiKey = 'YOUR_ETHERSCAN_API_KEY';
// Replace this with the Ethereum address you want to query
const address = '0xYourEthereumAddress';
// Etherscan API URL to fetch wallet balance
const url = `https://api.etherscan.io/api?module=account&action=balance&address=${address}&tag=latest&apikey=${apiKey}`;
async function getWalletBalance() {
try {
// Make the API request to Etherscan
const response = await axios.get(url);
const balanceInWei = response.data.result;
// Convert balance from Wei to Ether
const balanceInEther = balanceInWei / 1e18;
console.log(`Wallet Address: ${address}`);
console.log(`Wallet Balance: ${balanceInEther} ETH`);
} catch (error) {
console.error('Error fetching balance:', error);
}
}
// Call the function to get the balance
getWalletBalance();
Explanation:
- Axios is used to make the HTTP request to the Etherscan API.
- Replace
'YOUR_ETHERSCAN_API_KEY'
with the actual API key you obtained from Etherscan. - Replace
'0xYourEthereumAddress'
with the Ethereum address you want to query. - The balance is returned in Wei (the smallest unit of Ether). We convert this to Ether for readability by dividing by
1e18
.
Step 4: Run the Script
Once you have written the script, run it from your terminal:
node etherscanBalance.js
If everything is set up correctly, you’ll see an output like this:
Wallet Address: 0xYourEthereumAddress
Wallet Balance: 1.234 ETH
This script queries the wallet balance from the Ethereum blockchain using the Etherscan API.
Step 5: Query Ethereum Transaction Details
Let’s extend the functionality by querying transaction details for a specific transaction using the Etherscan API.
- Create a new file called
etherscanTransaction.js
. - Open the file and add the following code:
const axios = require('axios');
// Replace this with your actual Etherscan API key
const apiKey = 'YOUR_ETHERSCAN_API_KEY';
// Replace this with the transaction hash you want to query
const transactionHash = '0xYourTransactionHash';
// Etherscan API URL to fetch transaction details
const url = `https://api.etherscan.io/api?module=proxy&action=eth_getTransactionByHash&txhash=${transactionHash}&apikey=${apiKey}`;
async function getTransactionDetails() {
try {
// Make the API request to Etherscan
const response = await axios.get(url);
const transactionDetails = response.data.result;
// Log the transaction details
console.log('Transaction Details:', transactionDetails);
} catch (error) {
console.error('Error fetching transaction details:', error);
}
}
// Call the function to get the transaction details
getTransactionDetails();
Explanation:
- Replace
'YOUR_ETHERSCAN_API_KEY'
with your actual Etherscan API key. - Replace
'0xYourTransactionHash'
with the transaction hash you want to query. - This script uses the
eth_getTransactionByHash
endpoint to fetch transaction details, such as gas price, block number, and sender/receiver addresses.
Example API Call in Browser:
You can also query transaction details directly in your browser by visiting:
https://api.etherscan.io/api?module=proxy&action=eth_getTransactionByHash&txhash=0xYourTransactionHash&apikey=YOUR_ETHERSCAN_API_KEY
Step 6: Query ERC-20 Token Balances
You can also query ERC-20 token balances for a given address using the Etherscan API.
- Create a new file called
etherscanTokenBalance.js
. - Add the following code to fetch the ERC-20 token balance of a specific address:
const axios = require('axios');
// Replace this with your actual Etherscan API key
const apiKey = 'YOUR_ETHERSCAN_API_KEY';
// Replace this with the Ethereum address you want to query
const address = '0xYourEthereumAddress';
// Replace this with the contract address of the ERC-20 token
const contractAddress = '0xYourTokenContractAddress';
// Etherscan API URL to fetch the ERC-20 token balance
const url = `https://api.etherscan.io/api?module=account&action=tokenbalance&contractaddress=${contractAddress}&address=${address}&tag=latest&apikey=${apiKey}`;
async function getTokenBalance() {
try {
// Make the API request to Etherscan
const response = await axios.get(url);
const tokenBalance = response.data.result;
// Log the token balance (Note: Token balances are often in very small denominations)
console.log(`Token Balance: ${tokenBalance}`);
} catch (error) {
console.error('Error fetching token balance:', error);
}
}
// Call the function to get the token balance
getTokenBalance();
Explanation:
- Replace
'YOUR_ETHERSCAN_API_KEY'
with your Etherscan API key. - Replace
'0xYourEthereumAddress'
with the address you want to query. - Replace
'0xYourTokenContractAddress'
with the ERC-20 token's contract address (e.g., USDT or DAI token contract). - This script queries the ERC-20 token balance for a specific Ethereum address.
Other Useful Etherscan API Endpoints
- Get a List of Transactions for an Address:
https://api.etherscan.io/api?module=account&action=txlist&address=0xYourEthereumAddress&startblock=0&endblock=99999999&sort=asc&apikey=YOUR_API_KEY
- Get ERC-20 Token Transfer Events:
https://api.etherscan.io/api?module=account&action=tokentx&address=0xYourEthereumAddress&startblock=0&endblock=99999999&sort=asc&apikey=YOUR_API_KEY
- Get the Current Gas Price:
https://api.etherscan.io/api?module=proxy&action=eth_gasPrice&apikey=YOUR_API_KEY
These endpoints give you the flexibility to retrieve detailed blockchain data and customize your applications accordingly.
Conclusion
In this tutorial, you learned how to interact with the Ethereum blockchain using the Etherscan API. You successfully queried Ethereum wallet balances, transaction details, and ERC-20 token balances. By using the Etherscan API, you can easily access blockchain data without needing to run your own Ethereum node.
The Etherscan API is a powerful tool for developers who want to build applications that require data about Ethereum addresses, tokens, transactions, and smart contracts.
Comments
Please log in to leave a comment.