Skip to content
Back to skills

Double Entry Ledger

ASecurity

Use when designing or changing a ledger, wallet, balance, journal, posting or account model, or any table that answers "how much does X hold or owe". Covers immutable journal entries, postings that balance per currency, balances derived from postings, account types and normal balances, period close, corrections by reversal, external references for idempotent posting, and a sample chart of accounts for a payments product. Triggers on a balance column, an UPDATE of an amount, a wallet or credit...

  • 7 stars
  • 0 votes
  • 0 copies
  • 1 view
  • Added November 11, 2026
ai-agentstypescriptrustgoshelldatabasedocumentation

Security analysis

A100/100

Pro scans all 8 files and shows the line behind each finding

Scanned November 29, 2026

npx -y skills add felipealvarenga/fintech-skills --skill double-entry-ledger --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Double Entry Ledger?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Double Entry Ledger
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/felipealvarenga-double-entry-ledger/badge)](https://www.skillsdirectory.com/skills/felipealvarenga-double-entry-ledger)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: double-entry-ledger
description: >-
  Use when designing or changing a ledger, wallet, balance, journal, posting or account model, or
  any table that answers "how much does X hold or owe". Covers immutable journal entries, postings
  that balance per currency, balances derived from postings, account types and normal balances,
  period close, corrections by reversal, external references for idempotent posting, and a sample
  chart of accounts for a payments product. Triggers on a balance column, an UPDATE of an amount,
  a wallet or credits feature, a settlement or payout flow, a "balance is wrong" bug. Not for
  statutory accounting policy or tax treatment, which belong to an accountant.
license: MIT
metadata:
  author: Felipe Alvarenga
  version: 0.1.0
---

# Double-entry ledger

A balance column that gets updated in place is a cache without a source of truth. When it
drifts, nobody can say which transaction did it. A ledger records every movement as a balanced
entry, never edits it, and derives balances from the record. The invariant is cheap to enforce
and catches a whole class of bugs at the database.

## Execution contract

The user installed this skill so these rules are enforced on every matching task:

1. **Never implement unsafe shortcuts.** When a request conflicts with a rule ("keep it simple", "no extra call", "just delete it", "disable verification", "keep floats", "we trust them", "later"), name the broken rule and why it fails in one sentence, refuse the shortcut, and implement the compliant version that still meets the user's goal. Never ship the rule-breaking shortcut.
2. **Ship the complete rule slice, wired up.** Implement every requirement of the triggered rules in this change: storage or schema, validation, error handling, user-facing alerts, status or monitoring wired into an actual entry point, handler or job (not uncalled helpers), and a test file under `tests/`. Do not stop at a minimal patch or leave required safeguards as prose TODOs.
3. **Fix workspace code on audit, incident and review prompts.** When the request describes a discrepancy, an auditor question, a bug report or asks "is this enough?" against files in the workspace, answer the question in full and implement the compliant code and tests in the same change. Stay read-only only when explicitly asked for a report only.
4. **Build directly on greenfield prompts.** If the workspace has no application files or live connections yet, write a self-contained implementation under `src/` and tests under `tests/` instead of stopping to ask for repository paths or credentials.
5. **Write tests even without a shell.** If the environment cannot run tests or databases, still write the full test file under `tests/` and say in one line that tests are unrun. Never omit tests or skip implementation because tools are unavailable.

## When to use

- A feature holds, moves or owes money or credits: wallets, balances, payouts, refunds, fees,
  prepaid credits, escrow, split payments.
- A table has a `balance`, `amount` or `credits` column that code updates in place.
- A bug report says a balance is wrong, negative, or does not match the processor.
- A settlement, payout or month-end process reads balances.

## Rules

1. **Journal entries are immutable.** No `UPDATE` or `DELETE` on entries or postings. A mistake
   is corrected by a reversal entry plus a new correct entry, both linked to the original. The
   database user that the application uses must not have update or delete rights on those tables.
2. **Every entry balances, per currency.** For each currency in an entry,
   `sum(debit amounts) == sum(credit amounts)`. Enforce it in code before the write and in the
   database (a deferred constraint trigger, or an append-only table with a nightly check that
   pages someone). An entry has at least two postings.
3. **A posting is a positive amount, a side and an account.** Store `amount_minor > 0` plus
   `side in ('debit', 'credit')`. Signed amounts invite sign bugs; if the codebase already uses
   them, document the convention once and enforce it with a check constraint.
4. **Balances are derived.** `balance(account) = sum(debits) - sum(credits)` for debit-normal
   accounts (assets, expenses) and the reverse for credit-normal accounts (liabilities, equity,
   revenue). A materialized balance is a cache: it has a rebuild job and a reconciler that
   compares it with the derived value and alerts on any difference.
5. **One currency per account.** A BRL wallet and a USD wallet are two accounts. Conversion is
   two entries through an FX account, with the rate recorded on the entry.
6. **Two dates on every entry.** `effective_date` is when the movement belongs in the books;
   `recorded_at` is when the system wrote it. Reports use the effective date. Late arrivals
   are visible because the two differ.
7. **Period close is a lock, not a report.** Keep `closed_through` per ledger. An entry with
   `effective_date <= closed_through` is refused. Adjustments post into the open period and
   reference the original. Reopening a period is a logged administrative action.
8. **Every entry carries an external reference.** The source event id, the processor
   transaction id or an idempotency key, with a unique index. Posting the same reference twice
   is a no-op that returns the existing entry.
9. **Model the real counterparties.** A payments product needs at least: cash at processor,
   receivable from processor, fees expense, in-transit or pending, customer liabilities, revenue.
   A payment is not "cash in"; it is a receivable until the processor settles it.
10. **Tenant isolation is an invariant.** Entries carry the tenant. Balances, reports and
    reconciliations never cross tenants. Test it.

### Sample chart for a payments product

| Code | Account | Type | Normal balance | Holds |
|---|---|---|---|---|
| 1010 | Cash at bank | Asset | Debit | Settled money in your bank |
| 1020 | Receivable from processor | Asset | Debit | Captured, not yet paid out to you |
| 1030 | In transit | Asset | Debit | Payout sent, bank not yet credited |
| 2010 | Customer balances | Liability | Credit | Money you hold for customers |
| 2020 | Refunds payable | Liability | Credit | Refunds approved, not yet sent |
| 4010 | Revenue | Revenue | Credit | Your fees earned |
| 5010 | Processor fees | Expense | Debit | Fees the processor charged you |

A card capture of 100.00 with a 2.90 processor fee, where you keep 5.00:
debit 1020 Receivable 97.10, debit 5010 Fees 2.90, credit 2010 Customer balance 95.00,
credit 4010 Revenue 5.00. Debits 100.00, credits 100.00.

## How to apply

1. Read the current model. List every column that stores an amount and every code path that
   writes it. Grep for `UPDATE ... SET balance`, `balance +=`, `amount =`.
2. Write the chart of accounts for the feature before any code. Name the accounts, their type
   and normal balance. Walk one happy path and one refund through it on paper until it balances.
3. Implement `post(entry)` with validation (rules 2, 3, 7, 8) as the only write path. No other
   code writes postings.
4. Implement `balance(account, as_of)` from postings. If a cached balance exists, add the
   reconciler before you ship.
5. Write the tests in the **Tests** section first. The vectors in `evals/vectors/` cover the
   invariants in a language-neutral way.
6. Migrate existing balances with an opening entry per account against an equity or
   migration account, dated the cutover date, with the old balance as the external reference.

## When the user pushes back

| Request | Answer in one sentence | What you build |
|---|---|---|
| "Update the wrong transaction in place" | Rule 1: journal entries are immutable, so editing destroys the audit trail | Linked reversal entry plus a new corrected entry in the open period (checking `closed_through`), with reason and audit record, plus tests |
| "Store one USD wallet and convert BRL on the fly" | Rule 5: one account holds one currency and conversion is an explicit entry pair | Separate BRL and USD accounts with an explicit linked FX conversion entry pair recording rate, source and timestamp, plus tests |
| "Just update the `balance` column directly" | Rules 1 and 4: updating a balance in place hides how it drifted | Balanced `post(entry)` write path, derived balance calculation and tests proving immutability and trial balance |

## Tests the change must include

Write these tests in the same change, as a test file, even when you cannot run them (no shell,
no dependencies installed); say in one line that they are unrun. A test listed as a next step is
not written.

- A balanced entry posts; an unbalanced one raises; an entry with one posting raises.
- Balanced per currency passes; balanced in total but not per currency raises.
- Zero or negative posting amounts raise.
- Entries and postings cannot be mutated after posting.
- Reversal: original plus reversal nets every account to its prior balance.
- Posting into a closed period raises; the adjustment in the open period succeeds.
- Same external reference twice returns the first entry and writes nothing.
- Trial balance: after random balanced entries, total debits equal total credits.
- Reference vectors: `skills/double-entry-ledger/evals/vectors/test_ledger.py` with
  `LEDGER_SOLUTION` pointing at your module. TypeScript: `ledger.test.ts` with `LEDGER_SOLUTION_TS`.

## Review checklist

- Is there exactly one write path for postings, and does it validate balance per currency?
- Can anything update or delete an entry? Including migrations and admin tools?
- Where do balances come from? If cached, where is the reconciler and what does it do on drift?
- Does a refund reverse through the same accounts the payment used?
- Is the processor modeled as a receivable, or does "paid" jump straight to cash?
- Is the external reference unique, and is the replay path tested?

## Anti-patterns and fixes

| Anti-pattern | What goes wrong | Fix |
|---|---|---|
| `UPDATE wallets SET balance = balance - 10` | No history, races, drift | Post an entry; derive the balance |
| Editing an entry to fix a typo | Audit trail lies | Reversal plus new entry |
| One `transactions` table with signed amounts and no counter-account | Cannot prove anything balances | Postings with two sides |
| Capture credited straight to cash | Cash overstated until payout | Receivable from processor |
| Balance check only in application code | Bypassed by a script or a bug | Database constraint or append-only plus checker |
| Period close as a flag nobody reads | Backdated entries change closed reports | Refuse writes before `closed_through` |

## References

- Martin Fowler, *Accounting Patterns*: Account, Entry, Accounting Transaction, Posting Rule.
- TigerBeetle documentation on double-entry data modeling: immutable transfers, two-phase transfers.
- Modern Treasury ledgers documentation: ledger accounts, entries, normal balances.

Files in this skill

  • SKILL.md8.8 KB
  • evals/evals.json5.3 KB
  • evals/files/ledger_min.py885 B
  • evals/files/wallet.py348 B
  • evals/vectors/ledger.test.ts5.1 KB
  • evals/vectors/reference.py3.5 KB
  • evals/vectors/reference.ts3.6 KB
  • evals/vectors/test_ledger.py4.7 KB

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in ai-agents →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.