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 |
internals |
The seam the other crates reach the money representation through: cent, amount, scale, and the kuatia-money re-exports. Not public API (ADR-0029) |
OverflowError |
Returned when a monetary 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 |
Scale |
Decimal places, for parsing and formatting a decimal string. Not stored and not public; an amount formats itself |
Asset |
Registry row: { id, code, symbol, decimals }. Written once, never updated (ADR-0028) |
Amount |
A value with the Arc<Asset> it is denominated in, and the only money type on the public surface. Built by conversion, value first: (500, usd) is minor units, ("5.00", usd) the written form, and each also takes &usd. Gives up Display at the asset's scale, checked arithmetic that refuses two assets, and minor_units() -> i128 |
Denominate |
usd.amount("100.00")? on an Asset or an Arc<Asset>: the same conversions from the asset's side. A trait, so it must be in scope; the prelude brings it. See transfers.md |
AmountError |
AssetMismatch, Overflow, or Parse: why an amount could not be built or combined |
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 |
Envelope::reference() |
The caller's reference bytes from the reserved key, or None. Bytes, not a string: a caller writing the metadata map directly is not held to UTF-8 |
ValueDate |
The day an entry takes effect, as days since 1970-01-01. A calendar day rather than an instant, so no timezone shifts it. ValueDate::new(y, m, d) rejects a date that does not exist |
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 must not exceed its credits: the balance stays >= 0 and the account holds no negative posting) |
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 the commit transaction's own delete gives
double-spend safety, and this step does notsum(consumed) == sum(created) for each assetDEBIT_MUST_NOT_EXCEED_CREDIT flag. An account that permits overdraft can
hold one>= 0The output is a Plan. It holds transfer_id, postings_to_deactivate and
postings_to_create.
The async resource layer, and the only crate that an application depends on. It
re-exports kuatia-core, kuatia-types and kuatia-storage. So a caller
reaches the crates below it, and names none of them in a manifest.
| Feature | Effect |
|---|---|
sqlite |
Re-exports the SQL backend as kuatia::sql with the SQLite driver, and enables Ledger::connect |
postgres |
The same, with the PostgreSQL driver |
i128 |
Swaps the Cent backing to i128 across the whole chain |
Both backend features are off by default, so an application on InMemoryStore
or a hand-written Store does not compile sqlx.
| 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, AssetStore, BookStore, BalanceProjectionStore) |
error |
StoreError, LedgerError: unified error hierarchy |
mem_store |
InMemoryStore: in-memory Store implementation for tests |
sql |
The SQL backend (SqlStore), under the sqlite or postgres feature |
prelude |
The domain types, the builders, Ledger, and the stores in one import |
workflow |
run_transfers: multi-transfer LIFO composition over commit/reverse |
let ledger = Ledger::new(InMemoryStore::new());
let ledger = Ledger::connect("sqlite://ledger.db?mode=rwc").await?;
let ledger = Ledger::connect("postgres://user:pass@host/db").await?;
Ledger::connect installs the driver, connects a one-connection pool and
applies the schema. To size the pool yourself, build a SqlStore from your own
pool and pass it to Ledger::new. SqlStore::connect documents the two traps
that you then take on.
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 |
TransferBuilder builds a transfer, and ledger.commit(transfer) commits it:
| Builder method | Description |
|---|---|
.pay(from, to, amount) |
Single movement between accounts. amount is anything convertible into an Amount |
.deposit(to, amount, external) |
Two movements: offset on external + credit on target |
.withdraw(from, amount, external) |
Single movement from account to external |
.movement(from, to, amount) |
Raw movement for custom operations |
.build() |
Result<Transfer, AmountError>: the first amount that failed to convert, or the transfer |
| 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 |
|---|---|
asset(code, symbol, decimals) |
The asset with this code, registered on first sight. Returns the handle; a code registered at another precision is refused (ADR-0030) |
asset_by_id(id) |
The registered asset with this id, cached for the life of the process |
balance(account, asset) |
The everyday read: closest cache point plus the folded tail since its watermark. Returns an Amount, hydrated from the registry. asset is anything that names one: the handle, the row, or the id |
balance_as_of(account, asset, as_of) |
The balance at a past commit instant (unix ms), bounded above by as_of; commit time, never the value date |
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) |
get_postings(ids) |
Postings by id from the immutable record; a consumed posting still resolves, which is how a reader recovers the debit side of a committed envelope |
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 other posting and account write methods
are simple instructions that return the number of affected rows, as a u64. A
read and a setup step use them.
graph TB
Store --> AccountStore
Store --> PostingStore
Store --> TransferStore
Store --> CommitStore
Store --> EventStore
Store --> AssetStore
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) -> Amount. That last
one is the single read a backend can compute itself, because it can do so
exactly (ADR-0024). These are all reads, because only CommitStore writes a
postingTransferStore: 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_sinceAssetStore: create_asset, get_asset, get_asset_by_code,
list_assetsBookStore: create_book, get_book, list_booksA commit is one commit_envelope transaction and not a sequence of primitives.
So crash-safety comes from the transaction rather than from write-ahead
recovery. It is also the only way the ledger ever writes a posting.
A posting's state is its live-index membership:
Live.Spent.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
The delete of the consumed live row inside the commit transaction is the atomic
single-winner claim. So two commits cannot both spend a posting. The commit
whose delete affects no row is refused with CommitRejection::DoubleSpend. See
ADR-0025.
Balance computation lives in the Ledger and not in the Store. balance_exact
asks the store for one exact aggregate, which is PostingStore::live_balance
(ADR-0024). balance folds a tail on top of a cache point.
Cache maintenance sits apart, on ledger.projection(), and ProjectionConfig
tunes it. Neither one affects what a balance says. They affect only the speed of
the 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 carries IO only, as NotFound and Internal. The atomic
commit_envelope reports a domain refusal as an
Ok(CommitOutcome::Rejected(CommitRejection)) value. The refusal is a
double-spend, a frozen account, a closed account or an overdraft. The ledger
maps that value to a LedgerError.
The other writes return a count, and those are create_account and
create_book. The caller reads what the count says.
workflow::run_transfers(ledger, transfers) commits the transfers in order. On
the first failure it reverses the receipts it already committed, in
last-in-first-out order, through ledger.reverse(..). Each single commit is
already atomic in the store, so this is a plain runner and not a saga machine.
use kuatia::workflow::run_transfers;
let receipts = run_transfers(&ledger, &[
TransferBuilder::new().deposit(alice, ("50.00", &usd), bank).build()?,
TransferBuilder::new().pay(alice, bob, ("20.00", &usd)).build()?,
])
.await?;
If a transfer fails, the runner reverses the committed ones and returns the
original error. A reversal that fails surfaces as
LedgerError::CompensationFailed.