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

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

Make sure to have php and composer installed on your machine.

Oct 24, 2024
Read More
Tutorial

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

    const { ethers } = require('ethers');
    const randomBytes = ethers.utils.randomBytes(32);
    console.log(randomBytes); // Uint8Array of random bytes
  • crypto.randomBytes is part of Node.js, so it requires no external dependencies. This makes it ideal for Node.js environments where minimal dependencies are desired.
  • ethers.randomBytes requires the installation of the ethers.js library, which is primarily designed for blockchain-related projects. This is useful if you're already working with Ethereum, but it adds an external dependency to the project.

Oct 24, 2024
Read More
Tutorial

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

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.

Oct 24, 2024
Read More
Tutorial

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

  • API: This script uses Infura’s node access and Ethers.js to send Ether in real-time.
  • Use Case: Essential for dApps, wallets, or any application needing to send transactions or interact with the blockchain live.
  • 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.

Oct 24, 2024
Read More
Tutorial

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

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();
  • Infura Provider: You connect to the Ethereum network using the Infura provider (infuraProvider), which allows you to interact with Ethereum nodes.
  • Private Key: Replace 'YOUR_PRIVATE_KEY' with your Ethereum wallet’s private key (keep it secure).
  • Recipient Address: Replace '0xRecipientEthereumAddress' with the Ethereum address you want to send Ether to.
  • Gas and Fees: The gasLimit and gasPrice fields are required for sending transactions. The getGasPrice function retrieves the current gas price from the Infura node.

Oct 24, 2024
Read More
Tutorial

Getting Wallet Balance Using Ethers.js in Node.js

In this tutorial, you will learn how to retrieve the balance of an Ethereum wallet using Ethers.js in a Node.js environment. We will cover two methods:

By the end of this tutorial, you’ll be able to query the balance of any Ethereum wallet and display it in Ether units.

Oct 24, 2024
Read More
Tutorial

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

WETH is simply ETH wrapped in a smart contract to make it compatible with the ERC-20 token standard. Wrapping ETH into WETH enables users to interact with decentralized applications (dApps), decentralized exchanges (DEXs), and DeFi platforms that require ERC-20 tokens.

  • ETH: The native asset of Ethereum, does not conform to any token standard.
  • WETH: An ERC-20 token, designed to work seamlessly with Ethereum-based DeFi applications and smart contracts.

Oct 24, 2024
Read More
Tutorial
javascript python

How to Build a Fullstack App with Flask and React

In the frontend/src/ directory, modify App.js to call the Flask API and display the message:

import React, { useEffect, useState } from 'react';
import axios from 'axios';

function App() {
  const [message, setMessage] = useState('');

  useEffect(() => {
    // Fetch data from the Flask API
    axios.get('http://127.0.0.1:5000/')
      .then(response => setMessage(response.data.message))
      .catch(error => console.log(error));
  }, []);

  return (
    <div className="App">
      <h1>{message}</h1>
    </div>
  );
}

export default App;

Sep 30, 2024
Read More
Tutorial
javascript

Getting Started with Axios in JavaScript

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

Let's start by making a simple GET request to a public API using 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

  • 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

  • Function Modifiers:

- view: Indicates that the function does not modify the state.

Aug 22, 2024
Read More
Tutorial
solidity

Understanding Gas and Optimization in Smart Contracts

1. Minimize Storage Writes

  • Writing data to the blockchain is one of the most expensive operations. Whenever possible, minimize storage writes or combine them into a single operation.
  • Example: Instead of updating multiple state variables individually, group them into a struct and update the struct in a single operation.

Aug 22, 2024
Read More
Tutorial
solidity

Building a Decentralized Application (DApp) with Smart Contracts

  • Start Ganache and configure Truffle to use it by editing the truffle-config.js file.
  • Run truffle migrate to deploy the smart contract to the local blockchain provided by Ganache.

Now that the smart contract is deployed, let’s create a front-end interface to interact with it. We’ll use HTML, JavaScript, and Web3.js to build a simple web page that allows users to set and retrieve the message stored in the contract.

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

React's ecosystem is vast, with a multitude of libraries that enhance its functionality and simplify development tasks. This cheatsheet covers a wide array of React libraries, organized by category, with brief descriptions of each. These libraries can help you build robust, maintainable, and efficient React applications.

This cheatsheet offers a broad overview of the most widely-used libraries in the React ecosystem. These libraries cover various aspects of React development, from state management and UI components to testing and animations, helping you build robust and maintainable applications. Whether you're a beginner or an experienced developer, integrating these tools into your workflow can significantly enhance your productivity and the quality of your React projects.

Aug 21, 2024
Read More
Tutorial
javascript solidity

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

truffle migrate --network mainnet

You can host your front-end on a decentralized platform like Fleek or Netlify for broader access.

Aug 20, 2024
Read More
Tutorial
javascript nodejs

Building a React Application with Vite and Tailwind CSS

npm install

Install Tailwind CSS and its peer dependencies:

Aug 14, 2024
Read More
Tutorial
python

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

Managing open orders and closing positions is essential for effective trading. Pybit makes it straightforward to close orders.

Use the following function to close an open order:

Aug 14, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!