javascript nodejs solana blockchain decentralized-applications web3js wallet-address fetch-balance transaction-history token-holdings
Tutorial: Fetching Address Details from Solana
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
- Create a new project directory:
mkdir solana-address-details
cd solana-address-details
- Initialize a new Node.js project:
npm init -y
- 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.
Feel free to expand this tutorial by integrating these functions into a web application or exploring additional features offered by the Solana blockchain. Happy coding!
Comments
Please log in to leave a comment.