services
Get a key

library / Use cases / UC0045

Protocol vault drain alert

Detect a vault drain at confirmed commitment and pull the transaction behind it, with its signers and the accounts that received the SOL. Then work from that evidence to the missing check and a test that proves the fix.

By Carbium · Compliance, risk and monitoring · UC0045 · updated 2026-11-22

01

What a drain leaves behind

A program vault loses SOL in one of two ways. A System Program transfer signed by the vault's authority shows up as a transfer instruction. A program that owns the vault account can also debit its lamports directly and credit another account, and then no transfer instruction exists at all. A bug in the owning program can take the second route, so the watcher below takes the drain amount from the balance arrays of the transaction, which show the change on either route, and uses the parsed instructions only to name the programs that ran.

Every confirmed transaction carries preBalances and postBalances, one entry per account key and in the same order as the key list. The vault's post value minus its pre value is the drain. The accounts whose values rose are the receivers. The signers, together with the program ids of the top-level and inner instructions, show which code path ran.

Replicating the drain means replaying the transaction's inputs against a private copy. Dump the program binary with solana program dump, then start solana-test-validator with --bpf-program for that binary and --account (or --clone) for the vault and every other account the transaction listed. Send the same instruction data with the same account order, swap the attacker's signer keys for local keypairs you control (and update any account that held them to match), because a local validator cannot reuse the original signatures, and watch the vault fall. When it falls on your copy you hold a failing test. After the fix ships, the same transaction must fail on the same copy.

!Run the replay only on your private copy. A vulnerable program on mainnet stays vulnerable until the fix is deployed, so the drain instructions never go to the live program.
02

Pick what the vault is

Vault holdsWatch withEvidence in the transaction
SOL in a plain accountlogsSubscribe with a mentions filterpreBalances and postBalances
SPL tokens in a token accountlogsSubscribe on the token account, getTokenAccountBalance for a spot readpreTokenBalances and postTokenBalances
Several vaultsOne mentions subscription per vaultThe same arrays, one transaction per vault

For a plain SOL account, accountSubscribe sends nothing, so a mentions subscription on logsSubscribe is the way to hear about it. It fires for every transaction that lists the vault, whether lamports moved or not, so the script acts only on a balance change.

When a token vault pays out to an attacker's existing token account, the transaction lists the vault's token account, the attacker's token account and the vault's authority, and the attacker's wallet never appears. To name that wallet, take the owner on the receiving account's entry in postTokenBalances, or data.parsed.info.owner from a getAccountInfo read with jsonParsed encoding. The owner field on the account itself names the Token Program. One wallet can also hold more than one token account for the same mint, so match on the account you saw.

03

The watcher

The script takes the vault address as its argument, and optionally the signature of a drain that has already happened. It opens logsSubscribe with a mentions filter at confirmed commitment, so each transaction that lists the vault in its account keys produces one notification carrying a signature. For each signature it calls getTransaction with encoding: jsonParsed, commitment: confirmed and maxSupportedTransactionVersion: 1. Mainnet carries v1 transactions, and a lookup that leaves the value out answers -32015.

