services
Get a key

library / Blockchain ideas / BI0056

Revenue split ledger

A ledger for a wallet that several people share. Each incoming SOL payment is split by basis points the moment it is recorded, so every row sums exactly and each partner's balance owed is a plain sum. Runnable code and plan costs included.

By Carbium · Creator and membership · BI0056 · updated 2026-11-22

01

Who uses it

Picture a band, a two-person studio or a creator collective with one wallet that takes in sponsor payments and mint proceeds. The percentages were settled long ago. What nobody wants is a shared spreadsheet, or a dispute after a busy week about who is owed what.

The ledger follows that wallet and writes each incoming payment as a row, with every partner's share stored beside it. A statement is then a sum over rows. A hackathon team can put a dashboard on top in a weekend, with payments in one column and a balance per partner in the other. Reads on chain are public, so any busy address can stand in for the studio wallet during a demo. All calls go to services.carbium.sh under one key.

02

Shares and rounding

A share is a whole number of basis points, one hundredth of a percent, and the shares of one wallet add up to 10,000. Integers keep the arithmetic exact: 6000 and 4000 is a 60 and 40 split. The code reads SHARES as name:bps pairs and refuses to start when a pair is not a name and a whole number of basis points, or when the numbers miss 10,000.

Rounding each share on its own can miss the payment by a lamport either way. Split 1 lamport 50/50 and each partner is owed 0.5: round halves up and the wallet owes 2 lamports, round halves down and it owes 0. A tie is one example. Three partners at 3333, 3333 and 3334 on 2 lamports each round to 1, and the shares sum to 3.

PaymentShares in bpsEach rounded to nearestLargest remainder
1 lamport5000, 50001 + 1 = 2 (halves up) or 0 + 0 = 0 (halves down)1 + 0 = 1
2 lamports3333, 3333, 33341 + 1 + 1 = 31 + 0 + 1 = 2
1,000,000 lamports6000, 4000600,000 + 400,000600,000 + 400,000

Largest remainder removes the drift at the source. Floor every share, count the lamports left over, and give one each to the partners with the biggest remainders, the earlier name winning a tie. The shares then sum to the payment exactly. The split runs once, when the income row is recorded, and the result is stored. A later edit to SHARES applies to the next payment and leaves old rows alone, so an old statement never rewrites. The arithmetic runs in BigInt, because a payment times 10,000 can pass the largest integer a JavaScript number holds exactly.

03

The build

One file on @solana/kit and what Node 24 ships. It is read-only: no private key, nothing signed or sent. Pass a wallet address, or none.

  1. With no address, call getSlot, then up to nine getBlock calls starting 150 slots back, in accounts detail, and take the first account whose balance rose. That wallet is the demo.
  2. Open ledger.db with node:sqlite and create the moves and shares tables.
  3. List the newest LIMIT signatures (10 by default) with getSignaturesForAddress. If the call fails, print the reason and carry on with the rows already stored.
  4. For each listed signature with no error and no stored row, call getTransaction with jsonParsed encoding and read the wallet's balance change from meta.
  5. On a rise, split it and store each partner's share. Then store the move itself, zero and negative changes included.
  6. Print every income row with its shares, then the totals.
