Просмотр исходного кода

Give the ledger an asset registry, and make an amount carry its asset

A value in this ledger was a Cent: an integer with no asset on it. Two of them
added and compared freely, so a caller holding one account's dollars and the
same account's euros could sum them, and no invariant downstream could catch
it, because the mistake happens after the ledger has answered. Inside, the
per-asset discipline lived in map keys, runtime checks and a SQL predicate,
none of which a caller can see.

An asset is now a registered row: a code, a symbol, and the decimal places its
amounts are written at. A caller names one by code and the ledger mints its id,
so registration is one line that states what the caller knows and nothing else,
and it is idempotent, which is what setup code wants. A code registered at
another precision is refused rather than resolved, because the stored precision
is what every amount recorded against that asset was written at and the row
cannot be rewritten.

An Amount is a value with the asset it is denominated in, and it is what every
structure above the database columns holds: a movement, a posting, a posting to
be created, a cache point. It is also what the reads hand back, which is where
the bug class actually closed. Adding two assets is a rejected operation at the
call site that tries it. A string is parsed at the asset's own scale, so the
precision a caller once had to track is read from the registry instead, and a
double sign no longer slips through as a positive.

Making the stored structures hold an amount needed one decision: the serialized
form carries the asset definition beside the value. That is what lets a record
decode with no registry to consult, and it makes an append-only audit row
self-describing. The content address deliberately does not carry it, and still
hashes the asset's id and the value alone, so writing a symbol differently
cannot re-identify a transfer. A golden vector taken before any of this moved
asserts that, and it held.

The columns keep an integer beside an asset id, because an index and an exact
sum are built on them, and a posting read left-joins the registry to rebuild
the amount. Left, not inner: an inner join would drop a posting whose asset is
missing without saying so, and the only outcome worse than a loud failure is a
quiet one.

Cent is in no public signature. What a caller gets is Display at the asset's
scale, arithmetic that refuses a mismatch, and the minor units as a plain
integer for a presentation layer doing its own formatting. The crates that
still need the representation reach it through one named seam, since they are
siblings and cannot share a private one.

Three decisions are recorded as ADR-0028, ADR-0029 and ADR-0030. Upgrading an
existing database needs three things done first: register every asset already
in use, settle any two assets sharing a code before migration 015 adds the
unique index, and drain inflight authorizations, whose leg table rides as CBOR
in a transfer's metadata and has moved.
C 4 дней назад
Родитель
Сommit
883e5621d0
74 измененных файлов с 3689 добавлено и 1321 удалено
  1. 84 0
      CHANGELOG.md
  2. 4 3
      CLAUDE.md
  3. 1 0
      Cargo.lock
  4. 17 3
      crates/kuatia-core/src/hash.rs
  5. 80 56
      crates/kuatia-core/src/posting_resolution.rs
  6. 104 83
      crates/kuatia-core/src/validate.rs
  7. 2 3
      crates/kuatia-dashboard/src/api.rs
  8. 0 43
      crates/kuatia-dashboard/src/assets.rs
  9. 19 41
      crates/kuatia-dashboard/src/data.rs
  10. 4 2
      crates/kuatia-dashboard/src/main.rs
  11. 26 26
      crates/kuatia-dashboard/src/seed.rs
  12. 36 57
      crates/kuatia-dashboard/src/ui.rs
  13. 72 23
      crates/kuatia-money/src/lib.rs
  14. 97 0
      crates/kuatia-storage-sql/src/asset.rs
  15. 7 5
      crates/kuatia-storage-sql/src/commit.rs
  16. 4 1
      crates/kuatia-storage-sql/src/dialect.rs
  17. 1 0
      crates/kuatia-storage-sql/src/lib.rs
  18. 8 0
      crates/kuatia-storage-sql/src/migrate.rs
  19. 18 0
      crates/kuatia-storage-sql/src/migrations/014_assets.sql
  20. 8 0
      crates/kuatia-storage-sql/src/migrations/015_asset_code_unique.sql
  21. 34 7
      crates/kuatia-storage-sql/src/posting.rs
  22. 17 8
      crates/kuatia-storage-sql/src/projection.rs
  23. 19 6
      crates/kuatia-storage-sql/src/row.rs
  24. 1 1
      crates/kuatia-storage-sql/src/sqlite_ext.rs
  25. 17 5
      crates/kuatia-storage-sql/tests/postgres.rs
  26. 24 15
      crates/kuatia-storage-sql/tests/sqlite.rs
  27. 67 24
      crates/kuatia-storage/src/mem_store.rs
  28. 36 10
      crates/kuatia-storage/src/store.rs
  29. 141 33
      crates/kuatia-storage/src/store_tests.rs
  30. 15 6
      crates/kuatia-storage/tests/concurrency.rs
  31. 3 0
      crates/kuatia-types/Cargo.toml
  32. 557 0
      crates/kuatia-types/src/amount.rs
  33. 87 0
      crates/kuatia-types/src/asset.rs
  34. 2 2
      crates/kuatia-types/src/book.rs
  35. 8 6
      crates/kuatia-types/src/canonical.rs
  36. 27 0
      crates/kuatia-types/src/internals.rs
  37. 6 4
      crates/kuatia-types/src/lib.rs
  38. 24 16
      crates/kuatia-types/src/posting.rs
  39. 71 44
      crates/kuatia-types/src/transfer.rs
  40. 21 25
      crates/kuatia/examples/escrow.rs
  41. 27 25
      crates/kuatia/examples/fund_and_trade.rs
  42. 30 31
      crates/kuatia/examples/inflight_hold.rs
  43. 22 22
      crates/kuatia/examples/overdraft.rs
  44. 13 14
      crates/kuatia/examples/withdraw.rs
  45. 39 1
      crates/kuatia/src/error.rs
  46. 45 40
      crates/kuatia/src/inflight.rs
  47. 94 91
      crates/kuatia/src/inflight/projection.rs
  48. 10 0
      crates/kuatia/src/ledger.rs
  49. 151 0
      crates/kuatia/src/ledger/asset.rs
  50. 85 38
      crates/kuatia/src/ledger/balance.rs
  51. 48 23
      crates/kuatia/src/ledger/commit.rs
  52. 1 1
      crates/kuatia/src/ledger/projection.rs
  53. 126 65
      crates/kuatia/tests/concurrency.rs
  54. 89 56
      crates/kuatia/tests/inflight.rs
  55. 372 169
      crates/kuatia/tests/integration.rs
  56. 158 50
      crates/kuatia/tests/projection.rs
  57. 75 32
      crates/kuatia/tests/workflow.rs
  58. 3 0
      doc/SUMMARY.md
  59. 4 4
      doc/accounting-mapping.md
  60. 6 0
      doc/accounts.md
  61. 102 0
      doc/adr/0028-amount-carries-its-asset.md
  62. 104 0
      doc/adr/0029-stored-amounts-and-a-closed-money-surface.md
  63. 97 0
      doc/adr/0030-assets-named-by-code.md
  64. 3 0
      doc/adr/README.md
  65. 5 3
      doc/architecture.md
  66. 21 12
      doc/crates.md
  67. 24 22
      doc/examples/exchange.md
  68. 20 19
      doc/examples/retail.md
  69. 46 6
      doc/glossary.md
  70. 7 7
      doc/inflight.md
  71. 7 7
      doc/journaling.md
  72. 5 4
      doc/pending-states.md
  73. 28 1
      doc/storage-schema.md
  74. 53 20
      doc/transfers.md

+ 84 - 0
CHANGELOG.md

@@ -9,6 +9,43 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
 
 ### Added
 
+- Amounts are what the ledger stores and what it hands back. `Movement`,
+  `Posting`, `NewPosting` and `BalanceProjection` each hold one `Amount`
+  instead of an `AssetId` beside a value, and an amount serializes with its
+  asset's definition, so a stored record decodes with no registry to consult.
+  The content address is unchanged: it still hashes the asset's id and the
+  value, and a golden vector in `kuatia-core` asserts it. The amount columns
+  are unchanged too, so ADR-0024's exact sums and indexes still work; a posting
+  read left-joins the registry to rebuild the amount, and fails loudly rather
+  than dropping a row if an asset is missing. `Cent` no longer appears in any
+  public signature: an `Amount` gives up `Display`, checked arithmetic that
+  refuses two assets, and `minor_units() -> i128`, and the other crates reach
+  the integer through `kuatia_types::internals`. `AssetId` stays public as the
+  name of an asset. *(breaking throughout)* (ADR-0029)
+
+  Two notes for an upgrade. Register every asset already in use first, or
+  reads of postings in unregistered assets fail. And an inflight
+  authorization opened before this cannot be confirmed after it: the leg table
+  is CBOR inside a transfer's metadata and its shape moved.
+- An asset registry, and an `Amount` that carries its asset. `Asset { id, code,
+  symbol, decimals }` is a row written once and never updated; `AssetStore`
+  adds `create_asset`/`get_asset`/`list_assets` and migration `014_assets`.
+  `Amount` pairs a `Cent` with the `Arc<Asset>` it is denominated in, built
+  only by conversion: an integer is minor units, a string is the written form
+  parsed at the asset's own scale, so `(500, usd)` and `("5.00", usd)` are the
+  same amount and `("5.001", usd)` is refused. `balance`, `balance_exact`,
+  `balance_as_of` and `SubAccountBalance` now hand back an `Amount`, so two
+  balances in different assets cannot be added by the caller holding them, and
+  `InsufficientFunds` names the asset that fell short. A commit refuses an
+  unregistered asset, and a balance read of one fails: an unregistered asset
+  has no precision to report at. Each conversion also takes a reference to the
+  asset (`("100.00", &usd)`), and `Denominate` gives the same conversions from
+  the asset's side (`usd.amount("100.00")?`), so one handle serves several
+  movements without cloning. `Arc<Asset>` stops at the public API, so
+  nothing stored moves and `CANONICAL_VERSION` stays at 6. *(breaking: every
+  balance read, and any caller matching on `InsufficientFunds`)* (ADR-0028)
+- `Cent: TryFrom<i128>`, the range-checked conversion that previously existed
+  only inside the canonical and storage byte decoders.
 - `Ledger::balance_as_of(account, asset, as_of)`, the balance as it stood at a
   past commit instant: the newest cache point at or before `as_of` plus the
   transfers committed up to it. `as_of` is commit time in unix milliseconds and
@@ -37,6 +74,53 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
 
 ### Changed
 
+- `Ledger::asset(code, symbol, decimals)` registers an asset on first sight and
+  returns its handle, so naming money takes one line and no invented id:
+  `ledger.asset("EUR", "\u{20ac}", 2)`. Idempotent, so setup code calls it
+  unconditionally; a code already registered at another precision is
+  `AssetRedefined` rather than either definition quietly winning. The id is
+  minted in Rust as an account's or a book's is, `code` is unique (migration
+  `015_asset_code_unique`), and `AssetStore` gains `get_asset_by_code`. The
+  by-id lookup is now `asset_by_id`, and `create_asset` stays for a caller that
+  wants to choose the id. *(breaking: `Ledger::asset` has a new meaning)*
+  (ADR-0030)
+- Anything that names an asset takes `impl Into<AssetId>`: `BookBuilder::allow_asset`
+  and the `Ledger` reads (`asset`, `balance`, `balance_exact`, `balance_as_of`,
+  `balances`). An `Asset`, an `Arc<Asset>`, a reference to either, or the id
+  itself all work, so a caller holding a handle stops writing `.id` to get four
+  bytes back out of it. The `Store` trait keeps `&AssetId`, since it is used
+  behind `Arc<dyn Store>` and a generic method would cost object safety.
+- An amount conversion takes the value first: `(500, usd)`, `("5.00", usd)`,
+  `(500, &usd)`. The asset-first spelling is gone, because one order is enough
+  and this one reads the way the money does.
+- `Denominate` covers `Asset` as well as `Arc<Asset>`, so `asset.amount(500)?`
+  works on a row from `list_assets` and not only on a handle from `asset`. It
+  is a trait, so it has to be in scope; the prelude brings it.
+- `Asset::scale` is no longer public. It returned a `Scale`, which this cycle
+  took off the public surface, so a caller could call it and not name what came
+  back. An amount formats and parses itself.
+- A decimal amount refuses a second sign. `"--5"` used to strip one sign, parse
+  the rest with another, and come back as a positive five. One sign is allowed,
+  of either kind, and a digit or a point has to follow it.
+- `Ledger::asset` reports `AssetNotFound` only for an absent row. A store
+  failure used to arrive as the same error, so a dropped connection told a
+  caller to register an asset it had registered already.
+- `TransferBuilder`'s verbs take one amount in place of an asset beside a
+  value: `.pay(from, to, amount)`, `.deposit(to, amount, external)`,
+  `.withdraw(from, amount, external)`, `.movement(from, to, amount)`, where
+  `amount` is anything convertible into an `Amount`. A failed conversion is
+  held until `build`, which now returns `Result<Transfer, AmountError>`. That
+  retires `deposit`'s mid-chain `Result`, which was the one verb that broke the
+  fluent chain. *(breaking for every builder call site)* (ADR-0028)
+- `kuatia_money::Amount` is `Scale` and `ParseAmountError` is
+  `ParseDecimalError`. The old name described a decimal-place count that parsed
+  and formatted and was never stored, and it is the name the asset-carrying
+  value wants. An asset's scale is reachable as `asset.scale()`. *(breaking)*
+  (ADR-0028)
+- `SubAccountBalance::value` is `amount`, and carries an `Amount`. *(breaking)*
+- The dashboard's hardcoded asset table is gone: it registers its assets in the
+  ledger and reads precision back from there. Its `/api/overview` issued
+  figures serialize under `value` rather than `issued`.
 - The ledger no longer has to be held in an `Arc`. `commit`, `commit_envelope`,
   `reverse`, the inflight entry points and `workflow::run_transfers` take
   `&self`, so `Ledger::new(store)` is usable directly; an `Arc<Ledger>` still

+ 4 - 3
CLAUDE.md

@@ -9,9 +9,9 @@ Kuatia is an append-only, auditable, multi-asset UTXO-style ledger library in Ru
 ```
 crates/
   kuatia-money/     Cent monetary type + CentBacking trait; integer width (i64 default, i128 via feature) is hidden and swappable
-  kuatia-types/     Domain types: AccountId, Posting, Movement, AutoId, etc.; re-exports Cent/Amount from kuatia-money
+  kuatia-types/     Domain types: AccountId, Posting, Movement, AutoId, etc.; re-exports Cent/Scale from kuatia-money
   kuatia-core/      Pure, sync, no-IO logic: validation, hashing, posting selection
-  kuatia-storage/   Store trait (7 sub-traits), InMemoryStore, conformance tests
+  kuatia-storage/   Store trait (8 sub-traits), InMemoryStore, conformance tests
   kuatia-storage-sql/  SQL backend: SQLite/PostgreSQL via sqlx
   kuatia/           Async layer: Ledger resource, atomic commit engine, intent API
 doc/
@@ -26,8 +26,9 @@ doc/
 
 ## Key concepts
 
+- **Asset / Amount**: an `Asset` is a registry row (`{ id, code, symbol, decimals }`), written once and never updated, and `decimals` is the scale its written amounts parse at. A caller names one by code: `ledger.asset("EUR", "\u{20ac}", 2)` registers it on first sight and returns the handle, the id is minted in Rust like an account's, `code` is unique, and a code registered at another precision is refused (ADR-0030). `asset_by_id` is the lookup. An `Amount` is a value plus the `Arc<Asset>` it is denominated in, built only by conversion, value first (`(500, usd)` minor units, `("5.00", usd)` written form, `(500, &usd)` to borrow the handle, `usd.amount(..)` from the asset's side through the `Denominate` trait). Everything above the database columns holds one: `Movement`, `Posting`, `NewPosting`, `BalanceProjection`. An amount serializes with its asset, so a stored record decodes with no registry; the content address still hashes the asset id and the value, frozen by a golden vector in `kuatia-core`. `Cent` is in no public signature, and the other crates reach it through `kuatia_types::internals`; a caller uses `Display`, the checked arithmetic, or `minor_units() -> i128`. `AssetId` stays public as an asset's name. An unregistered asset has no amount: commits and balance reads of one fail (ADR-0028, ADR-0029).
 - **Posting**: signed amount of one asset owned by one account. State is live-index membership, so it is Live (unspent) or Spent, with nothing in between.
-- **Movement**: `{ from, to, asset, amount }` — the fundamental unit of intent. All operations (pay, deposit, withdraw) are one or more movements.
+- **Movement**: the fundamental unit of intent, an `Amount` moving from one account to another. A caller writes `.pay(from, to, ("5.00", usd))`; the stored `Movement { from, to, asset, amount }` keeps the id and the value apart, because the postings it resolves into carry an `AssetId` and because a `Movement` must stay deserializable while an `Amount` cannot be. All operations (pay, deposit, withdraw) are one or more movements.
 - **Envelope**: concrete postings to consume and create — the resolved form of movements.
 - **Conservation**: for each asset, `sum(consumed) == sum(created)`.
 - **Balance constraint**: one per-account flag, `AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT`. Default (no flag): overdraft allowed, unbounded, a shortfall becomes a negative offset posting and the transfer records if it conserves value. Flag set: balance may not go negative and the account may not hold a negative posting. Construct with `Account::debit_must_not_exceed_credit(id)`; query with `Account::forbids_overdraft()`. There is no bounded floor and no system/external policy label; a boundary/deposit account is just a default overdraft-permitting account.

+ 1 - 0
Cargo.lock

@@ -1104,6 +1104,7 @@ dependencies = [
  "bitflags",
  "kuatia-money",
  "serde",
+ "serde_json",
 ]
 
 [[package]]

+ 17 - 3
crates/kuatia-core/src/hash.rs

@@ -72,13 +72,26 @@ mod tests {
         EnvelopeBuilder::new()
             .creates(vec![NewPosting {
                 owner: AccountId::new(1),
-                asset: AssetId::new(1),
-                value: Cent::from(100),
+                amount: Amount::from((
+                    100,
+                    std::sync::Arc::new(Asset::new(AssetId::new(1), "USD", "$", 2)),
+                )),
                 payer: None,
             }])
             .build()
     }
 
+    /// A frozen vector, so a change to how an envelope is built or stored shows
+    /// up here rather than silently re-identifying every transfer in a database.
+    /// Only a deliberate `CANONICAL_VERSION` bump may move it.
+    #[test]
+    fn content_hash_matches_its_golden_vector() {
+        assert_eq!(
+            format!("{:?}", envelope_id(&sample_envelope())),
+            "TransferId(b0f1199b6039ce9d114ee5e9335508a85b16f60d51a3a9f0567e0d978b0655df)"
+        );
+    }
+
     #[test]
     fn content_hash_deterministic() {
         let t = sample_envelope();
@@ -91,7 +104,8 @@ mod tests {
     fn different_envelopes_different_hashes() {
         let t1 = sample_envelope();
         let mut t2 = sample_envelope();
-        t2.creates[0].value = Cent::from(200);
+        t2.creates[0].amount =
+            Amount::from((200, std::sync::Arc::clone(t2.creates[0].amount.asset())));
         assert_ne!(envelope_id(&t1), envelope_id(&t2));
     }
 

+ 80 - 56
crates/kuatia-core/src/posting_resolution.rs

@@ -18,9 +18,12 @@
 use std::collections::HashMap;
 use std::error::Error;
 use std::fmt;
+use std::sync::Arc;
 
+use kuatia_types::internals;
+use kuatia_types::internals::{Cent, OverflowError};
 use kuatia_types::{
-    Account, AccountId, AssetId, Cent, Envelope, EnvelopeBuilder, NewPosting, OverflowError,
+    Account, AccountId, Amount, AmountError, AssetId, Envelope, EnvelopeBuilder, NewPosting,
     Posting, PostingId, Transfer,
 };
 
@@ -37,10 +40,11 @@ use kuatia_types::{
 /// by [`ResolveError`].
 #[derive(Debug, Clone, PartialEq, Eq)]
 pub struct InsufficientFunds {
-    /// Total value of eligible postings.
-    pub available: Cent,
-    /// Amount the caller asked for.
-    pub requested: Cent,
+    /// What the eligible postings came to. Carries the asset, so the pair below
+    /// names a quantity rather than two bare numbers.
+    pub available: Amount,
+    /// What the caller asked for, in the same asset.
+    pub requested: Amount,
 }
 
 impl fmt::Display for InsufficientFunds {
@@ -98,10 +102,15 @@ impl From<OverflowError> for ResolveError {
 pub struct Debit {
     /// The account (subaccount) being debited.
     pub account: AccountId,
-    /// The asset owed.
-    pub asset: AssetId,
-    /// The positive amount owed.
-    pub amount: Cent,
+    /// The positive amount owed, carrying the asset it is owed in.
+    pub amount: Amount,
+}
+
+impl Debit {
+    /// The asset owed, which is what the available-postings map is keyed by.
+    pub fn asset(&self) -> AssetId {
+        self.amount.asset_id()
+    }
 }
 
 /// Output of resolution pass 1: postings credited straight from movements, plus
@@ -118,32 +127,33 @@ pub struct MovementDraft {
 /// accumulate the net debit on its source. Debits are returned in a
 /// deterministic (account, asset) order so golden vectors are stable regardless
 /// of `HashMap` iteration order.
-pub fn draft_movements(transfer: &Transfer) -> Result<MovementDraft, OverflowError> {
+pub fn draft_movements(transfer: &Transfer) -> Result<MovementDraft, AmountError> {
     let mut creates: Vec<NewPosting> = Vec::new();
-    let mut net_debits: HashMap<(AccountId, AssetId), Cent> = HashMap::new();
+    let mut net_debits: HashMap<(AccountId, AssetId), Amount> = HashMap::new();
 
     for m in &transfer.movements {
         let payer = if m.from != m.to { Some(m.from) } else { None };
         creates.push(NewPosting {
             owner: m.to,
-            asset: m.asset,
-            value: m.amount,
+            amount: m.amount.clone(),
             payer,
         });
-        let entry = net_debits.entry((m.from, m.asset)).or_insert(Cent::ZERO);
-        *entry = entry.checked_add(m.amount)?;
+        // Summing amounts rather than values makes the per-asset key a
+        // redundant check instead of the only one: a key that lost its asset
+        // leg would now fail here rather than net two assets together.
+        let running = match net_debits.remove(&(m.from, m.amount.asset_id())) {
+            Some(sum) => sum.checked_add(&m.amount)?,
+            None => m.amount.clone(),
+        };
+        net_debits.insert((m.from, m.amount.asset_id()), running);
     }
 
     let mut debits: Vec<Debit> = net_debits
         .into_iter()
         .filter(|(_, amount)| amount.is_positive())
-        .map(|((account, asset), amount)| Debit {
-            account,
-            asset,
-            amount,
-        })
+        .map(|((account, _), amount)| Debit { account, amount })
         .collect();
-    debits.sort_by_key(|d| (d.account, d.asset));
+    debits.sort_by_key(|d| (d.account, d.asset()));
 
     Ok(MovementDraft { creates, debits })
 }
@@ -193,40 +203,46 @@ pub fn resolve_envelope(input: ResolveInput<'_>) -> Result<Envelope, ResolveErro
     let mut consumes: Vec<PostingId> = Vec::new();
 
     for debit in &debits {
+        // Selection works in values rather than amounts: the key already fixed
+        // one asset for this whole pass, and a greedy walk needs an ordering,
+        // which two assets have no answer for.
+        let owed = internals::cent(&debit.amount);
+        let asset = debit.amount.asset();
         let avail: &[Posting] = available
-            .get(&(debit.account, debit.asset))
+            .get(&(debit.account, debit.asset()))
             .map(Vec::as_slice)
             .unwrap_or(&[]);
         let total_positive = Cent::checked_sum(
             avail
                 .iter()
-                .filter(|p| p.value.is_positive())
-                .map(|p| p.value),
+                .filter(|p| internals::cent(&p.amount).is_positive())
+                .map(|p| internals::cent(&p.amount)),
         )?;
 
-        if total_positive >= debit.amount {
+        if total_positive >= owed {
             // Enough positive postings: greedily take them largest-first to
             // minimise the number consumed (and therefore the change postings
             // created), summing as we go so we stop once the debit is covered.
-            let mut candidates: Vec<&Posting> =
-                avail.iter().filter(|p| p.value.is_positive()).collect();
-            candidates.sort_by_key(|p| std::cmp::Reverse(p.value));
+            let mut candidates: Vec<&Posting> = avail
+                .iter()
+                .filter(|p| internals::cent(&p.amount).is_positive())
+                .collect();
+            candidates.sort_by_key(|p| std::cmp::Reverse(internals::cent(&p.amount)));
 
             let mut consumed_sum = Cent::ZERO;
             for posting in candidates {
                 consumes.push(posting.id);
-                consumed_sum = consumed_sum.checked_add(posting.value)?;
-                if consumed_sum >= debit.amount {
+                consumed_sum = consumed_sum.checked_add(internals::cent(&posting.amount))?;
+                if consumed_sum >= owed {
                     break;
                 }
             }
 
-            let change = consumed_sum.checked_sub(debit.amount)?;
+            let change = consumed_sum.checked_sub(owed)?;
             if change.is_positive() {
                 creates.push(NewPosting {
                     owner: debit.account,
-                    asset: debit.asset,
-                    value: change,
+                    amount: Amount::from((change, asset)),
                     payer: None,
                 });
             }
@@ -241,21 +257,20 @@ pub fn resolve_envelope(input: ResolveInput<'_>) -> Result<Envelope, ResolveErro
             if permits_overdraft {
                 let positives: Vec<PostingId> = avail
                     .iter()
-                    .filter(|p| p.value.is_positive())
+                    .filter(|p| internals::cent(&p.amount).is_positive())
                     .map(|p| p.id)
                     .collect();
                 consumes.extend_from_slice(&positives);
-                let shortfall = debit.amount.checked_sub(total_positive)?;
+                let shortfall = owed.checked_sub(total_positive)?;
                 creates.push(NewPosting {
                     owner: debit.account,
-                    asset: debit.asset,
-                    value: shortfall.checked_neg()?,
+                    amount: Amount::from((shortfall.checked_neg()?, asset)),
                     payer: None,
                 });
             } else {
                 return Err(ResolveError::Selection(InsufficientFunds {
-                    available: total_positive,
-                    requested: debit.amount,
+                    available: Amount::from((total_positive, Arc::clone(asset))),
+                    requested: debit.amount.clone(),
                 }));
             }
         }
@@ -276,6 +291,16 @@ pub fn resolve_envelope(input: ResolveInput<'_>) -> Result<Envelope, ResolveErro
 mod tests {
     use super::*;
     use kuatia_types::*;
+    use std::sync::Arc;
+
+    /// An amount of `asset` in minor units. An amount compares by asset id, so
+    /// building the row here is equivalent to reading it back from a registry.
+    fn money<V>(asset: AssetId, value: V) -> Amount
+    where
+        Amount: From<(V, Arc<Asset>)>,
+    {
+        Amount::from((value, Arc::new(Asset::new(asset, "TEST", "$", 2))))
+    }
 
     fn acct(id: i64) -> AccountId {
         AccountId::new(id)
@@ -288,15 +313,15 @@ mod tests {
                 index,
             },
             owner,
-            AssetId::new(1),
-            Cent::from(value),
+            money(AssetId::new(1), value),
         )
     }
 
     fn pay(from: AccountId, to: AccountId, amount: i64) -> Transfer {
         TransferBuilder::new()
-            .pay(from, to, AssetId::new(1), Cent::from(amount))
+            .pay(from, to, money(AssetId::new(1), Cent::from(amount)))
             .build()
+            .unwrap()
     }
 
     fn accounts(list: impl IntoIterator<Item = Account>) -> HashMap<AccountId, Account> {
@@ -313,14 +338,13 @@ mod tests {
         let draft = draft_movements(&pay(acct(1), acct(2), 100)).unwrap();
         assert_eq!(draft.creates.len(), 1);
         assert_eq!(draft.creates[0].owner, acct(2));
-        assert_eq!(draft.creates[0].value, Cent::from(100));
+        assert_eq!(draft.creates[0].amount.minor_units(), 100);
         assert_eq!(draft.creates[0].payer, Some(acct(1)));
         assert_eq!(
             draft.debits,
             vec![Debit {
                 account: acct(1),
-                asset: AssetId::new(1),
-                amount: Cent::from(100),
+                amount: money(AssetId::new(1), 100),
             }]
         );
     }
@@ -336,8 +360,7 @@ mod tests {
             draft.debits,
             vec![Debit {
                 account: acct(1),
-                asset: AssetId::new(1),
-                amount: Cent::from(100),
+                amount: money(AssetId::new(1), 100),
             }]
         );
     }
@@ -386,7 +409,7 @@ mod tests {
             .filter(|p| p.owner == acct(1))
             .collect();
         assert_eq!(change.len(), 1);
-        assert_eq!(change[0].value, Cent::from(70));
+        assert_eq!(change[0].amount.minor_units(), 70);
     }
 
     #[test]
@@ -418,7 +441,7 @@ mod tests {
             .filter(|p| p.owner == acct(1))
             .collect();
         assert_eq!(change.len(), 1);
-        assert_eq!(change[0].value, Cent::from(10));
+        assert_eq!(change[0].amount.minor_units(), 10);
     }
 
     #[test]
@@ -438,8 +461,8 @@ mod tests {
         assert_eq!(
             err,
             ResolveError::Selection(InsufficientFunds {
-                available: Cent::from(40),
-                requested: Cent::from(100),
+                available: money(AssetId::new(1), 40),
+                requested: money(AssetId::new(1), 100),
             })
         );
     }
@@ -462,8 +485,8 @@ mod tests {
         assert_eq!(
             err,
             ResolveError::Selection(InsufficientFunds {
-                available: Cent::ZERO,
-                requested: Cent::from(100),
+                available: money(AssetId::new(1), Cent::ZERO),
+                requested: money(AssetId::new(1), 100),
             })
         );
     }
@@ -491,7 +514,7 @@ mod tests {
             .filter(|p| p.owner == acct(1))
             .collect();
         assert_eq!(offset.len(), 1);
-        assert_eq!(offset[0].value, Cent::from(-70));
+        assert_eq!(offset[0].amount.minor_units(), -70);
     }
 
     #[test]
@@ -515,8 +538,9 @@ mod tests {
                 .iter()
                 .find(|p| p.owner == acct(1))
                 .unwrap()
-                .value,
-            Cent::from(-100)
+                .amount
+                .minor_units(),
+            -100
         );
     }
 }

+ 104 - 83
crates/kuatia-core/src/validate.rs

@@ -11,6 +11,8 @@ use std::error::Error;
 use std::fmt;
 
 use crate::hash::{account_hash, envelope_id};
+use kuatia_types::internals;
+use kuatia_types::internals::{Cent, OverflowError};
 use kuatia_types::*;
 
 // ---------------------------------------------------------------------------
@@ -81,16 +83,42 @@ struct PostingKeys {
     balances: Vec<(AccountId, AssetId)>,
 }
 
+/// Add `amount` to its asset's bucket, starting the bucket at zero of that
+/// asset. The add refuses a mismatch, so the bucket cannot end up holding a
+/// sum of two assets even if the key were wrong.
+fn fold_by_asset(
+    buckets: &mut HashMap<AssetId, Amount>,
+    amount: &Amount,
+) -> Result<(), AmountError> {
+    let asset = amount.asset_id();
+    let running = match buckets.remove(&asset) {
+        Some(sum) => sum.checked_add(amount)?,
+        None => amount.clone(),
+    };
+    buckets.insert(asset, running);
+    Ok(())
+}
+
+/// The bucket's sum, or nothing of that asset when the side is empty. Compared
+/// by value, since the two sides are the same asset by construction and a
+/// missing side has no asset handle to build a zero from.
+fn sum_of(buckets: &HashMap<AssetId, Amount>, asset: &AssetId) -> Cent {
+    buckets
+        .get(asset)
+        .map(internals::cent)
+        .unwrap_or(Cent::ZERO)
+}
+
 fn posting_keys(envelope: &Envelope, consumed_postings: &[Posting]) -> PostingKeys {
     let mut owners: Vec<AccountId> = Vec::new();
     let mut balances: Vec<(AccountId, AssetId)> = Vec::new();
     for np in envelope.creates() {
         owners.push(np.owner);
-        balances.push((np.owner, np.asset));
+        balances.push((np.owner, np.asset()));
     }
     for p in consumed_postings {
         owners.push(p.owner);
-        balances.push((p.owner, p.asset));
+        balances.push((p.owner, p.asset()));
     }
     owners.sort();
     owners.dedup();
@@ -210,6 +238,9 @@ pub enum ValidationError {
     },
     /// An arithmetic operation overflowed.
     Overflow,
+    /// Two amounts of different assets were combined while folding a side of
+    /// the conservation check, which means a bucket key lost its asset.
+    Amount(AmountError),
 }
 
 impl fmt::Display for ValidationError {
@@ -278,6 +309,7 @@ impl fmt::Display for ValidationError {
                 write!(f, "account {account:?} not allowed by book {book:?}")
             }
             Self::Overflow => write!(f, "monetary amount overflow"),
+            Self::Amount(e) => write!(f, "amount: {e}"),
         }
     }
 }
@@ -290,6 +322,15 @@ impl From<OverflowError> for ValidationError {
     }
 }
 
+impl From<AmountError> for ValidationError {
+    fn from(e: AmountError) -> Self {
+        match e {
+            AmountError::Overflow => Self::Overflow,
+            other => Self::Amount(other),
+        }
+    }
+}
+
 // ---------------------------------------------------------------------------
 // The pure decision function
 // ---------------------------------------------------------------------------
@@ -377,10 +418,10 @@ pub fn validate_and_plan(input: PlanInput<'_>) -> Result<Plan, ValidationError>
         if !policy.allowed_assets.is_empty() {
             let mut referenced_assets: HashSet<AssetId> = HashSet::new();
             for pid in envelope.consumes() {
-                referenced_assets.insert(consumed_by_id[pid].asset);
+                referenced_assets.insert(consumed_by_id[pid].asset());
             }
             for np in envelope.creates() {
-                referenced_assets.insert(np.asset);
+                referenced_assets.insert(np.asset());
             }
             for asset in &referenced_assets {
                 if !policy.allowed_assets.contains(asset) {
@@ -413,17 +454,19 @@ pub fn validate_and_plan(input: PlanInput<'_>) -> Result<Plan, ValidationError>
     }
 
     // 6. Per-asset conservation: Σ consumed == Σ created
-    let mut consumed_by_asset: HashMap<AssetId, Cent> = HashMap::new();
+    // Summed as amounts, not values: an amount refuses to add across assets, so
+    // the bucket key is now a second line of defence rather than the only one.
+    // A key that lost its asset leg would fail here instead of quietly netting
+    // one asset against another.
+    let mut consumed_by_asset: HashMap<AssetId, Amount> = HashMap::new();
     for pid in envelope.consumes() {
         let posting = consumed_by_id[pid];
-        let entry = consumed_by_asset.entry(posting.asset).or_insert(Cent::ZERO);
-        *entry = entry.checked_add(posting.value)?;
+        fold_by_asset(&mut consumed_by_asset, &posting.amount)?;
     }
 
-    let mut created_by_asset: HashMap<AssetId, Cent> = HashMap::new();
+    let mut created_by_asset: HashMap<AssetId, Amount> = HashMap::new();
     for np in envelope.creates() {
-        let entry = created_by_asset.entry(np.asset).or_insert(Cent::ZERO);
-        *entry = entry.checked_add(np.value)?;
+        fold_by_asset(&mut created_by_asset, &np.amount)?;
     }
 
     // All assets must appear in both sides (or have sum 0 on the missing side)
@@ -432,8 +475,8 @@ pub fn validate_and_plan(input: PlanInput<'_>) -> Result<Plan, ValidationError>
     all_assets.extend(created_by_asset.keys());
 
     for asset in &all_assets {
-        let consumed_sum = consumed_by_asset.get(asset).copied().unwrap_or(Cent::ZERO);
-        let created_sum = created_by_asset.get(asset).copied().unwrap_or(Cent::ZERO);
+        let consumed_sum = sum_of(&consumed_by_asset, asset);
+        let created_sum = sum_of(&created_by_asset, asset);
         if consumed_sum != created_sum {
             return Err(ValidationError::ConservationViolation {
                 asset: *asset,
@@ -446,7 +489,7 @@ pub fn validate_and_plan(input: PlanInput<'_>) -> Result<Plan, ValidationError>
     // 7. A negative posting (offset position) is only allowed on an account
     //    that permits overdraft. Only DEBIT_MUST_NOT_EXCEED_CREDIT forbids it.
     for np in envelope.creates() {
-        if np.value.is_negative() {
+        if internals::cent(&np.amount).is_negative() {
             let account = input
                 .accounts
                 .get(&np.owner)
@@ -454,8 +497,8 @@ pub fn validate_and_plan(input: PlanInput<'_>) -> Result<Plan, ValidationError>
             if account.forbids_overdraft() {
                 return Err(ValidationError::NegativePostingOnNonSystemAccount {
                     account: np.owner,
-                    asset: np.asset,
-                    value: np.value,
+                    asset: np.asset(),
+                    value: internals::cent(&np.amount),
                 });
             }
         }
@@ -467,13 +510,13 @@ pub fn validate_and_plan(input: PlanInput<'_>) -> Result<Plan, ValidationError>
     for pid in envelope.consumes() {
         let posting = consumed_by_id[pid];
         let entry = deltas
-            .entry((posting.owner, posting.asset))
+            .entry((posting.owner, posting.asset()))
             .or_insert(Cent::ZERO);
-        *entry = entry.checked_sub(posting.value)?;
+        *entry = entry.checked_sub(internals::cent(&posting.amount))?;
     }
     for np in envelope.creates() {
-        let entry = deltas.entry((np.owner, np.asset)).or_insert(Cent::ZERO);
-        *entry = entry.checked_add(np.value)?;
+        let entry = deltas.entry((np.owner, np.asset())).or_insert(Cent::ZERO);
+        *entry = entry.checked_add(internals::cent(&np.amount))?;
     }
 
     for ((account_id, asset_id), delta) in &deltas {
@@ -512,8 +555,7 @@ pub fn validate_and_plan(input: PlanInput<'_>) -> Result<Plan, ValidationError>
                     index: i as u16,
                 },
                 np.owner,
-                np.asset,
-                np.value,
+                np.amount.clone(),
             )
         })
         .collect();
@@ -529,6 +571,16 @@ pub fn validate_and_plan(input: PlanInput<'_>) -> Result<Plan, ValidationError>
 mod tests {
     use super::*;
     use std::collections::BTreeMap;
+    use std::sync::Arc;
+
+    /// An amount of `asset` in minor units. These tests assert on ids and
+    /// values, and an amount compares by asset id, so the metadata is filler.
+    fn money<V>(asset: AssetId, value: V) -> Amount
+    where
+        Amount: From<(V, Arc<Asset>)>,
+    {
+        Amount::from((value, Arc::new(Asset::new(asset, "TEST", "$", 2))))
+    }
 
     fn make_account(id: i64, flags: AccountFlags) -> Account {
         Account {
@@ -552,14 +604,12 @@ mod tests {
             creates: vec![
                 NewPosting {
                     owner: AccountId::new(1),
-                    asset: AssetId::new(1),
-                    value: Cent::from(100),
+                    amount: money(AssetId::new(1), Cent::from(100)),
                     payer: None,
                 },
                 NewPosting {
                     owner: AccountId::new(99),
-                    asset: AssetId::new(1),
-                    value: Cent::from(-100),
+                    amount: money(AssetId::new(1), Cent::from(-100)),
                     payer: None,
                 },
             ],
@@ -623,8 +673,7 @@ mod tests {
             consumes: vec![],
             creates: vec![NewPosting {
                 owner: AccountId::new(1),
-                asset: AssetId::new(1),
-                value: Cent::from(100),
+                amount: money(AssetId::new(1), Cent::from(100)),
                 payer: None,
             }],
             book: BookId(0),
@@ -732,8 +781,7 @@ mod tests {
         let posting = Posting {
             id: pid,
             owner: AccountId::new(1),
-            asset: AssetId::new(1),
-            value: Cent::from(50),
+            amount: money(AssetId::new(1), Cent::from(50)),
         };
         // Try to send 50 but create 100 for recipient (conservation will fail first,
         // but let's test overdraft with a valid conservation)
@@ -741,8 +789,7 @@ mod tests {
             consumes: vec![pid],
             creates: vec![NewPosting {
                 owner: AccountId::new(2),
-                asset: AssetId::new(1),
-                value: Cent::from(50),
+                amount: money(AssetId::new(1), Cent::from(50)),
                 payer: None,
             }],
             book: BookId(0),
@@ -784,15 +831,13 @@ mod tests {
         let posting = Posting {
             id: pid,
             owner: AccountId::new(1),
-            asset: AssetId::new(1),
-            value: Cent::from(100),
+            amount: money(AssetId::new(1), Cent::from(100)),
         };
         let envelope = Envelope {
             consumes: vec![pid],
             creates: vec![NewPosting {
                 owner: AccountId::new(2),
-                asset: AssetId::new(1),
-                value: Cent::from(100),
+                amount: money(AssetId::new(1), Cent::from(100)),
                 payer: None,
             }],
             book: BookId(0),
@@ -831,15 +876,13 @@ mod tests {
         let posting = Posting {
             id: pid,
             owner: AccountId::new(1),
-            asset: AssetId::new(1),
-            value: Cent::from(100),
+            amount: money(AssetId::new(1), Cent::from(100)),
         };
         let envelope = Envelope {
             consumes: vec![pid],
             creates: vec![NewPosting {
                 owner: AccountId::new(2),
-                asset: AssetId::new(1),
-                value: Cent::from(100),
+                amount: money(AssetId::new(1), Cent::from(100)),
                 payer: None,
             }],
             book: BookId(0),
@@ -880,15 +923,13 @@ mod tests {
         let posting = Posting {
             id: pid,
             owner: AccountId::new(1),
-            asset: AssetId::new(1),
-            value: Cent::from(100),
+            amount: money(AssetId::new(1), Cent::from(100)),
         };
         let envelope = Envelope {
             consumes: vec![pid],
             creates: vec![NewPosting {
                 owner: AccountId::new(2),
-                asset: AssetId::new(1),
-                value: Cent::from(100),
+                amount: money(AssetId::new(1), Cent::from(100)),
                 payer: None,
             }],
             book: BookId(0),
@@ -957,22 +998,19 @@ mod tests {
         let posting = Posting {
             id: pid,
             owner: AccountId::new(1),
-            asset: AssetId::new(1),
-            value: Cent::from(100),
+            amount: money(AssetId::new(1), Cent::from(100)),
         };
         let envelope = Envelope {
             consumes: vec![pid],
             creates: vec![
                 NewPosting {
                     owner: AccountId::new(2),
-                    asset: AssetId::new(1),
-                    value: Cent::from(60),
+                    amount: money(AssetId::new(1), Cent::from(60)),
                     payer: Some(AccountId::new(1)),
                 },
                 NewPosting {
                     owner: AccountId::new(1),
-                    asset: AssetId::new(1),
-                    value: Cent::from(40),
+                    amount: money(AssetId::new(1), Cent::from(40)),
                     payer: None,
                 },
             ],
@@ -1024,14 +1062,12 @@ mod tests {
             creates: vec![
                 NewPosting {
                     owner: AccountId::new(2),
-                    asset: AssetId::new(1),
-                    value: Cent::from(100),
+                    amount: money(AssetId::new(1), Cent::from(100)),
                     payer: Some(sub),
                 },
                 NewPosting {
                     owner: sub,
-                    asset: AssetId::new(1),
-                    value: Cent::from(-100),
+                    amount: money(AssetId::new(1), Cent::from(-100)),
                     payer: None,
                 },
             ],
@@ -1069,14 +1105,12 @@ mod tests {
             creates: vec![
                 NewPosting {
                     owner: AccountId::new(2),
-                    asset: AssetId::new(1),
-                    value: Cent::from(100),
+                    amount: money(AssetId::new(1), Cent::from(100)),
                     payer: Some(sub),
                 },
                 NewPosting {
                     owner: sub,
-                    asset: AssetId::new(1),
-                    value: Cent::from(-100),
+                    amount: money(AssetId::new(1), Cent::from(-100)),
                     payer: None,
                 },
             ],
@@ -1118,14 +1152,12 @@ mod tests {
             creates: vec![
                 NewPosting {
                     owner: AccountId::new(999),
-                    asset: AssetId::new(1),
-                    value: Cent::from(100),
+                    amount: money(AssetId::new(1), Cent::from(100)),
                     payer: None,
                 },
                 NewPosting {
                     owner: AccountId::new(99),
-                    asset: AssetId::new(1),
-                    value: Cent::from(-100),
+                    amount: money(AssetId::new(1), Cent::from(-100)),
                     payer: None,
                 },
             ],
@@ -1158,14 +1190,12 @@ mod tests {
             creates: vec![
                 NewPosting {
                     owner: AccountId::new(1),
-                    asset: AssetId::new(1),
-                    value: Cent::from(-100),
+                    amount: money(AssetId::new(1), Cent::from(-100)),
                     payer: None,
                 },
                 NewPosting {
                     owner: AccountId::new(1),
-                    asset: AssetId::new(1),
-                    value: Cent::from(100),
+                    amount: money(AssetId::new(1), Cent::from(100)),
                     payer: None,
                 },
             ],
@@ -1256,22 +1286,19 @@ mod tests {
         let posting = Posting {
             id: pid,
             owner: AccountId::new(1),
-            asset: AssetId::new(1),
-            value: Cent::from(100),
+            amount: money(AssetId::new(1), Cent::from(100)),
         };
         let envelope = Envelope {
             consumes: vec![pid],
             creates: vec![
                 NewPosting {
                     owner: AccountId::new(2),
-                    asset: AssetId::new(1),
-                    value: Cent::from(60),
+                    amount: money(AssetId::new(1), Cent::from(60)),
                     payer: Some(AccountId::new(1)),
                 },
                 NewPosting {
                     owner: AccountId::new(1),
-                    asset: AssetId::new(1),
-                    value: Cent::from(40),
+                    amount: money(AssetId::new(1), Cent::from(40)),
                     payer: None,
                 },
             ],
@@ -1314,14 +1341,12 @@ mod tests {
             Posting {
                 id: pid_a,
                 owner: AccountId::new(1),
-                asset: AssetId::new(1),
-                value: Cent::from(100),
+                amount: money(AssetId::new(1), Cent::from(100)),
             },
             Posting {
                 id: pid_b,
                 owner: AccountId::new(1),
-                asset: AssetId::new(2),
-                value: Cent::from(50),
+                amount: money(AssetId::new(2), Cent::from(50)),
             },
         ];
         let envelope = Envelope {
@@ -1329,14 +1354,12 @@ mod tests {
             creates: vec![
                 NewPosting {
                     owner: AccountId::new(2),
-                    asset: AssetId::new(1),
-                    value: Cent::from(100),
+                    amount: money(AssetId::new(1), Cent::from(100)),
                     payer: Some(AccountId::new(1)),
                 },
                 NewPosting {
                     owner: AccountId::new(3),
-                    asset: AssetId::new(2),
-                    value: Cent::from(50),
+                    amount: money(AssetId::new(2), Cent::from(50)),
                     payer: Some(AccountId::new(1)),
                 },
             ],
@@ -1374,14 +1397,12 @@ mod tests {
             creates: vec![
                 NewPosting {
                     owner: AccountId::new(1),
-                    asset: AssetId::new(1),
-                    value: Cent::from(100),
+                    amount: money(AssetId::new(1), Cent::from(100)),
                     payer: None,
                 },
                 NewPosting {
                     owner: AccountId::new(99),
-                    asset: AssetId::new(1),
-                    value: Cent::from(-100),
+                    amount: money(AssetId::new(1), Cent::from(-100)),
                     payer: None,
                 },
             ],

+ 2 - 3
crates/kuatia-dashboard/src/api.rs

@@ -11,10 +11,9 @@ use axum::{
     extract::{Path, Query, State},
     routing::get,
 };
-use kuatia_core::AccountId;
+use kuatia_core::{AccountId, Asset};
 use serde::Deserialize;
 
-use crate::assets::AssetMeta;
 use crate::data::{
     AccountDetailDto, AccountDto, ApiError, AppState, EventDto, OverviewDto, TransferDto,
 };
@@ -31,7 +30,7 @@ pub fn router(state: AppState) -> Router {
         .with_state(state)
 }
 
-async fn assets(State(state): State<AppState>) -> Json<Vec<AssetMeta>> {
+async fn assets(State(state): State<AppState>) -> Json<Vec<Asset>> {
     Json((*state.assets).clone())
 }
 

+ 0 - 43
crates/kuatia-dashboard/src/assets.rs

@@ -1,43 +0,0 @@
-//! Static asset registry for the demo. Kuatia tracks assets only by opaque
-//! [`AssetId`]; symbols and decimal precision live in the application, so the
-//! dashboard defines them here and exposes them over the API for formatting.
-
-use kuatia_core::AssetId;
-use serde::Serialize;
-
-pub const USD: AssetId = AssetId::new(1);
-pub const EUR: AssetId = AssetId::new(2);
-pub const BTC: AssetId = AssetId::new(3);
-
-/// Presentation metadata for one asset.
-#[derive(Debug, Clone, Serialize)]
-pub struct AssetMeta {
-    pub id: AssetId,
-    pub code: &'static str,
-    pub symbol: &'static str,
-    pub decimals: u8,
-}
-
-/// All assets known to the demo, in display order.
-pub fn registry() -> Vec<AssetMeta> {
-    vec![
-        AssetMeta {
-            id: USD,
-            code: "USD",
-            symbol: "$",
-            decimals: 2,
-        },
-        AssetMeta {
-            id: EUR,
-            code: "EUR",
-            symbol: "\u{20ac}",
-            decimals: 2,
-        },
-        AssetMeta {
-            id: BTC,
-            code: "BTC",
-            symbol: "\u{20bf}",
-            decimals: 8,
-        },
-    ]
-}

+ 19 - 41
crates/kuatia-dashboard/src/data.rs

@@ -1,7 +1,8 @@
 //! Shared data layer. Reads the ledger and builds the DTOs consumed by both the
 //! JSON API ([`crate::api`]) and the server-rendered HTML views ([`crate::ui`]).
-//! Everything here is read-only. Monetary values stay as raw [`Cent`] (minor
-//! units); presentation formats them.
+//! Everything here is read-only. A monetary value stays an [`Amount`], which
+//! carries the asset it is in, so the presentation layer formats it at that
+//! asset's own scale rather than pairing it with a lookup of its own.
 
 use std::cmp::Reverse;
 use std::fmt;
@@ -14,20 +15,19 @@ use axum::{
 };
 use kuatia::error::LedgerError;
 use kuatia::ledger::Ledger;
-use kuatia_core::{Account, AccountId, AssetId, Cent, PostingId, PostingState};
+use kuatia_core::{Account, AccountId, Amount, Asset, PostingId, PostingState};
 use kuatia_storage::events::{LedgerEvent, LedgerEventKind};
 use kuatia_storage::store::{TransferQuery, TransferRecord};
 use serde::Serialize;
 use tera::Tera;
 
-use crate::assets::AssetMeta;
 use crate::seed::{EXTERNAL, account_label};
 
 /// Shared handler state.
 #[derive(Clone)]
 pub struct AppState {
     pub ledger: Arc<Ledger>,
-    pub assets: Arc<Vec<AssetMeta>>,
+    pub assets: Arc<Vec<Asset>>,
     pub tera: Arc<Tera>,
 }
 
@@ -36,12 +36,6 @@ pub struct AppState {
 // ---------------------------------------------------------------------------
 
 #[derive(Serialize)]
-pub struct BalanceDto {
-    pub asset: AssetId,
-    pub value: Cent,
-}
-
-#[derive(Serialize)]
 pub struct AccountDto {
     pub id: AccountId,
     /// IBAN-style account code (machine format, checksum-valid) for the full id.
@@ -55,15 +49,14 @@ pub struct AccountDto {
     pub debit_must_not_exceed_credit: bool,
     pub frozen: bool,
     pub closed: bool,
-    pub balances: Vec<BalanceDto>,
+    pub balances: Vec<Amount>,
 }
 
 #[derive(Serialize)]
 pub struct PostingDto {
     pub id: String,
     pub owner: AccountId,
-    pub asset: AssetId,
-    pub value: Cent,
+    pub amount: Amount,
     pub status: String,
 }
 
@@ -71,8 +64,7 @@ pub struct PostingDto {
 pub struct TransferLegDto {
     pub owner: AccountId,
     pub label: Option<&'static str>,
-    pub asset: AssetId,
-    pub value: Cent,
+    pub amount: Amount,
     pub payer: Option<AccountId>,
     pub payer_label: Option<&'static str>,
 }
@@ -95,17 +87,11 @@ pub struct EventDto {
 }
 
 #[derive(Serialize)]
-pub struct IssuedDto {
-    pub asset: AssetId,
-    pub issued: Cent,
-}
-
-#[derive(Serialize)]
 pub struct OverviewDto {
     pub accounts: usize,
     pub transfers: u64,
     pub assets: usize,
-    pub issued: Vec<IssuedDto>,
+    pub issued: Vec<Amount>,
 }
 
 #[derive(Serialize)]
@@ -134,13 +120,10 @@ fn posting_id(id: &PostingId) -> String {
 async fn account_dto(state: &AppState, account: &Account) -> Result<AccountDto, ApiError> {
     let mut balances = Vec::new();
     for asset in state.assets.iter() {
-        let value = state.ledger.balance(&account.id, &asset.id).await?;
-        // Emit only non-zero balances; a zero renders as the string "0".
-        if value.to_string() != "0" {
-            balances.push(BalanceDto {
-                asset: asset.id,
-                value,
-            });
+        let balance = state.ledger.balance(&account.id, asset.id).await?;
+        // Emit only the assets this account actually holds.
+        if !balance.is_zero() {
+            balances.push(balance);
         }
     }
     Ok(AccountDto {
@@ -164,8 +147,7 @@ fn transfer_dto(record: &TransferRecord) -> TransferDto {
         .map(|p| TransferLegDto {
             owner: p.owner,
             label: account_label(p.owner),
-            asset: p.asset,
-            value: p.value,
+            amount: p.amount.clone(),
             payer: p.payer,
             payer_label: p.payer.and_then(account_label),
         })
@@ -222,15 +204,12 @@ pub async fn overview(state: &AppState) -> Result<OverviewDto, ApiError> {
     // mirrors everything in circulation.
     let mut issued = Vec::new();
     for asset in state.assets.iter() {
-        let external = state.ledger.balance(&EXTERNAL, &asset.id).await?;
+        let external = state.ledger.balance(&EXTERNAL, asset).await?;
         let issued_value = external
             .checked_neg()
             .map_err(|_| ApiError::internal("overflow"))?;
-        if issued_value.to_string() != "0" {
-            issued.push(IssuedDto {
-                asset: asset.id,
-                issued: issued_value,
-            });
+        if !issued_value.is_zero() {
+            issued.push(issued_value);
         }
     }
 
@@ -275,12 +254,11 @@ pub async fn account_detail(state: &AppState, id: AccountId) -> Result<AccountDe
         .map(|(p, state)| PostingDto {
             id: posting_id(&p.id),
             owner: p.owner,
-            asset: p.asset,
-            value: p.value,
+            amount: p.amount.clone(),
             status: posting_state_label(state).to_string(),
         })
         .collect();
-    postings.sort_by_key(|p| Reverse(p.value));
+    postings.sort_by_key(|p| Reverse(p.amount.minor_units()));
 
     let transfers = state
         .ledger

+ 4 - 2
crates/kuatia-dashboard/src/main.rs

@@ -11,7 +11,6 @@
 //! ```
 
 mod api;
-mod assets;
 mod data;
 mod seed;
 mod ui;
@@ -85,9 +84,12 @@ async fn main() -> Result<(), Box<dyn Error>> {
         }
     }
 
+    // The registry is the authority on what the demo holds, so read it rather
+    // than keeping a second list beside it.
+    let assets = Arc::new(ledger.list_assets().await?);
     let state = AppState {
         ledger,
-        assets: Arc::new(assets::registry()),
+        assets,
         tera: Arc::new(ui::build_tera()?),
     };
 

+ 26 - 26
crates/kuatia-dashboard/src/seed.rs

@@ -6,11 +6,9 @@ use std::error::Error;
 use std::sync::Arc;
 
 use kuatia::ledger::Ledger;
-use kuatia_core::{Account, AccountId, Amount, AssetId, Cent, TransferBuilder};
+use kuatia_core::{Account, AccountId, Asset, TransferBuilder};
 use kuatia_storage_sql::SqlStore;
 
-use crate::assets::{BTC, EUR, USD};
-
 /// Well-known account ids used by the demo.
 pub const TREASURY: AccountId = AccountId::new(1);
 pub const EXTERNAL: AccountId = AccountId::new(99);
@@ -83,9 +81,12 @@ pub async fn seed_if_empty(ledger: &Arc<Ledger>) -> Result<bool, Box<dyn Error>>
 
 /// Populate the ledger with demo accounts and a spread of transfers.
 pub async fn populate(ledger: &Arc<Ledger>) -> Result<(), Box<dyn Error>> {
-    // Two-decimal assets (USD, EUR) and an 8-decimal asset (BTC).
-    let fiat = Amount::new(2);
-    let btc = Amount::new(8);
+    // Register the assets first: an amount cannot be built without its asset,
+    // so nothing below could be expressed otherwise. Naming each by code both
+    // registers it and hands back the handle.
+    let usd = ledger.asset("USD", "$", 2).await?;
+    let eur = ledger.asset("EUR", "\u{20ac}", 2).await?;
+    let btc = ledger.asset("BTC", "\u{20bf}", 8).await?;
 
     // Treasury and the external boundary permit overdraft (they hold the
     // negative side of issuance/deposits); the user accounts forbid it.
@@ -98,29 +99,30 @@ pub async fn populate(ledger: &Arc<Ledger>) -> Result<(), Box<dyn Error>> {
     create(ledger, CAROL, false).await?;
     create(ledger, MERCHANT, true).await?;
 
-    // Fund accounts from the external boundary.
-    deposit(ledger, ALICE, USD, fiat.parse("1000.00")?).await?;
-    deposit(ledger, BOB, EUR, fiat.parse("500.00")?).await?;
-    deposit(ledger, ALICE, BTC, btc.parse("0.50000000")?).await?;
-    deposit(ledger, CAROL, USD, fiat.parse("200.00")?).await?;
+    // Fund accounts from the external boundary. Each string is parsed at its
+    // asset's own scale, so the 8-decimal BTC amount needs no special case.
+    deposit(ledger, ALICE, ("1000.00", &usd)).await?;
+    deposit(ledger, BOB, ("500.00", &eur)).await?;
+    deposit(ledger, ALICE, ("0.50000000", &btc)).await?;
+    deposit(ledger, CAROL, ("200.00", &usd)).await?;
 
     // Ordinary payments between held balances.
-    pay(ledger, ALICE, BOB, USD, fiat.parse("150.00")?).await?;
-    pay(ledger, BOB, MERCHANT, EUR, fiat.parse("80.00")?).await?;
-    pay(ledger, ALICE, MERCHANT, BTC, btc.parse("0.10000000")?).await?;
+    pay(ledger, ALICE, BOB, ("150.00", &usd)).await?;
+    pay(ledger, BOB, MERCHANT, ("80.00", &eur)).await?;
+    pay(ledger, ALICE, MERCHANT, ("0.10000000", &btc)).await?;
 
     // Carol spends past her balance, into overdraft.
-    pay(ledger, CAROL, MERCHANT, USD, fiat.parse("250.00")?).await?;
+    pay(ledger, CAROL, MERCHANT, ("250.00", &usd)).await?;
 
     // Alice earmarks part of her balance into her savings subaccount. The two
     // balances stay segregated under the same base id.
-    pay(ledger, ALICE, ALICE_SAVINGS, USD, fiat.parse("300.00")?).await?;
+    pay(ledger, ALICE, ALICE_SAVINGS, ("300.00", &usd)).await?;
 
     // Atomic multi-asset trade: Alice buys EUR from Bob with USD.
     let trade = TransferBuilder::new()
-        .pay(ALICE, BOB, USD, fiat.parse("100.00")?)
-        .pay(BOB, ALICE, EUR, fiat.parse("90.00")?)
-        .build();
+        .pay(ALICE, BOB, ("100.00", &usd))
+        .pay(BOB, ALICE, ("90.00", &eur))
+        .build()?;
     ledger.commit(trade).await?;
 
     Ok(())
@@ -143,12 +145,11 @@ async fn create(
 async fn deposit(
     ledger: &Arc<Ledger>,
     to: AccountId,
-    asset: AssetId,
-    amount: Cent,
+    amount: (&str, &Arc<Asset>),
 ) -> Result<(), Box<dyn Error>> {
     let transfer = TransferBuilder::new()
-        .deposit(to, asset, amount, EXTERNAL)?
-        .build();
+        .deposit(to, amount, EXTERNAL)
+        .build()?;
     ledger.commit(transfer).await?;
     Ok(())
 }
@@ -157,10 +158,9 @@ async fn pay(
     ledger: &Arc<Ledger>,
     from: AccountId,
     to: AccountId,
-    asset: AssetId,
-    amount: Cent,
+    amount: (&str, &Arc<Asset>),
 ) -> Result<(), Box<dyn Error>> {
-    let transfer = TransferBuilder::new().pay(from, to, asset, amount).build();
+    let transfer = TransferBuilder::new().pay(from, to, amount).build()?;
     ledger.commit(transfer).await?;
     Ok(())
 }

+ 36 - 57
crates/kuatia-dashboard/src/ui.rs

@@ -13,11 +13,10 @@ use axum::{
     response::{Html, IntoResponse, Response},
     routing::get,
 };
-use kuatia_core::{AccountId, Amount, AssetId, Cent};
+use kuatia_core::{AccountId, Amount, Asset};
 use serde::Serialize;
 use tera::{Context, Tera};
 
-use crate::assets::AssetMeta;
 use crate::data::{
     self, AccountDto, ApiError, AppState, EventDto, OverviewDto, PostingDto, TransferDto,
 };
@@ -172,44 +171,34 @@ struct IssuedView {
 // Formatting helpers
 // ---------------------------------------------------------------------------
 
-/// Look up asset metadata by id.
-fn asset_of(assets: &[AssetMeta], id: AssetId) -> Option<&AssetMeta> {
-    assets.iter().find(|a| a.id == id)
-}
-
-/// Format a signed [`Cent`] with the given decimals and symbol, grouping the
-/// integer part with thousands separators.
-fn fmt(value: Cent, decimals: u8, symbol: &str) -> MoneyView {
-    let raw = Amount::new(decimals).format(value); // e.g. "-1234567.89" or "1000"
-    let negative = raw.starts_with('-');
-    let unsigned = raw.trim_start_matches('-');
-    let (whole, frac) = match unsigned.split_once('.') {
-        Some((w, f)) => (w, Some(f)),
-        None => (unsigned, None),
-    };
-    let grouped = group_thousands(whole);
-    let body = match frac {
-        Some(f) => format!("{grouped}.{f}"),
-        None => grouped,
+/// Render an amount at its own asset's scale and symbol, grouping the integer
+/// part with thousands separators.
+///
+/// Works from the minor units and the asset's decimals rather than any money
+/// type: the ledger hands out amounts, and the integer behind one is the only
+/// number a presentation layer needs.
+fn fmt_amount(amount: &Amount) -> MoneyView {
+    let decimals = usize::from(amount.asset().decimals);
+    let units = amount.minor_units();
+    let negative = units < 0;
+
+    // Left-pad so a value smaller than one unit still has an integer digit.
+    let digits = format!("{:0>width$}", units.unsigned_abs(), width = decimals + 1);
+    let split = digits.len() - decimals;
+    let grouped = group_thousands(&digits[..split]);
+    let body = if decimals == 0 {
+        grouped
+    } else {
+        format!("{grouped}.{}", &digits[split..])
     };
+
     let sign = if negative { "-" } else { "" };
     MoneyView {
-        text: format!("{sign}{symbol}{body}"),
+        text: format!("{sign}{}{body}", amount.asset().symbol),
         negative,
     }
 }
 
-/// Format using an asset's decimals/symbol, or fall back to the raw value.
-fn fmt_asset(value: Cent, asset: Option<&AssetMeta>) -> MoneyView {
-    match asset {
-        Some(a) => fmt(value, a.decimals, a.symbol),
-        None => MoneyView {
-            text: value.to_string(),
-            negative: value.to_string().starts_with('-'),
-        },
-    }
-}
-
 /// Insert commas every three digits from the right.
 fn group_thousands(digits: &str) -> String {
     let bytes = digits.as_bytes();
@@ -271,7 +260,7 @@ fn acct_link(id: AccountId) -> String {
     format!("/accounts/{id}")
 }
 
-fn account_view(dto: &AccountDto, assets: &[AssetMeta]) -> AccountView {
+fn account_view(dto: &AccountDto) -> AccountView {
     let display_id = acct_display(dto.id);
     let link = acct_link(dto.id);
     AccountView {
@@ -296,16 +285,14 @@ fn account_view(dto: &AccountDto, assets: &[AssetMeta]) -> AccountView {
             .balances
             .iter()
             .map(|b| BalanceView {
-                code: asset_of(assets, b.asset)
-                    .map(|a| a.code.to_string())
-                    .unwrap_or_default(),
-                money: fmt_asset(b.value, asset_of(assets, b.asset)),
+                code: b.asset().code.clone(),
+                money: fmt_amount(b),
             })
             .collect(),
     }
 }
 
-fn transfer_view(dto: &TransferDto, assets: &[AssetMeta]) -> TransferView {
+fn transfer_view(dto: &TransferDto, _assets: &[Asset]) -> TransferView {
     TransferView {
         short_id: short_hex(&dto.id),
         full_id: dto.id.clone(),
@@ -325,17 +312,17 @@ fn transfer_view(dto: &TransferDto, assets: &[AssetMeta]) -> TransferView {
                         .unwrap_or_else(|| acct_display(p))
                 }),
                 is_change: leg.payer.is_none(),
-                money: fmt_asset(leg.value, asset_of(assets, leg.asset)),
+                money: fmt_amount(&leg.amount),
             })
             .collect(),
     }
 }
 
-fn posting_view(dto: &PostingDto, assets: &[AssetMeta]) -> PostingView {
+fn posting_view(dto: &PostingDto, _assets: &[Asset]) -> PostingView {
     PostingView {
         short_id: short_hex(&dto.id),
         status: dto.status.clone(),
-        money: fmt_asset(dto.value, asset_of(assets, dto.asset)),
+        money: fmt_amount(&dto.amount),
     }
 }
 
@@ -349,14 +336,12 @@ fn event_view(dto: &EventDto) -> EventView {
     }
 }
 
-fn issued_view(dto: &OverviewDto, assets: &[AssetMeta]) -> Vec<IssuedView> {
+fn issued_view(dto: &OverviewDto) -> Vec<IssuedView> {
     dto.issued
         .iter()
         .map(|i| IssuedView {
-            code: asset_of(assets, i.asset)
-                .map(|a| a.code.to_string())
-                .unwrap_or_default(),
-            money: fmt_asset(i.issued, asset_of(assets, i.asset)),
+            code: i.asset().code.clone(),
+            money: fmt_amount(i),
         })
         .collect()
 }
@@ -372,16 +357,13 @@ async fn overview_ctx(state: &AppState) -> Result<Context, ApiError> {
     ctx.insert("accounts_count", &dto.accounts);
     ctx.insert("transfers_count", &dto.transfers);
     ctx.insert("assets_count", &dto.assets);
-    ctx.insert("issued", &issued_view(&dto, &state.assets));
+    ctx.insert("issued", &issued_view(&dto));
     Ok(ctx)
 }
 
 async fn accounts_ctx(state: &AppState) -> Result<Context, ApiError> {
     let dtos = data::accounts(state).await?;
-    let views: Vec<AccountView> = dtos
-        .iter()
-        .map(|a| account_view(a, &state.assets))
-        .collect();
+    let views: Vec<AccountView> = dtos.iter().map(account_view).collect();
     let mut ctx = Context::new();
     ctx.insert("nav", "accounts");
     ctx.insert("accounts", &views);
@@ -392,13 +374,10 @@ async fn account_ctx(state: &AppState, id: AccountId) -> Result<Context, ApiErro
     let dto = data::account_detail(state, id).await?;
     let mut ctx = Context::new();
     ctx.insert("nav", "accounts");
-    ctx.insert("account", &account_view(&dto.account, &state.assets));
+    ctx.insert("account", &account_view(&dto.account));
     ctx.insert(
         "subaccounts",
-        &dto.subaccounts
-            .iter()
-            .map(|a| account_view(a, &state.assets))
-            .collect::<Vec<_>>(),
+        &dto.subaccounts.iter().map(account_view).collect::<Vec<_>>(),
     );
     ctx.insert(
         "postings",

+ 72 - 23
crates/kuatia-money/src/lib.rs

@@ -240,6 +240,13 @@ impl Cent {
         Ok(sum)
     }
 
+    /// The value as a plain integer in minor units. The widest backing is 128
+    /// bits, so this is lossless whichever one is compiled in, and it is how a
+    /// caller that may not name [`Cent`] still reads the number.
+    pub fn minor_units(self) -> i128 {
+        self.0.to_i128()
+    }
+
     /// The canonical 16-byte big-endian encoding (sign-extended), used for
     /// content-addressed hashing. The width is fixed regardless of the backing,
     /// so the same amount hashes identically under any backing.
@@ -311,6 +318,17 @@ impl From<i8> for Cent {
     }
 }
 
+/// Fallible because the default `i64` backing holds only part of the `i128`
+/// range, and a value that does not fit is a different amount rather than a
+/// roundable one.
+impl TryFrom<i128> for Cent {
+    type Error = OverflowError;
+
+    fn try_from(v: i128) -> Result<Self, Self::Error> {
+        Backing::try_from_i128(v).map(Cent).ok_or(OverflowError)
+    }
+}
+
 impl fmt::Debug for Cent {
     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         write!(f, "Cent({})", self.0)
@@ -351,19 +369,20 @@ impl<'de> Deserialize<'de> for Cent {
 }
 
 // ---------------------------------------------------------------------------
-// Amount — human-friendly parser/formatter (not stored)
+// Scale: human-friendly parser/formatter (not stored)
 // ---------------------------------------------------------------------------
 
-/// Parses and formats human-readable amounts with a fixed number of decimal
-/// places. NOT stored anywhere — used only to convert between strings and
-/// [`Cent`] values.
-pub struct Amount {
+/// A fixed number of decimal places, for converting between a decimal string a
+/// person would write and the [`Cent`] the ledger stores. Never persisted:
+/// scale is a presentation concern and lives neither on the value nor on the
+/// asset (ADR-0009).
+pub struct Scale {
     decimals: u8,
 }
 
 /// Error returned when parsing an amount string fails.
 #[derive(Debug, Clone, PartialEq, Eq)]
-pub enum ParseAmountError {
+pub enum ParseDecimalError {
     /// The input string is not a valid number.
     InvalidFormat(String),
     /// Too many decimal places for the configured precision.
@@ -375,7 +394,7 @@ pub enum ParseAmountError {
     },
 }
 
-impl fmt::Display for ParseAmountError {
+impl fmt::Display for ParseDecimalError {
     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         match self {
             Self::InvalidFormat(s) => write!(f, "invalid amount format: {s}"),
@@ -386,22 +405,28 @@ impl fmt::Display for ParseAmountError {
     }
 }
 
-impl Error for ParseAmountError {}
+impl Error for ParseDecimalError {}
 
-impl Amount {
-    /// Create an `Amount` formatter with the given number of decimal places.
+impl Scale {
+    /// Create a scale with the given number of decimal places.
     pub fn new(decimals: u8) -> Self {
         Self { decimals }
     }
 
     /// Parses a decimal string into a [`Cent`] value.
-    pub fn parse(&self, s: &str) -> Result<Cent, ParseAmountError> {
+    pub fn parse(&self, s: &str) -> Result<Cent, ParseDecimalError> {
         let s = s.trim();
         let (negative, s) = if let Some(rest) = s.strip_prefix('-') {
             (true, rest)
         } else {
-            (false, s)
+            (false, s.strip_prefix('+').unwrap_or(s))
         };
+        // One sign only. The integer parser below accepts a sign of its own, so
+        // without this `--5` would strip one, parse `-5`, then negate it back to
+        // a positive five: a malformed amount entering as a real one.
+        if !s.starts_with(|c: char| c.is_ascii_digit() || c == '.') {
+            return Err(ParseDecimalError::InvalidFormat(s.to_string()));
+        }
 
         let (whole_str, frac_str) = if let Some((w, f)) = s.split_once('.') {
             (w, f)
@@ -410,25 +435,25 @@ impl Amount {
         };
 
         if whole_str.is_empty() && frac_str.is_empty() {
-            return Err(ParseAmountError::InvalidFormat(s.to_string()));
+            return Err(ParseDecimalError::InvalidFormat(s.to_string()));
         }
 
         let whole: Backing = if whole_str.is_empty() {
             Backing::ZERO
         } else {
             Backing::parse_str(whole_str)
-                .ok_or_else(|| ParseAmountError::InvalidFormat(s.to_string()))?
+                .ok_or_else(|| ParseDecimalError::InvalidFormat(s.to_string()))?
         };
 
         if frac_str.len() > self.decimals as usize {
-            return Err(ParseAmountError::TooManyDecimals {
+            return Err(ParseDecimalError::TooManyDecimals {
                 max: self.decimals,
                 found: frac_str.len(),
             });
         }
 
         if !frac_str.is_empty() && !frac_str.chars().all(|c| c.is_ascii_digit()) {
-            return Err(ParseAmountError::InvalidFormat(s.to_string()));
+            return Err(ParseDecimalError::InvalidFormat(s.to_string()));
         }
 
         let frac: Backing = if frac_str.is_empty() {
@@ -436,20 +461,20 @@ impl Amount {
         } else {
             let padded = format!("{:0<width$}", frac_str, width = self.decimals as usize);
             Backing::parse_str(&padded)
-                .ok_or_else(|| ParseAmountError::InvalidFormat(s.to_string()))?
+                .ok_or_else(|| ParseDecimalError::InvalidFormat(s.to_string()))?
         };
 
         let multiplier = Backing::ten_pow(self.decimals as u32)
-            .ok_or_else(|| ParseAmountError::InvalidFormat(s.to_string()))?;
+            .ok_or_else(|| ParseDecimalError::InvalidFormat(s.to_string()))?;
         let value = whole
             .checked_mul(multiplier)
             .and_then(|v| v.checked_add(frac))
-            .ok_or_else(|| ParseAmountError::InvalidFormat(s.to_string()))?;
+            .ok_or_else(|| ParseDecimalError::InvalidFormat(s.to_string()))?;
 
         let value = if negative {
             value
                 .checked_neg()
-                .ok_or_else(|| ParseAmountError::InvalidFormat(s.to_string()))?
+                .ok_or_else(|| ParseDecimalError::InvalidFormat(s.to_string()))?
         } else {
             value
         };
@@ -491,6 +516,15 @@ mod tests {
     }
 
     #[test]
+    fn try_from_i128_is_range_checked() {
+        assert_eq!(Cent::try_from(650i128), Ok(Cent::from(650)));
+        assert_eq!(Cent::try_from(-650i128), Ok(Cent::from(-650)));
+        if let Some(beyond) = Backing::MAX.to_i128().checked_add(1) {
+            assert_eq!(Cent::try_from(beyond), Err(OverflowError));
+        }
+    }
+
+    #[test]
     fn string_round_trip() {
         for v in [-1234i64, 0, 1, 500, i64::from(i32::MAX)] {
             let c = Cent::from(v);
@@ -534,14 +568,29 @@ mod tests {
         }
     }
 
+    /// A second sign is a malformed amount, not a double negative. Before this
+    /// was checked, `--5` parsed as a positive five.
+    #[test]
+    fn a_second_sign_is_refused() {
+        let scale = Scale::new(2);
+        for input in ["--5", "-+5", "--5.00", "+-5", "- 5"] {
+            assert!(
+                scale.parse(input).is_err(),
+                "{input:?} should not parse as an amount"
+            );
+        }
+        assert_eq!(scale.parse("-5"), Ok(Cent::from(-500)));
+        assert_eq!(scale.parse("+5"), Ok(Cent::from(500)));
+    }
+
     #[test]
-    fn amount_parse_format_round_trip() {
-        let amt = Amount::new(2);
+    fn scale_parse_format_round_trip() {
+        let amt = Scale::new(2);
         assert_eq!(amt.parse("12.34").unwrap(), Cent::from(1234));
         assert_eq!(amt.parse("-0.05").unwrap(), Cent::from(-5));
         assert_eq!(amt.format(Cent::from(1234)), "12.34");
         assert_eq!(amt.format(Cent::from(-5)), "-0.05");
-        assert_eq!(Amount::new(0).format(Cent::from(700)), "700");
+        assert_eq!(Scale::new(0).format(Cent::from(700)), "700");
     }
 
     #[test]

+ 97 - 0
crates/kuatia-storage-sql/src/asset.rs

@@ -0,0 +1,97 @@
+//! [`AssetStore`]: the asset registry, stored as JSON `TEXT` (ADR-0028).
+
+use async_trait::async_trait;
+use sqlx::Row;
+
+use kuatia_storage::error::StoreError;
+use kuatia_storage::store::*;
+use kuatia_types::*;
+
+use crate::SqlStore;
+use crate::row::{deserialize_json, serialize_json};
+
+#[async_trait]
+impl AssetStore for SqlStore {
+    async fn create_asset(&self, asset: Asset) -> Result<u64, StoreError> {
+        // Pessimistic locking, same shape as create_book: lock any existing row
+        // with `SELECT ... FOR UPDATE` inside the transaction, then insert with
+        // `ON CONFLICT DO NOTHING` as the portable backstop.
+        let lock = self.dialect.lock_clause();
+        let data = serialize_json(&asset)?;
+        let mut tx = self
+            .pool
+            .begin()
+            .await
+            .map_err(|e| StoreError::Internal(e.to_string()))?;
+
+        let existing = sqlx::query(&format!("SELECT 1 FROM assets WHERE id = $1 LIMIT 1{lock}"))
+            .bind(asset.id.0 as i32)
+            .fetch_optional(&mut *tx)
+            .await
+            .map_err(|e| StoreError::Internal(e.to_string()))?;
+        if existing.is_some() {
+            return Ok(0);
+        }
+
+        let res = sqlx::query(
+            "INSERT INTO assets (id, code, data) VALUES ($1, $2, $3) ON CONFLICT (id) DO NOTHING",
+        )
+        .bind(asset.id.0 as i32)
+        .bind(&asset.code)
+        .bind(&data)
+        .execute(&mut *tx)
+        .await
+        .map_err(|e| StoreError::Internal(e.to_string()))?;
+        if res.rows_affected() == 0 {
+            return Ok(0);
+        }
+
+        tx.commit()
+            .await
+            .map_err(|e| StoreError::Internal(e.to_string()))?;
+        Ok(1)
+    }
+
+    async fn get_asset(&self, id: &AssetId) -> Result<Asset, StoreError> {
+        let row = sqlx::query("SELECT data FROM assets WHERE id = $1")
+            .bind(id.0 as i32)
+            .fetch_optional(&self.pool)
+            .await
+            .map_err(|e| StoreError::Internal(e.to_string()))?
+            .ok_or_else(|| StoreError::NotFound(format!("asset {id:?}")))?;
+        let data: String = row
+            .try_get("data")
+            .map_err(|e| StoreError::Internal(e.to_string()))?;
+        deserialize_json(&data)
+    }
+
+    async fn get_asset_by_code(&self, code: &str) -> Result<Option<Asset>, StoreError> {
+        let row = sqlx::query("SELECT data FROM assets WHERE code = $1")
+            .bind(code)
+            .fetch_optional(&self.pool)
+            .await
+            .map_err(|e| StoreError::Internal(e.to_string()))?;
+        let Some(row) = row else {
+            return Ok(None);
+        };
+        let data: String = row
+            .try_get("data")
+            .map_err(|e| StoreError::Internal(e.to_string()))?;
+        Ok(Some(deserialize_json(&data)?))
+    }
+
+    async fn list_assets(&self) -> Result<Vec<Asset>, StoreError> {
+        let rows = sqlx::query("SELECT data FROM assets")
+            .fetch_all(&self.pool)
+            .await
+            .map_err(|e| StoreError::Internal(e.to_string()))?;
+        rows.iter()
+            .map(|row| {
+                let data: String = row
+                    .try_get("data")
+                    .map_err(|e| StoreError::Internal(e.to_string()))?;
+                deserialize_json(&data)
+            })
+            .collect()
+    }
+}

+ 7 - 5
crates/kuatia-storage-sql/src/commit.rs

@@ -19,6 +19,8 @@ use kuatia_storage::store::{
     CommitOutcome, CommitRejection, CommitRequest, CommitStore, TransitionOutcome,
     TransitionRejection,
 };
+use kuatia_types::internals;
+use kuatia_types::internals::Cent;
 use kuatia_types::*;
 
 use crate::SqlStore;
@@ -233,8 +235,8 @@ impl CommitStore for SqlStore {
                 .bind(p.id.index as i16)
                 .bind(p.owner.id)
                 .bind(p.owner.sub)
-                .bind(p.asset.0 as i32);
-            bind_money(q, self.dialect, p.value)
+                .bind(p.asset().0 as i32);
+            bind_money(q, self.dialect, internals::cent(&p.amount))
                 .execute(&mut *tx)
                 .await
                 .map_err(internal)?;
@@ -247,12 +249,12 @@ impl CommitStore for SqlStore {
                 .bind(p.id.index as i16)
                 .bind(p.owner.id)
                 .bind(p.owner.sub)
-                .bind(p.asset.0 as i32);
-            bind_money(q, self.dialect, p.value)
+                .bind(p.asset().0 as i32);
+            bind_money(q, self.dialect, internals::cent(&p.amount))
                 .execute(&mut *tx)
                 .await
                 .map_err(internal)?;
-            touched.insert((p.owner, p.asset));
+            touched.insert((p.owner, p.asset()));
         }
 
         // Overdraft floor: with consumed rows deleted and created rows inserted,

+ 4 - 1
crates/kuatia-storage-sql/src/dialect.rs

@@ -72,9 +72,12 @@ impl Dialect {
     /// Spelled out rather than `*` because the amount column needs
     /// [`money_read`](Self::money_read); the six columns are shared by
     /// `postings` and `live_postings`.
+    /// The explicit column list for a posting read, including the asset
+    /// definition joined from the registry: a posting carries an amount, and an
+    /// amount carries its asset. Pair it with [`joined`](crate::posting::joined).
     pub(crate) fn posting_columns(self) -> String {
         format!(
-            "transfer_id, idx, owner, subaccount, asset, {}",
+            "transfer_id, idx, owner, subaccount, asset, assets.data AS asset_def, {}",
             self.money_read("value")
         )
     }

+ 1 - 0
crates/kuatia-storage-sql/src/lib.rs

@@ -28,6 +28,7 @@ use kuatia_types::autoid::AutoId;
 use crate::dialect::Dialect;
 
 mod account;
+mod asset;
 mod book;
 mod commit;
 mod dialect;

+ 8 - 0
crates/kuatia-storage-sql/src/migrate.rs

@@ -117,6 +117,14 @@ impl SqlStore {
                 "013_value_date",
                 Migration::Shared(include_str!("migrations/013_value_date.sql")),
             ),
+            (
+                "014_assets",
+                Migration::Shared(include_str!("migrations/014_assets.sql")),
+            ),
+            (
+                "015_asset_code_unique",
+                Migration::Shared(include_str!("migrations/015_asset_code_unique.sql")),
+            ),
         ];
 
         for (name, migration) in migrations {

+ 18 - 0
crates/kuatia-storage-sql/src/migrations/014_assets.sql

@@ -0,0 +1,18 @@
+-- The asset registry (ADR-0028). Until now an AssetId was opaque, so 100 of
+-- asset 1 could be a dollar or a hundred of them depending on who read it, and
+-- the precision lived in whatever application happened to be formatting.
+--
+-- The id is an INTEGER because an AssetId is a u32, matching the asset columns
+-- on postings, live_postings and balance_projection. It is supplied by the
+-- caller and never assigned here. The row rides in data as JSON, like books, so
+-- a new field needs no migration, and code is duplicated out of it to stay
+-- readable in a query.
+--
+-- No semicolon belongs in these comments: the migration runner splits the file
+-- on them, so one here would be read as the start of a statement.
+
+CREATE TABLE IF NOT EXISTS assets (
+    id   INTEGER PRIMARY KEY,
+    code TEXT NOT NULL,
+    data TEXT NOT NULL
+);

+ 8 - 0
crates/kuatia-storage-sql/src/migrations/015_asset_code_unique.sql

@@ -0,0 +1,8 @@
+-- A code is how a caller names an asset (ADR-0030), so two rows may not share
+-- one. Without this, a get-or-create keyed on the code could register a second
+-- EUR under a different id and split every balance in it.
+--
+-- No semicolon belongs in these comments: the migration runner splits the file
+-- on them, so one here would be read as the start of a statement.
+
+CREATE UNIQUE INDEX IF NOT EXISTS idx_assets_code ON assets(code);

+ 34 - 7
crates/kuatia-storage-sql/src/posting.rs

@@ -12,8 +12,11 @@ use async_trait::async_trait;
 use sqlx::Row;
 use sqlx::any::AnyRow;
 
+use std::sync::Arc;
+
 use kuatia_storage::error::StoreError;
 use kuatia_storage::store::*;
+use kuatia_types::internals;
 use kuatia_types::*;
 
 use crate::SqlStore;
@@ -41,6 +44,18 @@ fn filter_source(filter: PostingFilter) -> &'static str {
     }
 }
 
+/// A posting table joined to the asset registry, because a posting carries an
+/// amount and an amount carries its asset.
+///
+/// Left-joined deliberately. An inner join would silently drop a posting whose
+/// asset is missing from the registry, which is the one outcome worse than an
+/// error; this way the decode fails loudly and says what is wrong. Writing such
+/// a posting is already refused a layer up, where a commit resolves every asset
+/// it names.
+pub(crate) fn joined(table: &str) -> String {
+    format!("{table} LEFT JOIN assets ON assets.id = {table}.asset")
+}
+
 /// Maximum posting ids matched by a single statement. `id_predicate` expands to
 /// an `OR` of `n` equality pairs, so the binding constraint is SQLite's
 /// expression-tree depth limit (`SQLITE_MAX_EXPR_DEPTH`, default 1000), which a
@@ -82,8 +97,9 @@ impl PostingStore for SqlStore {
         let mut found: HashMap<(String, i16), Posting> = HashMap::with_capacity(ids.len());
         for chunk in ids.chunks(MAX_IDS_PER_QUERY) {
             let sql = format!(
-                "SELECT {} FROM postings WHERE {}",
+                "SELECT {} FROM {} WHERE {}",
                 self.dialect.posting_columns(),
+                joined("postings"),
                 id_predicate(chunk.len(), 1)
             );
             let mut q = sqlx::query(&sql);
@@ -133,8 +149,9 @@ impl PostingStore for SqlStore {
         // for equality, never as a magnitude.
         let source = filter_source(filter);
         let mut sql = format!(
-            "SELECT {} FROM {source} WHERE owner = $1",
-            self.dialect.posting_columns()
+            "SELECT {} FROM {} WHERE owner = $1",
+            self.dialect.posting_columns(),
+            joined(source)
         );
         let mut placeholder = 2u32;
         if sub.is_some() {
@@ -166,7 +183,11 @@ impl PostingStore for SqlStore {
             .collect()
     }
 
-    async fn live_balance(&self, account: &AccountId, asset: &AssetId) -> Result<Cent, StoreError> {
+    async fn live_balance(
+        &self,
+        account: &AccountId,
+        asset: &AssetId,
+    ) -> Result<Amount, StoreError> {
         let row = sqlx::query(&live_balance_sql(self.dialect))
             .bind(account.id)
             .bind(account.sub)
@@ -174,7 +195,12 @@ impl PostingStore for SqlStore {
             .fetch_one(&self.pool)
             .await
             .map_err(|e| StoreError::Internal(e.to_string()))?;
-        row_to_cent(self.dialect, &row, "total")
+        let total = row_to_cent(self.dialect, &row, "total")?;
+        // Read separately rather than joined: the aggregate collapses the rows,
+        // so there is no asset column left to project, and a zero balance has no
+        // row to take one from. The registry is a primary-key read.
+        let definition = self.get_asset(asset).await?;
+        Ok(internals::amount(Arc::new(definition), total))
     }
 
     async fn get_posting_states(&self, ids: &[PostingId]) -> Result<Vec<PostingState>, StoreError> {
@@ -277,8 +303,9 @@ impl PostingStore for SqlStore {
             ));
             (
                 format!(
-                    "SELECT {} FROM {source} {w}",
-                    self.dialect.posting_columns()
+                    "SELECT {} FROM {} {w}",
+                    self.dialect.posting_columns(),
+                    joined(source)
                 ),
                 c,
             )

+ 17 - 8
crates/kuatia-storage-sql/src/projection.rs

@@ -7,18 +7,21 @@ use kuatia_storage::error::StoreError;
 use kuatia_storage::store::*;
 use kuatia_types::*;
 
+use kuatia_types::internals;
+
 use crate::SqlStore;
-use crate::row::{bind_money, row_to_cent};
+use crate::row::{bind_money, row_to_asset, row_to_cent};
 
 #[async_trait]
 impl BalanceProjectionStore for SqlStore {
     async fn append_balance_projection(
         &self,
         account: &AccountId,
-        asset: &AssetId,
-        balance: Cent,
+        balance: Amount,
         watermark: i64,
     ) -> Result<(), StoreError> {
+        let asset = balance.asset_id();
+        let value = internals::cent(&balance);
         // Append-only: mint a fresh monotonic id and insert a new cache point.
         let id = self.autoid.next();
         let sql = format!(
@@ -31,7 +34,7 @@ impl BalanceProjectionStore for SqlStore {
             .bind(account.id)
             .bind(account.sub)
             .bind(asset.0 as i32);
-        bind_money(q, self.dialect, balance)
+        bind_money(q, self.dialect, value)
             .bind(watermark)
             .execute(&self.pool)
             .await
@@ -47,10 +50,14 @@ impl BalanceProjectionStore for SqlStore {
     ) -> Result<Option<BalanceProjection>, StoreError> {
         // Closest at or before `as_of`: the largest watermark not exceeding it,
         // tie-broken by highest id. Row selection, not an aggregate over values.
+        // Joined to the registry for the same reason a posting read is: the
+        // cache point holds an amount, and an amount holds its asset.
         let row = sqlx::query(&format!(
-            "SELECT id, {}, watermark FROM balance_projection \
+            "SELECT balance_projection.id, assets.data AS asset_def, {}, watermark \
+             FROM balance_projection \
+             LEFT JOIN assets ON assets.id = balance_projection.asset \
              WHERE account = $1 AND subaccount = $2 AND asset = $3 AND watermark <= $4 \
-             ORDER BY watermark DESC, id DESC LIMIT 1",
+             ORDER BY watermark DESC, balance_projection.id DESC LIMIT 1",
             self.dialect.money_read("balance")
         ))
         .bind(account.id)
@@ -66,14 +73,16 @@ impl BalanceProjectionStore for SqlStore {
         let id: i64 = row
             .try_get("id")
             .map_err(|e| StoreError::Internal(e.to_string()))?;
-        let balance = row_to_cent(self.dialect, &row, "balance")?;
+        let balance = internals::amount(
+            row_to_asset(&row)?,
+            row_to_cent(self.dialect, &row, "balance")?,
+        );
         let watermark: i64 = row
             .try_get("watermark")
             .map_err(|e| StoreError::Internal(e.to_string()))?;
         Ok(Some(BalanceProjection {
             id,
             account: *account,
-            asset: *asset,
             balance,
             watermark,
         }))

+ 19 - 6
crates/kuatia-storage-sql/src/row.rs

@@ -8,6 +8,10 @@
 //! depends on the backend, and every amount crosses this module through
 //! [`bind_money`] and [`row_to_cent`] rather than through `Display`/`FromStr`.
 
+use std::sync::Arc;
+
+use kuatia_types::internals;
+use kuatia_types::internals::Cent;
 use std::str::FromStr;
 
 use sqlx::Row;
@@ -141,6 +145,19 @@ pub(crate) fn row_to_account(row: &AnyRow) -> Result<Account, StoreError> {
     })
 }
 
+/// Decode the asset definition a posting read joins in. The registry row is
+/// the same JSON `AssetStore` writes, so a posting comes back whole without a
+/// second query and without a lookup that could fail.
+pub(crate) fn row_to_asset(row: &AnyRow) -> Result<Arc<Asset>, StoreError> {
+    let data: Option<String> = row
+        .try_get("asset_def")
+        .map_err(|e| StoreError::Internal(e.to_string()))?;
+    let data = data.ok_or_else(|| {
+        StoreError::Internal("stored amount names an asset that is not in the registry".to_string())
+    })?;
+    Ok(Arc::new(deserialize_json(&data)?))
+}
+
 pub(crate) fn row_to_posting(dialect: Dialect, row: &AnyRow) -> Result<Posting, StoreError> {
     let transfer_id: String = row
         .try_get("transfer_id")
@@ -154,10 +171,7 @@ pub(crate) fn row_to_posting(dialect: Dialect, row: &AnyRow) -> Result<Posting,
     let subaccount: i64 = row
         .try_get("subaccount")
         .map_err(|e| StoreError::Internal(e.to_string()))?;
-    let asset: i32 = row
-        .try_get("asset")
-        .map_err(|e| StoreError::Internal(e.to_string()))?;
-    let value = row_to_cent(dialect, row, "value")?;
+    let amount = internals::amount(row_to_asset(row)?, row_to_cent(dialect, row, "value")?);
 
     Ok(Posting {
         id: PostingId {
@@ -165,7 +179,6 @@ pub(crate) fn row_to_posting(dialect: Dialect, row: &AnyRow) -> Result<Posting,
             index: idx as u16,
         },
         owner: AccountId::with_sub(owner, subaccount),
-        asset: AssetId::new(asset as u32),
-        value,
+        amount,
     })
 }

+ 1 - 1
crates/kuatia-storage-sql/src/sqlite_ext.rs

@@ -21,7 +21,7 @@ use std::sync::atomic::{AtomicI32, Ordering};
 use libsqlite3_sys as ffi;
 
 use kuatia_storage::error::StoreError;
-use kuatia_types::{decode_storage_i128, encode_storage_i128};
+use kuatia_types::internals::{decode_storage_i128, encode_storage_i128};
 
 /// Width of a stored amount, in bytes.
 const WIDTH: usize = 16;

+ 17 - 5
crates/kuatia-storage-sql/tests/postgres.rs

@@ -25,6 +25,18 @@ use sqlx::{Any, Pool, Row};
 
 static SCHEMA_SEQ: AtomicU64 = AtomicU64::new(0);
 
+/// An amount of `asset` in minor units. These tests assert on ids and values,
+/// and an amount compares by asset id, so the metadata here is filler.
+fn money<V>(asset: AssetId, value: V) -> Amount
+where
+    Amount: From<(V, std::sync::Arc<Asset>)>,
+{
+    Amount::from((
+        value,
+        std::sync::Arc::new(Asset::new(asset, "TEST", "$", 2)),
+    ))
+}
+
 async fn new_store() -> SqlStore {
     new_store_with_pool().await.0
 }
@@ -74,19 +86,19 @@ async fn amount_columns_are_numeric() {
             index: 0,
         },
         AccountId::new(1),
-        AssetId::new(1),
-        Cent::from(-4321),
+        money(AssetId::new(1), -4321),
     );
     seed_live(&store, 0x3f, std::slice::from_ref(&posting)).await;
 
     let got = store.get_postings(&[posting.id]).await.unwrap();
-    assert_eq!(got[0].value, Cent::from(-4321));
+    assert_eq!(got[0].amount.minor_units(), -4321);
     assert_eq!(
         store
             .live_balance(&AccountId::new(1), &AssetId::new(1))
             .await
-            .unwrap(),
-        Cent::from(-4321)
+            .unwrap()
+            .minor_units(),
+        -4321
     );
 
     for (table, column) in [

+ 24 - 15
crates/kuatia-storage-sql/tests/sqlite.rs

@@ -8,9 +8,22 @@ use kuatia_storage::store::{
 };
 use kuatia_storage::store_tests::{seed_live, spend_live};
 use kuatia_storage_sql::SqlStore;
+use kuatia_types::internals::{decode_storage_i128, encode_storage_i128};
 use kuatia_types::*;
 use sqlx::{Any, Pool, Row};
 
+/// An amount of `asset` in minor units. These tests assert on ids and values,
+/// and an amount compares by asset id, so the metadata here is filler.
+fn money<V>(asset: AssetId, value: V) -> Amount
+where
+    Amount: From<(V, std::sync::Arc<Asset>)>,
+{
+    Amount::from((
+        value,
+        std::sync::Arc::new(Asset::new(asset, "TEST", "$", 2)),
+    ))
+}
+
 async fn new_pool() -> Pool<Any> {
     kuatia_storage_sql::install_drivers().expect("install sqlite money functions");
     sqlx::any::AnyPoolOptions::new()
@@ -56,8 +69,7 @@ async fn columns_store_hex_ids_and_json_text() {
             index: 0,
         },
         AccountId::new(1),
-        AssetId::new(1),
-        Cent::from(100),
+        money(AssetId::new(1), 100),
     );
     seed_live(&store, 0xab, &[posting]).await;
 
@@ -116,8 +128,7 @@ async fn subaccount_columns_round_trip() {
             index: 0,
         },
         sub,
-        AssetId::new(1),
-        Cent::from(500),
+        money(AssetId::new(1), 500),
     );
     seed_live(&store, 0xcd, &[posting]).await;
 
@@ -520,8 +531,7 @@ async fn id_batches_chunk_across_reads_and_commit() {
                     index: i,
                 },
                 AccountId::new(1),
-                AssetId::new(1),
-                Cent::from(1),
+                money(AssetId::new(1), 1),
             )
         })
         .collect();
@@ -682,6 +692,7 @@ async fn blob_order_matches_numeric_order() {
 #[cfg(feature = "i128")]
 #[tokio::test]
 async fn value_beyond_i64_round_trips() {
+    use kuatia_types::internals::Cent;
     use std::str::FromStr;
 
     let store = new_store().await;
@@ -692,19 +703,19 @@ async fn value_beyond_i64_round_trips() {
             index: 0,
         },
         AccountId::new(1),
-        AssetId::new(1),
-        value,
+        money(AssetId::new(1), value),
     );
     seed_live(&store, 0x5c, std::slice::from_ref(&posting)).await;
 
     let got = store.get_postings(&[posting.id]).await.unwrap();
-    assert_eq!(got[0].value, value);
+    assert_eq!(got[0].amount.minor_units(), value.minor_units());
     assert_eq!(
         store
             .live_balance(&AccountId::new(1), &AssetId::new(1))
             .await
-            .unwrap(),
-        value
+            .unwrap()
+            .minor_units(),
+        value.minor_units()
     );
 }
 
@@ -781,8 +792,7 @@ async fn value_date_window_filters_in_sql() {
         let value_date = day.map(|d| ValueDate::new(2026, 11, d).unwrap());
         let mut builder = EnvelopeBuilder::new().creates(vec![NewPosting {
             owner: AccountId::new(1),
-            asset: AssetId::new(1),
-            value: Cent::from(10),
+            amount: money(AssetId::new(1), 10),
             payer: None,
         }]);
         if let Some(date) = value_date {
@@ -795,8 +805,7 @@ async fn value_date_window_filters_in_sql() {
                 index: 0,
             },
             AccountId::new(1),
-            AssetId::new(1),
-            Cent::from(10),
+            money(AssetId::new(1), 10),
         )];
         let involved = [AccountId::new(1)];
         let outcome = store

+ 67 - 24
crates/kuatia-storage/src/mem_store.rs

@@ -4,11 +4,14 @@
 
 use async_trait::async_trait;
 use std::collections::{HashMap, HashSet};
+use std::sync::Arc;
 use tokio::sync::RwLock;
 
 use kuatia_types::autoid::AutoId;
+use kuatia_types::internals;
+use kuatia_types::internals::Cent;
 use kuatia_types::{
-    Account, AccountId, AssetId, Book, BookId, Cent, Posting, PostingFilter, PostingId,
+    Account, AccountId, Amount, Asset, AssetId, Book, BookId, Posting, PostingFilter, PostingId,
     PostingState, TransferId,
 };
 
@@ -16,7 +19,7 @@ use crate::error::StoreError;
 use crate::events::{EventStore, LedgerEvent, event_dedup_key};
 use crate::query::{filter_transfers, paginate};
 use crate::store::{
-    AccountStore, BalanceProjection, BalanceProjectionStore, BookStore, CommitOutcome,
+    AccountStore, AssetStore, BalanceProjection, BalanceProjectionStore, BookStore, CommitOutcome,
     CommitRejection, CommitRequest, CommitStore, Page, PostingStore, TransferQuery, TransferRecord,
     TransferStore, TransitionOutcome, TransitionRejection,
 };
@@ -42,6 +45,7 @@ pub struct InMemoryStore {
     /// resolve `get_transfers_for_account` from the same instruction.
     transfer_accounts: RwLock<HashMap<TransferId, Vec<AccountId>>>,
     events: RwLock<Vec<LedgerEvent>>,
+    assets: RwLock<HashMap<AssetId, Asset>>,
     books: RwLock<HashMap<BookId, Book>>,
     /// Append-only balance cache points keyed by `(account, asset)` (ADR-0019).
     projections: RwLock<HashMap<(AccountId, AssetId), Vec<BalanceProjection>>>,
@@ -63,6 +67,7 @@ impl InMemoryStore {
             transfers: RwLock::new(HashMap::new()),
             transfer_accounts: RwLock::new(HashMap::new()),
             events: RwLock::new(Vec::new()),
+            assets: RwLock::new(HashMap::new()),
             books: RwLock::new(HashMap::new()),
             projections: RwLock::new(HashMap::new()),
             autoid: AutoId::new(),
@@ -79,22 +84,18 @@ impl BalanceProjectionStore for InMemoryStore {
     async fn append_balance_projection(
         &self,
         account: &AccountId,
-        asset: &AssetId,
-        balance: Cent,
+        balance: Amount,
         watermark: i64,
     ) -> Result<(), StoreError> {
         let id = self.autoid.next();
+        let key = (*account, balance.asset_id());
         let mut projections = self.projections.write().await;
-        projections
-            .entry((*account, *asset))
-            .or_default()
-            .push(BalanceProjection {
-                id,
-                account: *account,
-                asset: *asset,
-                balance,
-                watermark,
-            });
+        projections.entry(key).or_default().push(BalanceProjection {
+            id,
+            account: *account,
+            balance,
+            watermark,
+        });
         Ok(())
     }
 
@@ -201,7 +202,7 @@ impl PostingStore for InMemoryStore {
         let matches = |p: &&Posting| {
             p.owner.id == id
                 && sub.is_none_or(|s| p.owner.sub == s)
-                && asset.is_none_or(|a| p.asset == *a)
+                && asset.is_none_or(|a| p.asset() == *a)
         };
         // Read the requested set directly, with no merge back to the immutable
         // record.
@@ -220,7 +221,11 @@ impl PostingStore for InMemoryStore {
         Ok(result)
     }
 
-    async fn live_balance(&self, account: &AccountId, asset: &AssetId) -> Result<Cent, StoreError> {
+    async fn live_balance(
+        &self,
+        account: &AccountId,
+        asset: &AssetId,
+    ) -> Result<Amount, StoreError> {
         let live = self
             .get_postings_by_account(
                 account.id,
@@ -229,8 +234,16 @@ impl PostingStore for InMemoryStore {
                 PostingFilter::Live,
             )
             .await?;
-        Cent::checked_sum(live.iter().map(|p| p.value))
-            .map_err(|e| StoreError::Internal(e.to_string()))
+        let sum = Cent::checked_sum(live.iter().map(|p| internals::cent(&p.amount)))
+            .map_err(|_| StoreError::Internal("balance overflow".into()))?;
+        // The asset comes from the registry rather than from a posting, so a
+        // zero balance answers in the same asset as a non-zero one.
+        let assets = self.assets.read().await;
+        let row = assets
+            .get(asset)
+            .cloned()
+            .ok_or_else(|| StoreError::NotFound(format!("asset {asset:?}")))?;
+        Ok(internals::amount(Arc::new(row), sum))
     }
 
     async fn get_posting_states(&self, ids: &[PostingId]) -> Result<Vec<PostingState>, StoreError> {
@@ -391,11 +404,11 @@ impl CommitStore for InMemoryStore {
             }
             let mut assets: HashSet<AssetId> = HashSet::new();
             for p in req.create.iter().filter(|p| p.owner == *aid) {
-                assets.insert(p.asset);
+                assets.insert(p.asset());
             }
             for id in req.consume {
                 if let Some(p) = postings.live.get(id).filter(|p| p.owner == *aid) {
-                    assets.insert(p.asset);
+                    assets.insert(p.asset());
                 }
             }
             for asset in assets {
@@ -404,16 +417,16 @@ impl CommitStore for InMemoryStore {
                         .live
                         .values()
                         .filter(|p| {
-                            p.owner == *aid && p.asset == asset && !consumed_set.contains(&p.id)
+                            p.owner == *aid && p.asset() == asset && !consumed_set.contains(&p.id)
                         })
-                        .map(|p| p.value),
+                        .map(|p| internals::cent(&p.amount)),
                 )
                 .map_err(|_| overflow())?;
                 let created_sum = Cent::checked_sum(
                     req.create
                         .iter()
-                        .filter(|p| p.owner == *aid && p.asset == asset)
-                        .map(|p| p.value),
+                        .filter(|p| p.owner == *aid && p.asset() == asset)
+                        .map(|p| internals::cent(&p.amount)),
                 )
                 .map_err(|_| overflow())?;
                 let projected = live_sum.checked_add(created_sum).map_err(|_| overflow())?;
@@ -534,6 +547,36 @@ impl EventStore for InMemoryStore {
 }
 
 #[async_trait]
+impl AssetStore for InMemoryStore {
+    async fn create_asset(&self, asset: Asset) -> Result<u64, StoreError> {
+        let mut assets = self.assets.write().await;
+        if assets.contains_key(&asset.id) {
+            return Ok(0);
+        }
+        assets.insert(asset.id, asset);
+        Ok(1)
+    }
+
+    async fn get_asset(&self, id: &AssetId) -> Result<Asset, StoreError> {
+        let assets = self.assets.read().await;
+        assets
+            .get(id)
+            .cloned()
+            .ok_or_else(|| StoreError::NotFound(format!("asset {id:?}")))
+    }
+
+    async fn get_asset_by_code(&self, code: &str) -> Result<Option<Asset>, StoreError> {
+        let assets = self.assets.read().await;
+        Ok(assets.values().find(|a| a.code == code).cloned())
+    }
+
+    async fn list_assets(&self) -> Result<Vec<Asset>, StoreError> {
+        let assets = self.assets.read().await;
+        Ok(assets.values().cloned().collect())
+    }
+}
+
+#[async_trait]
 impl BookStore for InMemoryStore {
     async fn create_book(&self, book: Book) -> Result<u64, StoreError> {
         let mut books = self.books.write().await;

+ 36 - 10
crates/kuatia-storage/src/store.rs

@@ -9,13 +9,15 @@
 //! - [`TransferStore`]: committed transfer reads
 //! - [`CommitStore`]: the atomic commit boundary (ADR-0023)
 //! - [`EventStore`]: the ledger event log
+//! - [`AssetStore`]: the asset registry
 //! - [`BookStore`]: book persistence
 //! - [`BalanceProjectionStore`]: the cached balance projection (ADR-0019)
 
 use async_trait::async_trait;
+use kuatia_types::internals::Cent;
 use kuatia_types::{
-    Account, AccountId, AssetId, Book, BookId, Cent, Envelope, Posting, PostingFilter, PostingId,
-    PostingState, Receipt, TransferId, ValueDate,
+    Account, AccountId, Amount, Asset, AssetId, Book, BookId, Envelope, Posting, PostingFilter,
+    PostingId, PostingState, Receipt, TransferId, ValueDate,
 };
 
 use crate::error::StoreError;
@@ -146,7 +148,11 @@ pub trait PostingStore: Send + Sync {
     /// because it can do so exactly (ADR-0024): the SQL store folds native
     /// amount columns inside the database rather than shipping one row per
     /// posting to the caller. An overflow is an error, never a wrap.
-    async fn live_balance(&self, account: &AccountId, asset: &AssetId) -> Result<Cent, StoreError>;
+    async fn live_balance(
+        &self,
+        account: &AccountId,
+        asset: &AssetId,
+    ) -> Result<Amount, StoreError>;
 
     /// Query postings with filtering and pagination.
     async fn query_postings(&self, query: &PostingQuery) -> Result<Page<Posting>, StoreError> {
@@ -188,6 +194,26 @@ pub trait TransferStore: Send + Sync {
     ) -> Result<Page<TransferRecord>, StoreError>;
 }
 
+/// The asset registry: what each [`AssetId`] in a posting means.
+///
+/// A row is written once and never updated, so a reader can cache one for the
+/// life of the process without going stale.
+#[async_trait]
+pub trait AssetStore: Send + Sync {
+    /// Register an asset. A dumb instruction: insert it if absent and return
+    /// the **number of assets created**, 1 if newly created and 0 if this id
+    /// was already registered. The caller decides what 0 means.
+    async fn create_asset(&self, asset: Asset) -> Result<u64, StoreError>;
+    /// Fetch one asset by id.
+    async fn get_asset(&self, id: &AssetId) -> Result<Asset, StoreError>;
+    /// Fetch one asset by its code, which is unique. `None` rather than
+    /// `NotFound`, because the caller asking by code is usually deciding
+    /// whether to register it.
+    async fn get_asset_by_code(&self, code: &str) -> Result<Option<Asset>, StoreError>;
+    /// List every registered asset.
+    async fn list_assets(&self) -> Result<Vec<Asset>, StoreError>;
+}
+
 /// Book persistence.
 #[async_trait]
 pub trait BookStore: Send + Sync {
@@ -211,11 +237,10 @@ pub struct BalanceProjection {
     pub id: i64,
     /// Account (base id plus subaccount) this cache point is for.
     pub account: AccountId,
-    /// Asset this cache point is for.
-    pub asset: AssetId,
-    /// Cached balance: the sum of every committed transfer's delta for this
-    /// `(account, asset)` with commit time at or before `watermark`.
-    pub balance: Cent,
+    /// Cached balance, carrying the asset it is in: the sum of every committed
+    /// transfer's delta for this `(account, asset)` with commit time at or
+    /// before `watermark`.
+    pub balance: Amount,
     /// Commit-time cutoff (unix millis) the snapshot covers. A read folds in
     /// committed transfers with a commit time strictly greater than this.
     pub watermark: i64,
@@ -234,8 +259,7 @@ pub trait BalanceProjectionStore: Send + Sync {
     async fn append_balance_projection(
         &self,
         account: &AccountId,
-        asset: &AssetId,
-        balance: Cent,
+        balance: Amount,
         watermark: i64,
     ) -> Result<(), StoreError>;
 
@@ -376,6 +400,7 @@ pub trait Store:
     + TransferStore
     + CommitStore
     + EventStore
+    + AssetStore
     + BookStore
     + BalanceProjectionStore
 {
@@ -387,6 +412,7 @@ impl<
         + TransferStore
         + CommitStore
         + EventStore
+        + AssetStore
         + BookStore
         + BalanceProjectionStore,
 > Store for T

+ 141 - 33
crates/kuatia-storage/src/store_tests.rs

@@ -9,7 +9,10 @@
 
 use std::collections::BTreeMap;
 
+use kuatia_types::internals;
+use kuatia_types::internals::Cent;
 use kuatia_types::*;
+use std::sync::Arc;
 
 use crate::error::StoreError;
 use crate::events::{LedgerEvent, LedgerEventKind};
@@ -29,6 +32,18 @@ fn make_account(id: i64, flags: AccountFlags) -> Account {
     }
 }
 
+/// An amount of `asset` in minor units. These tests assert on ids and values,
+/// and an amount compares by asset id, so the metadata here is filler.
+fn money<V>(asset: u32, value: V) -> Amount
+where
+    Amount: From<(V, Arc<Asset>)>,
+{
+    Amount::from((
+        value,
+        Arc::new(Asset::new(AssetId::new(asset), "TEST", "$", 2)),
+    ))
+}
+
 fn make_posting(
     transfer_hash: [u8; 32],
     index: u16,
@@ -42,8 +57,7 @@ fn make_posting(
             index,
         },
         AccountId::new(owner),
-        AssetId::new(asset),
-        Cent::from(value),
+        money(asset, value),
     )
 }
 
@@ -61,8 +75,7 @@ fn make_posting_sub(
             index,
         },
         AccountId::with_sub(owner, sub),
-        AssetId::new(asset),
-        Cent::from(value),
+        money(asset, value),
     )
 }
 
@@ -71,14 +84,12 @@ fn make_envelope_with_book(book: BookId) -> (Envelope, TransferId) {
         .creates(vec![
             NewPosting {
                 owner: AccountId::new(1),
-                asset: AssetId::new(1),
-                value: Cent::from(100),
+                amount: money(1, Cent::from(100)),
                 payer: None,
             },
             NewPosting {
                 owner: AccountId::new(99),
-                asset: AssetId::new(1),
-                value: Cent::from(-100),
+                amount: money(1, Cent::from(-100)),
                 payer: None,
             },
         ])
@@ -96,14 +107,12 @@ fn make_envelope() -> (Envelope, TransferId) {
         .creates(vec![
             NewPosting {
                 owner: AccountId::new(1),
-                asset: AssetId::new(1),
-                value: Cent::from(100),
+                amount: money(1, Cent::from(100)),
                 payer: None,
             },
             NewPosting {
                 owner: AccountId::new(99),
-                asset: AssetId::new(1),
-                value: Cent::from(-100),
+                amount: money(1, Cent::from(-100)),
                 payer: None,
             },
         ])
@@ -152,6 +161,16 @@ async fn commit_as(
         store.create_account(seed_account(*owner)).await.unwrap();
     }
 
+    // Register every asset the postings name. A posting read resolves its
+    // asset definition from the registry, so a backend that stores the id in a
+    // column has somewhere to resolve it from.
+    let mut assets: Vec<u32> = create.iter().map(|p| p.asset().0).collect();
+    assets.sort();
+    assets.dedup();
+    for asset in assets {
+        store.create_asset(seed_asset(asset)).await.unwrap();
+    }
+
     let envelope = EnvelopeBuilder::new()
         .consumes(consume.to_vec())
         .creates(
@@ -159,8 +178,7 @@ async fn commit_as(
                 .iter()
                 .map(|p| NewPosting {
                     owner: p.owner,
-                    asset: p.asset,
-                    value: p.value,
+                    amount: money(p.asset().0, internals::cent(&p.amount)),
                     payer: None,
                 })
                 .collect(),
@@ -236,8 +254,7 @@ async fn commit_record(
                     index: i as u16,
                 },
                 np.owner,
-                np.asset,
-                np.value,
+                np.amount.clone(),
             )
         })
         .collect();
@@ -343,7 +360,7 @@ pub async fn commit_creates_postings(store: &(impl Store + 'static)) {
 
     let got = store.get_postings(&[p.id]).await.unwrap();
     assert_eq!(got.len(), 1);
-    assert_eq!(got[0].value, Cent::from(100));
+    assert_eq!(got[0].amount.minor_units(), 100);
 }
 
 /// Get non-existent posting returns NotFound.
@@ -374,7 +391,7 @@ pub async fn get_postings_by_account_filters(store: &(impl Store + 'static)) {
         .await
         .unwrap();
     assert_eq!(filtered.len(), 1);
-    assert_eq!(filtered[0].value, Cent::from(100));
+    assert_eq!(filtered[0].amount.minor_units(), 100);
 
     let active = store
         .get_postings_by_account(1, None, None, PostingFilter::Live)
@@ -406,7 +423,7 @@ pub async fn get_postings_by_subaccount(store: &(impl Store + 'static)) {
         .await
         .unwrap();
     assert_eq!(main_only.len(), 1);
-    assert_eq!(main_only[0].value, Cent::from(100));
+    assert_eq!(main_only[0].amount.minor_units(), 100);
     assert_eq!(main_only[0].owner, AccountId::new(1));
 
     // sub = Some(7) is that subaccount only; its two postings are never folded
@@ -567,7 +584,7 @@ pub async fn spent_posting_remains_in_immutable_table(store: &(impl Store + 'sta
 
     let got = store.get_postings(&[p.id]).await.unwrap();
     assert_eq!(got.len(), 1);
-    assert_eq!(got[0].value, Cent::from(100));
+    assert_eq!(got[0].amount.minor_units(), 100);
     assert_eq!(state_of(store, p.id).await, PostingState::Spent);
 }
 
@@ -596,10 +613,15 @@ pub async fn get_postings_by_account_live_filter(store: &(impl Store + 'static))
 pub async fn live_balance_matches_rust_sum(store: &(impl Store + 'static)) {
     let account = AccountId::new(70);
     let asset = AssetId::new(1);
+    // A balance answers in an asset, so the asset has to be registered: that is
+    // what lets a zero balance name the same asset a non-zero one does.
+    for id in [1, 2] {
+        store.create_asset(seed_asset(id)).await.unwrap();
+    }
 
     assert_eq!(
         store.live_balance(&account, &asset).await.unwrap(),
-        Cent::ZERO
+        money(1, 0)
     );
 
     let active = make_posting([0xC7; 32], 0, 70, 1, 900);
@@ -635,17 +657,17 @@ pub async fn live_balance_matches_rust_sum(store: &(impl Store + 'static)) {
             )
             .await
             .unwrap();
-        let expected = Cent::checked_sum(live.iter().map(|p| p.value)).unwrap();
+        let expected = Cent::checked_sum(live.iter().map(|p| internals::cent(&p.amount))).unwrap();
         assert_eq!(
             store.live_balance(&account, &asset).await.unwrap(),
-            expected,
+            money(asset.0, expected),
             "live_balance disagreed for {account:?} / {asset:?}"
         );
     }
 
     assert_eq!(
         store.live_balance(&account, &asset).await.unwrap(),
-        Cent::from(650)
+        money(1, 650)
     );
 }
 
@@ -665,8 +687,7 @@ pub async fn commit_indexes_involved_accounts(store: &(impl Store + 'static)) {
         .consumes(vec![consumed])
         .creates(vec![NewPosting {
             owner: AccountId::new(8),
-            asset: AssetId::new(1),
-            value: Cent::from(100),
+            amount: money(1, Cent::from(100)),
             payer: None,
         }])
         .build();
@@ -1394,6 +1415,85 @@ pub async fn events_sequence_ordering(store: &(impl Store + 'static)) {
 }
 
 // ---------------------------------------------------------------------------
+// AssetStore
+// ---------------------------------------------------------------------------
+
+fn make_asset(id: u32, code: &str, decimals: u8) -> Asset {
+    Asset::new(AssetId::new(id), code, "$", decimals)
+}
+
+/// An asset for a test that only needs one to exist. The code is derived from
+/// the id because a code is unique (ADR-0030), so a fixed one would collide the
+/// moment a test seeds two assets.
+fn seed_asset(id: u32) -> Asset {
+    make_asset(id, &format!("T{id}"), 2)
+}
+
+/// Register an asset and read it back, precision included.
+pub async fn create_and_get_asset(store: &(impl Store + 'static)) {
+    let asset = make_asset(1, "USD", 2);
+    store.create_asset(asset.clone()).await.unwrap();
+    let got = store.get_asset(&AssetId::new(1)).await.unwrap();
+    assert_eq!(got, asset);
+}
+
+/// Registering a known id lands nothing and reports 0, so a caller can tell a
+/// fresh registration from a repeat without reading first.
+pub async fn create_duplicate_asset_reports_zero(store: &(impl Store + 'static)) {
+    let asset = make_asset(1, "USD", 2);
+    assert_eq!(store.create_asset(asset.clone()).await.unwrap(), 1);
+    assert_eq!(
+        store
+            .create_asset(make_asset(1, "NOT-USD", 8))
+            .await
+            .unwrap(),
+        0
+    );
+    assert_eq!(store.get_asset(&AssetId::new(1)).await.unwrap(), asset);
+}
+
+/// An unregistered asset is NotFound, which is what makes an amount of it
+/// impossible to build rather than silently zero-scaled.
+pub async fn get_missing_asset_fails(store: &(impl Store + 'static)) {
+    let err = store.get_asset(&AssetId::new(999)).await.unwrap_err();
+    assert!(matches!(err, StoreError::NotFound(_)));
+}
+
+/// A code is unique, so a by-code read finds the one row or none. It returns
+/// an Option rather than NotFound because the caller is usually deciding
+/// whether to register it.
+pub async fn get_asset_by_code(store: &(impl Store + 'static)) {
+    assert!(store.get_asset_by_code("USD").await.unwrap().is_none());
+    let usd = make_asset(1, "USD", 2);
+    store.create_asset(usd.clone()).await.unwrap();
+    store.create_asset(make_asset(3, "BTC", 8)).await.unwrap();
+
+    assert_eq!(store.get_asset_by_code("USD").await.unwrap(), Some(usd));
+    assert_eq!(
+        store
+            .get_asset_by_code("BTC")
+            .await
+            .unwrap()
+            .map(|a| a.decimals),
+        Some(8)
+    );
+    assert!(store.get_asset_by_code("usd").await.unwrap().is_none());
+}
+
+/// List every registered asset.
+pub async fn list_assets(store: &(impl Store + 'static)) {
+    store.create_asset(make_asset(1, "USD", 2)).await.unwrap();
+    store.create_asset(make_asset(3, "BTC", 8)).await.unwrap();
+    let mut assets = store.list_assets().await.unwrap();
+    assets.sort_by_key(|a| a.id.0);
+    assert_eq!(assets.len(), 2);
+    assert_eq!(assets[0].code, "USD");
+    assert_eq!(assets[0].decimals, 2);
+    assert_eq!(assets[1].code, "BTC");
+    assert_eq!(assets[1].decimals, 8);
+}
+
+// ---------------------------------------------------------------------------
 // BookStore
 // ---------------------------------------------------------------------------
 
@@ -1452,8 +1552,9 @@ pub async fn balance_projection_absent_is_none(store: &(impl Store + 'static)) {
 /// An appended cache point round-trips: value and watermark come back intact and
 /// carry a store-minted id.
 pub async fn balance_projection_append_and_get_closest(store: &(impl Store + 'static)) {
+    store.create_asset(seed_asset(1)).await.unwrap();
     store
-        .append_balance_projection(&AccountId::new(1), &AssetId::new(1), Cent::from(1234), 500)
+        .append_balance_projection(&AccountId::new(1), money(1, 1234), 500)
         .await
         .unwrap();
     let got = store
@@ -1462,8 +1563,8 @@ pub async fn balance_projection_append_and_get_closest(store: &(impl Store + 'st
         .unwrap()
         .unwrap();
     assert_eq!(got.account, AccountId::new(1));
-    assert_eq!(got.asset, AssetId::new(1));
-    assert_eq!(got.balance, Cent::from(1234));
+    assert_eq!(got.balance.asset_id(), AssetId::new(1));
+    assert_eq!(got.balance, money(1, 1234));
     assert_eq!(got.watermark, 500);
 }
 
@@ -1473,8 +1574,9 @@ pub async fn balance_projection_append_and_get_closest(store: &(impl Store + 'st
 pub async fn balance_projection_closest_at_or_before_as_of(store: &(impl Store + 'static)) {
     let acc = AccountId::new(1);
     let asset = AssetId::new(1);
+    store.create_asset(seed_asset(1)).await.unwrap();
     store
-        .append_balance_projection(&acc, &asset, Cent::from(100), 200)
+        .append_balance_projection(&acc, money(1, 100), 200)
         .await
         .unwrap();
     let first = store
@@ -1484,7 +1586,7 @@ pub async fn balance_projection_closest_at_or_before_as_of(store: &(impl Store +
         .unwrap();
 
     store
-        .append_balance_projection(&acc, &asset, Cent::from(300), 400)
+        .append_balance_projection(&acc, money(1, 300), 400)
         .await
         .unwrap();
 
@@ -1498,7 +1600,7 @@ pub async fn balance_projection_closest_at_or_before_as_of(store: &(impl Store +
         latest.id > first.id,
         "cache-point id must increase on append"
     );
-    assert_eq!(latest.balance, Cent::from(300));
+    assert_eq!(latest.balance, money(1, 300));
     assert_eq!(latest.watermark, 400);
 
     // As of a time between them, the watermark-400 point is excluded (it would
@@ -1508,7 +1610,7 @@ pub async fn balance_projection_closest_at_or_before_as_of(store: &(impl Store +
         .await
         .unwrap()
         .unwrap();
-    assert_eq!(earlier.balance, Cent::from(100));
+    assert_eq!(earlier.balance, money(1, 100));
     assert_eq!(earlier.watermark, 200);
 
     // As of before any cache point, none is returned.
@@ -1581,6 +1683,12 @@ macro_rules! store_tests {
             // EventStore
             append_and_query_events,
             events_sequence_ordering,
+            // AssetStore
+            create_and_get_asset,
+            get_asset_by_code,
+            create_duplicate_asset_reports_zero,
+            get_missing_asset_fails,
+            list_assets,
             // BookStore
             create_and_get_book,
             create_duplicate_book_reports_zero,

+ 15 - 6
crates/kuatia-storage/tests/concurrency.rs

@@ -19,6 +19,18 @@ use kuatia_storage::store_tests::{seed_live, state_of};
 use kuatia_types::*;
 use std::collections::BTreeMap;
 
+/// An amount of `asset` in minor units. These tests assert on ids and values,
+/// and an amount compares by asset id, so the metadata here is filler.
+fn money<V>(asset: u32, value: V) -> Amount
+where
+    Amount: From<(V, std::sync::Arc<Asset>)>,
+{
+    Amount::from((
+        value,
+        std::sync::Arc::new(Asset::new(AssetId::new(asset), "TEST", "$", 2)),
+    ))
+}
+
 fn account(id: i64) -> Account {
     Account {
         id: AccountId::new(id),
@@ -40,8 +52,7 @@ fn funded() -> Posting {
             index: 0,
         },
         AccountId::new(1),
-        AssetId::new(1),
-        Cent::from(100),
+        money(1, 100),
     )
 }
 
@@ -70,8 +81,7 @@ async fn concurrent_commits_spend_a_posting_once() {
                     index: 0,
                 },
                 AccountId::new(2),
-                AssetId::new(1),
-                Cent::from(100),
+                money(1, 100),
             )];
             let involved = [AccountId::new(1), AccountId::new(2)];
             store
@@ -137,8 +147,7 @@ async fn concurrent_commit_and_transition_do_not_deadlock() {
                     index: 0,
                 },
                 AccountId::new(2),
-                AssetId::new(1),
-                Cent::from(100),
+                money(1, 100),
             )];
             let involved = [AccountId::new(1), AccountId::new(2)];
             store

+ 3 - 0
crates/kuatia-types/Cargo.toml

@@ -22,3 +22,6 @@ i128 = ["kuatia-money/i128"]
 kuatia-money.workspace = true
 serde.workspace = true
 bitflags.workspace = true
+
+[dev-dependencies]
+serde_json.workspace = true

+ 557 - 0
crates/kuatia-types/src/amount.rs

@@ -0,0 +1,557 @@
+//! [`Amount`]: a [`Cent`] that knows which asset it is denominated in
+//! (ADR-0028).
+
+use std::convert::Infallible;
+use std::error::Error;
+use std::fmt;
+use std::sync::Arc;
+
+use serde::{Deserialize, Deserializer, Serialize, Serializer};
+
+use crate::asset::Asset;
+use crate::ids::AssetId;
+use kuatia_money::{Cent, OverflowError, ParseDecimalError};
+
+/// A quantity of one asset.
+///
+/// A bare [`Cent`] adds to and compares with any other, so nothing stopped a
+/// caller holding two balances from summing dollars into euros. Carrying the
+/// asset makes that a rejected operation instead of a wrong number, and gives
+/// a decimal string somewhere to learn its precision from.
+///
+/// Built only through conversion, so an amount cannot exist without a
+/// registered asset behind it. The value comes first and the asset second, the
+/// way the money reads aloud. Integers are minor units and a string is the
+/// decimal form at the asset's own scale: `(500, usd)` is five dollars, and so
+/// is `("5.00", usd)`.
+#[derive(Clone)]
+pub struct Amount {
+    asset: Arc<Asset>,
+    value: Cent,
+}
+
+impl Amount {
+    /// Nothing, of one asset. The identity for [`checked_add`](Self::checked_add).
+    pub fn zero(asset: Arc<Asset>) -> Self {
+        Self {
+            asset,
+            value: Cent::ZERO,
+        }
+    }
+
+    /// The asset this is denominated in.
+    pub fn asset(&self) -> &Arc<Asset> {
+        &self.asset
+    }
+
+    /// The asset's id, which is what storage and the content address carry.
+    pub fn asset_id(&self) -> AssetId {
+        self.asset.id
+    }
+
+    /// The value in minor units, as a plain integer. The widest money backing
+    /// is 128 bits, so this is lossless whichever one is compiled in.
+    pub fn minor_units(&self) -> i128 {
+        self.value.minor_units()
+    }
+
+    pub(crate) fn cent(&self) -> Cent {
+        self.value
+    }
+
+    /// Whether this is a positive, negative or zero quantity.
+    pub fn is_positive(&self) -> bool {
+        self.value.is_positive()
+    }
+
+    /// True when the quantity is below zero, which an account permitting
+    /// overdraft may hold.
+    pub fn is_negative(&self) -> bool {
+        self.value.is_negative()
+    }
+
+    /// True when the quantity is nothing.
+    pub fn is_zero(&self) -> bool {
+        self.value.is_zero()
+    }
+
+    /// Add two amounts of the same asset. Mismatched assets are rejected, which
+    /// is the whole reason this type exists.
+    pub fn checked_add(&self, rhs: &Self) -> Result<Self, AmountError> {
+        self.same_asset(rhs)?;
+        Ok(Self {
+            asset: Arc::clone(&self.asset),
+            value: self.value.checked_add(rhs.value)?,
+        })
+    }
+
+    /// Subtract an amount of the same asset.
+    pub fn checked_sub(&self, rhs: &Self) -> Result<Self, AmountError> {
+        self.same_asset(rhs)?;
+        Ok(Self {
+            asset: Arc::clone(&self.asset),
+            value: self.value.checked_sub(rhs.value)?,
+        })
+    }
+
+    /// Negate, keeping the asset.
+    pub fn checked_neg(&self) -> Result<Self, AmountError> {
+        Ok(Self {
+            asset: Arc::clone(&self.asset),
+            value: self.value.checked_neg()?,
+        })
+    }
+
+    /// Sum amounts that must all be of `asset`. The asset is a parameter rather
+    /// than taken from the first item, so an empty sum still has one.
+    pub fn checked_sum(
+        asset: Arc<Asset>,
+        iter: impl IntoIterator<Item = Self>,
+    ) -> Result<Self, AmountError> {
+        let mut total = Self::zero(asset);
+        for item in iter {
+            total = total.checked_add(&item)?;
+        }
+        Ok(total)
+    }
+
+    fn same_asset(&self, rhs: &Self) -> Result<(), AmountError> {
+        if self.asset.id == rhs.asset.id {
+            return Ok(());
+        }
+        Err(AmountError::AssetMismatch {
+            left: self.asset.id,
+            right: rhs.asset.id,
+        })
+    }
+}
+
+/// Equality is by asset id and value. Two reads of the same asset are the same
+/// asset, so comparing the registry metadata would make equality depend on when
+/// each side was loaded.
+impl PartialEq for Amount {
+    fn eq(&self, other: &Self) -> bool {
+        self.asset.id == other.asset.id && self.value == other.value
+    }
+}
+
+impl Eq for Amount {}
+
+impl fmt::Debug for Amount {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        write!(f, "Amount({} {})", self.value, self.asset.code)
+    }
+}
+
+/// Formats at the asset's own scale and names it by code, so an amount cannot
+/// be printed at the wrong precision. Grouping separators are a locale
+/// decision and stay with the caller.
+impl fmt::Display for Amount {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        write!(
+            f,
+            "{} {}",
+            self.asset.scale().format(self.value),
+            self.asset.code
+        )
+    }
+}
+
+/// The serialized form carries the whole asset, not just its id, so an amount
+/// read back needs no registry to be whole again (ADR-0029). That is what makes
+/// a stored posting self-describing and its decode infallible.
+///
+/// The content address is the exception: it hashes the asset's id and the value
+/// alone, so a transfer's identity does not move when a code or a symbol is
+/// written differently.
+#[derive(Serialize, Deserialize)]
+#[serde(rename = "Amount")]
+struct AmountWire {
+    asset: Asset,
+    value: Cent,
+}
+
+impl Serialize for Amount {
+    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
+        AmountWire {
+            asset: Asset::clone(&self.asset),
+            value: self.value,
+        }
+        .serialize(serializer)
+    }
+}
+
+impl<'de> Deserialize<'de> for Amount {
+    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
+        let wire = AmountWire::deserialize(deserializer)?;
+        Ok(Self {
+            asset: Arc::new(wire.asset),
+            value: wire.value,
+        })
+    }
+}
+
+/// Why an amount could not be built or combined.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum AmountError {
+    /// Two amounts of different assets were combined. Each asset is its own
+    /// conservation boundary, so there is no sum to give.
+    AssetMismatch {
+        /// Asset of the left operand.
+        left: AssetId,
+        /// Asset of the right operand.
+        right: AssetId,
+    },
+    /// The result left the range the money backing can hold.
+    Overflow,
+    /// The decimal string did not parse at the asset's scale.
+    Parse(ParseDecimalError),
+}
+
+impl fmt::Display for AmountError {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        match self {
+            Self::AssetMismatch { left, right } => {
+                write!(f, "asset mismatch: {left:?} and {right:?}")
+            }
+            Self::Overflow => write!(f, "monetary amount overflow"),
+            Self::Parse(e) => write!(f, "amount: {e}"),
+        }
+    }
+}
+
+impl Error for AmountError {
+    fn source(&self) -> Option<&(dyn Error + 'static)> {
+        match self {
+            Self::Parse(e) => Some(e),
+            Self::AssetMismatch { .. } | Self::Overflow => None,
+        }
+    }
+}
+
+impl From<OverflowError> for AmountError {
+    fn from(_: OverflowError) -> Self {
+        Self::Overflow
+    }
+}
+
+impl From<ParseDecimalError> for AmountError {
+    fn from(e: ParseDecimalError) -> Self {
+        Self::Parse(e)
+    }
+}
+
+/// Lets an infallible conversion satisfy a bound that accepts a fallible one,
+/// so `(asset, Cent)` and `(asset, "5.00")` reach the same builder method.
+impl From<Infallible> for AmountError {
+    fn from(never: Infallible) -> Self {
+        match never {}
+    }
+}
+
+/// Build an amount of an asset from the asset's side: `usd.amount("100.00")?`,
+/// for a caller holding the asset rather than assembling a tuple.
+///
+/// Implemented for both [`Asset`] and `Arc<Asset>`, so it works on whatever a
+/// caller has: a handle from [`Ledger::asset`](../../kuatia/ledger/struct.Ledger.html)
+/// or a row from a listing. The `Arc` receiver shares the one row; the `Asset`
+/// one clones it, which costs the two strings and nothing in identity, since an
+/// amount compares by asset id.
+///
+/// This is a trait, so it has to be in scope. `kuatia::prelude::*` and
+/// `kuatia_core::*` both bring it. Not named `new`, which would read as
+/// constructing an [`Asset`].
+pub trait Denominate {
+    /// An amount of this asset, in whichever form the value is already in.
+    fn amount<V>(&self, value: V) -> Result<Amount, AmountError>
+    where
+        Amount: TryFrom<(V, Arc<Asset>)>,
+        <Amount as TryFrom<(V, Arc<Asset>)>>::Error: Into<AmountError>;
+}
+
+impl Denominate for Arc<Asset> {
+    fn amount<V>(&self, value: V) -> Result<Amount, AmountError>
+    where
+        Amount: TryFrom<(V, Arc<Asset>)>,
+        <Amount as TryFrom<(V, Arc<Asset>)>>::Error: Into<AmountError>,
+    {
+        Amount::try_from((value, Arc::clone(self))).map_err(Into::into)
+    }
+}
+
+impl Denominate for Asset {
+    fn amount<V>(&self, value: V) -> Result<Amount, AmountError>
+    where
+        Amount: TryFrom<(V, Arc<Asset>)>,
+        <Amount as TryFrom<(V, Arc<Asset>)>>::Error: Into<AmountError>,
+    {
+        Amount::try_from((value, Arc::new(self.clone()))).map_err(Into::into)
+    }
+}
+
+impl From<(Cent, Arc<Asset>)> for Amount {
+    fn from((value, asset): (Cent, Arc<Asset>)) -> Self {
+        Self { asset, value }
+    }
+}
+
+impl From<(Cent, &Arc<Asset>)> for Amount {
+    fn from((value, asset): (Cent, &Arc<Asset>)) -> Self {
+        Self::from((value, Arc::clone(asset)))
+    }
+}
+
+/// The value comes first, the way the money reads aloud: `("50.00", usd)`.
+/// Each conversion comes in two shapes, one taking the asset handle and one
+/// taking a reference to it, so a caller passing the same asset to several
+/// movements does not clone it at every call.
+macro_rules! amount_conversions {
+    (infallible $($value:ty),+) => {
+        $(
+            impl From<($value, Arc<Asset>)> for Amount {
+                fn from((value, asset): ($value, Arc<Asset>)) -> Self {
+                    Self { asset, value: Cent::from(value) }
+                }
+            }
+
+            impl From<($value, &Arc<Asset>)> for Amount {
+                fn from((value, asset): ($value, &Arc<Asset>)) -> Self {
+                    Self::from((value, Arc::clone(asset)))
+                }
+            }
+        )+
+    };
+}
+
+amount_conversions!(infallible i64, i32, u32, u8, i8);
+
+impl TryFrom<(i128, Arc<Asset>)> for Amount {
+    type Error = AmountError;
+
+    fn try_from((value, asset): (i128, Arc<Asset>)) -> Result<Self, Self::Error> {
+        Ok(Self {
+            asset,
+            value: Cent::try_from(value)?,
+        })
+    }
+}
+
+impl TryFrom<(i128, &Arc<Asset>)> for Amount {
+    type Error = AmountError;
+
+    fn try_from((value, asset): (i128, &Arc<Asset>)) -> Result<Self, Self::Error> {
+        Self::try_from((value, Arc::clone(asset)))
+    }
+}
+
+impl TryFrom<(&str, Arc<Asset>)> for Amount {
+    type Error = AmountError;
+
+    fn try_from((text, asset): (&str, Arc<Asset>)) -> Result<Self, Self::Error> {
+        let value = asset.scale().parse(text)?;
+        Ok(Self { asset, value })
+    }
+}
+
+impl TryFrom<(&str, &Arc<Asset>)> for Amount {
+    type Error = AmountError;
+
+    fn try_from((text, asset): (&str, &Arc<Asset>)) -> Result<Self, Self::Error> {
+        Self::try_from((text, Arc::clone(asset)))
+    }
+}
+
+impl TryFrom<(String, Arc<Asset>)> for Amount {
+    type Error = AmountError;
+
+    fn try_from((text, asset): (String, Arc<Asset>)) -> Result<Self, Self::Error> {
+        Self::try_from((text.as_str(), asset))
+    }
+}
+
+impl TryFrom<(String, &Arc<Asset>)> for Amount {
+    type Error = AmountError;
+
+    fn try_from((text, asset): (String, &Arc<Asset>)) -> Result<Self, Self::Error> {
+        Self::try_from((text.as_str(), Arc::clone(asset)))
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    fn usd() -> Arc<Asset> {
+        Arc::new(Asset::new(AssetId::new(1), "USD", "$", 2))
+    }
+
+    fn btc() -> Arc<Asset> {
+        Arc::new(Asset::new(AssetId::new(3), "BTC", "\u{20bf}", 8))
+    }
+
+    /// The same digits mean different quantities at different scales, which is
+    /// the reason a string cannot be parsed without its asset.
+    #[test]
+    fn integers_are_minor_units_and_strings_are_decimal() {
+        let from_int = Amount::from((500, usd()));
+        let from_str = Amount::try_from(("5.00", usd())).unwrap();
+        assert_eq!(from_int, from_str);
+        assert_eq!(from_int.minor_units(), 500);
+        assert_eq!(
+            Amount::try_from(("5.00", btc())).unwrap().minor_units(),
+            500_000_000
+        );
+    }
+
+    #[test]
+    fn a_string_finer_than_the_asset_is_refused() {
+        let err = Amount::try_from(("5.001", usd())).unwrap_err();
+        assert!(matches!(err, AmountError::Parse(_)));
+        assert!(Amount::try_from(("5.001", btc())).is_ok());
+    }
+
+    #[test]
+    fn mismatched_assets_do_not_combine() {
+        let dollars = Amount::from((500, usd()));
+        let coins = Amount::from((500, btc()));
+        assert_eq!(
+            dollars.checked_add(&coins),
+            Err(AmountError::AssetMismatch {
+                left: AssetId::new(1),
+                right: AssetId::new(3),
+            })
+        );
+        assert_eq!(
+            coins.checked_sub(&dollars),
+            Err(AmountError::AssetMismatch {
+                left: AssetId::new(3),
+                right: AssetId::new(1),
+            })
+        );
+    }
+
+    #[test]
+    fn same_asset_arithmetic_keeps_the_asset() {
+        let sum = Amount::from((500, usd()))
+            .checked_add(&Amount::from((250, usd())))
+            .unwrap();
+        assert_eq!(sum, Amount::from((750, usd())));
+        assert_eq!(sum.asset_id(), AssetId::new(1));
+        assert_eq!(sum.checked_neg().unwrap().minor_units(), -750);
+    }
+
+    /// The asset is a parameter so an empty sum still has one, and a stray
+    /// asset in the middle is caught rather than added.
+    #[test]
+    fn checked_sum_carries_the_asset_through_an_empty_run() {
+        assert_eq!(
+            Amount::checked_sum(usd(), Vec::new()).unwrap(),
+            Amount::zero(usd())
+        );
+        assert_eq!(
+            Amount::checked_sum(
+                usd(),
+                [Amount::from((100, usd())), Amount::from((25, usd()))]
+            )
+            .unwrap(),
+            Amount::from((125, usd()))
+        );
+        assert!(
+            Amount::checked_sum(
+                usd(),
+                [Amount::from((100, usd())), Amount::from((1, btc()))]
+            )
+            .is_err()
+        );
+    }
+
+    #[test]
+    fn i128_out_of_range_is_an_overflow() {
+        assert_eq!(
+            Amount::try_from((650i128, usd())).unwrap(),
+            Amount::from((650, usd()))
+        );
+        if let Some(beyond) = i128::from(i64::MAX).checked_add(1) {
+            let too_big = Amount::try_from((beyond, usd()));
+            #[cfg(not(feature = "i128"))]
+            assert_eq!(too_big, Err(AmountError::Overflow));
+            #[cfg(feature = "i128")]
+            assert!(too_big.is_ok());
+        }
+    }
+
+    #[test]
+    fn display_uses_the_asset_scale_and_code() {
+        assert_eq!(Amount::from((65_000, usd())).to_string(), "650.00 USD");
+        assert_eq!(
+            Amount::from((150_000_000, btc())).to_string(),
+            "1.50000000 BTC"
+        );
+        assert_eq!(
+            format!("{:?}", Amount::from((65_000, usd()))),
+            "Amount(65000 USD)"
+        );
+    }
+
+    /// A reference reaches the same conversions, so a caller passing one asset
+    /// to several movements does not clone the handle at every call.
+    #[test]
+    fn a_reference_to_the_asset_converts_too() {
+        let usd = usd();
+        let from_ref = Amount::try_from(("5.00", &usd)).unwrap();
+        assert_eq!(from_ref, Amount::from((500, &usd)));
+        assert_eq!(from_ref, Amount::from((Cent::from(500), usd.clone())));
+        assert_eq!(Amount::try_from((500i128, &usd)).unwrap(), from_ref);
+        assert_eq!(
+            Amount::try_from((String::from("5.00"), &usd)).unwrap(),
+            from_ref
+        );
+    }
+
+    /// `usd.amount(..)` is the same conversion from the other side, for a caller
+    /// holding the asset rather than building a tuple. It reads the same whether
+    /// the caller holds the shared handle or a row of its own.
+    #[test]
+    fn denominate_builds_from_the_asset() {
+        let usd = usd();
+        assert_eq!(usd.amount("5.00").unwrap(), Amount::from((500, &usd)));
+        assert_eq!(usd.amount(500).unwrap(), Amount::from((500, &usd)));
+        assert_eq!(
+            usd.amount(Cent::from(500)).unwrap(),
+            Amount::from((500, &usd))
+        );
+        assert!(matches!(usd.amount("5.001"), Err(AmountError::Parse(_))));
+
+        // A bare row works too, which is what a caller holds after listing the
+        // registry; an amount compares by asset id, so the two agree.
+        let row = Asset::new(AssetId::new(1), "USD", "$", 2);
+        assert_eq!(row.amount("5.00").unwrap(), usd.amount("5.00").unwrap());
+        assert_eq!(row.amount(500).unwrap(), Amount::from((500, &usd)));
+    }
+
+    /// A fraction shorter than the asset's scale is padded, not rejected: a
+    /// two-decimal asset reads "100.0" as ten thousand minor units.
+    #[test]
+    fn a_short_fraction_pads_to_the_scale() {
+        assert_eq!(usd().amount("100.0").unwrap().minor_units(), 10_000);
+        assert_eq!(usd().amount("100").unwrap().minor_units(), 10_000);
+        assert_eq!(btc().amount("1.5").unwrap().minor_units(), 150_000_000);
+    }
+
+    /// The asset travels with the value, so a stored amount decodes without a
+    /// registry and cannot come back at the wrong scale.
+    #[test]
+    fn round_trips_through_serde_carrying_its_asset() {
+        let amount = Amount::from((650, usd()));
+        let json = serde_json::to_string(&amount).unwrap();
+        assert_eq!(
+            json,
+            r#"{"asset":{"id":1,"code":"USD","symbol":"$","decimals":2},"value":"650"}"#
+        );
+
+        let back: Amount = serde_json::from_str(&json).unwrap();
+        assert_eq!(back, amount);
+        assert_eq!(back.asset().decimals, 2);
+        assert_eq!(back.to_string(), "6.50 USD");
+    }
+}

+ 87 - 0
crates/kuatia-types/src/asset.rs

@@ -0,0 +1,87 @@
+//! [`Asset`]: what an [`AssetId`] means, and the precision its amounts are
+//! written at.
+
+use std::sync::Arc;
+
+use serde::{Deserialize, Serialize};
+
+use crate::ids::AssetId;
+use kuatia_money::Scale;
+
+/// A registered unit of value. Conservation is enforced per asset, so this
+/// names a conservation boundary (ADR-0001) and not merely a label.
+///
+/// A row is immutable once created. Editing the precision would reinterpret
+/// every amount already recorded against it, since what is stored is minor
+/// units and nothing else.
+#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
+pub struct Asset {
+    /// Identity, supplied by the caller rather than minted, so an asset can be
+    /// named in code before the registry is reachable.
+    pub id: AssetId,
+    /// Short code a person uses for the asset, such as `USD` or `BTC`.
+    pub code: String,
+    /// Symbol for presentation, such as `$`. Never parsed.
+    pub symbol: String,
+    /// Decimal places between the amount a person writes and the minor units
+    /// stored: 2 for a cent currency, 8 for satoshis, 0 for a countable good.
+    pub decimals: u8,
+}
+
+impl Asset {
+    /// Define an asset. Nothing is persisted until the ledger registers it.
+    pub fn new(
+        id: AssetId,
+        code: impl Into<String>,
+        symbol: impl Into<String>,
+        decimals: u8,
+    ) -> Self {
+        Self {
+            id,
+            code: code.into(),
+            symbol: symbol.into(),
+            decimals,
+        }
+    }
+
+    /// The scale this asset's amounts are written at, for parsing a decimal
+    /// string or formatting one. Crate-internal: an amount parses and formats
+    /// itself, and nothing public hands out a `Scale` (ADR-0029).
+    pub(crate) fn scale(&self) -> Scale {
+        Scale::new(self.decimals)
+    }
+}
+
+/// An asset names itself, so anything that takes an `impl Into<AssetId>`
+/// accepts the registry row or the shared handle as readily as the id. The
+/// `&AssetId` impl is what keeps a caller that already had the id writing it
+/// the same way.
+impl From<&AssetId> for AssetId {
+    fn from(id: &AssetId) -> Self {
+        *id
+    }
+}
+
+impl From<Asset> for AssetId {
+    fn from(asset: Asset) -> Self {
+        asset.id
+    }
+}
+
+impl From<&Asset> for AssetId {
+    fn from(asset: &Asset) -> Self {
+        asset.id
+    }
+}
+
+impl From<Arc<Asset>> for AssetId {
+    fn from(asset: Arc<Asset>) -> Self {
+        asset.id
+    }
+}
+
+impl From<&Arc<Asset>> for AssetId {
+    fn from(asset: &Arc<Asset>) -> Self {
+        asset.id
+    }
+}

+ 2 - 2
crates/kuatia-types/src/book.rs

@@ -59,8 +59,8 @@ impl BookBuilder {
     }
 
     /// Add an allowed asset.
-    pub fn allow_asset(mut self, asset: AssetId) -> Self {
-        self.book.policy.allowed_assets.push(asset);
+    pub fn allow_asset(mut self, asset: impl Into<AssetId>) -> Self {
+        self.book.policy.allowed_assets.push(asset.into());
         self
     }
 

+ 8 - 6
crates/kuatia-types/src/canonical.rs

@@ -12,10 +12,12 @@
 //! prefixed with a `u32` length, and the top-level [`Envelope`](crate::Envelope)
 //! and [`Account`](crate::Account) preimages begin with [`CANONICAL_VERSION`].
 
+use crate::internals;
 use crate::{
-    Account, AccountFlags, AccountId, AccountSnapshotId, AssetId, BookId, Cent, Envelope,
-    NewPosting, Posting, PostingId, Receipt, TransferId,
+    Account, AccountFlags, AccountId, AccountSnapshotId, AssetId, BookId, Envelope, NewPosting,
+    Posting, PostingId, Receipt, TransferId,
 };
+use kuatia_money::Cent;
 
 /// Deterministic binary serialization. Every domain type can produce its
 /// canonical byte representation.
@@ -129,8 +131,8 @@ impl ToBytes for NewPosting {
         // still persisted on the envelope record for audit.
         let mut buf = Vec::new();
         buf.extend(self.owner.to_bytes());
-        buf.extend_from_slice(&self.asset.0.to_be_bytes());
-        buf.extend(self.value.to_bytes());
+        buf.extend_from_slice(&self.amount.asset_id().0.to_be_bytes());
+        buf.extend(internals::cent(&self.amount).to_bytes());
         buf
     }
 }
@@ -140,8 +142,8 @@ impl ToBytes for Posting {
         let mut buf = Vec::new();
         buf.extend(self.id.to_bytes());
         buf.extend(self.owner.to_bytes());
-        buf.extend_from_slice(&self.asset.0.to_be_bytes());
-        buf.extend(self.value.to_bytes());
+        buf.extend_from_slice(&self.amount.asset_id().0.to_be_bytes());
+        buf.extend(internals::cent(&self.amount).to_bytes());
         buf
     }
 }

+ 27 - 0
crates/kuatia-types/src/internals.rs

@@ -0,0 +1,27 @@
+//! The seam the rest of this workspace uses to reach an amount's integer.
+//!
+//! Not part of the public API. [`Cent`] is deliberately absent from every
+//! public signature, but the storage backends have to bind an integer to a
+//! column and the ledger has to do checked arithmetic, and they are separate
+//! crates, so `pub(crate)` cannot serve them. These two functions are that
+//! route, kept in one place so it stays greppable. The money vocabulary is
+//! re-exported here for the same reason: a caller of the ledger names amounts
+//! and assets, never the integer behind them.
+
+use std::sync::Arc;
+
+use crate::amount::Amount;
+use crate::asset::Asset;
+pub use kuatia_money::{
+    Cent, OverflowError, ParseDecimalError, Scale, decode_storage_i128, encode_storage_i128,
+};
+
+/// The amount's value in minor units.
+pub fn cent(amount: &Amount) -> Cent {
+    amount.cent()
+}
+
+/// An amount of `asset` from a value already in minor units.
+pub fn amount(asset: Arc<Asset>, value: Cent) -> Amount {
+    Amount::from((value, asset))
+}

+ 6 - 4
crates/kuatia-types/src/lib.rs

@@ -9,10 +9,13 @@ pub mod autoid;
 
 mod account;
 mod account_code;
+mod amount;
+mod asset;
 mod book;
 mod canonical;
 mod envelope;
 mod ids;
+pub mod internals;
 mod posting;
 mod transfer;
 mod value_date;
@@ -28,12 +31,11 @@ pub use canonical::{
     CANONICAL_VERSION, ToBytes, write_i64, write_u16, write_u32, write_u64, write_u128,
 };
 
-// Cent — re-exported from kuatia-money (swappable integer backing).
-pub use kuatia_money::{
-    Amount, Cent, OverflowError, ParseAmountError, decode_storage_i128, encode_storage_i128,
-};
+pub use kuatia_money::OverflowError;
 
 pub use account::{Account, AccountFlags};
+pub use amount::{Amount, AmountError, Denominate};
+pub use asset::Asset;
 pub use book::{Book, BookBuilder, BookPolicy};
 pub use envelope::{Envelope, EnvelopeBuilder, Metadata};
 pub use ids::{AccountId, AccountSnapshotId, AssetId, BookId, DEFAULT_BOOK, PostingId, TransferId};

+ 24 - 16
crates/kuatia-types/src/posting.rs

@@ -1,7 +1,7 @@
 //! Posting records and their derived lifecycle state.
 
+use crate::amount::Amount;
 use crate::ids::{AccountId, AssetId, PostingId};
-use kuatia_money::Cent;
 use serde::{Deserialize, Serialize};
 
 /// Which postings a read returns, by derived state.
@@ -41,21 +41,22 @@ pub struct Posting {
     pub id: PostingId,
     /// The account (subaccount) that owns this posting.
     pub owner: AccountId,
-    /// The asset this posting denominates.
-    pub asset: AssetId,
-    /// Signed: positive = value controlled by the account, negative = offset position.
-    pub value: Cent,
+    /// What the account holds here, carrying the asset it is denominated in.
+    /// Signed: positive is value the account controls, negative an offset
+    /// position.
+    pub amount: Amount,
 }
 
 impl Posting {
     /// Construct a posting record.
-    pub fn new(id: PostingId, owner: AccountId, asset: AssetId, value: Cent) -> Self {
-        Self {
-            id,
-            owner,
-            asset,
-            value,
-        }
+    pub fn new(id: PostingId, owner: AccountId, amount: Amount) -> Self {
+        Self { id, owner, amount }
+    }
+
+    /// The asset this posting denominates, which is what storage and the
+    /// content address carry.
+    pub fn asset(&self) -> AssetId {
+        self.amount.asset_id()
     }
 }
 
@@ -65,10 +66,9 @@ impl Posting {
 pub struct NewPosting {
     /// The account (subaccount) that will own the created posting.
     pub owner: AccountId,
-    /// The asset this posting denominates.
-    pub asset: AssetId,
-    /// Signed amount: positive = value controlled by the account, negative = offset position.
-    pub value: Cent,
+    /// What the posting will hold. Signed: positive is value the account
+    /// controls, negative an offset position.
+    pub amount: Amount,
     /// Provenance — who funded this posting. Descriptive only: it is excluded
     /// from the content-address preimage (see [`NewPosting`]'s `ToBytes`), so it
     /// does not affect the [`TransferId`](crate::TransferId) or the idempotency
@@ -76,3 +76,11 @@ pub struct NewPosting {
     /// [`Posting`].
     pub payer: Option<AccountId>,
 }
+
+impl NewPosting {
+    /// The asset this posting denominates, which is what storage and the
+    /// content address carry.
+    pub fn asset(&self) -> AssetId {
+        self.amount.asset_id()
+    }
+}

+ 71 - 44
crates/kuatia-types/src/transfer.rs

@@ -1,10 +1,10 @@
 //! The intent-based [`Transfer`] API: [`Movement`], [`TransferBuilder`], and
 //! the [`Receipt`] returned on commit.
 
+use crate::amount::{Amount, AmountError};
 use crate::envelope::Metadata;
-use crate::ids::{AccountId, AssetId, BookId, TransferId};
+use crate::ids::{AccountId, BookId, TransferId};
 use crate::value_date::ValueDate;
-use kuatia_money::{Cent, OverflowError};
 use serde::{Deserialize, Serialize};
 
 /// Confirmation of a committed transfer, carrying its content-addressed id.
@@ -25,10 +25,9 @@ pub struct Movement {
     pub from: AccountId,
     /// Account (subaccount) being credited.
     pub to: AccountId,
-    /// Asset to transfer.
-    pub asset: AssetId,
-    /// Amount to transfer (may be negative for offset postings).
-    pub amount: Cent,
+    /// What moves. Negative for the offset leg of a deposit, where value
+    /// enters the ledger rather than moving inside it.
+    pub amount: Amount,
 }
 
 /// A transfer intent: one or more movements to execute atomically.
@@ -55,9 +54,19 @@ pub struct Transfer {
 pub const REFERENCE_KEY: &str = "reference";
 
 /// Builder for constructing [`Transfer`] values.
+///
+/// Every verb takes one amount rather than an asset beside a number, and takes
+/// anything that converts into an [`Amount`]: `(500, usd)` for minor units,
+/// `("5.00", usd)` for the written form, `(usd, cent)` for a value already in
+/// hand. A conversion that fails is held until [`build`](Self::build), so the
+/// chain stays fluent and one bad amount cannot be mistaken for a committed
+/// transfer.
 #[derive(Default)]
 pub struct TransferBuilder {
     transfer: Transfer,
+    /// First conversion failure, surfaced by `build`. First rather than last,
+    /// because that is the one the caller wrote before the others.
+    error: Option<AmountError>,
 }
 
 impl TransferBuilder {
@@ -68,53 +77,67 @@ impl TransferBuilder {
 
     /// Add a movement. The neutral spelling, for a leg that is not a payment:
     /// each side of an exchange, for instance.
-    pub fn movement(
-        mut self,
-        from: AccountId,
-        to: AccountId,
-        asset: AssetId,
-        amount: Cent,
-    ) -> Self {
-        self.transfer.movements.push(Movement {
-            from,
-            to,
-            asset,
-            amount,
-        });
+    pub fn movement<A>(mut self, from: AccountId, to: AccountId, amount: A) -> Self
+    where
+        A: TryInto<Amount>,
+        A::Error: Into<AmountError>,
+    {
+        match amount.try_into() {
+            Ok(amount) => self.transfer.movements.push(Movement { from, to, amount }),
+            Err(e) => self.remember(e.into()),
+        }
         self
     }
 
     /// Add a payment. Both endpoints carry their own subaccount, so this spans
     /// subaccounts as readily as main accounts.
-    pub fn pay(self, from: AccountId, to: AccountId, asset: AssetId, amount: Cent) -> Self {
-        self.movement(from, to, asset, amount)
+    pub fn pay<A>(self, from: AccountId, to: AccountId, amount: A) -> Self
+    where
+        A: TryInto<Amount>,
+        A::Error: Into<AmountError>,
+    {
+        self.movement(from, to, amount)
     }
 
     /// Add a deposit: creates an offset posting on the external account and
-    /// credits the target account.  Pushes two movements whose net debit on the
+    /// credits the target account. Pushes two movements whose net debit on the
     /// external account is zero.
-    pub fn deposit(
-        self,
-        to: AccountId,
-        asset: AssetId,
-        amount: Cent,
-        external: AccountId,
-    ) -> Result<Self, OverflowError> {
-        let neg = amount.checked_neg()?;
-        Ok(self
-            .movement(external, external, asset, neg)
-            .movement(external, to, asset, amount))
+    pub fn deposit<A>(mut self, to: AccountId, amount: A, external: AccountId) -> Self
+    where
+        A: TryInto<Amount>,
+        A::Error: Into<AmountError>,
+    {
+        let amount = match amount.try_into() {
+            Ok(amount) => amount,
+            Err(e) => {
+                self.remember(e.into());
+                return self;
+            }
+        };
+        let offset = match amount.checked_neg() {
+            Ok(offset) => offset,
+            Err(e) => {
+                self.remember(e);
+                return self;
+            }
+        };
+        self.movement(external, external, offset)
+            .movement(external, to, amount)
     }
 
     /// Add a withdrawal: move value from an account to an external destination.
-    pub fn withdraw(
-        self,
-        from: AccountId,
-        asset: AssetId,
-        amount: Cent,
-        external: AccountId,
-    ) -> Self {
-        self.movement(from, external, asset, amount)
+    pub fn withdraw<A>(self, from: AccountId, amount: A, external: AccountId) -> Self
+    where
+        A: TryInto<Amount>,
+        A::Error: Into<AmountError>,
+    {
+        self.movement(from, external, amount)
+    }
+
+    fn remember(&mut self, error: AmountError) {
+        if self.error.is_none() {
+            self.error = Some(error);
+        }
     }
 
     /// Set the book.
@@ -172,8 +195,12 @@ impl TransferBuilder {
         self
     }
 
-    /// Consume the builder and return the [`Transfer`].
-    pub fn build(self) -> Transfer {
-        self.transfer
+    /// Consume the builder and return the [`Transfer`], or the first amount
+    /// that could not be converted.
+    pub fn build(self) -> Result<Transfer, AmountError> {
+        match self.error {
+            Some(error) => Err(error),
+            None => Ok(self.transfer),
+        }
     }
 }

+ 21 - 25
crates/kuatia/examples/escrow.rs

@@ -31,8 +31,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
     let buyer = AccountId::new(1);
     let seller = AccountId::new(2);
     let bank = AccountId::new(99);
-    let usd = AssetId::new(1);
-    let money = Amount::new(2);
+
+    let usd = ledger.asset("USD", "$", 2).await?;
 
     ledger
         .create_account(Account::debit_must_not_exceed_credit(buyer))
@@ -45,9 +45,9 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
     ledger
         .commit(
             TransferBuilder::new()
-                .deposit(buyer, usd, money.parse("500.00")?, bank)?
+                .deposit(buyer, ("500.00", &usd), bank)
                 .reference("funding-buyer")
-                .build(),
+                .build()?,
         )
         .await?;
 
@@ -67,17 +67,17 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
     ledger
         .commit(
             TransferBuilder::new()
-                .pay(buyer, escrow_for(sale), usd, money.parse("120.00")?)
+                .pay(buyer, escrow_for(sale), ("120.00", &usd))
                 .reference("escrow-in-7001")
-                .build(),
+                .build()?,
         )
         .await?;
     ledger
         .commit(
             TransferBuilder::new()
-                .pay(buyer, escrow_for(cancelled), usd, money.parse("80.00")?)
+                .pay(buyer, escrow_for(cancelled), ("80.00", &usd))
                 .reference("escrow-in-7002")
-                .build(),
+                .build()?,
         )
         .await?;
 
@@ -87,42 +87,39 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
         ("escrow(7001)", escrow_for(sale)),
         ("escrow(7002)", escrow_for(cancelled)),
     ];
-    report(&ledger, &money, usd, &watched).await?;
+    report(&ledger, &usd, &watched).await?;
 
     // Nothing recorded that these are pending. Reading the escrow balance is
     // what tells you, and it is the same read that tells you how much.
     for agreement in [sale, cancelled] {
-        let held = ledger.balance(&escrow_for(agreement), &usd).await?;
-        println!(
-            "agreement {agreement}: {} USD in escrow",
-            money.format(held)
-        );
+        let held = ledger.balance(&escrow_for(agreement), &usd.id).await?;
+        println!("agreement {agreement}: {held} in escrow");
     }
 
     // The sale closes: release to the seller.
-    let held = ledger.balance(&escrow_for(sale), &usd).await?;
+    let held = ledger.balance(&escrow_for(sale), &usd.id).await?;
     ledger
         .commit(
             TransferBuilder::new()
-                .pay(escrow_for(sale), seller, usd, held)
+                .pay(escrow_for(sale), seller, held)
                 .reference("escrow-release-7001")
-                .build(),
+                .build()?,
         )
         .await?;
 
     // The other falls through: refund the buyer, from the same account, by the
     // same kind of transfer. Only the destination differs.
-    let held = ledger.balance(&escrow_for(cancelled), &usd).await?;
+    let held = ledger.balance(&escrow_for(cancelled), &usd.id).await?;
     ledger
         .commit(
             TransferBuilder::new()
-                .pay(escrow_for(cancelled), buyer, usd, held)
+                .pay(escrow_for(cancelled), buyer, held)
                 .reference("escrow-refund-7002")
-                .build(),
+                .build()?,
         )
         .await?;
 
-    report(&ledger, &money, usd, &watched).await?;
+    report(&ledger, &usd, &watched).await?;
 
     // A drained escrow account holds no live postings, so it can be closed and
     // the agreement is provably finished rather than marked finished.
@@ -142,14 +139,13 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
 
 async fn report(
     ledger: &Ledger,
-    money: &Amount,
-    asset: AssetId,
+    asset: &Asset,
     accounts: &[(&str, AccountId)],
 ) -> Result<(), Box<dyn std::error::Error>> {
     let mut line = String::new();
     for (label, account) in accounts {
-        let balance = ledger.balance(account, &asset).await?;
-        line.push_str(&format!("{label} {}  ", money.format(balance)));
+        let balance = ledger.balance(account, asset.id).await?;
+        line.push_str(&format!("{label} {balance}  "));
     }
     println!("{}", line.trim_end());
     Ok(())

+ 27 - 25
crates/kuatia/examples/fund_and_trade.rs

@@ -16,11 +16,9 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
     let alice = AccountId::new(1);
     let bob = AccountId::new(2);
     let external = AccountId::new(99);
-    let usd = AssetId::new(1);
-    let eur = AssetId::new(2);
 
-    // Two-decimal money: `money.parse("100.00")` -> Cent in minor units.
-    let money = Amount::new(2);
+    let usd = ledger.asset("USD", "$", 2).await?;
+    let eur = ledger.asset("EUR", "\u{20ac}", 2).await?;
 
     ledger
         .create_account(Account::debit_must_not_exceed_credit(alice))
@@ -30,35 +28,40 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
         .await?;
     ledger.create_account(Account::new(external)).await?;
 
-    // Fund: $100.00 to Alice, €90.00 to Bob.
+    // Fund: $100.00 to Alice, 90.00 EUR to Bob. Each string is parsed at its
+    // own asset's scale, so neither needs a decimal count spelled out here.
     ledger
         .commit(
             TransferBuilder::new()
-                .deposit(alice, usd, money.parse("100.00")?, external)?
-                .build(),
+                .deposit(alice, ("100.00", &usd), external)
+                .build()?,
         )
         .await?;
     ledger
         .commit(
             TransferBuilder::new()
-                .deposit(bob, eur, money.parse("90.00")?, external)?
-                .build(),
+                .deposit(bob, ("90.00", &eur), external)
+                .build()?,
         )
         .await?;
 
     println!("after funding:");
-    print_balances(&ledger, alice, bob, usd, eur).await?;
+    print_balances(&ledger, alice, bob, &usd, &eur).await?;
 
-    // Trade: Alice gives 100 USD to Bob; Bob gives 90 EUR to Alice. Both legs
-    // settle in one atomic transfer — each asset is conserved independently.
+    // Trade: Alice gives 100 USD to Bob, Bob gives 90 EUR to Alice. Both legs
+    // settle in one atomic transfer, and each asset is conserved independently.
+    //
+    // The first leg is written from the asset's side, the second as a tuple.
+    // Both reach the same conversion; `amount` needs the `Denominate` trait in
+    // scope, which the prelude brings.
     let trade = TransferBuilder::new()
-        .movement(alice, bob, usd, money.parse("100.00")?)
-        .movement(bob, alice, eur, money.parse("90.00")?)
-        .build();
+        .movement(alice, bob, usd.amount("100.00")?)
+        .movement(bob, alice, ("90.00", &eur))
+        .build()?;
     ledger.commit(trade).await?;
 
     println!("after trade:");
-    print_balances(&ledger, alice, bob, usd, eur).await?;
+    print_balances(&ledger, alice, bob, &usd, &eur).await?;
 
     Ok(())
 }
@@ -67,19 +70,18 @@ async fn print_balances(
     ledger: &Ledger,
     alice: AccountId,
     bob: AccountId,
-    usd: AssetId,
-    eur: AssetId,
+    usd: &Asset,
+    eur: &Asset,
 ) -> Result<(), Box<dyn std::error::Error>> {
-    let money = Amount::new(2);
     println!(
-        "  alice: {} USD, {} EUR",
-        money.format(ledger.balance(&alice, &usd).await?),
-        money.format(ledger.balance(&alice, &eur).await?),
+        "  alice: {}, {}",
+        ledger.balance(&alice, usd).await?,
+        ledger.balance(&alice, eur).await?,
     );
     println!(
-        "  bob:   {} USD, {} EUR",
-        money.format(ledger.balance(&bob, &usd).await?),
-        money.format(ledger.balance(&bob, &eur).await?),
+        "  bob:   {}, {}",
+        ledger.balance(&bob, usd).await?,
+        ledger.balance(&bob, eur).await?,
     );
     Ok(())
 }

+ 30 - 31
crates/kuatia/examples/inflight_hold.rs

@@ -11,6 +11,7 @@
 //! cargo run -p kuatia --example inflight_hold
 //! ```
 
+use std::sync::Arc;
 use std::time::Duration;
 
 use kuatia::prelude::*;
@@ -25,8 +26,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
     let merchant = AccountId::new(2);
     let fee = AccountId::new(3);
     let external = AccountId::new(99);
-    let usd = AssetId::new(1);
-    let money = Amount::new(2); // two-decimal money
+
+    let usd = ledger.asset("USD", "$", 2).await?;
 
     ledger
         .create_account(Account::debit_must_not_exceed_credit(customer))
@@ -42,24 +43,24 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
     ledger
         .commit(
             TransferBuilder::new()
-                .deposit(customer, usd, money.parse("100.00")?, external)?
-                .build(),
+                .deposit(customer, ("100.00", &usd), external)
+                .build()?,
         )
         .await?;
     println!("funded:");
-    print_balances(&ledger, &money, customer, merchant, fee, usd).await?;
+    print_balances(&ledger, customer, merchant, fee, &usd).await?;
 
     // Authorize a $100 order: $90 destined for the merchant, $10 for the fee.
     // The funds leave the customer and park in one holding account per
     // destination. Nothing has reached the merchant or fee account yet.
     let order = TransferBuilder::new()
-        .pay(customer, merchant, usd, money.parse("90.00")?)
-        .pay(customer, fee, usd, money.parse("10.00")?)
-        .build();
+        .pay(customer, merchant, ("90.00", &usd))
+        .pay(customer, fee, ("10.00", &usd))
+        .build()?;
     let auth = ledger.authorize(order).await?;
     println!("\nauthorized (funds now held):");
-    print_balances(&ledger, &money, customer, merchant, fee, usd).await?;
-    print_status(&ledger, &money, &auth.inflight).await?;
+    print_balances(&ledger, customer, merchant, fee, &usd).await?;
+    print_status(&ledger, &auth.inflight).await?;
 
     // Time passes before the first shipment.
     sleep(Duration::from_millis(300)).await;
@@ -70,10 +71,10 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
     ledger
         .confirm(
             &auth.inflight,
-            confirm_one(customer, merchant, usd, money.parse("40.00")?),
+            confirm_one(customer, merchant, ("40.00", &usd))?,
         )
         .await?;
-    print_status(&ledger, &money, &auth.inflight).await?;
+    print_status(&ledger, &auth.inflight).await?;
 
     // More time passes before the second shipment.
     sleep(Duration::from_millis(300)).await;
@@ -86,12 +87,12 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
         .confirm(
             &auth.inflight,
             TransferBuilder::new()
-                .pay(customer, merchant, usd, money.parse("20.00")?)
-                .pay(customer, fee, usd, money.parse("10.00")?)
-                .build(),
+                .pay(customer, merchant, ("20.00", &usd))
+                .pay(customer, fee, ("10.00", &usd))
+                .build()?,
         )
         .await?;
-    print_status(&ledger, &money, &auth.inflight).await?;
+    print_status(&ledger, &auth.inflight).await?;
 
     // The order is finalized before everything was captured.
     sleep(Duration::from_millis(300)).await;
@@ -100,41 +101,43 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
     // customer. Already-captured amounts are untouched.
     println!("\nvoid: release the uncaptured remainder back to the customer");
     ledger.void(&auth.inflight).await?;
-    print_status(&ledger, &money, &auth.inflight).await?;
+    print_status(&ledger, &auth.inflight).await?;
 
     // Final tally: merchant captured $60, fee $10, customer got the $30 back.
     println!("\nfinal balances:");
-    print_balances(&ledger, &money, customer, merchant, fee, usd).await?;
+    print_balances(&ledger, customer, merchant, fee, &usd).await?;
 
     Ok(())
 }
 
 /// A one-leg confirm set, built with the same `.pay()` shape as a transfer:
 /// `from` is the leg's funder, `to` its destination.
-fn confirm_one(from: AccountId, to: AccountId, asset: AssetId, amount: Cent) -> Transfer {
-    TransferBuilder::new().pay(from, to, asset, amount).build()
+fn confirm_one(
+    from: AccountId,
+    to: AccountId,
+    amount: (&str, &Arc<Asset>),
+) -> Result<Transfer, AmountError> {
+    TransferBuilder::new().pay(from, to, amount).build()
 }
 
 async fn print_balances(
     ledger: &Ledger,
-    money: &Amount,
     customer: AccountId,
     merchant: AccountId,
     fee: AccountId,
-    usd: AssetId,
+    usd: &Asset,
 ) -> Result<(), Box<dyn std::error::Error>> {
     println!(
         "  customer: {}   merchant: {}   fee: {}",
-        money.format(ledger.balance(&customer, &usd).await?),
-        money.format(ledger.balance(&merchant, &usd).await?),
-        money.format(ledger.balance(&fee, &usd).await?),
+        ledger.balance(&customer, usd).await?,
+        ledger.balance(&merchant, usd).await?,
+        ledger.balance(&fee, usd).await?,
     );
     Ok(())
 }
 
 async fn print_status(
     ledger: &Ledger,
-    money: &Amount,
     inflight: &TransferId,
 ) -> Result<(), Box<dyn std::error::Error>> {
     let status = ledger.inflight_status(inflight).await?;
@@ -142,11 +145,7 @@ async fn print_status(
     for leg in &status.legs {
         println!(
             "    -> {:?}: authorized {}, confirmed {}, voided {}, held {}",
-            leg.destination,
-            money.format(leg.authorized),
-            money.format(leg.confirmed),
-            money.format(leg.voided),
-            money.format(leg.held),
+            leg.destination, leg.authorized, leg.confirmed, leg.voided, leg.held,
         );
     }
     Ok(())

+ 22 - 22
crates/kuatia/examples/overdraft.rs

@@ -19,8 +19,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
     let wallet = AccountId::new(2);
     let merchant = AccountId::new(3);
     let external = AccountId::new(99);
-    let usd = AssetId::new(1);
-    let money = Amount::new(2);
+
+    let usd = ledger.asset("USD", "$", 2).await?;
 
     ledger.create_account(Account::new(treasury)).await?;
     ledger
@@ -35,8 +35,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
         ledger
             .commit(
                 TransferBuilder::new()
-                    .deposit(account, usd, money.parse("30.00")?, external)?
-                    .build(),
+                    .deposit(account, ("30.00", &usd), external)
+                    .build()?,
             )
             .await?;
     }
@@ -44,47 +44,48 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
     println!("Both accounts hold 30.00 USD. Both now try to pay 70.00 USD.\n");
 
     println!("treasury permits overdraft (Account::new):");
-    print_postings(&ledger, treasury, usd).await?;
+    print_postings(&ledger, treasury, &usd).await?;
 
     ledger
         .commit(
             TransferBuilder::new()
-                .pay(treasury, merchant, usd, money.parse("70.00")?)
-                .build(),
+                .pay(treasury, merchant, ("70.00", &usd))
+                .build()?,
         )
         .await?;
 
     println!(
-        "  commit succeeded, balance {} USD",
-        money.format(ledger.balance(&treasury, &usd).await?)
+        "  commit succeeded, balance {}",
+        ledger.balance(&treasury, &usd).await?
     );
     println!("  the 30.00 posting was consumed and a 40.00 shortfall posting created:");
-    print_postings(&ledger, treasury, usd).await?;
+    print_postings(&ledger, treasury, &usd).await?;
 
     println!("\nwallet forbids it (Account::debit_must_not_exceed_credit):");
-    print_postings(&ledger, wallet, usd).await?;
+    print_postings(&ledger, wallet, &usd).await?;
 
     let refused = ledger
         .commit(
             TransferBuilder::new()
-                .pay(wallet, merchant, usd, money.parse("70.00")?)
-                .build(),
+                .pay(wallet, merchant, ("70.00", &usd))
+                .build()?,
         )
         .await;
 
     match refused {
+        // The shortfall names its own asset, so this reports a quantity without
+        // the example having to remember which asset it asked about.
         Err(LedgerError::Selection(shortfall)) => println!(
-            "  commit refused: available {} USD, requested {} USD",
-            money.format(shortfall.available),
-            money.format(shortfall.requested),
+            "  commit refused: available {}, requested {}",
+            shortfall.available, shortfall.requested,
         ),
         Err(other) => println!("  commit refused for another reason: {other}"),
         Ok(_) => println!("  commit succeeded, which it should not have"),
     }
 
     println!(
-        "  balance unchanged at {} USD",
-        money.format(ledger.balance(&wallet, &usd).await?)
+        "  balance unchanged at {}",
+        ledger.balance(&wallet, &usd).await?
     );
 
     Ok(())
@@ -95,12 +96,11 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
 async fn print_postings(
     ledger: &Ledger,
     account: AccountId,
-    asset: AssetId,
+    asset: &std::sync::Arc<Asset>,
 ) -> Result<(), Box<dyn std::error::Error>> {
-    let money = Amount::new(2);
     for (posting, state) in ledger.postings_with_state(&account).await? {
-        if posting.asset == asset {
-            println!("    {:>10} USD  {:?}", money.format(posting.value), state);
+        if posting.amount.asset_id() == asset.id {
+            println!("    {:>12}  {:?}", posting.amount.to_string(), state);
         }
     }
     Ok(())

+ 13 - 14
crates/kuatia/examples/withdraw.rs

@@ -15,45 +15,44 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
 
     let alice = AccountId::new(1);
     let external = AccountId::new(99);
-    let usd = AssetId::new(1);
-    let money = Amount::new(2);
+
+    let usd = ledger.asset("USD", "$", 2).await?;
 
     ledger
         .create_account(Account::debit_must_not_exceed_credit(alice))
         .await?;
     ledger.create_account(Account::new(external)).await?;
 
-    // Fund Alice with $100.00.
+    // Written form, parsed at the asset's own two decimals.
     ledger
         .commit(
             TransferBuilder::new()
-                .deposit(alice, usd, money.parse("100.00")?, external)?
-                .build(),
+                .deposit(alice, ("100.00", &usd), external)
+                .build()?,
         )
         .await?;
     println!(
-        "after deposit:  alice = {} USD",
-        money.format(ledger.balance(&alice, &usd).await?)
+        "after deposit:  alice = {}",
+        ledger.balance(&alice, &usd).await?
     );
 
-    // Withdraw $30.00 from Alice out to the external boundary account.
     ledger
         .commit(
             TransferBuilder::new()
-                .withdraw(alice, usd, money.parse("30.00")?, external)
-                .build(),
+                .withdraw(alice, ("30.00", &usd), external)
+                .build()?,
         )
         .await?;
     println!(
-        "after withdraw: alice = {} USD",
-        money.format(ledger.balance(&alice, &usd).await?)
+        "after withdraw: alice = {}",
+        ledger.balance(&alice, &usd).await?
     );
 
     // The external account carries the offset (negative) side: the mirror of the
     // value that currently sits inside the ledger.
     println!(
-        "external boundary: {} USD",
-        money.format(ledger.balance(&external, &usd).await?)
+        "external boundary: {}",
+        ledger.balance(&external, &usd).await?
     );
 
     Ok(())

+ 39 - 1
crates/kuatia/src/error.rs

@@ -6,8 +6,9 @@
 use std::error::Error;
 use std::fmt;
 
+use kuatia_core::internals::OverflowError;
 use kuatia_core::{
-    AccountId, AssetId, BookId, InsufficientFunds, OverflowError, PostingId, ResolveError,
+    AccountId, AmountError, AssetId, BookId, InsufficientFunds, PostingId, ResolveError,
     TransferId, ValidationError,
 };
 use kuatia_storage::error::StoreError;
@@ -53,6 +54,25 @@ pub enum LedgerError {
         /// Version this attempt targeted (`current + 1` at read time).
         expected: u64,
     },
+    /// An amount could not be built, or two assets were combined.
+    Amount(AmountError),
+    /// An amount named an asset that is not in the registry. An unregistered
+    /// asset has no precision, so there is no amount of it to build.
+    AssetNotFound(AssetId),
+    /// An asset with this id is already registered. A row is immutable, so a
+    /// second registration is rejected rather than merged.
+    AssetAlreadyExists(AssetId),
+    /// A code is registered with metadata other than the one asked for. The row
+    /// is immutable and the stored precision is what every amount recorded
+    /// against it was written at, so neither side can quietly win.
+    AssetRedefined {
+        /// The code both definitions claim.
+        code: String,
+        /// Decimal places the registry holds.
+        registered: u8,
+        /// Decimal places the caller asked for.
+        requested: u8,
+    },
     /// A transfer named a book that does not exist.
     BookNotFound(BookId),
     /// A book with this id already exists.
@@ -113,6 +133,17 @@ impl fmt::Display for LedgerError {
                 f,
                 "account version conflict for {account:?}: could not append version {expected}"
             ),
+            Self::Amount(e) => write!(f, "amount: {e}"),
+            Self::AssetNotFound(id) => write!(f, "asset not registered: {id:?}"),
+            Self::AssetAlreadyExists(id) => write!(f, "asset already registered: {id:?}"),
+            Self::AssetRedefined {
+                code,
+                registered,
+                requested,
+            } => write!(
+                f,
+                "asset {code} is registered with {registered} decimals, asked for {requested}"
+            ),
             Self::BookNotFound(id) => write!(f, "book not found: {id:?}"),
             Self::BookAlreadyExists(id) => write!(f, "book already exists: {id:?}"),
             Self::InflightNotFound(id) => write!(f, "inflight transaction not found: {id:?}"),
@@ -151,6 +182,7 @@ impl Error for LedgerError {
             Self::Validation(e) => Some(e),
             Self::Store(e) => Some(e),
             Self::Selection(e) => Some(e),
+            Self::Amount(e) => Some(e),
             Self::Overflow => Some(&OverflowError),
             Self::CompensationFailed { original, .. } => Some(original.as_ref()),
             _ => None,
@@ -179,6 +211,12 @@ impl From<ResolveError> for LedgerError {
     }
 }
 
+impl From<AmountError> for LedgerError {
+    fn from(e: AmountError) -> Self {
+        Self::Amount(e)
+    }
+}
+
 impl From<OverflowError> for LedgerError {
     fn from(_: OverflowError) -> Self {
         LedgerError::Overflow

+ 45 - 40
crates/kuatia/src/inflight.rs

@@ -13,8 +13,8 @@
 //! See `doc/adr/0014-inflight-holds-via-holding-accounts.md`.
 
 use kuatia_core::{
-    Account, AccountFlags, AccountId, AssetId, BookId, Cent, InsufficientFunds, Receipt, SUB_BITS,
-    Transfer, TransferBuilder, TransferId, hash::double_sha256,
+    Account, AccountFlags, AccountId, Amount, AssetId, BookId, InsufficientFunds, Receipt,
+    SUB_BITS, Transfer, TransferBuilder, TransferId, hash::double_sha256,
 };
 use kuatia_storage::store::TransferRecord;
 use serde::{Deserialize, Serialize};
@@ -31,7 +31,7 @@ use projection::{
 
 /// One leg of an inflight transaction: an amount of an asset funded by `funder`,
 /// parked in `hold`, destined for `destination`.
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
 pub struct InflightLeg {
     /// Account the funds settle to on confirm.
     pub destination: AccountId,
@@ -39,10 +39,8 @@ pub struct InflightLeg {
     pub hold: AccountId,
     /// Account that funded this leg (the funds return here on void).
     pub funder: AccountId,
-    /// Asset being held.
-    pub asset: AssetId,
-    /// Amount authorized for this leg.
-    pub amount: Cent,
+    /// What this leg holds, carrying the asset it is in.
+    pub amount: Amount,
 }
 
 /// Result of [`Ledger::authorize`].
@@ -80,22 +78,20 @@ pub enum InflightState {
 }
 
 /// Per-(destination, asset) status line.
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[derive(Debug, Clone, PartialEq, Eq)]
 pub struct InflightLegStatus {
     /// Destination account.
     pub destination: AccountId,
     /// Holding account.
     pub hold: AccountId,
-    /// Asset.
-    pub asset: AssetId,
-    /// Amount originally authorized.
-    pub authorized: Cent,
-    /// Amount confirmed to the destination so far.
-    pub confirmed: Cent,
-    /// Amount returned to funders so far.
-    pub voided: Cent,
-    /// Amount still held (`= authorized - confirmed - voided`).
-    pub held: Cent,
+    /// Originally authorized.
+    pub authorized: Amount,
+    /// Confirmed to the destination so far.
+    pub confirmed: Amount,
+    /// Returned to funders so far.
+    pub voided: Amount,
+    /// Still held (`= authorized - confirmed - voided`).
+    pub held: Amount,
 }
 
 /// Derived status of an inflight transaction.
@@ -177,17 +173,16 @@ impl Ledger {
                 destination: m.to,
                 hold,
                 funder: m.from,
-                asset: m.asset,
-                amount: m.amount,
+                amount: m.amount.clone(),
             });
-            builder = builder.movement(m.from, hold, m.asset, m.amount);
+            builder = builder.movement(m.from, hold, m.amount.clone());
         }
         let mut md = transfer.metadata.clone();
         md.insert(
             K_INFLIGHT.to_string(),
             encode_meta(&InflightMeta::Authorize { legs: legs.clone() })?,
         );
-        let rewritten = builder.metadata(md).build();
+        let rewritten = builder.metadata(md).build()?;
 
         let receipt = self.commit(rewritten).await?;
         Ok(Authorization {
@@ -217,7 +212,6 @@ impl Ledger {
                             group.hold,
                             group.destination,
                             group.destination,
-                            asset,
                             bal,
                             SettleRole::Confirm,
                         )
@@ -255,16 +249,20 @@ impl Ledger {
         for m in &confirms.movements {
             let leg = legs
                 .iter()
-                .find(|l| l.funder == m.from && l.destination == m.to && l.asset == m.asset)
+                .find(|l| {
+                    l.funder == m.from
+                        && l.destination == m.to
+                        && l.amount.asset_id() == m.amount.asset_id()
+                })
                 .ok_or(LedgerError::InflightLegNotFound {
                     destination: m.to,
-                    asset: m.asset,
+                    asset: m.amount.asset_id(),
                 })?;
-            let held = self.balance(&leg.hold, &m.asset).await?;
-            if m.amount > held {
+            let held = self.balance(&leg.hold, &m.amount.asset_id()).await?;
+            if m.amount.minor_units() > held.minor_units() {
                 return Err(LedgerError::Selection(InsufficientFunds {
                     available: held,
-                    requested: m.amount,
+                    requested: m.amount.clone(),
                 }));
             }
             receipts.push(
@@ -274,8 +272,7 @@ impl Ledger {
                     leg.hold,
                     m.to,
                     m.to,
-                    m.asset,
-                    m.amount,
+                    m.amount.clone(),
                     SettleRole::Confirm,
                 )
                 .await?,
@@ -304,7 +301,7 @@ impl Ledger {
                 // split owns the leg-order and rounding-leftover rules.
                 let remaining = self.balance(&group.hold, asset).await?;
                 for FunderPayout { funder, give } in
-                    distribute_to_funders(&legs, group.hold, *asset, remaining)?
+                    distribute_to_funders(&legs, group.hold, &remaining)?
                 {
                     receipts.push(
                         self.settle(
@@ -313,7 +310,6 @@ impl Ledger {
                             group.hold,
                             funder,
                             group.destination,
-                            *asset,
                             give,
                             SettleRole::Void,
                         )
@@ -343,7 +339,7 @@ impl Ledger {
         // its live per-asset balance. `group_holds` names the holds to fetch;
         // `derive_status` re-derives its own grouping to fold the status.
         let mut hold_history: Vec<(AccountId, Vec<TransferRecord>)> = Vec::new();
-        let mut held: BTreeMap<(AccountId, AssetId), Cent> = BTreeMap::new();
+        let mut held: BTreeMap<(AccountId, AssetId), Amount> = BTreeMap::new();
         for group in group_holds(&legs, *inflight)? {
             hold_history.push((group.hold, self.history(&group.hold).await?));
             for asset in &group.assets {
@@ -404,8 +400,7 @@ impl Ledger {
         hold: AccountId,
         target: AccountId,
         destination: AccountId,
-        asset: AssetId,
-        amount: Cent,
+        amount: Amount,
         role: SettleRole,
     ) -> Result<Receipt, LedgerError> {
         let meta = match role {
@@ -420,9 +415,9 @@ impl Ledger {
         };
         let tx = TransferBuilder::new()
             .book(book)
-            .pay(hold, target, asset, amount)
+            .pay(hold, target, amount)
             .metadata(meta_map(&meta)?)
-            .build();
+            .build()?;
         self.commit(tx).await
     }
 
@@ -460,17 +455,27 @@ fn inflight_subaccount(transfer: &Transfer) -> i64 {
 #[cfg(test)]
 mod tests {
     use super::*;
-    use kuatia_core::AccountId;
+    use kuatia_core::{AccountId, Amount, Asset};
+    use std::sync::Arc;
+
+    /// An amount of `asset` in minor units. An amount compares by asset id, so
+    /// building the row here is equivalent to reading it back from the registry.
+    fn money<V>(asset: AssetId, value: V) -> Amount
+    where
+        Amount: From<(V, Arc<Asset>)>,
+    {
+        Amount::from((value, Arc::new(Asset::new(asset, "TEST", "$", 2))))
+    }
 
     fn pay_trade(amount: i64) -> Transfer {
         TransferBuilder::new()
             .pay(
                 AccountId::new(1),
                 AccountId::new(2),
-                AssetId::new(1),
-                Cent::from(amount),
+                money(AssetId::new(1), amount),
             )
             .build()
+            .unwrap()
     }
 
     #[test]

+ 94 - 91
crates/kuatia/src/inflight/projection.rs

@@ -11,7 +11,11 @@
 
 use std::collections::{BTreeMap, BTreeSet};
 
-use kuatia_core::{AccountId, AssetId, Cent, Metadata, OverflowError, TransferId};
+use std::sync::Arc;
+
+use kuatia_core::internals;
+use kuatia_core::internals::Cent;
+use kuatia_core::{AccountId, Amount, AmountError, Asset, AssetId, Metadata, TransferId};
 use kuatia_storage::error::StoreError;
 use kuatia_storage::store::TransferRecord;
 use serde::{Deserialize, Serialize};
@@ -113,10 +117,18 @@ fn holds_of(legs: &[InflightLeg]) -> BTreeSet<AccountId> {
 fn assets_of(legs: &[InflightLeg], hold: AccountId) -> BTreeSet<AssetId> {
     legs.iter()
         .filter(|l| l.hold == hold)
-        .map(|l| l.asset)
+        .map(|l| l.amount.asset_id())
         .collect()
 }
 
+/// The asset definition carried by this hold's legs in `asset`. Every leg of one
+/// hold in one asset carries the same definition, so the first is enough.
+fn leg_asset(legs: &[InflightLeg], hold: AccountId, asset: AssetId) -> Option<&Arc<Asset>> {
+    legs.iter()
+        .find(|l| l.hold == hold && l.amount.asset_id() == asset)
+        .map(|l| l.amount.asset())
+}
+
 fn destination_of(
     legs: &[InflightLeg],
     hold: AccountId,
@@ -143,7 +155,7 @@ pub(super) struct StatusInput<'a> {
     /// Settle transfers found in each hold's history, tagged with that hold.
     pub(super) hold_history: &'a [(AccountId, Vec<TransferRecord>)],
     /// Live held balance per (hold, asset).
-    pub(super) held: &'a BTreeMap<(AccountId, AssetId), Cent>,
+    pub(super) held: &'a BTreeMap<(AccountId, AssetId), Amount>,
 }
 
 /// Fold the leg table, settling transfers, and held balances into an
@@ -164,8 +176,10 @@ pub(super) fn derive_status(input: StatusInput<'_>) -> Result<InflightStatus, Le
     // Authorized per (hold, asset).
     let mut authorized: BTreeMap<(AccountId, AssetId), Cent> = BTreeMap::new();
     for l in legs {
-        let e = authorized.entry((l.hold, l.asset)).or_insert(Cent::ZERO);
-        *e = e.checked_add(l.amount)?;
+        let e = authorized
+            .entry((l.hold, l.amount.asset_id()))
+            .or_insert(Cent::ZERO);
+        *e = e.checked_add(internals::cent(&l.amount))?;
     }
 
     // Index history by hold so attribution keys on the fetched-for hold, never
@@ -190,8 +204,10 @@ pub(super) fn derive_status(input: StatusInput<'_>) -> Result<InflightStatus, Le
                 if np.owner == group.hold {
                     continue; // change returned to the hold, not settled out
                 }
-                let e = bucket.entry((group.hold, np.asset)).or_insert(Cent::ZERO);
-                *e = e.checked_add(np.value)?;
+                let e = bucket
+                    .entry((group.hold, np.amount.asset_id()))
+                    .or_insert(Cent::ZERO);
+                *e = e.checked_add(internals::cent(&np.amount))?;
             }
         }
     }
@@ -199,26 +215,19 @@ pub(super) fn derive_status(input: StatusInput<'_>) -> Result<InflightStatus, Le
     let mut lines = Vec::new();
     for group in &groups {
         for asset in &group.assets {
+            // The leg table is where the asset's definition comes from: a status
+            // line reports amounts, and every leg of this hold in this asset
+            // carries the same one.
+            let row = leg_asset(legs, group.hold, *asset).ok_or_else(|| malformed(inflight))?;
+            let key = (group.hold, *asset);
+            let at = |value: Cent| internals::amount(Arc::clone(row), value);
             lines.push(InflightLegStatus {
                 destination: group.destination,
                 hold: group.hold,
-                asset: *asset,
-                authorized: authorized
-                    .get(&(group.hold, *asset))
-                    .copied()
-                    .unwrap_or(Cent::ZERO),
-                confirmed: confirmed
-                    .get(&(group.hold, *asset))
-                    .copied()
-                    .unwrap_or(Cent::ZERO),
-                voided: voided
-                    .get(&(group.hold, *asset))
-                    .copied()
-                    .unwrap_or(Cent::ZERO),
-                held: held
-                    .get(&(group.hold, *asset))
-                    .copied()
-                    .unwrap_or(Cent::ZERO),
+                authorized: at(authorized.get(&key).copied().unwrap_or(Cent::ZERO)),
+                confirmed: at(confirmed.get(&key).copied().unwrap_or(Cent::ZERO)),
+                voided: at(voided.get(&key).copied().unwrap_or(Cent::ZERO)),
+                held: held.get(&key).cloned().unwrap_or_else(|| at(Cent::ZERO)),
             });
         }
     }
@@ -263,7 +272,7 @@ fn overall_state(lines: &[InflightLegStatus]) -> InflightState {
 /// One funder's share of a voided hold balance.
 pub(super) struct FunderPayout {
     pub(super) funder: AccountId,
-    pub(super) give: Cent,
+    pub(super) give: Amount,
 }
 
 /// Split `remaining` back to the funders of `(hold, asset)` in leg order, each
@@ -273,13 +282,14 @@ pub(super) struct FunderPayout {
 pub(super) fn distribute_to_funders(
     legs: &[InflightLeg],
     hold: AccountId,
-    asset: AssetId,
-    mut remaining: Cent,
-) -> Result<Vec<FunderPayout>, OverflowError> {
+    remaining: &Amount,
+) -> Result<Vec<FunderPayout>, AmountError> {
+    let asset = remaining.asset();
+    let mut left = internals::cent(remaining);
     let mut funders: Vec<(AccountId, Cent)> = legs
         .iter()
-        .filter(|l| l.hold == hold && l.asset == asset)
-        .map(|l| (l.funder, l.amount))
+        .filter(|l| l.hold == hold && l.amount.asset_id() == remaining.asset_id())
+        .map(|l| (l.funder, internals::cent(&l.amount)))
         .collect();
     // Ensure any co-funding rounding leftover lands on the last funder.
     if let Some(last) = funders.last_mut() {
@@ -288,13 +298,16 @@ pub(super) fn distribute_to_funders(
 
     let mut payouts = Vec::new();
     for (funder, cap) in funders {
-        if !remaining.is_positive() {
+        if !left.is_positive() {
             break;
         }
-        let give = if cap < remaining { cap } else { remaining };
+        let give = if cap < left { cap } else { left };
         if give.is_positive() {
-            payouts.push(FunderPayout { funder, give });
-            remaining = remaining.checked_sub(give)?;
+            payouts.push(FunderPayout {
+                funder,
+                give: internals::amount(Arc::clone(asset), give),
+            });
+            left = left.checked_sub(give)?;
         }
     }
     Ok(payouts)
@@ -307,15 +320,20 @@ mod tests {
 
     // -- overall_state golden vectors --------------------------------------
 
+    /// One asset for the whole fixture, since `overall_state` reads only the
+    /// four values and never compares across assets.
+    fn money(value: i64) -> Amount {
+        Amount::from((value, Arc::new(Asset::new(AssetId::new(1), "TEST", "$", 2))))
+    }
+
     fn line(authorized: i64, confirmed: i64, voided: i64, held: i64) -> InflightLegStatus {
         InflightLegStatus {
             destination: AccountId::new(2),
             hold: AccountId::with_sub(2, 7),
-            asset: AssetId::new(1),
-            authorized: Cent::from(authorized),
-            confirmed: Cent::from(confirmed),
-            voided: Cent::from(voided),
-            held: Cent::from(held),
+            authorized: money(authorized),
+            confirmed: money(confirmed),
+            voided: money(voided),
+            held: money(held),
         }
     }
 
@@ -368,51 +386,47 @@ mod tests {
 
     // -- distribute_to_funders golden vectors ------------------------------
 
+    fn money_of(asset: u32, value: i64) -> Amount {
+        Amount::from((
+            value,
+            Arc::new(Asset::new(AssetId::new(asset), "TEST", "$", 2)),
+        ))
+    }
+
     fn leg(funder: i64, hold_sub: i64, asset: u32, amount: i64) -> InflightLeg {
         InflightLeg {
             destination: AccountId::new(2),
             hold: AccountId::with_sub(2, hold_sub),
             funder: AccountId::new(funder),
-            asset: AssetId::new(asset),
-            amount: Cent::from(amount),
+            amount: money_of(asset, amount),
         }
     }
 
     #[test]
     fn distribute_single_funder_gets_whole_balance() {
         let legs = [leg(1, 7, 1, 100)];
-        let out = distribute_to_funders(
-            &legs,
-            AccountId::with_sub(2, 7),
-            AssetId::new(1),
-            Cent::from(80),
-        )
-        .unwrap();
+        let out =
+            distribute_to_funders(&legs, AccountId::with_sub(2, 7), &money_of(1, 80)).unwrap();
         assert_eq!(out.len(), 1);
         assert_eq!(out[0].funder, AccountId::new(1));
         // Last (only) funder's cap is lifted, so the whole remaining is returned.
-        assert_eq!(out[0].give, Cent::from(80));
+        assert_eq!(out[0].give.minor_units(), 80);
     }
 
     #[test]
     fn distribute_co_funders_split_by_cap() {
         // Two funders of 60 and 40; a remaining 100 splits 60 / 40.
         let legs = [leg(1, 7, 1, 60), leg(3, 7, 1, 40)];
-        let out = distribute_to_funders(
-            &legs,
-            AccountId::with_sub(2, 7),
-            AssetId::new(1),
-            Cent::from(100),
-        )
-        .unwrap();
+        let out =
+            distribute_to_funders(&legs, AccountId::with_sub(2, 7), &money_of(1, 100)).unwrap();
         assert_eq!(out.len(), 2);
         assert_eq!(
-            (out[0].funder, out[0].give),
-            (AccountId::new(1), Cent::from(60))
+            (out[0].funder, out[0].give.clone()),
+            (AccountId::new(1), money_of(1, 60))
         );
         assert_eq!(
-            (out[1].funder, out[1].give),
-            (AccountId::new(3), Cent::from(40))
+            (out[1].funder, out[1].give.clone()),
+            (AccountId::new(3), money_of(1, 40))
         );
     }
 
@@ -421,28 +435,18 @@ mod tests {
         // First funder capped at 60; the last funder's cap is lifted so it
         // absorbs the leftover (100 - 60 = 40, even though it funded only 30).
         let legs = [leg(1, 7, 1, 60), leg(3, 7, 1, 30)];
-        let out = distribute_to_funders(
-            &legs,
-            AccountId::with_sub(2, 7),
-            AssetId::new(1),
-            Cent::from(100),
-        )
-        .unwrap();
+        let out =
+            distribute_to_funders(&legs, AccountId::with_sub(2, 7), &money_of(1, 100)).unwrap();
         assert_eq!(out.len(), 2);
-        assert_eq!(out[0].give, Cent::from(60));
-        assert_eq!(out[1].give, Cent::from(40));
+        assert_eq!(out[0].give.minor_units(), 60);
+        assert_eq!(out[1].give.minor_units(), 40);
     }
 
     #[test]
     fn distribute_no_funders_yields_no_payouts() {
         let legs: [InflightLeg; 0] = [];
-        let out = distribute_to_funders(
-            &legs,
-            AccountId::with_sub(2, 7),
-            AssetId::new(1),
-            Cent::from(100),
-        )
-        .unwrap();
+        let out =
+            distribute_to_funders(&legs, AccountId::with_sub(2, 7), &money_of(1, 100)).unwrap();
         assert!(out.is_empty());
     }
 
@@ -468,8 +472,7 @@ mod tests {
     fn np(owner: AccountId, asset: u32, value: i64) -> NewPosting {
         NewPosting {
             owner,
-            asset: AssetId::new(asset),
-            value: Cent::from(value),
+            amount: money_of(asset, value),
             payer: None,
         }
     }
@@ -493,7 +496,7 @@ mod tests {
         );
         let hold_history = vec![(hold, vec![confirm])];
         let mut held = BTreeMap::new();
-        held.insert((hold, AssetId::new(1)), Cent::from(40));
+        held.insert((hold, AssetId::new(1)), money_of(1, 40));
 
         let status = derive_status(StatusInput {
             inflight,
@@ -504,11 +507,11 @@ mod tests {
         .unwrap();
 
         assert_eq!(status.legs.len(), 1);
-        let l = status.legs[0];
-        assert_eq!(l.authorized, Cent::from(100));
-        assert_eq!(l.confirmed, Cent::from(60)); // change to hold excluded
-        assert_eq!(l.voided, Cent::ZERO);
-        assert_eq!(l.held, Cent::from(40));
+        let l = &status.legs[0];
+        assert_eq!(l.authorized.minor_units(), 100);
+        assert_eq!(l.confirmed.minor_units(), 60); // change to hold excluded
+        assert_eq!(l.voided.minor_units(), 0);
+        assert_eq!(l.held.minor_units(), 40);
         assert_eq!(status.state, InflightState::PartiallyConfirmed);
     }
 
@@ -538,7 +541,7 @@ mod tests {
         );
         let hold_history = vec![(hold, vec![confirm, void])];
         let mut held = BTreeMap::new();
-        held.insert((hold, AssetId::new(1)), Cent::ZERO);
+        held.insert((hold, AssetId::new(1)), money_of(1, 0));
 
         let status = derive_status(StatusInput {
             inflight,
@@ -548,10 +551,10 @@ mod tests {
         })
         .unwrap();
 
-        let l = status.legs[0];
-        assert_eq!(l.confirmed, Cent::from(70));
-        assert_eq!(l.voided, Cent::from(30));
-        assert_eq!(l.held, Cent::ZERO);
+        let l = &status.legs[0];
+        assert_eq!(l.confirmed.minor_units(), 70);
+        assert_eq!(l.voided.minor_units(), 30);
+        assert_eq!(l.held.minor_units(), 0);
         assert_eq!(status.state, InflightState::Mixed);
     }
 
@@ -562,7 +565,7 @@ mod tests {
         let legs = [leg(1, 7, 1, 100)];
         let hold_history = vec![(hold, vec![])];
         let mut held = BTreeMap::new();
-        held.insert((hold, AssetId::new(1)), Cent::from(100));
+        held.insert((hold, AssetId::new(1)), money_of(1, 100));
 
         let status = derive_status(StatusInput {
             inflight,
@@ -572,7 +575,7 @@ mod tests {
         })
         .unwrap();
 
-        assert_eq!(status.legs[0].held, Cent::from(100));
+        assert_eq!(status.legs[0].held.minor_units(), 100);
         assert_eq!(status.state, InflightState::Held);
     }
 }

+ 10 - 0
crates/kuatia/src/ledger.rs

@@ -7,18 +7,24 @@
 //! - `commit`: the commit engine (resolve, validate, atomic apply, reverse).
 //!   This is what a ledger fundamentally *is*.
 //! - `lifecycle`: account create, freeze, unfreeze, close.
+//! - `asset`: the asset registry and its process-lifetime cache.
 //! - `balance`: per-subaccount balance queries.
 //! - `query`: read-only queries and book CRUD (thin `Store` pass-throughs that
 //!   relabel `StoreError` as [`LedgerError`]).
 //!
 //! The inflight-hold API is a further cluster, in [`crate::inflight`].
 
+use std::collections::HashMap;
 use std::sync::Arc;
 
+use kuatia_types::{Asset, AssetId};
+use tokio::sync::RwLock;
+
 use kuatia_storage::store::Store;
 
 use crate::error::LedgerError;
 
+mod asset;
 mod balance;
 mod commit;
 mod lifecycle;
@@ -73,6 +79,9 @@ pub(crate) fn now_millis() -> Result<i64, LedgerError> {
 pub struct Ledger {
     store: Arc<dyn Store>,
     projection: ProjectionConfig,
+    /// Registry rows are immutable, so a hit never goes stale and the cache
+    /// needs no invalidation.
+    assets: RwLock<HashMap<AssetId, Arc<Asset>>>,
 }
 
 impl Ledger {
@@ -81,6 +90,7 @@ impl Ledger {
         Self {
             store: Arc::new(store),
             projection: ProjectionConfig::default(),
+            assets: RwLock::new(HashMap::new()),
         }
     }
 

+ 151 - 0
crates/kuatia/src/ledger/asset.rs

@@ -0,0 +1,151 @@
+//! The asset registry: registration, and the lookup an amount of an asset goes
+//! through (ADR-0028).
+
+use std::sync::Arc;
+
+use kuatia_core::autoid::AutoId;
+use kuatia_core::{Asset, AssetId, Envelope};
+
+use kuatia_storage::error::StoreError;
+
+use super::Ledger;
+use crate::error::LedgerError;
+
+/// Tries before a minted id is given up on. Each attempt is one read, and a
+/// clash needs a fresh millisecond or counter step, so a handful is plenty.
+const MINT_ATTEMPTS: usize = 8;
+
+/// Ids for assets come from the same generator accounts and books use, folded
+/// into the `u32` an [`AssetId`] carries. The high bit is cleared by the
+/// generator, so the fold keeps the counter and the low timestamp bits, which
+/// is what makes two registrations in one process differ.
+fn next_asset_id() -> u32 {
+    static IDS: AutoId = AutoId::new();
+    IDS.next() as u32
+}
+
+impl Ledger {
+    /// Register an asset, so amounts of it can be built and read.
+    pub async fn create_asset(&self, asset: Asset) -> Result<(), LedgerError> {
+        let id = asset.id;
+        if self.store.create_asset(asset).await? == 0 {
+            return Err(LedgerError::AssetAlreadyExists(id));
+        }
+        Ok(())
+    }
+
+    /// The asset with this code, registering it if the ledger has not seen it
+    /// before: `ledger.asset("EUR", "\u{20ac}", 2)`.
+    ///
+    /// Idempotent, so setup code calls it unconditionally. A code already
+    /// registered with other metadata is [`LedgerError::AssetRedefined`] rather
+    /// than either definition quietly winning: the stored precision is what
+    /// every amount recorded against the asset was written at, and a row is
+    /// immutable.
+    ///
+    /// The id is minted here, the way an account's or a book's is, because the
+    /// code is what a caller names and the id is what storage carries
+    /// (ADR-0030). Pass an id instead through
+    /// [`create_asset`](Self::create_asset) to choose it.
+    pub async fn asset(
+        &self,
+        code: impl Into<String>,
+        symbol: impl Into<String>,
+        decimals: u8,
+    ) -> Result<Arc<Asset>, LedgerError> {
+        let code = code.into();
+        if let Some(registered) = self.store.get_asset_by_code(&code).await? {
+            if registered.decimals != decimals {
+                return Err(LedgerError::AssetRedefined {
+                    code,
+                    registered: registered.decimals,
+                    requested: decimals,
+                });
+            }
+            return Ok(self.cache(registered).await);
+        }
+
+        // A fresh id, retried past the chance that a truncated snowflake lands
+        // on one already taken. The code's own uniqueness is the index's job,
+        // so a racing registration of the same code is caught by re-reading it.
+        let symbol = symbol.into();
+        for _ in 0..MINT_ATTEMPTS {
+            let id = AssetId::new(next_asset_id());
+            if self.store.get_asset(&id).await.is_ok() {
+                continue;
+            }
+            let asset = Asset::new(id, code.clone(), symbol.clone(), decimals);
+            if self.store.create_asset(asset.clone()).await? == 1 {
+                return Ok(self.cache(asset).await);
+            }
+            // Someone else took the code or the id between the read and the
+            // insert. Re-read by code: a matching row is the answer, and a
+            // mismatched one is the same refusal as above.
+            if let Some(registered) = self.store.get_asset_by_code(&code).await? {
+                if registered.decimals != decimals {
+                    return Err(LedgerError::AssetRedefined {
+                        code,
+                        registered: registered.decimals,
+                        requested: decimals,
+                    });
+                }
+                return Ok(self.cache(registered).await);
+            }
+        }
+        Err(LedgerError::Overflow)
+    }
+
+    /// Hold the row in the process cache and hand back the shared handle.
+    async fn cache(&self, asset: Asset) -> Arc<Asset> {
+        let handle = Arc::new(asset);
+        self.assets
+            .write()
+            .await
+            .insert(handle.id, Arc::clone(&handle));
+        handle
+    }
+
+    /// Fetch a registered asset, cached for the life of the process.
+    ///
+    /// A registry row never changes, so a hit is always current. A miss is
+    /// never cached: an asset registered after a failed lookup would otherwise
+    /// stay missing.
+    pub async fn asset_by_id(&self, id: impl Into<AssetId>) -> Result<Arc<Asset>, LedgerError> {
+        let id = &id.into();
+        if let Some(asset) = self.assets.read().await.get(id) {
+            return Ok(Arc::clone(asset));
+        }
+        let asset = match self.store.get_asset(id).await {
+            Ok(asset) => Arc::new(asset),
+            // Only an absent row means unregistered. Anything else is the store
+            // failing, and reporting that as a domain error would tell a caller
+            // to register an asset when the database is what is wrong.
+            Err(StoreError::NotFound(_)) => return Err(LedgerError::AssetNotFound(*id)),
+            Err(e) => return Err(e.into()),
+        };
+        self.assets.write().await.insert(*id, Arc::clone(&asset));
+        Ok(asset)
+    }
+
+    /// List every registered asset.
+    pub async fn list_assets(&self) -> Result<Vec<Asset>, LedgerError> {
+        Ok(self.store.list_assets().await?)
+    }
+
+    /// Refuse a transfer denominated in an unregistered asset. Conservation
+    /// puts every asset a transfer touches on the created side, so that side is
+    /// the whole set. An unregistered asset has no precision, so nothing could
+    /// report what the ledger held afterwards.
+    pub(crate) async fn require_registered_assets(
+        &self,
+        envelope: &Envelope,
+    ) -> Result<(), LedgerError> {
+        let mut seen: Vec<AssetId> = envelope.creates().iter().map(|p| p.asset()).collect();
+        seen.sort();
+        seen.dedup();
+        for asset in &seen {
+            self.asset_by_id(asset).await?;
+        }
+        Ok(())
+    }
+}

+ 85 - 38
crates/kuatia/src/ledger/balance.rs

@@ -27,20 +27,22 @@ use std::sync::Arc;
 
 use tracing::instrument;
 
-use kuatia_core::{AccountId, AssetId, Cent, PostingId};
+use kuatia_core::internals;
+use kuatia_core::internals::Cent;
+use kuatia_core::{AccountId, Amount, Asset, AssetId, PostingId};
 use kuatia_storage::store::{Store, TransferQuery, TransferRecord};
 
 use super::{Ledger, now_millis};
 use crate::error::LedgerError;
 
-/// A single subaccount's balance for one asset. Balances are always reported
-/// per subaccount and never summed across them (ADR-0012).
-#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+/// A single subaccount's balance. Balances are always reported per subaccount
+/// and never summed across them (ADR-0012).
+#[derive(Clone, PartialEq, Eq, Debug)]
 pub struct SubAccountBalance {
     /// The subaccount this balance belongs to.
     pub account: AccountId,
-    /// The balance of `account` for the queried asset.
-    pub value: Cent,
+    /// What that subaccount holds, carrying the asset it is denominated in.
+    pub amount: Amount,
 }
 
 // ---------------------------------------------------------------------------
@@ -66,8 +68,8 @@ async fn fold_account_delta(
     // Created side (credits): the envelope carries owner/asset/value directly.
     for record in records {
         for np in record.envelope.creates() {
-            if np.owner == *account && np.asset == *asset {
-                delta = delta.checked_add(np.value)?;
+            if np.owner == *account && np.asset() == *asset {
+                delta = delta.checked_add(internals::cent(&np.amount))?;
                 count += 1;
             }
         }
@@ -86,8 +88,8 @@ async fn fold_account_delta(
     }
     if !consumed_ids.is_empty() {
         for posting in store.get_postings(&consumed_ids).await? {
-            if posting.owner == *account && posting.asset == *asset {
-                delta = delta.checked_sub(posting.value)?;
+            if posting.owner == *account && posting.asset() == *asset {
+                delta = delta.checked_sub(internals::cent(&posting.amount))?;
                 count += 1;
             }
         }
@@ -139,11 +141,11 @@ pub(super) async fn append_cache_point(
     min_new: u64,
     debounce_ms: i64,
     account: &AccountId,
-    asset: &AssetId,
+    asset: Arc<Asset>,
 ) -> Result<(), LedgerError> {
     let new_watermark = now_millis()?.saturating_sub(grace_ms);
     let closest = store
-        .get_closest_balance_projection(account, asset, new_watermark)
+        .get_closest_balance_projection(account, &asset.id, new_watermark)
         .await?;
     let (snapshot, from_ts) = match closest {
         // Storage-based debounce: a cache point within `debounce_ms` below the
@@ -153,13 +155,16 @@ pub(super) async fn append_cache_point(
         // A cache point already covers this watermark: nothing to add. (Also the
         // debounce == 0 stop, so an exact-or-newer watermark is never duplicated.)
         Some(p) if p.watermark >= new_watermark => return Ok(()),
-        Some(p) => (p.balance, Some(p.watermark.saturating_add(1))),
+        Some(p) => (
+            internals::cent(&p.balance),
+            Some(p.watermark.saturating_add(1)),
+        ),
         None => (Cent::ZERO, None),
     };
     let (fold, count) = fold_tail(
         store,
         account,
-        asset,
+        &asset.id,
         from_ts,
         Some(new_watermark.saturating_add(1)),
     )
@@ -168,9 +173,9 @@ pub(super) async fn append_cache_point(
     if count < min_new {
         return Ok(());
     }
-    let balance = snapshot.checked_add(fold)?;
+    let balance = internals::amount(asset, snapshot.checked_add(fold)?);
     store
-        .append_balance_projection(account, asset, balance, new_watermark)
+        .append_balance_projection(account, balance, new_watermark)
         .await?;
     Ok(())
 }
@@ -183,12 +188,20 @@ impl Ledger {
     /// checks against. Still `O(live postings)`, but the SQL store adds them up
     /// inside the database rather than shipping every row here; prefer
     /// [`balance`](Ledger::balance) for the everyday read.
-    #[instrument(skip(self), name = "ledger.balance_exact")]
     pub async fn balance_exact(
         &self,
         account: &AccountId,
+        asset: impl Into<AssetId>,
+    ) -> Result<Amount, LedgerError> {
+        self.balance_exact_of(account, &asset.into()).await
+    }
+
+    #[instrument(skip(self), name = "ledger.balance_exact")]
+    async fn balance_exact_of(
+        &self,
+        account: &AccountId,
         asset: &AssetId,
-    ) -> Result<Cent, LedgerError> {
+    ) -> Result<Amount, LedgerError> {
         Ok(self.store.live_balance(account, asset).await?)
     }
 
@@ -201,14 +214,27 @@ impl Ledger {
     /// history) and bootstraps a cache point in the background. Once enough
     /// credits/debits have accrued since the closest cache point, it also appends
     /// a new one in the background for later reads.
+    pub async fn balance(
+        &self,
+        account: &AccountId,
+        asset: impl Into<AssetId>,
+    ) -> Result<Amount, LedgerError> {
+        self.balance_of(account, &asset.into()).await
+    }
+
     #[instrument(skip(self), name = "ledger.balance")]
-    pub async fn balance(&self, account: &AccountId, asset: &AssetId) -> Result<Cent, LedgerError> {
+    async fn balance_of(
+        &self,
+        account: &AccountId,
+        asset: &AssetId,
+    ) -> Result<Amount, LedgerError> {
         let now = now_millis()?;
+        let row = self.asset_by_id(asset).await?;
         let closest = self
             .store
             .get_closest_balance_projection(account, asset, now)
             .await?;
-        match closest {
+        let value = match closest {
             Some(p) => {
                 let (tail, count) = fold_tail(
                     self.store(),
@@ -219,20 +245,21 @@ impl Ledger {
                 )
                 .await?;
                 if count >= self.projection.snapshot_interval {
-                    self.spawn_append(*account, *asset);
+                    self.spawn_append(*account, Arc::clone(&row));
                 }
-                Ok(p.balance.checked_add(tail)?)
+                internals::cent(&p.balance).checked_add(tail)?
             }
             // No cache point: the authoritative live sum is O(live postings),
             // cheaper than folding the whole history. Bootstrap a cache point in
             // the background (the append itself gates on `snapshot_interval`, so a
             // small account never actually appends) so later reads use the tail.
             None => {
-                let balance = self.balance_exact(account, asset).await?;
-                self.spawn_append(*account, *asset);
-                Ok(balance)
+                let live = internals::cent(&self.store.live_balance(account, asset).await?);
+                self.spawn_append(*account, Arc::clone(&row));
+                live
             }
-        }
+        };
+        Ok(internals::amount(row, value))
     }
 
     /// The balance as it stood at `as_of`, a commit instant in unix
@@ -249,13 +276,22 @@ impl Ledger {
     /// timestamp, so that sum is always "now". It also appends no cache point,
     /// since a new one's watermark comes from the current clock and would
     /// describe a window this read never looked at.
-    #[instrument(skip(self), name = "ledger.balance_as_of")]
     pub async fn balance_as_of(
         &self,
         account: &AccountId,
+        asset: impl Into<AssetId>,
+        as_of: i64,
+    ) -> Result<Amount, LedgerError> {
+        self.balance_as_of_id(account, &asset.into(), as_of).await
+    }
+
+    #[instrument(skip(self), name = "ledger.balance_as_of")]
+    async fn balance_as_of_id(
+        &self,
+        account: &AccountId,
         asset: &AssetId,
         as_of: i64,
-    ) -> Result<Cent, LedgerError> {
+    ) -> Result<Amount, LedgerError> {
         let closest = self
             .store
             .get_closest_balance_projection(account, asset, as_of)
@@ -269,10 +305,11 @@ impl Ledger {
             Some(as_of.saturating_add(1)),
         )
         .await?;
-        match closest {
-            Some(p) => Ok(p.balance.checked_add(tail)?),
-            None => Ok(tail),
-        }
+        let value = match closest {
+            Some(p) => internals::cent(&p.balance).checked_add(tail)?,
+            None => tail,
+        };
+        Ok(internals::amount(self.asset_by_id(asset).await?, value))
     }
 
     /// Report the per-subaccount balances of a base account for one asset.
@@ -282,10 +319,19 @@ impl Ledger {
     /// `sub == None` spans every subaccount of `account`'s base id; `Some(s)`
     /// restricts to that one. Balances are never summed across subaccounts
     /// (ADR-0012).
-    #[instrument(skip(self), name = "ledger.balances")]
     pub async fn balances(
         &self,
         account: &AccountId,
+        asset: impl Into<AssetId>,
+        sub: Option<i64>,
+    ) -> Result<Vec<SubAccountBalance>, LedgerError> {
+        self.balances_of(account, &asset.into(), sub).await
+    }
+
+    #[instrument(skip(self), name = "ledger.balances")]
+    async fn balances_of(
+        &self,
+        account: &AccountId,
         asset: &AssetId,
         sub: Option<i64>,
     ) -> Result<Vec<SubAccountBalance>, LedgerError> {
@@ -296,10 +342,10 @@ impl Ledger {
             {
                 continue;
             }
-            let value = self.balance(&subaccount, asset).await?;
+            let amount = self.balance_of(&subaccount, asset).await?;
             result.push(SubAccountBalance {
                 account: subaccount,
-                value,
+                amount,
             });
         }
         Ok(result)
@@ -337,17 +383,18 @@ impl Ledger {
     /// point already exists, so a hot account read at high QPS does at most one
     /// fold per grace window, coordinated across every instance rather than in
     /// this process's memory.
-    fn spawn_append(&self, account: AccountId, asset: AssetId) {
+    fn spawn_append(&self, account: AccountId, asset: Arc<Asset>) {
         let store = Arc::clone(&self.store);
         let grace = self.projection.grace_ms;
         let min_new = self.projection.snapshot_interval;
         tokio::spawn(async move {
+            let id = asset.id;
             if let Err(err) =
-                append_cache_point(store.as_ref(), grace, min_new, grace, &account, &asset).await
+                append_cache_point(store.as_ref(), grace, min_new, grace, &account, asset).await
             {
                 // Best effort: a failed append only lengthens a later read's tail.
                 // Log it so a projection that silently stops advancing is visible.
-                tracing::warn!(?account, ?asset, error = %err, "balance projection append failed");
+                tracing::warn!(?account, asset = ?id, error = %err, "balance projection append failed");
             }
         });
     }

+ 48 - 23
crates/kuatia/src/ledger/commit.rs

@@ -12,11 +12,13 @@ use std::collections::HashMap;
 use std::collections::hash_map::Entry;
 use tracing::instrument;
 
+use kuatia_core::internals;
+use kuatia_core::internals::Cent;
 use kuatia_core::{
-    Account, AccountId, AccountSnapshotId, AssetId, Book, Cent, DEFAULT_BOOK, Envelope,
-    EnvelopeBuilder, NewPosting, Plan, PlanInput, Posting, PostingFilter, PostingId, Receipt,
-    ResolveInput, Transfer, TransferId, ValidationError, account_snapshot_id, draft_movements,
-    envelope_id, required_state, resolve_envelope, validate_and_plan,
+    Account, AccountId, AccountSnapshotId, AssetId, Book, DEFAULT_BOOK, Envelope, EnvelopeBuilder,
+    NewPosting, Plan, PlanInput, Posting, PostingFilter, PostingId, Receipt, ResolveInput,
+    Transfer, TransferId, ValidationError, account_snapshot_id, draft_movements, envelope_id,
+    required_state, resolve_envelope, validate_and_plan,
 };
 
 use kuatia_storage::error::StoreError;
@@ -62,8 +64,12 @@ impl Ledger {
 
         let mut balances = HashMap::new();
         for (account_id, asset_id) in &required.balances {
-            let bal = self.balance_exact(account_id, asset_id).await?;
-            balances.insert((*account_id, *asset_id), bal);
+            // The authoritative live sum, taken from the store rather than
+            // through `balance_exact`, so validating a transfer needs no
+            // registry lookup: an amount cannot be built without a registered
+            // asset, so one that reaches here already had one.
+            let bal = self.store.live_balance(account_id, asset_id).await?;
+            balances.insert((*account_id, *asset_id), internals::cent(&bal));
         }
 
         // Load the gating book. A missing named (non-default) book is an error;
@@ -139,11 +145,11 @@ impl Ledger {
                 .get_postings_by_account(
                     debit.account.id,
                     Some(debit.account.sub),
-                    Some(&debit.asset),
+                    Some(&debit.asset()),
                     PostingFilter::Live,
                 )
                 .await?;
-            available.insert((debit.account, debit.asset), postings);
+            available.insert((debit.account, debit.asset()), postings);
             if let Entry::Vacant(e) = accounts.entry(debit.account) {
                 e.insert(self.store.get_account(&debit.account).await?);
             }
@@ -193,6 +199,8 @@ impl Ledger {
             envelope.set_account_snapshots(self.resolve_snapshots(&ids).await?);
         }
 
+        self.require_registered_assets(&envelope).await?;
+
         // Idempotency pre-check: an already-committed transfer returns its receipt
         // without re-validating. The store also guards this atomically.
         let tid = envelope_id(&envelope);
@@ -284,8 +292,7 @@ impl Ledger {
             .iter()
             .map(|p| NewPosting {
                 owner: p.owner,
-                asset: p.asset,
-                value: p.value,
+                amount: p.amount.clone(),
                 payer: None,
             })
             .collect();
@@ -348,10 +355,22 @@ fn map_rejection(reason: CommitRejection) -> LedgerError {
 #[cfg(test)]
 mod tests {
     use super::*;
-    use kuatia_core::{Account, AccountFlags, TransferBuilder};
+    use kuatia_core::{Account, AccountFlags, Amount, Asset, TransferBuilder};
     use kuatia_storage::mem_store::InMemoryStore;
     use std::collections::BTreeMap;
 
+    /// An amount of `asset` in minor units. An amount compares by asset id, so
+    /// building the row here is equivalent to reading it back from the registry.
+    fn money<V>(asset: AssetId, value: V) -> Amount
+    where
+        Amount: From<(V, std::sync::Arc<Asset>)>,
+    {
+        Amount::from((
+            value,
+            std::sync::Arc::new(Asset::new(asset, "TEST", "$", 2)),
+        ))
+    }
+
     fn acct(id: i64, flags: AccountFlags) -> Account {
         Account {
             id: AccountId::new(id),
@@ -372,15 +391,18 @@ mod tests {
         ] {
             ledger.store().create_account(acct(id, p)).await.unwrap();
         }
+        ledger
+            .create_asset(Asset::new(AssetId::new(1), "USD", "$", 2))
+            .await
+            .unwrap();
         let deposit = TransferBuilder::new()
             .deposit(
                 AccountId::new(1),
-                AssetId::new(1),
-                Cent::from(100),
+                money(AssetId::new(1), 100),
                 AccountId::new(99),
             )
-            .unwrap()
-            .build();
+            .build()
+            .unwrap();
         ledger.commit(deposit).await.unwrap();
         ledger
     }
@@ -390,10 +412,10 @@ mod tests {
             .pay(
                 AccountId::new(1),
                 AccountId::new(2),
-                AssetId::new(1),
-                Cent::from(40),
+                money(AssetId::new(1), 40),
             )
             .build()
+            .unwrap()
     }
 
     /// A commit spends the payer's posting and credits the payee atomically.
@@ -405,15 +427,17 @@ mod tests {
             ledger
                 .balance(&AccountId::new(2), &AssetId::new(1))
                 .await
-                .unwrap(),
-            Cent::from(40)
+                .unwrap()
+                .minor_units(),
+            40
         );
         assert_eq!(
             ledger
                 .balance(&AccountId::new(1), &AssetId::new(1))
                 .await
-                .unwrap(),
-            Cent::from(60)
+                .unwrap()
+                .minor_units(),
+            60
         );
     }
 
@@ -431,8 +455,9 @@ mod tests {
             ledger
                 .balance(&AccountId::new(1), &AssetId::new(1))
                 .await
-                .unwrap(),
-            Cent::from(100)
+                .unwrap()
+                .minor_units(),
+            100
         );
     }
 

+ 1 - 1
crates/kuatia/src/ledger/projection.rs

@@ -39,7 +39,7 @@ impl<'a> Projection<'a> {
             0,
             0,
             account,
-            asset,
+            self.ledger.asset_by_id(asset).await?,
         )
         .await
     }

+ 126 - 65
crates/kuatia/tests/concurrency.rs

@@ -20,6 +20,16 @@ use kuatia::ledger::Ledger;
 use kuatia::mem_store::InMemoryStore;
 use kuatia_core::*;
 
+/// An amount of `asset` in minor units. An amount compares by asset id, and the
+/// tests register these same ids, so building the row here is equivalent to
+/// reading it back from the registry.
+fn money<V>(asset: AssetId, value: V) -> Amount
+where
+    Amount: From<(V, Arc<Asset>)>,
+{
+    Amount::from((value, Arc::new(Asset::new(asset, "TEST", "$", 2))))
+}
+
 fn usd() -> AssetId {
     AssetId::new(1)
 }
@@ -42,6 +52,15 @@ fn make_account(id: i64, flags: AccountFlags) -> Account {
     }
 }
 
+/// Register the assets these tests read. A balance read hydrates its asset from
+/// the registry, so an unregistered one has no amount to report.
+async fn register_assets(ledger: &Arc<Ledger>) {
+    ledger
+        .create_asset(Asset::new(usd(), "USD", "$", 2))
+        .await
+        .unwrap();
+}
+
 /// A ledger with overdraft-forbidding accounts `1..=n` plus an external account.
 async fn ledger_with_accounts(n: i64) -> Arc<Ledger> {
     let ledger = Arc::new(Ledger::new(InMemoryStore::new()));
@@ -57,14 +76,15 @@ async fn ledger_with_accounts(n: i64) -> Arc<Ledger> {
         .create_account(make_account(99, AccountFlags::empty()))
         .await
         .unwrap();
+    register_assets(&ledger).await;
     ledger
 }
 
-async fn deposit(ledger: &Arc<Ledger>, to: AccountId, amount: Cent) {
+async fn deposit(ledger: &Arc<Ledger>, to: AccountId, amount: i64) {
     let transfer = TransferBuilder::new()
-        .deposit(to, usd(), amount, external())
-        .unwrap()
-        .build();
+        .deposit(to, money(usd(), amount), external())
+        .build()
+        .unwrap();
     ledger.commit(transfer).await.unwrap();
 }
 
@@ -84,7 +104,7 @@ async fn concurrent_double_spend_has_one_winner() {
     let ledger = ledger_with_accounts(1 + RECIPIENTS).await;
 
     // Account 1 holds a single Active posting of 100.
-    deposit(&ledger, account(1), Cent::from(100)).await;
+    deposit(&ledger, account(1), 100).await;
 
     // Fire one full-balance payment per recipient, all at once.
     let mut handles = Vec::new();
@@ -92,8 +112,9 @@ async fn concurrent_double_spend_has_one_winner() {
         let ledger = Arc::clone(&ledger);
         handles.push(tokio::spawn(async move {
             let transfer = TransferBuilder::new()
-                .pay(account(1), account(recipient), usd(), Cent::from(100))
-                .build();
+                .pay(account(1), account(recipient), money(usd(), 100))
+                .build()
+                .unwrap();
             ledger.commit(transfer).await
         }));
     }
@@ -108,21 +129,29 @@ async fn concurrent_double_spend_has_one_winner() {
 
     // Conservation: payer drained, exactly one recipient credited, total = 100.
     assert_eq!(
-        ledger.balance(&account(1), &usd()).await.unwrap(),
-        Cent::ZERO
+        ledger
+            .balance(&account(1), &usd())
+            .await
+            .unwrap()
+            .minor_units(),
+        0
     );
     let mut credited = 0;
-    let mut total = Cent::ZERO;
+    let mut total: i128 = 0;
     for recipient in 2..=(1 + RECIPIENTS) {
-        let bal = ledger.balance(&account(recipient), &usd()).await.unwrap();
-        if bal != Cent::ZERO {
+        let bal = ledger
+            .balance(&account(recipient), &usd())
+            .await
+            .unwrap()
+            .minor_units();
+        if bal != 0 {
             credited += 1;
-            assert_eq!(bal, Cent::from(100));
+            assert_eq!(bal, 100);
         }
         total = total.checked_add(bal).unwrap();
     }
     assert_eq!(credited, 1, "exactly one recipient is credited");
-    assert_eq!(total, Cent::from(100), "value is conserved");
+    assert_eq!(total, 100, "value is conserved");
 }
 
 // ---------------------------------------------------------------------------
@@ -135,11 +164,12 @@ async fn concurrent_double_spend_has_one_winner() {
 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
 async fn recommit_same_envelope_is_idempotent() {
     let ledger = ledger_with_accounts(2).await;
-    deposit(&ledger, account(1), Cent::from(100)).await;
+    deposit(&ledger, account(1), 100).await;
 
     let transfer = TransferBuilder::new()
-        .pay(account(1), account(2), usd(), Cent::from(50))
-        .build();
+        .pay(account(1), account(2), money(usd(), 50))
+        .build()
+        .unwrap();
     let envelope = ledger.resolve(&transfer).await.unwrap();
 
     let first = ledger.commit_envelope(envelope.clone()).await.unwrap();
@@ -147,12 +177,20 @@ async fn recommit_same_envelope_is_idempotent() {
 
     assert_eq!(first, second, "replay returns the original receipt");
     assert_eq!(
-        ledger.balance(&account(1), &usd()).await.unwrap(),
-        Cent::from(50)
+        ledger
+            .balance(&account(1), &usd())
+            .await
+            .unwrap()
+            .minor_units(),
+        50
     );
     assert_eq!(
-        ledger.balance(&account(2), &usd()).await.unwrap(),
-        Cent::from(50)
+        ledger
+            .balance(&account(2), &usd())
+            .await
+            .unwrap()
+            .minor_units(),
+        50
     );
 }
 
@@ -165,11 +203,12 @@ async fn recommit_same_envelope_is_idempotent() {
 async fn concurrent_identical_commits_move_value_once() {
     const TASKS: usize = 8;
     let ledger = ledger_with_accounts(2).await;
-    deposit(&ledger, account(1), Cent::from(100)).await;
+    deposit(&ledger, account(1), 100).await;
 
     let transfer = TransferBuilder::new()
-        .pay(account(1), account(2), usd(), Cent::from(50))
-        .build();
+        .pay(account(1), account(2), money(usd(), 50))
+        .build()
+        .unwrap();
     let envelope = ledger.resolve(&transfer).await.unwrap();
 
     let mut handles = Vec::new();
@@ -197,12 +236,20 @@ async fn concurrent_identical_commits_move_value_once() {
 
     // Value moved exactly once, and exactly one transfer is stored.
     assert_eq!(
-        ledger.balance(&account(1), &usd()).await.unwrap(),
-        Cent::from(50)
+        ledger
+            .balance(&account(1), &usd())
+            .await
+            .unwrap()
+            .minor_units(),
+        50
     );
     assert_eq!(
-        ledger.balance(&account(2), &usd()).await.unwrap(),
-        Cent::from(50)
+        ledger
+            .balance(&account(2), &usd())
+            .await
+            .unwrap()
+            .minor_units(),
+        50
     );
     assert!(
         ledger
@@ -232,7 +279,7 @@ async fn freeze_during_commit_stays_consistent() {
     // Race is timing-dependent; run several fresh rounds to sample interleavings.
     for _ in 0..24 {
         let ledger = ledger_with_accounts(2).await;
-        deposit(&ledger, account(1), Cent::from(100)).await;
+        deposit(&ledger, account(1), 100).await;
 
         let freezer = {
             let ledger = Arc::clone(&ledger);
@@ -242,36 +289,46 @@ async fn freeze_during_commit_stays_consistent() {
             let ledger = Arc::clone(&ledger);
             tokio::spawn(async move {
                 let transfer = TransferBuilder::new()
-                    .pay(account(1), account(2), usd(), Cent::from(50))
-                    .build();
+                    .pay(account(1), account(2), money(usd(), 50))
+                    .build()
+                    .unwrap();
                 ledger.commit(transfer).await
             })
         };
         freezer.await.unwrap().expect("freeze always succeeds");
         let paid = payer.await.unwrap().is_ok();
 
-        let b1 = ledger.balance(&account(1), &usd()).await.unwrap();
-        let b2 = ledger.balance(&account(2), &usd()).await.unwrap();
+        let b1 = ledger
+            .balance(&account(1), &usd())
+            .await
+            .unwrap()
+            .minor_units();
+        let b2 = ledger
+            .balance(&account(2), &usd())
+            .await
+            .unwrap()
+            .minor_units();
 
         // Conservation and all-or-nothing, keyed on whether the pay committed.
         assert_eq!(
             b1.checked_add(b2).unwrap(),
-            Cent::from(100),
+            100,
             "value is conserved regardless of who won"
         );
         if paid {
-            assert_eq!(b1, Cent::from(50));
-            assert_eq!(b2, Cent::from(50));
+            assert_eq!(b1, 50);
+            assert_eq!(b2, 50);
         } else {
-            assert_eq!(b1, Cent::from(100));
-            assert_eq!(b2, Cent::ZERO);
+            assert_eq!(b1, 100);
+            assert_eq!(b2, 0);
         }
 
         // The account is frozen either way; no further payment may leave it.
         assert!(ledger.get_account(&account(1)).await.unwrap().is_frozen());
         let after = TransferBuilder::new()
-            .pay(account(1), account(2), usd(), Cent::from(10))
-            .build();
+            .pay(account(1), account(2), money(usd(), 10))
+            .build()
+            .unwrap();
         assert!(
             ledger.commit(after).await.is_err(),
             "a frozen account cannot pay"
@@ -293,7 +350,7 @@ async fn disjoint_transfers_all_commit_and_conserve() {
     // Accounts 1..=2*PAIRS: odd = payer (funded), even = payee.
     let ledger = ledger_with_accounts(2 * PAIRS).await;
     for k in 0..PAIRS {
-        deposit(&ledger, account(2 * k + 1), Cent::from(100)).await;
+        deposit(&ledger, account(2 * k + 1), 100).await;
     }
 
     let mut handles = Vec::new();
@@ -301,13 +358,9 @@ async fn disjoint_transfers_all_commit_and_conserve() {
         let ledger = Arc::clone(&ledger);
         handles.push(tokio::spawn(async move {
             let transfer = TransferBuilder::new()
-                .pay(
-                    account(2 * k + 1),
-                    account(2 * k + 2),
-                    usd(),
-                    Cent::from(100),
-                )
-                .build();
+                .pay(account(2 * k + 1), account(2 * k + 2), money(usd(), 100))
+                .build()
+                .unwrap();
             ledger.commit(transfer).await
         }));
     }
@@ -315,18 +368,18 @@ async fn disjoint_transfers_all_commit_and_conserve() {
         h.await.unwrap().expect("disjoint transfers never contend");
     }
 
-    let mut total = Cent::ZERO;
+    let mut total: i128 = 0;
     for id in 1..=(2 * PAIRS) {
-        let bal = ledger.balance(&account(id), &usd()).await.unwrap();
-        let expected = if id % 2 == 0 {
-            Cent::from(100)
-        } else {
-            Cent::ZERO
-        };
+        let bal = ledger
+            .balance(&account(id), &usd())
+            .await
+            .unwrap()
+            .minor_units();
+        let expected = if id % 2 == 0 { 100 } else { 0 };
         assert_eq!(bal, expected, "account {id} settled");
         total = total.checked_add(bal).unwrap();
     }
-    assert_eq!(total, Cent::from(100 * PAIRS), "value is conserved");
+    assert_eq!(total, i128::from(100 * PAIRS), "value is conserved");
 }
 
 // ---------------------------------------------------------------------------
@@ -342,6 +395,7 @@ async fn concurrent_overdraft_conserves_value() {
     const PAYEES: i64 = 8;
     for _ in 0..64 {
         let ledger = Arc::new(Ledger::new(InMemoryStore::new()));
+        register_assets(&ledger).await;
         // Account 1 permits overdraft (the default); payees forbid it.
         ledger
             .store()
@@ -368,8 +422,9 @@ async fn concurrent_overdraft_conserves_value() {
             let ledger = Arc::clone(&ledger);
             handles.push(tokio::spawn(async move {
                 let transfer = TransferBuilder::new()
-                    .pay(account(1), account(payee), usd(), Cent::from(60))
-                    .build();
+                    .pay(account(1), account(payee), money(usd(), 60))
+                    .build()
+                    .unwrap();
                 ledger.commit(transfer).await
             }));
         }
@@ -377,16 +432,22 @@ async fn concurrent_overdraft_conserves_value() {
             let _ = h.await.unwrap();
         }
 
-        let mut total = ledger.balance(&account(1), &usd()).await.unwrap();
+        let mut total = ledger
+            .balance(&account(1), &usd())
+            .await
+            .unwrap()
+            .minor_units();
         for payee in 2..=(1 + PAYEES) {
             total = total
-                .checked_add(ledger.balance(&account(payee), &usd()).await.unwrap())
+                .checked_add(
+                    ledger
+                        .balance(&account(payee), &usd())
+                        .await
+                        .unwrap()
+                        .minor_units(),
+                )
                 .unwrap();
         }
-        assert_eq!(
-            total,
-            Cent::ZERO,
-            "value is conserved under concurrent overdraft"
-        );
+        assert_eq!(total, 0, "value is conserved under concurrent overdraft");
     }
 }

+ 89 - 56
crates/kuatia/tests/inflight.rs

@@ -18,6 +18,16 @@ use std::sync::Arc;
 
 use kuatia::prelude::*;
 
+/// An amount of `asset` in minor units. An amount compares by asset id, and the
+/// tests register these same ids, so building the row here is equivalent to
+/// reading it back from the registry.
+fn money<V>(asset: AssetId, value: V) -> Amount
+where
+    Amount: From<(V, Arc<Asset>)>,
+{
+    Amount::from((value, Arc::new(Asset::new(asset, "TEST", "$", 2))))
+}
+
 fn eur() -> AssetId {
     AssetId::new(1)
 }
@@ -49,9 +59,9 @@ fn make_account(id: i64, flags: AccountFlags) -> Account {
 
 async fn deposit(ledger: &Arc<Ledger>, to: AccountId, asset: AssetId, amount: i64) {
     let t = TransferBuilder::new()
-        .deposit(to, asset, Cent::from(amount), ext())
-        .unwrap()
-        .build();
+        .deposit(to, money(asset, amount), ext())
+        .build()
+        .unwrap();
     ledger.commit(t).await.unwrap();
 }
 
@@ -71,6 +81,12 @@ async fn setup() -> Arc<Ledger> {
         .create_account(make_account(99, AccountFlags::empty()))
         .await
         .unwrap();
+    for asset in [
+        Asset::new(eur(), "EUR", "\u{20ac}", 2),
+        Asset::new(btc(), "BTC", "\u{20bf}", 8),
+    ] {
+        ledger.create_asset(asset).await.unwrap();
+    }
     deposit(&ledger, a(), eur(), 100).await;
     deposit(&ledger, a(), btc(), 1).await;
     deposit(&ledger, b(), btc(), 10).await;
@@ -80,23 +96,29 @@ async fn setup() -> Arc<Ledger> {
 
 fn trade() -> Transfer {
     TransferBuilder::new()
-        .pay(a(), b(), eur(), Cent::from(100))
-        .pay(b(), a(), btc(), Cent::from(10))
-        .pay(a(), fee(), btc(), Cent::from(1))
-        .pay(b(), fee(), eur(), Cent::from(1))
+        .pay(a(), b(), money(eur(), 100))
+        .pay(b(), a(), money(btc(), 10))
+        .pay(a(), fee(), money(btc(), 1))
+        .pay(b(), fee(), money(eur(), 1))
         .build()
+        .unwrap()
 }
 
-async fn bal(ledger: &Arc<Ledger>, account: AccountId, asset: AssetId) -> Cent {
-    ledger.balance(&account, &asset).await.unwrap()
+async fn bal(ledger: &Arc<Ledger>, account: AccountId, asset: AssetId) -> i128 {
+    ledger
+        .balance(&account, &asset)
+        .await
+        .unwrap()
+        .minor_units()
 }
 
 /// A one-movement confirm set, built with the same `.pay()` interface as a
 /// transfer: `from` is the leg's funder, `to` its destination.
 fn confirm_one(from: AccountId, to: AccountId, asset: AssetId, amount: i64) -> Transfer {
     TransferBuilder::new()
-        .pay(from, to, asset, Cent::from(amount))
+        .pay(from, to, money(asset, amount))
         .build()
+        .unwrap()
 }
 
 /// After authorize, funds leave the payers and sit in the holds; the payers'
@@ -107,21 +129,29 @@ async fn authorize_parks_funds_in_holds() {
     let auth = ledger.authorize(trade()).await.unwrap();
 
     // Payers emptied.
-    assert_eq!(bal(&ledger, a(), eur()).await, Cent::ZERO);
-    assert_eq!(bal(&ledger, a(), btc()).await, Cent::ZERO);
-    assert_eq!(bal(&ledger, b(), eur()).await, Cent::ZERO);
-    assert_eq!(bal(&ledger, b(), btc()).await, Cent::ZERO);
+    assert_eq!(bal(&ledger, a(), eur()).await, 0);
+    assert_eq!(bal(&ledger, a(), btc()).await, 0);
+    assert_eq!(bal(&ledger, b(), eur()).await, 0);
+    assert_eq!(bal(&ledger, b(), btc()).await, 0);
 
     // Destinations untouched.
-    assert_eq!(bal(&ledger, b(), eur()).await, Cent::ZERO);
-    assert_eq!(bal(&ledger, fee(), eur()).await, Cent::ZERO);
+    assert_eq!(bal(&ledger, b(), eur()).await, 0);
+    assert_eq!(bal(&ledger, fee(), eur()).await, 0);
 
     // Three holds are open, and status reports everything Held.
     assert_eq!(ledger.list_open_inflights().await.unwrap().len(), 3);
     let status = ledger.inflight_status(&auth.inflight).await.unwrap();
     assert_eq!(status.state, InflightState::Held);
-    let total_held: Cent = Cent::checked_sum(status.legs.iter().map(|l| l.held)).unwrap();
-    let total_auth: Cent = Cent::checked_sum(status.legs.iter().map(|l| l.authorized)).unwrap();
+    let total_held = status
+        .legs
+        .iter()
+        .map(|l| l.held.minor_units())
+        .sum::<i128>();
+    let total_auth = status
+        .legs
+        .iter()
+        .map(|l| l.authorized.minor_units())
+        .sum::<i128>();
     assert_eq!(total_held, total_auth);
 }
 
@@ -134,10 +164,10 @@ async fn confirm_all_settles_to_destinations() {
 
     ledger.confirm_all(&auth.inflight).await.unwrap();
 
-    assert_eq!(bal(&ledger, b(), eur()).await, Cent::from(100));
-    assert_eq!(bal(&ledger, a(), btc()).await, Cent::from(10));
-    assert_eq!(bal(&ledger, fee(), eur()).await, Cent::from(1));
-    assert_eq!(bal(&ledger, fee(), btc()).await, Cent::from(1));
+    assert_eq!(bal(&ledger, b(), eur()).await, 100);
+    assert_eq!(bal(&ledger, a(), btc()).await, 10);
+    assert_eq!(bal(&ledger, fee(), eur()).await, 1);
+    assert_eq!(bal(&ledger, fee(), btc()).await, 1);
 
     // Holds drained and closed.
     assert!(ledger.list_open_inflights().await.unwrap().is_empty());
@@ -155,12 +185,12 @@ async fn void_returns_funds_to_funders() {
     ledger.void(&auth.inflight).await.unwrap();
 
     // Everyone is back where they started.
-    assert_eq!(bal(&ledger, a(), eur()).await, Cent::from(100));
-    assert_eq!(bal(&ledger, a(), btc()).await, Cent::from(1));
-    assert_eq!(bal(&ledger, b(), btc()).await, Cent::from(10));
-    assert_eq!(bal(&ledger, b(), eur()).await, Cent::from(1));
-    assert_eq!(bal(&ledger, fee(), eur()).await, Cent::ZERO);
-    assert_eq!(bal(&ledger, fee(), btc()).await, Cent::ZERO);
+    assert_eq!(bal(&ledger, a(), eur()).await, 100);
+    assert_eq!(bal(&ledger, a(), btc()).await, 1);
+    assert_eq!(bal(&ledger, b(), btc()).await, 10);
+    assert_eq!(bal(&ledger, b(), eur()).await, 1);
+    assert_eq!(bal(&ledger, fee(), eur()).await, 0);
+    assert_eq!(bal(&ledger, fee(), btc()).await, 0);
 
     assert!(ledger.list_open_inflights().await.unwrap().is_empty());
     let status = ledger.inflight_status(&auth.inflight).await.unwrap();
@@ -178,18 +208,18 @@ async fn partial_confirm_then_confirm_remainder() {
         .confirm(&auth.inflight, confirm_one(a(), b(), eur(), 40))
         .await
         .unwrap();
-    assert_eq!(bal(&ledger, b(), eur()).await, Cent::from(40));
+    assert_eq!(bal(&ledger, b(), eur()).await, 40);
 
     // The B/EUR leg is partially confirmed.
     let status = ledger.inflight_status(&auth.inflight).await.unwrap();
     let leg = status
         .legs
         .iter()
-        .find(|l| l.destination.id == b().id && l.asset == eur())
+        .find(|l| l.destination.id == b().id && l.held.asset_id() == eur())
         .unwrap();
-    assert_eq!(leg.authorized, Cent::from(100));
-    assert_eq!(leg.confirmed, Cent::from(40));
-    assert_eq!(leg.held, Cent::from(60));
+    assert_eq!(leg.authorized.minor_units(), 100);
+    assert_eq!(leg.confirmed.minor_units(), 40);
+    assert_eq!(leg.held.minor_units(), 60);
     assert_eq!(status.state, InflightState::PartiallyConfirmed);
 
     // Confirm the rest.
@@ -197,7 +227,7 @@ async fn partial_confirm_then_confirm_remainder() {
         .confirm(&auth.inflight, confirm_one(a(), b(), eur(), 60))
         .await
         .unwrap();
-    assert_eq!(bal(&ledger, b(), eur()).await, Cent::from(100));
+    assert_eq!(bal(&ledger, b(), eur()).await, 100);
     // The B hold is now closed (its only asset drained).
     assert!(
         !ledger
@@ -224,18 +254,18 @@ async fn partial_confirm_then_void_remainder() {
     // B kept the confirmed 40 EUR from its own hold, and got its 1 EUR fee
     // contribution back from the (now voided) fee hold: 41 total. A got the
     // remaining 60 EUR of B's hold back.
-    assert_eq!(bal(&ledger, b(), eur()).await, Cent::from(41));
-    assert_eq!(bal(&ledger, a(), eur()).await, Cent::from(60));
+    assert_eq!(bal(&ledger, b(), eur()).await, 41);
+    assert_eq!(bal(&ledger, a(), eur()).await, 60);
 
     let status = ledger.inflight_status(&auth.inflight).await.unwrap();
     let leg = status
         .legs
         .iter()
-        .find(|l| l.destination.id == b().id && l.asset == eur())
+        .find(|l| l.destination.id == b().id && l.held.asset_id() == eur())
         .unwrap();
-    assert_eq!(leg.confirmed, Cent::from(40));
-    assert_eq!(leg.voided, Cent::from(60));
-    assert_eq!(leg.held, Cent::ZERO);
+    assert_eq!(leg.confirmed.minor_units(), 40);
+    assert_eq!(leg.voided.minor_units(), 60);
+    assert_eq!(leg.held.minor_units(), 0);
     assert_eq!(status.state, InflightState::Mixed);
 }
 
@@ -252,7 +282,7 @@ async fn over_confirm_is_rejected() {
         .unwrap_err();
     assert!(matches!(err, LedgerError::Selection(_)));
     // Nothing moved.
-    assert_eq!(bal(&ledger, b(), eur()).await, Cent::ZERO);
+    assert_eq!(bal(&ledger, b(), eur()).await, 0);
 }
 
 /// A single confirm call settles several legs at once, built with the same
@@ -264,17 +294,18 @@ async fn batch_confirm_multiple_legs() {
 
     // Confirm B's EUR leg and A's BTC leg in one call.
     let confirms = TransferBuilder::new()
-        .pay(a(), b(), eur(), Cent::from(100))
-        .pay(b(), a(), btc(), Cent::from(10))
-        .build();
+        .pay(a(), b(), money(eur(), 100))
+        .pay(b(), a(), money(btc(), 10))
+        .build()
+        .unwrap();
     let receipts = ledger.confirm(&auth.inflight, confirms).await.unwrap();
     assert_eq!(receipts.len(), 2);
 
-    assert_eq!(bal(&ledger, b(), eur()).await, Cent::from(100));
-    assert_eq!(bal(&ledger, a(), btc()).await, Cent::from(10));
+    assert_eq!(bal(&ledger, b(), eur()).await, 100);
+    assert_eq!(bal(&ledger, a(), btc()).await, 10);
     // The fee hold is untouched, so it is still open.
-    assert_eq!(bal(&ledger, fee(), eur()).await, Cent::ZERO);
-    assert_eq!(bal(&ledger, fee(), btc()).await, Cent::ZERO);
+    assert_eq!(bal(&ledger, fee(), eur()).await, 0);
+    assert_eq!(bal(&ledger, fee(), btc()).await, 0);
     assert_eq!(ledger.list_open_inflights().await.unwrap().len(), 1);
 
     let status = ledger.inflight_status(&auth.inflight).await.unwrap();
@@ -311,8 +342,9 @@ async fn concurrent_inflights_per_account() {
     // inflight under a different subaccount.
     deposit(&ledger, a(), eur(), 10).await;
     let other = TransferBuilder::new()
-        .pay(a(), b(), eur(), Cent::from(10))
-        .build();
+        .pay(a(), b(), money(eur(), 10))
+        .build()
+        .unwrap();
     let auth2 = ledger.authorize(other).await.unwrap();
     assert_ne!(auth.inflight, auth2.inflight);
 
@@ -337,12 +369,13 @@ async fn reauthorize_after_settlement() {
 
     // B now holds 100 EUR; authorize a new hold of 30 of it to fee.
     let again = TransferBuilder::new()
-        .pay(b(), fee(), eur(), Cent::from(30))
-        .build();
+        .pay(b(), fee(), money(eur(), 30))
+        .build()
+        .unwrap();
     let auth2 = ledger.authorize(again).await.unwrap();
-    assert_eq!(bal(&ledger, b(), eur()).await, Cent::from(70));
+    assert_eq!(bal(&ledger, b(), eur()).await, 70);
     ledger.confirm_all(&auth2.inflight).await.unwrap();
-    assert_eq!(bal(&ledger, fee(), eur()).await, Cent::from(31));
+    assert_eq!(bal(&ledger, fee(), eur()).await, 31);
 }
 
 /// Operating on a non-inflight or unknown transfer id is a clean error.
@@ -366,9 +399,9 @@ async fn balances_are_segregated_by_subaccount() {
     // B's EUR across subaccounts: the main (0, now empty) and its inflight hold.
     let all = ledger.balances(&b(), &eur(), None).await.unwrap();
     let main = all.iter().find(|e| e.account.sub == 0).unwrap();
-    assert_eq!(main.value, Cent::ZERO); // B's own 1 EUR went into the fee hold
+    assert_eq!(main.amount.minor_units(), 0); // B's own 1 EUR went into the fee hold
     let hold = all.iter().find(|e| e.account.sub != 0).unwrap();
-    assert_eq!(hold.value, Cent::from(100)); // A's 100 EUR parked for B
+    assert_eq!(hold.amount.minor_units(), 100); // A's 100 EUR parked for B
     assert_eq!(all.len(), 2);
 
     // Filtering to the main subaccount returns only it (still segregated form).

Разница между файлами не показана из-за своего большого размера
+ 372 - 169
crates/kuatia/tests/integration.rs


+ 158 - 50
crates/kuatia/tests/projection.rs

@@ -10,10 +10,31 @@ use kuatia::ledger::{Ledger, ProjectionConfig};
 use kuatia::mem_store::InMemoryStore;
 use kuatia_core::*;
 
+/// An amount of `asset` in minor units. An amount compares by asset id, and the
+/// tests register these same ids, so building the row here is equivalent to
+/// reading it back from the registry.
+fn money<V>(asset: AssetId, value: V) -> Amount
+where
+    Amount: From<(V, Arc<Asset>)>,
+{
+    Amount::from((value, Arc::new(Asset::new(asset, "TEST", "$", 2))))
+}
+
 fn usd() -> AssetId {
     AssetId::new(1)
 }
 
+/// Register the assets these tests read. A balance read hydrates its asset from
+/// the registry, so an unregistered one has no amount to report.
+async fn register_assets(ledger: &Arc<Ledger>) {
+    for (id, code, decimals) in [(1, "USD", 2), (2, "EUR", 2)] {
+        ledger
+            .create_asset(Asset::new(AssetId::new(id), code, "$", decimals))
+            .await
+            .unwrap();
+    }
+}
+
 fn account(id: i64) -> AccountId {
     AccountId::new(id)
 }
@@ -40,9 +61,9 @@ async fn overdraft(ledger: &Arc<Ledger>, id: i64) {
 
 async fn deposit(ledger: &Arc<Ledger>, to: i64, amount: i64) {
     let transfer = TransferBuilder::new()
-        .deposit(account(to), usd(), Cent::from(amount), external())
-        .unwrap()
-        .build();
+        .deposit(account(to), money(usd(), amount), external())
+        .build()
+        .unwrap();
     ledger.commit(transfer).await.unwrap();
 }
 
@@ -57,8 +78,9 @@ fn unix_millis_now() -> i64 {
 
 async fn pay(ledger: &Arc<Ledger>, from: i64, to: i64, amount: i64) {
     let transfer = TransferBuilder::new()
-        .pay(account(from), account(to), usd(), Cent::from(amount))
-        .build();
+        .pay(account(from), account(to), money(usd(), amount))
+        .build()
+        .unwrap();
     ledger.commit(transfer).await.unwrap();
 }
 
@@ -66,8 +88,16 @@ async fn pay(ledger: &Arc<Ledger>, from: i64, to: i64, amount: i64) {
 /// for every account, at every asset it might hold.
 async fn assert_projection_matches(ledger: &Arc<Ledger>, ids: &[i64]) {
     for &id in ids {
-        let authoritative = ledger.balance_exact(&account(id), &usd()).await.unwrap();
-        let projected = ledger.balance(&account(id), &usd()).await.unwrap();
+        let authoritative = ledger
+            .balance_exact(&account(id), &usd())
+            .await
+            .unwrap()
+            .minor_units();
+        let projected = ledger
+            .balance(&account(id), &usd())
+            .await
+            .unwrap()
+            .minor_units();
         assert_eq!(
             projected, authoritative,
             "projected balance for account {id} diverged from the live sum"
@@ -81,6 +111,7 @@ async fn assert_projection_matches(ledger: &Arc<Ledger>, ids: &[i64]) {
 #[tokio::test]
 async fn projected_balance_matches_live_sum_without_refresh() {
     let ledger = Arc::new(Ledger::new(InMemoryStore::new()));
+    register_assets(&ledger).await;
     no_overdraft(&ledger, 1).await;
     no_overdraft(&ledger, 2).await;
     overdraft(&ledger, 10).await;
@@ -110,6 +141,7 @@ async fn append_cache_point_snapshots_balance_and_preserves_answer() {
             ..ProjectionConfig::default()
         },
     ));
+    register_assets(&ledger).await;
     no_overdraft(&ledger, 1).await;
     no_overdraft(&ledger, 2).await;
     overdraft(&ledger, 99).await;
@@ -131,10 +163,14 @@ async fn append_cache_point_snapshots_balance_and_preserves_answer() {
         .await
         .unwrap()
         .expect("a cache point exists after append");
-    assert_eq!(cache_point.balance, Cent::from(650));
+    assert_eq!(cache_point.balance, money(usd(), 650));
     assert_eq!(
-        ledger.balance(&account(1), &usd()).await.unwrap(),
-        Cent::from(650)
+        ledger
+            .balance(&account(1), &usd())
+            .await
+            .unwrap()
+            .minor_units(),
+        650
     );
     assert_projection_matches(&ledger, &[1, 2]).await;
 }
@@ -143,6 +179,7 @@ async fn append_cache_point_snapshots_balance_and_preserves_answer() {
 #[tokio::test]
 async fn commit_does_not_write_cache_point() {
     let ledger = Arc::new(Ledger::new(InMemoryStore::new()));
+    register_assets(&ledger).await;
     no_overdraft(&ledger, 1).await;
     no_overdraft(&ledger, 2).await;
     overdraft(&ledger, 99).await;
@@ -172,6 +209,7 @@ async fn read_appends_cache_point_after_interval() {
             snapshot_interval: 1,
         },
     ));
+    register_assets(&ledger).await;
     no_overdraft(&ledger, 1).await;
     no_overdraft(&ledger, 2).await;
     overdraft(&ledger, 99).await;
@@ -180,7 +218,11 @@ async fn read_appends_cache_point_after_interval() {
     pay(&ledger, 1, 2, 250).await;
 
     // This read folds >= 1 credit/debit for account 1, so it spawns an append.
-    let _ = ledger.balance(&account(1), &usd()).await.unwrap();
+    let _ = ledger
+        .balance(&account(1), &usd())
+        .await
+        .unwrap()
+        .minor_units();
 
     // Let the background append run, then confirm a cache point exists.
     let mut appeared = false;
@@ -202,8 +244,16 @@ async fn read_appends_cache_point_after_interval() {
         "a read past the interval should append a cache point"
     );
     assert_eq!(
-        ledger.balance(&account(1), &usd()).await.unwrap(),
-        ledger.balance_exact(&account(1), &usd()).await.unwrap()
+        ledger
+            .balance(&account(1), &usd())
+            .await
+            .unwrap()
+            .minor_units(),
+        ledger
+            .balance_exact(&account(1), &usd())
+            .await
+            .unwrap()
+            .minor_units()
     );
 }
 
@@ -218,6 +268,7 @@ async fn read_below_interval_appends_nothing() {
             snapshot_interval: 1_000,
         },
     ));
+    register_assets(&ledger).await;
     no_overdraft(&ledger, 1).await;
     no_overdraft(&ledger, 2).await;
     overdraft(&ledger, 99).await;
@@ -226,10 +277,18 @@ async fn read_below_interval_appends_nothing() {
     pay(&ledger, 1, 2, 250).await;
 
     // A handful of credits/debits, far below the 1000 interval.
-    let bal = ledger.balance(&account(1), &usd()).await.unwrap();
+    let bal = ledger
+        .balance(&account(1), &usd())
+        .await
+        .unwrap()
+        .minor_units();
     assert_eq!(
         bal,
-        ledger.balance_exact(&account(1), &usd()).await.unwrap()
+        ledger
+            .balance_exact(&account(1), &usd())
+            .await
+            .unwrap()
+            .minor_units()
     );
 
     // Even after the background task has every chance to run, no cache point was
@@ -258,6 +317,7 @@ async fn read_below_interval_appends_nothing() {
 #[tokio::test]
 async fn snapshot_plus_nonempty_tail_matches_live_sum() {
     let ledger = Arc::new(Ledger::new(InMemoryStore::new()));
+    register_assets(&ledger).await;
     no_overdraft(&ledger, 1).await;
     no_overdraft(&ledger, 2).await;
     overdraft(&ledger, 99).await;
@@ -274,7 +334,7 @@ async fn snapshot_plus_nonempty_tail_matches_live_sum() {
     let watermark = unix_millis_now();
     ledger
         .store()
-        .append_balance_projection(&account(1), &usd(), snapshot, watermark)
+        .append_balance_projection(&account(1), snapshot.clone(), watermark)
         .await
         .unwrap();
 
@@ -289,8 +349,16 @@ async fn snapshot_plus_nonempty_tail_matches_live_sum() {
     deposit(&ledger, 1, 500).await;
 
     // The read is snapshot + folded tail, and still equals the live sum.
-    let projected = ledger.balance(&account(1), &usd()).await.unwrap();
-    let authoritative = ledger.balance_exact(&account(1), &usd()).await.unwrap();
+    let projected = ledger
+        .balance(&account(1), &usd())
+        .await
+        .unwrap()
+        .minor_units();
+    let authoritative = ledger
+        .balance_exact(&account(1), &usd())
+        .await
+        .unwrap()
+        .minor_units();
     assert_eq!(
         projected, authoritative,
         "snapshot + non-empty tail diverged from the live sum"
@@ -299,7 +367,8 @@ async fn snapshot_plus_nonempty_tail_matches_live_sum() {
     // actually carried value. Otherwise this silently degrades to the empty-tail
     // case the other tests already cover.
     assert_ne!(
-        snapshot, authoritative,
+        snapshot.minor_units(),
+        authoritative,
         "the snapshot already held the full balance; the tail was empty"
     );
     assert_projection_matches(&ledger, &[1, 2]).await;
@@ -343,6 +412,7 @@ async fn projection_matches_live_sum_across_random_utxo_history() {
             ..ProjectionConfig::default()
         },
     ));
+    register_assets(&ledger).await;
 
     // Accounts under test, including two subaccounts and both overdraft kinds.
     let no_overdraft_ids = [
@@ -395,9 +465,9 @@ async fn projection_matches_live_sum_across_random_utxo_history() {
                 let to = accounts[rng.below(accounts.len() as u64) as usize];
                 let amount = 1 + rng.below(500) as i64;
                 let t = TransferBuilder::new()
-                    .deposit(to, asset, Cent::from(amount), ext)
-                    .unwrap()
-                    .build();
+                    .deposit(to, money(asset, amount), ext)
+                    .build()
+                    .unwrap();
                 if let Ok(r) = ledger.commit(t).await {
                     receipts.push(r.transfer_id);
                 }
@@ -407,8 +477,9 @@ async fn projection_matches_live_sum_across_random_utxo_history() {
                 let from = accounts[rng.below(accounts.len() as u64) as usize];
                 let amount = 1 + rng.below(200) as i64;
                 let t = TransferBuilder::new()
-                    .withdraw(from, asset, Cent::from(amount), ext)
-                    .build();
+                    .withdraw(from, money(asset, amount), ext)
+                    .build()
+                    .unwrap();
                 if let Ok(r) = ledger.commit(t).await {
                     receipts.push(r.transfer_id);
                 }
@@ -429,8 +500,9 @@ async fn projection_matches_live_sum_across_random_utxo_history() {
                 }
                 let amount = 1 + rng.below(300) as i64;
                 let t = TransferBuilder::new()
-                    .pay(from, to, asset, Cent::from(amount))
-                    .build();
+                    .pay(from, to, money(asset, amount))
+                    .build()
+                    .unwrap();
                 if let Ok(r) = ledger.commit(t).await {
                     receipts.push(r.transfer_id);
                 }
@@ -441,8 +513,12 @@ async fn projection_matches_live_sum_across_random_utxo_history() {
         // the authoritative live-posting sum for every (account, asset).
         for account in accounts.iter().chain(std::iter::once(&ext)) {
             for asset in &assets {
-                let authoritative = ledger.balance_exact(account, asset).await.unwrap();
-                let projected = ledger.balance(account, asset).await.unwrap();
+                let authoritative = ledger
+                    .balance_exact(account, asset)
+                    .await
+                    .unwrap()
+                    .minor_units();
+                let projected = ledger.balance(account, asset).await.unwrap().minor_units();
                 assert_eq!(
                     projected, authoritative,
                     "projected != live sum for {account:?} / {asset:?}"
@@ -457,6 +533,7 @@ async fn projection_matches_live_sum_across_random_utxo_history() {
 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
 async fn projection_matches_under_concurrent_commits() {
     let ledger = Arc::new(Ledger::new(InMemoryStore::new()));
+    register_assets(&ledger).await;
     no_overdraft(&ledger, 1).await;
     for id in 2..=9 {
         no_overdraft(&ledger, id).await;
@@ -469,8 +546,9 @@ async fn projection_matches_under_concurrent_commits() {
         let ledger = Arc::clone(&ledger);
         handles.push(tokio::spawn(async move {
             let transfer = TransferBuilder::new()
-                .pay(account(1), account(payee), usd(), Cent::from(10))
-                .build();
+                .pay(account(1), account(payee), money(usd(), 10))
+                .build()
+                .unwrap();
             let _ = ledger.commit(transfer).await;
         }));
     }
@@ -488,6 +566,7 @@ async fn projection_matches_under_concurrent_commits() {
 #[tokio::test]
 async fn balance_as_of_excludes_later_commits() {
     let ledger = Arc::new(Ledger::new(InMemoryStore::new()));
+    register_assets(&ledger).await;
     no_overdraft(&ledger, 1).await;
     no_overdraft(&ledger, 2).await;
     overdraft(&ledger, 99).await;
@@ -503,13 +582,18 @@ async fn balance_as_of_excludes_later_commits() {
         ledger
             .balance_as_of(&account(1), &usd(), as_of)
             .await
-            .unwrap(),
-        Cent::from(750),
+            .unwrap()
+            .minor_units(),
+        750,
         "the as-of read picked up a transfer committed after it"
     );
     assert_eq!(
-        ledger.balance(&account(1), &usd()).await.unwrap(),
-        Cent::from(1250)
+        ledger
+            .balance(&account(1), &usd())
+            .await
+            .unwrap()
+            .minor_units(),
+        1250
     );
 }
 
@@ -522,6 +606,7 @@ async fn balance_as_of_excludes_later_commits() {
 #[tokio::test]
 async fn balance_as_of_folds_a_bounded_tail_onto_its_cache_point() {
     let ledger = Arc::new(Ledger::new(InMemoryStore::new()));
+    register_assets(&ledger).await;
     no_overdraft(&ledger, 1).await;
     no_overdraft(&ledger, 2).await;
     overdraft(&ledger, 99).await;
@@ -533,7 +618,7 @@ async fn balance_as_of_folds_a_bounded_tail_onto_its_cache_point() {
     let watermark = unix_millis_now();
     ledger
         .store()
-        .append_balance_projection(&account(1), &usd(), snapshot, watermark)
+        .append_balance_projection(&account(1), snapshot.clone(), watermark)
         .await
         .unwrap();
 
@@ -548,17 +633,22 @@ async fn balance_as_of_folds_a_bounded_tail_onto_its_cache_point() {
         ledger
             .balance_as_of(&account(1), &usd(), as_of)
             .await
-            .unwrap(),
-        Cent::from(1250),
+            .unwrap()
+            .minor_units(),
+        1250,
         "snapshot plus bounded tail diverged from the total at as_of"
     );
     assert_eq!(
-        ledger.balance(&account(1), &usd()).await.unwrap(),
-        Cent::from(1550)
+        ledger
+            .balance(&account(1), &usd())
+            .await
+            .unwrap()
+            .minor_units(),
+        1550
     );
     assert_ne!(
-        snapshot,
-        Cent::from(1250),
+        snapshot.minor_units(),
+        1250,
         "the snapshot already held the as-of balance; the tail was empty"
     );
 }
@@ -568,6 +658,7 @@ async fn balance_as_of_folds_a_bounded_tail_onto_its_cache_point() {
 #[tokio::test]
 async fn balance_as_of_ignores_a_cache_point_above_it() {
     let ledger = Arc::new(Ledger::new(InMemoryStore::new()));
+    register_assets(&ledger).await;
     no_overdraft(&ledger, 1).await;
     no_overdraft(&ledger, 2).await;
     overdraft(&ledger, 99).await;
@@ -582,7 +673,7 @@ async fn balance_as_of_ignores_a_cache_point_above_it() {
     let full = ledger.balance_exact(&account(1), &usd()).await.unwrap();
     ledger
         .store()
-        .append_balance_projection(&account(1), &usd(), full, unix_millis_now())
+        .append_balance_projection(&account(1), full.clone(), unix_millis_now())
         .await
         .unwrap();
 
@@ -590,11 +681,19 @@ async fn balance_as_of_ignores_a_cache_point_above_it() {
         ledger
             .balance_as_of(&account(1), &usd(), as_of)
             .await
-            .unwrap(),
-        Cent::from(750),
+            .unwrap()
+            .minor_units(),
+        750,
         "the as-of read used a cache point covering later commits"
     );
-    assert_eq!(ledger.balance(&account(1), &usd()).await.unwrap(), full);
+    assert_eq!(
+        ledger
+            .balance(&account(1), &usd())
+            .await
+            .unwrap()
+            .minor_units(),
+        full.minor_units()
+    );
 }
 
 /// An as-of read appends no cache point, even past the interval that makes the
@@ -608,6 +707,7 @@ async fn balance_as_of_appends_no_cache_point() {
             snapshot_interval: 1,
         },
     ));
+    register_assets(&ledger).await;
     no_overdraft(&ledger, 1).await;
     no_overdraft(&ledger, 2).await;
     overdraft(&ledger, 99).await;
@@ -618,7 +718,8 @@ async fn balance_as_of_appends_no_cache_point() {
     let _ = ledger
         .balance_as_of(&account(1), &usd(), unix_millis_now())
         .await
-        .unwrap();
+        .unwrap()
+        .minor_units();
 
     for _ in 0..1000 {
         tokio::task::yield_now().await;
@@ -639,6 +740,7 @@ async fn balance_as_of_appends_no_cache_point() {
 #[tokio::test]
 async fn balance_as_of_outside_the_committed_history() {
     let ledger = Arc::new(Ledger::new(InMemoryStore::new()));
+    register_assets(&ledger).await;
     no_overdraft(&ledger, 1).await;
     no_overdraft(&ledger, 2).await;
     overdraft(&ledger, 99).await;
@@ -652,14 +754,20 @@ async fn balance_as_of_outside_the_committed_history() {
         ledger
             .balance_as_of(&account(1), &usd(), before)
             .await
-            .unwrap(),
-        Cent::from(0)
+            .unwrap()
+            .minor_units(),
+        0
     );
     assert_eq!(
         ledger
             .balance_as_of(&account(1), &usd(), i64::MAX)
             .await
-            .unwrap(),
-        ledger.balance(&account(1), &usd()).await.unwrap()
+            .unwrap()
+            .minor_units(),
+        ledger
+            .balance(&account(1), &usd())
+            .await
+            .unwrap()
+            .minor_units()
     );
 }

+ 75 - 32
crates/kuatia/tests/workflow.rs

@@ -9,6 +9,16 @@ use kuatia::mem_store::InMemoryStore;
 use kuatia::workflow::run_transfers;
 use kuatia_core::*;
 
+/// An amount of `asset` in minor units. An amount compares by asset id, and the
+/// tests register these same ids, so building the row here is equivalent to
+/// reading it back from the registry.
+fn money<V>(asset: AssetId, value: V) -> Amount
+where
+    Amount: From<(V, Arc<Asset>)>,
+{
+    Amount::from((value, Arc::new(Asset::new(asset, "TEST", "$", 2))))
+}
+
 fn usd() -> AssetId {
     AssetId::new(1)
 }
@@ -47,19 +57,26 @@ async fn setup_ledger() -> Arc<Ledger> {
             .await
             .unwrap();
     }
+    ledger
+        .create_asset(Asset::new(usd(), "USD", "$", 2))
+        .await
+        .unwrap();
 
     ledger
 }
 
-fn deposit(to: AccountId, amount: Cent) -> Transfer {
+fn deposit(to: AccountId, amount: i64) -> Transfer {
     TransferBuilder::new()
-        .deposit(to, usd(), amount, external())
-        .unwrap()
+        .deposit(to, money(usd(), amount), external())
         .build()
+        .unwrap()
 }
 
-fn pay(from: AccountId, to: AccountId, amount: Cent) -> Transfer {
-    TransferBuilder::new().pay(from, to, usd(), amount).build()
+fn pay(from: AccountId, to: AccountId, amount: i64) -> Transfer {
+    TransferBuilder::new()
+        .pay(from, to, money(usd(), amount))
+        .build()
+        .unwrap()
 }
 
 /// A two-movement workflow (deposit then pay) commits both legs in order.
@@ -69,26 +86,35 @@ async fn workflow_happy_path() {
 
     let receipts = run_transfers(
         &ledger,
-        &[
-            deposit(account(1), Cent::from(100)),
-            pay(account(1), account(2), Cent::from(60)),
-        ],
+        &[deposit(account(1), 100), pay(account(1), account(2), 60)],
     )
     .await
     .unwrap();
     assert_eq!(receipts.len(), 2);
 
     assert_eq!(
-        ledger.balance(&account(1), &usd()).await.unwrap(),
-        Cent::from(40)
+        ledger
+            .balance(&account(1), &usd())
+            .await
+            .unwrap()
+            .minor_units(),
+        40
     );
     assert_eq!(
-        ledger.balance(&account(2), &usd()).await.unwrap(),
-        Cent::from(60)
+        ledger
+            .balance(&account(2), &usd())
+            .await
+            .unwrap()
+            .minor_units(),
+        60
     );
     assert_eq!(
-        ledger.balance(&external(), &usd()).await.unwrap(),
-        Cent::from(-100)
+        ledger
+            .balance(&external(), &usd())
+            .await
+            .unwrap()
+            .minor_units(),
+        -100
     );
 }
 
@@ -101,10 +127,7 @@ async fn workflow_compensation_on_failure() {
 
     let err = run_transfers(
         &ledger,
-        &[
-            deposit(account(1), Cent::from(50)),
-            pay(account(1), account(2), Cent::from(100)),
-        ],
+        &[deposit(account(1), 50), pay(account(1), account(2), 100)],
     )
     .await
     .unwrap_err();
@@ -115,12 +138,20 @@ async fn workflow_compensation_on_failure() {
     );
     // The deposit was compensated (reversed); the net effect is zero.
     assert_eq!(
-        ledger.balance(&account(1), &usd()).await.unwrap(),
-        Cent::ZERO
+        ledger
+            .balance(&account(1), &usd())
+            .await
+            .unwrap()
+            .minor_units(),
+        0
     );
     assert_eq!(
-        ledger.balance(&external(), &usd()).await.unwrap(),
-        Cent::ZERO
+        ledger
+            .balance(&external(), &usd())
+            .await
+            .unwrap()
+            .minor_units(),
+        0
     );
 }
 
@@ -132,9 +163,9 @@ async fn workflow_three_steps_happy() {
     let receipts = run_transfers(
         &ledger,
         &[
-            deposit(account(1), Cent::from(100)),
-            pay(account(1), account(2), Cent::from(60)),
-            pay(account(2), account(3), Cent::from(30)),
+            deposit(account(1), 100),
+            pay(account(1), account(2), 60),
+            pay(account(2), account(3), 30),
         ],
     )
     .await
@@ -142,15 +173,27 @@ async fn workflow_three_steps_happy() {
     assert_eq!(receipts.len(), 3);
 
     assert_eq!(
-        ledger.balance(&account(1), &usd()).await.unwrap(),
-        Cent::from(40)
+        ledger
+            .balance(&account(1), &usd())
+            .await
+            .unwrap()
+            .minor_units(),
+        40
     );
     assert_eq!(
-        ledger.balance(&account(2), &usd()).await.unwrap(),
-        Cent::from(30)
+        ledger
+            .balance(&account(2), &usd())
+            .await
+            .unwrap()
+            .minor_units(),
+        30
     );
     assert_eq!(
-        ledger.balance(&account(3), &usd()).await.unwrap(),
-        Cent::from(30)
+        ledger
+            .balance(&account(3), &usd())
+            .await
+            .unwrap()
+            .minor_units(),
+        30
     );
 }

+ 3 - 0
doc/SUMMARY.md

@@ -60,4 +60,7 @@
   - [0025: One live set: retire the reservation protocol and the saga-era store primitives](adr/0025-one-live-set-no-reservations.md)
   - [0026: Let the public API speak the caller's vocabulary](adr/0026-public-api-vocabulary.md)
   - [0027: Value date, separate from commit time and inside the content address](adr/0027-value-date-separate-from-commit-time.md)
+  - [0028: An amount carries its asset, and the ledger owns the asset registry](adr/0028-amount-carries-its-asset.md)
+  - [0029: Stored amounts, and a public surface that never names `Cent`](adr/0029-stored-amounts-and-a-closed-money-surface.md)
+  - [0030: An asset is named by its code, and the ledger mints its id](adr/0030-assets-named-by-code.md)
   - [ADR template](adr/template.md)

+ 4 - 4
doc/accounting-mapping.md

@@ -28,7 +28,7 @@ scope, not the accounting journal.
 | **Journal** (book of original entry) | **Transfer log**, `TransferStore` of `TransferRecord`s | Append-only, ordered source of truth for committed transfers. |
 | **Journal entry** (one balanced event) | Committed **`Transfer`** (intent) → **`Envelope`** (resolved) | One atomic accounting event. |
 | **Compound journal entry** | `Transfer` with multiple `Movement`s | One event touching many accounts/assets. |
-| **Entry line / leg** | **`Posting`** effect (often derived from a `Movement`) | A concrete account-level value fragment. A `Movement` is two-sided intent `{from, to, asset, amount}` that resolves into consumed/created postings, not a 1:1 debit/credit line. |
+| **Entry line / leg** | **`Posting`** effect (often derived from a `Movement`) | A concrete account-level value fragment. A `Movement` is two-sided intent, an amount moving `from` one account `to` another, that resolves into consumed/created postings rather than a 1:1 debit/credit line. |
 | **Σ debits = Σ credits** | **Per-asset conservation** `sum(consumed) == sum(created)` | Enforced in `validate_and_plan`; `ConservationViolation` otherwise. |
 | **Ledger** (accounts + running balances) | **Accounts + live postings** | Balances are projections over the live (unspent) postings, never stored. |
 | **Posting a transaction** (the verb) | **resolve + commit** (`Transfer` → `Envelope` → apply) | Confusing collision: in Kuatia a *posting* is a noun (a value fragment), not the act of recording. |
@@ -62,9 +62,9 @@ committed atomically:
 ```rust
 let transfer = TransferBuilder::new()
     .book(sales_book)
-    .pay(customer, revenue, usd, Cent::from(100))
-    .pay(customer, tax_payable, usd, Cent::from(15))
-    .build();
+    .pay(customer, revenue, ("100.00", &usd))
+    .pay(customer, tax_payable, ("15.00", &usd))
+    .build()?;
 // One Transfer → one Envelope → one TransferRecord in the transfer log.
 ```
 

+ 6 - 0
doc/accounts.md

@@ -167,6 +167,12 @@ balance(account, asset) = sum(p.value for p in postings
 There is no stored balance field. This eliminates drift between the balance
 and the underlying postings.
 
+A read returns an [`Amount`](glossary.md#amount): the asset rides along, so two
+balances of different assets cannot be added by the caller that holds them. The
+money type underneath is not public, so what a caller gets is the amount's own
+`Display`, its checked arithmetic, or `minor_units()` (ADR-0029). The asset must
+be registered, since an unregistered one has no precision to report at.
+
 `balance_as_of(account, asset, as_of)` answers the same question at a past instant, by folding only the transfers 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, not a value date: the cache points a read folds against are watermarked by the commit clock, so an entry backdated with a [value date](transfers.md#booking-date-and-value-date) still lands at the instant it was committed. A past balance cannot come from the postings themselves, because a posting carries no timestamp.
 
 ## Account Types in Practice

+ 102 - 0
doc/adr/0028-amount-carries-its-asset.md

@@ -0,0 +1,102 @@
+# An amount carries its asset, and the ledger owns the asset registry
+
+* Status: accepted
+* Authors: Cesar Rodas
+* Date: 2026-12-02
+* Targeted modules: `kuatia-money` (`Scale`, `Cent`), `kuatia-types` (`amount`,
+  `asset`, `transfer`), `kuatia-core` (`posting_resolution`), `kuatia-storage`
+  (`AssetStore`), `kuatia-storage-sql` (migration 014), `kuatia` (`ledger`),
+  `kuatia-dashboard`
+* Associated tickets/PRs: N/A
+
+## Context and Problem Statement
+
+A `Cent` is a signed integer of minor units and nothing else. It adds to and compares with any other `Cent`, so two balances read from one ledger in two assets could be summed into a number denominated in nothing. Inside the ledger that discipline held: conservation buckets by `.entry(posting.asset)`, the resolve algorithm keys net debits on `(from, asset)`, and a wrong fold is caught by the conservation check. The leak was on the way out. `Ledger::balance` returned a bare `Cent` and `SubAccountBalance` dropped the asset entirely, so the mistake happened in the caller, after the ledger had answered, where no invariant could reach it.
+
+The second half of the problem is precision. ADR-0009 put scale outside the value, in a presentation-only parser named `Amount`, and recorded the consequence it accepted: "the type system does not bind a `Cent` to its asset's decimal places, so callers must format/parse with the right `Amount` for the asset." With no registry in the ledger, an `AssetId` was opaque: 100 of asset 1 could be a dollar or a hundred of them, and the only thing that knew was whichever application was formatting. The demo dashboard carried its own hardcoded table of codes and decimals for exactly that reason.
+
+## Decision Drivers
+
+* The bug the library cannot catch is the one in the caller's hands, so the fix has to be in what the caller is handed.
+* A decimal string a person writes needs a scale to become minor units, and the asset is the only honest place for that scale to come from.
+* The content address and the amount columns are frozen; a vocabulary change must not move either.
+* The pure core stays IO-free and deterministic.
+* `kuatia-money` is a leaf crate that cannot see an `AssetId`.
+
+## Considered Options
+
+#### Keep `Cent` everywhere and document the hazard
+
+**Pros:**
+
+* Good, because it costs nothing and breaks no caller.
+
+**Cons:**
+
+* Bad, because it is what ADR-0009 already chose, and the hazard it documented is the one that keeps biting.
+* Bad, because a decimal string still has nowhere to learn its precision, so every application rebuilds the dashboard's table.
+
+#### An amount that carries scale rather than an asset
+
+`Amount { asset: AssetId, value: Cent, decimals: u8 }`, with the precision copied in at construction.
+
+**Pros:**
+
+* Good, because it needs no registry and no shared ownership.
+
+**Cons:**
+
+* Bad, because it contradicts ADR-0009's outcome by putting scale on the value, and duplicates registry state into every amount in the process.
+* Bad, because two amounts of one asset could disagree about its precision.
+
+#### An amount carrying `Arc<Asset>`, with a registry in the ledger
+
+**Pros:**
+
+* Good, because the asset's own row answers both questions: what the amount is denominated in, and at what scale its written form parses.
+* Good, because an amount cannot be built without a registered asset, so the invariant is structural rather than a validation step.
+* Good, because it absorbs the application-level asset tables that exist only because the ledger had none.
+
+**Cons:**
+
+* Bad, because a balance read now depends on the registry, so reading an unregistered asset is an error where it used to be a number.
+* Bad, because `Arc<Asset>` cannot ride through serde without a resolver, which bounds how far it can reach.
+
+## Decision Outcome
+
+Chosen option: **an amount carrying `Arc<Asset>`, with the registry in the ledger**, bounded to the public API.
+
+1. **`Asset`** is a registry row: `{ id, code, symbol, decimals }`, written once and never updated. Immutability is what makes the precision safe to rely on, since editing it would reinterpret every amount already recorded against the asset, and is also what makes the ledger's cache sound. `AssetStore` adds `create_asset`, `get_asset` and `list_assets`; migration `014_assets` stores the row as JSON beside its id, like books.
+
+2. **`Amount { asset: Arc<Asset>, value: Cent }`** lives in `kuatia-types`, not beside `Cent`, because `kuatia-money` has no dependency on the crate that defines `AssetId`. Conversion is the only way to build one, so no amount exists without an asset behind it. The tuple conversions follow one rule: an integer is minor units, a string is the written form at the asset's own scale. `(usd, 500)` and `(usd, "5.00")` are the same amount, and `(usd, "5.001")` fails rather than rounding.
+
+3. **`Arc<Asset>` stops at the public API.** `Posting`, `NewPosting`, `Movement`, `BalanceProjection`, the pure core's `(account, asset)` map keys and every storage row keep `AssetId`. `NewPosting` is serde-JSON inside the stored `transfers.transfer` column, and serde cannot hydrate an `Arc` without a registry to reach; the `Ledger` hydrates on the way out instead. Nothing stored changes, `CANONICAL_VERSION` stays at 6, and no transfer id moves.
+
+4. **The reads return amounts.** `balance`, `balance_exact` and `balance_as_of` return `Amount`, and `SubAccountBalance` carries one. `InsufficientFunds` gains its asset, so the two values in a shortfall name a quantity. Adding two assets is `AmountError::AssetMismatch`, refused at the call site that tries it.
+
+5. **The builder takes one amount per verb**, as `impl TryInto<Amount>`, and holds the first conversion failure until `build`. That keeps the chain fluent while making `build` fallible, which also retires `deposit`'s mid-chain `Result` (ADR-0026 left it as the one verb that broke the flow).
+
+6. **Commit refuses an unregistered asset.** Conservation puts every asset a transfer touches on the created side, so the created postings are the whole set to check. Validation itself pays nothing: it reads the authoritative live sum from the store, and an amount that reached it was built from a registered asset already.
+
+7. **The scale keeps its own name.** ADR-0009's `Amount` was a decimal-place count that parsed and formatted and was never stored. It is now `Scale`, and `ParseAmountError` is `ParseDecimalError`. ADR-0009 and ADR-0011 still say `Amount`, since an accepted record is not rewritten; this is where the rename lives.
+
+### Positive Consequences
+
+* The read-side leak closes: a caller holding two balances cannot add them unless they are the same asset.
+* A written amount parses at the right precision without the caller tracking it, which retires the negative consequence ADR-0009 accepted.
+* The snapshot-plus-tail additions in the balance path and the hand-built FX envelopes keep working unchanged, since both operate below the public surface.
+* The dashboard's own asset table is gone, and with it the path that rendered raw minor units for an asset missing from it.
+
+### Negative Consequences
+
+* A balance read of an unregistered asset is an error. That is intended, since an unregistered asset has no precision to report at, but it means every test, example and seed registers its assets first.
+* `build` is fallible for every caller, including ones passing a `Cent` that cannot fail. The blanket `From<Infallible>` keeps those call sites writing `(asset, cent)` with no ceremony, but the `Result` is still there.
+* The commit path takes a registry lookup per distinct asset. Cached after the first, uncached on a miss.
+* `Amount` is `Serialize` only. Rebuilding one needs the registry, so nothing deserializes it, and the dashboard's issued figures change key from `issued` to `value`.
+
+## Links
+
+* Refines [ADR-0009](0009-monetary-representation-integer-minor-units.md), whose accepted negative consequence this retires, and renames the `Amount` it introduced.
+* Follows [ADR-0026](0026-public-api-vocabulary.md): the public surface speaks the caller's vocabulary, and `deposit`'s mid-chain `Result` was the wart it left.
+* Constrained by [ADR-0024](0024-native-money-columns.md) (the amount columns) and the canonical preimage order, both unchanged here.
+* Conservation per asset: [ADR-0001](0001-modified-utxo-signed-postings.md).

+ 104 - 0
doc/adr/0029-stored-amounts-and-a-closed-money-surface.md

@@ -0,0 +1,104 @@
+# Stored amounts, and a public surface that never names `Cent`
+
+* Status: accepted
+* Authors: Cesar Rodas
+* Date: 2026-12-02
+* Targeted modules: `kuatia-money` (`Cent::minor_units`, the decimal parser),
+  `kuatia-types` (`amount`, `posting`, `transfer`, `canonical`, `internals`),
+  `kuatia-core` (`validate`, `posting_resolution`), `kuatia-storage`,
+  `kuatia-storage-sql` (`row`, `posting`, `projection`), `kuatia`
+  (`ledger`, `inflight`), `kuatia-dashboard`
+* Associated tickets/PRs: N/A
+
+## Context and Problem Statement
+
+ADR-0028 gave the ledger an `Amount` and bounded it to the public API: `Posting`, `NewPosting`, `Movement` and `BalanceProjection` kept an `AssetId` beside a `Cent`, and the `Ledger` paired them on the way out. Two things were wrong with stopping there.
+
+The shape being stored was still the shape the type was meant to retire. A reader of the schema or the structs saw the pair, the conversion happened at one edge only, and the accessors that bridged the two (`Posting::value()`, `Amount::value()`) handed the `Cent` straight back. Twenty-six public items still named `Cent` or `AssetId` in a way that let a caller take an amount apart and recombine it wrongly.
+
+The reason ADR-0028 stopped was real: `NewPosting` is serde-JSON inside the stored `transfers.transfer` column, and serde cannot rebuild an `Arc<Asset>` because it has no registry to reach. Any structure holding an `Amount` was therefore undecodable.
+
+## Decision Drivers
+
+* The bug class this work exists to remove is a value separated from its asset, so the stored form is where it matters most.
+* Nothing may move the content address: every `TransferId` in every database depends on the preimage byte-for-byte.
+* A read must not be able to fail *silently*; a loud failure is acceptable, a dropped row is not.
+* The amount columns stay native integers, because ADR-0024's exact `SUM()` and the ordering indexes are built on them.
+* `Cent`'s width is a compile-time choice (ADR-0011) and must stay invisible to callers.
+
+## Considered Options
+
+#### Hydrate from the registry on every read
+
+The store resolves each row's asset through `AssetStore` with a cache.
+
+**Pros:**
+
+* Good, because the stored bytes do not change at all.
+
+**Cons:**
+
+* Bad, because the store starts making domain decisions, against the dumb-storage line from ADR-0003 and ADR-0023.
+* Bad, because a row read becomes dependent on registry state, and the failure mode is a read that cannot answer.
+
+#### Deserialize into an unresolved placeholder asset
+
+`Amount` gains a `Deserialize` that yields an asset with `decimals: 0` until something re-hydrates it.
+
+**Pros:**
+
+* Good, because it is nearly free.
+
+**Cons:**
+
+* Bad, because an amount that formats at the wrong scale is exactly the defect this line of work removes, and a placeholder is that defect with a nicer name.
+
+#### Store the asset definition with the amount
+
+**Pros:**
+
+* Good, because an amount decodes with no registry, no resolver and no failure mode.
+* Good, because an append-only audit record becomes self-describing: a stored posting can be read with no other table.
+* Good, because it needs nothing of the store, which keeps serving rows.
+
+**Cons:**
+
+* Bad, because the definition is repeated in every stored record.
+* Bad, because the column tables cannot do this: an index and an exact sum need the integer and the id in their own columns.
+
+## Decision Outcome
+
+Chosen option: **store the asset definition with the amount**, and close the public surface behind it.
+
+1. **The serialized form of an `Amount` carries the whole asset**, not its id, so `Amount: Deserialize` exists and cannot fail or come back at the wrong scale. That is what lets `Movement`, `Posting`, `NewPosting` and `BalanceProjection` each hold one amount.
+
+2. **The content address does not carry it.** The preimage still writes the asset's `u32` id then the 16-byte value, so writing a code or a symbol differently cannot re-identify a transfer, and `CANONICAL_VERSION` stays at 6. A golden vector taken before the refactor is asserted in `kuatia-core`'s hash tests and did not move.
+
+3. **The column tables keep an integer beside an asset id** (ADR-0024 is unchanged), and a posting read **left-joins** the registry to rebuild the amount. Left, not inner, and no foreign key: an inner join or a missing FK would silently drop a posting whose asset is absent, while a left join fails the decode loudly and says so. The invariant is enforced where it belongs instead, at the commit, which resolves every asset a transfer moves value in. SQLite also cannot take a foreign key without rebuilding the table and needs the pragma set per connection, so the constraint would have been weaker than the check it replaced.
+
+4. **`Cent` is not public.** No public signature in `kuatia-types`, `kuatia-core`, `kuatia-storage` or `kuatia` names it. An `Amount` gives up `Display` at its asset's scale, `checked_add`/`checked_sub`/`checked_neg`/`checked_sum` that refuse two assets, the predicates, and `minor_units() -> i128` for a caller doing its own formatting. `AssetId` stays public, because an asset must be nameable to be registered, looked up or allowed by a book.
+
+5. **One seam, not an accessor.** The other crates still need the integer, for checked arithmetic and for a column bind, and they are separate crates, so `kuatia_types::internals` (doc(hidden)) holds `cent`, `amount`, `scale` and the money re-exports. One named place, greppable, rather than a public method that a caller would reasonably use.
+
+6. **Conservation sums amounts.** The per-asset buckets in `validate_and_plan` add `Amount`s, so a bucket keyed wrongly fails the addition rather than netting two assets. Posting selection still works in values: it needs an ordering, and two assets have no answer for that.
+
+### Positive Consequences
+
+* A stored posting is self-describing: its asset, its precision and its value travel together, which is what an append-only audit record should be.
+* The pairing bug is gone from the storage layer, the intent layer and the API at once, not just the edge.
+* The dashboard formats from `minor_units()` and the asset's own decimals, so its last mis-scaling path is gone along with its asset table.
+* `--5` no longer parses as a positive five, which mattered once a string became a way to state a transfer amount.
+
+### Negative Consequences
+
+* Every stored record is larger by its asset definition, repeated per posting.
+* An open inflight authorization cannot be confirmed across the upgrade: the leg table is CBOR inside a transfer's metadata and its shape moved.
+* A database carrying postings in assets that are not registered will fail those reads loudly until the assets are registered. That is the intended direction of the failure, but it makes registration the first step of an upgrade.
+* `Amount` has no total order, so a comparison is explicit and same-asset only.
+
+## Links
+
+* Supersedes point 3 of [ADR-0028](0028-amount-carries-its-asset.md), which bounded `Arc<Asset>` to the public API; the rest of 0028 stands.
+* Constrained by [ADR-0024](0024-native-money-columns.md) (native amount columns) and [ADR-0011](0011-swappable-money-backing.md) (the hidden backing width).
+* Keeps the storage layer free of domain decisions, per [ADR-0023](0023-atomic-storage-commit.md).
+* Conservation per asset: [ADR-0001](0001-modified-utxo-signed-postings.md).

+ 97 - 0
doc/adr/0030-assets-named-by-code.md

@@ -0,0 +1,97 @@
+# An asset is named by its code, and the ledger mints its id
+
+* Status: accepted
+* Authors: Cesar Rodas
+* Date: 2026-12-02
+* Targeted modules: `kuatia-types` (`asset`, `book`), `kuatia-storage`
+  (`AssetStore`), `kuatia-storage-sql` (migration 015), `kuatia`
+  (`ledger::asset`), `kuatia-dashboard`
+* Associated tickets/PRs: N/A
+
+## Context and Problem Statement
+
+ADR-0028 gave assets caller-supplied ids, reasoning that an asset is named like an account rather than minted. In practice a caller names an asset by its code and has no opinion about its id, so registering one took two steps and an invented number:
+
+```rust
+ledger.create_asset(Asset::new(AssetId::new(2), "EUR", "€", 2)).await?;
+let eur = ledger.asset(&AssetId::new(2)).await?;
+```
+
+The `2` is the caller keeping a registry of its own alongside the ledger's, which is the thing the registry exists to stop. Every test, example and seed in the tree carried such a table, and nothing but convention kept two of them from disagreeing.
+
+## Decision Drivers
+
+* A caller names money by its code, not by a number.
+* An id must stay stable, because postings, the amount columns and the content address all store it.
+* Precision is the dangerous field: an asset returned at the wrong scale mis-states every amount read through it.
+* Setup code runs repeatedly (tests, seeds, a service starting against an existing database), so registration wants to be idempotent.
+
+## Considered Options
+
+#### Keep caller-supplied ids, add a by-code lookup
+
+**Pros:**
+
+* Good, because it is the smallest change and the caller keeps its id space.
+
+**Cons:**
+
+* Bad, because the caller still holds a table mapping codes to numbers, which is what went wrong.
+
+#### Derive the id from the code
+
+An `AssetId` is a hash of the code, so one code is one id in every database.
+
+**Pros:**
+
+* Good, because two ledgers registering `EUR` agree without coordination, which helps if they are ever compared.
+
+**Cons:**
+
+* Bad, because a 32-bit hash collides, and a collision silently merges two assets into one balance.
+* Bad, because a code could then never be re-spelled.
+
+#### Name by code, mint the id (chosen)
+
+**Pros:**
+
+* Good, because the caller states what it knows (code, symbol, precision) and nothing it does not.
+* Good, because it matches how accounts and books already get their ids, in Rust through `AutoId`, never from the database.
+* Good, because one call both registers and returns the handle, so setup code is idempotent.
+
+**Cons:**
+
+* Bad, because the same code has different ids in two databases, so an id is not portable between them.
+* Bad, because it needs a unique index on the code, and a migration to add it.
+
+## Decision Outcome
+
+Chosen option: **name by code, mint the id**.
+
+1. **`Ledger::asset(code, symbol, decimals)` is get-or-create** and returns `Arc<Asset>`. The by-id lookup keeps its behaviour as `asset_by_id`. `create_asset` stays for a caller that wants to choose the id.
+
+2. **A code registered with other metadata is `LedgerError::AssetRedefined`.** Returning the stored row would hand back a precision the caller did not ask for and mis-state every amount formatted through it; rewriting the row is not possible, since a registry row is immutable (ADR-0028). So neither side wins and the disagreement is reported, carrying both decimal counts.
+
+3. **The id comes from `AutoId`**, folded into the `u32` an `AssetId` carries, retried past the small chance that a truncated snowflake lands on an id already taken. A code's uniqueness is the index's job, so a concurrent registration of the same code is caught by re-reading it rather than by locking.
+
+4. **`code` is unique** (migration `015_asset_code_unique`). Without it a get-or-create could register a second `EUR` under a different id and split every balance held in it.
+
+5. **`AssetStore` gains `get_asset_by_code`**, returning an `Option` rather than `NotFound`, because the caller asking by code is deciding whether to register.
+
+### Positive Consequences
+
+* Registering an asset is one line and says only what the caller knows: `ledger.asset("EUR", "€", 2)`.
+* The id-to-code tables in the tests, the examples and the dashboard are gone; the dashboard reads the registry for the list it renders.
+* Setup code is idempotent, so a seed can run against a populated database without an ignore-already-exists dance.
+
+### Negative Consequences
+
+* An `AssetId` is no longer portable between databases, which it was when a caller chose it. Nothing in the ledger compares ids across databases, but a tool that did would have to map by code.
+* A code is now part of an asset's identity in practice, so re-spelling one means a new asset.
+* Migration 015 fails on an existing database that already holds two assets sharing a code. That is the condition the index exists to prevent, and it has to be resolved by hand.
+
+## Links
+
+* Supersedes the caller-supplied-id clause of [ADR-0028](0028-amount-carries-its-asset.md); the rest of it, and all of [ADR-0029](0029-stored-amounts-and-a-closed-money-surface.md), stand.
+* Ids minted in Rust, never by the database: the `AutoId` rule in `CLAUDE.md`, as used by accounts and books.
+* Immutable registry rows: [ADR-0028](0028-amount-carries-its-asset.md), point 1.

+ 3 - 0
doc/adr/README.md

@@ -37,6 +37,9 @@ to reverse a decision. Instead, a new ADR supersedes it.
 | [0025](0025-one-live-set-no-reservations.md) | One live set: retire the reservation protocol and the saga-era store primitives | accepted | A posting is live or spent, with nothing in between: `PostingState` loses `Reserved`, `PostingFilter` loses `Active`, and `ReservationId`/`TransitionId` go. The six single-update write primitives are removed, leaving the atomic commit as the store's only posting write, and migration 012 drops `live_postings.reservation`. Follows 0023; supersedes 0006; amends 0008. |
 | [0026](0026-public-api-vocabulary.md) | Let the public API speak the caller's vocabulary | accepted | Four shapes left over from earlier designs leave the surface: the `Arc<Ledger>` every commit required and never used, `TransferBuilder`'s duplicate `_ref` methods, the `Envelope` spelling in `EnvelopeId`/`EnvelopeRecord` (now `TransferId`/`TransferRecord`), and the four-way balance surface (`compute_balance` becomes `balance_exact`; cache maintenance moves to `Ledger::projection()`). Nothing stored changes. Follows 0025; supersedes 0012's builder clause. |
 | [0027](0027-value-date-separate-from-commit-time.md) | Value date, separate from commit time and inside the content address | accepted | An entry can be booked one day and take effect another. `ValueDate` is a calendar day on `Transfer` and `Envelope`, inside the content address, so two entries differing only in the day they take effect are two transfers. `created_at` keeps its single meaning as the commit clock the balance cache folds against; migration 013 adds a filterable column and `TransferQuery` gains its own window. Bumps `CANONICAL_VERSION`. Follows 0026; constrained by 0019. |
+| [0028](0028-amount-carries-its-asset.md) | An amount carries its asset, and the ledger owns the asset registry | accepted | `Amount { asset: Arc<Asset>, value: Cent }` is what the public API takes and returns, so two assets cannot be added by a caller holding two balances. A registered `Asset` carries the precision a written amount parses at, which retires ADR-0009's accepted gap; its old presentation-only `Amount` becomes `Scale`. `Arc<Asset>` stops at the public surface, so nothing stored and no content address moves. Refines 0009; follows 0026. |
+| [0029](0029-stored-amounts-and-a-closed-money-surface.md) | Stored amounts, and a public surface that never names `Cent` | accepted | An amount's serialized form carries its asset, so `Movement`, `Posting`, `NewPosting` and `BalanceProjection` each hold one amount and decode with no registry. The content address still hashes the asset id and the value, proved by a golden vector. The column tables keep the integer and the id for ADR-0024's sums and left-join the registry to rebuild an amount. `Cent` leaves the public surface entirely, reachable only through `kuatia_types::internals`. Supersedes 0028's point 3. |
+| [0030](0030-assets-named-by-code.md) | An asset is named by its code, and the ledger mints its id | accepted | `ledger.asset("EUR", "€", 2)` registers on first sight and returns the handle, so a caller states the code, symbol and precision and never invents an id. A code is unique (migration 015) and one registered at another precision is refused rather than resolved. Supersedes ADR-0028's caller-supplied-id clause. |
 
 ## Recommended future ADRs
 

+ 5 - 3
doc/architecture.md

@@ -268,7 +268,9 @@ enforcing total ordering. This was removed because:
 ## Posting Selection
 
 The intent layer hides UTXO complexity from callers. Every operation is
-expressed as one or more `Movement { from, to, asset, amount }` values. The
+expressed as one or more movements, each an [`Amount`](glossary.md#amount)
+moving from one account to another, which the builder splits into the
+`Movement { from, to, asset, amount }` the resolve step reads. The
 resolve step aggregates net debits per (account, asset) across all movements,
 then for each pair with a positive net debit, the `select_postings` function
 uses a **greedy largest-first** algorithm:
@@ -320,8 +322,8 @@ use kuatia::workflow::run_transfers;
 
 let ledger: Ledger = /* ... */;
 let receipts = run_transfers(&ledger, &[
-    TransferBuilder::new().deposit(alice, usd, amount, bank)?.build(),
-    TransferBuilder::new().pay(alice, bob, usd, amount).build(),
+    TransferBuilder::new().deposit(alice, ("100.00", &usd), bank).build()?,
+    TransferBuilder::new().pay(alice, bob, ("40.00", &usd)).build()?,
 ])
 .await?;
 ```

+ 21 - 12
doc/crates.md

@@ -23,11 +23,15 @@ dependencies (`sha2`, `serde`, `bitflags`).
 | `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 |
+| `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` |
-| `Amount` | Parser/formatter for decimal strings. Not stored; use at API boundaries only |
+| `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](transfers.md#operations) |
+| `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 |
@@ -92,7 +96,7 @@ Async resource layer. Depends on `kuatia-core`, `tokio`, `async-trait`,
 | 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`) |
+| `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 |
 | `workflow` | `run_transfers`: multi-transfer LIFO composition over `commit`/`reverse` |
@@ -130,10 +134,11 @@ Transfers are built via `TransferBuilder` and committed with
 
 | 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 |
+| `.pay(from, to, amount)` | Single movement between accounts. `amount` is anything convertible into an [`Amount`](#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 |
 
 #### Account Lifecycle
 
@@ -148,7 +153,9 @@ Transfers are built via `TransferBuilder` and committed with
 
 | Method | Description |
 |--------|-------------|
-| `balance(account, asset)` | The everyday read: closest cache point plus the folded tail since its watermark |
+| `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) |
@@ -175,6 +182,7 @@ graph TB
     Store --> TransferStore
     Store --> CommitStore
     Store --> EventStore
+    Store --> AssetStore
     Store --> BookStore
 ```
 
@@ -183,7 +191,7 @@ graph TB
   `CommitStore::commit_transition`
 - **`PostingStore`**: `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
+  `live_balance(account, asset) -> Amount` (the one read a backend may compute
   itself, because it can do so exactly, ADR-0024). All reads: a posting is
   written only by `CommitStore`
 - **`TransferStore`**: `get_transfer`, `get_transfers_for_account`,
@@ -193,6 +201,7 @@ graph TB
   boundary (ADR-0023)
 - **`EventStore`**: `append_event` (idempotent on a dedup key: a transfer's id,
   or a lifecycle transition's `(account, version)`), `get_events_since`
+- **`AssetStore`**: `create_asset`, `get_asset`, `get_asset_by_code`, `list_assets`
 - **`BookStore`**: `create_book`, `get_book`, `list_books`
 
 A commit is one `commit_envelope` transaction, not a sequence of primitives, so
@@ -264,8 +273,8 @@ 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(),
+    TransferBuilder::new().deposit(alice, ("50.00", usd), bank).build()?,
+    TransferBuilder::new().pay(alice, bob, (amount, usd)).build()?,
 ])
 .await?;
 ```

+ 24 - 22
doc/examples/exchange.md

@@ -7,20 +7,22 @@ An exchange lets users deposit fiat, trade between currencies, and withdraw.
 ```rust
 use kuatia::prelude::*;
 
-// Assets
-let usd = AssetId::new(1);
-let eur = AssetId::new(2);
+// Assets, named by code: each call registers on first sight and hands back the
+// handle. An amount cannot be built without its asset, and a two-decimal
+// string has nowhere else to learn its scale from.
+let usd = ledger.asset("USD", "$", 2).await?;
+let eur = ledger.asset("EUR", "\u{20ac}", 2).await?;
 
 // Books: separate deposit/withdrawal flows from trading
 let deposits_book = BookBuilder::new("deposits")
-    .allow_asset(usd)
-    .allow_asset(eur)
+    .allow_asset(&usd)
+    .allow_asset(&eur)
     .allow_flags(AccountFlags::USER_0 | AccountFlags::USER_1) // wallets + bank
     .build();
 
 let trading_book = BookBuilder::new("trading")
-    .allow_asset(usd)
-    .allow_asset(eur)
+    .allow_asset(&usd)
+    .allow_asset(&eur)
     .allow_flags(AccountFlags::USER_0) // only user wallets
     .allow_account(exchange_pool)       // + the exchange pool
     .build();
@@ -44,29 +46,29 @@ let mut exchange_pool = Account::new(AccountId::default());
 exchange_pool.book = trading_book.id;
 ```
 
-**Deposit USD into Alice's wallet:**
+**Deposit $100.00 into Alice's wallet:**
 
 ```rust
 let deposit = TransferBuilder::new()
     .book(deposits_book.id)
-    .deposit(alice.id, usd, Cent::from(10_000), bank.id)?
-    .build();
+    .deposit(alice.id, ("100.00", &usd), bank.id)
+    .build()?;
 ledger.commit(deposit).await?;
-// Alice: +10,000 USD
-// Bank: -10,000 USD (offset: value entered the ledger boundary)
+// Alice: +$100.00
+// Bank: -$100.00 (offset: value entered the ledger boundary)
 ```
 
-**Alice trades 5,000 USD for EUR at 1:0.92:**
+**Alice trades $50.00 for EUR at 1:0.92:**
 
 ```rust
 let trade = TransferBuilder::new()
     .book(trading_book.id)
-    .pay(alice.id, exchange_pool, usd, Cent::from(5_000))
-    .pay(exchange_pool, alice.id, eur, Cent::from(4_600))
-    .build();
+    .pay(alice.id, exchange_pool, ("50.00", &usd))
+    .pay(exchange_pool, alice.id, ("46.00", &eur))
+    .build()?;
 ledger.commit(trade).await?;
-// Alice: 5,000 USD + 4,600 EUR
-// Exchange pool: 5,000 USD - 4,600 EUR
+// Alice: $50.00 + 46.00 EUR
+// Exchange pool: $50.00 - 46.00 EUR
 ```
 
 **Withdraw EUR to Alice's bank:**
@@ -74,11 +76,11 @@ ledger.commit(trade).await?;
 ```rust
 let withdrawal = TransferBuilder::new()
     .book(deposits_book.id)
-    .withdraw(alice.id, eur, Cent::from(4_600), bank.id)
-    .build();
+    .withdraw(alice.id, ("46.00", &eur), bank.id)
+    .build()?;
 ledger.commit(withdrawal).await?;
-// Alice: 5,000 USD, 0 EUR
-// Bank: -10,000 USD + 4,600 EUR
+// Alice: $50.00, 0.00 EUR
+// Bank: -$100.00 + 46.00 EUR
 ```
 
 Conservation holds at every step. The exchange pool absorbs the spread.

+ 20 - 19
doc/examples/retail.md

@@ -6,10 +6,11 @@ manages cash and bank accounts.
 **Setup:**
 
 ```rust
-// Assets
-let gs = AssetId::new(1);            // Guaranies (currency)
-let product_a = AssetId::new(100);   // Product: rice 1kg
-let product_b = AssetId::new(101);   // Product: cooking oil 1L
+// Assets, named by code. A product's `decimals` is what lets a quantity be
+// written as "50.000" rather than counted in thousandths at the call site.
+let gs = ledger.asset("GS", "\u{20b2}", 0).await?;          // Guaranies, no minor unit
+let product_a = ledger.asset("RICE", "kg", 3).await?;    // rice 1kg, to the gram
+let product_b = ledger.asset("OIL", "L", 3).await?;      // cooking oil 1L
 
 // Account flags
 const WAREHOUSE: AccountFlags = AccountFlags::USER_0;
@@ -19,21 +20,21 @@ const BANK: AccountFlags = AccountFlags::USER_3;
 
 // Books
 let sales_book = BookBuilder::new("sales")
-    .allow_asset(gs)
-    .allow_asset(product_a)
-    .allow_asset(product_b)
+    .allow_asset(&gs)
+    .allow_asset(&product_a)
+    .allow_asset(&product_b)
     .allow_flags(WAREHOUSE | CUSTOMER | REVENUE)
     .build();
 
 let inventory_book = BookBuilder::new("inventory")
-    .allow_asset(product_a)
-    .allow_asset(product_b)
+    .allow_asset(&product_a)
+    .allow_asset(&product_b)
     .allow_flags(WAREHOUSE)
     .allow_account(world) // issuance source
     .build();
 
 let banking_book = BookBuilder::new("banking")
-    .allow_asset(gs)
+    .allow_asset(&gs)
     .allow_flags(WAREHOUSE | BANK)
     .build();
 
@@ -62,8 +63,8 @@ bank.flags |= BANK;
 ```rust
 let receipt = TransferBuilder::new()
     .book(inventory_book.id)
-    .pay(world, warehouse.id, product_a, Cent::from(50_000)) // 50.000 units (precision 3)
-    .build();
+    .pay(world, warehouse.id, ("50.000", &product_a))
+    .build()?;
 ledger.commit(receipt).await?;
 // Warehouse: +50.000 rice
 // World: -50.000 rice (offset: issued into the ledger)
@@ -75,14 +76,14 @@ ledger.commit(receipt).await?;
 let sale = TransferBuilder::new()
     .book(sales_book.id)
     // Move product from warehouse to customer (consumed by sale)
-    .pay(warehouse.id, customer.id, product_a, Cent::from(2_000))
+    .pay(warehouse.id, customer.id, ("2.000", &product_a))
     // Customer pays cash
-    .pay(customer.id, cash_register.id, gs, Cent::from(30_000))
+    .pay(customer.id, cash_register.id, ("30000", &gs))
     // Record revenue
-    .pay(world, revenue.id, gs, Cent::from(30_000))
+    .pay(world, revenue.id, ("30000", &gs))
     // Record COGS (cost was 10,000 Gs per unit)
-    .pay(world, cogs.id, gs, Cent::from(20_000))
-    .build();
+    .pay(world, cogs.id, ("20000", &gs))
+    .build()?;
 ledger.commit(sale).await?;
 ```
 
@@ -91,8 +92,8 @@ ledger.commit(sale).await?;
 ```rust
 let deposit = TransferBuilder::new()
     .book(banking_book.id)
-    .pay(cash_register.id, bank.id, gs, Cent::from(30_000))
-    .build();
+    .pay(cash_register.id, bank.id, ("30000", &gs))
+    .build()?;
 ledger.commit(deposit).await?;
 ```
 

+ 46 - 6
doc/glossary.md

@@ -59,15 +59,55 @@ dashboard URLs); storage keeps the two `i64` legs. See ADR-0015.
 
 ### Asset
 
-An identifier (`AssetId(u32)`) representing a unit of value: a currency, a
-product, a token. Each asset is an independent conservation boundary: the sum
-of consumed postings must equal the sum of created postings *per asset* in
-every transfer.
+A unit of value: a currency, a product, a token. Each asset is an independent
+conservation boundary, so the sum of consumed postings must equal the sum of
+created postings *per asset* in every transfer.
+
+A caller names one by its code: `ledger.asset("EUR", "\u{20ac}", 2)` registers
+it on first sight and hands back the handle, and a code already registered at
+another precision is refused rather than quietly returned (ADR-0030).
+
+`AssetId(u32)` identifies one, minted by the ledger, and an `Asset` or an
+`Arc<Asset>` converts into its id, so anything taking an asset accepts
+whichever a caller holds.
+`Asset { id, code, symbol, decimals }` is its registry row, written once and never updated, and `decimals` is the scale a
+written amount of it parses at. An unregistered asset has no amount: a
+[transfer](transfers.md) in one is rejected and a balance read of one fails,
+because nothing could say what the number means (ADR-0028).
+
+### Amount
+
+A [`Cent`](crates.md) with the asset it is denominated in. The type exists so
+that two balances in different assets cannot be added: a `Cent` on its own
+compares and adds with any other.
+
+Built only by conversion, in whichever form the caller has. An integer is minor
+units and a string is the written form at the asset's own scale, so
+`(500, usd)` and `("5.00", usd)` are the same amount of a two-decimal asset,
+and `("5.001", usd)` is refused rather than rounded. A fraction shorter than
+the scale is padded, so `"100.0"` of a two-decimal asset is ten thousand minor
+units.
+
+The value comes first, the way the money reads aloud. Three spellings reach the
+same conversion: the handle (`(500, usd)`), a reference to it (`(500, &usd)`,
+which is what a caller with one asset and several movements writes), and the
+asset's own side (`usd.amount(500)?`, the `Denominate` trait, which works on an
+`Asset` or an `Arc<Asset>` and has to be in scope).
+
+What comes back out is the amount itself: `Display` renders it at its asset's
+scale, `checked_add` and its siblings refuse two assets, and `minor_units()`
+gives the plain integer for a caller formatting its own layout. The money type
+underneath is not public (ADR-0029).
 
 ### Movement
 
-The intent layer's building block: `{ from, to, asset, amount }`. Movements
-express *what* should happen. The ledger resolves them into concrete postings.
+The intent layer's building block: an [amount](#amount) moving from one account
+to another. Movements express *what* should happen, and the ledger resolves
+them into concrete postings.
+
+A caller states one as `(from, to, amount)`, and the stored `Movement` holds
+exactly that. So does a [`Posting`](#posting): the asset and the value do not
+travel separately anywhere above the database columns (ADR-0029).
 
 ### Transfer
 

+ 7 - 7
doc/inflight.md

@@ -64,18 +64,18 @@ use kuatia::prelude::*;
 
 // Authorize the trade. Funds leave A and B and park in the holds.
 let trade = TransferBuilder::new()
-    .pay(a, b, eur, Cent::from(100))
-    .pay(b, a, btc, Cent::from(10))
-    .pay(a, fee, btc, Cent::from(1))
-    .pay(b, fee, eur, Cent::from(1))
-    .build();
+    .pay(a, b, ("100.00", &eur))
+    .pay(b, a, ("10.00000000", &btc))
+    .pay(a, fee, ("1.00000000", &btc))
+    .pay(b, fee, ("1.00", &eur))
+    .build()?;
 let auth = ledger.authorize(trade).await?;
 
 // Confirm one or more legs, built with the same .pay() interface as a transfer
 // (from = funder, to = destination). Deliver 40 EUR of B's hold to B now:
 let some = TransferBuilder::new()
-    .pay(a, b, eur, Cent::from(40))
-    .build();
+    .pay(a, b, ("40.00", &eur))
+    .build()?;
 ledger.confirm(&auth.inflight, some).await?;
 
 // Confirm everything else and close the holds.

+ 7 - 7
doc/journaling.md

@@ -36,8 +36,8 @@ accounting grain is identical: one committed transfer is one journal entry.
 
 ## A journal entry: one balanced event
 
-A `Transfer` is a `Vec<Movement>` committed atomically. Each `Movement` is
-`{ from, to, asset, amount }`. On commit, `resolve()` turns the movements into
+A `Transfer` is a `Vec<Movement>` committed atomically. Each `Movement` carries
+an amount from one account to another. On commit, `resolve()` turns the movements into
 an `Envelope` of concrete postings to consume and create, and validation
 enforces per-asset conservation before anything is written. The whole entry
 commits or none of it does.
@@ -46,8 +46,8 @@ A minimal two-account entry:
 
 ```rust
 let transfer = TransferBuilder::new()
-    .pay(alice, bob, usd, Cent::from(50))
-    .build();
+    .pay(alice, bob, ("50.00", &usd))
+    .build()?;
 ```
 
 This is one journal entry: 50 USD leaves Alice, 50 USD arrives at Bob, and the
@@ -73,9 +73,9 @@ The equivalent business effects as one Kuatia transfer:
 ```rust
 let transfer = TransferBuilder::new()
     .book(sales_book)
-    .pay(customer, revenue, usd, Cent::from(100))
-    .pay(customer, tax_payable, usd, Cent::from(15))
-    .build();
+    .pay(customer, revenue, ("100.00", &usd))
+    .pay(customer, tax_payable, ("15.00", &usd))
+    .build()?;
 // One Transfer -> one Envelope -> one TransferRecord in the transfer log.
 ```
 

+ 5 - 4
doc/pending-states.md

@@ -35,21 +35,22 @@ Entering escrow is an ordinary payment, final the moment it commits:
 ```rust
 ledger.commit(
     TransferBuilder::new()
-        .pay(buyer, escrow_for(agreement), usd, amount)
+        .pay(buyer, escrow_for(agreement), ("120.00", &usd))
         .reference("escrow-in-7001")
-        .build(),
+        .build()?,
 ).await?;
 ```
 
 Leaving it is the same transfer with a different destination. Release pays the seller, refund pays the buyer, and nothing distinguishes them to the ledger:
 
 ```rust
+// The balance read hands back an amount, so it pays straight out again.
 let held = ledger.balance(&escrow_for(agreement), &usd).await?;
 ledger.commit(
     TransferBuilder::new()
-        .pay(escrow_for(agreement), seller, usd, held)   // or back to buyer
+        .pay(escrow_for(agreement), seller, held)   // or back to buyer
         .reference("escrow-release-7001")
-        .build(),
+        .build()?,
 ).await?;
 ```
 

+ 28 - 1
doc/storage-schema.md

@@ -3,7 +3,7 @@
 Reference for the tables `kuatia-storage-sql` creates. This is the composed
 end-state after replaying every migration in
 `crates/kuatia-storage-sql/src/migrations/` (`001_init` through
-`013_value_date`) plus the `_migrations` bookkeeping table created in
+`014_assets`) plus the `_migrations` bookkeeping table created in
 `crates/kuatia-storage-sql/src/migrate.rs`. It is a living reference: update it
 when a migration lands. For *why* the schema looks this way, see the ADRs it
 links to, not this file.
@@ -93,6 +93,11 @@ erDiagram
         TEXT name
         TEXT data
     }
+    assets {
+        INTEGER id PK
+        TEXT code
+        TEXT data
+    }
     balance_projection {
         BIGINT id PK
         BIGINT account
@@ -294,6 +299,28 @@ Book definitions (asset/account/flag policy) as JSON. Owned by `book.rs`
 
 - **Primary key**: `id`.
 
+### `assets`
+
+The asset registry: what each `AssetId` means and the decimal places its
+amounts are written at. Owned by `asset.rs` (`AssetStore`). A row is inserted
+once and never updated, which is what lets the ledger cache one for the life of
+the process. See [ADR-0028 (an amount carries its asset)](adr/0028-amount-carries-its-asset.md).
+
+| Column | Type | Key | Purpose |
+|---|---|---|---|
+| `id` | `INTEGER` | PK | Asset id, a `u32` supplied by the caller. |
+| `code` | `TEXT` | | Short code (`USD`), duplicated out of `data` to stay readable in a query. |
+| `data` | `TEXT` | | The `Asset` as JSON. |
+
+- **Primary key**: `id`.
+
+A posting read left-joins this table to rebuild the amount it returns, since a
+posting carries an amount and an amount carries its asset. Left-joined
+deliberately and with no foreign key: an inner join would silently drop a
+posting whose asset is absent, where a left join fails the decode and says so.
+The invariant lives at the commit, which resolves every asset a transfer moves
+value in (ADR-0029).
+
 ### `balance_projection`
 
 Append-only balance cache points: each row snapshots one `(account, subaccount,

+ 53 - 20
doc/transfers.md

@@ -7,38 +7,71 @@ 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.
+- **Intent layer**: callers express movements, each one an amount moving from
+  one account to another. 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:
+A movement is the fundamental building block. A caller states one as an
+[`Amount`](glossary.md#amount), which carries the asset with the value:
+
+```rust
+TransferBuilder::new()
+    .pay(from, to, ("50.00", usd))
+    .build()?
+```
+
+The stored movement holds the same thing:
 
 ```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)
+    amount: Amount,   // negative for the offset leg of a deposit
 }
 ```
 
+An amount serializes with its asset's definition alongside the value, so a
+stored movement reads back whole without consulting the registry (ADR-0029).
+The content address is the exception: it hashes the asset's id and the value
+alone, so writing a code or a symbol differently cannot re-identify a
+transfer.
+
 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
 
+Every verb takes one `amount`, which is anything that converts into an
+[`Amount`](glossary.md#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 cloning the handle |
+| `usd.amount(500)?` | the same conversion from the asset's side |
+
+The value comes first, the way the money reads aloud. `usd` is an `Arc<Asset>`
+from `ledger.asset(&id)`, or an `Asset` from `ledger.list_assets()`, so an
+unregistered asset cannot be named.
+
+`amount` is a method of the `Denominate` trait, which has to be in scope;
+`kuatia::prelude::*` and `kuatia_core::*` both bring it. The tuple forms need
+no import, and a conversion that fails is held until `build`, which is why
+that is where the `?` sits.
+
 ### Pay
 
 Transfer value between two accounts.
 
 ```rust
 TransferBuilder::new()
-    .pay(from, to, asset, amount)
-    .build()
+    .pay(from, to, amount)
+    .build()?
 ```
 
 Produces one movement:
@@ -59,8 +92,8 @@ and a credit on the target.
 
 ```rust
 TransferBuilder::new()
-    .deposit(to, asset, amount, external)
-    .build()
+    .deposit(to, amount, external)
+    .build()?
 ```
 
 Produces two movements:
@@ -85,8 +118,8 @@ Move value from an account to an external destination.
 
 ```rust
 TransferBuilder::new()
-    .withdraw(from, asset, amount, external)
-    .build()
+    .withdraw(from, amount, external)
+    .build()?
 ```
 
 Produces one movement:
@@ -104,8 +137,8 @@ For operations that don't fit the convenience methods:
 
 ```rust
 TransferBuilder::new()
-    .movement(from, to, asset, amount)
-    .build()
+    .movement(from, to, amount)
+    .build()?
 ```
 
 ## Resolve Algorithm
@@ -183,9 +216,9 @@ Set `reference` on anything that may legitimately repeat:
 
 ```rust
 let top_up = TransferBuilder::new()
-    .deposit(alice, usd, Cent::from(5_000), bank)?
+    .deposit(alice, ("50.00", usd), bank)
     .reference("top-up-8f21c4")   // this payment, not the last identical one
-    .build();
+    .build()?;
 ```
 
 Read the other way, this is retry safety: repeat the same reference and a
@@ -212,9 +245,9 @@ booked on, which is a correction, a late settlement or a future-dated order:
 
 ```rust
 let correction = TransferBuilder::new()
-    .pay(alice, bob, usd, amount)
+    .pay(alice, bob, (amount, usd))
     .value_date(ValueDate::new(2026, 11, 20)?)
-    .build();
+    .build()?;
 ```
 
 `ValueDate` is a calendar day, not an instant, so no timezone can shift it.
@@ -239,11 +272,11 @@ 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))
+    .deposit(alice, (1000, usd), bank)
+    .pay(alice, bob, (200, usd))
     .book(sales_book)
     .metadata(metadata)
-    .build();
+    .build()?;
 ```
 
 A single transfer can contain multiple movements of different types. All

Некоторые файлы не были показаны из-за большого количества измененных файлов