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

Discover more amazing content handpicked just for you

Tutorial

Etherscan vs Infura: Choosing the Right API for Your Blockchain Application

  • Use Etherscan if:
  • You only need to read blockchain data.
  • You want to build tools for analytics or explorers.
  • You don’t need to send transactions or interact directly with smart contracts.
  • Use Infura if:
  • You need to interact with the Ethereum blockchain in real-time.
  • You’re building dApps, wallets, or tools that require transactions.
  • You need to write data to the blockchain, such as sending Ether or deploying contracts.

In some cases, you might want to use both Etherscan and Infura. For example, you might use Etherscan to query transaction histories or token transfers, and Infura to send transactions or deploy contracts.

Oct 24, 2024
Read More
Tutorial

Understanding and Using the Etherscan API to Query Blockchain Data

node etherscanBalance.js

If everything is set up correctly, you’ll see an output like this:

Oct 24, 2024
Read More
Tutorial

Getting Wallet Balance Using Ethers.js in Node.js

> Important: Keep your private key secure. Never share it publicly or commit it to version control. For better security, consider using environment variables to store sensitive information like private keys.

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

Oct 24, 2024
Read More
Tutorial

Understanding 0x000000000000000000000000000000000000dead Address and Token Burns in Ethereum

The "0x000000000000000000000000000000000000dead" address is used as a burn address because it is widely recognized as a destination for token destruction. Since tokens sent to this address are permanently locked and cannot be retrieved, it’s an ideal address for conducting token burns. It is a well-established convention across many blockchain projects.

For example, in token burn events, project developers often send tokens to this address to signal to the community that those tokens are now out of circulation. This is usually followed by a public announcement, detailing the number of tokens burned and the reasons behind the burn.

Oct 24, 2024
Read More
Tutorial

ETH vs WETH: Understanding the Difference and Their Roles in Ethereum

  • Transaction Fees: ETH is required to pay gas fees, which are used to process transactions and execute smart contracts on the Ethereum network.
  • Store of Value: ETH, like Bitcoin, is often used as a store of value or an investment asset.
  • Participating in dApps: ETH is essential for interacting with decentralized applications (dApps) that run on the Ethereum network.

WETH (Wrapped Ether) is a token that represents an ERC-20 standard version of ETH. While ETH is the core currency of the Ethereum blockchain, it is not compatible with the ERC-20 standard, which governs the majority of tokens on the Ethereum network. This is where WETH comes into play.

Oct 24, 2024
Read More
Tutorial
rust

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

Here are some of the most commonly used SPL programs:

  • Token Program: Manages and interacts with tokens on the Solana blockchain. It supports minting, transferring, burning, and freezing tokens.
  • Associated Token Account Program: Creates and manages associated token accounts for users.
  • Memo Program: Allows developers to attach arbitrary data to transactions.
  • Token Swap Program: Enables token swapping functionalities similar to those found in decentralized exchanges (DEXs).

Aug 27, 2024
Read More
Cheatsheet
solidity

Blockchain Libraries Cheatsheet

  npm install ipfs

Aug 23, 2024
Read More
Cheatsheet
solidity

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
  • 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
Read More
Tutorial
solidity

Writing an ERC-20 Token Contract with OpenZeppelin

     mkdir my-token
     cd my-token
  • Initialize a new Hardhat project:

Aug 22, 2024
Read More
Tutorial
solidity

Understanding Gas and Optimization in Smart Contracts

Optimizing gas consumption in smart contracts can lead to substantial cost savings, especially for frequently executed contracts. Here are some strategies to consider:

1. Minimize Storage Writes

Aug 22, 2024
Read More
Tutorial
solidity

Building a Decentralized Application (DApp) with Smart Contracts

  • string public message: Declares a public string variable to store the message.
  • setMessage(string memory newMessage): A function to set a new message.
  • getMessage() public view returns (string memory): A function to retrieve the stored message.

After writing the smart contract, the next step is to compile and deploy it.

Aug 22, 2024
Read More
Tutorial
solidity

Introduction to Smart Contracts on Ethereum

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract SimpleStorage {
    uint256 public storedData;

    function set(uint256 x) public {
        storedData = x;
    }

    function get() public view returns (uint256) {
        return storedData;
    }
}

Explanation:

Aug 22, 2024
Read More
Tutorial
javascript solidity

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

Modify your smart contract to store and retrieve IPFS hashes. For simplicity, we'll store the hash of a file uploaded to IPFS.

Update MyDapp.sol:

Aug 20, 2024
Read More
Tutorial
javascript nodejs

Tracking Solana Address for New Trades and Amounts

   npm install @solana/web3.js

Step 2: Connect to the Solana Network

Aug 09, 2024
Read More
Tutorial
javascript nodejs

Tracking Newly Created Tokens on Solana

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.

Aug 09, 2024
Read More
Tutorial
javascript nodejs

Tracking Newly Created Tokens on Ethereum

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:

Aug 09, 2024
Read More
Tutorial
javascript bash +2

Building a Simple Solana Smart Contract with Anchor

   sudo apt update
   sudo apt install -y nodejs npm

Use npm to install the Anchor CLI:

Aug 09, 2024
Read More
Tutorial
bash rust

Creating a Token on Solana

   cargo install spl-token-cli

Check that the SPL Token CLI is installed correctly:

Aug 09, 2024
Read More
Tutorial
bash rust

Installing Solana on Ubuntu

Solana requires several dependencies to be installed on your system. Use the following commands to install them:

sudo apt install -y curl git build-essential libssl-dev pkg-config

Aug 09, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!