main.ts
// BI0056 · Revenue split ledger// https://carbium.sh/library/blockchainideas/revenue-split-ledger// 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 pairs = (process.env.SHARES ?? "partner1:6000,partner2:4000").split(",");const partners = pairs.every((p) => /^[^:]+:\d+$/.test(p)) ? pairs.map((p) => p.split(":") as [string, string]) : [];const bps = partners.map(([, b]) => BigInt(b));if (!key || bps.reduce((a, b) => a + b, 0n) !== 10000n) {  console.error("Set CARBIUM_KEY and keep SHARES (name:bps,...) summing to 10000, then run: node main.ts [wallet]");  process.exit(1);}const rpc = createSolanaRpcFromTransport(  createDefaultRpcTransport({ url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh", headers: { "x-api-key": key } }),);const msg = (e: unknown) => (e instanceof Error ? e.message : String(e));type Meta = { err?: unknown; preBalances: (number | bigint)[]; postBalances: (number | bigint)[] };type Keys = { pubkey: string }[];const change = (m: Meta, j: number) => Number(m.postBalances[j]) - Number(m.preBalances[j]);// Largest remainder: floor every share, then give the leftover lamports to the biggest remainders.function split(amount: bigint): bigint[] {  const out = bps.map((b) => (amount * b) / 10000n);  const rem = bps.map((b) => (amount * b) % 10000n);  const order = rem.map((_, i) => i).sort((i, j) => (rem[j] > rem[i] ? 1 : rem[j] < rem[i] ? -1 : i - j));  for (const i of order.slice(0, Number(amount - out.reduce((a, b) => a + b, 0n)))) out[i] += 1n;  return out;}// With no wallet argument: the first account whose balance rose in a recent finalized block.async function newestIncome(): Promise<string> {  const slot = await rpc.getSlot({ commitment: "finalized" }).send();  for (let i = 0n; i < 9n; i++) {    const at = (slot - 150n - i) as typeof slot;    try {      const block = (await rpc        .getBlock(at, { commitment: "finalized", transactionDetails: "accounts", rewards: false, maxSupportedTransactionVersion: 1 })        .send()) as unknown as { transactions: { transaction: { accountKeys: Keys }; meta: Meta | null }[] } | null;      for (const t of block?.transactions ?? []) {        const m = t.meta;        const j = m && !m.err ? t.transaction.accountKeys.findIndex((_, k) => change(m, k) > 0) : -1;        if (j >= 0) return t.transaction.accountKeys[j].pubkey;      }    } catch (e) { console.log(`block ${at} skipped: ${msg(e)}`); }  }  throw new Error("no account with a rising balance in nine blocks");}const db = new DatabaseSync("ledger.db");db.exec(`CREATE TABLE IF NOT EXISTS moves (wallet TEXT, sig TEXT, delta INTEGER, PRIMARY KEY (wallet, sig));CREATE TABLE IF NOT EXISTS shares (wallet TEXT, sig TEXT, partner TEXT, lamports INTEGER, PRIMARY KEY (wallet, sig, partner))`);const seen = db.prepare("SELECT 1 FROM moves WHERE wallet = ? AND sig = ?");const addShare = db.prepare("INSERT OR IGNORE INTO shares VALUES (?, ?, ?, ?)");const addMove = db.prepare("INSERT OR IGNORE INTO moves VALUES (?, ?, ?)");const all = <T>(sql: string, ...args: string[]) => db.prepare(sql).all(...args) as unknown as T[];async function main() {  const wallet = process.argv[2] ?? (await newestIncome());  const sigs = await rpc    .getSignaturesForAddress(address(wallet), { limit: Number(process.env.LIMIT ?? 10), commitment: "finalized" })    .send()    .catch((e) => (console.log(`listing failed, printing stored rows: ${msg(e)}`), []));  for (const s of sigs) {    if (s.err !== null || seen.get(wallet, s.signature)) continue;    try {      const tx = (await rpc        .getTransaction(s.signature, { commitment: "finalized", encoding: "jsonParsed", maxSupportedTransactionVersion: 1 })        .send()) as unknown as { meta: Meta | null; transaction: { message: { accountKeys: Keys } } } | null;      if (!tx?.meta) { console.log(`${s.signature.slice(0, 8)} not readable, skipped`); continue; }      const w = tx.transaction.message.accountKeys.findIndex((k) => k.pubkey === wallet);      const delta = w < 0 ? 0 : change(tx.meta, w);      if (delta > 0) split(BigInt(delta)).forEach((v, i) => addShare.run(wallet, s.signature, partners[i][0], Number(v)));      addMove.run(wallet, s.signature, delta);    } catch (e) { console.log(`${s.signature.slice(0, 8)} failed: ${msg(e)}`); }  }  for (const r of all<{ sig: string; delta: number }>("SELECT sig, delta FROM moves WHERE wallet = ? AND delta > 0", wallet)) {    const parts = all<{ partner: string; lamports: number }>("SELECT partner, lamports FROM shares WHERE wallet = ? AND sig = ?", wallet, r.sig);    console.log(`${r.sig.slice(0, 8)} +${r.delta} = ${parts.map((p) => `${p.partner} ${p.lamports}`).join(" + ")}`);  }  const t = db.prepare("SELECT COALESCE(SUM(delta) FILTER (WHERE delta > 0), 0) AS inc, COALESCE(-SUM(delta) FILTER (WHERE delta < 0), 0) AS spent FROM moves WHERE wallet = ?").get(wallet) as unknown as { inc: number; spent: number };  const owed = all<{ partner: string; v: number }>("SELECT partner, SUM(lamports) AS v FROM shares WHERE wallet = ? GROUP BY partner ORDER BY partner", wallet);  console.log(`${wallet}: income ${t.inc} lamports, owed ${owed.map((o) => `${o.partner} ${o.v}`).join(", ")}, paid out ${t.spent}`);}main().catch((e) => { console.error(msg(e)); process.exit(1); });

run: CARBIUM_KEY=<YOUR_KEY> node main.ts [wallet]

Every call asks for finalized, since nobody should be paid from a row that could be rewound.

getBlock and getTransaction carry maxSupportedTransactionVersion: 1, since mainnet carries v1 transactions and a block or transaction of that kind is refused with -32015 without it.

The two writes are ordered. Shares go in first and the move row last, because the move row is what tells later runs a signature is done. A crash between them leaves the signature unmarked, and the next run redoes the split into rows that INSERT OR IGNORE takes without duplicating. Each read sits in its own try, so one failing signature prints its message and the loop goes on. A rerun changes nothing it has already stored. A row prints as 5Kd9Xa2b +1000000 = partner1 600000 + partner2 400000.

