library / Integrations / I0008
Postgres deposit matching
A short Node script lists the new finalized transactions for one deposit account, reads the balance change in each, and prints SQL for Postgres. A unique key makes reruns safe, and one join marks the matching orders paid.
The match: one account per order
A deposit shows up on Solana as a signature, an account whose balance went up, an asset and an amount. Your database holds an order that expects some amount of one asset. Matching joins the two, and it works only when each order can be told apart by something on chain. The handle used here is the receiving account: every order gets its own deposit account, and its address sits in the orders row.
For SOL the account is the wallet. For an SPL token it is the token account that holds the balance. The difference matters because a wallet's signature list leaves out a transfer that only touches its token account, so you watch the account the payer sends to and store that address.
Each new deposit becomes one row, filled like this.
| From the chain | Column |
|---|---|
| Signature of the transaction | signature |
| The watched account | address |
| SOL or the token mint | asset |
| Balance change in base units, lamports for SOL | amount |
| Slot of the transaction | slot |
The Solana side: finalized reads
The script talks to the Carbium RPC at https://services.carbium.sh and names commitment finalized on every call, because a database credit is hard to take back.
getSignaturesForAddress lists the signatures that touched the account, newest first. The script passes the last stored signature as until, so only newer ones come back, and pages backwards with before when a page fills up. Failed transactions appear in that list with an error set. They move no funds, so the script drops them.
getTransaction then fetches each new signature with jsonParsed encoding and maxSupportedTransactionVersion: 1. Mainnet carries v1 transactions, and with that setting absent or 0 a call for one answers -32015, so the script sets 1. The deposit is the balance change of the watched account: post balance minus pre balance in lamports for SOL, or the change in the token balance entries at that account's index for a token. A balance change covers a plain transfer and a transfer made inside another program's call alike, where parsing instructions would need a case per program.
The signature list comes from Carbium's own address index, which keeps up to 30 days. An empty page past that is the index's age limit.
The Postgres side: one key, one join
One table holds what the chain said. Its primary key is (signature, address, asset), so a payment is stored once however many times it is read. The script prints insert ... on conflict do nothing, which makes a rerun, an overlapping run and a retried job safe.
- Create: create table deposit_events (signature text, address text, asset text, amount numeric, slot bigint, primary key (signature, address, asset)).
- Cursor: select signature from deposit_events where address = 'ACCOUNT' order by slot desc limit 1 gives the until value for the next run.
- Insert: printed by the script, one row for each successful transaction and asset, positive or not, so the cursor moves past outgoing transactions too.
- Match: update orders o set status = 'paid', paid_signature = e.signature from deposit_events e where e.address = o.deposit_address and e.asset = o.asset and e.amount >= o.amount and o.status = 'pending'.
The reader
Install with npm install @solana/[email protected], set "type": "module" in package.json, and use Node 24, which strips the types on load. The script takes the deposit account as its first argument and the cursor signature as an optional second. It needs CARBIUM_KEY and exits with a message when it is unset. CARBIUM_RPC_URL is optional. It only reads: no signing and no sending.
// I0008 · Postgres deposit matching// https://carbium.sh/library/integrate/postgres-deposit-matching// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { address, createDefaultRpcTransport, createSolanaRpcFromTransport, signature, type Signature } from "@solana/kit";const key = process.env.CARBIUM_KEY;if (!key) { console.error("Set CARBIUM_KEY."); process.exit(1);}const [account, last] = process.argv.slice(2);if (!account) { console.error("Usage: node main.ts <deposit-account> [last-signature]"); process.exit(1);}const watched = address(account);const rpc = createSolanaRpcFromTransport( createDefaultRpcTransport({ url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh", headers: { "x-api-key": key }, }),);const commitment = "finalized"; // named on every call: kit would send "confirmed"const LIMIT = 3; // keeps the first run short; raise it (up to 1000) for real useconst q = (s: string) => `'${s.replaceAll("'", "''")}'`;const retry = async <T>(label: string, call: () => Promise<T>): Promise<T> => { try { return await call(); } catch { await new Promise((r) => setTimeout(r, 5_000)); // one retry, for a 429 try { return await call(); } catch (e) { throw new Error(`${label}: ${e instanceof Error ? e.message : String(e)}`); } }};const fresh: { signature: Signature; slot: bigint }[] = [];const out: string[] = [];let stopped = "";try { // New signatures, newest first. With a cursor, page back with `before` until it is reached. let before: Signature | undefined; for (;;) { const page = await retry(`getSignaturesForAddress ${watched}`, () => rpc .getSignaturesForAddress(watched, { commitment, limit: LIMIT, ...(before ? { before } : {}), ...(last ? { until: signature(last) } : {}) }) .send(), ); fresh.push(...page.filter((s) => s.err === null)); // a failed transaction moved no funds if (!last || page.length < LIMIT) break; before = page[page.length - 1].signature; } for (const s of fresh.reverse()) { // oldest first, so a stop leaves no gap const tx = await retry(`getTransaction ${s.signature}`, () => rpc.getTransaction(s.signature, { commitment, encoding: "jsonParsed", maxSupportedTransactionVersion: 1 }).send(), ); if (!tx?.meta) throw new Error(`no transaction for ${s.signature}`); const meta = tx.meta; const i = tx.transaction.message.accountKeys.findIndex((k) => k.pubkey === watched); if (i < 0) throw new Error(`${watched} not in ${s.signature}`); const delta = new Map<string, bigint>(); const add = (asset: string, d: bigint) => delta.set(asset, (delta.get(asset) ?? 0n) + d); for (const b of meta.postTokenBalances ?? []) if (b.accountIndex === i) add(b.mint, BigInt(b.uiTokenAmount.amount)); for (const b of meta.preTokenBalances ?? []) if (b.accountIndex === i) add(b.mint, -BigInt(b.uiTokenAmount.amount)); if (!delta.size) add("SOL", meta.postBalances[i] - meta.preBalances[i]); for (const [asset, amount] of delta) out.push(`insert into deposit_events (signature, address, asset, amount, slot) values (${q(s.signature)}, ${q(watched)}, ${q(asset)}, ${amount}, ${s.slot}) on conflict do nothing;`); }} catch (e) { stopped = (e instanceof Error ? e.message : String(e)).replace(/\s+/g, " ");}console.log(`-- ${fresh.length} new signatures for ${watched}`);console.log("begin;");for (const line of out) console.log(line);console.log("commit;");if (stopped) { console.log(`-- stopped: ${stopped}`); process.exitCode = 1;}
run: node main.ts
Run it into psql
Pipe the output into psql, which takes its connection from the usual PG* variables. First read the cursor: CURSOR=$(psql -Atc "select signature from deposit_events where address = 'ACCOUNT' order by slot desc limit 1"). Then run the reader and append the match: { node main.ts ACCOUNT "$CURSOR"; status=$?; echo "update orders o set status = 'paid', paid_signature = e.signature from deposit_events e where e.address = o.deposit_address and e.asset = o.asset and e.amount >= o.amount and o.status = 'pending';"; exit "$status"; } | psql -v ON_ERROR_STOP=1. With no stored signature the cursor is empty and the script reads the newest page only, which is right for a fresh deposit account.
The script's output is one transaction: begin;, the inserts, commit;. Each call that fails gets one retry after 5 seconds. If it fails again, the script prints the rows it has, then a -- stopped: comment with the method name and the error message, and exits 1. This holds for the signature listing as well: a listing failure prints begin;, commit; and the comment. It works oldest first, so what it printed has no gap and the next run starts from the cursor. In a shell job use set -o pipefail, so that exit status survives the pipe.
Run it from cron or a systemd timer at the interval your checkout can wait.
What it costs against your limits
getSignaturesForAddress and getTransaction each cost 50 cells. A run on an idle account is one call, 50 cells. A run that finds N new signatures costs 50 times N plus 50, and 50 more for each extra page. On Free, getSignaturesForAddress allows 0.24 req/s, on Dev 1.2, on Business 100 and on Pro 500.
Limits are per account, so all keys share one budget. If you run the script for many accounts, space the runs out, since the 50 cell reads add up across them.
Where it ends
- It reads one account per run, and the newest 3 signatures when no cursor is given. LIMIT = 3 keeps the first run short, and with a cursor each 3-signature page is another 50-cell call. Raise it, up to 1000, for real use, and run a backfill on purpose.
- History reaches back 30 days at most, the age of Carbium's address index.
- It matches on the receiving account and the amount. It does not check who paid, and an amount over the order still pays it.
- Partial payments are not added up, and nothing refunds an overpayment.
- Amounts are in base units. Decimals, prices and currency conversion belong in your orders table.
- A run is a poll. A deposit shows up after the next run, once its transaction is finalized.
- The script reads and prints. It signs nothing, sends nothing and never connects to Postgres itself; psql applies the output.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| The run ends with a -- stopped: comment and exit status 1 after a few rows. | The comment starts with the failing method and its argument, then the error message. A 429 means the account's budget is spent, so wait and rerun. The rows printed before it are valid, and the next run resumes from the cursor. |
| A token payment never appears in deposit_events. | You are watching the owner wallet, and its signature list leaves out a transfer that only touches its token account. Pass the token account address and store it in orders.deposit_address. |
| The payment is in deposit_events and the order stays pending. | Compare asset (SOL or the mint address) and amount in base units: 1 SOL is 1000000000 lamports. An amount below the order's waits for more money, since nothing here adds partial payments. |
| Every run inserts nothing new but still costs a full page of reads. | The cursor argument is empty, so the script reads the newest page each time. Check that the psql -Atc output is a bare signature. The primary key keeps the rows unique, and the reads still cost cells. |
| An old deposit never shows up on an account with a long history. | The address index keeps up to 30 days, and an empty page past that is the index's age limit. Load older deposits from your own records. |
Questions
Can a WebSocket replace the polling?
logsSubscribe streams transaction logs by mention, and accountSubscribe stays silent for a plain SOL wallet, so use logs plus a balance read. Each subscription opens at 5, 25 or 200 credits by filter weight and then costs 20 credits per MiB sent. You would still run this read and insert on each notification, and the (signature, address, asset) primary key keeps each row exactly once.
Why read balance changes and not instructions?
A balance change covers a plain transfer and one made inside another program's call, with no parser per program. It also reports transfers you did not expect, which amount >= o.amount accepts, so keep the amount check in the match.
Can one run cover many deposit accounts?
Not in this script: it takes one account per run. Loop over the orders addresses in the shell and space the runs out, since each call reads at 50 cells and the account's keys share one budget.