DeveloperBreeze

In this tutorial, you will learn how to use Ethers.js and the Etherscan API to query ERC-20 token balances and view token transaction history for a specific Ethereum address. ERC-20 tokens are a standard for fungible tokens on the Ethereum blockchain, and querying their balances and transactions is essential for building decentralized applications (dApps) like wallets, token explorers, and DeFi platforms.

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.

Prerequisites

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

  • Node.js installed on your machine.
  • A basic understanding of JavaScript.
  • An Etherscan API key (explained below).
  • Familiarity with Ethers.js for blockchain interaction.

Step 1: Set Up Etherscan and Get an API Key

To use the Etherscan API, you’ll need to get an API key. Here’s how:

  1. Go to Etherscan’s website.
  2. Sign up for a free account (or log in if you already have one).
  3. Navigate to the API Keys section and generate a new API key.
  4. Copy your API key — you’ll use this key to interact with the Etherscan API.

Step 2: Install Ethers.js and Axios

We will use Ethers.js to interact with the Ethereum blockchain and Axios to make HTTP requests to the Etherscan API.

  1. Navigate to your project folder and run the following commands to install Ethers.js and Axios:
npm install ethers
npm install axios

Step 3: Query ERC-20 Token Balance Using Ethers.js

In this step, we will use Ethers.js to query the balance of an ERC-20 token for a specific Ethereum address.

  1. Create a new file called getTokenBalance.js in your project folder.
  2. Add the following code to query the token balance:
const ethers = require('ethers');

// Replace with your Infura or other Ethereum node provider URL
const provider = new ethers.JsonRpcProvider('https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID');

// Replace with the ERC-20 token contract address (e.g., USDT, DAI)
const contractAddress = '0xTokenContractAddress';

// Replace with the wallet address you want to query
const walletAddress = '0xYourEthereumAddress';

// ERC-20 token ABI (just the balanceOf function)
const abi = [
    'function balanceOf(address owner) view returns (uint256)'
];

// Create a contract instance
const contract = new ethers.Contract(contractAddress, abi, provider);

async function getTokenBalance() {
    try {
        // Query the balance
        const balance = await contract.balanceOf(walletAddress);

        // Convert balance to a human-readable format (tokens usually have 18 decimals)
        const formattedBalance = ethers.utils.formatUnits(balance, 18);

        console.log(`Token Balance: ${formattedBalance}`);
    } catch (error) {
        console.error('Error fetching token balance:', error);
    }
}

// Call the function to get the token balance
getTokenBalance();

Explanation:

  • Contract Address: Replace '0xTokenContractAddress' with the address of the ERC-20 token (e.g., USDT, DAI, or any other ERC-20 token).
  • Wallet Address: Replace '0xYourEthereumAddress' with the wallet address whose token balance you want to query.
  • ABI: We are using a minimal ABI with just the balanceOf function, which is all that’s required to query the token balance.

Running the Script:

Once you’ve added the code, run the script:

node getTokenBalance.js

You should see the token balance printed in the console, in a human-readable format (typically with 18 decimals for ERC-20 tokens).


Step 4: Query ERC-20 Token Transfer History Using Etherscan API

Now let’s query the ERC-20 token transfer history for a specific wallet address using the Etherscan API.

  1. Create a new file called getTokenTransactions.js.
  2. Add the following code to query the token transaction history:
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();

Explanation:

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

Running the Script:

Once you’ve added the code, run the script:

node getTokenTransactions.js

You should see a list of token transactions for the specified address, with details including the sender, recipient, value transferred, and transaction hash.


Step 5: Customizing the API Request

You can customize the Etherscan API request to suit your needs. Here are a few options:

  • Start and End Block: Adjust the startblock and endblock parameters to limit the range of blocks you want to query.
  • Sort: Set the sort parameter to asc (ascending) or desc (descending) to control the order of the transactions.
  • Token Transfers for All Tokens: You can modify the API call to query all token transfers for an address, not just a specific token contract, by omitting the contractaddress parameter.

Conclusion

