integration.rs 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723
  1. #![allow(missing_docs)]
  2. use std::sync::Arc;
  3. use kuatia::error::LedgerError;
  4. use kuatia::ledger::Ledger;
  5. use kuatia::mem_store::InMemoryStore;
  6. use kuatia::store::TransferQuery;
  7. use kuatia_core::*;
  8. use std::collections::BTreeMap;
  9. /// An amount of `asset` in minor units. An amount compares by asset id, and the
  10. /// tests register these same ids, so building the row here is equivalent to
  11. /// reading it back from the registry.
  12. fn money<V>(asset: AssetId, value: V) -> Amount
  13. where
  14. Amount: From<(V, Arc<Asset>)>,
  15. {
  16. Amount::from((value, Arc::new(Asset::new(asset, "TEST", "$", 2))))
  17. }
  18. fn usd() -> AssetId {
  19. AssetId::new(1)
  20. }
  21. fn eur() -> AssetId {
  22. AssetId::new(2)
  23. }
  24. fn account(id: i64) -> AccountId {
  25. AccountId::new(id)
  26. }
  27. fn external() -> AccountId {
  28. AccountId::new(99)
  29. }
  30. fn make_account(id: i64, flags: AccountFlags) -> Account {
  31. Account {
  32. id: AccountId::new(id),
  33. version: 1,
  34. flags,
  35. book: BookId(0),
  36. metadata: BTreeMap::new(),
  37. }
  38. }
  39. /// A ledger with nothing registered, for the registry's own tests.
  40. fn bare_ledger() -> Arc<Ledger> {
  41. Arc::new(Ledger::new(InMemoryStore::new()))
  42. }
  43. /// Register the assets these tests read. A balance read hydrates its asset from
  44. /// the registry, so an unregistered one has no amount to report.
  45. async fn register_assets(ledger: &Arc<Ledger>) {
  46. for asset in [
  47. Asset::new(usd(), "USD", "$", 2),
  48. Asset::new(eur(), "EUR", "\u{20ac}", 2),
  49. ] {
  50. ledger.create_asset(asset).await.unwrap();
  51. }
  52. }
  53. async fn setup_ledger() -> Arc<Ledger> {
  54. let store = InMemoryStore::new();
  55. let ledger = Arc::new(Ledger::new(store));
  56. ledger
  57. .store()
  58. .create_account(make_account(1, AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT))
  59. .await
  60. .unwrap();
  61. ledger
  62. .store()
  63. .create_account(make_account(2, AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT))
  64. .await
  65. .unwrap();
  66. ledger
  67. .store()
  68. .create_account(make_account(3, AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT))
  69. .await
  70. .unwrap();
  71. ledger
  72. .store()
  73. .create_account(make_account(99, AccountFlags::empty()))
  74. .await
  75. .unwrap();
  76. register_assets(&ledger).await;
  77. ledger
  78. }
  79. /// Helper: deposit via commit()
  80. async fn deposit(
  81. ledger: &Arc<Ledger>,
  82. to: AccountId,
  83. asset: AssetId,
  84. amount: i64,
  85. ext: AccountId,
  86. ) -> Receipt {
  87. let transfer = TransferBuilder::new()
  88. .deposit(to, money(asset, amount), ext)
  89. .build()
  90. .unwrap();
  91. ledger.commit(transfer).await.unwrap()
  92. }
  93. /// Helper: pay via commit()
  94. async fn pay(
  95. ledger: &Arc<Ledger>,
  96. from: AccountId,
  97. to: AccountId,
  98. asset: AssetId,
  99. amount: i64,
  100. ) -> Receipt {
  101. let transfer = TransferBuilder::new()
  102. .pay(from, to, money(asset, amount))
  103. .build()
  104. .unwrap();
  105. ledger.commit(transfer).await.unwrap()
  106. }
  107. /// Helper: withdraw via commit()
  108. async fn withdraw(
  109. ledger: &Arc<Ledger>,
  110. from: AccountId,
  111. asset: AssetId,
  112. amount: i64,
  113. ext: AccountId,
  114. ) -> Receipt {
  115. let transfer = TransferBuilder::new()
  116. .withdraw(from, money(asset, amount), ext)
  117. .build()
  118. .unwrap();
  119. ledger.commit(transfer).await.unwrap()
  120. }
  121. // ---------------------------------------------------------------------------
  122. // §4.1 Deposit
  123. // ---------------------------------------------------------------------------
  124. #[tokio::test]
  125. async fn deposit_creates_balanced_postings() {
  126. let ledger = setup_ledger().await;
  127. deposit(&ledger, account(1), usd(), 100, external()).await;
  128. assert_eq!(
  129. ledger
  130. .balance(&account(1), &usd())
  131. .await
  132. .unwrap()
  133. .minor_units(),
  134. 100
  135. );
  136. assert_eq!(
  137. ledger
  138. .balance(&external(), &usd())
  139. .await
  140. .unwrap()
  141. .minor_units(),
  142. -100
  143. );
  144. }
  145. // ---------------------------------------------------------------------------
  146. // §4.2 Internal transfer with change
  147. // ---------------------------------------------------------------------------
  148. #[tokio::test]
  149. async fn pay_with_change() {
  150. let ledger = setup_ledger().await;
  151. deposit(&ledger, account(1), usd(), 100, external()).await;
  152. pay(&ledger, account(1), account(2), usd(), 50).await;
  153. assert_eq!(
  154. ledger
  155. .balance(&account(1), &usd())
  156. .await
  157. .unwrap()
  158. .minor_units(),
  159. 50
  160. );
  161. assert_eq!(
  162. ledger
  163. .balance(&account(2), &usd())
  164. .await
  165. .unwrap()
  166. .minor_units(),
  167. 50
  168. );
  169. assert_eq!(
  170. ledger
  171. .balance(&external(), &usd())
  172. .await
  173. .unwrap()
  174. .minor_units(),
  175. -100
  176. );
  177. }
  178. // ---------------------------------------------------------------------------
  179. // §4.3 Multi-hop
  180. // ---------------------------------------------------------------------------
  181. #[tokio::test]
  182. async fn multi_hop_transfer() {
  183. let ledger = setup_ledger().await;
  184. deposit(&ledger, account(1), usd(), 100, external()).await;
  185. pay(&ledger, account(1), account(2), usd(), 50).await;
  186. pay(&ledger, account(2), account(3), usd(), 20).await;
  187. assert_eq!(
  188. ledger
  189. .balance(&account(1), &usd())
  190. .await
  191. .unwrap()
  192. .minor_units(),
  193. 50
  194. );
  195. assert_eq!(
  196. ledger
  197. .balance(&account(2), &usd())
  198. .await
  199. .unwrap()
  200. .minor_units(),
  201. 30
  202. );
  203. assert_eq!(
  204. ledger
  205. .balance(&account(3), &usd())
  206. .await
  207. .unwrap()
  208. .minor_units(),
  209. 20
  210. );
  211. assert_eq!(
  212. ledger
  213. .balance(&external(), &usd())
  214. .await
  215. .unwrap()
  216. .minor_units(),
  217. -100
  218. );
  219. }
  220. // ---------------------------------------------------------------------------
  221. // §4.5 Withdrawal
  222. // ---------------------------------------------------------------------------
  223. #[tokio::test]
  224. async fn withdrawal_reduces_external_liability() {
  225. let ledger = setup_ledger().await;
  226. deposit(&ledger, account(1), usd(), 100, external()).await;
  227. withdraw(&ledger, account(1), usd(), 50, external()).await;
  228. assert_eq!(
  229. ledger
  230. .balance(&account(1), &usd())
  231. .await
  232. .unwrap()
  233. .minor_units(),
  234. 50
  235. );
  236. assert_eq!(
  237. ledger
  238. .balance(&external(), &usd())
  239. .await
  240. .unwrap()
  241. .minor_units(),
  242. -50
  243. );
  244. }
  245. // ---------------------------------------------------------------------------
  246. // Full round-trip: deposit -> pay -> withdraw -> verify total = 0
  247. // ---------------------------------------------------------------------------
  248. #[tokio::test]
  249. async fn full_round_trip() {
  250. let ledger = setup_ledger().await;
  251. deposit(&ledger, account(1), usd(), 100, external()).await;
  252. pay(&ledger, account(1), account(2), usd(), 60).await;
  253. withdraw(&ledger, account(2), usd(), 60, external()).await;
  254. withdraw(&ledger, account(1), usd(), 40, external()).await;
  255. assert_eq!(
  256. ledger
  257. .balance(&account(1), &usd())
  258. .await
  259. .unwrap()
  260. .minor_units(),
  261. 0
  262. );
  263. assert_eq!(
  264. ledger
  265. .balance(&account(2), &usd())
  266. .await
  267. .unwrap()
  268. .minor_units(),
  269. 0
  270. );
  271. assert_eq!(
  272. ledger
  273. .balance(&external(), &usd())
  274. .await
  275. .unwrap()
  276. .minor_units(),
  277. 0
  278. );
  279. }
  280. // ---------------------------------------------------------------------------
  281. // Idempotency -- committing same envelope twice returns same receipt
  282. // ---------------------------------------------------------------------------
  283. #[tokio::test]
  284. async fn idempotent_commit() {
  285. let ledger = setup_ledger().await;
  286. let envelope = EnvelopeBuilder::new()
  287. .creates(vec![
  288. NewPosting {
  289. owner: account(1),
  290. amount: money(usd(), 100),
  291. payer: None,
  292. },
  293. NewPosting {
  294. owner: external(),
  295. amount: money(usd(), -100),
  296. payer: None,
  297. },
  298. ])
  299. .build();
  300. let r1 = ledger.commit_envelope(envelope.clone()).await.unwrap();
  301. let r2 = ledger.commit_envelope(envelope).await.unwrap();
  302. assert_eq!(r1.transfer_id, r2.transfer_id);
  303. // Balance should only be 100, not 200 (second commit was a no-op)
  304. assert_eq!(
  305. ledger
  306. .balance(&account(1), &usd())
  307. .await
  308. .unwrap()
  309. .minor_units(),
  310. 100
  311. );
  312. }
  313. /// A deposit consumes nothing, so two of the same amount to the same account
  314. /// are byte-identical and the second is a replay. This is the case a reference
  315. /// exists for, and the case that loses money without one.
  316. #[tokio::test]
  317. async fn identical_deposits_need_a_reference_to_both_land() {
  318. let ledger = setup_ledger().await;
  319. let plain = || {
  320. TransferBuilder::new()
  321. .deposit(account(1), money(usd(), 100), external())
  322. .build()
  323. .unwrap()
  324. };
  325. let first = ledger.commit(plain()).await.unwrap();
  326. let second = ledger.commit(plain()).await.unwrap();
  327. assert_eq!(
  328. first.transfer_id, second.transfer_id,
  329. "identical deposits are one transfer"
  330. );
  331. assert_eq!(
  332. ledger
  333. .balance(&account(1), &usd())
  334. .await
  335. .unwrap()
  336. .minor_units(),
  337. 100,
  338. "the second deposit was a replay, not a second credit"
  339. );
  340. let referenced = |r: &str| {
  341. TransferBuilder::new()
  342. .deposit(account(1), money(usd(), 100), external())
  343. .reference(r)
  344. .build()
  345. .unwrap()
  346. };
  347. let a = ledger.commit(referenced("top-up-1")).await.unwrap();
  348. let b = ledger.commit(referenced("top-up-2")).await.unwrap();
  349. assert_ne!(a.transfer_id, b.transfer_id);
  350. assert_eq!(
  351. ledger
  352. .balance(&account(1), &usd())
  353. .await
  354. .unwrap()
  355. .minor_units(),
  356. 300,
  357. "distinct references make distinct transfers"
  358. );
  359. // Repeating a reference is how a retry stays idempotent.
  360. let replay = ledger.commit(referenced("top-up-2")).await.unwrap();
  361. assert_eq!(replay.transfer_id, b.transfer_id);
  362. assert_eq!(
  363. ledger
  364. .balance(&account(1), &usd())
  365. .await
  366. .unwrap()
  367. .minor_units(),
  368. 300
  369. );
  370. }
  371. /// A payment distinguishes itself: the second consumes the change the first
  372. /// created, so it hashes differently with no reference set.
  373. #[tokio::test]
  374. async fn identical_payments_are_distinct_without_a_reference() {
  375. let ledger = setup_ledger().await;
  376. deposit(&ledger, account(1), usd(), 100, external()).await;
  377. let pay_ten = || {
  378. TransferBuilder::new()
  379. .pay(account(1), account(2), money(usd(), 10))
  380. .build()
  381. .unwrap()
  382. };
  383. let first = ledger.commit(pay_ten()).await.unwrap();
  384. let second = ledger.commit(pay_ten()).await.unwrap();
  385. assert_ne!(first.transfer_id, second.transfer_id);
  386. assert_eq!(
  387. ledger
  388. .balance(&account(2), &usd())
  389. .await
  390. .unwrap()
  391. .minor_units(),
  392. 20
  393. );
  394. }
  395. /// A value date is part of the content address, so two entries that differ only
  396. /// in the day they take effect are two transfers. This is also what lets a
  397. /// backdated deposit repeat without a reference.
  398. #[tokio::test]
  399. async fn value_date_distinguishes_otherwise_identical_transfers() {
  400. let ledger = setup_ledger().await;
  401. let dated = |y, m, d| {
  402. TransferBuilder::new()
  403. .deposit(account(1), money(usd(), 100), external())
  404. .value_date(ValueDate::new(y, m, d).unwrap())
  405. .build()
  406. .unwrap()
  407. };
  408. let first = ledger.commit(dated(2026, 11, 20)).await.unwrap();
  409. let second = ledger.commit(dated(2026, 11, 21)).await.unwrap();
  410. assert_ne!(first.transfer_id, second.transfer_id);
  411. assert_eq!(
  412. ledger
  413. .balance(&account(1), &usd())
  414. .await
  415. .unwrap()
  416. .minor_units(),
  417. 200
  418. );
  419. // The same day twice is still one transfer: the date distinguishes, it does
  420. // not excuse a caller from a reference.
  421. let replay = ledger.commit(dated(2026, 11, 20)).await.unwrap();
  422. assert_eq!(replay.transfer_id, first.transfer_id);
  423. assert_eq!(
  424. ledger
  425. .balance(&account(1), &usd())
  426. .await
  427. .unwrap()
  428. .minor_units(),
  429. 200
  430. );
  431. }
  432. /// Transfers are queryable by the day they take effect, independently of the
  433. /// instant they were committed. Everything here commits now, so a window on the
  434. /// commit clock cannot tell these apart.
  435. #[tokio::test]
  436. async fn transfers_filter_by_value_date_not_commit_time() {
  437. let ledger = setup_ledger().await;
  438. for (day, amount) in [(18, 10), (20, 20), (22, 30)] {
  439. ledger
  440. .commit(
  441. TransferBuilder::new()
  442. .deposit(account(1), money(usd(), amount), external())
  443. .value_date(ValueDate::new(2026, 11, day).unwrap())
  444. .build()
  445. .unwrap(),
  446. )
  447. .await
  448. .unwrap();
  449. }
  450. let window = TransferQuery {
  451. account: Some(1),
  452. from_value_date: Some(ValueDate::new(2026, 11, 19).unwrap()),
  453. to_value_date: Some(ValueDate::new(2026, 11, 22).unwrap()),
  454. ..Default::default()
  455. };
  456. let page = ledger.query_transfers(&window).await.unwrap();
  457. assert_eq!(page.total, 1, "only the entry valued on the 20th");
  458. // An entry with no value date is valued when it was booked, so it sits
  459. // outside an explicit window rather than inside every one.
  460. deposit(&ledger, account(1), usd(), 40, external()).await;
  461. let page = ledger.query_transfers(&window).await.unwrap();
  462. assert_eq!(page.total, 1);
  463. }
  464. /// A reversal carries the original's value date, so the period the entry landed
  465. /// in is the period it is undone in.
  466. #[tokio::test]
  467. async fn reversal_keeps_the_original_value_date() {
  468. let ledger = setup_ledger().await;
  469. let valued = ValueDate::new(2026, 11, 20).unwrap();
  470. let receipt = ledger
  471. .commit(
  472. TransferBuilder::new()
  473. .deposit(account(1), money(usd(), 100), external())
  474. .value_date(valued)
  475. .build()
  476. .unwrap(),
  477. )
  478. .await
  479. .unwrap();
  480. ledger.reverse(&receipt.transfer_id).await.unwrap();
  481. let window = TransferQuery {
  482. account: Some(1),
  483. from_value_date: Some(valued),
  484. to_value_date: Some(ValueDate::new(2026, 11, 21).unwrap()),
  485. ..Default::default()
  486. };
  487. assert_eq!(
  488. ledger.query_transfers(&window).await.unwrap().total,
  489. 2,
  490. "the entry and its reversal both fall in the period"
  491. );
  492. assert_eq!(
  493. ledger
  494. .balance(&account(1), &usd())
  495. .await
  496. .unwrap()
  497. .minor_units(),
  498. 0
  499. );
  500. }
  501. // ---------------------------------------------------------------------------
  502. // Overdraft prevention
  503. // ---------------------------------------------------------------------------
  504. #[tokio::test]
  505. async fn overdraft_rejected() {
  506. let ledger = setup_ledger().await;
  507. deposit(&ledger, account(1), usd(), 50, external()).await;
  508. let transfer = TransferBuilder::new()
  509. .pay(account(1), account(2), money(usd(), 100))
  510. .build()
  511. .unwrap();
  512. let result = ledger.commit(transfer).await;
  513. assert!(result.is_err());
  514. // Balance unchanged
  515. assert_eq!(
  516. ledger
  517. .balance(&account(1), &usd())
  518. .await
  519. .unwrap()
  520. .minor_units(),
  521. 50
  522. );
  523. }
  524. // ---------------------------------------------------------------------------
  525. // Reverse: forward compensating transfer
  526. // ---------------------------------------------------------------------------
  527. #[tokio::test]
  528. async fn reverse_restores_balances() {
  529. let ledger = setup_ledger().await;
  530. deposit(&ledger, account(1), usd(), 100, external()).await;
  531. let pay_receipt = pay(&ledger, account(1), account(2), usd(), 60).await;
  532. assert_eq!(
  533. ledger
  534. .balance(&account(1), &usd())
  535. .await
  536. .unwrap()
  537. .minor_units(),
  538. 40
  539. );
  540. assert_eq!(
  541. ledger
  542. .balance(&account(2), &usd())
  543. .await
  544. .unwrap()
  545. .minor_units(),
  546. 60
  547. );
  548. // Reverse the payment
  549. ledger.reverse(&pay_receipt.transfer_id).await.unwrap();
  550. assert_eq!(
  551. ledger
  552. .balance(&account(1), &usd())
  553. .await
  554. .unwrap()
  555. .minor_units(),
  556. 100
  557. );
  558. assert_eq!(
  559. ledger
  560. .balance(&account(2), &usd())
  561. .await
  562. .unwrap()
  563. .minor_units(),
  564. 0
  565. );
  566. }
  567. // ---------------------------------------------------------------------------
  568. // Frozen account blocks transfers
  569. // ---------------------------------------------------------------------------
  570. #[tokio::test]
  571. async fn frozen_account_rejected() {
  572. let store = InMemoryStore::new();
  573. let ledger = Arc::new(Ledger::new(store));
  574. register_assets(&ledger).await;
  575. let mut frozen = make_account(1, AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT);
  576. frozen.flags = AccountFlags::FROZEN;
  577. ledger.store().create_account(frozen).await.unwrap();
  578. ledger
  579. .store()
  580. .create_account(make_account(99, AccountFlags::empty()))
  581. .await
  582. .unwrap();
  583. let transfer = TransferBuilder::new()
  584. .deposit(account(1), money(usd(), 100), external())
  585. .build()
  586. .unwrap();
  587. let result = ledger.commit(transfer).await;
  588. assert!(result.is_err());
  589. }
  590. // ---------------------------------------------------------------------------
  591. // Multi-asset: each asset conserves independently
  592. // ---------------------------------------------------------------------------
  593. #[tokio::test]
  594. async fn multi_asset_independent_balances() {
  595. let ledger = setup_ledger().await;
  596. deposit(&ledger, account(1), usd(), 100, external()).await;
  597. deposit(&ledger, account(1), eur(), 200, external()).await;
  598. assert_eq!(
  599. ledger
  600. .balance(&account(1), &usd())
  601. .await
  602. .unwrap()
  603. .minor_units(),
  604. 100
  605. );
  606. assert_eq!(
  607. ledger
  608. .balance(&account(1), &eur())
  609. .await
  610. .unwrap()
  611. .minor_units(),
  612. 200
  613. );
  614. pay(&ledger, account(1), account(2), usd(), 30).await;
  615. assert_eq!(
  616. ledger
  617. .balance(&account(1), &usd())
  618. .await
  619. .unwrap()
  620. .minor_units(),
  621. 70
  622. );
  623. assert_eq!(
  624. ledger
  625. .balance(&account(1), &eur())
  626. .await
  627. .unwrap()
  628. .minor_units(),
  629. 200
  630. );
  631. assert_eq!(
  632. ledger
  633. .balance(&account(2), &usd())
  634. .await
  635. .unwrap()
  636. .minor_units(),
  637. 30
  638. );
  639. }
  640. // ---------------------------------------------------------------------------
  641. // §4.4 FX trade via market account
  642. // ---------------------------------------------------------------------------
  643. #[tokio::test]
  644. async fn fx_trade_via_market_account() {
  645. let store = InMemoryStore::new();
  646. let ledger = Arc::new(Ledger::new(store));
  647. register_assets(&ledger).await;
  648. // Setup accounts
  649. for (id, policy) in [
  650. (1, AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT),
  651. (50, AccountFlags::empty()), // FX market account
  652. (99, AccountFlags::empty()),
  653. ] {
  654. ledger
  655. .store()
  656. .create_account(make_account(id, policy))
  657. .await
  658. .unwrap();
  659. }
  660. // Seed: account1 has 100 USD, fx has 92 EUR
  661. deposit(&ledger, account(1), usd(), 100, external()).await;
  662. deposit(&ledger, account(50), eur(), 92, external()).await;
  663. // FX trade: account1 sells 100 USD, buys 92 EUR
  664. // Build the atomic envelope manually since it spans two assets
  665. let a1_usd_postings = ledger
  666. .store()
  667. .get_postings_by_account(1, None, Some(&usd()), PostingFilter::Live)
  668. .await
  669. .unwrap();
  670. let fx_eur_postings = ledger
  671. .store()
  672. .get_postings_by_account(50, None, Some(&eur()), PostingFilter::Live)
  673. .await
  674. .unwrap();
  675. let envelope = EnvelopeBuilder::new()
  676. .consumes(vec![a1_usd_postings[0].id, fx_eur_postings[0].id])
  677. .creates(vec![
  678. NewPosting {
  679. owner: account(50),
  680. amount: money(usd(), 100),
  681. payer: Some(account(1)),
  682. },
  683. NewPosting {
  684. owner: account(1),
  685. amount: money(eur(), 92),
  686. payer: Some(account(50)),
  687. },
  688. ])
  689. .build();
  690. ledger.commit_envelope(envelope).await.unwrap();
  691. // Verify
  692. assert_eq!(
  693. ledger
  694. .balance(&account(1), &usd())
  695. .await
  696. .unwrap()
  697. .minor_units(),
  698. 0
  699. );
  700. assert_eq!(
  701. ledger
  702. .balance(&account(1), &eur())
  703. .await
  704. .unwrap()
  705. .minor_units(),
  706. 92
  707. );
  708. assert_eq!(
  709. ledger
  710. .balance(&account(50), &usd())
  711. .await
  712. .unwrap()
  713. .minor_units(),
  714. 100
  715. );
  716. assert_eq!(
  717. ledger
  718. .balance(&account(50), &eur())
  719. .await
  720. .unwrap()
  721. .minor_units(),
  722. 0
  723. );
  724. }
  725. // ---------------------------------------------------------------------------
  726. // Account lifecycle: freeze / unfreeze / close
  727. // ---------------------------------------------------------------------------
  728. #[tokio::test]
  729. async fn freeze_blocks_transfers() {
  730. let ledger = setup_ledger().await;
  731. deposit(&ledger, account(1), usd(), 100, external()).await;
  732. ledger.freeze(&account(1)).await.unwrap();
  733. // Paying from a frozen account should fail
  734. let transfer = TransferBuilder::new()
  735. .pay(account(1), account(2), money(usd(), 50))
  736. .build()
  737. .unwrap();
  738. let result = ledger.commit(transfer).await;
  739. assert!(result.is_err());
  740. // Balance unchanged
  741. assert_eq!(
  742. ledger
  743. .balance(&account(1), &usd())
  744. .await
  745. .unwrap()
  746. .minor_units(),
  747. 100
  748. );
  749. }
  750. #[tokio::test]
  751. async fn unfreeze_re_enables_transfers() {
  752. let ledger = setup_ledger().await;
  753. deposit(&ledger, account(1), usd(), 100, external()).await;
  754. ledger.freeze(&account(1)).await.unwrap();
  755. ledger.unfreeze(&account(1)).await.unwrap();
  756. // Should work again
  757. pay(&ledger, account(1), account(2), usd(), 50).await;
  758. assert_eq!(
  759. ledger
  760. .balance(&account(1), &usd())
  761. .await
  762. .unwrap()
  763. .minor_units(),
  764. 50
  765. );
  766. }
  767. #[tokio::test]
  768. async fn close_account_with_zero_balance() {
  769. let ledger = setup_ledger().await;
  770. // Account 3 has never transacted -- zero balance, no postings
  771. ledger.close(&account(3)).await.unwrap();
  772. // Closed account rejects deposits
  773. let transfer = TransferBuilder::new()
  774. .deposit(account(3), money(usd(), 100), external())
  775. .build()
  776. .unwrap();
  777. let result = ledger.commit(transfer).await;
  778. assert!(result.is_err());
  779. }
  780. #[tokio::test]
  781. async fn close_account_with_balance_rejected() {
  782. let ledger = setup_ledger().await;
  783. deposit(&ledger, account(1), usd(), 100, external()).await;
  784. // Should fail -- account still has active postings
  785. let result = ledger.close(&account(1)).await;
  786. assert!(result.is_err());
  787. // Balance unchanged
  788. assert_eq!(
  789. ledger
  790. .balance(&account(1), &usd())
  791. .await
  792. .unwrap()
  793. .minor_units(),
  794. 100
  795. );
  796. }
  797. /// Paying the whole balance leaves no change posting, so the account holds
  798. /// nothing live and closing it is allowed: spent postings do not block close.
  799. #[tokio::test]
  800. async fn close_succeeds_once_postings_are_spent() {
  801. let ledger = setup_ledger().await;
  802. deposit(&ledger, account(1), usd(), 100, external()).await;
  803. let transfer = TransferBuilder::new()
  804. .pay(account(1), account(2), money(usd(), 100))
  805. .build()
  806. .unwrap();
  807. ledger.commit(transfer).await.unwrap();
  808. ledger.close(&account(1)).await.unwrap();
  809. assert!(ledger.get_account(&account(1)).await.unwrap().is_closed());
  810. }
  811. #[tokio::test]
  812. async fn freeze_closed_account_rejected() {
  813. let ledger = setup_ledger().await;
  814. ledger.close(&account(3)).await.unwrap();
  815. let result = ledger.freeze(&account(3)).await;
  816. assert!(result.is_err());
  817. }
  818. // ---------------------------------------------------------------------------
  819. // Query layer: history, postings, list_accounts, get_account
  820. // ---------------------------------------------------------------------------
  821. #[tokio::test]
  822. async fn history_returns_transfers_for_account() {
  823. let ledger = setup_ledger().await;
  824. deposit(&ledger, account(1), usd(), 100, external()).await;
  825. pay(&ledger, account(1), account(2), usd(), 40).await;
  826. deposit(&ledger, account(2), usd(), 50, external()).await;
  827. let h1 = ledger.history(&account(1)).await.unwrap();
  828. // account(1) was in the deposit and the pay
  829. assert_eq!(h1.len(), 2);
  830. let h2 = ledger.history(&account(2)).await.unwrap();
  831. // account(2) was in the pay and a second deposit
  832. assert_eq!(h2.len(), 2);
  833. }
  834. #[tokio::test]
  835. async fn postings_returns_all_postings() {
  836. let ledger = setup_ledger().await;
  837. deposit(&ledger, account(1), usd(), 100, external()).await;
  838. pay(&ledger, account(1), account(2), usd(), 60).await;
  839. let posts = ledger.postings(&account(1)).await.unwrap();
  840. // Original 100 posting (now consumed) + 40 change posting (active)
  841. assert_eq!(posts.len(), 2);
  842. let with_state = ledger.postings_with_state(&account(1)).await.unwrap();
  843. let active: Vec<_> = with_state
  844. .iter()
  845. .filter(|(_, s)| *s == PostingState::Live)
  846. .collect();
  847. assert_eq!(active.len(), 1);
  848. assert_eq!(active[0].0.amount.minor_units(), 40);
  849. }
  850. #[tokio::test]
  851. async fn get_postings_resolves_a_consumed_posting() {
  852. let ledger = setup_ledger().await;
  853. deposit(&ledger, account(1), usd(), 100, external()).await;
  854. pay(&ledger, account(1), account(2), usd(), 60).await;
  855. let with_state = ledger.postings_with_state(&account(1)).await.unwrap();
  856. let spent: Vec<PostingId> = with_state
  857. .iter()
  858. .filter(|(_, s)| *s == PostingState::Spent)
  859. .map(|(p, _)| p.id)
  860. .collect();
  861. assert_eq!(spent.len(), 1);
  862. let found = ledger.get_postings(&spent).await.unwrap();
  863. assert_eq!(found.len(), 1);
  864. assert_eq!(found[0].owner, account(1));
  865. assert_eq!(found[0].amount.minor_units(), 100);
  866. }
  867. #[tokio::test]
  868. async fn get_postings_unknown_id_is_an_error() {
  869. let ledger = setup_ledger().await;
  870. let unknown = PostingId {
  871. transfer: TransferId([7u8; 32]),
  872. index: 0,
  873. };
  874. assert!(ledger.get_postings(&[unknown]).await.is_err());
  875. }
  876. #[tokio::test]
  877. async fn list_accounts_returns_all() {
  878. let ledger = setup_ledger().await;
  879. let accounts = ledger.list_accounts().await.unwrap();
  880. // setup_ledger creates accounts 1, 2, 3, 99
  881. assert_eq!(accounts.len(), 4);
  882. }
  883. #[tokio::test]
  884. async fn get_account_by_id() {
  885. let ledger = setup_ledger().await;
  886. let acc = ledger.get_account(&account(1)).await.unwrap();
  887. assert_eq!(acc.id, account(1));
  888. assert!(acc.forbids_overdraft());
  889. }
  890. #[tokio::test]
  891. async fn get_account_not_found() {
  892. let ledger = setup_ledger().await;
  893. let result = ledger.get_account(&account(999)).await;
  894. assert!(result.is_err());
  895. }
  896. // ---------------------------------------------------------------------------
  897. // Append-only accounts: version history, version conflict, account_versions
  898. // ---------------------------------------------------------------------------
  899. #[tokio::test]
  900. async fn account_history_tracks_versions() {
  901. let ledger = setup_ledger().await;
  902. // Version 1: created
  903. let history = ledger.account_history(&account(1)).await.unwrap();
  904. assert_eq!(history.len(), 1);
  905. assert_eq!(history[0].version, 1);
  906. // Version 2: frozen
  907. ledger.freeze(&account(1)).await.unwrap();
  908. let history = ledger.account_history(&account(1)).await.unwrap();
  909. assert_eq!(history.len(), 2);
  910. assert_eq!(history[1].version, 2);
  911. assert!(history[1].is_frozen());
  912. // Version 3: unfrozen
  913. ledger.unfreeze(&account(1)).await.unwrap();
  914. let history = ledger.account_history(&account(1)).await.unwrap();
  915. assert_eq!(history.len(), 3);
  916. assert_eq!(history[2].version, 3);
  917. assert!(!history[2].is_frozen());
  918. }
  919. #[tokio::test]
  920. async fn store_never_compacts() {
  921. let ledger = setup_ledger().await;
  922. // Freeze and unfreeze multiple times
  923. for _ in 0..5 {
  924. ledger.freeze(&account(1)).await.unwrap();
  925. ledger.unfreeze(&account(1)).await.unwrap();
  926. }
  927. // All 11 versions preserved (1 creation + 10 mutations)
  928. let history = ledger.account_history(&account(1)).await.unwrap();
  929. assert_eq!(history.len(), 11);
  930. // Versions are monotonically increasing
  931. for (i, acc) in history.iter().enumerate() {
  932. assert_eq!(acc.version, (i + 1) as u64);
  933. }
  934. }
  935. #[tokio::test]
  936. async fn transfer_records_account_snapshots() {
  937. let ledger = setup_ledger().await;
  938. deposit(&ledger, account(1), usd(), 100, external()).await;
  939. // The envelope should have account_snapshots populated by the resolve step
  940. let transfers = ledger.history(&account(1)).await.unwrap();
  941. assert_eq!(transfers.len(), 1);
  942. assert!(!transfers[0].envelope.account_snapshots().is_empty());
  943. }
  944. #[tokio::test]
  945. async fn stale_snapshot_rejected() {
  946. let ledger = setup_ledger().await;
  947. // Get current snapshot for account(1)
  948. let acc1 = ledger.get_account(&account(1)).await.unwrap();
  949. let stale_snapshot = kuatia_core::account_snapshot_id(&acc1);
  950. // Freeze account(1) -- changes its snapshot hash
  951. ledger.freeze(&account(1)).await.unwrap();
  952. // Build an envelope with the stale snapshot
  953. let envelope = EnvelopeBuilder::new()
  954. .creates(vec![
  955. NewPosting {
  956. owner: account(1),
  957. amount: money(usd(), 100),
  958. payer: None,
  959. },
  960. NewPosting {
  961. owner: external(),
  962. amount: money(usd(), -100),
  963. payer: None,
  964. },
  965. ])
  966. .account_snapshots(vec![stale_snapshot])
  967. .build();
  968. let result = ledger.commit_envelope(envelope).await;
  969. assert!(result.is_err());
  970. }
  971. #[tokio::test]
  972. async fn account_hash_deterministic() {
  973. let acc = make_account(42, AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT);
  974. let h1 = kuatia_core::account_hash(&acc);
  975. let h2 = kuatia_core::account_hash(&acc);
  976. assert_eq!(h1, h2);
  977. }
  978. #[tokio::test]
  979. async fn account_hash_changes_with_version() {
  980. let mut acc = make_account(42, AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT);
  981. let h1 = kuatia_core::account_hash(&acc);
  982. acc.version = 2;
  983. acc.flags |= AccountFlags::FROZEN;
  984. let h2 = kuatia_core::account_hash(&acc);
  985. assert_ne!(h1, h2);
  986. }
  987. // ---------------------------------------------------------------------------
  988. // Overdraft via negative postings
  989. // ---------------------------------------------------------------------------
  990. #[tokio::test]
  991. async fn overdraft_creates_negative_posting() {
  992. let store = InMemoryStore::new();
  993. let ledger = Arc::new(Ledger::new(store));
  994. register_assets(&ledger).await;
  995. for (id, flags) in [
  996. (10, AccountFlags::empty()),
  997. (2, AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT),
  998. (99, AccountFlags::empty()),
  999. ] {
  1000. ledger
  1001. .store()
  1002. .create_account(make_account(id, flags))
  1003. .await
  1004. .unwrap();
  1005. }
  1006. // Fund account 10 with 50, then pay 100 — overdraft covers the 50 shortfall.
  1007. deposit(&ledger, account(10), usd(), 50, external()).await;
  1008. pay(&ledger, account(10), account(2), usd(), 100).await;
  1009. assert_eq!(
  1010. ledger
  1011. .balance(&account(10), &usd())
  1012. .await
  1013. .unwrap()
  1014. .minor_units(),
  1015. -50
  1016. );
  1017. assert_eq!(
  1018. ledger
  1019. .balance(&account(2), &usd())
  1020. .await
  1021. .unwrap()
  1022. .minor_units(),
  1023. 100
  1024. );
  1025. // A negative posting now backs the overdraft.
  1026. let postings = ledger
  1027. .store()
  1028. .get_postings_by_account(10, None, Some(&usd()), PostingFilter::Live)
  1029. .await
  1030. .unwrap();
  1031. assert!(postings.iter().any(|p| p.amount.minor_units() == -50));
  1032. }
  1033. #[tokio::test]
  1034. async fn debit_must_not_exceed_credit_rejects_overspend() {
  1035. let store = InMemoryStore::new();
  1036. let ledger = Arc::new(Ledger::new(store));
  1037. register_assets(&ledger).await;
  1038. for (id, flags) in [
  1039. (10, AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT),
  1040. (2, AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT),
  1041. (99, AccountFlags::empty()),
  1042. ] {
  1043. ledger
  1044. .store()
  1045. .create_account(make_account(id, flags))
  1046. .await
  1047. .unwrap();
  1048. }
  1049. // Account 10 forbids overdraft, so paying 100 from an empty balance fails.
  1050. let transfer = TransferBuilder::new()
  1051. .pay(account(10), account(2), money(usd(), 100))
  1052. .build()
  1053. .unwrap();
  1054. assert!(ledger.commit(transfer).await.is_err());
  1055. assert_eq!(
  1056. ledger
  1057. .balance(&account(10), &usd())
  1058. .await
  1059. .unwrap()
  1060. .minor_units(),
  1061. 0
  1062. );
  1063. }
  1064. #[tokio::test]
  1065. async fn overdraft_allows_arbitrary_negative() {
  1066. let store = InMemoryStore::new();
  1067. let ledger = Arc::new(Ledger::new(store));
  1068. register_assets(&ledger).await;
  1069. for (id, flags) in [
  1070. (10, AccountFlags::empty()),
  1071. (2, AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT),
  1072. (99, AccountFlags::empty()),
  1073. ] {
  1074. ledger
  1075. .store()
  1076. .create_account(make_account(id, flags))
  1077. .await
  1078. .unwrap();
  1079. }
  1080. pay(&ledger, account(10), account(2), usd(), 1_000_000).await;
  1081. assert_eq!(
  1082. ledger
  1083. .balance(&account(10), &usd())
  1084. .await
  1085. .unwrap()
  1086. .minor_units(),
  1087. -1_000_000
  1088. );
  1089. }
  1090. // ---------------------------------------------------------------------------
  1091. // Book policy enforcement
  1092. // ---------------------------------------------------------------------------
  1093. #[tokio::test]
  1094. async fn book_policy_rejects_disallowed_asset() {
  1095. let ledger = setup_ledger().await;
  1096. // Book 5 permits only EUR.
  1097. let book = BookBuilder::new("eur-only")
  1098. .id(BookId::new(5))
  1099. .allow_asset(eur())
  1100. .build();
  1101. ledger.store().create_book(book).await.unwrap();
  1102. deposit(&ledger, account(1), usd(), 100, external()).await;
  1103. // Paying USD under a EUR-only book is rejected, balance unchanged.
  1104. let transfer = TransferBuilder::new()
  1105. .book(BookId::new(5))
  1106. .pay(account(1), account(2), money(usd(), 50))
  1107. .build()
  1108. .unwrap();
  1109. assert!(ledger.commit(transfer).await.is_err());
  1110. assert_eq!(
  1111. ledger
  1112. .balance(&account(1), &usd())
  1113. .await
  1114. .unwrap()
  1115. .minor_units(),
  1116. 100
  1117. );
  1118. }
  1119. #[tokio::test]
  1120. async fn transfer_in_missing_named_book_is_rejected() {
  1121. let ledger = setup_ledger().await;
  1122. deposit(&ledger, account(1), usd(), 100, external()).await;
  1123. let transfer = TransferBuilder::new()
  1124. .book(BookId::new(404))
  1125. .pay(account(1), account(2), money(usd(), 50))
  1126. .build()
  1127. .unwrap();
  1128. assert!(ledger.commit(transfer).await.is_err());
  1129. assert_eq!(
  1130. ledger
  1131. .balance(&account(1), &usd())
  1132. .await
  1133. .unwrap()
  1134. .minor_units(),
  1135. 100
  1136. );
  1137. }
  1138. // ---------------------------------------------------------------------------
  1139. // Content-addressed determinism
  1140. // ---------------------------------------------------------------------------
  1141. #[tokio::test]
  1142. async fn identical_transfers_share_transfer_id() {
  1143. // Two independently-built default-book transfers must hash identically.
  1144. let a = TransferBuilder::new()
  1145. .pay(account(1), account(2), money(usd(), 10))
  1146. .build()
  1147. .unwrap();
  1148. let b = TransferBuilder::new()
  1149. .pay(account(1), account(2), money(usd(), 10))
  1150. .build()
  1151. .unwrap();
  1152. assert_eq!(a.book, b.book, "default book must be deterministic");
  1153. assert_eq!(a.book, DEFAULT_BOOK);
  1154. }
  1155. // ---------------------------------------------------------------------------
  1156. // Subaccounts (ADR-0012)
  1157. // ---------------------------------------------------------------------------
  1158. #[tokio::test]
  1159. async fn subaccount_balances_are_segregated() {
  1160. let ledger = setup_ledger().await;
  1161. let sub = AccountId::with_sub(1, 7);
  1162. // A subaccount is a full account record with its own policy.
  1163. ledger
  1164. .store()
  1165. .create_account(Account::debit_must_not_exceed_credit(sub))
  1166. .await
  1167. .unwrap();
  1168. // Fund the main account (1, 0) and the subaccount (1, 7) independently.
  1169. deposit(&ledger, account(1), usd(), 100, external()).await;
  1170. deposit(&ledger, sub, usd(), 40, external()).await;
  1171. // balance() reads exactly one subaccount and never rolls up the other.
  1172. assert_eq!(
  1173. ledger
  1174. .balance(&account(1), &usd())
  1175. .await
  1176. .unwrap()
  1177. .minor_units(),
  1178. 100
  1179. );
  1180. assert_eq!(
  1181. ledger.balance(&sub, &usd()).await.unwrap().minor_units(),
  1182. 40
  1183. );
  1184. // list_subaccounts spans the base id's subaccounts, sorted.
  1185. let subs = ledger.list_subaccounts(&account(1)).await.unwrap();
  1186. assert_eq!(subs, vec![account(1), sub]);
  1187. // balances() reports one entry per subaccount, never summed.
  1188. let all = ledger.balances(&account(1), &usd(), None).await.unwrap();
  1189. assert_eq!(all.len(), 2);
  1190. assert_eq!(
  1191. all.iter()
  1192. .find(|b| b.account == account(1))
  1193. .unwrap()
  1194. .amount
  1195. .minor_units(),
  1196. 100
  1197. );
  1198. assert_eq!(
  1199. all.iter()
  1200. .find(|b| b.account == sub)
  1201. .unwrap()
  1202. .amount
  1203. .minor_units(),
  1204. 40
  1205. );
  1206. // A subaccount filter restricts to that one.
  1207. let just_sub = ledger.balances(&account(1), &usd(), Some(7)).await.unwrap();
  1208. assert_eq!(just_sub.len(), 1);
  1209. assert_eq!(just_sub[0].account, sub);
  1210. assert_eq!(just_sub[0].amount.minor_units(), 40);
  1211. }
  1212. #[tokio::test]
  1213. async fn pay_moves_value_between_subaccounts() {
  1214. let ledger = setup_ledger().await;
  1215. let sub = AccountId::with_sub(1, 7);
  1216. ledger
  1217. .store()
  1218. .create_account(Account::debit_must_not_exceed_credit(sub))
  1219. .await
  1220. .unwrap();
  1221. deposit(&ledger, sub, usd(), 40, external()).await;
  1222. // Move 30 from subaccount (1, 7) to the main account (1, 0).
  1223. pay(&ledger, sub, account(1), usd(), 30).await;
  1224. assert_eq!(
  1225. ledger.balance(&sub, &usd()).await.unwrap().minor_units(),
  1226. 10
  1227. );
  1228. assert_eq!(
  1229. ledger
  1230. .balance(&account(1), &usd())
  1231. .await
  1232. .unwrap()
  1233. .minor_units(),
  1234. 30
  1235. );
  1236. }
  1237. #[tokio::test]
  1238. async fn closed_subaccounts_drop_out_of_aggregate_reads() {
  1239. let ledger = setup_ledger().await;
  1240. let sub = AccountId::with_sub(1, 7);
  1241. ledger
  1242. .store()
  1243. .create_account(Account::debit_must_not_exceed_credit(sub))
  1244. .await
  1245. .unwrap();
  1246. // The subaccount is created then closed while empty.
  1247. ledger.close(&sub).await.unwrap();
  1248. // list_subaccounts and balances exclude the closed subaccount.
  1249. let subs = ledger.list_subaccounts(&account(1)).await.unwrap();
  1250. assert_eq!(subs, vec![account(1)]);
  1251. let all = ledger.balances(&account(1), &usd(), None).await.unwrap();
  1252. assert!(all.iter().all(|b| b.account != sub));
  1253. }
  1254. #[tokio::test]
  1255. async fn registering_an_asset_makes_it_readable() {
  1256. let ledger = bare_ledger();
  1257. let usd = Asset::new(usd(), "USD", "$", 2);
  1258. ledger.create_asset(usd.clone()).await.unwrap();
  1259. let got = ledger.asset_by_id(&usd).await.unwrap();
  1260. assert_eq!(*got, usd);
  1261. // Built from the row the registry handed back, so the code and the scale in
  1262. // the rendering are the registered ones.
  1263. assert_eq!(Amount::from((65_000, got)).to_string(), "650.00 USD");
  1264. assert_eq!(ledger.list_assets().await.unwrap(), vec![usd]);
  1265. }
  1266. #[tokio::test]
  1267. async fn an_unregistered_asset_is_not_found() {
  1268. let ledger = bare_ledger();
  1269. let err = ledger.asset_by_id(&usd()).await.unwrap_err();
  1270. assert!(matches!(err, LedgerError::AssetNotFound(id) if id == usd()));
  1271. }
  1272. /// A second registration is refused rather than merged, because a row is
  1273. /// immutable: changing the precision would reinterpret every amount already
  1274. /// recorded against the asset.
  1275. #[tokio::test]
  1276. async fn registering_a_known_asset_is_refused() {
  1277. let ledger = bare_ledger();
  1278. ledger
  1279. .create_asset(Asset::new(usd(), "USD", "$", 2))
  1280. .await
  1281. .unwrap();
  1282. let err = ledger
  1283. .create_asset(Asset::new(usd(), "NOT-USD", "!", 8))
  1284. .await
  1285. .unwrap_err();
  1286. assert!(matches!(err, LedgerError::AssetAlreadyExists(id) if id == usd()));
  1287. assert_eq!(ledger.asset_by_id(&usd()).await.unwrap().decimals, 2);
  1288. }
  1289. /// A miss is not cached, so an asset registered after a failed lookup is found.
  1290. #[tokio::test]
  1291. async fn a_missed_lookup_does_not_poison_the_cache() {
  1292. let ledger = bare_ledger();
  1293. assert!(ledger.asset_by_id(&eur()).await.is_err());
  1294. ledger
  1295. .create_asset(Asset::new(eur(), "EUR", "\u{20ac}", 2))
  1296. .await
  1297. .unwrap();
  1298. assert_eq!(ledger.asset_by_id(&eur()).await.unwrap().code, "EUR");
  1299. }
  1300. /// A balance comes back denominated, so what a caller holds is a quantity of a
  1301. /// named asset rather than a bare number.
  1302. #[tokio::test]
  1303. async fn a_balance_carries_the_asset_it_was_read_for() {
  1304. let ledger = setup_ledger().await;
  1305. deposit(&ledger, account(1), usd(), 100, external()).await;
  1306. let bal = ledger.balance(&account(1), &usd()).await.unwrap();
  1307. assert_eq!(bal.asset_id(), usd());
  1308. assert_eq!(bal.minor_units(), 100);
  1309. assert_eq!(bal.to_string(), "1.00 USD");
  1310. assert_eq!(
  1311. ledger
  1312. .balance_exact(&account(1), &usd())
  1313. .await
  1314. .unwrap()
  1315. .asset_id(),
  1316. usd()
  1317. );
  1318. }
  1319. /// The bug the type exists to stop: two balances from one ledger, in different
  1320. /// assets, refusing to be added instead of producing a number denominated in
  1321. /// nothing.
  1322. #[tokio::test]
  1323. async fn two_assets_from_one_ledger_do_not_add() {
  1324. let ledger = setup_ledger().await;
  1325. deposit(&ledger, account(1), usd(), 100, external()).await;
  1326. deposit(&ledger, account(1), eur(), 50, external()).await;
  1327. let dollars = ledger.balance(&account(1), &usd()).await.unwrap();
  1328. let euros = ledger.balance(&account(1), &eur()).await.unwrap();
  1329. assert_eq!(
  1330. dollars.checked_add(&euros),
  1331. Err(AmountError::AssetMismatch {
  1332. left: usd(),
  1333. right: eur(),
  1334. })
  1335. );
  1336. assert_eq!(dollars.checked_add(&dollars).unwrap().minor_units(), 200);
  1337. }
  1338. /// A shortfall names the asset that fell short, so a caller reporting it does
  1339. /// not have to guess which one the two values are in.
  1340. #[tokio::test]
  1341. async fn insufficient_funds_names_the_asset() {
  1342. let ledger = setup_ledger().await;
  1343. deposit(&ledger, account(1), usd(), 40, external()).await;
  1344. let err = ledger
  1345. .commit(
  1346. TransferBuilder::new()
  1347. .pay(account(1), account(2), money(usd(), 100))
  1348. .build()
  1349. .unwrap(),
  1350. )
  1351. .await
  1352. .unwrap_err();
  1353. let LedgerError::Selection(shortfall) = err else {
  1354. panic!("expected a selection failure, got {err:?}");
  1355. };
  1356. assert_eq!(shortfall.available.asset_id(), usd());
  1357. assert_eq!(shortfall.available, money(usd(), 40));
  1358. assert_eq!(shortfall.requested, money(usd(), 100));
  1359. }
  1360. /// A commit in an unregistered asset is refused before anything is written.
  1361. /// Conservation puts every asset a transfer moves value in on its created side,
  1362. /// so that side is the whole set to check.
  1363. #[tokio::test]
  1364. async fn committing_an_unregistered_asset_is_refused() {
  1365. let ledger = setup_ledger().await;
  1366. let unknown = AssetId::new(77);
  1367. let err = ledger
  1368. .commit(
  1369. TransferBuilder::new()
  1370. .deposit(account(1), money(unknown, 100), external())
  1371. .build()
  1372. .unwrap(),
  1373. )
  1374. .await
  1375. .unwrap_err();
  1376. assert!(matches!(err, LedgerError::AssetNotFound(id) if id == unknown));
  1377. // Nothing landed: the account still holds only what it held before.
  1378. assert!(ledger.balance(&account(1), &usd()).await.unwrap().is_zero());
  1379. assert!(ledger.history(&account(1)).await.unwrap().is_empty());
  1380. }
  1381. /// Every way of naming an asset reaches the same read: the shared handle, the
  1382. /// registry row, and the bare id. A spelling the docs show and nothing compiles
  1383. /// is how two defects on this branch hid, so they are pinned here.
  1384. #[tokio::test]
  1385. async fn an_asset_can_be_named_by_handle_row_or_id() {
  1386. let ledger = setup_ledger().await;
  1387. deposit(&ledger, account(1), usd(), 100, external()).await;
  1388. let handle = ledger.asset_by_id(usd()).await.unwrap();
  1389. let row = Asset::clone(&handle);
  1390. let by_handle = ledger.balance(&account(1), &handle).await.unwrap();
  1391. let by_row = ledger.balance(&account(1), &row).await.unwrap();
  1392. let by_id = ledger.balance(&account(1), usd()).await.unwrap();
  1393. let by_id_ref = ledger.balance(&account(1), &usd()).await.unwrap();
  1394. assert_eq!(by_handle.minor_units(), 100);
  1395. assert_eq!(by_handle, by_row);
  1396. assert_eq!(by_handle, by_id);
  1397. assert_eq!(by_handle, by_id_ref);
  1398. // The same on a book policy, which is where the handle used to need `.id`.
  1399. let book = BookBuilder::new("mixed")
  1400. .allow_asset(&handle)
  1401. .allow_asset(row)
  1402. .allow_asset(usd())
  1403. .build();
  1404. assert_eq!(book.policy.allowed_assets, vec![usd(), usd(), usd()]);
  1405. }
  1406. /// Naming an asset by code registers it on first sight and returns the same
  1407. /// handle afterwards, so setup code calls it unconditionally.
  1408. #[tokio::test]
  1409. async fn naming_an_asset_by_code_registers_it_once() {
  1410. let ledger = bare_ledger();
  1411. let first = ledger.asset("EUR", "\u{20ac}", 2).await.unwrap();
  1412. let again = ledger.asset("EUR", "\u{20ac}", 2).await.unwrap();
  1413. assert_eq!(first.id, again.id);
  1414. assert_eq!(ledger.list_assets().await.unwrap().len(), 1);
  1415. // The id is minted, so it is whatever the generator gave, and the handle is
  1416. // the way back to it.
  1417. assert_eq!(ledger.asset_by_id(&first).await.unwrap().code, "EUR");
  1418. assert_eq!(first.amount("1.50").unwrap().to_string(), "1.50 EUR");
  1419. // A second code is a second asset, and amounts of the two do not combine.
  1420. let btc = ledger.asset("BTC", "\u{20bf}", 8).await.unwrap();
  1421. assert_ne!(btc.id, first.id);
  1422. assert!(
  1423. first
  1424. .amount(100)
  1425. .unwrap()
  1426. .checked_add(&btc.amount(100).unwrap())
  1427. .is_err()
  1428. );
  1429. }
  1430. /// A code already registered at another precision is refused. Returning the
  1431. /// stored row would format every later amount at a scale the caller did not ask
  1432. /// for, and the row cannot be rewritten.
  1433. #[tokio::test]
  1434. async fn redefining_an_asset_is_refused() {
  1435. let ledger = bare_ledger();
  1436. ledger.asset("EUR", "\u{20ac}", 2).await.unwrap();
  1437. let err = ledger.asset("EUR", "\u{20ac}", 8).await.unwrap_err();
  1438. assert!(matches!(
  1439. err,
  1440. LedgerError::AssetRedefined {
  1441. registered: 2,
  1442. requested: 8,
  1443. ..
  1444. }
  1445. ));
  1446. assert_eq!(
  1447. ledger.asset("EUR", "\u{20ac}", 2).await.unwrap().decimals,
  1448. 2
  1449. );
  1450. }
  1451. /// A minted asset id fits a signed 4-byte column, which is what the `asset`
  1452. /// columns are. An unmasked fold would store half of them as negative numbers.
  1453. #[tokio::test]
  1454. async fn minted_asset_ids_are_positive() {
  1455. let ledger = bare_ledger();
  1456. for n in 0..256 {
  1457. let asset = ledger.asset(format!("A{n}"), "?", 2).await.unwrap();
  1458. assert!(
  1459. asset.id.0 <= i32::MAX as u32,
  1460. "minted id {} does not fit a signed 4-byte column",
  1461. asset.id.0
  1462. );
  1463. }
  1464. assert_eq!(ledger.list_assets().await.unwrap().len(), 256);
  1465. }
  1466. /// Conservation nets to zero in each asset, read one account at a time.
  1467. ///
  1468. /// Value inside the ledger is mirrored by the offset postings that brought it
  1469. /// in, so the accounts in play net to zero. Summed from per-account reads
  1470. /// because that is the only balance read there is (ADR-0031), which also means
  1471. /// a missing account makes the total non-zero rather than quietly shrinking it.
  1472. #[tokio::test]
  1473. async fn conservation_nets_to_zero_across_the_accounts_in_play() {
  1474. let ledger = setup_ledger().await;
  1475. deposit(&ledger, account(1), usd(), 1000, external()).await;
  1476. deposit(&ledger, account(2), eur(), 500, external()).await;
  1477. pay(&ledger, account(1), account(2), usd(), 250).await;
  1478. pay(&ledger, account(2), account(3), usd(), 50).await;
  1479. let involved = [account(1), account(2), account(3), external()];
  1480. for asset in [usd(), eur()] {
  1481. let mut total = 0i128;
  1482. for id in &involved {
  1483. total += ledger.balance_exact(id, asset).await.unwrap().minor_units();
  1484. }
  1485. assert_eq!(total, 0, "{asset:?} did not net to zero");
  1486. }
  1487. // The external boundary holds the negative side of the USD deposit.
  1488. assert_eq!(
  1489. ledger
  1490. .balance_exact(&external(), usd())
  1491. .await
  1492. .unwrap()
  1493. .minor_units(),
  1494. -1000
  1495. );
  1496. }
  1497. /// What one account holds, across every registered asset, skipping the assets
  1498. /// it has no live posting of.
  1499. #[tokio::test]
  1500. async fn holdings_lists_every_asset_an_account_holds() {
  1501. let ledger = setup_ledger().await;
  1502. deposit(&ledger, account(1), usd(), 1000, external()).await;
  1503. let one = ledger.holdings(&account(1)).await.unwrap();
  1504. assert_eq!(one.len(), 1, "account 1 holds only USD");
  1505. assert_eq!(one[0].asset_id(), usd());
  1506. assert_eq!(one[0].minor_units(), 1000);
  1507. deposit(&ledger, account(1), eur(), 25, external()).await;
  1508. let two = ledger.holdings(&account(1)).await.unwrap();
  1509. assert_eq!(two.len(), 2);
  1510. assert_eq!(
  1511. two.iter().map(|a| a.minor_units()).sum::<i128>(),
  1512. 1025,
  1513. "both holdings are reported"
  1514. );
  1515. assert!(ledger.holdings(&account(3)).await.unwrap().is_empty());
  1516. }