Protocol fee revenue report
Measure what a protocol earned in fees from the history of its fee account: per-transaction inflows, their total and mean, set beside the account's current balance, with SOL fees and token fees kept apart.
Where an in-program fee lands
A program charges a fee inside an instruction by moving value to an account the protocol controls. A program can only touch accounts the transaction names, so each form of charge needs its accounts listed in the instruction.
| Fee form | Accounts the instruction lists | Notes |
|---|---|---|
| System Program transfer | the payer as signer and writable, the fee account writable, the System Program | lamports, moved by cross-program invocation signed by the payer |
| SPL Token transfer | the payer's token account writable, the payer's wallet as signer, the fee token account writable, the mint, the token program | smallest unit of the mint, moved by cross-program invocation |
| Lamports moved directly | an account the program owns, writable, and the fee account, writable | lamports; the debit needs no signer because the program owns the source |
The amount is usually a share of the amount the instruction already carries: fee = amount * fee_bps / 10_000 in integer math, rounded down, with checked multiplication so a large amount cannot overflow. Basis points are hundredths of a percent, so 25 is 0.25 percent. Whichever form ran, the outcome on chain is a balance change on the fee account.
The instruction logic that computes the amount and makes the transfer is program code, and it belongs in your program's own tests on a local validator. This report starts after it. It measures what reached the fee account, which is the revenue figure whatever instruction took the fee, whichever program version ran, and however many charges one transaction carried.
A fee account takes one of two shapes: a wallet that holds SOL, or a token account for a mint such as USDC, often owned by a program-derived address or a multisig. A wallet can own several token accounts for one mint, so a protocol that collects USDC may have more than one account to report on. Run the script once per account.
Inflows from balance deltas
Every confirmed transaction records each touched account before and after it ran: lamports in preBalances and postBalances, and token amounts in preTokenBalances and postTokenBalances, keyed by the account's position in the transaction. After minus before, for the fee account, is that transaction's effect on it. A positive number is an inflow. Zero means the transaction touched the account and changed nothing, and a negative number is a withdrawal. A failed transaction leaves token balances as they were, so the script skips any transaction that carries an error.
One delta per transaction means the inflow count is the number of transactions that paid the account. A transaction whose two instructions each charged the fee counts once, with both charges in the sum. The amounts are integers in the token's smallest unit, and the script keeps them as BigInt so a long sum stays exact.
| Call | Cells | In one run |
|---|---|---|
| getTokenAccountBalance | 10 | one |
| getSignaturesForAddress | 50 | one, two with a stand-in |
| getTransaction | 50 | up to 5, up to 10 with a stand-in |
With your own token account a run spends 310 cells: 10, 50 and five times 50. The stand-in lookup adds up to 300 more. A SOL wallet run adds one getBalance read after the token balance read is rejected. Cells are the admission charge per call, and each call class has its own rate on every plan.
Mainnet carries version 1 transactions, and getTransaction answers -32015 for one unless the request sends maxSupportedTransactionVersion: 1 with an encoding. The script sends both, jsonParsed and 1. Every call in it names confirmed commitment.
SOL fees versus token fees
The two kinds of fee sit in different arrays. SOL arrives as a lamport change at the account's index in preBalances and postBalances, where 1 SOL is 1,000,000,000 lamports. A token fee arrives as a change in the account's entry in the token balance arrays, in the smallest unit of its mint. The script looks for a token entry on the account first and falls back to lamports when there is none, so one file reads a SOL wallet or a USDC account. The current balance follows the same split: the token balance call first, then getBalance in lamports for a wallet.
| Fee form | Where the delta sits | Unit |
|---|---|---|
| SOL to a wallet | postBalances minus preBalances at the wallet's index | lamports |
| Token to a token account | postTokenBalances minus preTokenBalances at the account's index | smallest unit of the mint; USDC has 6 decimals |
| Wrapped SOL in a token account | the token balance arrays, as above | lamports, 9 decimals |
A protocol that charges in both SOL and a token has at least two fee accounts and two reports, and their totals never add: 1,000,000 lamports is 0.001 SOL and 1,000,000 USDC units is 1 USDC. If you need one figure, convert each inflow at the price of its own time and keep the unit beside every number you publish. Wrapped SOL account reader covers the wrapped case.
The report script
Pass a fee account as the only argument. With no argument the script finds one: it reads the newest transactions that mention the USDC mint, skips any with an error or a failed read, and picks the token account with the smallest positive USDC gain in the first transaction that has one. It prints that account and names it as a stand-in. A stand-in is an arbitrary account, so its totals show what the output looks like and say nothing about any protocol's revenue. The key comes from CARBIUM_KEY, and the script exits with a message when it is unset.
// UC0067 · Protocol fee revenue report// https://carbium.sh/library/usecase/protocol-fee-revenue-report// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MIT// Read-only: totals the newest inflows to a protocol's fee account and prints its current balance.import { address, createDefaultRpcTransport, createSolanaRpcFromTransport, type 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 USDC = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";type Bal = { accountIndex: number; mint: string; uiTokenAmount: { amount: string } };type Tx = { transaction: { message: { accountKeys: { pubkey: string }[] } }; meta: { err: unknown; preBalances: readonly (bigint | number)[]; postBalances: readonly (bigint | number)[]; preTokenBalances?: Bal[]; postTokenBalances?: Bal[] } | null;};const cfg = { commitment: "confirmed", encoding: "jsonParsed", maxSupportedTransactionVersion: 1 } as const;const load = async (sig: Signature) => (await rpc.getTransaction(sig, cfg).send()) as unknown as Tx | null;// Change in the account's token balance in one transaction; lamports when it holds no token entry.function delta(tx: Tx, account: string): bigint | null { const m = tx.meta; const i = tx.transaction.message.accountKeys.findIndex((k) => k.pubkey === account); if (!m || m.err || i < 0) return null; const at = (l?: Bal[]) => l?.find((b) => b.accountIndex === i); const pre = at(m.preTokenBalances), post = at(m.postTokenBalances); if (pre || post) return BigInt(post?.uiTokenAmount.amount ?? 0) - BigInt(pre?.uiTokenAmount.amount ?? 0); return BigInt(m.postBalances[i]) - BigInt(m.preBalances[i]);}// Stand-in: the token account with the smallest positive USDC gain in the first USDC transaction that has one.async function standIn(): Promise<string> { const sigs = await rpc.getSignaturesForAddress(address(USDC), { limit: 5, commitment: "confirmed" }).send(); for (const s of sigs.filter((s) => s.err === null)) { let tx: Tx | null; try { tx = await load(s.signature); } catch { continue; } if (!tx?.meta) continue; const pre = new Map((tx.meta.preTokenBalances ?? []).map((b) => [b.accountIndex, BigInt(b.uiTokenAmount.amount)])); const gains = (tx.meta.postTokenBalances ?? []).filter((b) => b.mint === USDC) .map((b) => ({ i: b.accountIndex, d: BigInt(b.uiTokenAmount.amount) - (pre.get(b.accountIndex) ?? BigInt(0)) })) .filter((g) => g.d > BigInt(0)).sort((a, b) => (a.d < b.d ? -1 : 1)); if (gains.length) return tx.transaction.message.accountKeys[gains[0].i].pubkey; } throw new Error("no USDC gain in the newest signatures");}// Token balance for a token account; a SOL wallet is rejected there, so fall back to its lamports.async function balanceOf(a: string): Promise<string> { try { const b = (await rpc.getTokenAccountBalance(address(a), { commitment: "confirmed" }).send()).value; return `${b.amount} (${b.uiAmountString})`; } catch { return `${(await rpc.getBalance(address(a), { commitment: "confirmed" }).send()).value} lamports`; }}const given = process.argv[2];const account = given ?? await standIn();if (!given) console.log(`stand-in account ${account}: smallest USDC gain in the first USDC transaction with one`);const [bal, sigs] = await Promise.allSettled([ balanceOf(account), rpc.getSignaturesForAddress(address(account), { limit: 20, commitment: "confirmed" }).send(),]);if (sigs.status === "rejected") { console.error("getSignaturesForAddress failed:", String(sigs.reason)); process.exit(1); }const picked = sigs.value.filter((s) => s.err === null).slice(0, 5);const reads = await Promise.allSettled(picked.map((s) => load(s.signature)));const inflows: bigint[] = [];reads.forEach((r, n) => { const tag = picked[n].signature.slice(0, 12); if (r.status === "rejected") { console.error(` ${tag} failed:`, String(r.reason)); return; } const d = r.value ? delta(r.value, account) : null; console.log(` ${tag} delta ${d ?? "n/a"}`); if (d !== null && d > BigInt(0)) inflows.push(d);});const total = inflows.reduce((a, b) => a + b, BigInt(0));const mean = inflows.length ? total / BigInt(inflows.length) : BigInt(0);const balance = bal.status === "fulfilled" ? bal.value : `unavailable (${String(bal.reason)})`;console.log(`inflows ${inflows.length} total ${total} mean ${mean} current balance ${balance}`);
run: CARBIUM_KEY=$CARBIUM_KEY node main.ts [fee-token-account]
The script reads the newest 20 signatures of the fee account, keeps the first five without an error, and reads those transactions. It prints each delta, then one line with the inflow count, total, mean and current balance. The mean is an integer division in the smallest unit. Each call settles on its own, so a failed read prints a line and the others still count, and a null transaction, which an older listed signature can return, is skipped. Nothing is signed or sent.
Reconciling with the balance
The balance is the sum of every delta since the account was created, inflows and outflows together. The five transactions in the script's window are a sample, so their inflow total will not equal the balance and should not be forced to.
What can be checked is the window itself. The balance before the oldest transaction you read equals the current balance minus every delta in the window, outflows included, and the script prints each one. That value should match the oldest transaction's own preTokenBalances entry for the account. A mismatch of exactly one delta means a transaction landed between the balance read and the signature read: read the balance again after the list and rerun.
For a full reconciliation, page the signature list back with before (Signature history pagination) until it ends, and sum all deltas. The list reaches back 30 days at most, so for an account older than that, record an opening balance at the start of your window and reconcile from there.
Where it ends
- Which instruction: a delta says how much arrived and nothing about which instruction charged it. The inner instructions and logs say that, and Inner instruction tree reads them.
- Other inflows: a plain transfer into the fee account looks like revenue. If the account receives anything besides fees, filter on the program id among the transaction's account keys before counting.
- Sample: five transactions are a sample. A busy protocol needs paging and a store, and Creator royalty income tracker keeps a SQLite tally in that way.
- History: the signature list comes from an address index that keeps up to 30 days. A listed older signature can return null from getTransaction, and an empty page past 30 days is the index's age limit, so the account may have older inflows.
- Charging code: the report cannot show that the program charges what its design says. A fee the program skipped leaves no trace, so compare the inflow count with the number of instructions your own logs show should have charged.
- Value: amounts stay in the smallest unit. A USD figure needs a price at the time of each inflow.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| getTransaction answers -32015 for a recent transaction. | The transaction is version 1 and the request left out maxSupportedTransactionVersion. Send 1 together with an encoding, as the script does. |
| getTransaction returns null for a signature the list just gave. | The address index reaches below the validator's ledger floor, so an older signature can list with no transaction behind it. The script skips the null; test it on the newest signatures. |
| The current balance line says unavailable. | Both balance reads failed: getTokenAccountBalance and then the getBalance fallback. The deltas come from other calls and still print; check the address and rerun. |
| The run shows no inflows on an account you know gets fees. | You passed the owner wallet. A token transfer lists the token accounts, never the receiving wallet, so pass the token account itself, and run once per token account the wallet owns. |
| The inflow count is lower than the number of times the fee was charged. | The count is per transaction. Two charges in one transaction make one inflow with both amounts in the delta, so count instructions from the logs if you need charges. |
| A stand-in run reports one or two inflows. | The stand-in is an arbitrary account with a short history. Pass your own fee account to get its real window. |
Questions
Does the fee have to go to a token account?
No. A program can move SOL to a wallet or tokens to a token account, whichever the protocol collects. The script reads either, and a protocol that collects both runs it once for each account.
Why not decode the fee instruction instead?
Decoding needs each program version's layout and breaks when it changes. A balance delta reads the same for any instruction, which is why this report counts revenue where it lands. Decoding answers a different question, which instruction charged.
How far back can the report go?
The signature list reaches back 30 days at most. For longer history, keep your own opening balance and totals from earlier runs and add the new window to them.