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

  • API: This script sends a GET request to Etherscan's API to fetch the balance of the specified Ethereum wallet.
  • Use Case: Ideal for applications needing read-only access to Ethereum data.

Use Infura when you need to interact with the Ethereum blockchain in real-time. Infura allows you to send transactions, deploy contracts, and interact with smart contracts. It is essential for decentralized applications (dApps) and any use case where you need to write to the blockchain.

Oct 24, 2024
Read More
Tutorial

Understanding and Using the Etherscan API to Query Blockchain Data

You can also query ERC-20 token balances for a given address using the Etherscan API.

const axios = require('axios');

// Replace this with your actual Etherscan API key
const apiKey = 'YOUR_ETHERSCAN_API_KEY';

// Replace this with the Ethereum address you want to query
const address = '0xYourEthereumAddress';

// Replace this with the contract address of the ERC-20 token
const contractAddress = '0xYourTokenContractAddress';

// Etherscan API URL to fetch the ERC-20 token balance
const url = `https://api.etherscan.io/api?module=account&action=tokenbalance&contractaddress=${contractAddress}&address=${address}&tag=latest&apikey=${apiKey}`;

async function getTokenBalance() {
  try {
    // Make the API request to Etherscan
    const response = await axios.get(url);
    const tokenBalance = response.data.result;

    // Log the token balance (Note: Token balances are often in very small denominations)
    console.log(`Token Balance: ${tokenBalance}`);
  } catch (error) {
    console.error('Error fetching token balance:', error);
  }
}

// Call the function to get the token balance
getTokenBalance();

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

Burning tokens refers to the process of sending cryptocurrency tokens to an address from which they cannot be retrieved. Tokens sent to this address are effectively removed from circulation forever. The address ends with "dead," signaling its purpose of making tokens unreachable.

Token burns serve several key purposes in the cryptocurrency world:

Oct 24, 2024
Read More
Tutorial

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

  • To retrieve the original ETH, users can exchange their WETH back through the smart contract.
  • The contract will burn the WETH and return the original ETH to the user.

Example on a DEX like Uniswap:

Oct 24, 2024
Read More
Tutorial
rust

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

use anchor_lang::prelude::*;
use spl_token::instruction::mint_to;
use solana_program::program::invoke;

declare_id!("YourProgramID");

#[program]
pub mod solana_spl_tutorial {
    use super::*;

    pub fn mint_token(ctx: Context<MintToken>, amount: u64) -> Result<()> {
        let cpi_accounts = MintTo {
            mint: ctx.accounts.mint.to_account_info(),
            to: ctx.accounts.token_account.to_account_info(),
            authority: ctx.accounts.authority.to_account_info(),
        };
        let cpi_program = ctx.accounts.token_program.to_account_info();
        let cpi_ctx = CpiContext::new(cpi_program, cpi_accounts);

        invoke(
            &mint_to(
                ctx.accounts.token_program.key,
                ctx.accounts.mint.key,
                ctx.accounts.token_account.key,
                ctx.accounts.authority.key,
                &[],
                amount,
            )?,
            &[
                ctx.accounts.mint.to_account_info(),
                ctx.accounts.token_account.to_account_info(),
                ctx.accounts.authority.to_account_info(),
            ],
        )?;

        Ok(())
    }
}

#[derive(Accounts)]
pub struct MintToken<'info> {
    #[account(mut)]
    pub mint: AccountInfo<'info>,
    #[account(mut)]
    pub token_account: AccountInfo<'info>,
    #[account(signer)]
    pub authority: AccountInfo<'info>,
    pub token_program: AccountInfo<'info>,
}

This simple program demonstrates how to use the SPL Token Program to mint new tokens.

Aug 27, 2024
Read More
Cheatsheet
solidity

Blockchain Libraries Cheatsheet

  • Description: A JavaScript library for Bitcoin-related operations, including creating and signing transactions, and managing addresses.
  • Use Cases:
  • Create Bitcoin wallets and addresses.
  • Sign and broadcast Bitcoin transactions.
  • Build Bitcoin-based applications with custom scripts.
  • Key Features:
  • Lightweight and easy to use.
  • Supports SegWit (Segregated Witness) transactions.
  • Comprehensive documentation for various Bitcoin operations.
  • Installation:
  npm install bitcoinjs-lib

