services
Get a key

library / Use cases / UC0025

Merchant end-of-day report

Add up what a merchant account received in a day: which address to list for SOL and for a token, what each payment costs in calls, and a Node report that totals, counts and flags what it could not read.

By Carbium · Payments and checkout · UC0025 · updated 2026-11-22

01

What the report adds up

A shop that takes Solana payments closes its day with the same questions a till answers: how many payments came in, how much, which was the largest, and whether anything looks wrong. Every payment is a transaction that changed a balance.

The report here lists the signatures an account appears in for a window, reads each successful transaction once, and takes the balance change of the merchant's account in that transaction. Positive changes count as payments. It prints each payment, then the count, the total in base units, the largest payment, and what it skipped or could not read.

Checking one order as it happens is a different job, covered in Solana Pay confirmation. The end-of-day report works after the fact on the account itself, which makes it a reconciliation tool: you compare its total with what your order system says was sold, and a gap in either direction is the thing to investigate. A live feed of the same sales is described in Point-of-sale recent sales.

02

Which address to list

getSignaturesForAddress returns the transactions that mention an address. For a merchant paid in SOL that is the merchant wallet, and the lamport balance change in each transaction is the payment.

A token payment works differently. In a USDC sale the account list holds the customer's token account, the shop's token account and the customer's signer, and the shop wallet is absent. Listing signatures for the wallet therefore misses most USDC sales. List the merchant's token account for that mint instead, and read the amount from the token balances in each transaction, matching the mint and the owning wallet.

A shop can own more than one USDC account, and a checkout or a customer's wallet may pay into a second one. If your checkout always pays to one account, list that one. If customers or tools sometimes pay to another, run the report once per account. Each run sums the owner's balances for the mint inside one transaction, so a move between the merchant's own accounts nets to zero, but a transaction that touches two of your accounts appears in both listings and is counted in both runs. Compare the signature lists of the runs and drop duplicates before you add the totals. The payment lines each run prints carry the signatures to compare.

03

The report in one file

The script takes the account to list as its first argument and reads CARBIUM_KEY from the environment, sending every call to https://services.carbium.sh with the key in x-api-key, or to CARBIUM_RPC_URL when you set it. END is the cut in Unix seconds and defaults to now. HOURS sets the window length and defaults to 24, so the window runs from END minus HOURS times 3600 up to END. MAX_TX caps how many signatures it takes from the window, failed ones included, and reads the successful ones among them. It defaults to 10, so a first run finishes in seconds. For a real day, raise it above the day's count. RATE is your plan's getTransaction rate in requests per second from the table below and defaults to 0.24, the Free rate. MINT and OWNER switch it to a token: the first argument is then the token account, and OWNER is the wallet that owns it.

