In the fast-evolving world of blockchain development, staying up to date with the latest tools and libraries is essential. In late 2024, Solana introduced Solana Web3.js 2.0—now officially rebranded as Solana Kit—a powerful upgrade to its foundational JavaScript library. This modernized toolkit brings enhanced type safety, improved error handling, and a more intuitive approach to managing WebSocket subscriptions for real-time blockchain monitoring.
This guide walks you through implementing a robust account monitoring system using Solana Kit and WebSocket connections, enabling you to track balance changes on any Solana account in real time. Whether you're building a DeFi dashboard, NFT tracker, or analytics tool, mastering this technique is a critical step toward responsive, data-driven dApps.
Key Improvements in Solana Kit
Solana Kit represents a major leap forward from the legacy Web3.js 1.0 library. Here are the most impactful changes:
- TypeScript-First Design: Built with strict typing and generics for better code reliability.
- Modern Async Iteration: Uses
for await...ofloops instead of callback-based patterns, aligning with current JavaScript standards. - AbortController Integration: Enables clean, predictable subscription cancellation.
- Enhanced Error Handling: Clearer error types and structured exception management.
These improvements make Solana Kit ideal for production-grade applications requiring stability and maintainability.
Prerequisites
Before diving in, ensure your development environment includes:
- Node.js (v20 or higher)
- npm or yarn
- TypeScript and ts-node (install globally or as dev dependencies)
👉 Discover how modern blockchain tools can accelerate your development workflow.
Setting Up the Project
Start by creating a new project directory and initializing it:
mkdir solana-subscriptions-v2 && cd solana-subscriptions-v2
npm init -yInstall the required packages:
npm install @solana/kit
npm install --save-dev typescript ts-node @types/nodeNext, create a tsconfig.json file to configure TypeScript:
{
"compilerOptions": {
"module": "NodeNext",
"moduleResolution": "NodeNext",
"noEmit": true,
"target": "ESNext"
}
}This configuration ensures compatibility with modern Node.js and ECMAScript features.
Building the Account Monitor
Create a file named app.ts and begin by importing the necessary components from Solana Kit:
import {
createSolanaRpcSubscriptions,
RpcSubscriptions,
SolanaRpcSubscriptionsApi,
address,
Address
} from '@solana/kit';Define Constants
Set up key constants for your monitoring script:
const WSS_PROVIDER_URL = 'wss://your-quicknode-endpoint.example';
const LAMPORTS_PER_SOL = 1_000_000_000;
const PUMP_FUN_FEE_ACCOUNT = address("CebN5WGQ4jvEPvsVU4EoHEpgzq1VV7AbicfhtW4xC9iM");Replace WSS_PROVIDER_URL with your actual WebSocket endpoint from a provider like QuickNode. The PUMP_FUN_FEE_ACCOUNT is used here as a demonstration—you can monitor any Solana address.
Note: Always use theaddress()function from@solana/kitto ensure type-safe address handling.
Format Balance Changes
Add a helper function to convert lamports to human-readable SOL amounts:
const lamportsToSolString = (lamports: number, includeUnit = true): string => {
const solAmount = lamports / LAMPORTS_PER_SOL;
return `${solAmount.toLocaleString('en-US', {
minimumFractionDigits: 2,
maximumFractionDigits: 2
})}${includeUnit ? ' SOL' : ''}`;
};This ensures clean, consistent output when logging balance updates.
Implementing Real-Time Monitoring
Define an interface for the tracking function parameters:
interface TrackAccountArgs {
rpcSubscriptions: RpcSubscriptions;
accountAddress: Address;
abortSignal: AbortSignal;
}Now, create the core function that subscribes to account changes:
async function trackAccount({ rpcSubscriptions, accountAddress, abortSignal }: TrackAccountArgs) {
let lastLamports: number | null = null;
try {
const accountNotifications = await rpcSubscriptions
.accountNotifications(accountAddress, { commitment: 'confirmed' })
.subscribe({ abortSignal });
try {
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(`Account change detected at slot ${slot.toLocaleString()}. New Balance: ${lamportsToSolString(currentLamports)} (${sign}${lamportsToSolString(Math.abs(delta))})`);
lastLamports = currentLamports;
}
} catch (error) {
throw error;
}
} catch (error) {
console.error('Subscription failed:', error);
}
}This function uses async iteration to process incoming WebSocket messages, calculates balance deltas, and logs them in a user-friendly format.
Entry Point and Execution
Add the main function to initialize and run the monitor:
async function main() {
console.log(`💊 Tracking Pump.fun Fee Account: ${PUMP_FUN_FEE_ACCOUNT} 💊`);
const rpcSubscriptions = createSolanaRpcSubscriptions(WSS_PROVIDER_URL);
const abortController = new AbortController();
try {
await trackAccount({
rpcSubscriptions,
accountAddress: PUMP_FUN_FEE_ACCOUNT,
abortSignal: abortController.signal
});
} catch (e) {
console.log('Subscription error', e);
} finally {
abortController.abort();
}
}
main();Run the script using:
npx ts-node app.tsYou’ll see output like:
Account change detected at slot 301,428,932. New Balance: 265,598.16 SOL (+0.14 SOL)👉 Explore how real-time blockchain data can power your next project.
Frequently Asked Questions
Q: What is Solana Kit?
A: Solana Kit is the updated version of Solana Web3.js 2.0, offering improved type safety, async iteration support, and better WebSocket management for building dApps on Solana.
Q: How do I get a WebSocket endpoint for Solana?
A: You can obtain a reliable WSS URL from blockchain infrastructure providers like QuickNode, Alchemy, or Helius by creating a free or paid account.
Q: Why use AbortController in subscriptions?
A: It allows graceful cancellation of WebSocket connections, preventing memory leaks and unnecessary billing on RPC services.
Q: How are WebSocket subscriptions billed?
A: Providers typically charge per message received. For example, QuickNode bills 20 API credits per response, so monitoring high-activity accounts can increase costs.
Q: Can I filter account notifications?
A: The accountNotifications method doesn’t support on-chain filters. For advanced filtering, consider using gRPC-based solutions like Yellowstone Geyser.
Q: Is Solana Kit compatible with older Web3.js code?
A: Not directly. Migration requires updating imports and refactoring subscription logic to use async iteration and typed interfaces.
Optimization and Cost Management
WebSocket usage impacts both performance and cost. To optimize:
- Cancel subscriptions promptly using
AbortController. - Monitor only necessary accounts to reduce message volume.
- Use commitment levels wisely:
confirmedoffers a balance between speed and reliability.
For high-throughput applications, consider alternative solutions like Yellowstone Geyser gRPC or managed streaming platforms that support filtering and data routing.
Final Thoughts
Solana Kit sets a new standard for developer experience on the Solana blockchain. Its modern syntax, robust typing, and clean subscription model make real-time account monitoring more reliable and maintainable than ever before.
By mastering this approach, you're well-equipped to build responsive dApps that react instantly to on-chain activity—whether tracking token flows, detecting wallet movements, or powering live analytics dashboards.
👉 Start building with real-time blockchain data today—unlock powerful insights instantly.