services
Get a key

library / Use cases / UC0033

Deposit sweep queue

Find which of thousands of deposit addresses hold enough SOL to sweep. A Node script reads balances 100 at a time at finalized, fills a SQLite queue with states, and leaves every private key to a separate signer.

By Carbium · Exchanges, custodians and on-ramps · UC0033 · updated 2026-11-22

01

Where the keys stay

An exchange that gives each customer a deposit address ends up holding thousands of keypairs. Moving the funds from those addresses into a hot or cold wallet is a sweep, and most of the work in a sweep has nothing to do with signing. It is deciding which addresses hold enough to justify a transaction, in what order to take them, and knowing afterward that the money moved. That part needs public keys only.

The script holds no private key and signs nothing. It reads addresses, writes a queue to SQLite and exits. A separate signing service claims rows from that queue, builds the transfer, signs it and sends it. The split keeps every signing key away from the process that holds the API key and talks to the network. If the scanner host is compromised, the attacker gets the API key and write access to the queue rows. That is why the signer picks the destination itself and reads the balance again before signing.

$A key that can sign a sweep can sign any other transfer from the same address. Keep the signer on a small host, derive or unwrap keys inside an HSM or your own key service, and give the signer only the queue rows it has claimed. A SQLite file is shared only by processes on one host, so a signer on its own host needs the queue behind a small service or in the exchange's shared database.
02

The queue and its states

Each address has one row: its lamport balance, the slot of the read and a state. The scanner sets the state on every pass from the balance it just read and the state it stored last time.

StateMeaningWho sets it
pendingNet balance is at or above the sweep thresholdScanner
claimedA signer has taken the row and is building the transferYour signer
sweptA pending or claimed address now reads under the threshold; lasts one pass, then idleScanner
idleUnder the threshold, nothing queuedScanner
skipOwned by another program or carrying data, so a plain transfer cannot move itScanner

A signer claims work with one statement, UPDATE queue SET state = 'claimed' WHERE addr = ? AND state = 'pending', and checks the changed-row count. Two signers racing for the same row then cannot both win. The scanner writes each row with one upsert that works out the new state inside the statement, so a row a signer claimed stays claimed while the balance stays high, and a sweep in flight is never queued twice.

The swept state is a cross-check. When a claimed address later reads under the threshold, the chain says the funds left, whatever the signer reported. A claimed row that never reaches swept points at a sweep that failed or never landed.

03

The scanner in one file

Pass addresses as arguments, or point ADDRESSES_FILE at a text file with one address per line. With neither, the script takes the fee payers of the newest transactions on a busy program, so a first run has live accounts to read. The settings are CARBIUM_KEY, QUEUE_DB (a SQLite file, in memory when unset), SWEEP_MIN (net lamports worth a sweep, 10,000,000 when unset), PAUSE_MS between calls (7000 when unset) and EVERY_S to repeat the pass on a timer. Each repeat starts EVERY_S seconds after the previous pass ends, so a slow pass never overlaps the next one. With EVERY_S unset the script runs one pass and exits. Calls go through @solana/kit to the RPC endpoint.

