| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691 |
- #![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 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());
- }
|