Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

ledgerkit

CI

A double-entry ledger engine in strict TypeScript. Balanced-by-construction entries, bigint minor-unit money, idempotent posting, point-in-time balances, and penny-perfect allocation. Zero runtime dependencies.

This is the core that sits under invoicing, POS, billing, and wallet systems: the part that must be correct rather than clever. It is small on purpose. Everything in it exists to enforce five invariants.

The five invariants

  1. Every entry balances. Debits equal credits, checked at posting time. There is no API for writing an unbalanced entry, so the books cannot be broken by a code path you forgot about.
  2. The journal is append-only and immutable. Corrections are reversal entries, never edits. Posted entries are deep-frozen. History is evidence; a ledger you can rewrite is a story, not a record.
  3. Money is integer minor units in bigint. There is no fromNumber(). Floats are refused at the boundary because 0.1 + 0.2 !== 0.3 is how ledgers grow phantom pennies, and a ledger that can drift is not a ledger.
  4. Posting is idempotent. Replay the same idempotency key (a Stripe event id, a POS transaction number) and you get the original entry back, posted exactly once. Same key with different contents throws loudly, because that's a caller bug that silence would bury.
  5. Balances are derived state. The cached balance of every account must always equal a full recomputation from the journal. The test suite enforces this equivalence under fuzz; if the cache can disagree with the journal, the cache is lying to someone.

Usage

import { Ledger } from "./src/ledger.js";
import { Money, USD } from "./src/money.js";

const ledger = new Ledger(USD);
ledger.openAccount("cash", "asset");
ledger.openAccount("revenue", "income");
ledger.openAccount("sales_tax_payable", "liability");

// A $100 sale with 8.75% tax: one atomic entry, three legs, provably balanced.
ledger.post({
  description: "sale #1001",
  idempotencyKey: "pos-txn-1001",
  legs: [
    { account: "cash",              side: "debit",  amount: Money.parse("108.75", USD) },
    { account: "revenue",           side: "credit", amount: Money.parse("100.00", USD) },
    { account: "sales_tax_payable", side: "credit", amount: Money.parse("8.75",  USD) },
  ],
});

ledger.balance("cash").format();                       // "108.75"
ledger.balanceAt("cash", new Date("2026-01-31"));      // balance as of any moment
ledger.trialBalance();                                  // every account + proof debits == credits

A refund is a new entry with the sides swapped, not a deletion. The original sale stays in the journal forever, which is exactly what you want when someone asks "what happened here?" eight months later.

Overdraft is a policy, not an accident

ledger.openAccount("cash", "asset");                          // may not go negative
ledger.openAccount("customer_credit", "liability", { allowNegative: true });

An entry that would take a protected account negative is rejected atomically: no journal row, no partial balance change, nothing to clean up.

Allocation without losing a penny

Money.parse("100.00", USD).allocate([1, 1, 1]);
// [$33.34, $33.33, $33.33] — sums to exactly $100.00, always

Largest-remainder allocation for splitting totals by ratio (commission splits, installments, tax apportionment). The fuzz suite runs hundreds of random allocations and asserts the parts always sum exactly to the whole, including for negative amounts.

The tests are the specification

npm install && npm test    # 21 tests

Three layers, in ascending order of importance:

  • Example tests: sales with tax, refunds as reversals, overdraft rejection, idempotent webhook replay, point-in-time balances.
  • Boundary tests: precision the currency can't represent is rejected (not rounded), float-drift is impossible by construction (a dime added 1,000 times is exactly $100.00), garbage input names its line.
  • Invariant fuzz: a thousand random multi-leg entries with random idempotent replays, then three assertions that define what a ledger is: total debits equal total credits; signed balances net to exactly zero; every cached balance equals full recomputation from the journal. The PRNG is seeded and the seed is logged, so any failure is reproducible.

What this is not

  • Not a database. The journal lives in memory; persistence is your storage layer's job. The design maps directly onto an append-only table with a unique index on the idempotency key (which gives you invariant 4 under concurrency via insert-or-conflict).
  • Not multi-currency. One ledger, one currency, and mixing is a typed error. FX involves rate sources and gain/loss accounts, and pretending that's a constructor option would be dishonest.
  • Not an accounting application. No chart-of-accounts opinions, no reporting periods, no tax rules. It's the engine those get built on.

License

MIT

About

A double-entry ledger engine in strict TypeScript: balanced-by-construction entries, bigint money, idempotent posting, point-in-time balances. The invariants that keep money honest.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages