BEGINNERPROJECTCHAPTER 07

Project: a double-entry ledger for a wallet

Build the ledger yourself: a posting function that refuses what must never be written, a replay of 83,887 attempts, and every wallet balance matching to the kobo

120 MINPAYMENTSUPDATED 2026-11-14

You build a small double-entry ledger in Python and SQLite, and prove it on Owoleaf’s books: 83,887 transaction attempts, 191,103 entries and 2,000 customer wallets, generated in the finance lab. You write the ledger’s schema and its posting function. You replay the lab’s history into it in time order. Then you compare every wallet balance with the generated ledger, run the lab’s check.py on your file, and see what your posting function does with the 4,060 attempts that failed.

Everything is standard-library Python. The lab’s limits, fees and bank codes are illustrative, set by the generator, and are not the CBN’s or any scheme’s rules.

What you are building

Three tables hold the whole ledger, and they are the three you met in the double-entry chapter. Accounts are the places money can sit: a wallet for each customer, plus the company’s own accounts (the settlement account at the partner bank, card funds owed by the processor, share capital, fee revenue and the processor’s fees). Transactions are the events, one row per attempt. Entries are the lines of each transaction: an account, a direction (debit or credit) and an amount in integer kobo.

A balance is not stored anywhere. A wallet is a liability, money Owoleaf owes the customer, so its balance is its credits minus its debits, summed from its entries. This is the design the PAYMENT LEDGER simulation below argues for: store movements, derive balances. A stored balance can drift from the movements that were meant to produce it. A sum cannot.

The table names and the column names are the lab’s, because check.py reads them by name. Everything else is yours to decide, and the project makes you decide it (money as integer kobo follows the minor units lesson): which accounts may go negative, which refusals exist, and what the function says when it refuses.

The posting function is the only door

The rule that makes a ledger trustworthy is about who may write. Anything can read the tables. Only one function writes to them, and it runs every check before the first row goes in.

Here are the rules this project’s function applies, in the order it applies them. Each is a way a ledger goes wrong in real systems, and the table says what you would see without it.

Rule Refusal code What goes wrong without it
A posting has at least two legs too_few_legs One-sided entries: money appears or vanishes
Each amount is an integer greater than zero bad_amount A float such as 15.5 kobo, or a zero or negative amount that hides a direction error
Debits equal credits unbalanced The books stop balancing; the trial balance is off by the difference
Every account exists unknown_account Money posted to an account nobody opened
The transaction id has not been posted before duplicate A request replayed with the same transaction id moves money twice. A retry that arrives with a new id gets past this rule, as the third break shows
No wallet ends below zero insufficient_funds A customer spends money they do not have

Two of these deserve a second look. The duplicate rule is the small cousin of an idempotency key. The source system’s transaction id is written in the same SQLite transaction as the entries, so a second attempt to post the same id finds it and stops. It stops only a caller that reuses the id. A retry that arrives with a new id and the same external reference, which is what the double-entry chapter’s break did, passes this rule, and the third break at the end of the lab posts one. Closing that gap takes a uniqueness rule on kind plus external reference, which the module 2 wallet project adds. The simulation below shows why the key has to be committed together with the entries, and the idempotency chapter in module 2 builds the full version for a payment API.

The insufficient_funds rule works on the net effect of the whole posting on each account, not leg by leg. A wallet that is debited ₦1,000 and credited ₦1,000 in one posting does not change, so it is not refused for the order of its legs. The balance check reads the balance first and writes second, which is a check-then-act sequence (see check-then-act). In this lab a single process does the replay, so nothing can change the balance between the read and the write. In a service with several writers, the read and the write must sit in one transaction that holds the write lock from the start (in SQLite, BEGIN IMMEDIATE), or two postings can both pass the check.

The function writes the transaction row and its entries inside a SQLite savepoint. If anything fails half way, the savepoint rolls back and neither row stays. All or nothing is a promise the function makes, not a hope.

Rules the ledger does not own

Replay the failed attempts and you learn something about where rules belong. Of the 4,060 attempts that failed in the lab’s history, your ledger refuses only 276. The rest it would have posted without complaint: 2,058 funding transfers that hit a balance cap, 698 payouts to a bank that was unavailable, 400 declined cards, 606 transfers and payouts over a daily limit, and 22 that would have pushed the recipient over a cap.

The ledger is not wrong to accept them. A balance cap, a daily limit, a declined card and an unavailable bank are not facts about the ledger’s arithmetic. They are decisions made by the wallet’s policy, the provider and the partner bank, before anything is posted. A ledger that checked them would need to know every tier, limit and bank status, and would change every time one of them did. The ledger owns one kind of rule: the ones that protect its own invariants. Money is conserved, and a wallet is never negative. Everything else belongs to the layer in front of it.

That split also tells you what the 276 are. 260 are attempts the lab recorded as insufficient_funds. The other 16 were recorded as daily_limit. The generator checks the daily limit first, so those 16 failed on the limit and would also have failed on funds. Your ledger sees the second reason, which the lab’s label hid.

Replaying history, in time order

The replay reads transactions.csv and entries.csv and posts the history in order of created_at, then id. Time order matters because the wallet rule depends on it: a payout is legal only if the money arrived first. Replay out of order and a funded payout looks like an overdraft.

For the 79,827 transactions that posted (79,729 succeeded and 98 that were later reversed) the replay takes their legs from entries.csv and calls the function. A posted transaction must be accepted. If your function refuses one, either your rules are stricter than the generator’s, or you have a bug, and the replay stops so you see it.