In this tutorial, you learned how to use Ethers.js to query ERC-20 token balances and how to leverage the Etherscan API to retrieve token transaction histories. These are essential techniques for building decentralized applications, wallets, or blockchain explorers that interact with ERC-20 tokens on the Ethereum network.

You now have the tools to query token balances and transaction histories programmatically, enabling you to create powerful blockchain-based applications.


Continue Reading

Discover more amazing content handpicked just for you

Tutorial

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

  • crypto.randomBytes:
  • Library: crypto.randomBytes is part of Node.js’s built-in crypto module. It requires no additional dependencies and is readily available in any Node.js environment.
  • Usage: The function takes a single argument specifying the number of bytes to generate and returns a Buffer object containing the random bytes.
  • Example:
    const crypto = require('crypto');
    const randomBytes = crypto.randomBytes(32);
    console.log(randomBytes.toString('hex')); // Prints a 32-byte random hex string

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

In this tutorial, we will walk through how to use Ethers.js along with Infura to send Ethereum transactions and interact with smart contracts. Infura provides scalable access to Ethereum nodes, allowing you to interact with the blockchain in real-time without running your own node.

By the end of this tutorial, you will be able to send Ether, call smart contract functions, and deploy contracts using Infura as your provider.

Oct 24, 2024
Read More
Tutorial

Understanding and Using the Etherscan API to Query Blockchain Data

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

Oct 24, 2024
Read More
Tutorial

Getting Wallet Balance Using Ethers.js in Node.js

First, you need to install Ethers.js, a library for interacting with the Ethereum blockchain.

Run the following command in your project folder to install it:

Oct 24, 2024
Read More
Tutorial

Understanding 0x000000000000000000000000000000000000dead Address and Token Burns in Ethereum

The "0x000000000000000000000000000000000000dead" address plays a vital role in the cryptocurrency ecosystem, acting as a black hole for tokens that need to be permanently removed from circulation. Token burns, when done responsibly, can reduce supply, increase scarcity, and potentially drive up the value of a cryptocurrency. However, it’s important to understand the potential risks and long-term impacts of token burns before making investment decisions based on burn events.

Oct 24, 2024
Read More
Tutorial

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

Example on a DEX like Uniswap:

  • Users can simply exchange ETH for WETH by interacting with the platform's smart contract, which handles the wrapping/unwrapping process automatically.

Oct 24, 2024
Read More
Cheatsheet
solidity

Blockchain Libraries Cheatsheet

  • Description: A library of reusable and secure smart contract components, adhering to the latest Ethereum standards.
  • Use Cases:
  • Implement ERC-20, ERC-721, and ERC-1155 tokens.
  • Use access control patterns like Ownable and Role-Based Access Control.
  • Implement secure and efficient upgradeable contracts.
  • Manage governance, staking, and more with pre-built modules.
  • Key Features:
  • Security-focused implementations.
  • Regular updates following best practices.
  • Easy integration with any Solidity project.
  • Installation:
  npm install @openzeppelin/contracts

Aug 23, 2024
Read More
Cheatsheet
solidity

Blockchain Development Tools, Libraries, and Frameworks Cheatsheet

  • Description: A library of secure and community-vetted smart contracts for Ethereum development.
  • Key Features:
  • Prebuilt, secure implementations of ERC-20, ERC-721, and ERC-1155 tokens.
  • Reusable components for access control, governance, and more.
  • Highly customizable and extensible.
  • Regularly updated with best practices for security and gas efficiency.
  • Website: OpenZeppelin Contracts
  • Description: The main programming language for writing smart contracts on Ethereum.
  • Key Features:
  • Statically-typed language designed for the Ethereum Virtual Machine (EVM).
  • Supports inheritance, libraries, and user-defined types.
  • Extensive support for complex data types like structs and mappings.
  • Integrated development environment support in Remix, Truffle, and Hardhat.
  • Website: Solidity

Aug 23, 2024
Read More
Tutorial
solidity

Writing an ERC-20 Token Contract with OpenZeppelin

  • Open the Hardhat console:
     npx hardhat console --network localhost

