Custody vault monitor, vendor-neutral
Watch custody vault addresses from the chain alone. A Node script snapshots SOL and token balances every minute, prints each inflow and outflow, and lists new signatures, up to 50 per round, so you can check the custodian's console against the ledger.
What a vault is from outside
A custody vault on Solana is one address, or a handful, that your custodian's signing setup controls. Multisig, MPC and hardware-backed schemes differ in how they approve a transfer. On chain they look the same: an address with a SOL balance, some token accounts and a history of signatures. That shared surface is all a vendor-neutral monitor reads.
The point is a second opinion. The custodian's console tells you what the custodian believes. The ledger tells you what happened. A script that reads only the chain lets finance or security compare the two, and it keeps working if you change custodian, because the only input is the list of vault addresses.
Three signals earn an alert. A balance change in either direction, with outflows marked. A new signature that touches the vault: a failed transaction moves no tokens but still charges its fee to the fee payer, so a failed transaction the vault paid for shows as a small SOL outflow next to a sig line with failed true. Anyone can also send a failed transaction that names the vault. And a token you did not expect, which appears as a new mint in the snapshot.
Tokens need care. A wallet can own more than one token account for one mint, so the monitor adds the accounts up per mint. Token-2022 mints live under a separate program, so the script lists both token programs for each vault.
Why a snapshot loop
Vault addresses are quiet. A hot wallet moves often and a cold vault can sit for weeks. A loop that reads each address once a minute and compares it with the stored snapshot is the smallest thing that works. A dropped connection cannot make it miss a change, because every round compares against saved state and never against what a feed happened to deliver.
A live feed is the upgrade when a minute is too slow. logsSubscribe streams transaction logs by mention, and accountSubscribe sends nothing for a plain SOL wallet, so the pairing is logs plus a balance read. Exchange deposit alerts wires that pairing with its dedupe, and the snapshot here makes a good safety net behind it.
The monitor in one file
Pass the vault addresses as arguments. The script reads CARBIUM_KEY and two optional settings: VAULT_DB, a SQLite file for the snapshots (memory when unset, so every start is a fresh baseline), and POLL_SECONDS, the pause between rounds (60 when unset). Set VAULT_DB for any real run.
// UC0034 · Custody vault monitor, vendor-neutral// https://carbium.sh/library/usecase/custody-vault-monitor-vendor-neutral// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MIT// Read-only vault monitor: snapshots SOL and token totals of custody addresses, prints each change and each new signature.import { DatabaseSync } from "node:sqlite";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 vaults = process.argv.slice(2);if (!vaults.length) { console.error("Usage: node main.ts <vault-address> [<vault-address> ...]"); process.exit(1); }vaults.forEach((v) => address(v)); // throws on a malformed addressconst LEVEL = "finalized" as const;const PAUSE = Number(process.env.POLL_SECONDS ?? 60) * 1000;const TOKEN_PROGRAMS = ["TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA", "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb"];const rpc = createSolanaRpcFromTransport(createDefaultRpcTransport({ url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh", headers: { "x-api-key": key } }));const db = new DatabaseSync(process.env.VAULT_DB ?? ":memory:");db.exec("CREATE TABLE IF NOT EXISTS snap (vault TEXT, asset TEXT, v TEXT, PRIMARY KEY (vault, asset))");const put = db.prepare("INSERT OR REPLACE INTO snap VALUES (?, ?, ?)");const say = (o: object) => console.log(JSON.stringify(o));type Parsed = { parsed: { info: { mint: string; tokenAmount: { amount: string } } } };async function totals(vault: string) { // SOL plus one sum per mint, over every token account in both programs const owner = address(vault), sums = new Map<string, bigint>(); sums.set("SOL", (await rpc.getBalance(owner, { commitment: LEVEL }).send()).value); for (const p of TOKEN_PROGRAMS) { const r = await rpc.getTokenAccountsByOwner(owner, { programId: address(p) }, { encoding: "jsonParsed", commitment: LEVEL }).send(); for (const a of r.value) { const i = (a.account.data as unknown as Parsed).parsed.info; sums.set(i.mint, (sums.get(i.mint) ?? 0n) + BigInt(i.tokenAmount.amount)); } } return sums;}async function check(vault: string) { const old = db.prepare("SELECT asset, v FROM snap WHERE vault = ?").all(vault); const first = old.length === 0; const last = old.find((r) => r.asset === "#sig")?.v as string | undefined; const now = await totals(vault); // every read comes before any write: a failed read leaves the snapshot alone const page = await rpc.getSignaturesForAddress(address(vault), { limit: first ? 1 : 50, commitment: LEVEL, ...(last ? { until: signature(last) } : {}) }).send(); const before = new Map(old.filter((r) => r.asset !== "#sig").map((r): [string, bigint] => [String(r.asset), BigInt(String(r.v))])); if (first) say({ vault, baseline: true, assets: now.size, sig: page[0]?.signature }); for (const asset of new Set([...before.keys(), ...now.keys()])) { const was = before.get(asset) ?? 0n, after = now.get(asset) ?? 0n; if (!first && after !== was) say({ vault, asset, kind: after < was ? "outflow" : "inflow", before: was.toString(), after: after.toString() }); put.run(vault, asset, after.toString()); } if (!first) for (const s of [...page].reverse()) say({ vault, sig: s.signature, slot: Number(s.slot), failed: s.err !== null }); if (page[0]) put.run(vault, "#sig", page[0].signature);}async function run() { console.log(`watching ${vaults.length} vault(s) every ${PAUSE / 1000} s`); for (;;) { for (const v of vaults) await check(v).catch((e) => console.error(`${v}: ${e instanceof Error ? e.message : e}`)); await new Promise((r) => setTimeout(r, PAUSE)); }}void run();
run: CARBIUM_KEY=$CARBIUM_KEY VAULT_DB=vaults.db node main.ts <vault-address> [<vault-address> ...]
The first round for a vault stores a baseline and prints one line with the newest signature. Later rounds read getBalance and getTokenAccountsByOwner for both token programs, compare the totals with the stored ones and print one JSON line per change. Amounts are strings of base units: lamports for SOL, raw token amounts for a mint. A mint whose accounts all closed shows as an outflow to zero.
Signatures use a cursor. The script stores the newest signature it has listed and asks getSignaturesForAddress for everything after it with until, so a round lists only what is new, oldest first, with a failed flag.
Every call names finalized, so an alert rests on the same level a curl check reads.
A failed read changes nothing. The script reads all of a vault's balances and signatures before it writes the snapshot, so a 429 or a half-read token list never looks like a balance of zero and never raises a false outflow. Vaults are read one after another, each on its own, and a vault that fails is retried next round while the others carry on.
What the alerts say
| Line | Meaning | Check first |
|---|---|---|
| outflow | SOL or a mint total dropped since the last round | Match the amount to an approved withdrawal in the custodian's console |
| inflow | A total rose | Confirm the sender, and look for unknown mints sent to the vault |
| sig, failed false | A transaction touching the vault landed | Open it with getTransaction and read who signed |
| sig, failed true | A transaction touching the vault failed | Treat it as an attempt. No tokens moved, and the SOL fee left the vault if the vault paid it |
A signature that touches the vault is not always a withdrawal. Anyone can send a transfer to your address or list it in an instruction, and it lands in the same list. The balance diff tells inflow from outflow, and the signature line tells you when to look.
To explain a signature, call getTransaction with maxSupportedTransactionVersion set to 1. Mainnet carries version 1 transactions, and with the setting absent or 0 getTransaction answers -32015 for one. The kit 8.6.0 types accept 1 without a cast.
Calls per round
Each vault takes four reads per round: getBalance, one getTokenAccountsByOwner for each token program, and one getSignaturesForAddress. The signatures call costs 50 cells, with limits of 0.24, 1.2, 100 and 500 req/s on Free, Dev, Business and Pro.
With 60 s rounds, N vaults need N/60 signature calls a second. On the signatures call alone, Free carries 14 vaults and Dev 72 at that pause. A longer POLL_SECONDS stretches it: a cold vault read every ten minutes uses a tenth of that budget.
An alert that needs a closer look costs one getTransaction, also 50 cells. Limits are per account, so a second key adds no room. To read the SOL balance of a long list of addresses in one call, see SOL balances for many accounts.
Where it ends
- History: getSignaturesForAddress reaches back 30 days at most, from Carbium's own address index. An empty page past that is the index's age limit, so it says nothing about older transactions. The monitor starts at the moment you start it and rebuilds no earlier history.
- One page per round: up to 50 new signatures per vault. A busier address loses the older ones between two rounds. Page with before if your volume needs it.
- Detection only: the script reads and signs nothing. It cannot freeze a vault or reject a transfer. Approval rules stay with the custodian.
- Netting: a deposit and a withdrawal of equal size inside one round cancel in the totals. Only the signature lines show them.
- Value: the script compares raw amounts. It knows no prices, no per-asset threshold and no fiat limit. Add them in your code.
- Delivery: it prints JSON lines. Routing them to a pager or a chat channel, and noticing when the script itself stops, is yours.
- Off-chain moves: transfers between customers inside the custodian's own books never reach the chain, so no chain monitor sees them.
- Availability: it runs as one process on one SQLite file with no failover, so a stopped host stops the watch.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| A withdrawal made while the script was down never alerts. | Run with VAULT_DB set to a file. The stored snapshot then shows the change as one diff on the first round after the restart, and the signature cursor lists what landed. The in-memory default starts a new baseline and hides it. |
| sig lines appear but no outflow line. | The transaction netted to zero in the round, or it touched the vault without moving its funds. Open it with getTransaction and read the balance changes. |
| getTransaction answers null for a signature the list shows. | Signature pages come from an address index that reaches below the validator's ledger floor, so an older listed signature can come back null. Handle null, and expect the newest signatures to read. |
| getTransaction answers -32015. | The transaction is version 1. Pass maxSupportedTransactionVersion: 1 with an encoding. |
| A long vault list prints 429 errors. | Each vault spends one 50-cell signatures call per round. The 429 carries a retry-after hint, the vault keeps its snapshot and the next round retries it. Raise POLL_SECONDS or move up a plan. |
Questions
Does it work with any custodian?
It reads addresses, so yes. You need the vault addresses from your custodian, and per-customer deposit addresses count as vaults too. Nothing in the script depends on how the vault is signed.
Why poll instead of subscribe?
Vault balances change rarely, and a snapshot compare survives a dropped socket and a restart. Add a logs subscription when a minute is too slow, and keep the snapshot as the check behind it.
Can it tell me who signed a transfer?
Not from the balance diff. Open the signature with getTransaction, at 50 cells, and read the signers in the account keys. Set maxSupportedTransactionVersion to 1.
Why finalized for an alert?
An alert should rest on a settled ledger, so a balance change that later falls away never pages anyone. Change LEVEL if your policy wants an earlier read.