library / AI and blockchain / SI0030
Agent payment reconciliation
A read-only Node check that matches the payments an agent says it made against what the chain recorded for each transaction, and prints which matched, differ, were never recorded or never landed.
Why the agent's own log is not enough
An agent that pays for things keeps a record of what it meant to pay. That record is intent. The chain holds what happened, and the two drift apart in ordinary ways.
Reconciliation compares the two after the fact. Before it sends, the agent's signer writes a row with the signature and the change in balance it expects the wallet to show. Later a reader with no key looks up what each transaction did and sorts every result into a few named states.
What the ledger holds
The ledger is one SQLite table, payments, with two text columns. signature is the base58 transaction signature. delta is the signed change in raw units the wallet should see, so -2500000 means 2.5 USDC left a wallet whose token has 6 decimals. It is text because a token amount can pass what a JavaScript number holds exactly, and the file turns it into a bigint.
A transaction carries its signature once it is signed, so the signer can write the row first and send second.
The file reads in two modes. With only a wallet address it measures the wallet's SOL change from the transaction's pre and post balances, in lamports. With a mint as the second argument it measures the wallet's token change from the pre and post token balances. A token transfer to an existing token account lists the token accounts and the sender's authority and never the receiving wallet, so the instruction is the wrong place to look. The balance records name an owner, and a wallet can own more than one token account for one mint, so the file sums every record whose owner is the wallet and whose mint matches.
The two modes differ on fees. A token change is exact, because the fee comes out of SOL. A SOL change includes the fee whenever the wallet pays it, so the signer records the amount plus the fee it expects, and a priority fee shows as a difference.
The reconciler file
One file on Node 24, with @solana/kit 8.6.0 for the RPC calls and node:sqlite for the ledger. Set CARBIUM_KEY and pass the wallet, and a mint if you reconcile a token. PAYMENTS_DB is the path to the signer's database, opened read-only so a mistyped path stops the run. Left out, the file uses an empty in-memory table, so every landed transaction prints UNLISTED and a failed one still prints FAILED, which is the right answer when nothing was recorded.
// SI0030 · Agent payment reconciliation// https://carbium.sh/library/si/agent-payment-reconciliation// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MIT// Agent payment reconciliation, read only. Run: CARBIUM_KEY=... node main.ts <wallet> [mint]import { DatabaseSync } from "node:sqlite";import { address, createDefaultRpcTransport, createSolanaRpcFromTransport, signature } from "@solana/kit";const key = process.env.CARBIUM_KEY;const target = process.argv[2];const mint = process.argv[3];if (!key || !target) { console.error("Set CARBIUM_KEY to your Carbium API key and pass a wallet address, then an optional mint."); process.exit(1);}const apiKey: string = key;const wallet = address(target);const rpc = createSolanaRpcFromTransport( createDefaultRpcTransport({ url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh", headers: { "x-api-key": apiKey }, }),);// The signer writes one row per payment before it sends: the signature and the signed change// (raw units, as text) it expects the wallet to see. Opened read-only so a wrong path fails loudly.const path = process.env.PAYMENTS_DB;const db = path ? new DatabaseSync(path, { readOnly: true }) : new DatabaseSync(":memory:");if (!path) db.exec("create table payments (signature text primary key, delta text not null)");const ledger = new Map<string, bigint>();for (const row of db.prepare("select signature, delta from payments order by rowid desc").all()) { ledger.set(String(row.signature), BigInt(String(row.delta)));}type TokenBalance = { owner?: string; mint: string; uiTokenAmount: { amount: string } };const held = (list: unknown): bigint => ((list ?? []) as TokenBalance[]) .filter((b) => b.owner === target && b.mint === mint) .reduce((sum, b) => sum + BigInt(b.uiTokenAmount.amount), 0n);async function actualDelta(sig: string): Promise<bigint | null> { const tx = await rpc .getTransaction(signature(sig), { encoding: "jsonParsed", maxSupportedTransactionVersion: 1, commitment: "confirmed" }) .send(); if (!tx || !tx.meta) return null; if (mint) return held(tx.meta.postTokenBalances) - held(tx.meta.preTokenBalances); const keys = tx.transaction.message.accountKeys as unknown as { pubkey: string }[]; const i = keys.findIndex((k) => String(k.pubkey) === target); return i < 0 ? null : BigInt(tx.meta.postBalances[i]) - BigInt(tx.meta.preBalances[i]);}// A failed page read leaves the page empty, and the ledger status check below still runs.let page: { signature: string; err: unknown }[] = [];try { page = [...(await rpc.getSignaturesForAddress(wallet, { limit: 5, commitment: "confirmed" }).send())];} catch (e) { console.log(`page read failed: ${(e as Error).message}`);}const results = await Promise.allSettled(page.map((entry) => actualDelta(entry.signature)));page.forEach((entry, i) => { const sig = entry.signature; const result = results[i]; if (result.status === "rejected") return console.log(`lookup failed ${sig}: ${(result.reason as Error).message}`); const got = result.value; const expected = ledger.get(sig); if (got === null) console.log(`no body ${sig}`); else if (entry.err !== null) console.log(`FAILED ${sig}`); else if (expected === undefined) console.log(`UNLISTED ${sig} ${got}`); else if (expected !== got) console.log(`DIFFERS ${sig} expected ${expected} got ${got}`); else console.log(`matched ${sig} ${got}`);});// Ledger rows the newest page does not show: ask the node whether it knows them at all.const onPage = new Set<string>(page.map((entry) => entry.signature));const absent = [...ledger.keys()].filter((s) => !onPage.has(s)).slice(0, 100);if (absent.length > 0) { try { const status = await rpc.getSignatureStatuses(absent.map(signature), { searchTransactionHistory: true }).send(); absent.forEach((s, i) => { const st = status.value[i]; console.log(st ? (st.err !== null ? `FAILED ${s}` : `landed, off page ${s}`) : `MISSING ${s}`); }); } catch (e) { console.log(`status check failed: ${(e as Error).message}`); }}
run: node main.ts <wallet address> [mint address]
The file reads the five newest signatures for the wallet, then looks up all five transactions in one Promise.allSettled, so one failed lookup leaves the other four standing. The two calls that take a commitment, the signature page and getTransaction, name confirmed; getSignatureStatuses takes none.
getTransaction takes maxSupportedTransactionVersion: 1. Mainnet carries v1 transactions, and without that setting, or with 0, the call answers -32015 for a v1 transaction. The file asks for jsonParsed because accountKeys then arrive as objects with a pubkey, lookup-table addresses included, in the same order as the pre and post balances, so one index serves both lists.
A signature the address index lists can lie below the validator's ledger floor, so getTransaction may answer null for an older one. The file prints no body and moves on. Last, up to the newest 100 ledger signatures that were not on the page go to getSignatureStatuses with history search on. The call reads the validator's own ledger, which has a floor, so a null answer prints MISSING and is reliable only for rows newer than that floor. An old payment that did land can come back null.
What each line means
| Line | Meaning | What to do |
|---|---|---|
| matched <signature> <delta> | The ledger row and the chain agree on the change. | Nothing. |
| DIFFERS <signature> expected X got Y | The transaction landed and moved a different amount. | Open it. In SOL mode check the fee first. |
| UNLISTED <signature> <delta> | A transaction touched the wallet and the ledger has no row. | Decide whether it is a deposit or a payment nobody recorded. |
| FAILED <signature> | The transaction landed with an error, on the page or off it. A failed transaction can still pay its fee. | Find out why the agent sent it. |
| MISSING <signature> | A ledger row the node has no record of. | A transaction still in flight also answers null and can land until its blockhash expires, so treat a recent row as unpaid only after that blockhash has expired, then check whether the signer retried. For an old row, look it up by hand before paying again. |
| landed, off page <signature> | The row is not on the newest page, and the node knows the transaction landed without an error. | Nothing, or raise limit to compare its amount. |
| lookup failed <signature>: <message> | One transaction lookup failed, often with a 429. | Run again after the bucket refills. |
| no body <signature> | The signature is listed but its transaction came back null. | Look it up by hand or skip it. |
| page read failed: <message> | The signature page call failed, often with a 429. No transaction was compared, and the ledger status check still ran. | Run again after the bucket refills. |
| status check failed: <message> | The status call for the ledger rows off the page failed. Those rows have no verdict. | Run again after the bucket refills. |
For a book of record, change the commitment in the two calls to finalized. Keep one level across every call. Commitment levels can differ by a slot, so a pass that mixes them, such as a finalized lookup of a signature from a confirmed page, can see a finalized getTransaction answer null for a signature the page already lists. The pass then prints no body, and that line clears on the next run.
What a pass costs
getSignaturesForAddress costs 50 cells, and so does each getTransaction. A pass over five signatures is 300 cells with the getSignatureStatuses call extra. A rate class absorbs bursts up to 1,024 cells or one second of its rate, whichever is larger. The page read and the lookups sit in different classes, so twenty lookups (1,000 cells) still fit the 1,024-cell burst, and on Pro one second of getTransaction's rate is 1,250 cells.
getSignaturesForAddress runs at 0.24, 1.2, 100 and 500 req/s on Free, Dev, Business and Pro. getTransaction runs at 0.24, 1.2, 5 and 25. A getTransaction over its rate gets 429 and the file prints it as lookup failed. On Free the first pass is served, because 250 cells of lookups fit the burst. About four passes of 250 cells fit the 1,024-cell burst before a Free key gets 429, and the bucket then refills at 0.24 req/s.
Limits are per account, and an account's keys share one budget, so the reconciler competes with the agent's own reads.
Where it ends
- The file reports and stops nothing. A DIFFERS line says a payment went wrong, and the cap on what an agent may pay lives in the signer, before it signs.
- It checks the wallet's own change. A payment of the right amount to the wrong recipient matches. In SOL mode, reconcile the recipient's wallet too, with its own PAYMENTS_DB whose delta is that payee's expected change, because rows holding the payer's delta print DIFFERS on every recipient. You can also store the destination in the ledger and compare it. In token mode the recipient wallet's signature page never lists an incoming transfer to an existing token account, so paging the token account is the route there. In that case pass the token account's address and change the held filter to match records whose accountIndex points at that address in accountKeys, because token balance records carry an index and no address.
- One page holds five signatures. A longer gap leaves payments unchecked until you raise limit, and only the newest 100 off-page ledger rows are checked for status. Carbium's address index keeps up to 30 days, so older history is not served, and an empty page past that is the index's age limit.
- The ledger is only as honest as whoever can write to it. Keep the signer's database out of the agent's reach.
- There is no loop. Run the file from a scheduler; every run only reads, so a rerun is safe.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| Every transaction prints UNLISTED although the agent paid. | The ledger is empty, PAYMENTS_DB points at another file, the rows belong to a different wallet, or the signatures are stored in a form other than base58. Open the table the signer writes to and compare one row with a signature the page prints. |
| SOL payments print DIFFERS by a small constant amount. | The wallet paid the fee and the ledger delta left it out. Record the amount plus the expected fee, or reconcile in token mode where the change is exact. |
| Token mode prints a delta of 0 for a transaction that moved tokens. | The mint argument is wrong, or the tokens moved between accounts the wallet does not own. The file sums only balance records whose owner is the wallet and whose mint matches. |
| getTransaction answers -32015 when you port the check to another client. | Pass maxSupportedTransactionVersion: 1 on every getTransaction and getBlock call. |
| Most lookups print as failed with 429. | The pass asked for more cells than the getTransaction bucket held, as when passes run back to back on Free. Wait the retry-after time, lower limit, or run on a plan with a higher rate. Other keys on the account spend the same budget. |
| An older signature prints no body. | The address index lists signatures below the validator's ledger floor, so the transaction can answer null. Prove the check on the newest signatures and look older ones up by hand. |
Questions
Why not trust the agent's own transaction log?
The log records what the agent meant to do and what its tool returned. The chain records what landed, so only a read of the chain shows a payment that never confirmed or landed for another amount.
Does the reconciler need any key that can sign?
No. It holds a public wallet address and the Carbium key, makes read calls and opens the database read-only. Signing stays in the signer.
How do I reconcile payouts to many recipients?
Run the file against the paying wallet and sum the change. In SOL mode you can also run it once per recipient wallet to check each payee got its amount, each run with its own PAYMENTS_DB whose delta is that payee's expected change, because rows holding the payer's delta print DIFFERS on every recipient. A longer list needs a larger limit and a ledger row per signature.