The 4,060 failed attempts have no entries, so there is nothing to copy. The replay builds the legs the attempt would have posted from its kind: a payout debits the wallet for the amount plus the fee, credits the settlement account the amount, and credits fee revenue the fee. Then it asks the function for a dry run. The function runs every check and writes nothing. The replay stores the failed attempt as a transactions row with no entries, which is the lab’s own rule for failures.

▶ SIMULATION
CLIENT
waiting on —
retries 0 · ok responses 0
LEDGER (balance rows, updated in place)
alice: $100
bob: $50
carol: $0
sum: $150 / $150
DB WORKER
running — · crashes 0
open txn: —
—
journal (0 entries)none: only the current balance is stored
legs that took effectT1: debits 0 · credits 0   T2: debits 0 · credits 0
✓ sum of all balances is constant ($150)✓ each transfer applied once
SCHEDULE
01[DB]DB: balances updated in place, one autocommit statement per leg, no key
02[CLIENT]CLIENT: send T1: alice → bob $30, key k-7f3a
03[DB]DB: T1 debit alice $30
04[DB]DB: T1 credit bob $30
05[NET]NET: T1 response lost; client times out and retries T1
06[CLIENT]CLIENT: send T2: bob → carol $50, key k-91c2
07[DB]DB: T2 debit bob $50
08[DB]DB: process crashes and restarts; client times out and retries T2
09[DB]DB: T2 credit carol $50 (if the process that started T2 is still alive)
10[DB]DB: respond to T2 (if anyone is still waiting)
11[NET]NET: report
Start of update in place scenario. 11 steps.
-- one autocommit statement per leg, no key
UPDATE accounts SET balance = balance - 30 WHERE id = 'alice';
-- crash here: $30 is gone
UPDATE accounts SET balance = balance + 30 WHERE id = 'bob';
-- response lost here: the client retries and both run again

The simulation uses three accounts, two transfers and plain dollars, so you can see the same ideas in a small space. Run the three designs one after another. In UPDATE IN PLACE, a lost response makes the client retry and the first transfer applies twice, and a crash between the two statements of the second transfer destroys $50. TRANSACTION, NO KEY survives the crash with the books balanced, but still moves the first transfer twice. FIX: JOURNAL + KEY answers the retry from its key and ends with the $150 it started with. Watch the two invariants, the sum of all balances and each transfer applied once. Your ledger is the third design, plus the overdraft rule, running on 83,887 attempts and not two.

What a clean comparison proves, and what it does not

When the replay finishes you compare balances: for each of the 2,005 accounts, your sum of credits minus debits against the generator’s. Zero differences means your code posted every recorded entry once, to the right account, for the right amount. check.py then tests six properties of your file, including that every transaction balances and that no wallet was ever negative at any point in time. The sixth compares your settlement account with the partner bank’s statement, so it runs only when the database has a bank_statement table and the answer key sits beside it.

It does not prove that the entries were right. The generator wrote them, and your ledger agrees with the generator because both are consistent, not because either matches the world. In a real company the thing you reconcile with is outside your books: the partner bank’s statement, and the provider’s settlement report. The reconciliation chapter in module 2 does that comparison. Here you only prove the inside is sound.

The replay’s second lesson is easy to miss. The 79,827 posted transactions never overdraw a wallet, so they pass whether or not you wrote the overdraft rule. Only the failed attempts test it. A ledger checked against good data alone has not been tested. The break at the end of the lab shows this.

Lab

LAB Build a wallet ledger, replay Owoleaf's books into it and prove it ~90 MIN
YOU NEEDPython 3.9 or later (standard library only)labs/finance from the course lab repository (step 1 generates the data)About 100 MB of disk for the lab data and your ledger file

You work in labs/finance. You create five small files there: ledger.py, try_door.py, replay.py, compare.py and show_refusals.py. The data is generated at seed 42 and scale 0.1, so your numbers match the ones below. Your ledger file is data/mine.sqlite, and it lives next to the lab’s answers/ folder because check.py looks for the answer key beside the database it checks.

1. Check the books you will replay.

cd labs/finance
ls data/finance.sqlite >/dev/null 2>&1 || python3 generate.py
python3 check.py
python3 -c "
import sqlite3
db = sqlite3.connect('data/finance.sqlite')
for t in ('transactions', 'entries', 'accounts'):
    print(t, db.execute(f'SELECT COUNT(*) FROM {t}').fetchone()[0])"

check.py ends with OK: all invariants hold. (If you ran loans.py earlier, it also prints a line about the loan book.) Then:

transactions 83887
entries 191103
accounts 2005

2,005 accounts are the 2,000 customer wallets and the five company accounts. 83,887 transactions include 4,060 failed attempts, which have no entries.

2. Write the ledger. Save this as ledger.py. Read it before you run anything: the schema is the design, and check_legs is the door.

"""A double-entry wallet ledger in SQLite. Money is integer kobo everywhere.

The table and column names match the lab's own tables, because check.py reads them by name.
The design is yours: the constraints, the posting rules and the refusal reasons.
"""
import sqlite3

