library / Use cases / Payments and checkout / UC0089
Partial payment accumulator
A running state for an invoice paid in several USDC transfers: a table keyed by signature that never counts one twice, a cursor that survives restarts, four states with overpayment kept apart, and a read-only Node script.
One invoice, many signatures
A customer who owes 900 USDC rarely pays in one transfer. They send 500 from one wallet, then 400 the next day from a treasury, or a payment app splits the amount for them. Each transfer is its own transaction with its own signature, and the signature is the only identifier the chain gives a payment. An invoice is therefore a sum over signatures, and the job is keeping that sum right.
Two things break the sum. A signature seen twice, through an overlapping poll, a restart or a retried webhook, adds its amount twice and marks the invoice paid early. A signature that never reaches the sum leaves the customer with a reminder for money already sent. The design answers both with a table keyed by signature and a cursor stored beside it.
The design assumes one deposit token account per invoice, so every credit to that account belongs to that invoice. USDC has 6 decimals and all amounts below are integer base units: 900 USDC is 900000000.
The accumulator table and its cursor
Two tables live in one SQLite file. credits holds one row per counted transfer, with signature as the primary key and amount in base units. invoice holds a single row: the deposit token account, the amount due and the cursor, which is the newest signature already handled.
- Every insert is INSERT OR IGNORE. A signature that arrives a second time changes zero rows, so the total stays where it was.
- A credit is the deposit account's post balance minus its pre balance in that transaction, matched on the account's index in the key list. A transaction with meta.err set contributes nothing, and an outgoing move gives a negative delta that is skipped.
- The total is a SUM over the rows each time it is needed. No counter lives in memory, so a restart recomputes the same figure it had before.
- The cursor goes to getSignaturesForAddress as until, so the next pass lists only signatures newer than it. The new rows and the new cursor are written inside one SQLite transaction, so a crash leaves both or neither.
The state rules
The state is computed from the total and the due amount each time, and nothing stores it. Compare both as BigInt in base units.
| State | Condition | Usual next step |
|---|---|---|
| open | total is 0 | Send the first reminder |
| partial | total is above 0 and below due | Ask for the remainder, due minus total |
| paid | total equals due | Release the order |
| overpaid | total is above due | Hold the order and settle the excess by hand |
Overpayment gets its own state because a customer who sends 1000 against a 900 invoice has not paid it exactly. Folding that case into paid hides the extra 100 from the ledger, and someone finds it at month end. Because the state is derived, a late transfer to an invoice already marked paid moves it to overpaid on its own, with no status field to correct.
Rows are only ever added, so the total only rises. That keeps the history simple to audit: rows are written oldest first, so summing them in SQLite rowid order up to a signature rebuilds any total the invoice showed.
The script
With no arguments, main.ts reads the newest finalized transactions that mention the USDC mint and picks the token account with the largest balance among those that received USDC. It then walks that account's five newest signatures from oldest to newest. Each one goes through getTransaction in jsonParsed encoding with maxSupportedTransactionVersion: 1, because mainnet carries v1 transactions and Carbium answers -32015 for one when the value is absent or 0. The call goes to the RPC endpoint with the key in the `x-api-key` header.
Every call passes commitment: "finalized", because a ledger should book only a transfer that can no longer be undone.
// UC0089 · Partial payment accumulator// https://carbium.sh/library/usecase/partial-payment-accumulator// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MIT// Read-only: a running invoice state (open, partial, paid, overpaid) from USDC credits to one token account, kept in SQLite.import { DatabaseSync } from "node:sqlite";import { address, createDefaultRpcTransport, createSolanaRpcFromTransport, 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 url = process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh";const USDC = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";const [accArg, dueArg] = process.argv.slice(2);const rpc = createSolanaRpcFromTransport(createDefaultRpcTransport({ url, headers: { "x-api-key": key } }));type Bal = { accountIndex: number; mint: string; uiTokenAmount: { amount: string } };type Tx = { meta: { err: unknown; preTokenBalances?: Bal[] | null; postTokenBalances?: Bal[] | null } | null; transaction: { message: { accountKeys: { pubkey: string }[] } } };type Inv = { account: string; due: bigint; cursor: string | null };const db = new DatabaseSync("invoices.db");db.exec(`CREATE TABLE IF NOT EXISTS credits (signature TEXT PRIMARY KEY, amount INTEGER NOT NULL); CREATE TABLE IF NOT EXISTS invoice (id INTEGER PRIMARY KEY CHECK (id = 1), account TEXT, due INTEGER, cursor TEXT)`);const get = db.prepare("SELECT account, due, cursor FROM invoice WHERE id = 1");const total = db.prepare("SELECT COALESCE(SUM(amount), 0) AS t FROM credits");const add = db.prepare("INSERT OR IGNORE INTO credits (signature, amount) VALUES (?, ?)");get.setReadBigInts(true);total.setReadBigInts(true);const sum = () => (total.get() as unknown as { t: bigint }).t;const state = (t: bigint, due: bigint) => (t === 0n ? "open" : t < due ? "partial" : t === due ? "paid" : "overpaid");const fetchTx = async (sig: string) => (await rpc.getTransaction(signature(sig), { encoding: "jsonParsed", maxSupportedTransactionVersion: 1, commitment: "finalized" }).send()) as unknown as Tx | null;// What the token account gained in this transaction; a failed or outgoing one gives 0.function credit(tx: Tx, account: string): bigint { if (!tx.meta || tx.meta.err) return 0n; const i = tx.transaction.message.accountKeys.findIndex((k) => k.pubkey === account); const amt = (l?: Bal[] | null) => BigInt(l?.find((b) => b.accountIndex === i)?.uiTokenAmount.amount ?? "0"); const d = amt(tx.meta.postTokenBalances) - amt(tx.meta.preTokenBalances); return d > 0n ? d : 0n;}// The USDC token account with the largest balance among those credited in the newest mint transactions.async function findAccount(): Promise<string> { const page = await rpc.getSignaturesForAddress(address(USDC), { limit: 5, commitment: "finalized" }).send(); for (const s of page.filter((p) => p.err === null)) { const tx = await fetchTx(s.signature).catch(() => null); if (!tx?.meta) continue; const keys = tx.transaction.message.accountKeys.map((k) => k.pubkey); const best = (tx.meta.postTokenBalances ?? []) .filter((b) => b.mint === USDC && credit(tx, keys[b.accountIndex]) > 0n) .sort((a, b) => (BigInt(b.uiTokenAmount.amount) > BigInt(a.uiTokenAmount.amount) ? 1 : -1))[0]; if (best) return keys[best.accountIndex]; } throw new Error("no USDC credit in the newest mint transactions");}async function pass(n: number) { const inv = get.get() as unknown as Inv | undefined; const account = inv?.account ?? accArg ?? (await findAccount()); const until = inv?.cursor ? { until: signature(inv.cursor) } : {}; const page = await rpc.getSignaturesForAddress(address(account), { limit: 5, commitment: "finalized", ...until }).send(); const got: [string, bigint][] = []; for (const s of page.filter((p) => p.err === null).reverse()) { try { const tx = await fetchTx(s.signature); if (!tx) { console.log(`${s.signature.slice(0, 8)} returned null, stopping this pass`); break; } got.push([s.signature, credit(tx, account)]); } catch (e) { console.log(`${s.signature.slice(0, 8)} failed: ${(e as Error).message}`); break; } } const demo = got.map(([, a]) => a).filter((a) => a > 0n).slice(0, 3).reduce((a, b) => a + b, 0n) || 1000000n; const due = inv?.due ?? BigInt(dueArg ?? demo); let added = 0; db.exec("BEGIN"); for (const [sig, amt] of got) { if (amt > 0n) added += Number(add.run(sig, amt).changes); const t = sum(); console.log(`${sig.slice(0, 8)} ${amt > 0n ? "+" + amt : "no credit"} total ${t} of ${due} ${state(t, due)}`); } db.prepare("INSERT INTO invoice (id, account, due, cursor) VALUES (1, ?, ?, ?) ON CONFLICT (id) DO UPDATE SET cursor = excluded.cursor") .run(account, due, got.at(-1)?.[0] ?? inv?.cursor ?? null); db.exec("COMMIT"); console.log(`pass ${n}: ${added} new rows, total ${sum()} of ${due}, ${state(sum(), due)}`);}for (const n of [1, 2]) await pass(n).catch((e) => console.log(`pass ${n} failed: ${(e as Error).message}`));
run: CARBIUM_KEY=$CARBIUM_KEY node main.ts [deposit token account] [due in base units]
The demo due amount is the sum of the first three credits it finds. With one credit the printed run goes from open straight to paid, so partial appears only when the walk finds more than one credit, and a fourth credit would show overpaid. Pass your own due amount as the second argument for a real invoice, and a deposit token account as the first. The due amount and account are stored on the first pass, so later passes ignore both arguments.
After the walk the script prints each signature with its credit, the running total and the state. It then runs a second pass over the same account. That pass lists only signatures newer than the cursor, and on a busy account like the demo's it can carry new credits, which then raise the total and can move the invoice to overpaid. A signature already counted changes zero rows. A getTransaction that returns null, or fails, stops the pass at that signature and leaves the cursor behind it, so the next pass tries it again, but only while it is still among the five newest signatures above the cursor.
What a pass costs and how to avoid polling
| Method | Cells per call | Free req/s | Dev req/s | Business req/s | Pro req/s |
|---|---|---|---|---|---|
| getSignaturesForAddress | 50 | 0.24 | 1.2 | 100 | 500 |
| getTransaction | 50 | 0.24 | 1.2 | 5 | 25 |
An idle pass is one 50-cell listing call. Each new signature adds one 50-cell getTransaction, and it is paid once, because the cursor moves past it.
To skip polling, open a WebSocket with the key as ?api-key= in the URL and send logsSubscribe with a mention filter on the deposit token account. A mention subscription opens at 25 credits and then costs 20 credits per MiB sent. Treat each notification as a prompt only: take its signature and feed it through the same fetch and insert, so one code path decides what counts. The keyed insert makes the poll and the stream safe to run together. Invoice payment tracker covers the single-transfer version of this job.
Where it ends
- One deposit token account serves one invoice. Payments sent to a shared address need a reference to tell invoices apart, as in Memo payment lookup.
- The script reads the five newest signatures per pass and moves the cursor to the newest one it handled. If more than five new transfers arrive between two passes, the older ones are skipped and never counted, and a failed signature is retried only while it is still among the five newest above the cursor. Paging with before down to the cursor before moving it closes that gap.
- Carbium serves signature pages from an address index that keeps up to 30 days. An empty page past that is the index's age limit, so keep your own rows and start an invoice inside the window.
- A wallet can own more than one token account for a mint. Funds sent to a different token account of the same customer never reach this invoice.
- Any sender can pay a public deposit address. The script counts the amount and does not check who sent it.
- Refunds are manual. The script is read-only, signs nothing and sends nothing, so an overpaid invoice waits for a person.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| An invoice flips to paid after a restart or an overlapping poll because a transfer was added twice. | Key the credits table on the signature and insert with INSERT OR IGNORE. Compute the total with a SUM over the rows, never a counter kept in memory. |
| getTransaction fails with -32015 on a v1 transaction. | Pass maxSupportedTransactionVersion: 1 on every getTransaction call. With the value absent or 0, Carbium answers -32015 for a v1 transaction. |
| getTransaction answers null for a signature the listing returned, and the cursor jumps past it so the payment is never counted. | Stop the pass at that signature and write the cursor only up to the last handled one. Pages reach below the validator's ledger floor, so an older signature can list and still read null. |
| A customer overpays and the ledger shows the invoice as paid. | Keep overpaid as its own state: total above due. Settle the excess by hand. |
| Amounts are compared as floats and a payment of 25.50 USDC rounds to a different total. | Read uiTokenAmount.amount as a BigInt of base units and store it as an integer. 25.50 USDC is 25500000. |
| The ledger books a payment at confirmed because a call left commitment out. | Set commitment: "finalized" on getSignaturesForAddress and getTransaction. Kit fills in confirmed otherwise. |
Questions
Why store each credit instead of one running total?
A single total cannot tell a repeated transfer from a new one. Rows keyed by signature let the database refuse the repeat, and the total is a sum you can rebuild and audit.
What happens if the script crashes between two transfers?
Nothing is lost. The rows and the cursor are written in one SQLite transaction, so the restart resumes from the last committed cursor, and any signature seen again is ignored.
What does one pass cost on Carbium?
A listing call costs 50 cells and each new transaction read costs another 50. A pass with nothing new is one listing call.
Can invoices share one deposit address?
The script assumes not, because every credit to the account counts toward its one invoice. Shared addresses need a unique reference in each payment, matched alongside the amount.