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

Ensure you have a Laravel project set up. You can create a new Laravel project by running:

composer create-project --prefer-dist laravel/laravel example-app

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

  • 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.
  • Rate Limits: Infura’s free tier provides a generous number of requests (e.g., 100,000 requests per day) and supports more requests as you scale. This makes it more suitable for real-time dApps.
  • Pricing: Infura’s paid plans offer higher limits and additional features like access to Layer 2 networks.

Oct 24, 2024
Read More
Tutorial

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

Let’s start by sending Ether from one account to another using Ethers.js and Infura.

const ethers = require('ethers');

// Replace with your Infura Project ID
const infuraProvider = new ethers.JsonRpcProvider('https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID');

// Replace with your wallet's private key
const privateKey = 'YOUR_PRIVATE_KEY';

// Create a wallet instance and connect it to Infura
const wallet = new ethers.Wallet(privateKey, infuraProvider);

// Replace with the recipient's Ethereum address
const recipientAddress = '0xRecipientEthereumAddress';

// Amount to send (in Ether)
const amountInEther = '0.01';

async function sendTransaction() {
    try {
        // Convert Ether to Wei (the smallest unit of Ether)
        const amountInWei = ethers.utils.parseEther(amountInEther);

        // Create the transaction
        const tx = {
            to: recipientAddress,
            value: amountInWei,
            gasLimit: ethers.utils.hexlify(21000), // Gas limit for basic transactions
            gasPrice: await infuraProvider.getGasPrice() // Get current gas price from Infura
        };

        // Send the transaction
        const transaction = await wallet.sendTransaction(tx);

        console.log('Transaction sent:', transaction.hash);

        // Wait for the transaction to be mined
        const receipt = await transaction.wait();
        console.log('Transaction confirmed:', receipt);
    } catch (error) {
        console.error('Error sending transaction:', error);
    }
}

// Call the function to send the transaction
sendTransaction();

Oct 24, 2024
Read More
Tutorial

Getting Wallet Balance Using Ethers.js in Node.js

In this tutorial, you learned how to use Ethers.js to query the balance of an Ethereum wallet in Node.js. You also saw how to use Infura or connect to a public node to access the Ethereum network. This is the foundation for working with Ethereum and interacting with wallets and smart contracts in a programmatic way.

By connecting to the Ethereum network and querying wallet balances, you now have a powerful tool for building decentralized applications (dApps) and automating blockchain-related tasks.

Oct 24, 2024
Read More
Tutorial

Understanding 0x000000000000000000000000000000000000dead Address and Token Burns in Ethereum

For example, in token burn events, project developers often send tokens to this address to signal to the community that those tokens are now out of circulation. This is usually followed by a public announcement, detailing the number of tokens burned and the reasons behind the burn.

Token burns are typically done to increase scarcity, and scarcity can lead to a higher token value if demand remains the same or increases. The basic principle of supply and demand comes into play: when the supply of an asset is reduced, it becomes more valuable (assuming demand holds steady).

Oct 24, 2024
Read More
Tutorial

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

  • Decentralized Exchanges (DEXs): Many decentralized exchanges (like Uniswap) require ERC-20 tokens for trading. WETH allows ETH holders to trade ETH just like any other ERC-20 token.
  • DeFi Lending Platforms: Platforms such as Aave or Compound often require collateral in the form of ERC-20 tokens, making WETH essential for ETH holders who want to participate.
  • Token Swaps: WETH allows for seamless token swaps between ETH and other ERC-20 tokens on platforms that support such swaps.

ETH and WETH serve different but complementary roles in the Ethereum ecosystem. While ETH is the native currency used to power the network, WETH enables ETH to interact with the growing number of decentralized applications and DeFi protocols that rely on the ERC-20 standard. By understanding how to wrap and unwrap ETH, you can effectively engage in the broader Ethereum DeFi ecosystem without leaving the native ETH environment.

Oct 24, 2024
Read More
Tutorial
javascript python

How to Build a Fullstack App with Flask and React

Visit http://127.0.0.1:5000/ in your browser. You should see:

{"message": "Welcome to the Task Manager API!"}

Sep 30, 2024
Read More
Tutorial
javascript

Getting Started with Axios in JavaScript

axios.all([
    axios.get('https://jsonplaceholder.typicode.com/posts/1'),
    axios.get('https://jsonplaceholder.typicode.com/posts/2')
  ])
  .then(axios.spread((post1, post2) => {
    console.log('Post 1:', post1.data);
    console.log('Post 2:', post2.data);
  }))
  .catch(error => {
    console.error('Error fetching data:', error);
  });
  • We use axios.all() to send multiple requests.
  • The axios.spread() function is used to handle the responses separately.

Sep 02, 2024
Read More
Cheatsheet
solidity

Blockchain Development Tools, Libraries, and Frameworks Cheatsheet

  • Description: The most popular Ethereum block explorer and analytics platform.
  • Key Features:
  • Allows users to explore blocks, transactions, and token transfers.
  • Provides detailed information on smart contracts and token contracts.
  • Offers API services for integrating blockchain data into applications.
  • Supports Ethereum mainnet and testnets.
  • Website: Etherscan
  • Description: A universal blockchain explorer and analytics platform for multiple cryptocurrencies.
  • Key Features:
  • Supports Ethereum, Bitcoin, and other major blockchains.
  • Provides advanced search and analytics features.
  • Allows users to explore transactions, addresses, and blocks.
  • Offers an API for integrating blockchain data into applications.
  • Website: Blockchair

Aug 23, 2024
Read More
Tutorial
solidity

Writing an ERC-20 Token Contract with OpenZeppelin

  • Open a terminal and create a new directory for your project:
     mkdir my-token
     cd my-token

Aug 22, 2024
Read More
Cheatsheet
solidity

Solidity Cheatsheet

Fallback and receive functions handle direct payments to contracts.

  • Fallback: Called when no other function matches or if no data is provided.

Aug 22, 2024
Read More
Tutorial
solidity

Understanding Gas and Optimization in Smart Contracts

3. Optimize Loops

  • Loops can be costly, especially if they iterate over large datasets. Limit the number of iterations or consider splitting loops into multiple transactions if possible.
  • Example: Avoid looping over large arrays or mappings within a single transaction.

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

Key Features:

  • Decentralized: Operates on the blockchain, not controlled by any single entity.
  • Trustless: Executes automatically when conditions are met, without requiring trust between parties.
  • Immutable: Once deployed, the contract's code cannot be changed, ensuring the terms are fixed.

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

This contract stores a message on the blockchain and allows users to update and retrieve it. It also emits an event whenever the message is changed.

Compile the contract using Truffle:

Aug 20, 2024
Read More
Tutorial
javascript nodejs

Building a React Application with Vite and Tailwind CSS

module.exports = {
  content: [
    "./index.html",
    "./src/**/*.{js,jsx,ts,tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}

In your src directory, open the index.css file (or create one if it doesn't exist) and add the following lines:

Aug 14, 2024
Read More
Tutorial
python

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

Monitoring open positions is essential for active traders to manage their portfolio and respond to market changes.

The following function fetches open positions for a specific trading pair:

Aug 14, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!