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

When developing cryptographic applications in JavaScript, one common requirement is the generation of cryptographically secure random bytes. Two popular methods for doing this are crypto.randomBytes from Node.js's built-in crypto module, and ethers.randomBytes from the ethers.js library, which is often used for Ethereum-related operations. Both functions serve the same purpose, but they have some key differences. Let’s explore these two methods in detail.

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

Oct 24, 2024
Read More
Tutorial

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

Use Infura when you need to interact with the Ethereum blockchain in real-time. Infura allows you to send transactions, deploy contracts, and interact with smart contracts. It is essential for decentralized applications (dApps) and any use case where you need to write to the blockchain.

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 {
    const tx = {
      to: recipientAddress,
      value: ethers.utils.parseEther(amountInEther),
      gasLimit: 21000, // Gas limit for a basic transaction
      gasPrice: await infuraProvider.getGasPrice() // Get current gas price from Infura
    };

    // Send the transaction
    const transaction = await wallet.sendTransaction(tx);
    console.log('Transaction Hash:', 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);
  }
}

sendTransaction();

Oct 24, 2024
Read More
Tutorial

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

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.

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

Oct 24, 2024
Read More
Tutorial

Understanding and Using the Etherscan API to Query Blockchain Data

node etherscanBalance.js

If everything is set up correctly, you’ll see an output like this:

Oct 24, 2024
Read More
Tutorial

Getting Wallet Balance Using Ethers.js in Node.js

To follow along, you’ll need the following:

  • Node.js installed on your machine.
  • Basic understanding of JavaScript.
  • An Ethereum wallet (with private key or mnemonic phrase).
  • (Optional) An Infura account to access the Ethereum network.

Oct 24, 2024
Read More
Tutorial

Understanding 0x000000000000000000000000000000000000dead Address and Token Burns in Ethereum

Many projects use token burns strategically, announcing burn events in advance to generate interest in the project and potentially boost the value of the remaining tokens.

Although token burns can increase the scarcity of a token, they are not without risk:

Oct 24, 2024
Read More
Tutorial

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

  • Users can simply exchange ETH for WETH by interacting with the platform's smart contract, which handles the wrapping/unwrapping process automatically.
  • 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.

Oct 24, 2024
Read More
Cheatsheet
solidity

Blockchain Libraries Cheatsheet

  npm install bitcore-lib

Aug 23, 2024
Read More
Cheatsheet
solidity

Blockchain Development Tools, Libraries, and Frameworks Cheatsheet

  • Description: A flexible and extensible development environment for Ethereum, designed to manage and automate tasks like contract compilation and deployment.
  • Key Features:
  • Local Ethereum network for testing (Hardhat Network).
  • Easy integration with popular tools like Ethers.js and Waffle.
  • Plugins for Solidity coverage, gas reporting, and more.
  • Error messages and stack traces specific to Solidity.
  • Highly customizable and scriptable.
  • Website: Hardhat
  • Description: A framework for Ethereum DApp development that integrates with IPFS, Swarm, Whisper, and other decentralized technologies.
  • Key Features:
  • Integrated with Web3.js, IPFS, Swarm, and Whisper.
  • Supports multiple blockchain environments.
  • Real-time deployment to IPFS or Swarm.
  • Automated contract testing and deployment.
  • Supports integration with legacy systems.
  • Website: Embark

Aug 23, 2024
Read More
Tutorial
solidity

Writing an ERC-20 Token Contract with OpenZeppelin

  • In the scripts directory, create a new file called deploy.js:
     touch scripts/deploy.js

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

  • Optimization: Gnosis Safe optimized their contract by minimizing storage writes and using efficient data structures like mappings and structs.
  • Impact: These optimizations reduced the gas cost for executing multi-signature transactions, making the platform more accessible.

Understanding gas and optimizing its consumption in smart contracts is crucial for developing cost-effective and efficient decentralized applications. By implementing strategies such as minimizing storage writes, using view and pure functions, optimizing loops, and leveraging efficient data structures, you can significantly reduce the gas costs associated with your smart contracts.

Aug 22, 2024
Read More
Tutorial
solidity

Building a Decentralized Application (DApp) with Smart Contracts

Decentralized applications (DApps) represent the future of software, leveraging blockchain technology to create applications that are transparent, secure, and free from centralized control. By combining smart contracts with a user interface, DApps offer a new way to interact with blockchain technology. In this tutorial, we will guide you through the process of building a DApp on the Ethereum blockchain. You’ll learn how to create a simple DApp, connect it to a smart contract, and deploy it on a test network.

