Stablecoin settlement checks
How far to trust the pre and post balance diff when you settle a stablecoin payment: what it records, the ways a check misreads it, which commitment level to read, what the lookups cost on Carbium, and a read-only Node script.
What the diff is made of
Every executed transaction carries a meta record written by the validator. It holds preBalances and postBalances in lamports, one per account in the transaction's key list, and preTokenBalances and postTokenBalances for the SPL token accounts it touched. Each token entry gives accountIndex, mint, owner and uiTokenAmount.amount, a string of base units. These are account state before and after execution, so they record what the ledger did, whatever the instructions claimed.
That makes the diff the strongest evidence a settlement can have. It does not depend on how the payer built the transaction, which program moved the funds or whether a router sat in the middle. Reading instruction data would tie you to each program's layout. For a stablecoin payment, the check is the post amount minus the pre amount for your owner and your mint, in integer base units. USDC has 6 decimals, so 25.50 USDC is 25500000. Compare the amount string as a BigInt and leave the float uiAmount alone.
Where the diff misleads
For a transaction that succeeded, the recorded numbers are exact. The mistakes come from how a check reads them.
- A missing entry means zero. An account created in the transaction has no pre entry, and one closed in it has no post entry. The script treats the absent side as 0.
- Sum by owner and mint. One owner can hold several token accounts for a mint, and a transfer can move funds between them. The owner's net is the sum across all of its accounts.
- SOL deltas include the fee. The fee payer's lamport change is the transfer plus meta.fee, plus rent for any account the transaction created. For stablecoin settlement, read token balances and ignore lamports.
- The net hides the path. A payer that sends 100 and receives 40 back in the same transaction shows a delta of 60, and a pass-through account shows 0 though funds crossed it. Read the inner instructions when the route matters to your records.
- A transfer fee shrinks the delta. A Token-2022 mint with a transfer fee delivers less than the sender's amount. The delta is what landed, so it is the number to settle on.
- A failed transaction still has a meta. Its err is set, its token balances are unchanged and only the fee is charged. Check err first. A set err means nothing was paid, so never book that transaction against an invoice.
- The owner can change inside a transaction. SetAuthority can reassign a token account, so pre and post list different owners for one accountIndex. Match on the index if your flow can see that.
Pick the commitment for settlement
A settlement should read finalized. The JSON-RPC server's own default is finalized, but @solana/kit 8.6.0 fills in confirmed when a call leaves commitment out, so a script that omits it reads at confirmed without saying so. The script sets finalized on both of its calls.
Waiting for finalized now costs a slot at most, about 200 ms since Alpenglow on 2026-10-21, so a settlement loses almost nothing by reading it. Use finalized on every call in one check so its reads agree.
A check in one file
The script takes a mint and reads one transaction. With no signature it finds the latest successful finalized transaction that mentions the mint, then fetches it with getTransaction in jsonParsed encoding and maxSupportedTransactionVersion: 1. Mainnet carries v1 transactions, and with that value absent or 0 Carbium answers -32015 for one, uncharged. Send the key in the `x-api-key` header to the RPC endpoint, https://services.carbium.sh.
// UC0003 · Stablecoin settlement checks// https://carbium.sh/library/usecase/stablecoin-settlement-checks// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MIT// Read-only: the net stablecoin change per owner in one finalized transaction, from its pre and post token balances.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 [mint, sigArg, owner, expected] = process.argv.slice(2);if (!mint) { console.error("Usage: node main.ts <mint> [signature] [owner expectedBaseUnits]"); process.exit(1); }const rpc = createSolanaRpcFromTransport(createDefaultRpcTransport({ url, headers: { "x-api-key": key } }));type Bal = { accountIndex: number; mint: string; owner?: string; uiTokenAmount: { amount: string } };type Tx = { slot: bigint; meta: { err: unknown; fee: bigint; preTokenBalances?: Bal[] | null; postTokenBalances?: Bal[] | null } | null };async function retry<T>(f: () => Promise<T>): Promise<T> { for (let i = 0; ; i++) { try { return await f(); } catch (e) { if (i === 2) throw e; await new Promise((r) => setTimeout(r, 4000)); } }}async function latest(): Promise<string> { const page = await retry(() => rpc.getSignaturesForAddress(address(mint!), { limit: 10, commitment: "finalized" }).send()); const hit = page.find((s) => s.err === null); if (!hit) { console.error("No successful transaction found for", mint); process.exit(1); } return hit.signature;}const sig = sigArg ?? (await latest());// Mainnet carries v1 transactions: a maxSupportedTransactionVersion of 0 or none gets -32015 for one.const tx = (await retry(() => rpc.getTransaction(signature(sig), { encoding: "jsonParsed", maxSupportedTransactionVersion: 1, commitment: "finalized" }).send()) ) as unknown as Tx | null;const meta = tx?.meta;if (!tx || !meta) { console.error("Transaction not found at finalized:", sig); process.exit(1); }// A missing pre or post entry adds nothing, which reads as a balance of 0 on that side.const net = new Map<string, bigint>();const add = (list: Bal[] | null | undefined, sign: bigint) => { for (const b of list ?? []) { if (b.mint !== mint) continue; const who = b.owner ?? `account ${b.accountIndex}`; net.set(who, (net.get(who) ?? 0n) + sign * BigInt(b.uiTokenAmount.amount)); }};add(meta.preTokenBalances, -1n);add(meta.postTokenBalances, 1n);console.log(`tx ${sig}\nslot ${tx.slot}, fee ${meta.fee} lamports, ${meta.err ? "FAILED" : "succeeded"}`);let sum = 0n;for (const [who, d] of net) { sum += d; if (d !== 0n) console.log(`${who} ${d > 0n ? "+" : ""}${d}`);}console.log(`net across owners ${sum} base units${sum === 0n ? "" : " (a mint, a burn or a transfer fee took part)"}`);if (owner && expected) { const got = net.get(owner) ?? 0n, want = BigInt(expected); const verdict = meta.err ? "FAILED" : got === want ? "SETTLED" : got > want ? "OVER" : "SHORT"; console.log(`${verdict}: ${owner} received ${got}, expected ${want}`);}
run: CARBIUM_KEY=$CARBIUM_KEY node main.ts <mint> [signature] [owner expectedBaseUnits]
It prints one line per owner whose balance changed and the net across owners. When you pass an owner and an expected amount in base units, it adds a verdict: SETTLED when the received amount equals the expected one, OVER or SHORT otherwise, FAILED when the transaction errored. The net across owners is 0 for a plain transfer. A non-zero net means a mint, a burn or a transfer fee took part, which deserves a look before you book the payment. The script signs and sends nothing, and it retries a failed call twice after 4 seconds.
Finding and watching payments
A check needs the signature. Either the payer sends it or you list it. getSignaturesForAddress on the receiving token account returns its recent transactions. Use that account's address: an incoming transfer lists the destination token account in its keys, and the owner's wallet may not appear at all. Carbium serves these pages from its own address index, which keeps up to 30 days. An empty page past that is the index's age limit, so keep your own record of the signatures you have settled.
For a second check, read the token account's balance with getTokenAccountBalance and compare it with the balance you booked last time plus the deltas since. Pass commitment: "finalized". SPL token balance covers that read.
| 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 |
| getTokenAccountBalance | 10 | 0.5 | 15 | 50 | 400 |
Each settlement costs one getTransaction, plus one getSignaturesForAddress if you list instead of receiving the signature. Queue the lookups so a burst stays inside your plan's rate. RPC rate-limit alerts helps size that queue.
To avoid polling, open a WebSocket with the key as ?api-key= in the URL. logsSubscribe with a mention filter on the receiving token account streams each transaction that touches it, and signatureSubscribe sends one confirmation for a signature, then ends. Treat a notification as a prompt: take its signature and run the same getTransaction check, so one code path decides. A subscription with a mention filter opens at 25 credits, then costs 20 credits per MiB sent, and a refused one is free. accountSubscribe stays silent for a plain SOL wallet, so a SOL settlement uses logs mentions plus getBalance.
Where it ends
- The diff proves an amount landed on an owner at finalized. It does not say which customer or invoice the payment is for. That needs a reference you control.
- The script reads one transaction. A payment split over several transactions needs your own ledger to sum the deltas that share a reference.
- The script covers token balances. A SOL settlement needs the fee and rent handled by hand, as above.
- A method Carbium does not serve answers -32601: check the method name and do not retry.
- The script is read-only. Moving the funds is your own software's job.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| The check passes on a transaction that failed. | Read meta.err first. A failed transaction has a meta and unchanged token balances, so any set err means not paid. |
| The expected amount is compared as a float and a payment of 25.50 fails or passes by rounding. | Use uiTokenAmount.amount as a BigInt in base units. USDC has 6 decimals, so 25.50 is 25500000. |
| The delta is read from one token account address and the payer used another account of the same owner. | Sum by owner and mint across all token accounts in the transaction. |
| The check reads at confirmed because a call left commitment out. | Set commitment: "finalized" on getSignaturesForAddress, getTransaction and every balance read. Kit fills in confirmed otherwise. |
| 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. |
| The signature list for an old payment comes back empty and the payment is taken as missing. | The address index keeps up to 30 days, and an empty page past that is its age limit. Keep your own record of settled signatures. |
Questions
Is the pre and post balance diff enough proof that a payment arrived?
It proves an amount landed on an account at the commitment you read, and that the transaction succeeded when err is null. It does not tie the payment to an invoice, so add a reference and match on it too.
Why is the fee payer's SOL delta bigger than the transfer?
The lamport change includes the fee in meta.fee, plus rent when the transaction created accounts. Subtract the fee, or settle on token balances.
Should settlement read finalized or confirmed?
Finalized. Since Alpenglow the extra wait is small. Set it on every call, because kit fills in confirmed when you leave it out.
Can I watch for payments instead of polling?
Yes. Subscribe with logsSubscribe and a mention filter on the receiving token account, then run the check on each signature. A subscription opens at 25 credits and costs 20 credits per MiB sent.
What does a settlement check cost in cells?
getTransaction costs 50 cells and so does getSignaturesForAddress. A token account balance read costs 10.