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

Discover more amazing content handpicked just for you

Tutorial

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

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

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

Oct 24, 2024
Read More
Tutorial

Understanding and Using the Etherscan API to Query Blockchain Data

This script queries the wallet balance from the Ethereum blockchain using the Etherscan API.

Let’s extend the functionality by querying transaction details for a specific transaction using the Etherscan API.

Oct 24, 2024
Read More
Tutorial

Getting Wallet Balance Using Ethers.js in Node.js

Once your script is set up, run it from the command line:

node getBalance.js

Oct 24, 2024
Read More
Tutorial
rust

Using Solana's Program Library: Building Applications with Pre-Built Functions

Solana, one of the fastest-growing blockchain platforms, offers a robust development environment for building decentralized applications (dApps). A key feature of Solana's ecosystem is its Program Library (SPL), which provides pre-built functions that developers can leverage to speed up the development process. In this tutorial, we will explore how to use Solana's Program Library to build applications efficiently, focusing on the essentials you need to get started.

Before diving into Solana's Program Library, ensure you have the following:

Aug 27, 2024
Read More
Cheatsheet
solidity

Blockchain Libraries Cheatsheet

and reactive Java and Android library for working with smart contracts and integrating with Ethereum nodes.

  • Use Cases:
  • Build Ethereum-based applications in Java and Android.
  • Interact with smart contracts and Ethereum nodes.
  • Send transactions, query blockchain data, and manage Ethereum accounts.
  • Key Features:
  • Full support for Ethereum JSON-RPC.
  • Asynchronous and synchronous execution of requests.
  • Built-in support for Solidity smart contract wrappers.
  • Installation:

Aug 23, 2024
Read More
Cheatsheet
solidity

Blockchain Development Tools, Libraries, and Frameworks Cheatsheet

with development tools like Hardhat and Truffle.

Aug 23, 2024
Read More
Tutorial
solidity

Writing an ERC-20 Token Contract with OpenZeppelin

Once your contract is deployed, you can interact with it using Hardhat or a front-end interface.

  • Open the Hardhat console:

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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Message DApp</title>
</head>
<body>
    <h1>Decentralized Message Store</h1>
    <input type="text" id="messageInput" placeholder="Enter a new message">
    <button onclick="setMessage()">Set Message</button>
    <p id="currentMessage">Loading message...</p>

    <script src="https://cdn.jsdelivr.net/npm/web3@latest/dist/web3.min.js"></script>
    <script>
        const contractAddress = 'YOUR_CONTRACT_ADDRESS';
        const abi = [/* ABI from compiled contract */];

        const web3 = new Web3(Web3.givenProvider);
        const contract = new web3.eth.Contract(abi, contractAddress);

        async function setMessage() {
            const accounts = await web3.eth.getAccounts();
            const message = document.getElementById('messageInput').value;
            await contract.methods.setMessage(message).send({ from: accounts[0] });
            loadMessage();
        }

        async function loadMessage() {
            const message = await contract.methods.getMessage().call();
            document.getElementById('currentMessage').innerText = message;
        }

        window.onload = loadMessage;
    </script>
</body>
</html>
  • Web3.js: A JavaScript library for interacting with the Ethereum blockchain.
  • contract.methods.setMessage(message).send({ from: accounts[0] }): Calls the smart contract’s setMessage function and sends a transaction to the blockchain.
  • contract.methods.getMessage().call(): Calls the smart contract’s getMessage function to retrieve the stored message.

Aug 22, 2024
Read More
Tutorial
solidity

Introduction to Smart Contracts on Ethereum

Explanation:

  • pragma solidity ^0.8.0;: Specifies the version of Solidity.
  • contract SimpleStorage: Defines a new smart contract named SimpleStorage.
  • uint256 public storedData: Declares a public variable to store an unsigned integer.
  • function set(uint256 x) public: A function to set the value of storedData.
  • function get() public view returns (uint256): A function to retrieve the value of storedData.

Aug 22, 2024
Read More
Tutorial
javascript solidity

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

npx create-react-app client
cd client
npm install web3

Web3.js is a JavaScript library that allows you to interact with the Ethereum blockchain.

Aug 20, 2024
Read More
Tutorial
python

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

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.

Managing open orders and closing positions is essential for effective trading. Pybit makes it straightforward to close orders.

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

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

Aug 09, 2024
Read More
Tutorial
javascript json

Fetching Address Details from Solana

Conclusion

In this tutorial, we explored how to fetch address details from the Solana blockchain using the Solana Web3.js library. We covered fetching wallet balance, transaction history, and token holdings. By leveraging Solana's high-performance capabilities, you can build decentralized applications that require fast and efficient blockchain interactions.

Aug 09, 2024
Read More
Tutorial
javascript bash +2

Building a Simple Solana Smart Contract with Anchor

   anchor deploy
  • Make sure your Solana CLI is configured to use the Devnet (solana config set --url https://api.devnet.solana.com).

Aug 09, 2024
Read More
Tutorial
bash rust

Creating a Token on Solana

   spl-token transfer <TOKEN_MINT_ADDRESS> <AMOUNT> <RECIPIENT_TOKEN_ACCOUNT>

Replace <RECIPIENT_TOKEN_ACCOUNT> with the token account address of the recipient.

Aug 09, 2024
Read More
Tutorial
bash rust

Installing Solana on Ubuntu

You should see the Rust version printed in the terminal.

With Rust installed, you can now install the Solana command-line tools. These tools are essential for interacting with the Solana network.

Aug 09, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!