main.ts
// UC0033 · Deposit sweep queue// https://carbium.sh/library/usecase/deposit-sweep-queue// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MIT// Read-only: builds a deposit sweep queue. It reads many deposit addresses 100 at a time and queues those worth sweeping. The signer that moves funds lives elsewhere.import { readFileSync } from "node:fs";import { DatabaseSync } from "node:sqlite";import { address, createDefaultRpcTransport, createSolanaRpcFromTransport, type Address } 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 LEVEL = "finalized" as const;const BATCH = 100; // pubkeys per getMultipleAccounts call; 300 is the most a call takes, on Pro onlyconst FEE = 5000n; // base fee of a one-signature transfer, in lamportsconst MIN = BigInt(process.env.SWEEP_MIN ?? 10_000_000); // net lamports worth a sweepconst PAUSE = Number(process.env.PAUSE_MS ?? 7000); // 7000 suits Dev; Business 2010, Pro 260, Free 201000const SYSTEM = "11111111111111111111111111111111";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.QUEUE_DB ?? ":memory:");db.exec("CREATE TABLE IF NOT EXISTS queue (addr TEXT PRIMARY KEY, lamports INTEGER, state TEXT, slot INTEGER)");// One atomic upsert: a row a signer claimed stays claimed while high, and pending or claimed that now reads low becomes swept.const put = db.prepare(`INSERT INTO queue VALUES (?, ?, ?, ?) ON CONFLICT(addr) DO UPDATE SET lamports = excluded.lamports, slot = excluded.slot,  state = CASE WHEN queue.state = 'claimed' AND excluded.state = 'pending' THEN 'claimed'    WHEN queue.state IN ('pending', 'claimed') AND excluded.state = 'idle' THEN 'swept' ELSE excluded.state END`);const say = (e: unknown) => console.error(e instanceof Error ? e.message : e);const sleep = (ms: number) => new Promise((res) => setTimeout(res, ms));// With no addresses given: the fee payers of the newest transactions on a busy program.async function discover(): Promise<string[]> {  const jup = address("JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4");  const sigs = await rpc.getSignaturesForAddress(jup, { limit: 5, commitment: LEVEL }).send();  type Tx = { transaction: { message: { accountKeys: { pubkey: string }[] } } } | null;  const done = await Promise.allSettled(sigs.filter((s) => !s.err).map(async (s) => {    const tx = (await rpc.getTransaction(s.signature, { encoding: "jsonParsed", maxSupportedTransactionVersion: 1, commitment: LEVEL }).send()) as unknown as Tx;    return tx?.transaction.message.accountKeys[0]?.pubkey ?? ""; // null when the node no longer serves it  }));  done.forEach((d) => { if (d.status === "rejected") say(d.reason); });  return done.flatMap((d) => (d.status === "fulfilled" && d.value ? [d.value] : []));}// One retry after twice the pause, long enough for the burst bucket to refill.async function read(batch: Address[]) {  const call = () => rpc.getMultipleAccounts(batch, { encoding: "base64", commitment: LEVEL }).send();  try { return await call(); } catch (e) { say(`retrying in ${PAUSE * 2} ms: ${e instanceof Error ? e.message : e}`); await sleep(PAUSE * 2); return call(); }}async function scan(addrs: Address[]) {  for (let i = 0; i < addrs.length; i += BATCH) {    const batch = addrs.slice(i, i + BATCH);    try {      const r = await read(batch);      const slot = Number(r.context.slot);      batch.forEach((a, j) => {        const acc = r.value[j];        const lamports = acc?.lamports ?? 0n; // no account: never funded, or swept to nothing        let state = "idle";        if (acc && (acc.owner !== SYSTEM || acc.data[0].length > 0)) {          state = "skip";          say(`skip ${a}: owner ${acc.owner}, data ${acc.data[0].length} base64 chars`);        } else if (lamports - FEE >= MIN) state = "pending";        put.run(a, Number(lamports), state, slot);      });    } catch (e) { say(`batch at ${i} failed, rows keep their state until the next pass: ${e instanceof Error ? e.message : e}`); }    if (i + BATCH < addrs.length) await sleep(PAUSE);  }}function summary() {  console.log(JSON.stringify(db.prepare("SELECT state, COUNT(*) AS n, SUM(lamports) AS lamports FROM queue GROUP BY state").all()));  for (const r of db.prepare("SELECT addr, lamports, slot FROM queue WHERE state = 'pending' ORDER BY lamports DESC LIMIT 10").all()) console.log(JSON.stringify(r));}async function main() {  let list = process.argv.slice(2);  if (process.env.ADDRESSES_FILE) list = list.concat(readFileSync(process.env.ADDRESSES_FILE, "utf8").split(/\s+/).filter(Boolean));  if (!list.length) list = await discover();  const addrs = [...new Set(list)].map((a) => address(a)); // throws on a malformed address  if (!addrs.length) { console.error("No addresses to scan."); process.exit(1); }  const pass = async () => { await scan(addrs); summary(); };  await pass();  const every = Number(process.env.EVERY_S ?? 0);  while (every > 0) { await sleep(every * 1000); await pass(); } // the next pass starts EVERY_S after this one ends}main().catch((e) => { say(e); process.exit(1); });

run: CARBIUM_KEY=$CARBIUM_KEY QUEUE_DB=queue.db node main.ts [<deposit-address> ...]

A missing account reads as a zero balance: it was never funded or it was swept to nothing. An account owned by a program other than the system program, or one that holds data, becomes skip, because a plain system transfer cannot move it, and the script prints its owner and data length in base64 characters to stderr so a surprise is easy to read. For the rest, the script subtracts FEE, the 5,000 lamport base fee of a one-signature transfer, and queues the address when what is left reaches SWEEP_MIN. If a separate fee payer covers sweeps, set FEE to 0n.

Sweeping the whole balance leaves zero, which Solana accepts. A partial sweep that leaves a balance under the rent-exempt minimum for an empty account, 890,880 lamports, fails. Plan to take everything or to leave at least that much. After each pass the script prints the count and total by state and the ten largest pending rows.

04

What a pass costs

getMultipleAccounts is one of the account reads, charged 10 cells per pubkey: 1000 cells for 100 pubkeys, and 1001 when the request body passes 4 KiB. One hundred base58 addresses in a JSON body come to roughly 4.7 KB, so the admission charge per call is 1001.

CallCellsFree req/sDev req/sBusiness req/sPro req/s
getAccountInfo, getMultipleAccounts, getTokenAccountBalance10 per pubkey0.51550400