main.ts
// UC0045 · Protocol vault drain alert// https://carbium.sh/library/usecase/protocol-vault-drain-alert// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MIT// Read-only: flags a large SOL drop from a vault, then names the signers, programs and receivers.import { address, createDefaultRpcTransport, createSolanaRpcFromTransport, signature } from "@solana/kit";const key = process.env.CARBIUM_KEY;if (!key) { console.error("Set CARBIUM_KEY to your Carbium API key."); process.exit(1); }const vault = process.argv[2];if (!vault) { console.error("Usage: node main.ts <vault address> [drain signature]"); process.exit(1); }const drain = process.argv[3];const wsUrl = new URL(process.env.CARBIUM_WS_URL ?? "wss://services.carbium.sh");wsUrl.searchParams.set("api-key", key);const rpc = createSolanaRpcFromTransport(createDefaultRpcTransport({  url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh", headers: { "x-api-key": key } }));const dropLamports = BigInt(process.env.DROP_SOL ?? "10") * 10n ** 9n;const lookback = Number(process.env.LOOKBACK ?? 5);type Ix = { programId: string };type Tx = { meta: { err: unknown; preBalances: (number | bigint)[]; postBalances: (number | bigint)[]; innerInstructions?: { instructions: Ix[] }[] } | null;  transaction: { message: { accountKeys: { pubkey: string; signer: boolean }[]; instructions: Ix[] } } };const seen = new Set<string>();const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));const sol = (l: bigint) => `${l < 0n ? "-" : "+"}${(l < 0n ? -l : l) / 10n ** 9n}.${((l < 0n ? -l : l) % 10n ** 9n).toString().padStart(9, "0")} SOL`;async function fetchTx(sig: string): Promise<Tx | null> {  for (let i = 0; i < 4; i++) {    const tx = (await rpc.getTransaction(signature(sig), { encoding: "jsonParsed", commitment: "confirmed", maxSupportedTransactionVersion: 1 }).send()) as unknown as Tx | null;    if (tx) return tx;    await sleep(500);  }  return null;}async function check(sig: string) {  if (seen.has(sig)) return;  seen.add(sig);  const tx = await fetchTx(sig);  const meta = tx?.meta;  if (!tx || !meta) return console.log(`${sig.slice(0, 12)}.. no transaction data (older than the ledger, or not visible yet)`);  if (meta.err) return;  const keys = tx.transaction.message.accountKeys;  const at = keys.findIndex((k) => k.pubkey === vault);  if (at < 0) return;  const delta = (i: number) => BigInt(meta.postBalances[i]!) - BigInt(meta.preBalances[i]!);  console.log(`${sig.slice(0, 12)}.. vault ${sol(delta(at))}`);  if (-delta(at) < dropLamports) return;  const inner = (meta.innerInstructions ?? []).flatMap((g) => g.instructions);  const programs = new Set([...tx.transaction.message.instructions, ...inner].map((x) => x.programId));  const receivers = keys.map((k, i) => ({ k: k.pubkey, d: delta(i) })).filter((r) => r.d > 0n).sort((a, b) => (b.d > a.d ? 1 : -1)).slice(0, 3);  console.log(`ALERT drain ${sig}`);  console.log("  signers:", keys.filter((k) => k.signer).map((k) => k.pubkey).join(", "));  console.log("  programs:", [...programs].join(", "));  for (const r of receivers) console.log(`  received ${sol(r.d)} at ${r.k}`);}const safe = (sig: string) => check(sig).catch((e) => { seen.delete(sig); console.error(sig.slice(0, 12), "failed:", String(e)); });async function scan() {  const sigs = await rpc.getSignaturesForAddress(address(vault!), { limit: lookback }).send();  for (const s of [...sigs].reverse()) if (!s.err) await safe(s.signature);}function watch() {  const ws = new WebSocket(wsUrl);  ws.onopen = () => {    ws.send(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "logsSubscribe", params: [{ mentions: [vault] }, { commitment: "confirmed" }] }));    scan().catch((e) => console.error("scan failed:", String(e)));  };  ws.onmessage = (ev) => {    const m = JSON.parse(String(ev.data));    if (m.error) console.error("subscribe failed:", m.error.message);    if (m.method === "logsNotification" && !m.params.result.value.err) void safe(m.params.result.value.signature);  };  ws.onerror = () => ws.close();  ws.onclose = () => { console.error("socket closed, reconnecting"); setTimeout(watch, 2000); };}console.log(`watching ${vault}, alert on drops of ${dropLamports / 10n ** 9n} SOL or more`);if (drain) void safe(drain);watch();

run: CARBIUM_KEY=$CARBIUM_KEY node main.ts <vault address> [drain signature]

On start and after every reconnect the script also reads the newest LOOKBACK signatures with getSignaturesForAddress (default 5) and checks them oldest first, which closes the gap after a dropped socket. A drain that sits further back is out of that window, so pass its signature as the second argument and the script runs the check on it directly. A seen set keeps one signature from being judged twice, and a lookup that fails is removed from the set so a later scan or a rerun with that signature can try it again.

The check finds the vault in the transaction's accountKeys, subtracts preBalances from postBalances as integer lamports and prints one line. A fall of at least DROP_SOL whole SOL (default 10) prints an alert that lists the signers and the program id of every top-level and inner instruction, followed by the three accounts that gained the most. Failed transactions are skipped, since they move no lamports besides the fee. The script signs and sends nothing.

Each notification costs one getTransaction at 50 cells, and a null answer is retried up to three times, so one signature costs up to four 50-cell getTransaction calls. Each scan costs one getSignaturesForAddress at 50 cells and up to LOOKBACK getTransaction calls at 50 cells each, plus their null retries. The per-plan rates of those two calls cap how busy a vault the watcher can follow.

CallCellsFree req/sDev req/sBusiness req/sPro req/s
getTransaction500.241.2525
getSignaturesForAddress500.241.2100500

A mentions subscription sits in the middle weight tier: 25 credits to open, then 20 credits per MiB sent, and a refused subscription costs nothing. The calls in this script run at confirmed: the subscription and getTransaction set it, and @solana/kit fills it in for getSignaturesForAddress.

