transfers.md 13 KB

Transfers

Overview

A transfer is the atomic unit of value movement in the ledger. It consumes the postings that exist and creates new ones. Per-asset conservation holds across both sides.

There are two layers:

  • Intent layer: a caller expresses movements, and each one is an amount that moves from one account to another. The ledger resolves these into concrete postings.
  • Envelope layer: the concrete postings to consume and to create. The ledger uses this layer internally after resolution, and a direct caller can use it too.

Movements

A movement is the fundamental unit. A caller states one as an Amount, which carries the asset with the value:

TransferBuilder::new()
    .pay(from, to, ("50.00", usd))
    .build()?

The stored movement holds the same thing:

struct Movement {
    from: AccountId,  // account being debited
    to: AccountId,    // account being credited
    amount: Amount,   // negative for the offset leg of a deposit
}

An amount serializes with its asset's definition beside the value. So a stored movement reads back whole, and nothing has to consult the registry (ADR-0029). The content address is the exception. It hashes the asset's id and the value alone. So a code or a symbol that someone writes differently cannot re-identify a transfer.

Every operation is one or more movements, and that holds for pay, deposit and withdraw. The resolve step aggregates the net debit per (account, asset) pair. It then selects postings only for an account with a positive net debit.

Operations

Every verb takes one amount, which is anything that converts into an Amount:

Written Means
(500, usd) 500 minor units
("5.00", usd) the written form, parsed at the asset's own scale
(500, &usd) the same, without a clone of the handle
usd.amount(500)? the same conversion from the asset's side

The value comes first. A person speaks the money in that order. usd is an Arc<Asset> from ledger.asset(&id), or an Asset from ledger.list_assets(). So nothing can name an unregistered asset.

amount is a method of the Denominate trait, which must be in scope. Both kuatia::prelude::* and kuatia_core::* bring it. The tuple forms need no import. A conversion that fails waits until build, which is the reason the ? sits there.

Pay

Transfer value between two accounts.

TransferBuilder::new()
    .pay(from, to, amount)
    .build()?

Produces one movement:

from to asset amount
A B USD 50

Resolve selects postings from A to cover 50 and creates a +50 posting on B. It 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, which means an account without the DEBIT_MUST_NOT_EXCEED_CREDIT flag. So it can hold the negative offset posting. The operation creates an offset posting on the source and a credit on the target.

