| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723 |
- #![allow(missing_docs)]
- use std::sync::Arc;
- use kuatia::error::LedgerError;
- use kuatia::ledger::Ledger;
- use kuatia::mem_store::InMemoryStore;
- use kuatia::store::TransferQuery;
- use kuatia_core::*;
- use std::collections::BTreeMap;
- /// 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)
- }
- fn eur() -> AssetId {
- AssetId::new(2)
- }
- fn account(id: i64) -> AccountId {
- AccountId::new(id)
- }
- fn external() -> AccountId {
- AccountId::new(99)
- }
- fn make_account(id: i64, flags: AccountFlags) -> Account {
- Account {
- id: AccountId::new(id),
- version: 1,
- flags,
- book: BookId(0),
- metadata: BTreeMap::new(),
- }
- }
- /// A ledger with nothing registered, for the registry's own tests.
- fn bare_ledger() -> Arc<Ledger> {
- Arc::new(Ledger::new(InMemoryStore::new()))
- }
- /// 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 asset in [
- Asset::new(usd(), "USD", "$", 2),
- Asset::new(eur(), "EUR", "\u{20ac}", 2),
- ] {
- ledger.create_asset(asset).await.unwrap();
- }
- }
- async fn setup_ledger() -> Arc<Ledger> {
- let store = InMemoryStore::new();
- let ledger = Arc::new(Ledger::new(store));
- ledger
- .store()
- .create_account(make_account(1, AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT))
- .await
- .unwrap();
- ledger
- .store()
- .create_account(make_account(2, AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT))
- .await
- .unwrap();
- ledger
- .store()
- .create_account(make_account(3, AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT))
- .await
- .unwrap();
- ledger
- .store()
- .create_account(make_account(99, AccountFlags::empty()))
- .await
- .unwrap();
- register_assets(&ledger).await;
- ledger
- }
- /// Helper: deposit via commit()
- async fn deposit(
- ledger: &Arc<Ledger>,
- to: AccountId,
- asset: AssetId,
- amount: i64,
- ext: AccountId,
- ) -> Receipt {
- let transfer = TransferBuilder::new()
- .deposit(to, money(asset, amount), ext)
- .build()
- .unwrap();
- ledger.commit(transfer).await.unwrap()
- }
- /// Helper: pay via commit()
- async fn pay(
- ledger: &Arc<Ledger>,
- from: AccountId,
- to: AccountId,
- asset: AssetId,
- amount: i64,
- ) -> Receipt {
- let transfer = TransferBuilder::new()
- .pay(from, to, money(asset, amount))
- .build()
- .unwrap();
- ledger.commit(transfer).await.unwrap()
- }
- /// Helper: withdraw via commit()
- async fn withdraw(
- ledger: &Arc<Ledger>,
- from: AccountId,
- asset: AssetId,
- amount: i64,
- ext: AccountId,
- ) -> Receipt {
- let transfer = TransferBuilder::new()
- .withdraw(from, money(asset, amount), ext)
- .build()
- .unwrap();
- ledger.commit(transfer).await.unwrap()
- }
- // ---------------------------------------------------------------------------
- // §4.1 Deposit
- // ---------------------------------------------------------------------------
- #[tokio::test]
- async fn deposit_creates_balanced_postings() {
- let ledger = setup_ledger().await;
- deposit(&ledger, account(1), usd(), 100, external()).await;
- assert_eq!(
- ledger
- .balance(&account(1), &usd())
- .await
- .unwrap()
- .minor_units(),
- 100
- );
- assert_eq!(
- ledger
- .balance(&external(), &usd())
- .await
- .unwrap()
- .minor_units(),
- -100
- );
- }
- // ---------------------------------------------------------------------------
- // §4.2 Internal transfer with change
- // ---------------------------------------------------------------------------
- #[tokio::test]
- async fn pay_with_change() {
- let ledger = setup_ledger().await;
- deposit(&ledger, account(1), usd(), 100, external()).await;
- pay(&ledger, account(1), account(2), usd(), 50).await;
- assert_eq!(
- ledger
- .balance(&account(1), &usd())
- .await
- .unwrap()
- .minor_units(),
- 50
- );
- assert_eq!(
- ledger
- .balance(&account(2), &usd())
- .await
- .unwrap()
- .minor_units(),
- 50
- );
- assert_eq!(
- ledger
- .balance(&external(), &usd())
- .await
- .unwrap()
- .minor_units(),
- -100
- );
- }
- // ---------------------------------------------------------------------------
- // §4.3 Multi-hop
- // ---------------------------------------------------------------------------
- #[tokio::test]
- async fn multi_hop_transfer() {
- let ledger = setup_ledger().await;
- deposit(&ledger, account(1), usd(), 100, external()).await;
- pay(&ledger, account(1), account(2), usd(), 50).await;
- pay(&ledger, account(2), account(3), usd(), 20).await;
- assert_eq!(
- ledger
- .balance(&account(1), &usd())
- .await
- .unwrap()
- .minor_units(),
- 50
- );
- assert_eq!(
- ledger
- .balance(&account(2), &usd())
- .await
- .unwrap()
- .minor_units(),
- 30
- );
- assert_eq!(
- ledger
- .balance(&account(3), &usd())
- .await
- .unwrap()
- .minor_units(),
- 20
- );
- assert_eq!(
- ledger
- .balance(&external(), &usd())
- .await
- .unwrap()
- .minor_units(),
- -100
- );
- }
- // ---------------------------------------------------------------------------
- // §4.5 Withdrawal
- // ---------------------------------------------------------------------------
- #[tokio::test]
- async fn withdrawal_reduces_external_liability() {
- let ledger = setup_ledger().await;
- deposit(&ledger, account(1), usd(), 100, external()).await;
- withdraw(&ledger, account(1), usd(), 50, external()).await;
- assert_eq!(
- ledger
- .balance(&account(1), &usd())
- .await
- .unwrap()
- .minor_units(),
- 50
- );
- assert_eq!(
- ledger
- .balance(&external(), &usd())
- .await
- .unwrap()
- .minor_units(),
- -50
- );
- }
- // ---------------------------------------------------------------------------
- // Full round-trip: deposit -> pay -> withdraw -> verify total = 0
- // ---------------------------------------------------------------------------
- #[tokio::test]
- async fn full_round_trip() {
- let ledger = setup_ledger().await;
- deposit(&ledger, account(1), usd(), 100, external()).await;
- pay(&ledger, account(1), account(2), usd(), 60).await;
- withdraw(&ledger, account(2), usd(), 60, external()).await;
- withdraw(&ledger, account(1), usd(), 40, external()).await;
- assert_eq!(
- ledger
- .balance(&account(1), &usd())
- .await
- .unwrap()
- .minor_units(),
- 0
- );
- assert_eq!(
- ledger
- .balance(&account(2), &usd())
- .await
- .unwrap()
- .minor_units(),
- 0
- );
- assert_eq!(
- ledger
- .balance(&external(), &usd())
- .await
- .unwrap()
- .minor_units(),
- 0
- );
- }
- // ---------------------------------------------------------------------------
- // Idempotency -- committing same envelope twice returns same receipt
- // ---------------------------------------------------------------------------
- #[tokio::test]
- async fn idempotent_commit() {
- let ledger = setup_ledger().await;
- let envelope = EnvelopeBuilder::new()
- .creates(vec![
- NewPosting {
- owner: account(1),
- amount: money(usd(), 100),
- payer: None,
- },
- NewPosting {
- owner: external(),
- amount: money(usd(), -100),
- payer: None,
- },
- ])
- .build();
- let r1 = ledger.commit_envelope(envelope.clone()).await.unwrap();
- let r2 = ledger.commit_envelope(envelope).await.unwrap();
- assert_eq!(r1.transfer_id, r2.transfer_id);
- // Balance should only be 100, not 200 (second commit was a no-op)
- assert_eq!(
- ledger
- .balance(&account(1), &usd())
- .await
- .unwrap()
- .minor_units(),
- 100
- );
- }
- /// A deposit consumes nothing, so two of the same amount to the same account
- /// are byte-identical and the second is a replay. This is the case a reference
- /// exists for, and the case that loses money without one.
- #[tokio::test]
- async fn identical_deposits_need_a_reference_to_both_land() {
- let ledger = setup_ledger().await;
- let plain = || {
- TransferBuilder::new()
- .deposit(account(1), money(usd(), 100), external())
- .build()
- .unwrap()
- };
- let first = ledger.commit(plain()).await.unwrap();
- let second = ledger.commit(plain()).await.unwrap();
- assert_eq!(
- first.transfer_id, second.transfer_id,
- "identical deposits are one transfer"
- );
- assert_eq!(
- ledger
- .balance(&account(1), &usd())
- .await
- .unwrap()
- .minor_units(),
- 100,
- "the second deposit was a replay, not a second credit"
- );
- let referenced = |r: &str| {
- TransferBuilder::new()
- .deposit(account(1), money(usd(), 100), external())
- .reference(r)
- .build()
- .unwrap()
- };
- let a = ledger.commit(referenced("top-up-1")).await.unwrap();
- let b = ledger.commit(referenced("top-up-2")).await.unwrap();
- assert_ne!(a.transfer_id, b.transfer_id);
- assert_eq!(
- ledger
- .balance(&account(1), &usd())
- .await
- .unwrap()
- .minor_units(),
- 300,
- "distinct references make distinct transfers"
- );
- // Repeating a reference is how a retry stays idempotent.
- let replay = ledger.commit(referenced("top-up-2")).await.unwrap();
- assert_eq!(replay.transfer_id, b.transfer_id);
- assert_eq!(
- ledger
- .balance(&account(1), &usd())
- .await
- .unwrap()
- .minor_units(),
- 300
- );
- }
- /// A payment distinguishes itself: the second consumes the change the first
- /// created, so it hashes differently with no reference set.
- #[tokio::test]
- async fn identical_payments_are_distinct_without_a_reference() {
- let ledger = setup_ledger().await;
- deposit(&ledger, account(1), usd(), 100, external()).await;
- let pay_ten = || {
- TransferBuilder::new()
- .pay(account(1), account(2), money(usd(), 10))
- .build()
- .unwrap()
- };
- let first = ledger.commit(pay_ten()).await.unwrap();
- let second = ledger.commit(pay_ten()).await.unwrap();
- assert_ne!(first.transfer_id, second.transfer_id);
- assert_eq!(
- ledger
- .balance(&account(2), &usd())
- .await
- .unwrap()
- .minor_units(),
- 20
- );
- }
- /// A value date is part of the content address, so two entries that differ only
- /// in the day they take effect are two transfers. This is also what lets a
- /// backdated deposit repeat without a reference.
- #[tokio::test]
- async fn value_date_distinguishes_otherwise_identical_transfers() {
- let ledger = setup_ledger().await;
- let dated = |y, m, d| {
- TransferBuilder::new()
- .deposit(account(1), money(usd(), 100), external())
- .value_date(ValueDate::new(y, m, d).unwrap())
- .build()
- .unwrap()
- };
- let first = ledger.commit(dated(2026, 11, 20)).await.unwrap();
- let second = ledger.commit(dated(2026, 11, 21)).await.unwrap();
- assert_ne!(first.transfer_id, second.transfer_id);
- assert_eq!(
- ledger
- .balance(&account(1), &usd())
- .await
- .unwrap()
- .minor_units(),
- 200
- );
- // The same day twice is still one transfer: the date distinguishes, it does
- // not excuse a caller from a reference.
- let replay = ledger.commit(dated(2026, 11, 20)).await.unwrap();
- assert_eq!(replay.transfer_id, first.transfer_id);
- assert_eq!(
- ledger
- .balance(&account(1), &usd())
- .await
- .unwrap()
- .minor_units(),
- 200
- );
- }
- /// Transfers are queryable by the day they take effect, independently of the
- /// instant they were committed. Everything here commits now, so a window on the
- /// commit clock cannot tell these apart.
- #[tokio::test]
- async fn transfers_filter_by_value_date_not_commit_time() {
- let ledger = setup_ledger().await;
- for (day, amount) in [(18, 10), (20, 20), (22, 30)] {
- ledger
- .commit(
- TransferBuilder::new()
- .deposit(account(1), money(usd(), amount), external())
- .value_date(ValueDate::new(2026, 11, day).unwrap())
- .build()
- .unwrap(),
- )
- .await
- .unwrap();
- }
- let window = TransferQuery {
- account: Some(1),
- from_value_date: Some(ValueDate::new(2026, 11, 19).unwrap()),
- to_value_date: Some(ValueDate::new(2026, 11, 22).unwrap()),
- ..Default::default()
- };
- let page = ledger.query_transfers(&window).await.unwrap();
- assert_eq!(page.total, 1, "only the entry valued on the 20th");
- // An entry with no value date is valued when it was booked, so it sits
- // outside an explicit window rather than inside every one.
- deposit(&ledger, account(1), usd(), 40, external()).await;
- let page = ledger.query_transfers(&window).await.unwrap();
- assert_eq!(page.total, 1);
- }
- /// A reversal carries the original's value date, so the period the entry landed
- /// in is the period it is undone in.
- #[tokio::test]
- async fn reversal_keeps_the_original_value_date() {
- let ledger = setup_ledger().await;
- let valued = ValueDate::new(2026, 11, 20).unwrap();
- let receipt = ledger
- .commit(
- TransferBuilder::new()
- .deposit(account(1), money(usd(), 100), external())
- .value_date(valued)
- .build()
- .unwrap(),
- )
- .await
- .unwrap();
- ledger.reverse(&receipt.transfer_id).await.unwrap();
- let window = TransferQuery {
- account: Some(1),
- from_value_date: Some(valued),
- to_value_date: Some(ValueDate::new(2026, 11, 21).unwrap()),
- ..Default::default()
- };
- assert_eq!(
- ledger.query_transfers(&window).await.unwrap().total,
- 2,
- "the entry and its reversal both fall in the period"
- );
- assert_eq!(
- ledger
- .balance(&account(1), &usd())
- .await
- .unwrap()
- .minor_units(),
- 0
- );
- }
- // ---------------------------------------------------------------------------
- // Overdraft prevention
- // ---------------------------------------------------------------------------
- #[tokio::test]
- async fn overdraft_rejected() {
- let ledger = setup_ledger().await;
- deposit(&ledger, account(1), usd(), 50, external()).await;
- let transfer = TransferBuilder::new()
- .pay(account(1), account(2), money(usd(), 100))
- .build()
- .unwrap();
- let result = ledger.commit(transfer).await;
- assert!(result.is_err());
- // Balance unchanged
- assert_eq!(
- ledger
- .balance(&account(1), &usd())
- .await
- .unwrap()
- .minor_units(),
- 50
- );
- }
- // ---------------------------------------------------------------------------
- // Reverse: forward compensating transfer
- // ---------------------------------------------------------------------------
- #[tokio::test]
- async fn reverse_restores_balances() {
- let ledger = setup_ledger().await;
- deposit(&ledger, account(1), usd(), 100, external()).await;
- let pay_receipt = pay(&ledger, account(1), account(2), usd(), 60).await;
- assert_eq!(
- ledger
- .balance(&account(1), &usd())
- .await
- .unwrap()
- .minor_units(),
- 40
- );
- assert_eq!(
- ledger
- .balance(&account(2), &usd())
- .await
- .unwrap()
- .minor_units(),
- 60
- );
- // Reverse the payment
- ledger.reverse(&pay_receipt.transfer_id).await.unwrap();
- assert_eq!(
- ledger
- .balance(&account(1), &usd())
- .await
- .unwrap()
- .minor_units(),
- 100
- );
- assert_eq!(
- ledger
- .balance(&account(2), &usd())
- .await
- .unwrap()
- .minor_units(),
- 0
- );
- }
- // ---------------------------------------------------------------------------
- // Frozen account blocks transfers
- // ---------------------------------------------------------------------------
- #[tokio::test]
- async fn frozen_account_rejected() {
- let store = InMemoryStore::new();
- let ledger = Arc::new(Ledger::new(store));
- register_assets(&ledger).await;
- let mut frozen = make_account(1, AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT);
- frozen.flags = AccountFlags::FROZEN;
- ledger.store().create_account(frozen).await.unwrap();
- ledger
- .store()
- .create_account(make_account(99, AccountFlags::empty()))
- .await
- .unwrap();
- let transfer = TransferBuilder::new()
- .deposit(account(1), money(usd(), 100), external())
- .build()
- .unwrap();
- let result = ledger.commit(transfer).await;
- assert!(result.is_err());
- }
- // ---------------------------------------------------------------------------
- // Multi-asset: each asset conserves independently
- // ---------------------------------------------------------------------------
- #[tokio::test]
- async fn multi_asset_independent_balances() {
- let ledger = setup_ledger().await;
- deposit(&ledger, account(1), usd(), 100, external()).await;
- deposit(&ledger, account(1), eur(), 200, external()).await;
- assert_eq!(
- ledger
- .balance(&account(1), &usd())
- .await
- .unwrap()
- .minor_units(),
- 100
- );
- assert_eq!(
- ledger
- .balance(&account(1), &eur())
- .await
- .unwrap()
- .minor_units(),
- 200
- );
- pay(&ledger, account(1), account(2), usd(), 30).await;
- assert_eq!(
- ledger
- .balance(&account(1), &usd())
- .await
- .unwrap()
- .minor_units(),
- 70
- );
- assert_eq!(
- ledger
- .balance(&account(1), &eur())
- .await
- .unwrap()
- .minor_units(),
- 200
- );
- assert_eq!(
- ledger
- .balance(&account(2), &usd())
- .await
- .unwrap()
- .minor_units(),
- 30
- );
- }
- // ---------------------------------------------------------------------------
- // §4.4 FX trade via market account
- // ---------------------------------------------------------------------------
- #[tokio::test]
- async fn fx_trade_via_market_account() {
- let store = InMemoryStore::new();
- let ledger = Arc::new(Ledger::new(store));
- register_assets(&ledger).await;
- // Setup accounts
- for (id, policy) in [
- (1, AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT),
- (50, AccountFlags::empty()), // FX market account
- (99, AccountFlags::empty()),
- ] {
- ledger
- .store()
- .create_account(make_account(id, policy))
- .await
- .unwrap();
- }
- // Seed: account1 has 100 USD, fx has 92 EUR
- deposit(&ledger, account(1), usd(), 100, external()).await;
- deposit(&ledger, account(50), eur(), 92, external()).await;
- // FX trade: account1 sells 100 USD, buys 92 EUR
- // Build the atomic envelope manually since it spans two assets
- let a1_usd_postings = ledger
- .store()
- .get_postings_by_account(1, None, Some(&usd()), PostingFilter::Live)
- .await
- .unwrap();
- let fx_eur_postings = ledger
- .store()
- .get_postings_by_account(50, None, Some(&eur()), PostingFilter::Live)
- .await
- .unwrap();
- let envelope = EnvelopeBuilder::new()
- .consumes(vec![a1_usd_postings[0].id, fx_eur_postings[0].id])
- .creates(vec![
- NewPosting {
- owner: account(50),
- amount: money(usd(), 100),
- payer: Some(account(1)),
- },
- NewPosting {
- owner: account(1),
- amount: money(eur(), 92),
- payer: Some(account(50)),
- },
- ])
- .build();
- ledger.commit_envelope(envelope).await.unwrap();
- // Verify
- assert_eq!(
- ledger
- .balance(&account(1), &usd())
- .await
- .unwrap()
- .minor_units(),
- 0
- );
- assert_eq!(
- ledger
- .balance(&account(1), &eur())
- .await
- .unwrap()
- .minor_units(),
- 92
- );
- assert_eq!(
- ledger
- .balance(&account(50), &usd())
- .await
- .unwrap()
- .minor_units(),
- 100
- );
- assert_eq!(
- ledger
- .balance(&account(50), &eur())
- .await
- .unwrap()
- .minor_units(),
- 0
- );
- }
- // ---------------------------------------------------------------------------
- // Account lifecycle: freeze / unfreeze / close
- // ---------------------------------------------------------------------------
- #[tokio::test]
- async fn freeze_blocks_transfers() {
- let ledger = setup_ledger().await;
- deposit(&ledger, account(1), usd(), 100, external()).await;
- ledger.freeze(&account(1)).await.unwrap();
- // Paying from a frozen account should fail
- let transfer = TransferBuilder::new()
- .pay(account(1), account(2), money(usd(), 50))
- .build()
- .unwrap();
- let result = ledger.commit(transfer).await;
- assert!(result.is_err());
- // Balance unchanged
- assert_eq!(
- ledger
- .balance(&account(1), &usd())
- .await
- .unwrap()
- .minor_units(),
- 100
- );
- }
- #[tokio::test]
- async fn unfreeze_re_enables_transfers() {
- let ledger = setup_ledger().await;
- deposit(&ledger, account(1), usd(), 100, external()).await;
- ledger.freeze(&account(1)).await.unwrap();
- ledger.unfreeze(&account(1)).await.unwrap();
- // Should work again
- pay(&ledger, account(1), account(2), usd(), 50).await;
- assert_eq!(
- ledger
- .balance(&account(1), &usd())
- .await
- .unwrap()
- .minor_units(),
- 50
- );
- }
- #[tokio::test]
- async fn close_account_with_zero_balance() {
- let ledger = setup_ledger().await;
- // Account 3 has never transacted -- zero balance, no postings
- ledger.close(&account(3)).await.unwrap();
- // Closed account rejects deposits
- let transfer = TransferBuilder::new()
- .deposit(account(3), money(usd(), 100), external())
- .build()
- .unwrap();
- let result = ledger.commit(transfer).await;
- assert!(result.is_err());
- }
- #[tokio::test]
- async fn close_account_with_balance_rejected() {
- let ledger = setup_ledger().await;
- deposit(&ledger, account(1), usd(), 100, external()).await;
- // Should fail -- account still has active postings
- let result = ledger.close(&account(1)).await;
- assert!(result.is_err());
- // Balance unchanged
- assert_eq!(
- ledger
- .balance(&account(1), &usd())
- .await
- .unwrap()
- .minor_units(),
- 100
- );
- }
- /// Paying the whole balance leaves no change posting, so the account holds
- /// nothing live and closing it is allowed: spent postings do not block close.
- #[tokio::test]
- async fn close_succeeds_once_postings_are_spent() {
- let ledger = setup_ledger().await;
- deposit(&ledger, account(1), usd(), 100, external()).await;
- let transfer = TransferBuilder::new()
- .pay(account(1), account(2), money(usd(), 100))
- .build()
- .unwrap();
- ledger.commit(transfer).await.unwrap();
- ledger.close(&account(1)).await.unwrap();
- assert!(ledger.get_account(&account(1)).await.unwrap().is_closed());
- }
- #[tokio::test]
- async fn freeze_closed_account_rejected() {
- let ledger = setup_ledger().await;
- ledger.close(&account(3)).await.unwrap();
- let result = ledger.freeze(&account(3)).await;
- assert!(result.is_err());
- }
- // ---------------------------------------------------------------------------
- // Query layer: history, postings, list_accounts, get_account
- // ---------------------------------------------------------------------------
- #[tokio::test]
- async fn history_returns_transfers_for_account() {
- let ledger = setup_ledger().await;
- deposit(&ledger, account(1), usd(), 100, external()).await;
- pay(&ledger, account(1), account(2), usd(), 40).await;
- deposit(&ledger, account(2), usd(), 50, external()).await;
- let h1 = ledger.history(&account(1)).await.unwrap();
- // account(1) was in the deposit and the pay
- assert_eq!(h1.len(), 2);
- let h2 = ledger.history(&account(2)).await.unwrap();
- // account(2) was in the pay and a second deposit
- assert_eq!(h2.len(), 2);
- }
- #[tokio::test]
- async fn postings_returns_all_postings() {
- let ledger = setup_ledger().await;
- deposit(&ledger, account(1), usd(), 100, external()).await;
- pay(&ledger, account(1), account(2), usd(), 60).await;
- let posts = ledger.postings(&account(1)).await.unwrap();
- // Original 100 posting (now consumed) + 40 change posting (active)
- assert_eq!(posts.len(), 2);
- let with_state = ledger.postings_with_state(&account(1)).await.unwrap();
- let active: Vec<_> = with_state
- .iter()
- .filter(|(_, s)| *s == PostingState::Live)
- .collect();
- assert_eq!(active.len(), 1);
- assert_eq!(active[0].0.amount.minor_units(), 40);
- }
- #[tokio::test]
- async fn get_postings_resolves_a_consumed_posting() {
- let ledger = setup_ledger().await;
- deposit(&ledger, account(1), usd(), 100, external()).await;
- pay(&ledger, account(1), account(2), usd(), 60).await;
- let with_state = ledger.postings_with_state(&account(1)).await.unwrap();
- let spent: Vec<PostingId> = with_state
- .iter()
- .filter(|(_, s)| *s == PostingState::Spent)
- .map(|(p, _)| p.id)
- .collect();
- assert_eq!(spent.len(), 1);
- let found = ledger.get_postings(&spent).await.unwrap();
- assert_eq!(found.len(), 1);
- assert_eq!(found[0].owner, account(1));
- assert_eq!(found[0].amount.minor_units(), 100);
- }
- #[tokio::test]
- async fn get_postings_unknown_id_is_an_error() {
- let ledger = setup_ledger().await;
- let unknown = PostingId {
- transfer: TransferId([7u8; 32]),
- index: 0,
- };
- assert!(ledger.get_postings(&[unknown]).await.is_err());
- }
- #[tokio::test]
- async fn list_accounts_returns_all() {
- let ledger = setup_ledger().await;
- let accounts = ledger.list_accounts().await.unwrap();
- // setup_ledger creates accounts 1, 2, 3, 99
- assert_eq!(accounts.len(), 4);
- }
- #[tokio::test]
- async fn get_account_by_id() {
- let ledger = setup_ledger().await;
- let acc = ledger.get_account(&account(1)).await.unwrap();
- assert_eq!(acc.id, account(1));
- assert!(acc.forbids_overdraft());
- }
- #[tokio::test]
- async fn get_account_not_found() {
- let ledger = setup_ledger().await;
- let result = ledger.get_account(&account(999)).await;
- assert!(result.is_err());
- }
- // ---------------------------------------------------------------------------
- // Append-only accounts: version history, version conflict, account_versions
- // ---------------------------------------------------------------------------
- #[tokio::test]
- async fn account_history_tracks_versions() {
- let ledger = setup_ledger().await;
- // Version 1: created
- let history = ledger.account_history(&account(1)).await.unwrap();
- assert_eq!(history.len(), 1);
- assert_eq!(history[0].version, 1);
- // Version 2: frozen
- ledger.freeze(&account(1)).await.unwrap();
- let history = ledger.account_history(&account(1)).await.unwrap();
- assert_eq!(history.len(), 2);
- assert_eq!(history[1].version, 2);
- assert!(history[1].is_frozen());
- // Version 3: unfrozen
- ledger.unfreeze(&account(1)).await.unwrap();
- let history = ledger.account_history(&account(1)).await.unwrap();
- assert_eq!(history.len(), 3);
- assert_eq!(history[2].version, 3);
- assert!(!history[2].is_frozen());
- }
- #[tokio::test]
- async fn store_never_compacts() {
- let ledger = setup_ledger().await;
- // Freeze and unfreeze multiple times
- for _ in 0..5 {
- ledger.freeze(&account(1)).await.unwrap();
- ledger.unfreeze(&account(1)).await.unwrap();
- }
- // All 11 versions preserved (1 creation + 10 mutations)
- let history = ledger.account_history(&account(1)).await.unwrap();
- assert_eq!(history.len(), 11);
- // Versions are monotonically increasing
- for (i, acc) in history.iter().enumerate() {
- assert_eq!(acc.version, (i + 1) as u64);
- }
- }
- #[tokio::test]
- async fn transfer_records_account_snapshots() {
- let ledger = setup_ledger().await;
- deposit(&ledger, account(1), usd(), 100, external()).await;
- // The envelope should have account_snapshots populated by the resolve step
- let transfers = ledger.history(&account(1)).await.unwrap();
- assert_eq!(transfers.len(), 1);
- assert!(!transfers[0].envelope.account_snapshots().is_empty());
- }
- #[tokio::test]
- async fn stale_snapshot_rejected() {
- let ledger = setup_ledger().await;
- // Get current snapshot for account(1)
- let acc1 = ledger.get_account(&account(1)).await.unwrap();
- let stale_snapshot = kuatia_core::account_snapshot_id(&acc1);
- // Freeze account(1) -- changes its snapshot hash
- ledger.freeze(&account(1)).await.unwrap();
- // Build an envelope with the stale snapshot
- let envelope = EnvelopeBuilder::new()
- .creates(vec![
- NewPosting {
- owner: account(1),
- amount: money(usd(), 100),
- payer: None,
- },
- NewPosting {
- owner: external(),
- amount: money(usd(), -100),
- payer: None,
- },
- ])
- .account_snapshots(vec![stale_snapshot])
- .build();
- let result = ledger.commit_envelope(envelope).await;
- assert!(result.is_err());
- }
- #[tokio::test]
- async fn account_hash_deterministic() {
- let acc = make_account(42, AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT);
- let h1 = kuatia_core::account_hash(&acc);
- let h2 = kuatia_core::account_hash(&acc);
- assert_eq!(h1, h2);
- }
- #[tokio::test]
- async fn account_hash_changes_with_version() {
- let mut acc = make_account(42, AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT);
- let h1 = kuatia_core::account_hash(&acc);
- acc.version = 2;
- acc.flags |= AccountFlags::FROZEN;
- let h2 = kuatia_core::account_hash(&acc);
- assert_ne!(h1, h2);
- }
- // ---------------------------------------------------------------------------
- // Overdraft via negative postings
- // ---------------------------------------------------------------------------
- #[tokio::test]
- async fn overdraft_creates_negative_posting() {
- let store = InMemoryStore::new();
- let ledger = Arc::new(Ledger::new(store));
- register_assets(&ledger).await;
- for (id, flags) in [
- (10, AccountFlags::empty()),
- (2, AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT),
- (99, AccountFlags::empty()),
- ] {
- ledger
- .store()
- .create_account(make_account(id, flags))
- .await
- .unwrap();
- }
- // Fund account 10 with 50, then pay 100 — overdraft covers the 50 shortfall.
- deposit(&ledger, account(10), usd(), 50, external()).await;
- pay(&ledger, account(10), account(2), usd(), 100).await;
- assert_eq!(
- ledger
- .balance(&account(10), &usd())
- .await
- .unwrap()
- .minor_units(),
- -50
- );
- assert_eq!(
- ledger
- .balance(&account(2), &usd())
- .await
- .unwrap()
- .minor_units(),
- 100
- );
- // A negative posting now backs the overdraft.
- let postings = ledger
- .store()
- .get_postings_by_account(10, None, Some(&usd()), PostingFilter::Live)
- .await
- .unwrap();
- assert!(postings.iter().any(|p| p.amount.minor_units() == -50));
- }
- #[tokio::test]
- async fn debit_must_not_exceed_credit_rejects_overspend() {
- let store = InMemoryStore::new();
- let ledger = Arc::new(Ledger::new(store));
- register_assets(&ledger).await;
- for (id, flags) in [
- (10, AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT),
- (2, AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT),
- (99, AccountFlags::empty()),
- ] {
- ledger
- .store()
- .create_account(make_account(id, flags))
- .await
- .unwrap();
- }
- // Account 10 forbids overdraft, so paying 100 from an empty balance fails.
- let transfer = TransferBuilder::new()
- .pay(account(10), account(2), money(usd(), 100))
- .build()
- .unwrap();
- assert!(ledger.commit(transfer).await.is_err());
- assert_eq!(
- ledger
- .balance(&account(10), &usd())
- .await
- .unwrap()
- .minor_units(),
- 0
- );
- }
- #[tokio::test]
- async fn overdraft_allows_arbitrary_negative() {
- let store = InMemoryStore::new();
- let ledger = Arc::new(Ledger::new(store));
- register_assets(&ledger).await;
- for (id, flags) in [
- (10, AccountFlags::empty()),
- (2, AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT),
- (99, AccountFlags::empty()),
- ] {
- ledger
- .store()
- .create_account(make_account(id, flags))
- .await
- .unwrap();
- }
- pay(&ledger, account(10), account(2), usd(), 1_000_000).await;
- assert_eq!(
- ledger
- .balance(&account(10), &usd())
- .await
- .unwrap()
- .minor_units(),
- -1_000_000
- );
- }
- // ---------------------------------------------------------------------------
- // Book policy enforcement
- // ---------------------------------------------------------------------------
- #[tokio::test]
- async fn book_policy_rejects_disallowed_asset() {
- let ledger = setup_ledger().await;
- // Book 5 permits only EUR.
- let book = BookBuilder::new("eur-only")
- .id(BookId::new(5))
- .allow_asset(eur())
- .build();
- ledger.store().create_book(book).await.unwrap();
- deposit(&ledger, account(1), usd(), 100, external()).await;
- // Paying USD under a EUR-only book is rejected, balance unchanged.
- let transfer = TransferBuilder::new()
- .book(BookId::new(5))
- .pay(account(1), account(2), money(usd(), 50))
- .build()
- .unwrap();
- assert!(ledger.commit(transfer).await.is_err());
- assert_eq!(
- ledger
- .balance(&account(1), &usd())
- .await
- .unwrap()
- .minor_units(),
- 100
- );
- }
- #[tokio::test]
- async fn transfer_in_missing_named_book_is_rejected() {
- let ledger = setup_ledger().await;
- deposit(&ledger, account(1), usd(), 100, external()).await;
- let transfer = TransferBuilder::new()
- .book(BookId::new(404))
- .pay(account(1), account(2), money(usd(), 50))
- .build()
- .unwrap();
- assert!(ledger.commit(transfer).await.is_err());
- assert_eq!(
- ledger
- .balance(&account(1), &usd())
- .await
- .unwrap()
- .minor_units(),
- 100
- );
- }
- // ---------------------------------------------------------------------------
- // Content-addressed determinism
- // ---------------------------------------------------------------------------
- #[tokio::test]
- async fn identical_transfers_share_transfer_id() {
- // Two independently-built default-book transfers must hash identically.
- let a = TransferBuilder::new()
- .pay(account(1), account(2), money(usd(), 10))
- .build()
- .unwrap();
- let b = TransferBuilder::new()
- .pay(account(1), account(2), money(usd(), 10))
- .build()
- .unwrap();
- assert_eq!(a.book, b.book, "default book must be deterministic");
- assert_eq!(a.book, DEFAULT_BOOK);
- }
- // ---------------------------------------------------------------------------
- // Subaccounts (ADR-0012)
- // ---------------------------------------------------------------------------
- #[tokio::test]
- async fn subaccount_balances_are_segregated() {
- let ledger = setup_ledger().await;
- let sub = AccountId::with_sub(1, 7);
- // A subaccount is a full account record with its own policy.
- ledger
- .store()
- .create_account(Account::debit_must_not_exceed_credit(sub))
- .await
- .unwrap();
- // Fund the main account (1, 0) and the subaccount (1, 7) independently.
- deposit(&ledger, account(1), usd(), 100, external()).await;
- deposit(&ledger, sub, usd(), 40, external()).await;
- // balance() reads exactly one subaccount and never rolls up the other.
- assert_eq!(
- ledger
- .balance(&account(1), &usd())
- .await
- .unwrap()
- .minor_units(),
- 100
- );
- assert_eq!(
- ledger.balance(&sub, &usd()).await.unwrap().minor_units(),
- 40
- );
- // list_subaccounts spans the base id's subaccounts, sorted.
- let subs = ledger.list_subaccounts(&account(1)).await.unwrap();
- assert_eq!(subs, vec![account(1), sub]);
- // balances() reports one entry per subaccount, never summed.
- let all = ledger.balances(&account(1), &usd(), None).await.unwrap();
- assert_eq!(all.len(), 2);
- assert_eq!(
- all.iter()
- .find(|b| b.account == account(1))
- .unwrap()
- .amount
- .minor_units(),
- 100
- );
- assert_eq!(
- all.iter()
- .find(|b| b.account == sub)
- .unwrap()
- .amount
- .minor_units(),
- 40
- );
- // A subaccount filter restricts to that one.
- let just_sub = ledger.balances(&account(1), &usd(), Some(7)).await.unwrap();
- assert_eq!(just_sub.len(), 1);
- assert_eq!(just_sub[0].account, sub);
- assert_eq!(just_sub[0].amount.minor_units(), 40);
- }
- #[tokio::test]
- async fn pay_moves_value_between_subaccounts() {
- let ledger = setup_ledger().await;
- let sub = AccountId::with_sub(1, 7);
- ledger
- .store()
- .create_account(Account::debit_must_not_exceed_credit(sub))
- .await
- .unwrap();
- deposit(&ledger, sub, usd(), 40, external()).await;
- // Move 30 from subaccount (1, 7) to the main account (1, 0).
- pay(&ledger, sub, account(1), usd(), 30).await;
- assert_eq!(
- ledger.balance(&sub, &usd()).await.unwrap().minor_units(),
- 10
- );
- assert_eq!(
- ledger
- .balance(&account(1), &usd())
- .await
- .unwrap()
- .minor_units(),
- 30
- );
- }
- #[tokio::test]
- async fn closed_subaccounts_drop_out_of_aggregate_reads() {
- let ledger = setup_ledger().await;
- let sub = AccountId::with_sub(1, 7);
- ledger
- .store()
- .create_account(Account::debit_must_not_exceed_credit(sub))
- .await
- .unwrap();
- // The subaccount is created then closed while empty.
- ledger.close(&sub).await.unwrap();
- // list_subaccounts and balances exclude the closed subaccount.
- let subs = ledger.list_subaccounts(&account(1)).await.unwrap();
- assert_eq!(subs, vec![account(1)]);
- let all = ledger.balances(&account(1), &usd(), None).await.unwrap();
- assert!(all.iter().all(|b| b.account != sub));
- }
- #[tokio::test]
- async fn registering_an_asset_makes_it_readable() {
- let ledger = bare_ledger();
- let usd = Asset::new(usd(), "USD", "$", 2);
- ledger.create_asset(usd.clone()).await.unwrap();
- let got = ledger.asset_by_id(&usd).await.unwrap();
- assert_eq!(*got, usd);
- // Built from the row the registry handed back, so the code and the scale in
- // the rendering are the registered ones.
- assert_eq!(Amount::from((65_000, got)).to_string(), "650.00 USD");
- assert_eq!(ledger.list_assets().await.unwrap(), vec![usd]);
- }
- #[tokio::test]
- async fn an_unregistered_asset_is_not_found() {
- let ledger = bare_ledger();
- let err = ledger.asset_by_id(&usd()).await.unwrap_err();
- assert!(matches!(err, LedgerError::AssetNotFound(id) if id == usd()));
- }
- /// A second registration is refused rather than merged, because a row is
- /// immutable: changing the precision would reinterpret every amount already
- /// recorded against the asset.
- #[tokio::test]
- async fn registering_a_known_asset_is_refused() {
- let ledger = bare_ledger();
- ledger
- .create_asset(Asset::new(usd(), "USD", "$", 2))
- .await
- .unwrap();
- let err = ledger
- .create_asset(Asset::new(usd(), "NOT-USD", "!", 8))
- .await
- .unwrap_err();
- assert!(matches!(err, LedgerError::AssetAlreadyExists(id) if id == usd()));
- assert_eq!(ledger.asset_by_id(&usd()).await.unwrap().decimals, 2);
- }
- /// A miss is not cached, so an asset registered after a failed lookup is found.
- #[tokio::test]
- async fn a_missed_lookup_does_not_poison_the_cache() {
- let ledger = bare_ledger();
- assert!(ledger.asset_by_id(&eur()).await.is_err());
- ledger
- .create_asset(Asset::new(eur(), "EUR", "\u{20ac}", 2))
- .await
- .unwrap();
- assert_eq!(ledger.asset_by_id(&eur()).await.unwrap().code, "EUR");
- }
- /// A balance comes back denominated, so what a caller holds is a quantity of a
- /// named asset rather than a bare number.
- #[tokio::test]
- async fn a_balance_carries_the_asset_it_was_read_for() {
- let ledger = setup_ledger().await;
- deposit(&ledger, account(1), usd(), 100, external()).await;
- let bal = ledger.balance(&account(1), &usd()).await.unwrap();
- assert_eq!(bal.asset_id(), usd());
- assert_eq!(bal.minor_units(), 100);
- assert_eq!(bal.to_string(), "1.00 USD");
- assert_eq!(
- ledger
- .balance_exact(&account(1), &usd())
- .await
- .unwrap()
- .asset_id(),
- usd()
- );
- }
- /// The bug the type exists to stop: two balances from one ledger, in different
- /// assets, refusing to be added instead of producing a number denominated in
- /// nothing.
- #[tokio::test]
- async fn two_assets_from_one_ledger_do_not_add() {
- let ledger = setup_ledger().await;
- deposit(&ledger, account(1), usd(), 100, external()).await;
- deposit(&ledger, account(1), eur(), 50, external()).await;
- let dollars = ledger.balance(&account(1), &usd()).await.unwrap();
- let euros = ledger.balance(&account(1), &eur()).await.unwrap();
- assert_eq!(
- dollars.checked_add(&euros),
- Err(AmountError::AssetMismatch {
- left: usd(),
- right: eur(),
- })
- );
- assert_eq!(dollars.checked_add(&dollars).unwrap().minor_units(), 200);
- }
- /// A shortfall names the asset that fell short, so a caller reporting it does
- /// not have to guess which one the two values are in.
- #[tokio::test]
- async fn insufficient_funds_names_the_asset() {
- let ledger = setup_ledger().await;
- deposit(&ledger, account(1), usd(), 40, external()).await;
- let err = ledger
- .commit(
- TransferBuilder::new()
- .pay(account(1), account(2), money(usd(), 100))
- .build()
- .unwrap(),
- )
- .await
- .unwrap_err();
- let LedgerError::Selection(shortfall) = err else {
- panic!("expected a selection failure, got {err:?}");
- };
- assert_eq!(shortfall.available.asset_id(), usd());
- assert_eq!(shortfall.available, money(usd(), 40));
- assert_eq!(shortfall.requested, money(usd(), 100));
- }
- /// A commit in an unregistered asset is refused before anything is written.
- /// Conservation puts every asset a transfer moves value in on its created side,
- /// so that side is the whole set to check.
- #[tokio::test]
- async fn committing_an_unregistered_asset_is_refused() {
- let ledger = setup_ledger().await;
- let unknown = AssetId::new(77);
- let err = ledger
- .commit(
- TransferBuilder::new()
- .deposit(account(1), money(unknown, 100), external())
- .build()
- .unwrap(),
- )
- .await
- .unwrap_err();
- assert!(matches!(err, LedgerError::AssetNotFound(id) if id == unknown));
- // Nothing landed: the account still holds only what it held before.
- assert!(ledger.balance(&account(1), &usd()).await.unwrap().is_zero());
- assert!(ledger.history(&account(1)).await.unwrap().is_empty());
- }
- /// Every way of naming an asset reaches the same read: the shared handle, the
- /// registry row, and the bare id. A spelling the docs show and nothing compiles
- /// is how two defects on this branch hid, so they are pinned here.
- #[tokio::test]
- async fn an_asset_can_be_named_by_handle_row_or_id() {
- let ledger = setup_ledger().await;
- deposit(&ledger, account(1), usd(), 100, external()).await;
- let handle = ledger.asset_by_id(usd()).await.unwrap();
- let row = Asset::clone(&handle);
- let by_handle = ledger.balance(&account(1), &handle).await.unwrap();
- let by_row = ledger.balance(&account(1), &row).await.unwrap();
- let by_id = ledger.balance(&account(1), usd()).await.unwrap();
- let by_id_ref = ledger.balance(&account(1), &usd()).await.unwrap();
- assert_eq!(by_handle.minor_units(), 100);
- assert_eq!(by_handle, by_row);
- assert_eq!(by_handle, by_id);
- assert_eq!(by_handle, by_id_ref);
- // The same on a book policy, which is where the handle used to need `.id`.
- let book = BookBuilder::new("mixed")
- .allow_asset(&handle)
- .allow_asset(row)
- .allow_asset(usd())
- .build();
- assert_eq!(book.policy.allowed_assets, vec![usd(), usd(), usd()]);
- }
- /// Naming an asset by code registers it on first sight and returns the same
- /// handle afterwards, so setup code calls it unconditionally.
- #[tokio::test]
- async fn naming_an_asset_by_code_registers_it_once() {
- let ledger = bare_ledger();
- let first = ledger.asset("EUR", "\u{20ac}", 2).await.unwrap();
- let again = ledger.asset("EUR", "\u{20ac}", 2).await.unwrap();
- assert_eq!(first.id, again.id);
- assert_eq!(ledger.list_assets().await.unwrap().len(), 1);
- // The id is minted, so it is whatever the generator gave, and the handle is
- // the way back to it.
- assert_eq!(ledger.asset_by_id(&first).await.unwrap().code, "EUR");
- assert_eq!(first.amount("1.50").unwrap().to_string(), "1.50 EUR");
- // A second code is a second asset, and amounts of the two do not combine.
- let btc = ledger.asset("BTC", "\u{20bf}", 8).await.unwrap();
- assert_ne!(btc.id, first.id);
- assert!(
- first
- .amount(100)
- .unwrap()
- .checked_add(&btc.amount(100).unwrap())
- .is_err()
- );
- }
- /// A code already registered at another precision is refused. Returning the
- /// stored row would format every later amount at a scale the caller did not ask
- /// for, and the row cannot be rewritten.
- #[tokio::test]
- async fn redefining_an_asset_is_refused() {
- let ledger = bare_ledger();
- ledger.asset("EUR", "\u{20ac}", 2).await.unwrap();
- let err = ledger.asset("EUR", "\u{20ac}", 8).await.unwrap_err();
- assert!(matches!(
- err,
- LedgerError::AssetRedefined {
- registered: 2,
- requested: 8,
- ..
- }
- ));
- assert_eq!(
- ledger.asset("EUR", "\u{20ac}", 2).await.unwrap().decimals,
- 2
- );
- }
- /// A minted asset id fits a signed 4-byte column, which is what the `asset`
- /// columns are. An unmasked fold would store half of them as negative numbers.
- #[tokio::test]
- async fn minted_asset_ids_are_positive() {
- let ledger = bare_ledger();
- for n in 0..256 {
- let asset = ledger.asset(format!("A{n}"), "?", 2).await.unwrap();
- assert!(
- asset.id.0 <= i32::MAX as u32,
- "minted id {} does not fit a signed 4-byte column",
- asset.id.0
- );
- }
- assert_eq!(ledger.list_assets().await.unwrap().len(), 256);
- }
- /// Conservation nets to zero in each asset, read one account at a time.
- ///
- /// Value inside the ledger is mirrored by the offset postings that brought it
- /// in, so the accounts in play net to zero. Summed from per-account reads
- /// because that is the only balance read there is (ADR-0031), which also means
- /// a missing account makes the total non-zero rather than quietly shrinking it.
- #[tokio::test]
- async fn conservation_nets_to_zero_across_the_accounts_in_play() {
- let ledger = setup_ledger().await;
- deposit(&ledger, account(1), usd(), 1000, external()).await;
- deposit(&ledger, account(2), eur(), 500, external()).await;
- pay(&ledger, account(1), account(2), usd(), 250).await;
- pay(&ledger, account(2), account(3), usd(), 50).await;
- let involved = [account(1), account(2), account(3), external()];
- for asset in [usd(), eur()] {
- let mut total = 0i128;
- for id in &involved {
- total += ledger.balance_exact(id, asset).await.unwrap().minor_units();
- }
- assert_eq!(total, 0, "{asset:?} did not net to zero");
- }
- // The external boundary holds the negative side of the USD deposit.
- assert_eq!(
- ledger
- .balance_exact(&external(), usd())
- .await
- .unwrap()
- .minor_units(),
- -1000
- );
- }
- /// What one account holds, across every registered asset, skipping the assets
- /// it has no live posting of.
- #[tokio::test]
- async fn holdings_lists_every_asset_an_account_holds() {
- let ledger = setup_ledger().await;
- deposit(&ledger, account(1), usd(), 1000, external()).await;
- let one = ledger.holdings(&account(1)).await.unwrap();
- assert_eq!(one.len(), 1, "account 1 holds only USD");
- assert_eq!(one[0].asset_id(), usd());
- assert_eq!(one[0].minor_units(), 1000);
- deposit(&ledger, account(1), eur(), 25, external()).await;
- let two = ledger.holdings(&account(1)).await.unwrap();
- assert_eq!(two.len(), 2);
- assert_eq!(
- two.iter().map(|a| a.minor_units()).sum::<i128>(),
- 1025,
- "both holdings are reported"
- );
- assert!(ledger.holdings(&account(3)).await.unwrap().is_empty());
- }
|