services
Get a key

library / Blockchain ideas / BI0006

Multi-address deposit monitor

Watch many deposit addresses over one Carbium WebSocket, fetch each hit with getTransaction and credit every transfer once in SQLite, with costs per plan, a path for lists that outgrow it and a runnable main.ts.

By Carbium · Payment tools · BI0006 · updated 2026-11-22

01

Who uses it

An exchange gives each customer a deposit address and credits the account when funds land on it. The same job shows up in a checkout that issues one address per invoice, a payroll tool that watches contractor wallets and a game shop that takes tokens for items. The list can hold ten addresses or ten thousand, and the question stays the same: how do you hear about an incoming transfer without reading every block yourself?

The code below handles the first few hundred addresses on one machine. It opens one socket, subscribes once per address, looks up each hit with one call and writes the credit to a SQLite table that refuses a second credit for the same transfer. A hackathon team can point it at wallets of their own, send themselves a transfer and watch the row appear.

02

What it records

Each deposit is one row. A deposit is a positive balance change on a watched address in a transaction that succeeded.

ColumnWhere it comes fromExample
Signaturevalue.signature in the logsNotificationthe transaction id you paste into an explorer
Addressthe watched wallet or token accountthe address you handed to a customer
MintSOL, or mint from postTokenBalancesSOL or a token's mint address
Amountpost balance minus pre balance, as an integer string1500000000 lamports is 1.5 SOL
Slotslot from getTransactionthe newest row per address is the restart cursor

The monitor reads the transaction's balance arrays, so it sees system transfers, token transfers and any program that moves funds in. The primary key on signature, address and mint turns a second sighting into a no-op. One transfer can reach you twice, from the stream and from a restart backfill, and a transaction that mentions two watched addresses arrives once per subscription.

$Amounts are stored as integer text. Raw token amounts can pass 2^53, so the code holds them as bigint and never as a float.
03

The build

The monitor is one file on @solana/kit and what Node 24 ships, with node:sqlite for the table. It is read-only: no private key, nothing sent.

  1. Open one WebSocket to wss://services.carbium.sh with the key as ?api-key=.
  2. For each address send logsSubscribe with { mentions: [address] } at commitment finalized. A subscription takes one mention, so 200 addresses are 200 subscriptions on the same socket. Each reply carries a subscription id or a refusal, and a refusal is free.
  3. On every logsNotification with err null, queue the signature if it has not been seen.
  4. Every 5 seconds take one signature and call getTransaction over https://services.carbium.sh at commitment finalized and encoding jsonParsed.
  5. Subtract pre from post balances for SOL and for tokens. For every watched address with a positive change, insert a row and print it. An insert that changes nothing was already credited.
  6. When the socket opens, call getSignaturesForAddress for each address that already has a deposit, with until set to that deposit's signature, and queue the results. This closes the gap left by a restart or a dropped socket.

The code listens for logs that mention the address because accountSubscribe stays silent for a plain SOL wallet on Carbium, and most deposit addresses are plain SOL wallets.

SPL tokens need one extra step. A token transfer lists the source and destination token accounts and the sender's authority, and it leaves out the wallet that owns the destination. Subscribe to the destination token account, the associated token account for each mint you accept. The code takes wallets and token accounts in one list. SPL token balance reads one such account.

main.ts
// BI0006 · Multi-address deposit monitor// https://carbium.sh/library/blockchainideas/multi-address-deposit-monitor// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { DatabaseSync } from "node:sqlite";import { createDefaultRpcTransport, createSolanaRpcFromTransport, isSolanaError } from "@solana/kit";import { SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR, type Address, type 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 = new Set(process.argv.slice(2)); // wallets for SOL, token account addresses for SPL tokensif (watched.size === 0) {  console.error("Usage: node main.ts <address> [address ...]");  process.exit(1);}const WS_URL = `${process.env.CARBIUM_WS_URL ?? "wss://services.carbium.sh"}/?api-key=${key}`;const rpc = createSolanaRpcFromTransport(  createDefaultRpcTransport({ url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh", headers: { "x-api-key": key } }),);const GAP_MS = Number(process.env.GAP_MS ?? 5000); // 5 s keeps getTransaction under Free's 0.24 req/sconst db = new DatabaseSync(process.env.DEPOSIT_DB ?? "deposits.db");db.exec("CREATE TABLE IF NOT EXISTS deposits (sig TEXT, addr TEXT, mint TEXT, amount TEXT, slot INTEGER, PRIMARY KEY (sig, addr, mint))");const insert = db.prepare("INSERT OR IGNORE INTO deposits VALUES (?, ?, ?, ?, ?)");const last = db.prepare("SELECT sig FROM deposits WHERE addr = ? ORDER BY slot DESC LIMIT 1");const queue: string[] = [];const seen = new Set<string>();let pausedUntil = 0;const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));async function handle(sig: string): Promise<void> {  // jsonParsed lists every account key, so the balance arrays line up with it  const tx: any = await rpc.getTransaction(sig as Signature, { commitment: "finalized", encoding: "jsonParsed", maxSupportedTransactionVersion: 1 }).send();  if (!tx?.meta || tx.meta.err) return;  const m = tx.meta;  const keys = tx.transaction.message.accountKeys.map((k: { pubkey: string }) => k.pubkey as string);  const rows: [string, string, bigint][] = keys.map((k: string, i: number) => [k, "SOL", BigInt(m.postBalances[i]) - BigInt(m.preBalances[i])]);  for (const b of m.postTokenBalances ?? []) {    const pre = m.preTokenBalances?.find((p: { accountIndex: number }) => p.accountIndex === b.accountIndex)?.uiTokenAmount.amount ?? "0";    const acct: string = keys[b.accountIndex];    rows.push([watched.has(acct) ? acct : b.owner ?? "", b.mint, BigInt(b.uiTokenAmount.amount) - BigInt(pre)]);  }  for (const [addr, mint, amount] of rows) {    if (!watched.has(addr) || amount <= 0) continue;    if (Number(insert.run(sig, addr, mint, String(amount), Number(tx.slot)).changes) > 0) console.log(`DEPOSIT ${addr} ${mint} +${amount} ${sig}`);  }}function enqueue(sig: string): void {  if (!seen.has(sig)) { seen.add(sig); queue.push(sig); }}function connect(): void {  const ws = new WebSocket(WS_URL);  ws.onopen = async () => {    [...watched].forEach((addr, i) => ws.send(JSON.stringify({      jsonrpc: "2.0", id: i + 1, method: "logsSubscribe", params: [{ mentions: [addr] }, { commitment: "finalized" }],    })));    for (const addr of watched) { // catch up on what landed while the socket was down      const row = last.get(addr);      if (!row) continue;      try {        for (const s of await rpc.getSignaturesForAddress(addr as Address, { until: row.sig as Signature, limit: 100, commitment: "finalized" }).send()) if (!s.err) enqueue(s.signature);      } catch (e) { console.error("backfill failed:", e instanceof Error ? e.message : e); }      await sleep(GAP_MS);    }  };  ws.onmessage = (ev) => {    const msg = JSON.parse(String(ev.data));    if (typeof msg.id === "number") { console.log(msg.error ? `subscribe refused: ${msg.error.message}` : `subscribed, id ${msg.result}`); return; }    if (msg.method === "logsNotification" && !msg.params.result.value.err) enqueue(msg.params.result.value.signature);  };  ws.onclose = () => setTimeout(connect, 2000);  ws.onerror = () => ws.close();}setInterval(async () => {  const sig = Date.now() < pausedUntil ? undefined : queue.shift();  if (!sig) return;  try { await handle(sig); } catch (e) {    queue.unshift(sig);    const wait = isSolanaError(e, SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR) && e.context.statusCode === 429 ? Number(e.context.headers.get("retry-after") ?? 5) : 5;    pausedUntil = Date.now() + wait * 1000;    console.error("getTransaction failed, will retry:", e instanceof Error ? e.message : e);  }}, GAP_MS);console.log(`watching ${watched.size} addresses`);connect();

run: CARBIUM_KEY=<YOUR_KEY> node main.ts <address> [<address> ...]

The same pattern with an err filter drives the Failed-mint monitor.

04

What it costs

A logs-mentions subscription opens at 25 credits and then costs 20 credits per MiB sent. Deposit addresses are quiet, so the traffic part is small: if a notification runs 2 KiB, a MiB is about 500 notifications. The opening charge is the figure to watch, because it repeats on every reconnect.

getTransaction and getSignaturesForAddress cost 50 cells each. The last column shows what opening 100 subscriptions takes from the plan's credits.

PlanCreditsgetTransaction req/sgetSignaturesForAddress req/sOpening 100 subscriptions
Free ($0)500K once, at sign-up0.240.242,500 credits, 0.5% of the grant
Dev ($20)10M per month1.21.20.025% of the month
Business ($250)50M per month51000.005% of the month
Pro ($500)200M per month255000.00125% of the month

Every successful transaction that mentions a watched address costs one lookup, whether it moved funds in or out, so the rate you need is the activity of the whole list. On Free, 0.24 req/s is one lookup every 4 seconds or so, and the 5 second gap in the code stays under it. On Dev set GAP_MS=1000 for a gap that fits 1.2 req/s. Limits are per account, so other tools on the same keys draw on the same budget. Free carries 5 sockets and the monitor uses one.

Each reconnect opens every subscription again. On 1,000 addresses that is 25,000 credits per reconnect, 0.25% of a Dev month. The 2 second delay in the close handler bounds how often a flapping link can do it.

05

When the list grows

  • One subscription per address, as built here. The credit shows as soon as the transaction finalizes. Subscription counts are capped per account by tier. A refused subscription is free, so you find your ceiling by opening them and reading the refusals.
  • Poll getSignaturesForAddress for each address. There is no subscription cap, and at a plan's ceiling the loop covers req/s times 60 addresses per minute: 14 on Free, 72 on Dev, 6,000 on Business and 30,000 on Pro, with nothing else on the account calling it. Poll only the addresses with an open deposit session and those numbers stretch further.
  • The gRPC stream, Carbon Stream, at https://services.carbium.sh:9443 with the key in x-token. It opens on Dev, Business and Pro, and Free is off. Its server-side filters suit a list where the subscription cap is your limit. The code here does not use it.
06

Where it ends

  • The monitor reads and records. Sweeping funds to a hot wallet needs signing and belongs to a separate program with its own keys.
  • A token transfer into a token account you did not list does not mention your wallet, so no subscription fires for it. Derive the associated token account for every mint you accept.
  • Amounts are net per transaction. A watched address that sends and receives in one transaction shows the difference, and a fee payer shows its change after the fee.
  • Only transactions that landed with err null count. A transaction rejected in preflight or one whose blockhash expired leaves no log.
  • History reaches back 30 days at most. The backfill takes 100 signatures per address and cannot recover a gap older than the index.
  • The seen set grows for the life of the process. Bound it before you run this for weeks.
07

When it goes wrong

what goes wrongwhat to do
A subscribe reply is a refusal, or the socket closes straight away.Check CARBIUM_KEY, then the subscription count against your tier's cap. A refusal is free. Move the surplus addresses to a polling loop.
A token transfer to a customer never shows up.You listed the owner wallet. A token transfer does not mention it, so list the token account that receives the mint and the subscription fires.
getTransaction returns null, so the signature is skipped.The code returns without a row. Finalized is 0 to 1 slots behind processed, so a null is rare. Restart the monitor and the backfill queues again anything after the last stored deposit.
getTransaction answers 429.The loop reads retry-after, puts the signature back and pauses. If it repeats, raise GAP_MS to match your plan's req/s and check what else on the account calls, since the limit is shared across its keys.
An address with no earlier deposit loses transfers that landed while the monitor was down.No stored row means no cursor, so the backfill skips it. Start the monitor before the address goes to a customer, or seed its first page of getSignaturesForAddress yourself.
08

Questions

Can one accountSubscribe watch many SOL wallets?

Not for a plain SOL wallet. accountSubscribe stays silent for one on Carbium, so use logsSubscribe with mentions and let getTransaction supply the amount.

Why credit at finalized?

Finalized sits 0 to 1 slots behind processed, so the wait is short and a finalized deposit cannot be rolled back. Crediting from one level keeps the rule simple.

How many addresses can one account watch?

Subscription counts are capped per account by tier. Free carries 5 sockets and the monitor needs one. Past the cap, poll or move to the gRPC stream.

How far back can the backfill reach?

getSignaturesForAddress comes from Carbium's own address index, which keeps up to 30 days. An empty page past that is the index's age limit and says nothing about the address's first transaction.