DeveloperBreeze

Introduction

In this tutorial, we will explore how to fetch address details from the Solana blockchain. Solana is a high-performance blockchain known for its speed and low transaction costs, making it an ideal platform for decentralized applications. We will cover how to interact with Solana using its JSON-RPC API and the Solana Web3.js library to retrieve information such as balance, transaction history, and token holdings of a specific wallet address.

Prerequisites

Before we begin, make sure you have the following:

  • Node.js and npm installed on your system.
  • Basic knowledge of JavaScript.
  • A Solana wallet address (for testing purposes, 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-address-details
   cd solana-address-details
  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 a test network where you can experiment without using real SOL tokens.

Step 3: Fetch Wallet Balance

Next, let's fetch the balance of a specific wallet address. Add the following function to your index.js file:

async function getWalletBalance(walletAddress) {
  try {
    const publicKey = new solanaWeb3.PublicKey(walletAddress);
    const balance = await connection.getBalance(publicKey);
    console.log(`Wallet Balance: ${balance / solanaWeb3.LAMPORTS_PER_SOL} SOL`);
  } catch (error) {
    console.error('Error fetching wallet balance:', error);
  }
}

// Replace with your Solana wallet address
const walletAddress = 'YourWalletAddressHere';
getWalletBalance(walletAddress);

This function takes a wallet address, converts it to a PublicKey object, and uses the getBalance method to fetch the balance in lamports (the smallest unit of SOL). It then converts lamports to SOL for display.

Step 4: Fetch Transaction History

To fetch the transaction history of the wallet, add the following function:

async function getTransactionHistory(walletAddress) {
  try {
    const publicKey = new solanaWeb3.PublicKey(walletAddress);
    const confirmedSignatures = await connection.getSignaturesForAddress(publicKey);

    console.log('Transaction History:');
    for (const signatureInfo of confirmedSignatures) {
      const transactionDetails = await connection.getTransaction(signatureInfo.signature);
      console.log(`- Transaction Signature: ${signatureInfo.signature}`);
      console.log(`  Slot: ${transactionDetails.slot}`);
      console.log(`  Result: ${transactionDetails.meta.err ? 'Error' : 'Success'}`);
    }
  } catch (error) {
    console.error('Error fetching transaction history:', error);
  }
}

getTransactionHistory(walletAddress);

This function retrieves the transaction signatures associated with the wallet address and fetches the details of each transaction. It logs the transaction signature, slot number, and result status (success or error).

Step 5: Fetch Token Holdings

Finally, let's fetch the token holdings of the wallet:

async function getTokenHoldings(walletAddress) {
  try {
    const publicKey = new solanaWeb3.PublicKey(walletAddress);
    const tokenAccounts = await connection.getParsedTokenAccountsByOwner(publicKey, {
      programId: solanaWeb3.TOKEN_PROGRAM_ID,
    });

    console.log('Token Holdings:');
    tokenAccounts.value.forEach((tokenAccount) => {
      const tokenAmount = tokenAccount.account.data.parsed.info.tokenAmount.uiAmount;
      const tokenMint = tokenAccount.account.data.parsed.info.mint;
      console.log(`- Token Mint: ${tokenMint}`);
      console.log(`  Amount: ${tokenAmount}`);
    });
  } catch (error) {
    console.error('Error fetching token holdings:', error);
  }
}

getTokenHoldings(walletAddress);

This function uses the getParsedTokenAccountsByOwner method to retrieve token accounts owned by the wallet address. It then logs the token mint address and the amount held.

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.

Continue Reading

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

Blockchain Libraries Cheatsheet

  • Description: A lightweight and fully featured library for interacting with the Ethereum blockchain.
  • Use Cases:
  • Interact with smart contracts and wallets.
  • Create and manage Ethereum addresses.
  • Sign transactions and data.
  • Query the Ethereum blockchain and perform low-level operations.
  • Key Features:
  • Modular design with a smaller bundle size compared to Web3.js.
  • Built-in support for ENS (Ethereum Name Service).
  • Simplified API for common Ethereum tasks.
  • Installation:

Aug 23, 2024 Cheatsheet

Blockchain Development Tools, Libraries, and Frameworks Cheatsheet

  • Description: A JavaScript library that allows you to interact with the Ethereum blockchain via HTTP, WebSocket, or IPC.
  • Key Features:
  • Comprehensive set of tools to interact with smart contracts.
  • Connects to Ethereum nodes via HTTP, WebSocket, or IPC.
  • Handles sending Ether and deploying contracts.
  • Provides utilities for managing accounts, keys, and wallets.
  • Website: Web3.js

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!