DeveloperBreeze

Introduction

In this tutorial, we'll learn how to track newly created tokens on the Solana blockchain. Solana uses the SPL Token Program for its token operations, which allows developers to create, transfer, and manage tokens efficiently. We will explore how to interact with Solana's RPC API and the Solana Web3.js library to monitor new token creation events.

Prerequisites

  • Node.js and npm installed on your system.
  • Basic knowledge of JavaScript and Solana.
  • A Solana Devnet account (you can create one using the Solana CLI or a wallet like Phantom).

Step 1: Set Up Your Project

  1. Create a new project directory:
   mkdir solana-token-tracker
   cd solana-token-tracker
  1. Initialize a new Node.js project:
   npm init -y
  1. Install the Solana Web3.js library:
   npm install @solana/web3.js

Step 2: Connect to the Solana Network

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

const solanaWeb3 = require('@solana/web3.js');

// Connect to the Solana Devnet
const connection = new solanaWeb3.Connection(
  solanaWeb3.clusterApiUrl('devnet'),
  'confirmed'
);

console.log('Connected to Solana Devnet');

This code establishes a connection to the Solana Devnet, allowing us to interact with the network for development purposes.

Step 3: Fetch New Token Creation Transactions

Solana tokens are created using the SPL Token Program, so we'll track transactions involving this program to identify new tokens. Add the following function to your index.js file:

async function getNewTokens(startSlot) {
  try {
    const currentSlot = await connection.getSlot();
    const signatures = await connection.getConfirmedSignaturesForAddress2(
      new solanaWeb3.PublicKey(solanaWeb3.TOKEN_PROGRAM_ID),
      { startSlot, limit: 100 }
    );

    console.log('Newly Created Tokens:');
    for (const signatureInfo of signatures) {
      const transaction = await connection.getConfirmedTransaction(signatureInfo.signature);
      const transactionInstructions = transaction.transaction.message.instructions;

      transactionInstructions.forEach((instruction) => {
        if (instruction.programId.equals(solanaWeb3.TOKEN_PROGRAM_ID)) {
          const data = Buffer.from(instruction.data);
          const command = data.readUInt8(0);

          // Command 1 represents the Token Mint To instruction
          if (command === 1) {
            const mintAccount = instruction.keys[0].pubkey.toBase58();
            console.log(`- New Token Mint: ${mintAccount}`);
          }
        }
      });
    }
  } catch (error) {
    console.error('Error fetching new tokens:', error);
  }
}

// Replace with the starting slot number
const startSlot = 1000000;
getNewTokens(startSlot);

Explanation

  • Token Program ID: The TOKEN_PROGRAM_ID is used to filter transactions that involve token operations. We're interested in the Mint To instruction, which indicates new token creation.
  • Fetch Signatures: We fetch the confirmed signatures for transactions involving the SPL Token Program starting from a specified slot.
  • Process Instructions: We inspect the transaction instructions to identify those that correspond to the Mint To operation, which indicates token creation.

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 Solana blockchain using the Solana Web3.js library. By monitoring transactions involving the SPL Token Program, we can identify new token minting events. This approach provides a powerful way to stay updated with new token launches on Solana.

Continue Reading

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

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

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();
  • 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.

Oct 24, 2024 Tutorial

Blockchain Development Tools, Libraries, and Frameworks Cheatsheet

  • Description: An interactive tutorial platform for learning Solidity by building a game.
  • Key Features:
  • Step-by-step lessons on Solidity and smart contract development.
  • Interactive coding exercises and challenges.
  • Gamified learning experience.
  • Covers basic to advanced Solidity topics.
  • Website: CryptoZombies

Aug 23, 2024 Cheatsheet

Tracking Solana Address for New Trades and Amounts

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);
  • Fetch Transactions: We fetch the transaction signatures for the specified address and track them using getSignaturesForAddress.
  • Monitor New Transactions: Using setInterval, we periodically fetch new transactions and check for token transfer instructions.
  • Parse Transactions: We parse each transaction's instructions to identify token transfers and log the details to the console.
  • Token Program ID: We check if the program ID matches Solana's SPL Token Program to identify relevant instructions.

Aug 09, 2024 Tutorial

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!