TransferBuilder::new()
    .deposit(to, 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 necessary, because the operation creates the offset directly.

Conservation: created sum = -100 + 100 = 0. Consumed sum = 0. Both sides balance.

Withdraw

Move value from an account to an external destination.

TransferBuilder::new()
    .withdraw(from, 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 an operation that does not fit the convenience methods:

TransferBuilder::new()
    .movement(from, to, amount)
    .build()?

Resolve Algorithm

The resolve step converts a Transfer, which is the intent, into an Envelope, which holds concrete postings. It uses a two-pass algorithm:

Pass 1: Create output postings and aggregate debits

For each movement:

  1. Create a NewPosting { owner: to, asset, value: amount }. Set payer: Some(from) when from != to.
  2. Add 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 the net debit is above 0:

  1. Query the live postings for that account and that asset.
  2. The positive postings sometimes cover the net debit. Then run a greedy largest-first selection and compute change = selected sum − net debit. If the change is above 0, create a change posting that returns the remainder to the account.
  3. The positive postings are sometimes not enough:
    • For an account that permits overdraft, which has no DEBIT_MUST_NOT_EXCEED_CREDIT flag: consume every positive posting. Then create a negative posting for the shortfall, net_debit − total_positive.
    • For an account that forbids overdraft, which is an account with the flag: fail with InsufficientFunds.

A pair with a net debit of 0 or below needs no posting selection, so resolve skips it. In a deposit, the account that permits overdraft is one such pair.

Aggregation benefit

Resolve aggregates the debits before selection, so several movements that debit the same account share one selection pass. Take a transfer with two payments from account A, of 50 and 30. Resolve then selects postings once for 80 rather than twice.

Envelope

After resolution, the result is an Envelope:

struct Envelope {
    consumes: Vec<PostingId>,       // postings to deactivate
    creates: Vec<NewPosting>,       // new postings to create
    account_snapshots: Vec<AccountSnapshotId>,
    book: BookId,
    metadata: Metadata,
}

The envelope is content-addressed. Its TransferId is the double-SHA-256 of its canonical binary serialization. This gives idempotency, because a second commit of the same envelope returns the cached receipt. It also gives tamper evidence.

Transfer identity: give every distinct transfer a reference

The id is the hash of the content, so two transfers with identical content are one transfer. The second commit returns the receipt of the first one and applies nothing.

A payment distinguishes itself. The postings it consumes are part of the content, and the second payment consumes what the first one left behind. So two payments of the same amount to the same account are two transfers, and the caller does nothing to make that true.

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. The ledger discards the second one as a replay. The same holds for any issuance.

Set reference on anything that can legitimately repeat:

let top_up = TransferBuilder::new()
    .deposit(alice, ("50.00", usd), 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. That is the behaviour you want from a retry, and one rule covers both. The reference lives 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 that the balance cache folds its tail against (ADR-0019). A backdated one would hide a transfer behind a cache point that exists, and the cached balance would then be silently wrong.

Set a value date on an entry that belongs to a different day than the day the ledger booked it on. A correction, a late settlement and a future-dated order are all such entries:

let correction = TransferBuilder::new()
    .pay(alice, bob, (amount, usd))
    .value_date(ValueDate::new(2026, 11, 20)?)
    .build()?;

ValueDate is a calendar day and 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 a dated entry, because a backdated deposit repeats safely without a reference.

It also means that nothing can correct a value date in place. The ledger reverses and reposts an entry with a wrong value. A reversal carries the original's value date, so the period the entry landed in is the period of its reversal.

An entry with no value date takes effect on the day of its commit. It falls outside an explicit value-date window rather than inside every one.

See ADR-0027.

Transfer Builder

The TransferBuilder gives a fluent API for the construction of a transfer:

let transfer = TransferBuilder::new()
    .deposit(alice, (1000, usd), bank)
    .pay(alice, bob, (200, usd))
    .book(sales_book)
    .metadata(metadata)
    .build()?;

One transfer can hold several movements of different types, and all of them run atomically. A transfer with several movements is a compound journal entry. See 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. That is one transaction, and it spends the consumed postings, inserts the created ones, stores the transfer and appends the event.

The transaction re-checks double-spend, freeze and 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 that you already hold. A hand-built multi-asset envelope, an FX envelope and a reversal are all such envelopes, and reverse() uses this method. There is one commit path.

Reversal

reverse(transfer_id) creates a compensating envelope that:

  1. Consumes the postings that the original transfer created
  2. Recreates the postings that the original transfer consumed

This undoes the operation and keeps the full audit trail. The ledger deletes no posting.

Validation

Every envelope goes through validate_and_plan() before the ledger applies it. These are the validation steps:

  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 the commit transaction's own delete gives double-spend safety, and validation does not
  4. All referenced accounts exist, not frozen, not closed
  5. Account snapshot pinning (if provided)
  6. Book policy (if a book is loaded): the book allows the referenced assets, accounts and flags
  7. Per-asset conservation: sum(consumed) == sum(created)
  8. Negative postings forbidden only on an account that forbids overdraft, which is an account with the DEBIT_MUST_NOT_EXCEED_CREDIT flag. An account that permits overdraft can hold one
  9. Balance-constraint enforcement: for an account that forbids overdraft, the projected balance stays >= 0

Steps 1-7 run in the pure core before the write. store.commit_envelope(..) then applies the effects in one transaction, and that transaction re-checks the stateful guards inside itself. The guards are:

  • Double-spend. The delete of a consumed live posting is the atomic single-winner claim.
  • Freeze and close.
  • The zero floor of an account that forbids overdraft, which is steps 8 and 9. It is one exact aggregate over the post-commit live rows.

The checks and the writes share the transaction, so the floor is strict and not best-effort. Two transfers cannot both pass and together push an account below zero (ADR-0023, which supersedes 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.

See architecture.md for details on each check.