Aug 22, 2024
Read More
Cheatsheet
solidity

Solidity Cheatsheet

uint public myVariable;
address private owner;
bool internal isActive;

uint constant MY_CONSTANT = 10;
address immutable MY_ADDRESS = msg.sender;

  • Function Modifiers:

Aug 22, 2024
Read More
Tutorial
solidity

Understanding Gas and Optimization in Smart Contracts

  • Prevents Abuse: By charging for computational resources, Ethereum discourages spam and abuse on the network.
  • Incentivizes Efficiency: Developers are motivated to write optimized code to minimize gas costs.

Different operations in a smart contract consume different amounts of gas. Simple operations like adding two numbers are inexpensive, while more complex operations like loops or external contract calls can be costly. It’s important to understand how various Solidity operations consume gas.

Aug 22, 2024
Read More
Tutorial
solidity

Building a Decentralized Application (DApp) with Smart Contracts

Each of these use cases can be built on the same principles you learned in this tutorial but with more complex logic and integrations.

In this tutorial, we covered the basics of building a decentralized application (DApp) with smart contracts on the Ethereum blockchain. You learned how to set up a development environment, write and deploy a smart contract, and create a front-end interface to interact with it. This DApp is just the beginning—there's much more to explore in the world of decentralized applications, from scaling solutions to integrating with off-chain data sources.

Aug 22, 2024
Read More
Tutorial
solidity

Introduction to Smart Contracts on Ethereum

  • Switch to the "Deploy & Run Transactions" tab.
  • Select "Injected Web3" as the environment to connect to MetaMask.
  • Choose a test network like Ropsten or Kovan in MetaMask.
  • Click "Deploy" and confirm the transaction in MetaMask.
  • Once deployed, the contract will appear in the "Deployed Contracts" section.
  • You can now call the set and get functions to interact with your contract.

Aug 22, 2024
Read More
Tutorial
javascript solidity

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

To deploy your smart contract to the Ethereum mainnet, you’ll need to configure Truffle to connect to an Ethereum node (e.g., Infura) and provide a wallet with Ether to pay for gas.

Update truffle-config.js with the necessary configurations and deploy:

Aug 20, 2024
Read More
Tutorial
python

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

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

   def get_open_positions(symbol):
       response = session.my_position(symbol=symbol)
       if response['ret_code'] == 0:
           positions = response['result']
           print(f"Open positions for {symbol}: {positions}")
       else:
           print(f"Error fetching positions: {response['ret_msg']}")
       return positions

   get_open_positions('BTCUSD')

Aug 14, 2024
Read More
Tutorial
python

A Beginner's Guide to Pybit: Interacting with the Bybit API

In the rapidly evolving world of cryptocurrency trading, accessing and interacting with exchange APIs is essential for automated trading and data analysis. Pybit is a Python wrapper for the Bybit API, making it easier to access and interact with Bybit's functionalities using Python. In this tutorial, we'll walk you through the basics of setting up Pybit, fetching market data, and executing trades.

  • Basic knowledge of Python.
  • A Bybit account.
  • Installed Python packages: pybit, requests.

Aug 14, 2024
Read More
Tutorial
javascript nodejs

Tracking Solana Address for New Trades and Amounts

Step 1: Set Up Your Project

   mkdir solana-address-tracker
   cd solana-address-tracker

Aug 09, 2024
Read More
Tutorial
javascript nodejs

Tracking Newly Created Tokens on Solana

   mkdir solana-token-tracker
   cd solana-token-tracker
   npm init -y

Aug 09, 2024
Read More
Tutorial
javascript nodejs

Tracking Newly Created Tokens on Ethereum

Introduction

In this tutorial, we will learn how to track newly created tokens on the Ethereum blockchain. With the rapid growth of decentralized finance (DeFi) and non-fungible tokens (NFTs), keeping an eye on newly created tokens can be valuable for investors, developers, and enthusiasts. We will use Etherscan's API to monitor token creation events and Web3.js to interact with the Ethereum network.

Aug 09, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!