Aug 23, 2024
Read More
Cheatsheet
solidity

Blockchain Development Tools, Libraries, and Frameworks Cheatsheet

  • Description: An open-source blockchain explorer for Ethereum-based networks.
  • Key Features:
  • Provides a user-friendly interface for exploring blocks, transactions, and tokens.
  • Supports custom networks and sidechains.
  • Allows token holders to track token balances and transaction histories.
  • Easy to deploy and customize.
  • Website: BlockScout
  • Description: A decentralized oracle network that provides real-world data to smart contracts.
  • Key Features:
  • Fetches data from APIs and off-chain sources for use in smart contracts.
  • Secure and reliable, with decentralization to avoid single points of failure.
  • Supports various data types including price feeds, weather data, and more.
  • Integrates easily with Ethereum smart contracts.
  • Website: Chainlink

Aug 23, 2024
Read More
Tutorial
solidity

Writing an ERC-20 Token Contract with OpenZeppelin

  • Follow the prompts to create a basic Hardhat sample project.
  • Install the OpenZeppelin Contracts library:

Aug 22, 2024
Read More
Tutorial
solidity

Understanding Gas and Optimization in Smart Contracts

Understanding gas and optimizing its consumption in smart contracts is crucial for developing cost-effective and efficient decentralized applications. By implementing strategies such as minimizing storage writes, using view and pure functions, optimizing loops, and leveraging efficient data structures, you can significantly reduce the gas costs associated with your smart contracts.

As you continue your journey in Ethereum development, keep refining your skills in gas optimization and stay updated with best practices and tools. Gas efficiency not only saves costs but also contributes to the overall scalability and usability of the Ethereum network.

Aug 22, 2024
Read More
Tutorial
solidity

Building a Decentralized Application (DApp) with Smart Contracts

  • Decentralized: Operates on a blockchain network.
  • Open-source: The code is public and available for anyone to view and audit.
  • Autonomous: Once deployed, it runs independently without human intervention.
  • Smart Contract Integration: Relies on smart contracts to execute transactions and operations.

Before you start building your DApp, you’ll need to set up your development environment. Here’s what you need:

Aug 22, 2024
Read More
Tutorial
solidity

Introduction to Smart Contracts on Ethereum

Steps to Deploy:

  • Switch to the "Deploy & Run Transactions" tab.
  • Select "Injected Web3" as the environment to connect to MetaMask.
  • Choose a test network like Ropsten or Kovan in MetaMask.
  • Click "Deploy" and confirm the transaction in MetaMask.

Aug 22, 2024
Read More
Tutorial
javascript solidity

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

Update MyDapp.sol:

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

contract MyDapp {
    string public ipfsHash;

    event IPFSHashChanged(string newIPFSHash);

    function setIPFSHash(string memory newIPFSHash) public {
        ipfsHash = newIPFSHash;
        emit IPFSHashChanged(newIPFSHash);
    }

    function getIPFSHash() public view returns (string memory) {
        return ipfsHash;
    }
}

Aug 20, 2024
Read More
Tutorial
javascript nodejs

Tracking Solana Address for New Trades and Amounts

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:

Aug 09, 2024
Read More
Tutorial
javascript nodejs

Tracking Newly Created Tokens on Solana

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

Aug 09, 2024
Read More
Tutorial
javascript nodejs

Tracking Newly Created Tokens on Ethereum

Step 1: Set Up Your Project

   mkdir ethereum-token-tracker
   cd ethereum-token-tracker

Aug 09, 2024
Read More
Tutorial
javascript bash +2

Building a Simple Solana Smart Contract with Anchor

Use Anchor to create a new project named counter:

   anchor init counter

Aug 09, 2024
Read More
Tutorial
bash rust

Creating a Token on Solana

If you don't have a recipient wallet, create one and get its token account:

   solana-keygen new --outfile ~/recipient-wallet.json
   spl-token create-account <TOKEN_MINT_ADDRESS> --owner ~/recipient-wallet.json

Aug 09, 2024
Read More
Tutorial
bash rust

Installing Solana on Ubuntu

   cargo build --release
   export PATH="$HOME/solana/target/release:$PATH"

Aug 09, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!