DeveloperBreeze

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:

  1. Go to Etherscan’s website.
  2. Sign up for an account (or log in if you already have one).
  3. Once logged in, go to the API Keys section.
  4. 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.

  1. Create a file called etherscanBalance.js in your project folder.
  2. 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.

  1. Create a new file called etherscanTransaction.js.
  2. 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.

  1. Create a new file called etherscanTokenBalance.js.
  2. 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

  1. 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
  1. 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
  1. 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.

Related Posts

More content you might like

Tutorial
php

Handling HTTP Requests and Raw Responses in Laravel

In this tutorial, we covered how to handle various HTTP requests in Laravel using the Http facade, including:

Laravel’s Http facade provides a simple yet powerful way to work with APIs, making HTTP requests and handling responses intuitive and clean. By utilizing the methods discussed, you can seamlessly integrate external services into your Laravel application.

Oct 24, 2024
Read More
Tutorial

Understanding `crypto.randomBytes` and `ethers.randomBytes`: A Comparison

  • ethers.randomBytes:
  • Library: ethers.randomBytes is provided by the ethers.js library, a popular JavaScript library for Ethereum development. You need to install and include ethers.js as a dependency in your project to use this function.
  • Usage: This function optionally takes the number of bytes you want to generate. If no argument is passed, it defaults to generating 32 bytes. It returns a Uint8Array of random bytes.
  • Example:
    const { ethers } = require('ethers');
    const randomBytes = ethers.utils.randomBytes(32);
    console.log(randomBytes); // Uint8Array of random bytes

Oct 24, 2024
Read More
Tutorial

How to Query ERC-20 Token Balances and Transactions Using Ethers.js and Etherscan API

  • Query the balance of ERC-20 tokens for an Ethereum address.
  • Retrieve ERC-20 token transfer histories using the Etherscan API.

To follow along with this tutorial, you’ll need:

Oct 24, 2024
Read More
Tutorial

Etherscan vs Infura: Choosing the Right API for Your Blockchain Application

  • Data Analytics: Use Etherscan if you need to fetch historical data, such as transaction histories, token balances, or account balances.
  • Blockchain Explorers: Ideal for building tools similar to Etherscan itself, where you query and display blockchain data to users.
  • Read-Only Data: You can’t send transactions, but you can retrieve information about any Ethereum address, smart contract, or token transfer.
  • Decentralized Applications (dApps): If you’re building an application that needs to interact with Ethereum in real-time, such as sending transactions or calling smart contract functions.
  • Wallets: If you are developing a wallet application that needs to sign and broadcast transactions.
  • Smart Contract Deployment: Use Infura to deploy or interact with smart contracts on the Ethereum blockchain.

Oct 24, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Be the first to share your thoughts!