library / Use cases / Payouts, payroll and remittance / UC0096
Payout recipient resolution
Fill the recipient field of a payout ledger from a transaction. You get the rule for each transfer shape, the token account to owner step, and a read-only Node script that prints every USDC and SOL credit and the resolved recipients.
What the recipient field needs
A payout ledger row ends with a recipient: the wallet that now holds the money. The transaction that paid it has no field with that name. Where the receiver appears depends on how the transfer was built, so a parser written for one instruction layout fills the field for some payouts and leaves it empty or wrong for the rest.
The input to the job is a signature. The output is the list of wallets that received value in that transaction, each with an amount you can match to a ledger row. The script below reads that list from the balance changes the node records after the transaction ran. Those records exist for every transaction, whatever instructions built it.
Where each transfer shape keeps its receiver
| Shape | What the instruction lists | Where to read the receiver |
|---|---|---|
| SOL transfer | The destination account, which is the receiving wallet. | Lamport change of that account, post minus pre. |
| Token transfer to an existing token account | The source and destination token accounts and the sender's authority. The receiving wallet is absent. | Owner on the token balance entry of the destination token account. |
| Token transfer to a new token account | A create instruction names the owner, and the transfer names only the token account. | The same balance entry, which exists once the transaction has run. |
| Token transfer inside another program's call | The top-level instruction lists that program's own accounts. The transfer sits among the inner instructions. | Token balance entries, which count every inner move. |
| SOL moved by a program with no transfer instruction | Nothing. A program can change the lamports of accounts it owns. | Lamport change per account. |
The balance rows are the one source that agrees across all five shapes. They also net out hops. If a program passed USDC through an intermediate account inside one transaction, that account shows no change and only the final holder shows a credit.
From token account to owner
Every token balance entry carries an accountIndex, the mint, the owner wallet and the amount in base units. The index points into the transaction's account list and gives the token account address. The owner field gives the wallet that controls it. Subtract the pre entry at the same index from the post entry. A token account created in the transaction has no pre entry, so its starting amount is zero.
A wallet can own more than one token account for one mint, so the script collects recipients by owner. A payout that landed in two accounts of the same wallet still names one wallet. Amounts stay integers in base units, 6 decimals for USDC, and become text only when they print.
Keep positive differences only. The sender shows a negative change and is no recipient. A wallet that both sends and receives inside the transaction shows its net, and that net is the figure a ledger row can match.
Addresses loaded from lookup tables
A versioned transaction can name some accounts through address lookup tables, so those accounts are absent from the message's own key list. The indexes in the balance arrays count across a combined list: the message's static keys first, then the loaded writable addresses, then the loaded readonly ones. Map an index against the static keys alone and any account past them gets no address.
With jsonParsed the node returns the combined list in accountKeys, each entry tagged with its source, so the script indexes it directly. With other encodings you rebuild the order from loadedAddresses in the meta. To see what a table holds, read it with the lookup table reader.
The resolver script
Run it with no argument and it reads the newest 100 signatures that touched the USDC mint, then prints the first transaction that carries a USDC credit, with any SOL credits beside it. Pass a signature to resolve that transaction instead, whatever it moved. It calls getSignaturesForAddress for the mint and getTransaction with jsonParsed, each at confirmed commitment.
// UC0096 · Payout recipient resolution// https://carbium.sh/library/usecase/payout-recipient-resolution// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MIT// Read-only recipient resolver: who received USDC and SOL in one transaction, read from its balance changes.import { address, createDefaultRpcTransport, createSolanaRpcFromTransport, isSignature, 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 arg = process.argv[2];if (arg !== undefined && !isSignature(arg)) { console.error("Usage: node main.ts [<transaction signature>]"); process.exit(1); }const USDC = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"; // USDC on mainnetconst rpc = createSolanaRpcFromTransport(createDefaultRpcTransport({ url, headers: { "x-api-key": key } }));type Bal = { accountIndex: number; mint: string; owner?: string; uiTokenAmount: { amount: string } };type Parsed = { meta: { err: unknown; fee: number | bigint; preBalances: (number | bigint)[]; postBalances: (number | bigint)[]; preTokenBalances?: Bal[]; postTokenBalances?: Bal[] } | null; transaction: { message: { accountKeys: { pubkey: string }[] } };};const fmt = (n: bigint, d: number) => `${n / 10n ** BigInt(d)}.${(n % 10n ** BigInt(d)).toString().padStart(d, "0")}`;// Credits of one transaction by token account, owner and SOL account; null when the call has no data for it.const resolve = async (sig: string) => { const tx = (await rpc.getTransaction(signature(sig), { commitment: "confirmed", encoding: "jsonParsed", maxSupportedTransactionVersion: 1 }).send()) as unknown as Parsed | null; if (!tx?.meta) return null; const { meta } = tx; const lines: string[] = []; const recipients = new Set<string>(); let usdc = false; if (meta.err) return { lines, recipients: [] as string[], usdc }; // a failed transaction reverted its transfers const keys = tx.transaction.message.accountKeys.map((k) => k.pubkey); // static keys, then lookup-table addresses const pre = new Map((meta.preTokenBalances ?? []).map((b) => [b.accountIndex, b] as const)); const tokenIdx = new Set([...pre.keys(), ...(meta.postTokenBalances ?? []).map((b) => b.accountIndex)]); for (const b of meta.postTokenBalances ?? []) { if (b.mint !== USDC || !b.owner) continue; const gain = BigInt(b.uiTokenAmount.amount) - BigInt(pre.get(b.accountIndex)?.uiTokenAmount.amount ?? "0"); if (gain <= 0n) continue; lines.push(`token account ${keys[b.accountIndex]} owner ${b.owner} ${fmt(gain, 6)} USDC`); recipients.add(b.owner); usdc = true; } keys.forEach((k, i) => { const gain = BigInt(meta.postBalances[i]!) - BigInt(meta.preBalances[i]!) + (i === 0 ? BigInt(meta.fee) : 0n); if (gain <= 0n || tokenIdx.has(i)) return; // a token account's own gain is rent lines.push(`SOL credit ${k} ${fmt(gain, 9)} SOL`); recipients.add(k); }); return { lines, recipients: [...recipients], usdc };};const sigs: string[] = arg ? [arg] : (await rpc.getSignaturesForAddress(address(USDC), { commitment: "confirmed", limit: 100 }).send()).filter((s) => !s.err).map((s) => s.signature);const stop = Date.now() + 25_000;let done = false;for (const sig of sigs) { if (Date.now() > stop) break; try { const r = await resolve(sig); if (!r) { console.log(`${sig.slice(0, 12)} no transaction data, skipped`); continue; } if (!r.lines.length || (!arg && !r.usdc)) { console.log(`${sig.slice(0, 12)} no ${arg ? "" : "USDC "}credits, skipped`); continue; } console.log(`signature ${sig}`); r.lines.forEach((l) => console.log(l)); console.log(`recipients: ${r.recipients.join(", ")}`); done = true; break; } catch (e) { console.log(`${sig.slice(0, 12)} read failed: ${e}`); }}if (!done) console.log("no credit found in these signatures");
run: CARBIUM_KEY=$CARBIUM_KEY node main.ts [<transaction signature>]
getTransaction passes maxSupportedTransactionVersion: 1 because mainnet carries v1 transactions. With the value absent or 0 the call answers -32015, uncharged, for one of them.
Each token credit prints as token account, owner and amount, and each SOL credit prints by account. A lamport gain on an address that appears in the token balance lists is left out, since that is the rent paid to open a token account. The last line is the resolved recipient set: token owners plus the SOL accounts. The fee payer's change has the fee added back, so a payer that only paid the fee shows no credit.
A signature can come from the address index with no transaction data behind it, since the index reaches below the validator's ledger floor. getTransaction then answers null, and one below the floor never gets data. The script prints that signature and moves to the next one. A call that throws is printed and skipped the same way.
What a lookup costs
Cells are the admission charge per call. Resolving one transaction is one getTransaction. Finding the signatures is one getSignaturesForAddress.
| Call | Cells | 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 |
A ledger of 300 payouts with one signature each is 300 calls and 15,000 cells. At the Business rate of 5 req/s that takes 60 s, and at Pro's 25 req/s it takes 12 s. Store the resolved recipients next to the signature so no ledger row triggers a second lookup.
Where it ends
- The balance change shows who ended up holding the value. It does not show who you meant to pay. A ledger recipient that differs from the chain's owner is a mismatch to investigate, and the chain cannot say which side is right.
- A token account closed in the same transaction has a pre entry and no post entry. The script reads the post list, so it reports no credit for that account. The rent lamports it released show as a SOL credit on the account that received them.
- An owner can be a program address, such as a vault or an escrow. The script reports it as the recipient. A payout into a program's custody resolves to a person only through that program's own records.
- A wallet that received funds and passed them on inside the transaction nets to zero and does not appear.
- The script reads one mint. Another token needs its mint address in place of the constant, and a Token-2022 mint with a transfer fee credits the net amount that arrived.
- A failed transaction has its transfers reverted and only the fee moved, so the script skips it. The script reads only: no key, no signing, no sending.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| The ledger's recipient column holds a token account address. | Take the owner field of the token balance entry. The token account is the holding place and the owner is the wallet that controls it. |
| getTransaction answers -32015 for some signatures. | Pass maxSupportedTransactionVersion: 1 with the encoding. With the value absent or 0 the call answers -32015 for a v1 transaction. |
| A recipient address is missing for accounts late in the list. | The index was applied to the static keys only, so an index past their end has no address. Index the combined list instead: static keys, loaded writable, then loaded readonly. The jsonParsed encoding returns it ready. |
| A signature from the address page returns null. | The index lists signatures below the validator's ledger floor, and one there never gets transaction data. Skip it and resolve payouts from signatures the ledger still holds. |
| A freshly created token account shows up as a SOL recipient. | That lamport gain is the rent paid to open the account. Skip every index that appears in the pre or post token balance lists. |
| The resolved owner is a program address. | Treat it as custody. The payout reached a program's vault, and the person behind it comes from that program's records. |
Questions
Why read balances and not the instructions?
Instructions follow a layout per program, and a token transfer never names the receiving wallet. Balance entries give the owner and the amount in one shape for every transfer, including those made inside another program's call.
Is the receiving wallet in the account keys?
Not reliably. For a SOL transfer the destination is the wallet. For a token transfer to an existing token account the keys list the token account and the sender's authority, and the wallet sits in the owner field of the balance entry.
Can one transaction pay several people?
Yes. Each recipient gets its own credit line, and you match the amounts to ledger rows. A wallet paid into two token accounts collapses to one recipient because the script groups by owner.
How do I resolve a payout paid in SOL?
Read the lamport change of every account in the combined list, with the fee added back for the fee payer. The script prints each positive change and leaves out the rent paid to open token accounts.