SCHEMA = """
CREATE TABLE accounts (
  id          INTEGER PRIMARY KEY,
  code        TEXT NOT NULL UNIQUE,
  name        TEXT NOT NULL,
  type        TEXT NOT NULL CHECK (type IN ('asset', 'liability', 'equity', 'income', 'expense')),
  customer_id INTEGER,
  currency    TEXT NOT NULL,
  opened_at   TEXT NOT NULL,
  overdraft_ok INTEGER NOT NULL CHECK (overdraft_ok IN (0, 1))   -- 0 for wallets
);
CREATE TABLE transactions (
  id                       INTEGER PRIMARY KEY,
  kind                     TEXT NOT NULL,
  status                   TEXT NOT NULL CHECK (status IN ('succeeded', 'failed', 'reversed')),
  failure_reason           TEXT,
  customer_id              INTEGER,
  counterparty_customer_id INTEGER,
  amount_kobo              INTEGER NOT NULL,
  fee_kobo                 INTEGER NOT NULL,
  rail                     TEXT NOT NULL,
  external_ref             TEXT NOT NULL,
  counterparty_bank        TEXT,
  related_transaction_id   INTEGER,
  created_at               TEXT NOT NULL
);
CREATE TABLE entries (
  id             INTEGER PRIMARY KEY,
  transaction_id INTEGER NOT NULL REFERENCES transactions(id),
  account_id     INTEGER NOT NULL REFERENCES accounts(id),
  direction      TEXT NOT NULL CHECK (direction IN ('debit', 'credit')),
  amount_kobo    INTEGER NOT NULL CHECK (amount_kobo > 0),
  posted_at      TEXT NOT NULL
);
CREATE INDEX entries_txn ON entries (transaction_id);
CREATE INDEX entries_account ON entries (account_id, posted_at);
"""


class Refused(Exception):
    """The ledger said no. `reason` is a short code; the message says which account or amount."""

    def __init__(self, reason, detail=""):
        super().__init__(f"{reason}: {detail}" if detail else reason)
        self.reason = reason


def connect(path):
    db = sqlite3.connect(path, isolation_level=None)   # we say when a transaction begins and ends
    db.execute("PRAGMA foreign_keys = ON")
    return db


def balance(db, account_id):
    """Credits minus debits, in kobo, summed from the entries. A wallet's balance is this."""
    return db.execute(
        """SELECT COALESCE(SUM(CASE direction WHEN 'credit' THEN amount_kobo ELSE -amount_kobo END), 0)
           FROM entries WHERE account_id = ?""", (account_id,)).fetchone()[0]


def check_legs(db, txn_id, legs):
    """Raise Refused if the postings break a rule. Writes nothing. legs: (account_id, direction, kobo)."""
    if len(legs) < 2:
        raise Refused("too_few_legs", f"{len(legs)} leg(s)")
    for _, direction, kobo in legs:
        if direction not in ("debit", "credit"):
            raise Refused("bad_direction", repr(direction))
        if type(kobo) is not int or kobo <= 0:
            raise Refused("bad_amount", repr(kobo))
    debits = sum(k for _, d, k in legs if d == "debit")
    credits = sum(k for _, d, k in legs if d == "credit")
    if debits != credits:
        raise Refused("unbalanced", f"debits {debits} != credits {credits}")
    if db.execute("SELECT 1 FROM transactions WHERE id = ?", (txn_id,)).fetchone():
        raise Refused("duplicate", f"transaction {txn_id} is already posted")
    change = {}                                  # net credit-positive change per account
    for account_id, direction, kobo in legs:
        change[account_id] = change.get(account_id, 0) + (kobo if direction == "credit" else -kobo)
    for account_id, delta in change.items():
        row = db.execute("SELECT code, overdraft_ok FROM accounts WHERE id = ?", (account_id,)).fetchone()
        if row is None:
            raise Refused("unknown_account", str(account_id))
        code, overdraft_ok = row
        if not overdraft_ok and balance(db, account_id) + delta < 0:
            raise Refused("insufficient_funds",
                          f"{code} holds {balance(db, account_id)} kobo, posting changes it by {delta}")


def post(db, txn, legs, posted_at, dry_run=False):
    """Post one transaction and its entries, all or nothing, or raise Refused.
    txn is a dict with the transactions columns. dry_run runs every check and writes nothing."""
    check_legs(db, txn["id"], legs)
    if dry_run:
        return
    db.execute("SAVEPOINT post")
    try:
        cols = list(txn)
        db.execute(f"INSERT INTO transactions ({', '.join(cols)}) VALUES ({', '.join('?' * len(cols))})",
                   [txn[c] for c in cols])
        db.executemany(
            "INSERT INTO entries (transaction_id, account_id, direction, amount_kobo, posted_at) VALUES (?, ?, ?, ?, ?)",
            [(txn["id"], a, d, k, posted_at) for a, d, k in legs])
        db.execute("RELEASE post")
    except Exception:
        db.execute("ROLLBACK TO post")
        db.execute("RELEASE post")
        raise


def record_failed(db, txn):
    """Keep a failed attempt as a transactions row with no entries (the lab's rule for failures)."""
    if txn["status"] != "failed":
        raise Refused("not_failed", f"transaction {txn['id']} has status {txn['status']}")
    cols = list(txn)
    db.execute(f"INSERT INTO transactions ({', '.join(cols)}) VALUES ({', '.join('?' * len(cols))})",
               [txn[c] for c in cols])

3. Try the door by hand. Save this as try_door.py. It builds a tiny ledger in memory with a settlement account and two wallets, and tries six postings, four of which should be refused.

from ledger import SCHEMA, Refused, balance, connect, post

