library / Use cases / Exchanges, custodians and on-ramps / UC0105
Exchange reserve tracker
Sum SOL and one token across a set of reserve wallets, with the slot each total was read at. A Node script stores every snapshot in SQLite and prints the change since the last one, ready to set against your customer liabilities.
What a reserve is on chain
An exchange or custodian holds customer assets in a set of wallets: hot wallets that pay withdrawals, cold wallets that sit still, and deposit addresses that have not been swept yet. A reserve figure is the sum of what those wallets hold, set against what the ledger owes customers. The chain supplies the first half of that comparison, and only for the wallets you list.
SOL sits in the lamport balance of the wallet. A token sits in token accounts the wallet owns, and a wallet can own more than one token account for the same mint, so the total for a mint is the sum over all of them. Token accounts by owner shows the lookup the script uses. SOL delegated to a validator moves into a stake account and leaves the wallet's balance, so a reserve that includes it needs those stake account addresses in the list too.
Amounts stay integers: lamports for SOL, and the raw token amount with the mint's decimals beside it. Divide only when you print. A reserve report that rounds early drifts from the ledger by a few units on every run, and the drift looks like a leak.
One read for the SOL total
The SOL total comes from getMultipleAccounts, which answers every address from one slot and returns that slot in its context. That matters for a sum. Reading wallets one after another takes long enough for a slot to pass, and a transfer between two of your own wallets can then be counted twice or missed, so the total moves when no money left. Same-slot multi-account snapshot covers the technique on its own.
The call is sized by plan. getMultipleAccounts charges 10 cells per pubkey, 1000 for 100 pubkeys, and the 1024-cell burst caps a call at 100 pubkeys below Pro. Taking 300 pubkeys in one call is a Pro feature of the method. The script sends at most 100 wallets and exits on a longer list. For a larger set, run one group of 100 per process and keep each group's total with its slot.
Tokens read one wallet at a time. The script calls getTokenAccountsByOwner for each wallet with the mint as the filter and jsonParsed encoding, then adds up the amount of every account returned. Each answer has its own slot, so the script keeps the smallest and the largest and prints the gap between them as spread. A spread of zero means every wallet was read in the same slot.
The tracker in one file
Pass the mint first, then the wallets. The script reads CARBIUM_KEY and two optional settings: RESERVE_DB, a SQLite file (reserve.db when unset), and EVERY_SECONDS, the pause between snapshots (60 when unset). It calls the RPC endpoint through @solana/kit with one client for the whole run.
// UC0105 · Exchange reserve tracker// https://carbium.sh/library/usecase/exchange-reserve-tracker// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MIT// Read-only: totals SOL and one token across reserve wallets, stores each snapshot in SQLite and prints the change since the last.import { DatabaseSync } from "node:sqlite";import { address, createDefaultRpcTransport, createSolanaRpcFromTransport } 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 [mintArg, ...walletArgs] = process.argv.slice(2);if (!mintArg || !walletArgs.length || walletArgs.length > 100) { console.error("Usage: node main.ts <mint> <wallet> [<wallet> ...] (1 to 100 wallets)"); process.exit(1);}const mint = address(mintArg); // address() throws on a malformed valueconst wallets = walletArgs.map((w) => address(w));const LEVEL = "finalized" as const;const EVERY = Number(process.env.EVERY_SECONDS ?? 60);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.RESERVE_DB ?? "reserve.db");db.exec("CREATE TABLE IF NOT EXISTS snap (at TEXT, asset TEXT, slot INTEGER, total TEXT)");const say = (e: unknown) => console.error(e instanceof Error ? e.message : e);type Parsed = { parsed: { info: { tokenAmount: { amount: string } } } };function record(asset: string, lo: bigint, hi: bigint, total: bigint, decimals: number) { const prev = db.prepare("SELECT total FROM snap WHERE asset = ? ORDER BY rowid DESC LIMIT 1").get(asset) as { total: string } | undefined; db.prepare("INSERT INTO snap VALUES (?, ?, ?, ?)").run(new Date().toISOString(), asset, Number(lo), total.toString()); const change = prev ? (total - BigInt(prev.total)).toString() : "first snapshot"; console.log(JSON.stringify({ asset, total: total.toString(), decimals, change, slot: Number(lo), spread: Number(hi - lo) }));}async function snapshot() { try { // one call, one slot for every wallet const r = await rpc.getMultipleAccounts(wallets, { encoding: "base64", commitment: LEVEL }).send(); record("SOL", r.context.slot, r.context.slot, r.value.reduce((s, a) => s + (a?.lamports ?? 0n), 0n), 9); } catch (e) { say(e); } let total = 0n, lo = 0n, hi = 0n; try { // a partial token sum would look like an outflow, so any failure skips the row for (const w of wallets) { const r = await rpc.getTokenAccountsByOwner(w, { mint }, { encoding: "jsonParsed", commitment: LEVEL }).send(); const s = r.context.slot; if (!lo || s < lo) lo = s; if (s > hi) hi = s; for (const a of r.value) total += BigInt((a.account.data as unknown as Parsed).parsed.info.tokenAmount.amount); } const supply = await rpc.getTokenSupply(mint, { commitment: LEVEL }).send(); record(mint, lo, hi, total, supply.value.decimals); } catch (e) { say(`no token total this cycle: ${e instanceof Error ? e.message : e}`); }}void snapshot();setInterval(() => void snapshot(), EVERY * 1000);
run: CARBIUM_KEY=$CARBIUM_KEY RESERVE_DB=reserve.db node main.ts <mint> <wallet> [<wallet> ...]
snapshot runs once at start and then on the timer. It writes one row per asset: a timestamp, SOL or the mint address, the earliest slot read, and the total as text, because a lamport total across many wallets can pass what a JavaScript number holds exactly. Each printed line carries the total, the decimals, the slot, the spread and change, which is the difference from the previous row for that asset, or first snapshot on an empty database.
The two assets are independent. A failed SOL read leaves the token read to run, and the other way round, and each failure prints to stderr. The script only reads: it signs nothing and sends nothing. Replace console.log with a write to your reporting store if you keep one, and keep the SQLite file as the local record of what each run saw.
Which commitment the numbers carry
Every call in the script passes finalized, so each row holds balances that cannot roll back, the figure to put in a report. Drop the option and @solana/kit 8.6.0 sends confirmed on its own, so keep it when you edit the calls. On mainnet today finalized trails the newest slot by one at most, and a reserve read at that level is as fresh as a sixty-second timer needs.
Keep one level for the whole series. A row read at confirmed next to a row read at finalized can show a change that only reflects the level.
What a cycle costs
The SOL read is one call per cycle however many wallets are in it, and its cost grows with the wallet count. It belongs to the account reads class, which has its own rate by plan.
| Call | Used for | Cells | Free req/s | Dev req/s | Business req/s | Pro req/s |
|---|---|---|---|---|---|---|
| getMultipleAccounts | SOL total for up to 100 wallets | 10 per pubkey | 0.5 | 15 | 50 | 400 |
A 100-wallet call spends 1000 of the 1,024-cell burst, the cells of 100 single account reads. At Free's 0.5 req/s that is about 200 seconds of rate to earn back, and at Dev's 15 req/s under 7, so on Free set EVERY_SECONDS above 200 or list fewer wallets. A call that finds its cells spent gets 429. The script prints it, writes no row for that asset and tries again on the next cycle.
The token read adds one call per wallet each cycle, plus one getTokenSupply call for the mint's decimals, so a long wallet list stretches the cycle and widens the spread. Keys on one account share one budget, so a second key adds no capacity. For an hourly or daily proof, set EVERY_SECONDS to 3600 or 86400 and keep the process up under a service manager. The script loops on its own timer, so a scheduler that starts it again each time would leave several copies running.
Where it ends
- Only the wallets you list count. A wallet you forgot, or one created after the run started, is outside the total. The chain cannot tell which addresses belong to you.
- Liabilities live in your ledger. The script gives the asset half of a reserve check. Customer balances, off-chain holdings and any audit attestation stay with you. Custody vault monitor covers watching the vaults themselves.
- One mint per run. Run the script again with another mint and the same RESERVE_DB to keep several assets in one file. Wrapped SOL is a token, so its mint goes through the same path.
- Token reads are not one slot. A transfer between two reserve wallets that lands inside the spread can be counted twice or missed in that cycle, and the next cycle corrects it. Read the spread field before you act on a one-cycle change.
- The series starts at the first run. The script cannot read a balance at a past slot, and the address index behind getSignaturesForAddress reaches back 30 days at most.
- Up to 100 addresses per process, stake accounts included. Token accounts the listed wallets own are found on their own and need no entry, and each further token needs its own run.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| The SOL total falls by one wallet's balance after a sweep. | The sweep sent the funds to a wallet outside the list. An emptied wallet reads as a missing account and counts as zero lamports, so add the sweep's destination to the list and the total comes back on the next cycle. |
| getMultipleAccounts answers 429 on a long wallet list. | The call costs 10 cells per pubkey and spends most of the burst at 100 wallets. Raise EVERY_SECONDS, split the list into smaller groups, or move up a plan. |
| The token line never prints and stderr says no token total this cycle. | One wallet's token read failed, so the script dropped the partial sum. Read the error above it, usually a 429, and lengthen EVERY_SECONDS. |
| Every run prints first snapshot. | RESERVE_DB points at a new file each time. Use a fixed path, because a relative one resolves against the folder you run from. |
| The script exits with the usage line. | It needs the mint first and then 1 to 100 wallets. Below Pro the burst caps one getMultipleAccounts call at 100 pubkeys, so split longer lists across processes. |
Questions
Does this prove an exchange is fully reserved?
It gives the asset side with a slot on each figure. The liability side comes from your own ledger, and an attestation needs both, signed off by whoever audits you.
Why not call getBalance for each wallet?
Separate reads land in different slots, so a move between your own wallets can be counted twice or missed. One getMultipleAccounts call answers all wallets from the same slot.
Can it track several tokens?
Run it once per mint against the same RESERVE_DB. Each asset gets its own rows, keyed by the mint address, and its own change line.
Why does the script print a spread for tokens only?
The SOL read is one call and has one slot. The token read is one call per wallet, so the slots can differ, and the spread tells you how far apart they were.