Exchange deposit alerts
Watch deposit addresses on Solana and credit each customer once. A live logs feed gives the alert, a polling sweep catches what it misses, and a Node script reads the amount from the transaction and deduplicates in SQLite.
What a deposit is on Solana
An exchange or custodian gives each customer a deposit address and credits the account when funds arrive. On Solana a deposit is a balance change inside one transaction. The job has three steps: find every transaction that touches your addresses, read the change for each address, and credit it once.
SOL and tokens arrive differently. SOL changes the lamport balance of the wallet itself. An SPL token lands in a token account, usually the wallet's associated token account for that mint, and the transfer names that token account and leaves out the wallet owner. A feed on the wallet address therefore sees SOL deposits and misses token deposits. To catch tokens, watch the token account for each mint you accept. SPL token balance shows how to find it.
Amounts stay integers in base units: lamports for SOL, and the raw token amount with the mint's decimals for a token. The script credits the net positive change of a transaction for an address, so an outgoing sweep from the same address never counts as a deposit.
A live feed and a polling safety net
The feed is a WebSocket on wss://services.carbium.sh with the key as ?api-key= in the URL. logsSubscribe streams transaction logs, all or by mention. The script subscribes once per address with the mentions filter, and Solana takes one address in each mentions filter, so ten addresses mean ten subscriptions on one socket.
A socket drops, and a notification can arrive while your process is down. So on every connect and once a minute the script lists the latest signatures for each address with getSignaturesForAddress and credits any it has not seen. Both paths call the same credit function and write to the same SQLite table, so a deposit seen twice credits once.
signatureSubscribe sends one confirmation for a signature and then ends. It fits a withdrawal you submitted yourself, where you know the signature. An inbound deposit arrives under a signature you have not seen, so it needs logsSubscribe.
The watcher in one file
Pass the addresses as arguments. The script reads CARBIUM_KEY and two optional settings: DEPOSIT_DB, a SQLite file (in memory when unset), and BACKFILL, the signatures read per sweep (100 when unset). A constant, MISSES (3), sets how many empty or failed answers from getTransaction the script accepts for one signature. RPC goes through @solana/kit, with one client and one socket held for the whole run.
// UC0006 · Exchange deposit alerts// https://carbium.sh/library/usecase/exchange-deposit-alerts// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MIT// Read-only: alerts on deposits to watched Solana addresses. logsSubscribe is the live feed, getSignaturesForAddress the safety net, SQLite the dedupe.import { DatabaseSync } from "node:sqlite";import { SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR, address, createDefaultRpcTransport, createSolanaRpcFromTransport, isSolanaError, 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 watched = process.argv.slice(2);if (!watched.length) { console.error("Usage: node main.ts <address> [<address> ...]"); process.exit(1); }watched.forEach((a) => address(a)); // throws on a malformed addressconst LEVEL = "finalized" as const;const MISSES = 3; // empty or RPC-error getTransaction answers accepted before a signature is recorded as unreadableconst BACKFILL = Number(process.env.BACKFILL ?? 100);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 db = new DatabaseSync(process.env.DEPOSIT_DB ?? ":memory:");db.exec("CREATE TABLE IF NOT EXISTS seen (sig TEXT, addr TEXT, slot INTEGER, PRIMARY KEY (sig, addr))");type Bal = { accountIndex: number; mint: string; owner?: string; uiTokenAmount: { amount: string; decimals: number } };type Tx = { slot: number | bigint; transaction: { message: { accountKeys: { pubkey: string }[] } }; meta: { err: unknown; preBalances: (number | bigint)[]; postBalances: (number | bigint)[]; preTokenBalances?: Bal[]; postTokenBalances?: Bal[] } | null };const say = (e: unknown) => console.error(e instanceof Error ? e.message : e);const busy = new Set<string>();const misses = new Map<string, number>();async function credit(addr: string, sig: string) { const id = `${sig}:${addr}`; if (busy.has(id) || db.prepare("SELECT 1 FROM seen WHERE sig = ? AND addr = ?").get(sig, addr)) return; busy.add(id); try { let tx: Tx | null = null, why = "empty answer"; // version 1, so a v1 transaction reads instead of answering -32015 const opts = { encoding: "jsonParsed", maxSupportedTransactionVersion: 1, commitment: LEVEL } as const; try { tx = (await rpc.getTransaction(signature(sig), opts).send()) as unknown as Tx | null; } catch (e) { if (!isSolanaError(e) || isSolanaError(e, SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR)) throw e; why = (e as Error).message; } // 429 and network errors retry uncounted const meta = tx?.meta; if (!tx || !meta) { const n = (misses.get(id) ?? 0) + 1; misses.set(id, n); if (n < MISSES) throw new Error(`transaction ${sig} not readable: ${why} (miss ${n} of ${MISSES}), the next sweep retries`); console.log(JSON.stringify({ addr, sig, unreadable: true, why })); db.prepare("INSERT OR IGNORE INTO seen VALUES (?, ?, ?)").run(sig, addr, -1); return; } const slot = Number(tx.slot), keys = tx.transaction.message.accountKeys.map((k) => k.pubkey); const out = (o: object) => console.log(JSON.stringify({ addr, sig, slot, ...o })); if (!meta.err) { const i = keys.indexOf(addr); const sol = i < 0 ? 0n : BigInt(meta.postBalances[i]!) - BigInt(meta.preBalances[i]!); if (sol > 0n) out({ asset: "SOL", lamports: sol.toString() }); const pre = new Map((meta.preTokenBalances ?? []).map((b): [string, bigint] => [`${b.accountIndex}:${b.mint}`, BigInt(b.uiTokenAmount.amount)])); for (const b of meta.postTokenBalances ?? []) { const delta = BigInt(b.uiTokenAmount.amount) - (pre.get(`${b.accountIndex}:${b.mint}`) ?? 0n); if (delta > 0n && (b.owner === addr || keys[b.accountIndex] === addr)) out({ mint: b.mint, amount: delta.toString(), decimals: b.uiTokenAmount.decimals }); } } db.prepare("INSERT OR IGNORE INTO seen VALUES (?, ?, ?)").run(sig, addr, slot); } finally { busy.delete(id); }}async function sweep() { for (const addr of watched) { try { const page = await rpc.getSignaturesForAddress(address(addr), { limit: BACKFILL, commitment: LEVEL }).send(); console.log(`sweep ${addr}: ${page.length} recent signatures`); for (const s of [...page].reverse()) if (!s.err) await credit(addr, s.signature).catch(say); } catch (e) { say(e); } }}function connect() { const subs = new Map<number, string>(); const ws = new WebSocket(wsUrl); ws.onopen = () => { watched.forEach((a, i) => ws.send(JSON.stringify({ jsonrpc: "2.0", id: i, method: "logsSubscribe", params: [{ mentions: [a] }, { commitment: LEVEL }] }))); console.log(`watching ${watched.length} address(es)`); void sweep(); }; ws.onmessage = (ev) => { const m = JSON.parse(String(ev.data)); if (m.error) return say(m.error.message); if (typeof m.id === "number" && typeof m.result === "number") subs.set(m.result, watched[m.id]!); const v = m.params?.result?.value, addr = subs.get(m.params?.subscription); if (v && addr && !v.err) credit(addr, v.signature).catch(say); }; ws.onclose = () => setTimeout(connect, 2000);}connect();setInterval(() => void sweep(), 60_000);
run: CARBIUM_KEY=$CARBIUM_KEY DEPOSIT_DB=deposits.db node main.ts <deposit-address> [<deposit-address> ...]
credit(addr, sig) is the only place a deposit is decided. It skips a pair it has stored and fetches the transaction with jsonParsed encoding. It sets maxSupportedTransactionVersion to 1, because a version 1 transaction answers an error when the setting is absent or 0. It skips a failed transaction and prints one JSON line for each positive change: SOL as lamports, a token as mint, amount and decimals. It writes the pair to SQLite last. A fetch that fails at the transport, such as a 429 or a dropped connection, leaves the pair unwritten and uncounted, so the next sweep tries again.
A fetch that returns nothing counts as a miss, and so does one the node answers with an RPC error, such as an unsupported transaction version. After MISSES misses the script prints a line with unreadable and the last error as why, and records the pair with slot -1. A signature the node never serves, or always refuses, then stops costing 50 cells on every sweep. The miss count lives in memory, so a restart counts again from zero.
Replace the console.log with your ledger write, and record the signature in the same database transaction as the credit. The script itself only reads: it signs nothing and sends nothing.
When to credit
logsSubscribe, getSignaturesForAddress and getTransaction all name finalized. A call you add to the script must pass LEVEL too.
Finalized is a practical place to credit now. A customer's balance used to wait about 32 slots for finalized. Since the Alpenglow switch on mainnet on 2026-10-21 a slot is about 200 ms and finalized sits 0 to 1 slots behind processed, so the credit lands roughly one slot after the first sighting. To credit earlier, set the LEVEL constant to confirmed and decide in your own risk policy what to release at which level. Take the credit decision from one level and never compare across levels.
What it costs per address
Three costs apply: the subscriptions, the sweep and one transaction read for each new transaction on a watched address. The sweep and the transaction read are metered in calls per second by plan.
| Call | Used for | Cells | Free req/s | Dev req/s | Business req/s | Pro req/s |
|---|---|---|---|---|---|---|
| getSignaturesForAddress | Sweep, once a minute per address | 50 | 0.24 | 1.2 | 100 | 500 |
| getTransaction | One per new transaction on a watched address | 50 | 0.24 | 1.2 | 5 | 25 |
A logs mentions subscription is in the middle weight: it opens at 25 credits, then costs 20 credits per MiB sent, and a refused one is free. Connection and subscription counts are capped per account by tier, and Free carries 5 sockets. The script uses one socket for every address.
The sweep is the part that grows with the address count. One sweep a minute costs the number of addresses divided by 60, in requests per second of getSignaturesForAddress. At the Free rate of 0.24 that is about 14 addresses, and at the Dev rate of 1.2 it is 72. credit calls getTransaction once for every new successful transaction touching the address, outgoing ones included, at 0.24, 1.2, 5 or 25 per second by plan.
Keys on one account share that budget, so a second key adds no capacity. A 429 on getTransaction delays that credit to the next sweep and loses nothing, and it never counts as a miss. The first sweep on a fresh store reads up to BACKFILL transactions per address, which at the Free rate mostly answers 429 and drains over the next sweeps, so a smaller BACKFILL helps. For address sets beyond what the sweep rate allows, the gRPC stream on port 9443 opens on Dev, Business and Pro, with the key in the x-token header.
Where it ends
- One page per sweep: the latest BACKFILL signatures per address, 100 by default. An address with more activity than that between two sweeps, or a process that was down for longer, loses the older ones. Page with before if your volume needs it.
- History: getSignaturesForAddress lists up to 30 days from Carbium's own address index, which reaches below the validator's ledger floor, so a listed signature can still come back null from getTransaction. The script marks it unreadable after 3 misses. Anything older than the index cannot be rebuilt.
- Tokens: the script reads the token account you pass. It does not derive associated token accounts and does not discover mints that customers send by mistake.
- Shared addresses: if customers share one address and are told apart by memo, matching the memo to a customer is your code. The script prints addresses and amounts.
- One process and one SQLite file. Several workers need one shared store, or two of them will credit the same deposit.
- Screening, risk rules and the credit decision belong to your ledger.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| A token deposit never alerts. | The feed watches the address you pass, and a token transfer names the token account. Pass the associated token account for each mint you accept. |
| The same deposit credits twice after a restart. | Run with DEPOSIT_DB set to a file, because the in-memory default forgets what it saw on exit. Write your ledger credit and the signature in one database transaction. |
| accountSubscribe on the wallet never fires. | It stays silent for a plain SOL wallet. Use logsSubscribe with the mentions filter, as the script does. |
| getTransaction answers 429 during a burst of transactions, or on the first sweep of a new store. | It costs 50 cells and has its own rate by plan. The script leaves the signature unrecorded and the next sweep retries it. Lower BACKFILL for the first run, or move up a plan. |
| The transaction is not readable right after the notification, or never, or getTransaction answers an RPC error such as an unsupported transaction version. | The script counts a miss for an empty answer and for an RPC error alike, and the next sweep retries. After 3 misses it prints a line with unreadable and the last error, and records the pair so it stops asking. |
| A sweep returns an empty page for an old address. | getSignaturesForAddress comes from an address index that keeps up to 30 days. An empty page past that is the index's age limit, so it says nothing about the address's first transaction. |
Questions
Can one subscription watch many addresses?
The mentions filter takes one address, so the script opens one subscription per address on a single socket. Each opens at 25 credits, and the account caps subscription counts by tier.
Why does the script read the transaction instead of calling getBalance?
The transaction carries the balances before and after for every account it touched, so you get the change that one transaction made, for SOL and for tokens. Two getBalance reads around a notification can merge two deposits, and they cover SOL only.
Can I recover deposits from before the script started?
Up to the latest BACKFILL signatures per address that getTransaction still serves. An older listed signature can come back null, and the script marks it unreadable after 3 misses.
Why finalized and not confirmed?
A finalized credit waits about one slot longer than a confirmed one before it posts. Change LEVEL to confirmed if your policy releases funds earlier.