main.ts
// UC0025 · Merchant end-of-day report// https://carbium.sh/library/usecase/merchant-end-of-day-report// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MIT// Read-only end-of-day report: what one account received in a time window, from its on-chain history.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";if (!process.argv[2]) { console.error("Usage: node main.ts <account to report on>"); process.exit(1); }const account = address(process.argv[2]);const mint = process.env.MINT; // set for a token report; the account is then the merchant's token accountconst owner = process.env.OWNER; // the wallet that owns that token accountif (mint && !owner) { console.error("Set OWNER to the wallet that owns the token account."); process.exit(1); }const maxTx = Number(process.env.MAX_TX ?? 10), hours = Number(process.env.HOURS ?? 24);const end = Number(process.env.END ?? Math.floor(Date.now() / 1000)); // the cut, Unix secondsconst since = end - hours * 3600;const commitment = "finalized";const BURST = 20; // getTransaction calls a rate class absorbs at once below Proconst rate = Number(process.env.RATE ?? 0.24); // the plan's getTransaction req/s; Free is 0.24const rpc = createSolanaRpcFromTransport(createDefaultRpcTransport({ url, headers: { "x-api-key": key } }));const errText = (e: unknown) => (e instanceof Error ? e.message : String(e));// seconds to wait when the error is a 429, else nullconst retryAfter = (e: unknown): number | null => {  const c = (e as { context?: { statusCode?: number; headers?: ConstructorParameters<typeof Headers>[0] } } | null)?.context;  if (c?.statusCode !== 429) return null;  return Number(new Headers(c.headers).get("retry-after")) || 1;};// balance change of the account in one transaction; null when the transaction cannot be readasync function received(sig: Signature): Promise<bigint | null> {  const tx = await rpc.getTransaction(sig, { encoding: "json", maxSupportedTransactionVersion: 1, commitment }).send();  const meta = tx?.meta;  if (!tx || !meta || meta.err) return null;  if (mint) {    const sum = (rows: readonly { mint: string; owner?: string; uiTokenAmount: { amount: string } }[] | null | undefined) =>      (rows ?? []).filter((b) => b.mint === mint && b.owner === owner).reduce((n, b) => n + BigInt(b.uiTokenAmount.amount), 0n);    return sum(meta.postTokenBalances) - sum(meta.preTokenBalances);  }  const keys = [...tx.transaction.message.accountKeys, ...(meta.loadedAddresses?.writable ?? []), ...(meta.loadedAddresses?.readonly ?? [])];  const i = keys.indexOf(account);  return i < 0 ? 0n : BigInt(meta.postBalances[i]!) - BigInt(meta.preBalances[i]!);}// one call that sleeps for the retry-after hint on a 429 and tries again, five tries in allasync function retry<T>(call: () => Promise<T>): Promise<T> {  for (let n = 0; ; n++) {    try { return await call(); } catch (e) {      const s = retryAfter(e);      if (s === null || n >= 4) throw e;      await new Promise((r) => setTimeout(r, s * 1000));    }  }}const read = (sig: Signature) => retry(() => received(sig));const sigs: { signature: Signature; err: unknown }[] = [];let reachedWindowStart = false;try {  let before: Signature | undefined;  while (sigs.length < maxTx && !reachedWindowStart) {    const page = await retry(() => rpc.getSignaturesForAddress(account, { limit: 50, before, commitment }).send());    if (page.length === 0) { reachedWindowStart = true; break; }    for (const s of page) {      const t = Number(s.blockTime ?? 0);      if (t >= end) continue; // after the cut      if (t < since) { reachedWindowStart = true; break; }      sigs.push(s);    }    before = page[page.length - 1]!.signature;  }} catch (e) { console.error(retryAfter(e) === null ? "Listing failed:" : "Listing hit 429 after five tries:", errText(e)); process.exit(1); }const day = sigs.slice(0, maxTx);const failedOnChain = day.filter((s) => s.err !== null).length;const todo = day.filter((s) => s.err === null).map((s) => s.signature);const reads: PromiseSettledResult<bigint | null>[] = [];for (let i = 0; i < todo.length; i += BURST) {  if (i > 0) await new Promise((r) => setTimeout(r, (BURST / rate) * 1000)); // let the plan's cells refill  reads.push(...(await Promise.allSettled(todo.slice(i, i + BURST).map(read))));}let total = 0n, largest = 0n, payments = 0, unreadable = 0, failedReads = 0;for (const [i, r] of reads.entries()) {  if (r.status === "rejected") { failedReads++; console.error("read failed:", errText(r.reason)); continue; }  if (r.value === null) { unreadable++; continue; }  if (r.value > 0n) { payments++; total += r.value; if (r.value > largest) largest = r.value; console.log(`payment ${todo[i]} ${r.value}`); }}console.log(`account ${account}, window ${hours} h ending ${new Date(end * 1000).toISOString()}, ${day.length} signatures listed`);console.log(reachedWindowStart && sigs.length <= maxTx ? "window fully covered" : `stopped at MAX_TX=${maxTx}: the total covers only the newest part of the window`);console.log(`payments ${payments}, total ${total} base units, largest ${largest}`);if (!mint) console.log(`total ${total / 1_000_000_000n}.${(total % 1_000_000_000n).toString().padStart(9, "0")} SOL`);console.log(`failed on chain ${failedOnChain}, unreadable ${unreadable}, read errors ${failedReads}`);

run: CARBIUM_KEY=$CARBIUM_KEY HOURS=24 MAX_TX=10 node main.ts <merchant account>

The listing pages back with before, skips signatures at or after END, and stops when a signature is older than the window or the cap is reached, and it says which one stopped it. Signatures whose transaction failed on chain are counted and never read, since a failed payment moves nothing into the merchant's account. Every other transaction is read with getTransaction, with maxSupportedTransactionVersion: 1 because mainnet carries v1 transactions and the call answers -32015 for one when the value is absent or 0. The listing and every read run at finalized.

The reads go out in groups of 20, the size of the burst, and each is settled on its own, so one refused or empty read shows up in the summary and the rest of the day still totals. A read that returns null is counted as unreadable. The totals print as integer base units, with a SOL figure beside the total when no mint is set. Amounts stay in base units inside the script, so the sum has no rounding.

04

What a day costs in calls

Both calls the report depends on cost 50 cells: one getSignaturesForAddress per page of signatures and one getTransaction per payment. All keys on your Carbium account share one budget, so a report run competes with whatever else your checkout does on the same account.