BANK, WALLET_A, WALLET_B = 1, 2, 3   # account ids: the settlement account and two wallets
db = connect(":memory:")
db.executescript(SCHEMA)
for i, code, kind, overdraft_ok in [(BANK, "settlement_bank", "asset", 1), (WALLET_A, "wallet:a", "liability", 0),
                                    (WALLET_B, "wallet:b", "liability", 0)]:
    db.execute("INSERT INTO accounts VALUES (?, ?, ?, ?, NULL, 'NGN', '2026-01-01', ?)",
               (i, code, code, kind, overdraft_ok))


def txn(i, kind, amount):
    return dict(id=i, kind=kind, status="succeeded", amount_kobo=amount, fee_kobo=0, rail="internal",
                external_ref=f"INT{i:010d}", created_at="2026-01-01T09:00:00+01:00")


tries = [
    (1, "funding_transfer", [(BANK, "debit", 500_000), (WALLET_A, "credit", 500_000)]),   # ₦5,000 arrives from the bank
    (2, "p2p_transfer", [(WALLET_A, "debit", 200_000), (WALLET_B, "credit", 200_000)]),       # one wallet pays another ₦2,000
    (3, "p2p_transfer", [(WALLET_A, "debit", 200_000), (WALLET_B, "credit", 190_000)]),       # the credit is short
    (4, "p2p_transfer", [(WALLET_A, "debit", 300_001), (WALLET_B, "credit", 300_001)]),       # one kobo more than it holds
    (5, "p2p_transfer", [(WALLET_A, "debit", 15.5), (WALLET_B, "credit", 15.5)]),             # a float
    (2, "p2p_transfer", [(WALLET_A, "debit", 200_000), (WALLET_B, "credit", 200_000)]),       # transaction 2 again
]
for i, kind, legs in tries:
    try:
        post(db, txn(i, kind, legs[0][2]), legs, "2026-01-01T09:00:00+01:00")
        print(f"transaction {i}: posted")
    except Refused as r:
        print(f"transaction {i}: refused, {r}")
print("wallet a holds", balance(db, WALLET_A), "kobo; wallet b holds", balance(db, WALLET_B), "kobo")
print("transactions stored:", db.execute("SELECT COUNT(*) FROM transactions").fetchone()[0])
python3 try_door.py
transaction 1: posted
transaction 2: posted
transaction 3: refused, unbalanced: debits 200000 != credits 190000
transaction 4: refused, insufficient_funds: wallet:a holds 300000 kobo, posting changes it by -300001
transaction 5: refused, bad_amount: 15.5
transaction 2: refused, duplicate: transaction 2 is already posted
wallet a holds 300000 kobo; wallet b holds 200000 kobo
transactions stored: 2

Check the arithmetic. ₦5,000 arrives (500,000 kobo) and wallet a pays wallet b ₦2,000 (200,000 kobo), so wallet a holds 300,000 kobo. Transaction 4 asks for 300,001: one kobo too many, and refused. The refused attempts stored nothing: only the two good transactions are in the table.

4. Replay Owoleaf’s books. Save this as replay.py. It loads the accounts, then walks every transaction in time order.

"""Replay the lab's books into your own ledger, in time order, and count what the ledger refuses."""
import csv
import os
import sqlite3
import sys
from collections import Counter, defaultdict

from ledger import SCHEMA, Refused, connect, post, record_failed

DATA = "data"
OUT = sys.argv[1] if len(sys.argv) > 1 else os.path.join(DATA, "mine.sqlite")
INT_COLS = {"id", "customer_id", "counterparty_customer_id", "amount_kobo", "fee_kobo", "related_transaction_id"}


def read(name):
    with open(os.path.join(DATA, name), newline="") as f:
        return list(csv.DictReader(f))


def as_txn(row):
    return {k: (int(v) if k in INT_COLS and v != "" else (None if v == "" else v)) for k, v in row.items()}


def attempt_legs(t, acct):
    """What a failed attempt would have posted. acct maps account code to id."""
    w = lambda cid: acct[f"wallet:{cid}"]
    amount, fee = t["amount_kobo"], t["fee_kobo"]
    if t["kind"] == "funding_transfer":
        return [(acct["settlement_bank"], "debit", amount), (w(t["customer_id"]), "credit", amount)]
    if t["kind"] == "funding_card":
        return [(acct["card_clearing"], "debit", amount), (w(t["customer_id"]), "credit", amount - fee),
                (acct["fee_revenue"], "credit", fee)]
    if t["kind"] == "p2p_transfer":
        return [(w(t["customer_id"]), "debit", amount), (w(t["counterparty_customer_id"]), "credit", amount)]
    if t["kind"] == "payout_nip":
        return [(w(t["customer_id"]), "debit", amount + fee), (acct["settlement_bank"], "credit", amount),
                (acct["fee_revenue"], "credit", fee)]
    raise ValueError(t["kind"])


