DEV Community

Cover image for Fetching and Updating Solana Wallet Balances
Sumana
Sumana

Posted on

Fetching and Updating Solana Wallet Balances

Introduction

This TypeScript tutorial guides you through fetching and updating wallet balances on the Solana blockchain. You'll learn how to retrieve SOL balances programmatically and perform airdrops, enabling you to manage wallet funds with ease.

Step 1: Setting Up Your TypeScript Project

First, set up your TypeScript project:

npm init -y
npm install --save-dev typescript
npx tsc --init
Enter fullscreen mode Exit fullscreen mode

Step 2: Installing Solana Web3.js Library

Install the Solana Web3.js library:

npm install --save @solana/web3.js
Enter fullscreen mode Exit fullscreen mode

Step 3: Fetching and Updating Wallet Balances

Create index.ts:

import { Connection, PublicKey, LAMPORTS_PER_SOL } from "@solana/web3.js";
import { airdrop } from "../airdrop";

export const showBalance = async (publicKey: PublicKey): Promise<number | null> => {
    const conn = new Connection("http://127.0.0.1:8899", "confirmed");
    const response = await conn.getAccountInfo(publicKey);

    if (response === null) {
        return null;
    }
    return response.lamports / LAMPORTS_PER_SOL;
};

(async () => {
    const publicKey = "Your Key";
    const balance = await showBalance(new PublicKey(publicKey));
    console.log(`The balance of the ${publicKey} is ${balance}`);

    await airdrop(publicKey, 5);

    const updatedBalance = await showBalance(new PublicKey(publicKey));
    console.log(`Updated balance of the ${publicKey} is ${updatedBalance}`);
})();
Enter fullscreen mode Exit fullscreen mode

Step 4: Building and Executing Your Project

Build your project:

npm run build
Enter fullscreen mode Exit fullscreen mode

Run your project:

node dist/index.js
Enter fullscreen mode Exit fullscreen mode

Conclusion

You've successfully fetched and updated a Solana wallet's balance using TypeScript. Keep exploring Solana's capabilities to build innovative and secure applications🚀!

P.S. If you need help with airdropping SOL, check out my Airdrop Post for a detailed guide.

Top comments (0)