DeveloperBreeze

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.

Continue Reading

Discover more amazing content handpicked just for you

Tutorial
php

Handling HTTP Requests and Raw Responses in Laravel

  • $response->successful(): Returns true if the response has a status code of 200-299.
  • $response->failed(): Returns true if the request failed (status code of 400 or greater).

Other useful methods include:

Oct 24, 2024
Read More
Tutorial

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

  • Use crypto.randomBytes when:
  • You are building Node.js applications without blockchain-specific functionality.
  • You want to avoid adding external dependencies.
  • Use ethers.randomBytes when:
  • You are developing Ethereum-related applications and already have ethers.js in your project.
  • You want the flexibility of generating random bytes with minimal configuration, defaulting to 32 bytes for Ethereum addresses or private keys.

Oct 24, 2024
Read More
Tutorial

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

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();
  • 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.

Oct 24, 2024
Read More
Tutorial

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

  • 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.
  • Rate Limits: Etherscan’s free tier limits the number of API requests per second (usually around 5 per second). This is fine for querying data but can be limiting for large-scale applications that need to process a lot of data quickly.
  • Pricing: Etherscan offers paid tiers that increase the API request limits.

Oct 24, 2024
Read More
Tutorial

Sending Transactions and Interacting with Smart Contracts Using Infura and Ethers.js

Once the script is ready, run it using Node.js:

node sendTransaction.js

Oct 24, 2024
Read More
Tutorial

Getting Wallet Balance Using Ethers.js in Node.js

Once your script is set up, run it from the command line:

node getBalance.js

Oct 24, 2024
Read More
Tutorial

Understanding 0x000000000000000000000000000000000000dead Address and Token Burns in Ethereum

Burning tokens refers to the process of sending cryptocurrency tokens to an address from which they cannot be retrieved. Tokens sent to this address are effectively removed from circulation forever. The address ends with "dead," signaling its purpose of making tokens unreachable.

Token burns serve several key purposes in the cryptocurrency world:

Oct 24, 2024
Read More
Tutorial

ETH vs WETH: Understanding the Difference and Their Roles in Ethereum

  • Users deposit ETH into a smart contract.
  • The smart contract issues an equivalent amount of WETH.
  • WETH can then be used within DeFi platforms and decentralized applications.
  • To retrieve the original ETH, users can exchange their WETH back through the smart contract.
  • The contract will burn the WETH and return the original ETH to the user.

Oct 24, 2024
Read More
Tutorial
javascript python

How to Build a Fullstack App with Flask and React

  • Fetch tasks from Flask and display them in React.
  • Create new tasks using a form in React.

You can add more CRUD operations like Update and **

Sep 30, 2024
Read More
Tutorial
javascript

Getting Started with Axios in JavaScript

If you're working on a Node.js project, you can install Axios using npm:

npm install axios

Sep 02, 2024
Read More
Cheatsheet
solidity

Blockchain Development Tools, Libraries, and Frameworks Cheatsheet

  • Description: The official documentation for the Ethereum blockchain, covering topics from basics to advanced development.
  • Key Features:
  • Comprehensive guides on setting up development environments.
  • Tutorials on smart contract development and DApp creation.
  • Detailed explanations of Ethereum concepts and protocols.
  • Regularly updated with the latest information.
  • Website: Ethereum Documentation
  • Description: The official documentation for OpenZeppelin’s smart contract libraries and tools.
  • Key Features:
  • Guides on using OpenZeppelin Contracts, SDK, and Defender.
  • Best practices for secure smart contract development.
  • Tutorials on integrating OpenZeppelin tools with DApps.
  • Regularly updated with the latest security features.
  • Website: OpenZeppelin Documentation

Aug 23, 2024
Read More
Tutorial
solidity

