library / Use cases / Payments and checkout / UC0053
Multi-token payment intake
Turn each arrival at a payment wallet, in SOL or a token, into one row of asset, raw amount and decimals, check it against a table of accepted assets and flag the rest. A read-only Node script shows the rows for a live USDC arrival.
Why SOL and tokens arrive differently
A payment program that takes SOL and several tokens at one wallet watches two kinds of ledger entry. SOL lives in the wallet's own lamport balance, so a transfer changes preBalances and postBalances at the wallet's position in the transaction's key list. A token lives in a separate token account that the wallet owns. The wallet address holds no USDC itself. It holds the authority over accounts that do.
Those accounts belong to one of two programs. The original Token program holds USDC and USDT. Token-2022 holds newer mints such as PYUSD, and one wallet can have accounts under both. A wallet can also own several accounts for the same mint, so its balance for a mint is the sum over those accounts.
The arrival looks different inside the transaction too. A SOL transfer lists the wallet among its keys. A token transfer to an existing token account lists that account and the sender's authority, and it does not list the receiving wallet. What names the receiver is the owner field on each entry of postTokenBalances, so an intake reads the receiver from there.
One row format for both
Give every arrival the same three fields: the asset, a raw amount as an integer and the decimals that say where the point goes. For SOL the raw amount is lamports and the decimals are 9. For a token the raw amount is the amount string of its balance entry, in base units, and the decimals come from the same entry. Hold the amount as a BigInt, keep the decimals next to it, and divide only when you display.
The raw amount is a delta: the wallet's post amount minus its pre amount, summed over every account it owns for that asset. A token account created in the transaction has no pre entry, which reads as zero before. A SOL delta on a wallet that also paid the transaction fee is lower by that fee, so an intake wallet that only receives funds gives the clean number.
With one format, the code after the read has one path. The ledger, the invoice match and the refund queue take rows and never ask whether the money came as lamports or as a token.
The accepted-assets table
The table is your policy in data. Each row names an asset you take, keyed by its mint address. SOL has no mint, so it uses its own key. The intake looks every row up in the table. A hit prints a named intake row. A miss prints the mint and the amount under the word UNACCEPTED, so the arrival stays visible and nothing counts as received.
| Asset | Key | Token program | Decimals |
|---|---|---|---|
| SOL | SOL | System Program | 9 |
| USDC | EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v | Token | 6 |
| USDT | Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB | Token | 6 |
| PYUSD | 2b1kV6DkPAnxd5ixfnxCpjxmKwqjjaYmCZfHsFu24GXo | Token-2022 | 6 |
Key on the mint address and never on a symbol or a name, because anyone can create a token called USDC. The mint address is the only identity a payment program can rely on. Keep the token program in the same row, since the code that opens your token accounts needs it. Token program detection shows how to read it from the mint.
The script
Pass a signature and optionally the receiving wallet, or pass nothing. With nothing, the script lists the newest 15 signatures on the USDC mint and reads them together with getTransaction, each load settled on its own. It takes the first owner with a positive USDC delta that is a plain wallet, meaning an account owned by the System Program, checking up to five candidates. That check leaves out pool authorities and program vaults, which also receive USDC all day. When none of the five is a plain wallet, the first owner with a positive delta is used, and when no transaction qualifies the script prints one line and exits. Every call sets commitment: "finalized" so a booked payment is read at one level.
The transaction is read with maxSupportedTransactionVersion: 1. Mainnet carries v1 transactions, and Carbium answers -32015 for a v1 transaction, uncharged, when that value is absent or 0. The script then calls getTokenAccountsByOwner once for each token program, prints token accounts: N under <program> for each, and merges the accounts by mint. Last it prints the intake rows from the transaction it already holds.
// UC0053 · Multi-token payment intake// https://carbium.sh/library/usecase/multi-token-payment-intake// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MIT// Read-only: turn one arrival at a wallet into intake rows (asset, raw amount, decimals), flagging assets outside the accepted table.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 rpc = createSolanaRpcFromTransport(createDefaultRpcTransport({ url, headers: { "x-api-key": key } }));const commitment = "finalized" as const;const [argSig, argWallet] = process.argv.slice(2);const USDC = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";const ACCEPTED = new Map([["SOL", "SOL"], [USDC, "USDC"], ["Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB", "USDT"], ["2b1kV6DkPAnxd5ixfnxCpjxmKwqjjaYmCZfHsFu24GXo", "PYUSD"]]);const PROGRAMS = ["TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA", "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb"];const SYSTEM = "11111111111111111111111111111111";type Bal = { accountIndex: number; mint: string; owner?: string; uiTokenAmount: { amount: string; decimals: number } };type Tx = { meta: { err: unknown; preBalances: (bigint | number)[]; postBalances: (bigint | number)[]; preTokenBalances?: Bal[] | null; postTokenBalances?: Bal[] | null } | null; transaction: { message: { accountKeys: { pubkey: string }[] } } };async function attempt<T>(label: string, f: () => Promise<T>): Promise<T | undefined> { try { return await f(); } catch (e) { console.error(`${label} failed: ${(e as Error).message}`); }}// Mainnet carries v1 transactions: a maxSupportedTransactionVersion of 0 or none gets -32015 for one.const getTx = (s: string) => rpc.getTransaction(signature(s), { encoding: "jsonParsed", maxSupportedTransactionVersion: 1, commitment }).send() as unknown as Promise<Tx | null>;// One row per asset for this wallet: post minus pre, summed over its accounts. A missing entry reads as zero.function intake(tx: Tx, wallet: string) { const m = tx.meta!, rows = new Map<string, { raw: bigint; decimals: number }>(); const i = tx.transaction.message.accountKeys.findIndex((k) => k.pubkey === wallet); if (i >= 0) rows.set("SOL", { raw: BigInt(m.postBalances[i]) - BigInt(m.preBalances[i]), decimals: 9 }); for (const [list, sign] of [[m.preTokenBalances, -1n], [m.postTokenBalances, 1n]] as const) for (const b of list ?? []) if (b.owner === wallet) { const r = rows.get(b.mint) ?? { raw: 0n, decimals: b.uiTokenAmount.decimals }; rows.set(b.mint, { ...r, raw: r.raw + sign * BigInt(b.uiTokenAmount.amount) }); } return rows;}// Owners whose USDC balance rose in this transaction.const risen = (t: Tx) => [...new Set((t.meta?.postTokenBalances ?? []).flatMap((b) => b.mint === USDC && b.owner && (intake(t, b.owner).get(USDC)?.raw ?? 0n) > 0n ? [b.owner] : []))];const listed = argSig ? [argSig] : ((await attempt("getSignaturesForAddress", () => rpc.getSignaturesForAddress(address(USDC), { limit: 15, commitment }).send())) ?? []).filter((s) => s.err === null).map((s) => s.signature as string);const loaded = await Promise.allSettled(listed.map(getTx));const txs: { s: string; t: Tx }[] = [];loaded.forEach((r, i) => { if (r.status === "rejected") console.error(`getTransaction ${listed[i].slice(0, 8)} failed: ${String(r.reason)}`); else if (r.value?.meta && !r.value.meta.err) txs.push({ s: listed[i], t: r.value }); // null: an older signature the ledger no longer holds});let pick = argWallet && txs[0] ? { ...txs[0], o: argWallet } : undefined;if (!argWallet) { const found = txs.flatMap(({ s, t }) => risen(t).map((o) => ({ s, t, o }))); for (const c of found.slice(0, 5)) { // prefer a plain wallet: pool authorities and vaults are owned by programs const info = await attempt("getAccountInfo", () => rpc.getAccountInfo(address(c.o), { encoding: "base64", commitment }).send()); if (String(info?.value?.owner) === SYSTEM) { pick = c; break; } } pick ??= found[0];}if (!pick) { console.log("No USDC arrival found in the newest signatures."); process.exit(0); }const { s: sig, t: tx, o: owner } = pick;// Token holdings: one read per token program, merged by mint.const held = new Map<string, { raw: bigint; accounts: number }>();const reads = await Promise.allSettled(PROGRAMS.map((p) => rpc.getTokenAccountsByOwner(address(owner), { programId: address(p) }, { encoding: "jsonParsed", commitment }).send()));reads.forEach((r, i) => { if (r.status === "rejected") { console.error(`getTokenAccountsByOwner under ${PROGRAMS[i]} failed: ${String(r.reason)}`); return; } console.log(`token accounts: ${r.value.value.length} under ${PROGRAMS[i]}`); for (const a of r.value.value) { const { mint, tokenAmount } = (a.account.data as unknown as { parsed: { info: { mint: string; tokenAmount: { amount: string } } } }).parsed.info; const h = held.get(mint) ?? { raw: 0n, accounts: 0 }; held.set(mint, { raw: h.raw + BigInt(tokenAmount.amount), accounts: h.accounts + 1 }); }});console.log(`wallet ${owner}\ntx ${sig}`);for (const [id, r] of intake(tx, owner)) { if (r.raw <= 0n) continue; const name = ACCEPTED.get(id); console.log(`${name ? "intake" : "UNACCEPTED"} ${name ?? id} ${r.raw} raw, ${r.decimals} decimals`);}for (const [id, name] of ACCEPTED) { const h = held.get(id); if (h) console.log(`holding ${name} ${h.raw} raw in ${h.accounts} account(s)`); }
run: CARBIUM_KEY=$CARBIUM_KEY node main.ts
A run prints one token accounts line per program, then the wallet and the signature, an intake USDC row with a positive raw amount and 6 decimals, and a holding line for each accepted mint the wallet has, with the number of accounts behind it. Each call sits in its own try or settles on its own, so a failed holdings read for one program prints the failure and the rows still print. Carbium builds its signature lists from an address index of up to 30 days that reaches below the validator's ledger floor, so getTransaction can answer null for an older signature the list still shows. The script skips a null and keeps the other transactions it loaded.
Finding arrivals and what they cost
To start an intake on arrival, open a WebSocket and call logsSubscribe with a mention filter on the wallet and on each token account you hold. A plain SOL wallet sends nothing to accountSubscribe, so SOL arrivals come from logs mentions plus a getBalance read. Take the signature from each notification and run the same getTransaction intake, so one code path writes every row.
An intake for a known wallet is one getTransaction plus the holdings reads. The discovery in the script adds a signature list, 15 getTransaction reads and a getAccountInfo check on up to five candidates.
| Method | Cells per call | Free req/s | Dev req/s | Business req/s | Pro req/s |
|---|---|---|---|---|---|
| getTransaction | 50 | 0.24 | 1.2 | 5 | 25 |
| getSignaturesForAddress | 50 | 0.24 | 1.2 | 100 | 500 |
| getAccountInfo | 10 | 0.5 | 15 | 50 | 400 |
Queue the intakes so a burst of payments stays inside the req/s of your plan.
Where it ends
- Several accounts for one mint give one row, summed. If your records need to know which account took the funds, keep the account index from the balance entry as well.
- A mint with a transfer fee, which Token-2022 allows, delivers less than the sender's amount. The row records what landed, so an invoice check has to allow for the withheld fee. Transfer fee calculator shows the arithmetic.
- The rows carry raw amounts and no value. Adding SOL and three tokens into one currency needs a price source, which USD-pegged checkout pricing covers.
- A row proves an amount arrived at an owner. It does not say which order it pays for, so put a reference in the payment and match on it too. Stablecoin settlement checks goes into that match.
- One getTransaction costs 50 cells, so a Free key sustains about one intake every four seconds and a Pro key 25 a second. Plan the queue around that number for your plan.
- The script reads. Refunds, sweeps and any signing are your own software's job.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| A token payment is never found by listing the wallet's signatures. | A transfer to an existing token account does not list the receiving wallet. List signatures by the token account address, or follow logs mentions on the token accounts. |
| A USDC amount and a SOL amount are stored in one column and read at the same scale. | Store the raw integer with its decimals. SOL is 9 decimals and USDC is 6, so the same raw number means different amounts. |
| A token named USDC with another mint is booked as USDC. | Look the asset up by mint address in the accepted table. A mint that is not in it prints as UNACCEPTED. |
| getTransaction answers -32015 for a payment. | Pass maxSupportedTransactionVersion: 1 on every getTransaction call. With the value absent or 0 Carbium answers -32015 for a v1 transaction. |
| One failed holdings read stops the whole intake. | Settle each call on its own. Print the call that failed and carry on with the rows you have. |
| getTransaction answers null for a signature that a list returned. | The address index keeps up to 30 days and can list signatures below the ledger floor. Skip the null, and prove intake code on the newest signatures. |
Questions
Do I need one watcher for SOL and another for tokens?
One watcher is enough. Subscribe to logs mentions on the wallet and on its token accounts, then run the same getTransaction intake on each signature. SOL needs a getBalance read as well, since accountSubscribe stays silent for a plain SOL wallet.
How do I know which token program an account belongs to?
The owner of the mint account tells you. getTokenAccountsByOwner takes one program per call, so a wallet that may hold both kinds is read under both, as the script does.
Why is a token row lower than the invoice amount?
Either the payer sent less, or the mint is a Token-2022 mint with a nonzero transfer fee, which withholds part of each transfer on arrival. USDC is a Token program mint and never does. The row shows what landed, which is the number to settle on.
Why did a small SOL payment to a new wallet never arrive?
An empty system account has to receive at least the rent-exempt minimum in its first transfer, 890,880 lamports. A smaller transfer fails, so no intake row exists for it.