A decentralized application (DApp) is an application that runs on a peer-to-peer network, like a blockchain, rather than relying on a single centralized server. DApps are open-source, operate autonomously, and the data is stored on the blockchain, making them transparent and resistant to censorship.

Aug 22, 2024
Read More
Tutorial
solidity

Introduction to Smart Contracts on Ethereum

  • Set a Value: Use the set function to store a number in the contract.
  • Get the Value: Use the get function to retrieve the stored number.

You’ll notice that calling the set function will require gas (a small amount of Ether) to execute, whereas calling the get function is free as it’s a view function.

Aug 22, 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
python

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

   from flask import Flask, request, jsonify

   app = Flask(__name__)

   @app.route('/webhook', methods=['POST'])
   def webhook():
       data = request.json
       print(f"Webhook received: {data}")
       # Process the data as needed
       return jsonify({'status': 'success'}), 200

   if __name__ == '__main__':
       app.run(port=5000)

This Flask app listens for POST requests on /webhook and prints the received data. You can expand this to handle specific webhook events like order fills, price alerts, etc.

Aug 14, 2024
Read More
Tutorial
python

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

The following function places a limit order to buy 0.01 BTC at $30,000:

   def place_limit_order(symbol, side, qty, price):
       response = session.place_active_order(
           symbol=symbol,
           side=side,
           order_type='Limit',
           qty=qty,
           price=price,
           time_in_force='GoodTillCancel'
       )
       return response

   order_response = place_limit_order('BTCUSD', 'Buy', 0.01, 30000)
   print("Order Response:", order_response)

Aug 14, 2024
Read More
Tutorial
javascript nodejs

Tracking Solana Address for New Trades and Amounts

We'll now write a function to track a specific Solana address and log new trades:

async function trackAddress(address) {
  try {
    const publicKey = new solanaWeb3.PublicKey(address);

    console.log(`Tracking address: ${publicKey.toBase58()}`);

    let lastSignature = '';

    // Fetch initial transactions
    const signatures = await connection.getSignaturesForAddress(publicKey, { limit: 1 });
    if (signatures.length > 0) {
      lastSignature = signatures[0].signature;
    }

    // Monitor for new transactions
    setInterval(async () => {
      const signatures = await connection.getSignaturesForAddress(publicKey, {
        limit: 10,
      });

      for (const signatureInfo of signatures) {
        if (signatureInfo.signature !== lastSignature) {
          const transaction = await connection.getConfirmedTransaction(signatureInfo.signature);

          if (transaction) {
            const { meta, transaction: tx } = transaction;

            const instructions = tx.message.instructions;
            const postBalances = meta.postBalances;
            const preBalances = meta.preBalances;

            // Check if the transaction involves token transfers
            instructions.forEach((instruction, index) => {
              const programId = instruction.programId.toBase58();

              // Solana's SPL Token Program ID
              if (programId === solanaWeb3.TOKEN_PROGRAM_ID.toBase58()) {
                const data = Buffer.from(instruction.data);
                const command = data.readUInt8(0);

                // 3 represents the Token Transfer instruction
                if (command === 3) {
                  const amount = data.readUInt64LE(1);
                  const fromAccount = instruction.keys[0].pubkey.toBase58();
                  const toAccount = instruction.keys[1].pubkey.toBase58();

                  const balanceChange = (preBalances[index] - postBalances[index]) / solanaWeb3.LAMPORTS_PER_SOL;

                  console.log(`New Trade Detected!`);
                  console.log(`- Signature: ${signatureInfo.signature}`);
                  console.log(`- From: ${fromAccount}`);
                  console.log(`- To: ${toAccount}`);
                  console.log(`- Amount: ${balanceChange} SOL`);
                }
              }
            });
          }

          lastSignature = signatureInfo.signature;
        }
      }
    }, 10000); // Check every 10 seconds
  } catch (error) {
    console.error('Error tracking address:', error);
  }
}

// Replace with the Solana address you want to track
const addressToTrack = 'YourSolanaAddressHere';
trackAddress(addressToTrack);

Aug 09, 2024
Read More
Tutorial
javascript nodejs

Tracking Newly Created Tokens on Solana

You can run this script periodically to monitor for new token creation events. Consider setting up a cron job or a scheduled task to execute the script at regular intervals.

node index.js

Aug 09, 2024
Read More
Tutorial
javascript nodejs

Tracking Newly Created Tokens on Ethereum

Step 1: Set Up Your Project

   mkdir ethereum-token-tracker
   cd ethereum-token-tracker

Aug 09, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!