Loyalty points liability tracker
Rewards points on chain are owed until redeemed. The script reads a mint's supply, subtracts the issuer's own token accounts, prices what is left at your value per point, and logs each snapshot to SQLite so the change between runs shows.
Points are a liability
A loyalty program that issues points as an SPL token owes its customers every point they have not yet redeemed. Finance wants one figure from that: how many points sit in customer hands, and what honouring them costs at your value per point. The mint answers the first half. Its supply is a counter that each mint instruction raises and each burn lowers.
Supply counts every point that exists, including those your own accounts hold: the treasury you mint into, the account redemptions land in before you burn them, a reserve set aside for a campaign. Nobody is owed those. Outstanding points are the supply minus the balances of the token accounts you control, and the liability is outstanding points times your value per point. The value is an input you set, since the chain stores no price for a point.
A wallet can own several token accounts for one mint, so give the script every token account address you control, one after another following the mint.
Reading supply and treasury
getTokenSupply returns the amount as a base-unit string with the mint's decimals. getTokenAccountBalance returns the same shape for one token account. Keep the amounts as BigInt. A supply of 75 billion points at 6 decimals is 7.5e16 base units, past the 9e15 a JavaScript number holds exactly, and a liability total is the last place to accept rounding. Divide by the decimals only when printing.
Both calls read at finalized commitment, so the snapshot counts only settled transactions.
The supply and the treasury balances arrive in separate calls and can describe different slots. A mint or a redemption that lands between them moves the outstanding figure by that one transaction. The script prints the supply's slot with every snapshot so a surprising number can be matched to a block.
The snapshot script
The script reads the supply and every treasury balance together, settles each call and prints which ones failed. If any treasury read failed it stops without saving, since a missing balance would count the issuer's own points as owed. Otherwise it computes outstanding points and the liability at POINT_VALUE_USD (default 0.01), appends a row to a SQLite file named after the mint with the time taken and the value per point used, and prints the change since the previous row. It reads CARBIUM_KEY, exits with a message when it is unset, and signs and sends nothing.
// UC0051 · Loyalty points liability tracker// https://carbium.sh/library/usecase/loyalty-points-liability-tracker// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MIT// Read-only: snapshots a rewards token's outstanding points and what they owe, and logs each run in SQLite.import { DatabaseSync } from "node:sqlite";import { address, createDefaultRpcTransport, createSolanaRpcFromTransport } 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 [mintArg, ...extra] = process.argv.slice(2);if (!mintArg) { console.error("Usage: node main.ts <mint> [treasury token account ...]"); process.exit(1); }const mint = address(mintArg); // throws on anything that is not an addressconst treasury = [...new Set(extra)].map((a) => address(a)); // token accounts the issuer controlsconst value = Number(process.env.POINT_VALUE_USD ?? "0.01"); // dollars per point: your inputif (!(value >= 0 && Number.isFinite(value))) { console.error("POINT_VALUE_USD must be a number."); process.exit(1); }const valueMicro = BigInt(Math.round(value * 1e6));const rpc = createSolanaRpcFromTransport(createDefaultRpcTransport({ url, headers: { "x-api-key": key } }));const commitment = "finalized";const [supply, balances] = await Promise.all([ rpc.getTokenSupply(mint, { commitment }).send().catch((e: Error) => { console.error(`supply failed: ${e.message}`); return process.exit(1); }), Promise.allSettled(treasury.map((t) => rpc.getTokenAccountBalance(t, { commitment }).send())),]);const failed = balances.flatMap((r, i) => r.status === "rejected" ? [`${treasury[i]}: ${r.reason?.message ?? r.reason}`] : []);if (failed.length) { console.error(`treasury reads failed, nothing saved:\n${failed.join("\n")}`); process.exit(1); }const heldTotal = balances.reduce((n, r) => r.status === "fulfilled" ? n + BigInt(r.value.value.amount) : n, 0n);const { decimals, amount } = supply.value;const outstanding = BigInt(amount) - heldTotal;if (outstanding < 0n) { console.error("Treasury balances exceed the supply: check each address belongs to this mint."); process.exit(1); }const liability = (outstanding * valueMicro) / 10n ** BigInt(decimals); // micro-dollarsconst fmt = (n: bigint, d: number) => { const s = (n < 0n ? -n : n).toString().padStart(d + 1, "0"); return (n < 0n ? "-" : "") + (d ? `${s.slice(0, -d)}.${s.slice(-d)}` : s);};const db = new DatabaseSync(`${mint}.db`);db.exec("CREATE TABLE IF NOT EXISTS snaps (taken_at TEXT, slot INTEGER, value_micro TEXT, supply TEXT, held TEXT, outstanding TEXT, liability TEXT)");const prev = db.prepare("SELECT outstanding FROM snaps ORDER BY rowid DESC LIMIT 1").get();db.prepare("INSERT INTO snaps VALUES (?, ?, ?, ?, ?, ?, ?)").run(new Date().toISOString(), Number(supply.context.slot), valueMicro.toString(), amount, heldTotal.toString(), outstanding.toString(), liability.toString());console.log(`${mint} at slot ${supply.context.slot}: supply ${fmt(BigInt(amount), decimals)}, treasury ${fmt(heldTotal, decimals)}`);console.log(`outstanding ${fmt(outstanding, decimals)} points, liability $${fmt(liability, 6)} at $${value} a point`);console.log(prev ? `change since last snapshot: ${fmt(outstanding - BigInt(String(prev.outstanding)), decimals)} points` : "first snapshot saved");
run: CARBIUM_KEY=$CARBIUM_KEY POINT_VALUE_USD=0.01 node main.ts <mint> [treasury token account ...]
A positive change means customers collected more points than they redeemed between two runs. A negative one means redemptions, burns, or points moved into your treasury outran issuance. A transfer between two listed accounts changes neither figure. Run it from cron on your reporting schedule, once a day for most programs, and the file becomes the liability history.
Explaining a change
A snapshot says how much moved and nothing about why. getSignaturesForAddress on the mint address lists the transactions that name the mint, which covers mints, burns and transferChecked calls, and getTransaction reads one of them. A plain transfer instruction does not name the mint, so to explain treasury movements you run getSignaturesForAddress on each treasury token account as well as on the mint. The supply change between two snapshots equals the mints minus the burns in that window, which checks the tracker against the chain. Mints into and burns from your listed accounts change the supply and leave outstanding unchanged. The outstanding change minus the supply change equals the treasury total's change with the sign flipped. That covers treasury mints, treasury burns and transfers between customers and your accounts.
Both calls cost 50 cells, and the address index keeps up to 30 days, so reconcile weekly and never less often than every 30 days, before the index ages a window out. Pass maxSupportedTransactionVersion: 1 to getTransaction: mainnet carries v1 transactions, and with the field absent or 0 the call answers -32015 for one. A signature the list returns can still answer null, because the index reaches below the validator's ledger floor, so handle null and reconcile from newer signatures.
Whoever holds the mint authority can raise the liability at will, and Token mint supply and authorities shows how to read that authority. For which wallets hold points, Token holder tracker follows joins and leaves per wallet. getTokenLargestAccounts is not served, so there is no direct list of the largest holders.
Rate budget of a run
Each treasury account is one account read at 10 cells, the admission charge per call.
| Plan | Cells per read | Account reads per second |
|---|---|---|
| Free | 10 | 0.5 |
| Dev | 10 | 15 |
| Business | 10 | 50 |
| Pro | 10 | 400 |
The burst covers about 100 treasury reads at once below Pro and 400 on Pro. A program with a dozen treasury accounts fits inside that on every plan, Free included, and a daily run never touches the sustained rate. An account's keys share one budget, so count any other job on the account against it.
Where it ends
- Points kept in your own database and never minted appear nowhere in this number. The figure covers the token only, and the ledger of record stays yours.
- Points held by a pool, a vault or an exchange account count as outstanding like any wallet. If they are not owed to customers, add those token accounts to the treasury list.
- The value per point is your input. The file stores the liability computed at the value you passed that day, with that value beside it, and a later change to the value does not rewrite earlier rows.
- Breakage, expiry and the accounting or tax treatment of unredeemed points are decisions for your finance team. The script reports points owed and does not estimate how many will never be redeemed.
- A Token-2022 mint with extensions such as a transfer fee needs a check against your ledger before you rely on its supply figure.
- Snapshots begin at the first run. Rebuilding earlier history from transactions reaches back 30 days at most.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| A treasury read fails and no snapshot is saved. | Rerun, and check that each address is a token account of this mint. A wallet address has no token balance to read. The script refuses to save without every treasury balance, because the issuer's points would then count as owed. |
| The script stops with treasury balances above the supply. | One of the addresses belongs to another mint. Check each token account's mint field against the mint you passed. |
| getTransaction answers -32015 while reconciling a window. | Pass maxSupportedTransactionVersion: 1 with an encoding. Mainnet carries v1 transactions, and the call fails for one when the field is absent or 0. |
| getTransaction answers null for a signature the list just returned. | The address index reaches below the validator's ledger floor, so an older signature can list and still answer null. Skip it and reconcile from newer signatures. |
| getTokenLargestAccounts answers -32601. | The method is not served and the error is final, so remove the call and any retry. Follow holders through transaction balances with the holder tracker. |
| The liability differs from the finance ledger by a small steady amount. | The script rounds the value per point to a millionth of a dollar. Pass a value that fits that grid. |
Questions
Can I count the customers who hold points?
Not from a supply call, which carries no holder count, and no direct holder list is served. Follow joins and leaves with Token holder tracker from a baseline you hold.
How often should the snapshot run?
Once per reporting period is enough, a day for most programs. The treasury reads fit the account-read burst on every plan.
Does burning redeemed points lower the liability?
Yes, when the burn is from an account off your treasury list: the supply falls, so outstanding falls by the burned amount. A burn from a listed account lowers the supply and the treasury total by the same amount and leaves outstanding unchanged. Points sent into a treasury account you listed also leave the outstanding figure, with the supply unchanged.
Does the redemption account belong on the treasury list?
Yes, when points sent there wait to be burned and are no longer owed to anyone. List its token account so they leave the outstanding figure at once, and the later burn then changes nothing further.