Pure, sans-IO (Input/Output) decision logic. No async runtime, near-zero
dependencies (sha2, serde, bitflags).
| Module | Purpose |
|---|---|
types |
Domain model: all core types, binary serialization, and AutoId generator |
validate |
validate_and_plan(): single entry point for invariant enforcement |
hash |
Double-SHA-256 (Secure Hash Algorithm), canonical encoding helpers, transfer/account hashing |
posting_selection |
Greedy largest-first posting selection for the intent layer |
| Type | Description |
|---|---|
AccountId(i64) |
Stable account identity (snowflake-style, generated in Rust) |
AssetId(u32) |
Asset identifier (USD, BTC, etc.). Conservation boundary |
TransferId([u8; 32]) |
Content-addressed double-SHA-256 of transfer bytes |
PostingId { transfer, index } |
Identifies a posting by its creating transfer + position |
AccountSnapshotId { account, snapshot_id } |
Account state hash for version pinning |
Cent |
Smallest monetary unit (private field, backing integer hidden). Backing is i64 by default, i128 under the i128 feature. Checked arithmetic via checked_add, checked_sub, checked_neg, checked_sum returning Result<Cent, OverflowError> |
OverflowError |
Returned when a Cent operation would overflow or underflow |
PostingState |
Derived posting state (from live-index membership, not stored): Live, Spent, Missing |
PostingFilter |
Read filter over derived posting state: Live, All |
Amount |
Parser/formatter for decimal strings. Not stored; use at API boundaries only |
Posting |
Immutable signed amount of one asset owned by one account. Carries no state field; its state is derived from live-index membership (see PostingState) |
NewPosting |
Posting to be created (no id yet, assigned during validation) |
Transfer |
Atomic unit: consumes postings + creates postings + metadata |
EnvelopeBuilder |
Fluent builder for Envelope construction (the resolved form; TransferBuilder builds the intent) |
REFERENCE_KEY |
Reserved metadata key for a caller's transfer reference, set via TransferBuilder::reference |
Account |
Versioned entity with flags, book, metadata. Account::new(id) allows overdraft by default; Account::debit_must_not_exceed_credit(id) forbids it; Account::forbids_overdraft() queries the constraint |
AccountFlags |
Bitflags: FROZEN, CLOSED, DEBIT_MUST_NOT_EXCEED_CREDIT (when set, the account's debits may not exceed its credits: balance stays >= 0, no negative postings) |
Metadata |
BTreeMap<String, Vec<u8>> for free-form key-value data |
Receipt |
Confirmation of a committed transfer (contains transfer_id) |
AutoId |
Snowflake-inspired i64 ID generator: [0][40-bit ms][23-bit CRC32 or counter]. The ms field counts from KUATIA_EPOCH_MS (2026-01-01T00:00:00Z), giving ~34.8 years forward. Lives in kuatia-types::autoid |
validate_and_plan(input: PlanInput) -> Result<Plan, ValidationError> checks,
in order:
graph TD
A[1. Non-empty] --> B[2. No duplicate consumes]
B --> C[3. Posting existence]
C --> E[4. Account existence & lifecycle]
E --> F[5. Snapshot pinning]
F --> BP[6. Book policy]
BP --> G[7. Per-asset conservation]
G --> H[8. Negative posting restriction]
H --> J[9. Balance-constraint enforcement]
J --> I[Plan]
style I fill:#e8f5e9
Posting carries no state, so double-spend safety is enforced by the
commit transaction's own delete, not here)sum(consumed) == sum(created) for each assetDEBIT_MUST_NOT_EXCEED_CREDIT flag is
set); allowed on overdraft-permitting accounts>= 0Output is a Plan containing transfer_id, postings_to_deactivate, and
postings_to_create.
Async resource layer. Depends on kuatia-core, tokio, async-trait,
serde.
| Module | Purpose |
|---|---|
kuatia |
Ledger: primary API (non-generic, uses Arc<dyn Store>), atomic commit engine, intent layer |
store |
Store composite trait + sub-traits (AccountStore, PostingStore, TransferStore, CommitStore, EventStore, BookStore, BalanceProjectionStore) |
error |
StoreError, LedgerError: unified error hierarchy |
mem_store |
InMemoryStore: in-memory Store implementation for tests |
workflow |
run_transfers: multi-transfer LIFO composition over commit/reverse |
commit(transfer) resolves the intent into an envelope (read-only), validates it
in the pure core, then applies the effects through store.commit_envelope(..) in
one transaction. The store re-checks the stateful guards inside it:
graph LR
A[resolve] -->|Envelope| V[load + validate_and_plan]
V --> C["store.commit_envelope(..)"]
C -->|"one tx: idempotency + double-spend + freeze/close + floor, then apply"| E[Receipt]
style E fill:#e8f5e9
A crash leaves no half-applied state, so there is no recovery step.
| Method | Description |
|---|---|
commit(transfer) |
Resolve intent, validate, then one atomic store commit |
commit_envelope(envelope) |
The one commit path: validate → atomic store.commit_envelope; for pre-built/FX envelopes |
reverse(transfer_id) |
Builds a compensating envelope and runs commit_envelope |
Transfers are built via TransferBuilder and committed with
ledger.commit(transfer):
| Builder method | Description |
|---|---|
.pay(from, to, asset, amount) |
Single movement between accounts |
.deposit(to, asset, amount, external) |
Two movements: offset on external + credit on target |
.withdraw(from, asset, amount, external) |
Single movement from account to external |
.movement(from, to, asset, amount) |
Raw movement for custom operations |
| Method | Description |
|---|---|
create_account(account) |
Create account and emit AccountCreated event |
freeze(id) |
Set FROZEN flag, increment version, emit AccountFrozen event |
unfreeze(id) |
Clear FROZEN flag, increment version, emit AccountUnfrozen event |
close(id) |
Set CLOSED flag (requires zero active postings), emit AccountClosed event |
| Method | Description |
|---|---|
balance(account, asset) |
The everyday read: closest cache point plus the folded tail since its watermark |
balance_exact(account, asset) |
The authoritative sum of the live (unspent) postings, uncached. What the commit path reads |
balances(account, asset, sub?) |
One entry per non-closed subaccount; never summed across them (ADR-0012) |
list_accounts() |
All current account snapshots |
get_account(id) |
Latest account snapshot |
query_transfers(query) |
Paginated, filtered transfer history (by date range, book) |
history(account) |
All transfers involving an account |
postings(account) |
All postings (any state) |
query_postings(query) |
Paginated, filtered postings (by asset, PostingFilter) |
account_history(id) |
All version snapshots |
get_events_since(seq, limit) |
Query ledger event log after a sequence number |
The Store trait is a composite of focused sub-traits. A transfer commits
atomically through CommitStore; the remaining posting/account write methods are
dumb instructions returning the number of affected rows (u64), used by reads
and setup.
graph TB
Store --> AccountStore
Store --> PostingStore
Store --> TransferStore
Store --> CommitStore
Store --> EventStore
Store --> BookStore
AccountStore: get_account, get_accounts, create_account,
get_account_history, list_accounts; a version is appended only by
CommitStore::commit_transitionPostingStore: get_postings, get_posting_states,
get_postings_by_account(account, sub?, asset?, filter), query_postings(query),
live_balance(account, asset) -> Cent (the one read a backend may compute
itself, because it can do so exactly, ADR-0024). All reads: a posting is
written only by CommitStoreTransferStore: get_transfer, get_transfers_for_account,
query_transfersCommitStore: commit_envelope(request) -> CommitOutcome,
commit_transition(next, event) -> TransitionOutcome: the atomic write
boundary (ADR-0023)EventStore: append_event (idempotent on a dedup key: a transfer's id,
or a lifecycle transition's (account, version)), get_events_sinceBookStore: create_book, get_book, list_booksA commit is one commit_envelope transaction, not a sequence of primitives, so
crash-safety comes from the transaction rather than write-ahead recovery, and it
is the only way a posting is ever written.
State is live-index membership: in it, the posting is Live; in the immutable
table only, Spent; in neither, Missing. The posting row itself never
changes, and only a commit moves one between the two tables.
stateDiagram-v2
[*] --> Live: commit creates it
Live --> Spent: commit consumes it
Deleting the consumed live row inside the commit transaction is the atomic
single-winner claim, so two commits cannot both spend a posting: the one whose
delete affects no row is refused with CommitRejection::DoubleSpend. See
ADR-0025.
Balance computation lives in the Ledger, not the Store: balance_exact asks the
store for one exact aggregate (PostingStore::live_balance, ADR-0024) and
balance folds a tail on top of a cache point. Cache maintenance sits apart on
ledger.projection(), and ProjectionConfig tunes it; neither affects what a
balance says, only how fast it is read (ADR-0019).
LedgerError
├── Validation(ValidationError) // from kuatia-core (includes Overflow)
├── Store(StoreError) // storage failures
├── Selection(SelectionError) // insufficient funds (includes Overflow)
├── TransferNotFound
├── PostingNotReversible
├── DoubleSpend // a consumed posting was not live at commit time
├── AccountNotFound
├── AccountNotEmpty // can't close with active postings
├── AccountAlreadyClosed
├── BookNotFound // transfer named a book that does not exist
├── Overflow // monetary arithmetic overflow
└── CompensationFailed // multi-transfer reversal failed (original + compensation errors)
StoreError
├── NotFound(String)
├── Internal(String)
└── Misconfigured(String) // backend setup missing, retrying will not fix it
StoreError is IO-only (NotFound, Internal). The atomic commit_envelope
reports a domain refusal as an Ok(CommitOutcome::Rejected(CommitRejection))
value (double-spend, frozen, closed, overdraft) that the ledger maps to a
LedgerError; the remaining count-returning writes (create_account,
create_book) report a count and the caller derives meaning from it.
workflow::run_transfers(ledger, transfers) commits the transfers in order and,
on the first failure, reverses the already-committed receipts LIFO via
ledger.reverse(..). Each single commit is already atomic in the store, so this
is a plain runner, not a saga VM.
use kuatia::workflow::run_transfers;
let receipts = run_transfers(&ledger, &[
TransferBuilder::new().deposit(alice, usd, amount, bank)?.build(),
TransferBuilder::new().pay(alice, bob, usd, amount).build(),
])
.await?;
If a transfer fails, the committed ones are reversed and the original error is
returned; a failing reversal surfaces as LedgerError::CompensationFailed.