services
Get a key

library / Blockchain ideas / BI0021

Invoice payment tracker

A tracker that turns an invoice into a status. It reads finalized payments to the payee's address, sums them against the amount due, keeps each payment in a local SQLite table and reports unpaid, partial, paid or overpaid. Runnable code and plan costs included.

By Carbium · Commerce · BI0021 · updated 2026-11-22

01

Who uses it

A freelancer, a small agency or an online shop sends an invoice that asks for a fixed amount in SOL at one address. Afterwards the sender wants one answer per invoice: unpaid, partly paid, paid or overpaid. Today that answer usually comes from opening an explorer, finding the right transfer and adding up the amounts by hand.

A hackathon team can build the back office in a weekend: an invoice list on the left, a status on the right, a payment history under each row. Every read is public, so the demo needs only a busy wallet standing in for the payee. Swap in your own address when the first real invoice goes out. All calls go to services.carbium.sh under one key.

02

What it tracks

An invoice is a small record: an id, the payee address, the amount due and the time it was issued. A payment is a finalized transaction after that time in which the payee's balance rose. The tracker adds the payments up, so a customer who pays in two transfers still settles the invoice.

StatusRuleTypical next step
Unpaidno finalized payment since the issue timesend a reminder
Partialthe total received is below the amount dueask for the difference
Paidthe total equals the amount dueclose the invoice
Overpaidthe total is above the amount duerefund or credit the extra

The amount of a payment is the change in the payee's lamport balance, read from the transaction's meta. That works for a plain System transfer and for a payment routed through another program, because the balance change records the outcome. A lamport is a billionth of a SOL, and the code converts the amount due once, with rounding, so the comparison is between whole numbers.

$A status is evidence about an address. It shows that SOL arrived, and the tracker cannot say which customer sent it.
03

The build

One file with @solana/kit and what Node 24 ships. It is read-only: no private key, nothing signed or sent. Run it with the payee address and the amount due in SOL, and it prints each new payment and then the invoice status.

  1. Read the payee and the amount due from the command line, and INVOICE (the invoice id), SINCE (the issue time in unix seconds) and LIMIT from the environment.
  2. Open invoices.db with node:sqlite and create the payments table, keyed by invoice and signature.
  3. Call getSignaturesForAddress on the payee at finalized commitment for the newest LIMIT signatures only (5 by default). Skip failed transactions, signatures older than SINCE and signatures already stored.
  4. For each new signature, wait GAP_MS, then call getTransaction at finalized with jsonParsed encoding and maxSupportedTransactionVersion set to 1.
  5. Store the payee's balance gain, zero included, so the next run never reads that signature again.
  6. Sum the invoice's rows and print the status.