PlangetTransaction req/s300 payments read in about
Free0.2421 minutes
Dev1.24 minutes
Business51 minute
Pro2512 seconds

The times assume the calls run at the plan's rate for that method. A class absorbs a burst of 1,024 cells or one second of its rate, whichever is larger. That is about twenty getTransaction calls at once below Pro, and 25 on Pro, where one second of the rate is 1,250 cells. The script sends 20 at a time and waits 20 divided by RATE seconds between groups, which is the time the plan needs to refill the cells those 20 reads used. Listing pages go out one after another, and a day of more than about 20 pages spends the same burst on Free. A listing page or a read that still gets a 429 sleeps for the retry-after hint and is sent again, up to four more times.

05

Closing the day

  • Pass the Unix time of your shop's local closing moment as END, and set HOURS to the length of the day. blockTime is UTC seconds, so a shop that closes at local midnight takes that moment, and a daylight-saving change moves it by an hour.
  • Run the report a few minutes after closing time. Payments after END are skipped, so a late run counts the same day.
  • Run it from a scheduled job on your server, once per account per day, and keep the key there.
  • Save each day's signatures with the totals. The address index behind the listing keeps up to 30 days, so the totals for last month's days come from your own records.
  • Match the total against orders. If each order carries a reference key as in Solana Pay confirmation, the reference tells you which order each signature settles. The balance change tells you the amount.
06

Where it ends

  • Any positive balance change counts as a payment. A refund from a supplier, a top-up from your own other wallet and a sale all look the same to the report. Fund your merchant account from known addresses and subtract them, or tag orders with reference keys and match on those.
  • Payments that go out of the account, such as refunds and sweeps to cold storage, are skipped, so the total is takings and the account's closing balance will not equal opening balance plus the total.
  • History comes from the 30-day address index, and an empty page past it marks the age limit. A report for an older day needs the signatures you saved at the time.
  • The index lists signatures from below the node's ledger floor, so an older day can include a signature whose transaction the node no longer holds, and getTransaction returns null for it. The report counts those as unreadable and prints how many, so a high count means that day has to be rebuilt from your own records.
  • The script reads the first MAX_TX signatures in the window, newest first. If it stops at the cap, the total covers only the newest part of the day, and the output says so. Raise the cap before you rely on a total.
  • It reads and adds. It builds no payment requests, signs nothing and sends nothing, and it does not fetch exchange rates, so fiat value of a day's SOL is a separate step.
07

When it goes wrong

what goes wrongwhat to do
The USDC total is zero while customers paid.The listing was for the merchant wallet, and a token transfer to an existing token account never names the wallet. List the merchant's token account for that mint, and set MINT and OWNER.
The report ends in a 429 on a large day.The script retries a refused listing page or read four more times after the retry-after hint, five tries in all. If a read still ends in 429, RATE is above your plan's getTransaction rate or a Free key's shared network budget is spent: set RATE from the table, run the job later, or on a plan whose rate covers the day's count. If the output says the listing hit 429, the day has more pages than the plan's getSignaturesForAddress rate and burst cover, so run the job later or on a plan with a higher rate.
Some payments show as unreadable and the total looks short.The index lists signatures below the node's ledger floor, and getTransaction returns null for them, so the report cannot read those payments. Rebuild that day's total from the signatures and payment lines you saved the evening it ended. Then run the report each evening for the day just ended and save its output, so the next day never depends on a null read.
A daylight-saving day gives a total that disagrees with the till.On the days the clocks change, the local day is 23 or 25 hours long, so HOURS=24 ends an hour away from the closing moment. Set END to the local closing time and HOURS to the real length of that day.
The total includes money that was never a sale.Every inflow counts. Tag orders with a reference key and reconcile by reference, and exclude transfers from your own wallets.
The same day gives a different total on two runs.The window ended at run time, so each run covered a different span, or the first run stopped at MAX_TX. Set END to the cut and raise the cap.
08

Questions

Can I get the report without reading every transaction?

For a SOL account the job can record getBalance at each close and compare the two readings, but that gives net change with refunds and top-ups inside it. A per-payment count and a largest payment need each transaction, one getTransaction each.

Does the report need a WebSocket?

No. It reads history after the day ends with plain RPC calls. A live running tally is a separate build that subscribes to logs for the account and reads each payment as it arrives.

How do I report several merchant accounts?

Run the script once per account and add the results. Every key on your Carbium account draws on one budget, so run the merchant accounts one after another so a morning of reports stays inside the plan's rate.