Each rate class absorbs bursts up to 1,024 cells or one second of its rate, whichever is larger. Below Pro that is 1,024 cells, so a 100-pubkey call fits the burst once and the next one waits for the bucket to refill. Pro's burst is one second of its rate, 4,000 cells, which holds three such calls. The req/s above count 10-cell reads, so a plan refills 10 cells for each req/s every second.

PlanCells refilled per secondPause between 100-pubkey calls
Free5201000 ms
Dev1507000 ms
Business5002010 ms
Pro4000260 ms

PAUSE_MS defaults to 7000, the Dev pause. Set it to your plan's figure. A pass over 1,000 addresses is 10 calls of 100, about a minute on Dev. Five thousand addresses are 50 calls, just under six minutes on Dev and under two on Business.

A failed batch is retried once after twice PAUSE_MS. If the retry fails too, the script prints the error and leaves those rows as they were, so the next pass reads them again. Keys on one account share the budget, so a second key adds no capacity. A call may carry up to 300 pubkeys on Pro, the only plan whose burst allows it. On Pro, set the BATCH constant in main.ts to 300; below Pro, leave it at 100. The 260 ms Pro pause in the table is for 100-pubkey calls, so a 300-pubkey batch needs a longer PAUSE_MS, which you find by watching for 429s.

05

Scan only what moved

Most deposit addresses are quiet most of the day, so a full pass over all of them spends cells on balances that did not change. A lighter loop watches for activity and scans only the addresses that saw some, with a slow full pass as the safety net.

logsSubscribe streams transaction logs, all or by mention, and a mention filter names the address a transaction touched. accountSubscribe on the WebSocket sends nothing for a plain SOL wallet, so the logs feed plus a balance read is the pairing for SOL. Exchange deposit alerts builds that feed and the dedupe around it. Feed the addresses it reports into this script's scan and keep a full pass on a timer. For a few hundred known accounts and no queue, SOL balances for many accounts is the smaller version of the read.

06

Reading at finalized

Every read in the script names finalized, because a sweep moves real funds and the read that queues it should be one a fork cannot undo. The cost is small: a deposit reaches the queue a moment later than it would at a lower level.

A balance is a snapshot. A customer can deposit again between the scanner's read and the signer's transfer. The signer should read the balance again just before it signs and sweep what the address holds at that moment.

07

Where it ends

  • No key custody: the script never sees a private key, derives none and signs nothing. Key storage, derivation and the sweep transaction belong to your signer.
  • SOL only. A token deposit sits in a token account, a wallet can own more than one for one mint, and moving it needs the owner's signature plus SOL for the fee. Once you know their addresses, read those accounts with the same batched getMultipleAccounts read and a token-amount check in place of the lamport check, because this loop marks every token account skip.
  • One process and one SQLite file. Several scanners, or a signer on another host, need the queue in one shared store.
  • The queue reflects the last pass. A deposit that arrives after the read waits for the next one.
  • The fee is a constant. A transfer that adds a priority fee or other instructions costs more, and SWEEP_MIN should clear that cost.
  • Screening, risk rules and the choice of destination wallet belong to your ledger.
08

When it goes wrong

what goes wrongwhat to do
A batch fails with a 429 during the first pass over a large address list.PAUSE_MS is shorter than your plan needs between 100-pubkey calls. Set it to your plan's pause. The script retries each failed batch once after twice that pause, and the rows keep their old state if the retry fails too.
Every address shows skip.The owner is not the system program or the account holds data. Read the owner and data length the script prints for each skip row and check that you pass plain system wallet addresses.
A partial sweep fails with an insufficient-funds-for-rent error.An empty account must end at zero or at 890,880 lamports or more. Sweep the whole balance, or leave at least that much behind.
The same address is queued again right after a sweep.The sweep had not finalized when the scanner read. The script reads at finalized, so wait for the next pass, and keep the row claimed until the signer's own transaction finalizes.
A claimed row never turns to swept.The sweep failed or never landed, or the address received more funds than the threshold since. Check the signer's transaction signature with a status read before releasing the row.
09

Questions

Can the scanner hold the private keys too?

It can, but gains nothing from them. Keeping signing keys in a separate service means the process with network access and the API key can be lost without losing funds.

How many addresses can one call read?

The script sends 100 pubkeys per call. A call takes up to 300 pubkeys on Pro, and below Pro the 1024-cell burst caps it at 100.

How do I sweep token deposits?

Read the token accounts with the same batched getMultipleAccounts read, checking the token amount in place of the lamport balance, queue the ones over your threshold, and have the signer move them with the owner's signature. A wallet can own several token accounts for one mint, so list them all.

Why not queue every address on a timer without reading balances?

A transfer costs a fee and a signature for every address, including empty ones. A balance read costs cells and queues only the addresses that justify a transaction.