Markdown
When building on-chain monitoring tools or automated security agents on Solana, latency and simplicity matter. Relying on slow RPC polling or heavy Anchor IDL setups just to watch liquidity changes in a DEX pool introduces unnecessary overhead.

In this post, I’ll walk through how I built sentinel-solana—a lightweight, real-time monitoring agent in TypeScript that decodes Raydium V4 pool buffers directly and tracks liquidity outflows over Helius WebSockets.

Architecture Overview

To keep the agent fast and modular, the core logic is split into two focused components:

  1. src/parser.ts — Decodes raw binary account data from Raydium V4 liquidity pools using LIQUIDITY_STATE_LAYOUT_V4 from @raydium-io/raydium-sdk and converts key fields into BigInt for exact arithmetic.
  2. src/monitor.ts — Establishes WebSocket subscriptions via Helius RPC, resolves the underlying token vaults, and monitors real-time balance deltas to flag anomalous liquidity withdrawals.

Step 1: Decoding the Raydium V4 Pool State

A common gotcha when working with Solana AMMs is assuming token reserves live directly inside the main pool account. In Raydium V4, the pool account stores configuration flags, status, and swap accumulators, while the actual token reserves reside in two separate SPL Token accounts: baseVault and quoteVault.

By decoding the pool's binary buffer on startup, we can extract both the pool's operational status and the exact vault addresses we need to watch:

 typescript import { LIQUIDITY_STATE_LAYOUT_V4 } from '@raydium-io/raydium-sdk'; export interface PoolState { status: string; baseMint: string; quoteMint: string; baseVault: string; quoteVault: string; baseDecimal: number; quoteDecimal: number; swapBaseInAmount: bigint; swapQuoteOutAmount: bigint; } export function decodeRaydiumPool(data: Buffer): PoolState | null { try { if (data.length < LIQUIDITY_STATE_LAYOUT_V4.span) { console.warn(`Unexpected buffer size: ${data.length} bytes`); return null; } const decoded = LIQUIDITY_STATE_LAYOUT_V4.decode(data); return { status: decoded.status.toString(), baseMint: decoded.baseMint.toBase58(), quoteMint: decoded.quoteMint.toBase58(), baseVault: decoded.baseVault.toBase58(), quoteVault: decoded.quoteVault.toBase58(), baseDecimal: Number(decoded.baseDecimal), quoteDecimal: Number(decoded.quoteDecimal), swapBaseInAmount: BigInt(decoded.swapBaseInAmount.toString()), swapQuoteOutAmount: BigInt(decoded.swapQuoteOutAmount.toString()), }; } catch (error) { console.error('Error decoding pool buffer:', error); return null; } } Step 2: Real-Time WebSocket Subscriptions & Drop Detection Once baseMint, quoteMint, and quoteVault are resolved, sentinel-solana opens two onAccountChange WebSocket listeners with confirmed commitment: Pool Account Listener: Watches the main AMM account for unexpected status changes or pool freezes. Quote Vault Listener: Decodes incoming SPL Token buffer updates on the fly via @solana/spl-token's AccountLayout and compares each new balance against the previous state using BigInt precision. TypeScript import { Connection, PublicKey } from '@solana/web3.js'; import { AccountLayout } from '@solana/spl-token'; import { decodeRaydiumPool } from './parser'; import * as dotenv from 'dotenv'; dotenv.config(); const RPC_URL = process.env.HELIUS_RPC_URL!; const WSS_URL = process.env.HELIUS_WSS_URL!; const connection = new Connection(RPC_URL, { wsEndpoint: WSS_URL, commitment: 'confirmed', }); // Example: Raydium V4 SOL/USDC Pool const TARGET_POOL_ADDRESS = new PublicKey('58oQChx4yWmvKdwLLZzBi4ChoCc2fqCUWBkwMihLYQo2'); const DROP_THRESHOLD_PERCENT = 10; async function startPoolSentinel() { console.log(`Initializing Sentinel-Solana for pool: ${TARGET_POOL_ADDRESS.toBase58()}`); const initialAccountInfo = await connection.getAccountInfo(TARGET_POOL_ADDRESS); if (!initialAccountInfo) { console.error('Pool not found on-chain.'); return; } const poolState = decodeRaydiumPool(initialAccountInfo.data); if (!poolState) return; console.log('Pool successfully decoded:'); console.log(` Base Mint: ${poolState.baseMint}`); console.log(` Quote Mint: ${poolState.quoteMint}`); console.log(` Quote Vault (Liquidity): ${poolState.quoteVault}`); let lastQuoteBalance: bigint | null = null; // 1. Monitor pool status changes connection.onAccountChange( TARGET_POOL_ADDRESS, (accountInfo) => { const updated = decodeRaydiumPool(accountInfo.data); if (!updated) return; if (updated.status !== poolState.status) { console.warn(`[ALERT] Pool status changed! Was: ${poolState.status} -> Now: ${updated.status}`); poolState.status = updated.status; } }, 'confirmed' ); // 2. Monitor Quote Vault liquidity outflows const quoteVaultPubkey = new PublicKey(poolState.quoteVault); connection.onAccountChange( quoteVaultPubkey, (vaultInfo) => { const tokenAccountData = AccountLayout.decode(vaultInfo.data); const currentBalance = tokenAccountData.amount; if (lastQuoteBalance !== null && lastQuoteBalance > 0n && currentBalance < lastQuoteBalance) { const diff = lastQuoteBalance - currentBalance; const dropPercent = Number((diff * 10000n) / lastQuoteBalance) / 100; if (dropPercent >= DROP_THRESHOLD_PERCENT) { console.error( `[CRITICAL ALERT] Sharp liquidity withdrawal detected! Drop by ${dropPercent.toFixed(2)}% ` + `(Previous: ${lastQuoteBalance.toString()}, Current: ${currentBalance.toString()})` ); } } lastQuoteBalance = currentBalance; console.log(`Quote Vault balance updated: ${currentBalance.toString()}`); }, 'confirmed' ); console.log('WebSocket subscriptions active. Waiting for real-time events...'); } startPoolSentinel(); Live Mainnet Output Running the monitor against the mainnet SOL/USDC pool (58oQChx4yWmvKdwLLZzBi4ChoCc2fqCUWBkwMihLYQo2) immediately resolves the vault (HLmqeL62xR1QoZ1HKKbXRrdN1p3phKpxRMb2VVopvBBz) and streams every swap's balance change in real time: Plaintext Initializing Sentinel-Solana for pool: 58oQChx4yWmvKdwLLZzBi4ChoCc2fqCUWBkwMihLYQo2 Pool successfully decoded: Base Mint: So11111111111111111111111111111111111111112 Quote Mint: EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v Quote Vault (Liquidity): HLmqeL62xR1QoZ1HKKbXRrdN1p3phKpxRMb2VVopvBBz WebSocket subscriptions active. Waiting for real-time events... Quote Vault balance updated: 8015896570107 Quote Vault balance updated: 8015898213075 Quote Vault balance updated: 8015947713075 What's Next This architecture provides a low-latency foundation that can be extended with: Instant Alerting: Dispatching critical liquidity drop alerts directly to Telegram or Discord webhooks. Dual-Vault Correlation: Tracking both baseVault and quoteVault simultaneously to distinguish normal arbitrage swaps from one-sided liquidity drains. Custom Program Layouts: Applying the same binary buffer parsing approach with @coral-xyz/borsh to monitor custom Anchor or native Solana contracts. You can check out the source code in the sentinel-solana repository on GitHub. Markdown ## What's Next This architecture provides a low-latency foundation that can be extended with: - **Instant Alerting**: Dispatching critical liquidity drop alerts directly to Telegram or Discord webhooks. - **Dual-Vault Correlation**: Tracking both `baseVault` and `quoteVault` simultaneously to distinguish normal arbitrage swaps from one-sided liquidity drains. - **Custom Program Layouts**: Applying the same binary buffer parsing approach with `@coral-xyz/borsh` to monitor custom Anchor or native Solana contracts. How would you approach real-time anomaly detection and alerting on Solana AMM pools? Feel free to share your thoughts or ask questions about the architecture in the comments below. #solana, #typescript, #web3, #security