main.ts
// BI0021 · Invoice payment tracker// https://carbium.sh/library/blockchainideas/invoice-payment-tracker// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { DatabaseSync } from "node:sqlite";import { address, createDefaultRpcTransport, createSolanaRpcFromTransport } from "@solana/kit";const key = process.env.CARBIUM_KEY ?? "";const payee = process.argv[2] ?? "";const due = Math.round(Number(process.argv[3] ?? "") * 1e9); // amount due in lamportsif (!key || !payee || !(due > 0)) {  console.error("Set CARBIUM_KEY, then run: node main.ts <payee wallet> <amount due in SOL>");  process.exit(1);}const invoice = process.env.INVOICE ?? "INV-1";const since = Number(process.env.SINCE ?? 0); // unix seconds when the invoice was issuedconst LIMIT = Number(process.env.LIMIT ?? 5);const GAP_MS = Number(process.env.GAP_MS ?? 4500); // 50 cells per call: one call per 4.5 s fits Free's 0.24 req/sconst rpc = createSolanaRpcFromTransport(  createDefaultRpcTransport({    url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh",    headers: { "x-api-key": key },  }),);type Tx = {  meta: { preBalances: (number | bigint)[]; postBalances: (number | bigint)[] } | null;  transaction: { message: { accountKeys: { pubkey: string }[] } };};const db = new DatabaseSync("invoices.db");db.exec("CREATE TABLE IF NOT EXISTS payments (invoice TEXT, signature TEXT, lamports INTEGER, paid_at TEXT, PRIMARY KEY (invoice, signature))");const seen = db.prepare("SELECT 1 FROM payments WHERE invoice = ? AND signature = ?");const store = db.prepare("INSERT OR IGNORE INTO payments VALUES (?, ?, ?, ?)");const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));async function main() {  const sigs = await rpc.getSignaturesForAddress(address(payee), { limit: LIMIT, commitment: "finalized" }).send();  console.log(`${sigs.length} recent signatures at ${payee}`);  for (const s of sigs) {    if (s.err !== null || s.blockTime === null || Number(s.blockTime) < since || seen.get(invoice, s.signature)) continue;    await sleep(GAP_MS);    try {      const tx = (await rpc        .getTransaction(s.signature, { commitment: "finalized", encoding: "jsonParsed", maxSupportedTransactionVersion: 1 })        .send()) as unknown as Tx | null;      if (!tx?.meta) {        console.log(`${s.signature.slice(0, 8)} not readable, skipped`);        continue;      }      // The payment is whatever the payee's balance gained in this transaction.      const at = tx.transaction.message.accountKeys.findIndex((k) => k.pubkey === payee);      const gain = at < 0 ? 0 : Math.max(0, Number(tx.meta.postBalances[at]) - Number(tx.meta.preBalances[at]));      store.run(invoice, s.signature, gain, new Date(Number(s.blockTime) * 1000).toISOString());      console.log(`${s.signature.slice(0, 8)} +${gain / 1e9} SOL`);    } catch (e) {      console.log(`${s.signature.slice(0, 8)} failed: ${e instanceof Error ? e.message : e}`);    }  }  const row = db.prepare("SELECT COALESCE(SUM(lamports), 0) AS total FROM payments WHERE invoice = ?").get(invoice) as unknown as { total: number };  const status = row.total === 0 ? "unpaid" : row.total < due ? "partial" : row.total === due ? "paid" : "overpaid";  console.log(`${invoice}: ${status}, ${row.total / 1e9} of ${due / 1e9} SOL received`);}main().catch((e) => {  console.error(e instanceof Error ? e.message : e);  process.exit(1);});

run: CARBIUM_KEY=<YOUR_KEY> INVOICE=INV-1 node main.ts <PAYEE_WALLET> 0.5

Both calls ask for finalized, because a paid mark is hard to undo.

Setting maxSupportedTransactionVersion to 1 matters because mainnet carries v1 transactions, and a payment sent as one would otherwise fail the read. GAP_MS defaults to 4500, which spaces the 50-cell reads to fit the Free plan. Lower it on a bigger plan.

Each read sits in its own try, so one failing signature prints its message and the loop goes on. The table also makes reruns idempotent: run the file ten times and the totals stay the same.

04

What it costs

Two methods do the work. One getSignaturesForAddress call per refresh costs 50 cells, and each new signature adds one getTransaction call at 50 cells, outgoing and zero-gain transactions included. The first read of a busy address is the expensive one, and the plan sets how fast it goes. Limits belong to the account, so every other tool on its keys draws from the same budget.

PlanCreditsgetTransaction rategetSignaturesForAddress rateFirst read of ten new signatures
Free ($0)500K once, at sign-up0.24 req/s0.24 req/sabout 42 s
Dev ($20)10M per month1.2 req/s1.2 req/sabout 8.3 s
Business ($250)50M per month5 req/s100 req/s2 s
Pro ($500)200M per month25 req/s500 req/s0.4 s

The last column is ten reads divided by the plan's getTransaction rate, before network time. After the first run the table does the remembering. A listing every 30 seconds is 0.033 req/s, well under Free's 0.24, and a refresh that finds nothing new costs that single listing call.

