accounts.md 11 KB

Accounts

Overview

An account is a versioned entity that owns postings. The ledger never stores a balance. It always computes one from the postings of a given (account, asset) pair. balance() sums the live postings, which are the postings in the live index. It excludes a spent posting, because a spent posting stays only in the immutable table.

Structure

Field Type Description
id AccountId { id: i64, sub: i64 } Stable identity: a base id plus a subaccount (sub = 0 is the main account)
version u64 Starts at 1, increments on every mutation
flags AccountFlags Lifecycle (FROZEN, CLOSED, INFLIGHT), the balance constraint (DEBIT_MUST_NOT_EXCEED_CREDIT), and user-defined bits
book BookId Book this account belongs to
metadata Metadata BTreeMap<String, Vec<u8>> for free-form data

Subaccounts

An AccountId is a base id plus a sub. sub = 0 is the account's main account. A non-zero sub is a subaccount of the same base id.

Each (id, sub) is a full account record with its own flags, book, version and lifecycle. The ledger creates, versions, freezes and closes it exactly like any other account. A subaccount can forbid overdraft while its base account permits it, or the reverse, because every check keys on the full AccountId.

Subaccounts partition one owner's holdings into several balances, and a caller can address each one. They serve as sub-ledgers, earmarks and reservations, and they need no unrelated top-level account. AccountId has these helpers: new(id) for the main account, with_sub(id, sub), base() for the main account of an id, and is_main().

AccountId also has an IBAN-style string form through Display and FromStr. It is a fixed 20 characters: an 18-character base-36 body, then two ISO 7064 mod-97 check digits at the end. There is no country code. An example is KUJL QEL8 IX2X GTBK 4425.

The body packs the base id, which is 63 bits, and the subaccount, which is SUB_BITS bits, into one 93-bit value. A keyed format-preserving permutation then runs over that value before the encode step, and the parse step inverts the permutation. So a code does not reveal the raw ids. The key is a global seed with a default, and set_id_seed configures it.

A parse validates the checksum, so the ledger rejects a mistyped identifier. This is obfuscation and not security, because the seed decodes it. The form is for display and for routes only, and storage keeps the two i64 legs. The fixed width is what caps the subaccount at SUB_BITS. See ADR-0015.

The ledger always reports a balance per subaccount and never sums balances across subaccounts:

  • balance(&AccountId, &AssetId) reads exactly one subaccount.
  • balances(&AccountId, &AssetId, sub) returns one entry per non-closed subaccount. sub = None spans all of them, and Some(s) filters to one.
  • list_subaccounts(&AccountId) lists the non-closed subaccounts of a base id.

A base account does not roll up its subaccounts. There is deliberately no API that sums across them. An aggregate read takes a base id: i64 plus an optional subaccount filter, as get_postings_by_account and get_transfers_for_account do. An exact entity operation takes the full &AccountId. Book membership has the base account as its scope, so a book that lists a base account admits every subaccount of that account. See adr/0012-subaccounts.md.

Balance constraint

An account carries one balance rule, and its flags hold that rule:

State Balance floor Negative postings
default (no flag) none yes (overdraft allowed, unbounded)
DEBIT_MUST_NOT_EXCEED_CREDIT >= 0 no

By default an account can overdraw without bound. An overdraft is a negative posting, which is an offset position, and the ledger assigns it to the account to cover a shortfall. The account's positive postings are sometimes not enough for a debit. The resolve step then consumes all of them and creates a negative posting for the remainder. The ledger records the transfer if it conserves value per asset.

DEBIT_MUST_NOT_EXCEED_CREDIT forbids this. The account's debits must never exceed its credits, so its balance must not go negative and it must not hold a negative posting. Validation rejects any transfer that creates a negative posting on such an account, and any transfer that projects its balance below zero.

The convenience constructor Account::debit_must_not_exceed_credit(id) names the invariant directly, and Account::forbids_overdraft() reports it. There is no bounded "credit line" floor between the two states. The application above the ledger enforces a credit-line limit if it needs one.

The commit transaction re-checks the zero floor over the live rows that survive the spend, so the check is strict and not best-effort. Double-spend safety comes from the same transaction. The delete of a consumed live row is the atomic single-winner claim, so nothing can consume a posting twice. See accounting-mapping.md and the ADR at adr/0023-atomic-storage-commit.md.

Lifecycle

An account follows a three-state lifecycle, and flags control it:

Created (v1) → Frozen (v2) → Unfrozen (v3) → Closed (v4)
                  ↑               │
                  └───────────────┘
Operation Precondition Effect
freeze(id) Not closed Sets FROZEN flag, increments version
unfreeze(id) Frozen Clears FROZEN flag, increments version
close(id) Zero live postings Sets CLOSED flag, increments version
  • A frozen account rejects every transfer, both a debit and a credit.
  • A closed account rejects every transfer, and nothing can reopen it.
  • A close needs zero live postings for every asset.

