DeveloperBreeze

Introduction

In this tutorial, we'll learn how to track a specific Solana address for new trades and notify via console.log with the transaction details, including the amount bought or sold. We will use the Solana Web3.js library to connect to the Solana blockchain, listen for new transactions, and fetch their details.

Prerequisites

  • Node.js and npm installed on your system.
  • Basic knowledge of JavaScript and Solana.
  • A Solana wallet address you wish to track.

Step 1: Set Up Your Project

  1. Create a new project directory:
   mkdir solana-address-tracker
   cd solana-address-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 initializes a connection to the Solana Devnet, which is useful for testing without using real SOL tokens.

Step 3: Track a Specific Solana Address

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);

Explanation

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

Conclusion

In this tutorial, we explored how to track a specific Solana address for new trades using the Solana Web3.js library. By monitoring transactions and parsing their instructions, we can log details of each new trade to the console. This approach can be extended to trigger notifications or other actions when new trades occur.

Continue Reading

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

Blockchain Development Tools, Libraries, and Frameworks Cheatsheet

  • Description: A blockchain-based storage solution for permanent, low-cost data storage.
  • Key Features:
  • Stores data permanently with a one-time fee.
  • Uses a unique consensus mechanism called Proof of Access.
  • Integrates with Ethereum for storing DApp data, NFTs, and more.
  • Scalable and reliable for long-term data storage.
  • Website: Arweave

Aug 23, 2024 Cheatsheet

Tracking Newly Created Tokens on Ethereum

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

Aug 09, 2024 Tutorial

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!