05

What to add next

  • One address per invoice. Give each invoice its own receiving address or a Solana Pay reference key, then list at that address. A payment is matched to its invoice by where it went, so two invoices for the same amount never get mixed up. Solana Pay confirmation walks through the reference flow.
  • Live status. Open wss://services.carbium.sh with the key as ?api-key= and send logsSubscribe with a mention of the payee. It costs 25 credits to open and then 20 credits per MiB sent, and each notification carries a signature to hand to the same reader. A plain SOL wallet gets nothing from accountSubscribe, so the logs mention plus getBalance is the pairing.
  • Token invoices. For a stablecoin invoice, list at the payee's token account and read postTokenBalances instead of lamports. Point-of-sale recent sales shows that path.
  • Reminders. A query for invoices still unpaid after their due date, sent to email or chat.
  • A ledger export. One CSV row per payment with invoice, signature, amount and time, for the accountant.
06

Where it ends

  • History is the 30-day address index at most. An older payment is not served, and an empty page past that marks the index's age limit. Keep invoices.db, because it is the only record that outlives the window.
  • The listing reads only the newest LIMIT signatures (5 by default) and never pages back, so on a busy payee a payment older than that window is missed. Raise LIMIT to cover the time since SINCE.
  • The code counts SOL only. A payment in a token needs the token path above.
  • One shared address cannot tell invoices apart. Every payment after SINCE counts toward every invoice run against that payee.
  • Refunds you send are not subtracted. The code counts only balance increases, so an invoice you refunded still reads paid.
  • If the payee also pays the network fee in a transaction, the balance change is net of that fee. The payment reads short by at least the 5,000-lamport base fee per signature plus any priority fee, and the invoice reads partial by that much.
  • A listed signature with no block time is skipped until the node reports one, and a transaction the node returns as null is skipped and printed.
  • The code does not convert prices. An invoice in dollars needs its SOL amount fixed when you issue it, and you store that amount.
07

When it goes wrong

what goes wrongwhat to do
An invoice reads unpaid and the customer says they paid.Check where the money went. The code counts SOL that arrived at the listed address after SINCE. A payment in a token, to another address or before the issue time is not counted.
getTransaction answers -32015.The call left out maxSupportedTransactionVersion, or set it to 0, and the transaction is v1. Pass 1 on every getTransaction call in code you write.
getTransaction returns null for a signature the listing just gave.The address index reaches below the validator's ledger floor, so an old signature can list and then read as null. The code prints it and skips it. Keep your own rows for anything older than the node's ledger.
A paid invoice reads partial by the network fee.The payee paid the network fee in that transaction, so the balance change is net of it: at least 5,000 lamports per signature plus any priority fee. Have the customer pay from their own wallet, so the customer's wallet pays the fee.
A paid invoice falls back to unpaid after a month.The invoices.db file was deleted or moved, and the listing no longer reaches the payment. Restore the file from backup. Payments older than 30 days cannot be read again.
The run stops with a clear message instead of output.The key or an argument is missing. Set CARBIUM_KEY and pass the payee address and the amount due in SOL.
08

Questions

Do I need a separate address for each invoice?

For a demo, no. For real use, yes: with one address per invoice, or a reference key per invoice, each payment belongs to exactly one invoice by construction.

How often should the tracker poll?

Every 30 seconds is plenty for most invoices and fits the Free plan's listing rate. For instant status, subscribe to the payee's logs and read each new signature as it arrives.

Can it track a USDC invoice?

Yes, with a change in the reader. List at the payee's token account and compare the token balance rows in the transaction meta, as the point-of-sale entry does. A wallet can own more than one token account for a mint, so list at the one you published.

Will it run on the Free plan?

Yes. The first read of a busy address is slow at 0.24 req/s, and later runs read only new payments from the table.