Monitoring Solana Accounts Using WebSocket and Solana Web3.js 2.0

·

This guide explores the major updates in Solana Web3.js 2.0, focusing on its new WebSocket subscription system to monitor account balance changes on the Solana blockchain. Through code examples, we demonstrate project setup, environment configuration, and implementation steps, highlighting the API's type safety, modern async iteration, and improved error handling—ideal for developers integrating Solana solutions.


Overview

Solana Web3.js 2.0 introduces a revamped JavaScript library for interacting with the Solana blockchain, featuring a robust WebSocket subscription system. This tutorial walks through leveraging the new subscription API to track account balance changes, emphasizing its enhanced type safety and error management.

Key Learning Outcomes

Prerequisites


Key Differences from Web3.js 1.0

  1. Type Safety: Strict TypeScript integration.
  2. Modern Async Iterators: Uses for await...of instead of callbacks.
  3. AbortController Integration: Streamlined subscription cleanup.
  4. Enhanced Error Handling: Structured error types.

Environment Setup

1. Initialize Project

mkdir solana-subscriptions-v2 && cd solana-subscriptions-v2  
npm init -y  
npm install @solana/web3.js@2  
npm install --save-dev typescript ts-node @types/node  

2. Configure TypeScript

Update tsconfig.json:

{
  "compilerOptions": {
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "target": "ESNext"
  }
}

Building the Account Monitor

1. Import Dependencies

import {
  createSolanaRpcSubscriptions,
  RpcSubscriptions,
  SolanaRpcSubscriptionsApi,
  address,
  Address
} from '@solana/web3.js';

2. Define Constants

const WSS_PROVIDER_URL = 'wss://your-quicknode-endpoint.example';
const LAMPORTS_PER_SOL = 1_000_000_000;
const PUMP_FUN_FEE_ACCOUNT = address("CebN5WGQ4jvEPvsVU4EoHEpgzq1VV7AbicfhtW4xC9iM");

3. Utility Function

const lamportsToSolString = (lamports: number, includeUnit = true): string => {
  const solAmount = lamports / LAMPORTS_PER_SOL;
  return `${solAmount.toLocaleString('en-US', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })} ${includeUnit ? 'SOL' : ''}`;
};

4. Track Account Function

async function trackAccount({ rpcSubscriptions, accountAddress, abortSignal }: TrackAccountArgs) {
  let lastLamports: number | null = null;
  try {
    const accountNotifications = await rpcSubscriptions
      .accountNotifications(accountAddress, { commitment: 'confirmed' })
      .subscribe({ abortSignal });
    for await (const notification of accountNotifications) {
      const { slot } = notification.context;
      const currentLamports = Number(notification.value.lamports);
      const delta = lastLamports !== null ? currentLamports - lastLamports : 0;
      const sign = delta > 0 ? '+' : delta < 0 ? '-' : ' ';
      console.log(`Slot ${slot.toLocaleString()}: Balance ${lamportsToSolString(currentLamports)} (${sign}${lamportsToSolString(Math.abs(delta))})`);
      lastLamports = currentLamports;
    }
  } catch (error) {
    console.error('Subscription error:', error);
  }
}

5. Execute Script

async function main() {
  const rpcSubscriptions = createSolanaRpcSubscriptions(WSS_PROVIDER_URL);
  const abortController = new AbortController();
  try {
    await trackAccount({
      rpcSubscriptions,
      accountAddress: PUMP_FUN_FEE_ACCOUNT,
      abortSignal: abortController.signal
    });
  } finally {
    abortController.abort();
  }
}
main();

Billing Optimization

WebSocket billing is based on responses received. Optimize by:

Alternatives:


FAQs

How do I handle WebSocket disconnections?

Use exponential backoff retry logic and AbortController for reconnection.

Can I monitor multiple accounts simultaneously?

Yes! Create separate subscriptions for each account.

What’s the cost implication?

~20 credits per response. Filter data to minimize costs.


Conclusion

Solana Web3.js 2.0’s subscription API offers a reliable, type-safe way to monitor real-time blockchain events. Implement the guide’s steps to build efficient account trackers.

👉 Explore Solana Web3.js 2.0 Documentation
👉 QuickNode API Credits Guide

For further reading: