# Transfers ## Overview A transfer is the atomic unit of value movement in the ledger. It consumes existing postings and creates new ones, preserving per-asset conservation. There are two layers: - **Intent layer**: callers express movements (from, to, asset, amount). The ledger resolves these into concrete postings. - **Envelope layer**: concrete postings to consume and create. Used internally after resolution and available for direct callers. ## Movements A movement is the fundamental building block: ```rust struct Movement { from: AccountId, // account being debited to: AccountId, // account being credited asset: AssetId, // asset to transfer amount: Cent, // amount (may be negative for offset postings) } ``` Every operation (pay, deposit, withdraw) is expressed as one or more movements. The resolve step aggregates net debits per (account, asset) and selects postings only for accounts with a positive net debit. ## Operations ### Pay Transfer value between two accounts. ```rust TransferBuilder::new() .pay(from, to, asset, amount) .build() ``` Produces one movement: | from | to | asset | amount | |------|----|-------|--------| | A | B | USD | 50 | Resolve selects postings from A to cover 50, creates a +50 posting on B, and returns change to A if the selected postings exceed 50. ### Deposit Fund an account from a boundary source account. The source is an ordinary account that permits overdraft (no `DEBIT_MUST_NOT_EXCEED_CREDIT` flag), so it can hold the negative offset posting. Creates an offset posting on the source and a credit on the target. ```rust TransferBuilder::new() .deposit(to, asset, amount, external) .build() ``` Produces two movements: | from | to | asset | amount | |------|----|-------|--------| | external | external | USD | -100 | | external | to | USD | +100 | The first movement creates a -100 offset posting on the external account. The second creates a +100 posting on the target account. Net debit on the external account: -100 + 100 = **0**. No posting selection is needed: the offset is created directly. Conservation: created sum = -100 + 100 = 0. Consumed sum = 0. Both sides balance. ### Withdraw Move value from an account to an external destination. ```rust TransferBuilder::new() .withdraw(from, asset, amount, external) .build() ``` Produces one movement: | from | to | asset | amount | |------|----|-------|--------| | A | external | USD | 50 | Resolve selects postings from A to cover 50, creates a +50 posting on the external account, and returns change to A. ### Raw movement For operations that don't fit the convenience methods: ```rust TransferBuilder::new() .movement(from, to, asset, amount) .build() ``` ## Resolve Algorithm The resolve step converts a `Transfer` (intent) into an `Envelope` (concrete postings) using a two-pass algorithm: ### Pass 1: Create output postings and aggregate debits For each movement: 1. Create a `NewPosting { owner: to, asset, value: amount }` with `payer: Some(from)` when `from != to` 2. Accumulate the movement's amount into a net debit map keyed by `(from, asset)` ### Pass 2: Select postings for accounts with positive net debit For each `(account, asset)` pair where net debit > 0: 1. Query active postings for that account and asset 2. If positive postings cover the net debit: run greedy largest-first selection, compute change = selected sum − net debit, and (if change > 0) create a change posting returning the remainder to the account. 3. If positive postings are **insufficient**: - For accounts that allow overdraft (the `DEBIT_MUST_NOT_EXCEED_CREDIT` flag is not set): consume all positive postings and create a **negative posting** for the shortfall (`net_debit − total_positive`). - For accounts that forbid overdraft (the flag is set): fail with `InsufficientFunds`. Pairs with net debit <= 0 (e.g. the overdraft-permitting account in a deposit) are skipped. No posting selection needed. ### Aggregation benefit Aggregating debits before selection means that multiple movements debiting the same account share one selection pass. For example, if a transfer contains two payments from account A (50 + 30), the resolve selects postings once for 80 rather than twice. ## Envelope After resolution, the result is an `Envelope`: ```rust struct Envelope { consumes: Vec, // postings to deactivate creates: Vec, // new postings to create account_snapshots: Vec, book: BookId, metadata: Metadata, } ``` The envelope is content-addressed: its `TransferId` is the double-SHA-256 of its canonical binary serialization. This provides idempotency (committing the same envelope twice returns the cached receipt) and tamper evidence. ## Transfer identity: give every distinct transfer a reference Because the id is the hash of the content, two transfers with identical content **are one transfer**: the second commit returns the first one's receipt and applies nothing. A payment distinguishes itself. The postings it consumes are part of the content, and the second payment consumes what the first left behind, so paying the same amount to the same account twice produces two transfers with no effort from the caller. A transfer that consumes nothing cannot distinguish itself. A deposit creates value at the boundary, so two deposits of the same amount to the same account are byte-identical, and the second is discarded as a replay. The same holds for any issuance. Set `reference` on anything that may legitimately repeat: ```rust let top_up = TransferBuilder::new() .deposit(alice, usd, Cent::from(5_000), bank)? .reference("top-up-8f21c4") // this payment, not the last identical one .build(); ``` Read the other way, this is retry safety: repeat the same reference and a redelivered request collapses onto the transfer it already committed, which is the behaviour you want from a retry. One rule covers both. The reference is stored under the reserved `REFERENCE_KEY` metadata key, so it is part of the content address and part of the audit record. ## Booking date and value date Two dates, and they answer different questions: | | Set by | Means | Query with | |---|---|---|---| | `created_at` | the ledger, at commit | the instant this entry was recorded | `from_ts` / `to_ts` | | `value_date` | the caller, optional | the day this entry takes effect | `from_value_date` / `to_value_date` | A caller cannot set `created_at`, and that is deliberate: it is the clock the balance cache folds its tail against (ADR-0019), so a backdated one would hide a transfer behind an existing cache point and silently wrong the cached balance. Set a value date on an entry that belongs to a different day than the one it is booked on, which is a correction, a late settlement or a future-dated order: ```rust let correction = TransferBuilder::new() .pay(alice, bob, usd, amount) .value_date(ValueDate::new(2026, 11, 20)?) .build(); ``` `ValueDate` is a calendar day, not an instant, so no timezone can shift it. `ValueDate::new` rejects a date that does not exist, which keeps the builder method itself infallible. The value date is part of the content address, so two entries that differ only in the day they take effect are two transfers. That closes the duplicate trap above for dated entries: a backdated deposit repeats safely without a reference. It also means a value date cannot be corrected in place. An entry valued wrongly is reversed and reposted, and a reversal carries the original's value date, so the period the entry landed in is the period it is undone in. An entry with no value date takes effect the day it was committed, and falls outside an explicit value-date window rather than inside every one. See [ADR-0027](adr/0027-value-date-separate-from-commit-time.md). ## Transfer Builder The `TransferBuilder` provides a fluent API for constructing transfers: ```rust let transfer = TransferBuilder::new() .deposit(alice, usd, Cent::from(1000), bank) .pay(alice, bob, usd, Cent::from(200)) .book(sales_book) .metadata(metadata) .build(); ``` A single transfer can contain multiple movements of different types. All movements execute atomically. A transfer with multiple movements is a compound journal entry; see [journaling.md](journaling.md). ## Commit Path ``` Transfer → resolve → Envelope → validate → atomic store commit → Receipt ``` Resolution is read-only. `commit(transfer)` resolves, validates in the pure core, then hands the result to `CommitStore::commit_envelope`, one transaction that spends the consumed postings, inserts the created ones, stores the transfer and appends the event. The transaction re-checks double-spend, freeze/close and the overdraft floor inside itself, so those guards are strict rather than best-effort (ADR-0023). `ledger.commit_envelope(envelope)` takes the same path for an envelope you already hold (a hand-built multi-asset or FX envelope, or a reversal), and `reverse()` uses it. There is one commit path. ## Reversal `reverse(transfer_id)` creates a compensating envelope that: 1. Consumes the original transfer's created postings 2. Recreates the original transfer's consumed postings This undoes the operation while preserving the full audit trail. No postings are deleted. ## Validation Every envelope passes through `validate_and_plan()` before being applied. The validation steps are: 1. Non-empty (must consume or create at least one posting) 2. No duplicate consumed PostingIds 3. All consumed postings exist in the immutable table (a `Posting` carries no state, so double-spend safety is enforced by the commit transaction's own delete, not by validation) 5. All referenced accounts exist, not frozen, not closed 6. Account snapshot pinning (if provided) 7. Book policy (if a book is loaded): referenced assets/accounts/flags allowed by the book 8. Per-asset conservation: `sum(consumed) == sum(created)` 9. Negative postings forbidden only on accounts that forbid overdraft (the `DEBIT_MUST_NOT_EXCEED_CREDIT` flag is set); allowed on overdraft-permitting accounts 10. Balance-constraint enforcement: for an account that forbids overdraft, the projected balance stays `>= 0` Steps 1-8 run in the pure core before the write. The effects are then applied by `store.commit_envelope(..)` in one transaction, which re-checks the stateful guards inside it: double-spend (deleting a consumed live posting is the atomic single-winner claim), freeze/close, and the zero floor of an account that forbids overdraft (steps 9-10, one exact aggregate over the post-commit live rows). Because the checks and the writes share the transaction, the floor is **strict**, not best-effort: two transfers cannot both pass and jointly push an account below zero (ADR-0023, superseding the best-effort floor of ADR-0003). A crash leaves no half-applied state, so there is no write-ahead record and no recovery. See `crates/kuatia/tests/concurrency.rs` for the asserted guarantees and [architecture.md](architecture.md). See [architecture.md](architecture.md) for details on each check.