Functional Weave
Code in TypeScript

finance.ledger.trial-balance

Trial balance from journal lines: debit or credit balance per account, and proof that debits equal credits.

1.0.0 · published 2026-10-03 by charlie · Anterra

Pinned by 13 tests, run in TypeScript, Python and Rust.

What it does

Totals every account's debits and credits and shows each account's balance on the side it falls, the way a trial balance is printed. If double entry was kept, the debit column equals the credit column; `balanced` says whether it does.

The lines can come from any number of journals: a trial balance is built from the whole ledger for a period, not one journal at a time. The lines are checked with finance.ledger.journal-validate first, and a line that cannot be totalled meaningfully is an error, thrown with that capability's message: an amount in another currency, a negative amount, or a malformed account code. An unbalanced set of lines is not an error. Proving whether the ledger balances is what a trial balance is for, so that is the `balanced` answer.

For example

  • trialBalance(lines ×7, GBP) → rows ×5, total debit £120.00, total credit £120.00, balanced true three journals: a sale, a receipt and an expense
  • trialBalance(lines ×2, GBP) → rows ×2, total debit £1.00, total credit £1.00, balanced true accounts sort as text, so 1000 comes before 900
  • trialBalance(lines ×4, GBP) → rows ×3, total debit £5.00, total credit £5.00, balanced true an account that nets to zero keeps its row

The function

The same function in TypeScript, Python and Rust, pinned by the same tests. Pick your language; the choice follows you around the registry.

export function trialBalance(lines: readonly JournalLine[], currency: string): TrialBalance
linesJournalLine[]every posted journal line in the period, from any number of journals
currencystringthe ledger's currency; every amount must be in it
returnsTrialBalance

The types it declares, generated into your project

/** One account's line on the trial balance. */
export interface TrialBalanceRow {
  readonly account: string;
  /** total debits posted */
  readonly debits: Money;
  /** total credits posted */
  readonly credits: Money;
  /** debits less credits when that is positive; otherwise zero */
  readonly debitBalance: Money;
  /** credits less debits when that is positive; otherwise zero */
  readonly creditBalance: Money;
}

export interface TrialBalance {
  /** one per account, sorted by account code as text */
  readonly rows: readonly TrialBalanceRow[];
  /** sum of the debit balances */
  readonly totalDebit: Money;
  /** sum of the credit balances */
  readonly totalCredit: Money;
  /** whether the two totals agree */
  readonly balanced: boolean;
}

Your code names it in one line, in the file that uses it

import { trialBalance } from "#fune/finance.ledger.trial-balance@^1";
impl/typescript.ts · 47 lines · open · raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

import { validateJournal } from "./finance_ledger_journal_validate.ts";  ← from finance.ledger.journal-validate ^1.0.0 · built alongside by fune
import { type JournalLine } from "./finance_ledger_journal_validate_types.ts";
import { addMoney } from "./money_add.ts";  ← from money.add ^1.0.0 · built alongside by fune
import { type Money, money } from "./money_amount.ts";  ← from money.amount ^1.0.0 · built alongside by fune
import { type TrialBalance, type TrialBalanceRow } from "./finance_ledger_trial_balance_types.ts";

const FATAL = ["invalid-account", "currency-mismatch", "negative-amount"];

/**
 * A trial balance: each account's balance on its own side, and whether the
 * debit column equals the credit column.
 *
 * Lines that cannot be totalled are thrown with journal-validate's message; an
 * unbalanced ledger is an answer, not an error.
 */
export function trialBalance(lines: readonly JournalLine[], currency: string): TrialBalance {
  const check = validateJournal(lines, currency);
  for (const problem of check.problems) {
    if (FATAL.includes(problem.code)) throw new RangeError(problem.message);
  }

  const zero = money(0, currency);
  const totals = new Map<string, { debits: Money; credits: Money }>();
  for (const line of lines) {
    if (line.debit.minor === 0 && line.credit.minor === 0) continue;
    const current = totals.get(line.account) ?? { debits: zero, credits: zero };
    totals.set(line.account, {
      debits: addMoney(current.debits, line.debit),
      credits: addMoney(current.credits, line.credit),
    });
  }

  const accounts = [...totals.keys()].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
  const rows: TrialBalanceRow[] = [];
  let totalDebit = zero;
  let totalCredit = zero;
  for (const account of accounts) {
    const { debits, credits } = totals.get(account)!;
    const net = debits.minor - credits.minor;
    const debitBalance = money(net > 0 ? net : 0, currency);
    const creditBalance = money(net < 0 ? -net : 0, currency);
    rows.push({ account, debits, credits, debitBalance, creditBalance });
    totalDebit = addMoney(totalDebit, debitBalance);
    totalCredit = addMoney(totalCredit, creditBalance);
  }
  return { rows, totalDebit, totalCredit, balanced: totalDebit.minor === totalCredit.minor };
}

