DeveloperBreeze

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.

Prerequisites

  • Node.js and npm installed on your system.
  • Basic knowledge of JavaScript and Ethereum.
  • An Etherscan API key (you can obtain one by signing up on Etherscan).

Step 1: Set Up Your Project

  1. Create a new project directory:
   mkdir ethereum-token-tracker
   cd ethereum-token-tracker
  1. Initialize a new Node.js project:
   npm init -y
  1. Install the necessary libraries:
   npm install web3 axios

Step 2: Connect to the Ethereum Network

Create a new file called index.js and add the following code to connect to the Ethereum blockchain:

const Web3 = require('web3');

// Connect to an Ethereum node using Infura
const web3 = new Web3('https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID');

console.log('Connected to Ethereum Mainnet');

Replace YOUR_INFURA_PROJECT_ID with your Infura project ID. You can sign up for a free Infura account and create a project to get the project ID.

Step 3: Fetch Newly Created Tokens

We will use Etherscan's API to fetch information about newly created tokens. Add the following function to your index.js file:

const axios = require('axios');

// Replace with your Etherscan API key
const ETHERSCAN_API_KEY = 'YOUR_ETHERSCAN_API_KEY';

async function getNewTokens() {
  try {
    const url = `https://api.etherscan.io/api?module=account&action=tokentx&address=0x0&startblock=0&endblock=99999999&sort=asc&apikey=${ETHERSCAN_API_KEY}`;
    const response = await axios.get(url);

    if (response.data.status === '1') {
      const transactions = response.data.result;
      const newTokens = transactions.filter(tx => tx.tokenSymbol && tx.tokenName && tx.from === '0x0000000000000000000000000000000000000000');

      console.log('Newly Created Tokens:');
      newTokens.forEach(token => {
        console.log(`- Token Name: ${token.tokenName}`);
        console.log(`  Token Symbol: ${token.tokenSymbol}`);
        console.log(`  Token Contract Address: ${token.contractAddress}`);
      });
    } else {
      console.error('Error fetching token transactions:', response.data.message);
    }
  } catch (error) {
    console.error('Error:', error);
  }
}

getNewTokens();

Explanation

  • Etherscan API: We use the tokentx action from Etherscan's API to fetch token transfer events. The API returns a list of token transactions, including newly created tokens.
  • Filter for New Tokens: We filter transactions where the from address is 0x0000000000000000000000000000000000000000, indicating a token creation event. This address is used as a placeholder for the "zero address" in token contracts.
  • Display Information: We log the name, symbol, and contract address of each newly created token.

Step 4: Monitor for New Tokens

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

Conclusion

In this tutorial, we explored how to track newly created tokens on the Ethereum blockchain using Etherscan's API and Web3.js. This approach provides a simple yet effective way to monitor token creation events, which can be useful for various applications in the blockchain space.

Continue Reading

Handpicked posts just for you — based on your current read.

Blockchain Development Tools, Libraries, and Frameworks Cheatsheet

  • Description: A lightweight and complete library for interacting with the Ethereum blockchain and its ecosystem.
  • Key Features:
  • Smaller and more modular than Web3.js.
  • Easy-to-use API for interacting with contracts and wallets.
  • Extensive support for signing transactions and handling wallets.
  • Built-in utilities for interacting with Ethereum Name Service (ENS).
  • Works well with Hardhat and other Ethereum tools.
  • Website: Ethers.js

Aug 23, 2024 Cheatsheet

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 Tutorial

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!