def main():
    if os.path.exists(OUT):
        os.remove(OUT)
    db = connect(OUT)
    db.executescript(SCHEMA)
    db.execute("BEGIN")
    for a in read("accounts.csv"):
        db.execute("INSERT INTO accounts VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
                   (int(a["id"]), a["code"], a["name"], a["type"], a["customer_id"] or None,
                    a["currency"], a["opened_at"], 0 if a["type"] == "liability" else 1))
    acct = {code: i for i, code in db.execute("SELECT id, code FROM accounts")}

    legs_by_txn = defaultdict(list)
    for e in read("entries.csv"):
        legs_by_txn[int(e["transaction_id"])].append(
            (int(e["account_id"]), e["direction"], int(e["amount_kobo"]), e["posted_at"]))

    txns = sorted((as_txn(r) for r in read("transactions.csv")), key=lambda t: (t["created_at"], t["id"]))
    posted, verdicts = 0, Counter()
    for n, t in enumerate(txns, 1):
        if t["status"] == "failed":
            try:
                post(db, t, attempt_legs(t, acct), t["created_at"], dry_run=True)
                verdicts[(t["failure_reason"], "would post")] += 1
            except Refused as r:
                verdicts[(t["failure_reason"], "refused: " + r.reason)] += 1
            record_failed(db, t)
        else:
            legs = legs_by_txn[t["id"]]
            post(db, t, [(a, d, k) for a, d, k, _ in legs], legs[0][3])   # a posted transaction must go in
            posted += 1
        if n % 10_000 == 0:
            db.execute("COMMIT")
            db.execute("BEGIN")
    db.execute("COMMIT")

    # check.py also reads the partner bank's statement. It is not yours to build: load it as given.
    db.execute("""CREATE TABLE bank_statement (line INTEGER PRIMARY KEY, value_date TEXT, booked_at TEXT,
                  direction TEXT, amount_kobo INTEGER, reference TEXT, narration TEXT, balance_kobo INTEGER)""")
    db.execute("BEGIN")
    db.executemany("INSERT INTO bank_statement VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
                   [(int(r["line"]), r["value_date"], r["booked_at"], r["direction"], int(r["amount_kobo"]),
                     r["reference"], r["narration"], int(r["balance_kobo"])) for r in read("bank_statement.csv")])
    db.execute("COMMIT")

    entries = db.execute("SELECT COUNT(*) FROM entries").fetchone()[0]
    print(f"posted {posted:,} transactions ({entries:,} entries); replayed {len(txns) - posted:,} failed attempts as dry runs")
    print(f"{'failure_reason in the data':32} {'what your ledger said':32} attempts")
    for (reason, verdict), n in sorted(verdicts.items()):
        print(f"{reason:32} {verdict:32} {n:>7,}")
    print(f"refused in all: {sum(n for (r, v), n in verdicts.items() if v.startswith('refused')):,}")


if __name__ == "__main__":
    main()
python3 replay.py

It takes about 8 seconds and ends with this table:

posted 79,827 transactions (191,103 entries); replayed 4,060 failed attempts as dry runs
failure_reason in the data       what your ledger said            attempts
balance_cap                      would post                         2,058
beneficiary_bank_unavailable     would post                           698
card_declined                    would post                           400
daily_limit                      refused: insufficient_funds           16
daily_limit                      would post                           606
insufficient_funds               refused: insufficient_funds          260
recipient_balance_cap            would post                            22
refused in all: 276

79,827 posted transactions is the 79,729 that succeeded plus the 98 payouts that were later reversed. The 191,103 entries are every entry in the lab’s ledger. Read the table as the section “Rules the ledger does not own” does: 260 attempts refused for funds, 16 more that were recorded as daily_limit but were also short of funds, and 3,784 that your ledger would have posted.

5. Compare every balance. Save this as compare.py.

"""Compare every balance in your ledger with the generated ledger, account by account."""
import sqlite3

from ledger import balance, connect

mine = connect("data/mine.sqlite")
gen = sqlite3.connect("data/finance.sqlite")
expected = dict(gen.execute("""SELECT account_id, SUM(CASE direction WHEN 'credit' THEN amount_kobo ELSE -amount_kobo END)
                               FROM entries GROUP BY account_id"""))
wallets = [i for (i,) in gen.execute("SELECT id FROM accounts WHERE code LIKE 'wallet:%' ORDER BY id")]
others = [i for (i,) in gen.execute("SELECT id FROM accounts WHERE code NOT LIKE 'wallet:%' ORDER BY id")]

for name, ids in (("wallets", wallets), ("company accounts", others)):
    diff = [(i, balance(mine, i), expected.get(i, 0)) for i in ids if balance(mine, i) != expected.get(i, 0)]
    print(f"{name}: {len(ids):,} compared, {len(diff)} differences")
    for i, got, want in diff[:5]:
        print(f"  account {i}: yours {got:,} kobo, generated {want:,} kobo")

total = sum(balance(mine, i) for i in wallets)
print(f"customer money held in wallets: {total:,} kobo, or {total // 100:,}.{total % 100:02d} naira")
print("smallest wallet balance:", min(balance(mine, i) for i in wallets), "kobo")
python3 compare.py
wallets: 2,000 compared, 0 differences
company accounts: 5 compared, 0 differences
customer money held in wallets: 12,243,862,835 kobo, or 122,438,628.35 naira
smallest wallet balance: 0 kobo

Zero differences on 2,000 wallets and on the five company accounts. The total is ₦122,438,628.35 held for customers, and the smallest wallet holds 0 kobo: some customer spent every kobo, and your ledger let them do exactly that and no more. The same total, 12,243,862,835 kobo, is the liability line in step 1’s check.py output.

6. Run the lab’s checker on your file. check.py takes --db and reads the tables by name, so your file must have accounts, transactions and entries with the lab’s columns, plus bank_statement if you want invariant 6 to run. That is why replay.py loaded the statement. Without that table check.py does not fail: it prints 6 skipped: no bank_statement table (or it is empty) in this database and goes on, and if the answers/breaks.csv key is not beside your file it prints 6 skipped: no answers/breaks.csv beside the database and the folder it looked in. Either way it can still end with OK: all invariants hold, so read the lines above OK before you trust it. You should see no skipped line here.

python3 check.py --db data/mine.sqlite
accounts by type (debit-positive kobo): {'asset': 17355054889, 'equity': -5000000000, 'expense': 110590267, 'income': -221782321, 'liability': -12243862835}
settlement_bank in ledger 17,189,646,589 kobo; on the statement 17,192,741,324 kobo
OK: all invariants hold

All six invariants ran and hold on your file, and there is no skipped line. Invariant 6 compares your settlement account with the bank statement, and the two figures differ by what the nine planted breaks explain, which check.py works out by reading data/answers/breaks.csv. You do not need to open that file; the reconciliation chapter in module 2 is where you find the breaks yourself.

7. Look at what your ledger refused. Save this as show_refusals.py. It recomputes each failed transfer or payout’s wallet balance at the moment it was attempted, from your entries, without using the ledger’s rules.

"""Show three attempts your ledger refused: the amount asked against what the wallet held at the time."""
from ledger import connect

db = connect("data/mine.sqlite")
rows = db.execute("""SELECT t.id, t.kind, t.failure_reason, t.customer_id, t.amount_kobo, t.fee_kobo, t.created_at,
                            (SELECT COALESCE(SUM(CASE e.direction WHEN 'credit' THEN e.amount_kobo ELSE -e.amount_kobo END), 0)
                             FROM entries e JOIN accounts a ON a.id = e.account_id
                             WHERE a.code = 'wallet:' || t.customer_id AND e.posted_at < t.created_at)
                     FROM transactions t WHERE t.status = 'failed' AND t.kind IN ('p2p_transfer', 'payout_nip')
                     ORDER BY t.id""").fetchall()
short = [r for r in rows if r[7] < r[4] + r[5]]
print(f"{len(short)} failed p2p and payout attempts asked for more than the wallet held")
by_reason = {}
for r in short:
    by_reason[r[2]] = by_reason.get(r[2], 0) + 1
print("by the reason the lab recorded:", by_reason)
for tid, kind, reason, cid, amount, fee, ts, held in short[:3]:
    print(f"txn {tid} {kind} by C{cid:07d} at {ts}: asked {amount + fee:,} kobo, wallet held {held:,}, short by {amount + fee - held:,}")
python3 show_refusals.py
276 failed p2p and payout attempts asked for more than the wallet held
by the reason the lab recorded: {'insufficient_funds': 260, 'daily_limit': 16}
txn 1164 p2p_transfer by C0000164 at 2026-01-29T18:33:41+01:00: asked 1,212,700 kobo, wallet held 944,630, short by 268,070
txn 2091 p2p_transfer by C0001146 at 2026-02-06T22:51:33+01:00: asked 429,500 kobo, wallet held 76,605, short by 352,895
txn 2128 p2p_transfer by C0000952 at 2026-02-07T10:03:01+01:00: asked 879,200 kobo, wallet held 0, short by 879,200

The 276 agree with step 4, found a second way. Take the first line and redo it: the wallet held ₦9,446.30 (944,630 kobo), the transfer asked for ₦12,127.00 (1,212,700 kobo), and 1,212,700 − 944,630 = 268,070 kobo, or ₦2,680.70, short.

8. Recompute one wallet by hand. The wallet of customer C0000009 has five entries. Print them with a running total.