04

Payouts and other outflows

The same post minus pre balance reading is used for every signature, so money that leaves shows up as a row with a negative change. The statement sums those rows and prints them as paid out, next to the owed amounts, so the signers can see how much has already left. A payout the wallet pays the network fee on includes that fee in the change.

$Owed is gross. It sums the shares and subtracts nothing, so the signers compare it with paid out by hand until payouts are tied to partners.

Fees on failed transactions are a gap. A failed transaction still costs its fee, and the wallet pays it when it is the transaction's fee payer, but the code skips every signature whose err is set. That fee leaves the wallet and appears in no row, so the balance on chain sits below income minus paid out by that much.

05

What it costs

Each refresh begins with one getSignaturesForAddress listing, 50 cells. Every signature that is new then adds a getTransaction read of 50 cells, whether it brought money in, sent money out or changed nothing, because each one needs a row. The no-argument run also pays for getSlot, a 1-cell read, and up to nine getBlock calls. Every key on an account draws from one shared budget, so other tools using those keys spend from it as well.

PlangetTransaction req/s
Free ($0)0.24 req/s
Dev ($20)1.2 req/s
Business ($250)5 req/s
Pro ($500)25 req/s

A rate class absorbs a burst of 1,024 cells or one second of its rate, whichever is larger. Ten getTransaction reads are 500 cells, so a refresh at the default LIMIT fits the burst on every plan and is not slowed. Back-to-back refreshes, or a raised LIMIT on Free, run past the burst, and the reads beyond it settle at the sustained rate in the table and get 429 once they pass it. The per-signature try prints that error, and because no move row was stored, the next run reads that signature again.

Once a signature is stored it is never read again, so a refresh that finds nothing new costs only the listing. A signature that reads as null, or whose read failed, is not stored, so it is read again, at 50 cells, on every refresh that still lists it.

06

What to add next

  • Payouts per partner. Put each partner's address beside the name and credit an outflow to the partner whose balance rose in the same transaction. The statement can then show owed minus paid for each name.
  • Live rows. Open wss://services.carbium.sh with the key as ?api-key= and send logsSubscribe with a mention of the wallet. It costs 25 credits to open and 20 credits per MiB sent, and each notification carries a signature for the same reader. accountSubscribe stays silent for a plain SOL wallet, so the mention is the trigger.
  • Token income. For USDC or another mint, list at the wallet's token account and compare its pre and post token balances. The same split applies to the token's base units. A wallet can own more than one token account for a mint.

Creator royalty income tracker is the entry to read for where the income comes from, and Invoice payment tracker uses the same balance-change reading for one invoice at a time.

07

Where it ends

  • History is the 30-day address index at most. An older payment is not served, and an empty page past that point is the index's age limit. Keep ledger.db, because it is the only record that outlives the window.
  • The listing reads the newest LIMIT signatures and never pages back. A busy wallet that gets more new signatures than LIMIT between two runs loses the older ones. Raise LIMIT, run more often or add Signature history pagination.
  • Fees the wallet paid on failed transactions are in no row, since failed signatures are skipped.
  • Owed is gross and paid out is one total. No outflow is tied to a partner.
  • Any balance rise counts as income. A refund or a partner topping the wallet up is split like a sale, and money in and out within one transaction shows as the net change.
  • A signature that lists but reads as null is skipped and printed. The address index reaches below the validator's ledger floor, so old signatures can do this.
  • The no-argument run takes whichever account's balance rose first, which can be a program or tip account. It exists to make the demo run. Pass your own wallet for real use.
08

When it goes wrong

what goes wrongwhat to do
getTransaction or getBlock answers -32015.The call left out maxSupportedTransactionVersion or set it to 0, and the transaction or block is v1. Pass 1 on both calls.
A listed signature reads as null.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 older ones.
The run stops with a message and prints no rows.Either CARBIUM_KEY is empty, a SHARES pair is not name:bps with whole-number bps, or the pairs do not add to 10000. Export the key and correct the pairs.
The run prints a listing failure and then a statement of old rows.getSignaturesForAddress failed, so the statement comes from stored rows only. Rerun; nothing stored is read twice.
Owed totals fall a lamport or more short of income.The split was changed to round each share on its own. Restore the leftover step: floor every share, then give one lamport each to the biggest remainders.
The no-argument run stops with no account with a rising balance.Skipped slots answer with an error, and the nine blocks tried held no balance rise. Rerun, or pass a wallet address.
09

Questions

Can the shares change later?

Yes. Edit SHARES and the next payment uses the new split. Rows already stored keep the shares they were given, so earlier statements stay as they were.

Why split when the row is recorded?

Rounding depends on the shares in force at that moment. Keeping the result means every row sums to its payment, a statement is a plain sum and a later edit cannot move old figures.

Can it pay the partners?

No. It is read-only, with no key, signing or sending. It tells you who is owed, and payouts go out through your own wallet tool, then show up as outflows on the next run.