Writing an ERC-20 Token Contract with OpenZeppelin

  • ERC20: Inherits from the OpenZeppelin ERC20 contract, which implements the standard ERC-20 functions and events.
  • Ownable: Provides basic authorization control, allowing the contract owner to perform restricted actions.
  • Constructor: Initializes the token with a name, symbol, and initial supply, which is minted to the contract creator’s address.
  • Mint Function: Allows the contract owner to mint new tokens to a specified address.
  • Burn Function: Allows token holders to destroy (burn) their tokens, reducing the total supply.

Next, you need to compile your contract to ensure there are no errors.

Aug 22, 2024
Read More
Cheatsheet
solidity

Solidity Cheatsheet

- uint: Unsigned integers (e.g., uint256, uint128)

- address: Holds a 20-byte Ethereum address

Aug 22, 2024
Read More
Tutorial
solidity

Understanding Gas and Optimization in Smart Contracts

Gas is a fundamental concept in the Ethereum blockchain, serving as the unit that measures the computational work required to execute operations in smart contracts. Every transaction or operation on Ethereum consumes gas, and users must pay for it with Ether (ETH). Understanding how gas works and optimizing your smart contracts to minimize gas consumption is crucial for developing cost-effective and efficient decentralized applications (DApps). This tutorial will guide you through the essentials of gas in Ethereum, strategies for gas optimization, and best practices for writing efficient smart contracts.

Gas is the measure of computational effort required to execute operations on the Ethereum network. Each operation, from simple arithmetic to complex smart contract execution, consumes a specific amount of gas. Users must pay for gas in Ether, which compensates miners for the resources required to process and validate transactions.

Aug 22, 2024
Read More
Tutorial
solidity

Building a Decentralized Application (DApp) with Smart Contracts

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract MessageStore {
    string public message;

    function setMessage(string memory newMessage) public {
        message = newMessage;
    }

    function getMessage() public view returns (string memory) {
        return message;
    }
}

Explanation:

Aug 22, 2024
Read More
Tutorial
solidity

Introduction to Smart Contracts on Ethereum

Writing smart contracts requires attention to detail, especially when it comes to security and efficiency. Here are some best practices:

  • Avoid Overflow/Underflow: Use Solidity’s SafeMath library to prevent arithmetic overflow and underflow.
  • Use Modifiers for Access Control: Restrict who can execute certain functions using modifiers like onlyOwner.
  • Gas Optimization: Write efficient code to minimize gas costs. Avoid unnecessary computations and storage operations.
  • Audit and Test: Thoroughly test your contract and consider an external audit before deploying on the mainnet.

Aug 22, 2024
Read More
Cheatsheet

Comprehensive React Libraries Cheatsheet

No preview available for this content.

Aug 21, 2024
Read More
Tutorial
javascript solidity

Creating a Decentralized Application (dApp) with Solidity, Ethereum, and IPFS: From Smart Contracts to Front-End

The rise of blockchain technology has led to the development of decentralized applications (dApps), which operate on a peer-to-peer network rather than relying on centralized servers. dApps provide increased security, transparency, and resistance to censorship. In this tutorial, we'll walk through the process of building a dApp using Solidity, Ethereum, and IPFS. We’ll cover everything from writing smart contracts to deploying them on the Ethereum blockchain, and then integrating them with a front-end built with modern web technologies.

To start, ensure you have Node.js and npm installed on your machine. You can download them from the Node.js website.

Aug 20, 2024
Read More
Tutorial
javascript nodejs

Building a React Application with Vite and Tailwind CSS

This will generate a dist directory with your optimized application.

You've successfully set up a modern React application using Vite and Tailwind CSS! This setup provides a fast and efficient development environment with powerful styling capabilities. From here, you can expand your project with additional components, routing, state management, and more.

Aug 14, 2024
Read More
Tutorial
python

Advanced Pybit Tutorial: Managing Leverage, Stop-Loss Orders, Webhooks, and More

A stop-loss order helps limit potential losses by automatically closing a position at a specified price level.

You can set a stop-loss order when opening a position or on an existing position:

Aug 14, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!