---
id: BI0021
title: "Invoice payment tracker"
url: https://carbium.sh/library/blockchainideas/invoice-payment-tracker
collection: Blockchain ideas
category: Commerce
revision: 1
updated: 2026-11-22
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# 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.

## 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.

## 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.

| Status | Rule | Typical next step |
|---|---|---|
| Unpaid | no finalized payment since the issue time | send a reminder |
| Partial | the total received is below the amount due | ask for the difference |
| Paid | the total equals the amount due | close the invoice |
| Overpaid | the total is above the amount due | refund 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.

## 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` (run: `CARBIUM_KEY=<YOUR_KEY> INVOICE=INV-1 node main.ts <PAYEE_WALLET> 0.5`)

```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: MIT

import { 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 lamports
if (!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 issued
const 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/s
const 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);
});
```

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.

## 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.

| Plan | Credits | getTransaction rate | getSignaturesForAddress rate | First read of ten new signatures |
|---|---|---|---|---|
| Free ($0) | 500K once, at sign-up | 0.24 req/s | 0.24 req/s | about 42 s |
| Dev ($20) | 10M per month | 1.2 req/s | 1.2 req/s | about 8.3 s |
| Business ($250) | 50M per month | 5 req/s | 100 req/s | 2 s |
| Pro ($500) | 200M per month | 25 req/s | 500 req/s | 0.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.

## 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](https://carbium.sh/library/usecase/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](https://carbium.sh/library/blockchainideas/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.

## 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.

## When it goes wrong

| What goes wrong | What 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. |

## 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.

## Related

- [Solana Pay confirmation](https://carbium.sh/library/usecase/solana-pay-confirmation) (Use cases, UC0002)
- [Point-of-sale recent sales](https://carbium.sh/library/blockchainideas/point-of-sale-recent-sales) (Blockchain ideas, BI0008)
- [carbium.sh/docs#rpc](https://carbium.sh/docs#rpc)
- [carbium.sh/docs#limits](https://carbium.sh/docs#limits)
- [carbium.sh/docs#migrate](https://carbium.sh/docs#migrate)
- [carbium.sh/docs#websocket](https://carbium.sh/docs#websocket)
- [carbium.sh/docs#endpoints](https://carbium.sh/docs#endpoints)