Install

fune build

With that line in your source, in a TypeScript project (language typescript in fune.project), fune build resolves it and its 3 dependencies, pins them in fune.lock, downloads only the TypeScript package of each, and builds the code above into your project’s .fune/build, one readable file per capability with a header linking back here. Or pin a range in fune.project and build in one step:

fune add finance.ledger.trial-balance
Download for TypeScript finance.ledger.trial-balance-1.0.0-typescript.fune · 18,418 bytes sha256 96a62742e68331b25f47c65d33ee4fcf2447b3b4324307c9f72d0e919ef57ed8

The manifest, vectors and README with only the TypeScript implementation. Install it without the registry with fune add ./finance.ledger.trial-balance-1.0.0-typescript.fune, or fetch it from a terminal with fune pull finance.ledger.trial-balance@1.0.0:typescript.

The whole function, every language, is one file too: finance.ledger.trial-balance-1.0.0.fune, 24,288 bytes, sha256 cec194b001064de3bcd8096dca2aab7883610285ae3ebb71ca1ec50454999df3. It installs into a project of any language.

Customise it in your app

The seams this capability offers. Put a marker directly above a function of your own and fune build wires it into the built code; the package on the registry is not changed, the built file’s header lists it under CUSTOMISED, and fune hooks lists every hook in the project. How hooks work.

before — your function gets the arguments and returns them, changed or not, or throws to refuse the call.

// fune: before finance.ledger.trial-balance

after — your function gets the result and the arguments, and returns the final result.

// fune: after finance.ledger.trial-balance

replace — inside this capability’s code only, calls to a dependency go to your function, with the same signature. Other capabilities that use it are unaffected; write in * to replace it everywhere.

// fune: replace finance.ledger.journal-validate in finance.ledger.trial-balance
// fune: replace money.add in finance.ledger.trial-balance
// fune: replace money.amount in finance.ledger.trial-balance

step — your function runs at a numbered point inside the function’s body, receives the in-scope values it names as parameters, and may return replacements. List the points with fune show finance.ledger.trial-balance --steps.

// fune: step finance.ledger.trial-balance after <n|label>

Tests

A version published now needs at least 8 tests for every function, and one that expects the error for each function that throws; the registry refuses it otherwise. fune verify --all runs each case in TypeScript, Python and Rust, and a project runs them again with fune verify. This page lists the cases; it does not run them. The exact JSON is vectors.json.

CaseArgumentsExpected
three journals: a sale, a receipt and an expense lines ×7, GBP → rows ×5, total debit £120.00, total credit £120.00, balanced true
accounts sort as text, so 1000 comes before 900 lines ×2, GBP → rows ×2, total debit £1.00, total credit £1.00, balanced true
an account that nets to zero keeps its row lines ×4, GBP → rows ×3, total debit £5.00, total credit £5.00, balanced true
an unbalanced ledger is an answer, not an error lines ×2, GBP → rows ×2, total debit £100.00, total credit £99.99, balanced false
no lines: an empty trial balance that balances , GBP → rows , total debit £0.00, total credit £0.00, balanced true
zero lines are skipped and make no row lines ×3, GBP → rows ×2, total debit £1.00, total credit £1.00, balanced true
a line with both sides is totalled on both lines ×2, GBP → rows ×2, total debit £3.00, total credit £3.00, balanced true
many postings to one account lines ×4, GBP → rows ×2, total debit £0.06, total credit £0.06, balanced true
a euro ledger lines ×2, EUR → rows ×2, total debit €1.00, total credit €1.00, balanced true
a line in another currency is refused lines ×2, GBP → error: line 2: amount is in EUR, not the journal currency GBP
Show the other 3 tests
CaseArgumentsExpected
a negative amount is refused lines ×2, GBP → error: line 1: debit and credit must not be negative
a malformed account code is refused lines ×2, GBP → error: line 1: account "12 00" is not a valid account code
the ledger currency must be an ISO code , pounds → error: ISO 4217

More from the author

Lines with a zero debit and a zero credit are skipped and do not create a row. A line with both a debit and a credit is totalled on both sides. An account whose debits and credits cancel still has a row, with both balances zero, because it had postings.

Rows are sorted by account code as text (byte order), which is how a chart of accounts with codes like `1200-01` sorts. Codes of different lengths do not sort numerically: `1000` comes before `900`. Pad codes to a fixed width if a numeric order is wanted.

Files

PathBytes
README.md1,307
impl/python.py2,140
impl/rust.rs3,521
impl/typescript.ts2,104
vectors.json10,143