Append-Only Versioning

The ledger never modifies an account in place. Each mutation appends a new version:

Version 1: { flags: DEBIT_MUST_NOT_EXCEED_CREDIT }          ← created
Version 2: { flags: DEBIT_MUST_NOT_EXCEED_CREDIT | FROZEN } ← frozen
Version 3: { flags: DEBIT_MUST_NOT_EXCEED_CREDIT }          ← unfrozen

The store enforces version_new == version_current + 1, which prevents a gap and prevents an overwrite. account_history(id) queries the full history.

Snapshot Pinning

A transfer can carry AccountSnapshotId values. Each one is a pair of (AccountId, snapshot_hash), and it records the account version that the transfer validated against.

During validation, when snapshots are present, the ledger hashes the current account state and compares the two. A mismatch produces AccountVersionMismatch. This prevents a TOCTOU race, where something mutates an account between the load and the apply.

commit() fills in the snapshots when a caller provides none.

Subaccounts and balances

A base id plus an i64 subaccount identifies an account, written as AccountId { id, sub }. sub = 0 is the main account. Each (id, sub) is its own record with its own flags, book and version, so a subaccount is a full account that shares a base id.

Subaccounts are how one account holds many concurrent inflights. An inflight hold is a subaccount of its destination, keyed by a value that the trade derives. See adr/0012-subaccounts.md.

The ledger reports a balance segregated per subaccount and never sums balances across subaccounts:

  • balance(&AccountId, asset) reads one subaccount.
  • balances(&AccountId, asset, sub) returns one entry per non-closed subaccount. sub = None spans all of them, and Some(s) filters to one. It excludes a closed subaccount.
  • list_subaccounts(&AccountId) lists the non-closed subaccounts of a base account.

Balance Computation

The ledger computes the balance for an (account reference, asset) pair like this:

balance(account, asset) = sum(p.value for p in postings
                              where p.owner == account
                              and   p.asset == asset
                              and   p.is_live)

There is no stored balance field. So no drift can appear between the balance and the postings under it.

A read returns an Amount. The asset travels with the value, so a caller that holds two balances of different assets cannot add them. The money type underneath is not public. A caller gets the amount's own Display, its checked arithmetic, or minor_units() (ADR-0029). The asset must be registered, because an unregistered one has no precision to report at.

balance_as_of(account, asset, as_of) answers the same question at a past instant. It folds only the transfers that committed up to as_of onto the newest cache point at or before it (ADR-0019). as_of is a commit instant in unix milliseconds and not a value date.

The commit clock watermarks the cache points that a read folds against. So an entry that a value date backdates still lands at the instant of its commit. A past balance cannot come from the postings themselves, because a posting carries no timestamp.

Account Types in Practice

The single flag divides accounts into two kinds. Intent is a matter of how you use the account, not a distinct type. A wallet, a boundary and a system account are all intents, not types.

Overdraft-forbidding accounts (DEBIT_MUST_NOT_EXCEED_CREDIT)

These hold a positive posting only, and they cannot go negative. Use them for an end-user wallet, a merchant account, and any account that must never spend value it does not hold. Construct one with Account::debit_must_not_exceed_credit(id).

Overdraft-permitting accounts (default)

An ordinary Account::new(id) can go negative without bound. This covers:

  • Issuance and system balance: a revenue, COGS or fee account, or an internal account that holds an offset position.
  • Ledger boundary: the counterparty in a deposit and in a withdrawal, where value enters or leaves the ledger. It takes on a negative balance to offset the value that the ledger credits elsewhere. This is normal and not a bug.
  • Credit-like accounts: an account whose balance can go below zero. The ledger enforces no upper bound on the overdraft. A specific credit limit is the application's responsibility.

The positive postings of such an account are sometimes not enough for a debit. A negative posting then covers the shortfall.

Accounts carry no accounting class

There is no asset, liability, equity, income or expense dimension on an account. The structure table above is the whole record, and no field classifies it. So the ledger cannot group accounts the way a balance sheet or a profit-and-loss statement does. Those are the reports this blocks, and the only ones. A trial balance is a flat list of every account's balance, so it needs a read across accounts rather than a class.

A class that something only reports on fits in metadata, which the ledger stores and never interprets. A class that the ledger has to enforce fits better in one of the user-defined AccountFlags bits. A book policy can gate participation on a flag, and it cannot gate on metadata. The retail example marks its revenue and warehouse accounts that way.

Classical accounting's "asset" names a class of account. Kuatia's Asset names a currency or a commodity. The two senses are unrelated.