python3 -c "
from ledger import connect, balance
db = connect('data/mine.sqlite')
acct = db.execute(\"SELECT id FROM accounts WHERE code = 'wallet:9'\").fetchone()[0]
total = 0
for kind, d, k in db.execute('SELECT t.kind, e.direction, e.amount_kobo FROM entries e JOIN transactions t ON t.id = e.transaction_id WHERE e.account_id = ? ORDER BY e.posted_at, e.id', (acct,)):
    total += k if d == 'credit' else -k
    print(f'{kind:14} {d:6} {k:>10,}  running {total:>10,}')
print('balance()', balance(db, acct))
"
funding_card   credit  1,351,617  running  1,351,617
funding_card   credit    498,804  running  1,850,421
p2p_transfer   credit    893,600  running  2,744,021
funding_card   credit    230,194  running  2,974,215
payout_nip     debit   1,546,783  running  1,427,432
balance() 1427432

Four credits add to 1,351,617 + 498,804 + 893,600 + 230,194 = 2,974,215 kobo. The payout debit of 1,546,783 leaves 1,427,432 kobo, which is ₦14,274.32. The card fundings are credited net of the lab’s 1.5% fee: in each card transaction the wallet receives the amount less the fee, and fee revenue receives the fee.

Break it three ways, and watch what each failure looks like.

First, go round the door. Copy your file and insert one entry with SQL, as a second code path in a hurry might: a ₦1.00 debit to the settlement account on transaction 2, with no matching credit.

cp data/mine.sqlite data/broken.sqlite
python3 -c "
import sqlite3
db = sqlite3.connect('data/broken.sqlite')
db.execute(\"INSERT INTO entries (transaction_id, account_id, direction, amount_kobo, posted_at) VALUES (2, 1, 'debit', 100, '2026-01-03T16:03:31+01:00')\")
db.commit()"
python3 check.py --db data/broken.sqlite
accounts by type (debit-positive kobo): {'asset': 17355054989, 'equity': -5000000000, 'expense': 110590267, 'income': -221782321, 'liability': -12243862835}
settlement_bank in ledger 17,189,646,689 kobo; on the statement 17,192,741,324 kobo
FAIL
  1. 1 transactions do not balance, e.g. [(2,)]
  3. trial balance is off by 100 kobo: {'asset': 17355054989, 'equity': -5000000000, 'expense': 110590267, 'income': -221782321, 'liability': -12243862835}
  6. bank minus ledger is 3094635 kobo; the planted breaks explain 3094735

check.py exits with status 1 and prints three failures, all from the same 100 kobo: transaction 2 does not balance (invariant 1), the trial balance is off by 100 kobo (3), and the settlement account now differs from the bank by 100 kobo more than the planted breaks explain (6). check.py catches it afterwards. Your posting function would have refused it as unbalanced before it was written, which is the whole argument for one door.

Second, remove the overdraft rule and replay into a separate file:

mkdir nofunds
sed 's/not overdraft_ok and balance/False and balance/' ledger.py > nofunds/ledger.py
cp replay.py nofunds/
python3 nofunds/replay.py data/nofunds.sqlite | tail -9
python3 check.py --db data/nofunds.sqlite | tail -1
posted 79,827 transactions (191,103 entries); replayed 4,060 failed attempts as dry runs
failure_reason in the data       what your ledger said            attempts
balance_cap                      would post                         2,058
beneficiary_bank_unavailable     would post                           698
card_declined                    would post                           400
daily_limit                      would post                           622
insufficient_funds               would post                           260
recipient_balance_cap            would post                            22
refused in all: 0
OK: all invariants hold

Every attempt now “would post”, refused in all is 0, and check.py still says OK, because the dry runs wrote nothing and the 79,827 real postings never overdraw. Good data cannot test the rule. Only the failed attempts can.

Third, replay a retry. The double-entry chapter’s break was a retry that arrived with a new transaction id and the same external reference, so the duplicate rule, which looks only at the id, has nothing to stop. Post the funding #49972 again that way into a copy:

cp data/mine.sqlite data/retry.sqlite
python3 - <<'PY'
from ledger import Refused, connect, post

db = connect("data/retry.sqlite")
cols = ("id", "kind", "status", "failure_reason", "customer_id", "counterparty_customer_id", "amount_kobo",
        "fee_kobo", "rail", "external_ref", "counterparty_bank", "related_transaction_id", "created_at")
retry = dict(zip(cols, db.execute("SELECT * FROM transactions WHERE id = 49972").fetchone()))
retry.update(id=83_888, created_at="2026-05-25T06:08:09+01:00")     # a new id, the same external_ref
legs = db.execute("SELECT account_id, direction, amount_kobo FROM entries WHERE transaction_id = 49972").fetchall()
wallet = db.execute("SELECT id FROM accounts WHERE code = 'wallet:36'").fetchone()[0]
held = lambda: db.execute("""SELECT SUM(CASE direction WHEN 'credit' THEN amount_kobo ELSE -amount_kobo END)
                             FROM entries WHERE account_id = ?""", (wallet,)).fetchone()[0]
before = held()
try:
    post(db, retry, legs, retry["created_at"])
    print("transaction 83888: posted")
except Refused as r:
    print(f"transaction 83888: refused, {r}")
print(f"wallet:36 holds {before:,} kobo before the retry and {held():,} after")
print("transactions with that reference:",
      db.execute("SELECT COUNT(*) FROM transactions WHERE external_ref = ?", (retry["external_ref"],)).fetchone()[0])
PY
python3 check.py --db data/retry.sqlite
transaction 83888: posted
wallet:36 holds 5,190,487 kobo before the retry and 6,744,387 after
transactions with that reference: 2
accounts by type (debit-positive kobo): {'asset': 17356608789, 'equity': -5000000000, 'expense': 110590267, 'income': -221782321, 'liability': -12245416735}
settlement_bank in ledger 17,191,200,489 kobo; on the statement 17,192,741,324 kobo
FAIL
  6. bank minus ledger is 1540835 kobo; the planted breaks explain 3094735

Your ledger accepted the retry and moved ₦15,539.00 (1,553,900 kobo) twice: wallet 36 gained 6,744,387 − 5,190,487 = 1,553,900 kobo of money that never arrived. Checks 1 to 5 pass, because the duplicate balances. Only check 6 notices, by the same amount as in the double-entry chapter: 3,094,735 − 1,553,900 = 1,540,835. So the duplicate rule stops a replay that reuses the transaction id, and nothing more. A real retry comes from a client or a bank that does not know your ids. What identifies it is the reference the outside world sent. The fix is a uniqueness rule on kind plus external reference. The kind has to be part of it, because the lab’s rule is that a payout return reuses the payout’s reference. The wallet with reconciliation project in module 2 adds exactly this rule. You can see it work now, with the database enforcing it:

cp data/mine.sqlite data/retry_fixed.sqlite
python3 - <<'PY'
import sqlite3

from ledger import Refused, connect, post

db = connect("data/retry_fixed.sqlite")
db.execute("CREATE UNIQUE INDEX one_per_reference ON transactions (kind, external_ref)")   # the real data has no clashes
cols = ("id", "kind", "status", "failure_reason", "customer_id", "counterparty_customer_id", "amount_kobo",
        "fee_kobo", "rail", "external_ref", "counterparty_bank", "related_transaction_id", "created_at")
retry = dict(zip(cols, db.execute("SELECT * FROM transactions WHERE id = 49972").fetchone()))
retry.update(id=83_888, created_at="2026-05-25T06:08:09+01:00")
legs = db.execute("SELECT account_id, direction, amount_kobo FROM entries WHERE transaction_id = 49972").fetchall()
try:
    post(db, retry, legs, retry["created_at"])
    print("transaction 83888: posted")
except (Refused, sqlite3.IntegrityError) as e:
    print(f"transaction 83888: refused, {e}")
print("transactions stored:", db.execute("SELECT COUNT(*) FROM transactions").fetchone()[0])
PY
python3 check.py --db data/retry_fixed.sqlite | tail -1
transaction 83888: refused, UNIQUE constraint failed: transactions.kind, transactions.external_ref
transactions stored: 83887
OK: all invariants hold

The index builds without complaint because the 98 reversals share a reference with their payouts but have a different kind. The retry is now refused, and the savepoint in post means it left no half-written row behind.

Clean up with rm -r nofunds data/broken.sqlite data/nofunds.sqlite data/retry.sqlite data/retry_fixed.sqlite. Then answer the chapter’s last question: which of the six rules did the real data never make your ledger use?

The answer, from a run

Wrap check_legs so that it counts every refusal while replay.py runs on the real data, and the count is {'insufficient_funds': 276}. That one rule is the only one that ever fired. The other five, too_few_legs, bad_amount, unbalanced, unknown_account and duplicate, never did: the 79,827 posted transactions satisfy all of them, and the failed attempts, built from the same kinds, never break them either. duplicate never fires because every id in the history is unique, and the third break shows it would not have fired on a retry with a new id anyway. Step 3’s try_door.py exercises three of the five (unbalanced, bad_amount and duplicate). Nothing in this lab exercises too_few_legs or unknown_account, so write a posting for each, one with a single leg and one with an account id that does not exist, and check that you get the refusal codes in the table.

ARTEFACT Write the ledger design note ~45 MIN
YOU PRODUCELedger design note

Template

# Ledger design note: <ledger name>, version <n>
Author <engineer> · Reviewer <second engineer> · Signs off <finance controller> · Date <date>
Decision needed: <what the signer is asked to approve, and by when>

## Purpose
<One paragraph: what the ledger records, and what it is not for.>

## Accounts
| Account | Type | May go negative? | Why |
|---|---|---|---|

## Posting rules
| Rule | Refusal code | What goes wrong without it |
|---|---|---|

## Invariants and how each is checked
| Invariant | Check (command or query) | Last result |
|---|---|---|

## What the ledger does not own
| Rule or fact | Owner | How the ledger finds out |
|---|---|---|

## Tests
- On good data: <what, and the result>
- On bad data: <what, and the result>

## Known gaps
| Gap | What would show it | Fix and owner |
|---|---|---|

## How this note could be wrong
<One way, and what would show it.>
WORKED EXAMPLE

Owoleaf ledger design note, version 1. Ayomide, the engineer who owns the ledger, writes it. A second engineer reviews it. Nkiru, who does the finance work, signs for the accounts and invariants, because at a real company the finance controller signs what the books may and may not do. Decision needed: approve this ledger as the only way to write entries.

Purpose. Record every movement as entries that balance, and derive every balance from them.

Accounts. 2,005: 2,000 wallets (liabilities, refused below zero) and five company accounts (a design choice: only wallets are refused below zero).

Rules. Six, each with a code. Only insufficient_funds ever fired on the real history: 276 of the 4,060 failed attempts. The other 3,784 the ledger would post.

Invariants. The replay matched 2,000 wallets and 5 company accounts with 0 differences. Wallets hold 12,243,862,835 kobo (₦122,438,628.35). check.py --db data/mine.sqlite runs six invariants and ends OK: all invariants hold.

Not owned. Balance caps, daily limits, card declines and bank availability belong to the wallet’s policy, the provider and the partner bank. The ledger learns of them only as a refused attempt.

Tests. Good data: 79,827 posted transactions. Bad data: try_door.py (four of six postings refused) and the 4,060 failed attempts as dry runs. With the overdraft rule removed, refusals fell to 0 and check.py still said OK, so only the bad data tests that rule.

Gaps. A retry with a new id and the same external reference posted ₦15,539.00 (1,553,900 kobo) twice, and only invariant 6 noticed. Fix: a unique index on kind plus external reference, owner Ayomide. too_few_legs and unknown_account have no test yet.

Could be wrong. The generator wrote the entries, so a clean match shows consistency, not truth. Only the partner bank’s statement sits outside the generator: it differs from the ledger by 3,094,735 kobo, which the nine planted breaks explain.

Now you

A month later, Owoleaf has added the unique index on kind plus external reference to its ledger, and Nkiru wants a version 2 of the note before the wallet goes to more customers. You are the engineer who owns the ledger. Rewrite the note for version 2. Use the lab’s outputs: the third break’s refusal (UNIQUE constraint failed), transactions stored: 83887 and OK: all invariants hold on retry_fixed.sqlite, and the answer to the chapter’s last question, that only insufficient_funds ever fired. Add a rule to the table, remove the gap the index closes, keep any it does not (the index stops only a retry that carries the same reference), and write the two missing tests (one leg, an unknown account) and their results from your own run. The second engineer reviews it, and Nkiru signs it. It supports one decision: whether the wallet may take more customers on this ledger.

Self-check

All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: Integrating a payment provider: charges, verification, webhooks →