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
trial_balance(lines ×7, GBP)→ rows ×5, total debit £120.00, total credit £120.00, balanced true three journals: a sale, a receipt and an expensetrial_balance(lines ×2, GBP)→ rows ×2, total debit £1.00, total credit £1.00, balanced true accounts sort as text, so 1000 comes before 900trial_balance(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.
pub fn trial_balance(lines: &[JournalLine], currency: &str) -> TrialBalance
| lines | JournalLine[] | every posted journal line in the period, from any number of journals |
| currency | string | the ledger's currency; every amount must be in it |
| returns | TrialBalance |
The types it declares, generated into your project
/// One account's line on the trial balance.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TrialBalanceRow {
pub account: String,
/// total debits posted
pub debits: Money,
/// total credits posted
pub credits: Money,
/// debits less credits when that is positive; otherwise zero
pub debit_balance: Money,
/// credits less debits when that is positive; otherwise zero
pub credit_balance: Money,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TrialBalance {
/// one per account, sorted by account code as text
pub rows: Vec<TrialBalanceRow>,
/// sum of the debit balances
pub total_debit: Money,
/// sum of the credit balances
pub total_credit: Money,
/// whether the two totals agree
pub balanced: bool,
}
Your code names it in one line, in the file that uses it
fune!(finance.ledger.trial-balance@^1); // then call trial_balance(…)
Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.
use super::funejson::Value; ← the fune runtime: the JSON value the test vectors use; fune build keeps it only where a signature takes one
use super::finance_ledger_journal_validate::{journal_line_from_value, validate_journal, JournalLine}; ← from finance.ledger.journal-validate ^1.0.0 · built alongside by fune
use super::money_add::add_money; ← from money.add ^1.0.0 · built alongside by fune
use super::money_amount::{money, money_to_value, Money}; ← from money.amount ^1.0.0 · built alongside by fune
const FATAL: [&str; 3] = ["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.
///
/// # Panics
/// Panics, with journal-validate's message, on a line that cannot be totalled:
/// another currency, a negative amount or a malformed account code. An
/// unbalanced ledger is an answer, not a panic.
pub fn trial_balance(lines: &[JournalLine], currency: &str) -> TrialBalance {
let check = validate_journal(lines, currency);
for problem in &check.problems {
if FATAL.contains(&problem.code.as_str()) {
panic!("{}", problem.message);
}
}
let zero = money(0, currency);
let mut totals: Vec<(String, Money, Money)> = Vec::new();
for line in lines {
if line.debit.minor == 0 && line.credit.minor == 0 {
continue;
}
match totals.iter_mut().find(|(account, _, _)| *account == line.account) {
Some(entry) => {
entry.1 = add_money(&entry.1, &line.debit);
entry.2 = add_money(&entry.2, &line.credit);
}
None => totals.push((line.account.clone(), line.debit.clone(), line.credit.clone())),
}
}
totals.sort_by(|a, b| a.0.cmp(&b.0));
let mut rows: Vec<TrialBalanceRow> = Vec::with_capacity(totals.len());
let mut total_debit = zero.clone();
let mut total_credit = zero;
for (account, debits, credits) in totals {
let net = debits.minor - credits.minor;
let debit_balance = money(if net > 0 { net } else { 0 }, currency);
let credit_balance = money(if net < 0 { -net } else { 0 }, currency);
total_debit = add_money(&total_debit, &debit_balance);
total_credit = add_money(&total_credit, &credit_balance);
rows.push(TrialBalanceRow {
account,
debits,
credits,
debit_balance,
credit_balance,
});
}
let balanced = total_debit.minor == total_credit.minor;
TrialBalance {
rows,
total_debit,
total_credit,
balanced,
}
}
pub fn trial_balance_to_value(tb: &TrialBalance) -> Value {
Value::obj(vec![
(
"rows",
Value::Arr(
tb.rows
.iter()
.map(|r| {
Value::obj(vec![
("account", Value::str(&r.account)),
("debits", money_to_value(&r.debits)),
("credits", money_to_value(&r.credits)),
("debitBalance", money_to_value(&r.debit_balance)),
("creditBalance", money_to_value(&r.credit_balance)),
])
})
.collect(),
),
),
("totalDebit", money_to_value(&tb.total_debit)),
("totalCredit", money_to_value(&tb.total_credit)),
("balanced", Value::Bool(tb.balanced)),
])
}
pub fn fune_vector(args: &[Value]) -> Value {
let lines: Vec<JournalLine> = args[0].as_arr().iter().map(journal_line_from_value).collect();
trial_balance_to_value(&trial_balance(&lines, args[1].as_str()))
}Install
fune build
With that line in your source, in a Rust project (language rust in fune.project), fune build resolves it and its 3 dependencies, pins them in fune.lock, downloads only the Rust 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. A crate’s build.rs runs it before every compile. Or pin a range in fune.project and build in one step:
fune add finance.ledger.trial-balance
The manifest, vectors and README with only the Rust implementation. Install it without the registry with fune add ./finance.ledger.trial-balance-1.0.0-rust.fune, or fetch it from a terminal with fune pull finance.ledger.trial-balance@1.0.0:rust.
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.
| Case | Arguments | Expected | |
|---|---|---|---|
| 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
| Case | Arguments | Expected | |
|---|---|---|---|
| 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
| Path | Bytes |
|---|---|
| README.md | 1,307 |
| impl/python.py | 2,140 |
| impl/rust.rs | 3,521 |
| impl/typescript.ts | 2,104 |
| vectors.json | 10,143 |