04

From alert to fix

  1. Stop further loss with whatever control the program already has: a pause flag, a withdrawal cap, or an upgrade authority that can ship a patched build.
  2. Save the alert output and fetch the full transaction. Note the signers, the program ids and the order of the accounts.
  3. Follow the receiving accounts with getSignaturesForAddress to see where the SOL moved next. The address index reaches back 30 days.
  4. Match the evidence to a missing check using the table below, and reproduce the drain on a private copy.
  5. Write the failing test first, ship the fix, and confirm the same transaction now fails on the copy.
What the transaction showsLikely gapCheck that closes it
The authority account is not among the signersMissing signer checkRequire the authority to sign and compare it with the key stored in state
An account the program should never read, owned by another program or created just beforeMissing owner or address checkVerify the owner and compare the address with the one recorded at setup
A vault PDA that any user's accounts can reachSeeds that do not bind the vault to its ownerDerive the PDA from seeds that include the user or pool and compare the result
An unexpected program id among the inner instructionsUnchecked cross-program call targetCompare the program id with a fixed value before invoking
A payout far above the amount the caller put inUnchecked arithmetic or a stale priceUse checked math and bound every payout by the vault's own accounting

Learning from it means changing what you watch. Set the drop threshold as a share of the vault's balance as well as a fixed amount, watch the program's upgrade authority for a change of key, and keep the transaction that drained you as a permanent regression test. For wider screening of authority keys across mints, see Token authority screening, and for reading a transaction line by line see Transaction explainer.

05

Where it ends

  • The alert arrives after the transaction has landed at confirmed. It reports a drain and cannot stop one. Stopping needs a control inside the program, such as a pause flag or a per-transaction withdrawal cap.
  • getAccountInfo returns current state. The vault's earlier balance comes from preBalances, but data accounts the exploit rewrote have to be rebuilt to their state before the exploit, worked out from the program's state layout and the transactions that wrote them earlier, since the exploit's own instruction data does not hold that state.
  • getSignaturesForAddress pages come from an address index that keeps up to 30 days. An empty page past that marks the index's age limit, and the address may have older transactions. For an old signature the index lists but the node cannot read, the watcher prints no transaction data after its retries and goes on to the next signature.
  • A vault busier than the table above allows loses lookups to 429s. The script prints each failure and drops the signature from seen, but the scan runs only at start and on reconnect and reads only the newest LOOKBACK signatures, so on a busy vault a failed lookup is lost. Rerun the script with that signature as the second argument to check it again, and for a sustained overload use a higher plan or a narrower filter.
  • The script follows SOL only. A token vault needs the same check on preTokenBalances and postTokenBalances, and the owner lookup described earlier.
  • Your plan caps connections and subscriptions per account, and Free carries 5 sockets. Watching many vaults means counting subscriptions before adding more.
06

When it goes wrong

what goes wrongwhat to do
The watcher stays quiet while 135 SOL leaves in many transactions of 5 SOL each.Keep a rolling sum of the vault's falls over a window and alert on the sum as well as on a single transaction.
getTransaction answers null for a signature the scan listed.The signature list reaches below the validator's ledger floor, so older entries can be missing. Treat null as a skipped signature and test the code on the newest ones.
The lookup answers -32015.Pass maxSupportedTransactionVersion: 1 with an encoding. Absent or 0, a v1 transaction or a block holding one is refused.
The alert names a receiving token account that nobody recognises.Take the owner on that account's postTokenBalances entry, or data.parsed.info.owner from a jsonParsed getAccountInfo read.
The socket drops and a drain lands during the gap.Rerun the scan on every reconnect with a LOOKBACK that covers the usual gap, and keep the seen set so repeats are skipped.
The first lookup after a notification returns null.The transaction may not be readable yet at confirmed. Retry a few times a short while apart, as the script does, before giving up.
07

Questions

Can this alert stop a drain in progress?

No. It reads a transaction that has already landed at confirmed. Stopping a drain takes a pause flag, a withdrawal cap or a program upgrade that you control.

Can I replay the drain on mainnet to test my fix?

No. If the program is still vulnerable the replay drains the live vault again. Copy the program and its accounts into a local test validator and replay there.

How far back can I look for the first suspicious transaction?

getSignaturesForAddress reaches back 30 days at most. Older history is not served, so keep your own records of anything you may need to investigate later.

Why read balance arrays when the parsed instructions are available?

A program that owns the vault can debit its lamports directly, and that leaves no transfer instruction to parse. The balance arrays show the change however it was made.