integration.rs 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691
  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 list_accounts_returns_all() {
  852. let ledger = setup_ledger().await;
  853. let accounts = ledger.list_accounts().await.unwrap();
  854. // setup_ledger creates accounts 1, 2, 3, 99
  855. assert_eq!(accounts.len(), 4);
  856. }
  857. #[tokio::test]
  858. async fn get_account_by_id() {
  859. let ledger = setup_ledger().await;
  860. let acc = ledger.get_account(&account(1)).await.unwrap();
  861. assert_eq!(acc.id, account(1));
  862. assert!(acc.forbids_overdraft());
  863. }
  864. #[tokio::test]
  865. async fn get_account_not_found() {
  866. let ledger = setup_ledger().await;
  867. let result = ledger.get_account(&account(999)).await;
  868. assert!(result.is_err());
  869. }
  870. // ---------------------------------------------------------------------------
  871. // Append-only accounts: version history, version conflict, account_versions
  872. // ---------------------------------------------------------------------------
  873. #[tokio::test]
  874. async fn account_history_tracks_versions() {
  875. let ledger = setup_ledger().await;
  876. // Version 1: created
  877. let history = ledger.account_history(&account(1)).await.unwrap();
  878. assert_eq!(history.len(), 1);
  879. assert_eq!(history[0].version, 1);
  880. // Version 2: frozen
  881. ledger.freeze(&account(1)).await.unwrap();
  882. let history = ledger.account_history(&account(1)).await.unwrap();
  883. assert_eq!(history.len(), 2);
  884. assert_eq!(history[1].version, 2);
  885. assert!(history[1].is_frozen());
  886. // Version 3: unfrozen
  887. ledger.unfreeze(&account(1)).await.unwrap();
  888. let history = ledger.account_history(&account(1)).await.unwrap();
  889. assert_eq!(history.len(), 3);
  890. assert_eq!(history[2].version, 3);
  891. assert!(!history[2].is_frozen());
  892. }
  893. #[tokio::test]
  894. async fn store_never_compacts() {
  895. let ledger = setup_ledger().await;
  896. // Freeze and unfreeze multiple times
  897. for _ in 0..5 {
  898. ledger.freeze(&account(1)).await.unwrap();
  899. ledger.unfreeze(&account(1)).await.unwrap();
  900. }
  901. // All 11 versions preserved (1 creation + 10 mutations)
  902. let history = ledger.account_history(&account(1)).await.unwrap();
  903. assert_eq!(history.len(), 11);
  904. // Versions are monotonically increasing
  905. for (i, acc) in history.iter().enumerate() {
  906. assert_eq!(acc.version, (i + 1) as u64);
  907. }
  908. }
  909. #[tokio::test]
  910. async fn transfer_records_account_snapshots() {
  911. let ledger = setup_ledger().await;
  912. deposit(&ledger, account(1), usd(), 100, external()).await;
  913. // The envelope should have account_snapshots populated by the resolve step
  914. let transfers = ledger.history(&account(1)).await.unwrap();
  915. assert_eq!(transfers.len(), 1);
  916. assert!(!transfers[0].envelope.account_snapshots().is_empty());
  917. }
  918. #[tokio::test]
  919. async fn stale_snapshot_rejected() {
  920. let ledger = setup_ledger().await;
  921. // Get current snapshot for account(1)
  922. let acc1 = ledger.get_account(&account(1)).await.unwrap();
  923. let stale_snapshot = kuatia_core::account_snapshot_id(&acc1);
  924. // Freeze account(1) -- changes its snapshot hash
  925. ledger.freeze(&account(1)).await.unwrap();
  926. // Build an envelope with the stale snapshot
  927. let envelope = EnvelopeBuilder::new()
  928. .creates(vec![
  929. NewPosting {
  930. owner: account(1),
  931. amount: money(usd(), 100),
  932. payer: None,
  933. },
  934. NewPosting {
  935. owner: external(),
  936. amount: money(usd(), -100),
  937. payer: None,
  938. },
  939. ])
  940. .account_snapshots(vec![stale_snapshot])
  941. .build();
  942. let result = ledger.commit_envelope(envelope).await;
  943. assert!(result.is_err());
  944. }
  945. #[tokio::test]
  946. async fn account_hash_deterministic() {
  947. let acc = make_account(42, AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT);
  948. let h1 = kuatia_core::account_hash(&acc);
  949. let h2 = kuatia_core::account_hash(&acc);
  950. assert_eq!(h1, h2);
  951. }
  952. #[tokio::test]
  953. async fn account_hash_changes_with_version() {
  954. let mut acc = make_account(42, AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT);
  955. let h1 = kuatia_core::account_hash(&acc);
  956. acc.version = 2;
  957. acc.flags |= AccountFlags::FROZEN;
  958. let h2 = kuatia_core::account_hash(&acc);
  959. assert_ne!(h1, h2);
  960. }
  961. // ---------------------------------------------------------------------------
  962. // Overdraft via negative postings
  963. // ---------------------------------------------------------------------------
  964. #[tokio::test]
  965. async fn overdraft_creates_negative_posting() {
  966. let store = InMemoryStore::new();
  967. let ledger = Arc::new(Ledger::new(store));
  968. register_assets(&ledger).await;
  969. for (id, flags) in [
  970. (10, AccountFlags::empty()),
  971. (2, AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT),
  972. (99, AccountFlags::empty()),
  973. ] {
  974. ledger
  975. .store()
  976. .create_account(make_account(id, flags))
  977. .await
  978. .unwrap();
  979. }
  980. // Fund account 10 with 50, then pay 100 — overdraft covers the 50 shortfall.
  981. deposit(&ledger, account(10), usd(), 50, external()).await;
  982. pay(&ledger, account(10), account(2), usd(), 100).await;
  983. assert_eq!(
  984. ledger
  985. .balance(&account(10), &usd())
  986. .await
  987. .unwrap()
  988. .minor_units(),
  989. -50
  990. );
  991. assert_eq!(
  992. ledger
  993. .balance(&account(2), &usd())
  994. .await
  995. .unwrap()
  996. .minor_units(),
  997. 100
  998. );
  999. // A negative posting now backs the overdraft.
  1000. let postings = ledger
  1001. .store()
  1002. .get_postings_by_account(10, None, Some(&usd()), PostingFilter::Live)
  1003. .await
  1004. .unwrap();
  1005. assert!(postings.iter().any(|p| p.amount.minor_units() == -50));
  1006. }
  1007. #[tokio::test]
  1008. async fn debit_must_not_exceed_credit_rejects_overspend() {
  1009. let store = InMemoryStore::new();
  1010. let ledger = Arc::new(Ledger::new(store));
  1011. register_assets(&ledger).await;
  1012. for (id, flags) in [
  1013. (10, AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT),
  1014. (2, AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT),
  1015. (99, AccountFlags::empty()),
  1016. ] {
  1017. ledger
  1018. .store()
  1019. .create_account(make_account(id, flags))
  1020. .await
  1021. .unwrap();
  1022. }
  1023. // Account 10 forbids overdraft, so paying 100 from an empty balance fails.
  1024. let transfer = TransferBuilder::new()
  1025. .pay(account(10), account(2), money(usd(), 100))
  1026. .build()
  1027. .unwrap();
  1028. assert!(ledger.commit(transfer).await.is_err());
  1029. assert_eq!(
  1030. ledger
  1031. .balance(&account(10), &usd())
  1032. .await
  1033. .unwrap()
  1034. .minor_units(),
  1035. 0
  1036. );
  1037. }
  1038. #[tokio::test]
  1039. async fn overdraft_allows_arbitrary_negative() {
  1040. let store = InMemoryStore::new();
  1041. let ledger = Arc::new(Ledger::new(store));
  1042. register_assets(&ledger).await;
  1043. for (id, flags) in [
  1044. (10, AccountFlags::empty()),
  1045. (2, AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT),
  1046. (99, AccountFlags::empty()),
  1047. ] {
  1048. ledger
  1049. .store()
  1050. .create_account(make_account(id, flags))
  1051. .await
  1052. .unwrap();
  1053. }
  1054. pay(&ledger, account(10), account(2), usd(), 1_000_000).await;
  1055. assert_eq!(
  1056. ledger
  1057. .balance(&account(10), &usd())
  1058. .await
  1059. .unwrap()
  1060. .minor_units(),
  1061. -1_000_000
  1062. );
  1063. }
  1064. // ---------------------------------------------------------------------------
  1065. // Book policy enforcement
  1066. // ---------------------------------------------------------------------------
  1067. #[tokio::test]
  1068. async fn book_policy_rejects_disallowed_asset() {
  1069. let ledger = setup_ledger().await;
  1070. // Book 5 permits only EUR.
  1071. let book = BookBuilder::new("eur-only")
  1072. .id(BookId::new(5))
  1073. .allow_asset(eur())
  1074. .build();
  1075. ledger.store().create_book(book).await.unwrap();
  1076. deposit(&ledger, account(1), usd(), 100, external()).await;
  1077. // Paying USD under a EUR-only book is rejected, balance unchanged.
  1078. let transfer = TransferBuilder::new()
  1079. .book(BookId::new(5))
  1080. .pay(account(1), account(2), money(usd(), 50))
  1081. .build()
  1082. .unwrap();
  1083. assert!(ledger.commit(transfer).await.is_err());
  1084. assert_eq!(
  1085. ledger
  1086. .balance(&account(1), &usd())
  1087. .await
  1088. .unwrap()
  1089. .minor_units(),
  1090. 100
  1091. );
  1092. }
  1093. #[tokio::test]
  1094. async fn transfer_in_missing_named_book_is_rejected() {
  1095. let ledger = setup_ledger().await;
  1096. deposit(&ledger, account(1), usd(), 100, external()).await;
  1097. let transfer = TransferBuilder::new()
  1098. .book(BookId::new(404))
  1099. .pay(account(1), account(2), money(usd(), 50))
  1100. .build()
  1101. .unwrap();
  1102. assert!(ledger.commit(transfer).await.is_err());
  1103. assert_eq!(
  1104. ledger
  1105. .balance(&account(1), &usd())
  1106. .await
  1107. .unwrap()
  1108. .minor_units(),
  1109. 100
  1110. );
  1111. }
  1112. // ---------------------------------------------------------------------------
  1113. // Content-addressed determinism
  1114. // ---------------------------------------------------------------------------
  1115. #[tokio::test]
  1116. async fn identical_transfers_share_transfer_id() {
  1117. // Two independently-built default-book transfers must hash identically.
  1118. let a = TransferBuilder::new()
  1119. .pay(account(1), account(2), money(usd(), 10))
  1120. .build()
  1121. .unwrap();
  1122. let b = TransferBuilder::new()
  1123. .pay(account(1), account(2), money(usd(), 10))
  1124. .build()
  1125. .unwrap();
  1126. assert_eq!(a.book, b.book, "default book must be deterministic");
  1127. assert_eq!(a.book, DEFAULT_BOOK);
  1128. }
  1129. // ---------------------------------------------------------------------------
  1130. // Subaccounts (ADR-0012)
  1131. // ---------------------------------------------------------------------------
  1132. #[tokio::test]
  1133. async fn subaccount_balances_are_segregated() {
  1134. let ledger = setup_ledger().await;
  1135. let sub = AccountId::with_sub(1, 7);
  1136. // A subaccount is a full account record with its own policy.
  1137. ledger
  1138. .store()
  1139. .create_account(Account::debit_must_not_exceed_credit(sub))
  1140. .await
  1141. .unwrap();
  1142. // Fund the main account (1, 0) and the subaccount (1, 7) independently.
  1143. deposit(&ledger, account(1), usd(), 100, external()).await;
  1144. deposit(&ledger, sub, usd(), 40, external()).await;
  1145. // balance() reads exactly one subaccount and never rolls up the other.
  1146. assert_eq!(
  1147. ledger
  1148. .balance(&account(1), &usd())
  1149. .await
  1150. .unwrap()
  1151. .minor_units(),
  1152. 100
  1153. );
  1154. assert_eq!(
  1155. ledger.balance(&sub, &usd()).await.unwrap().minor_units(),
  1156. 40
  1157. );
  1158. // list_subaccounts spans the base id's subaccounts, sorted.
  1159. let subs = ledger.list_subaccounts(&account(1)).await.unwrap();
  1160. assert_eq!(subs, vec![account(1), sub]);
  1161. // balances() reports one entry per subaccount, never summed.
  1162. let all = ledger.balances(&account(1), &usd(), None).await.unwrap();
  1163. assert_eq!(all.len(), 2);
  1164. assert_eq!(
  1165. all.iter()
  1166. .find(|b| b.account == account(1))
  1167. .unwrap()
  1168. .amount
  1169. .minor_units(),
  1170. 100
  1171. );
  1172. assert_eq!(
  1173. all.iter()
  1174. .find(|b| b.account == sub)
  1175. .unwrap()
  1176. .amount
  1177. .minor_units(),
  1178. 40
  1179. );
  1180. // A subaccount filter restricts to that one.
  1181. let just_sub = ledger.balances(&account(1), &usd(), Some(7)).await.unwrap();
  1182. assert_eq!(just_sub.len(), 1);
  1183. assert_eq!(just_sub[0].account, sub);
  1184. assert_eq!(just_sub[0].amount.minor_units(), 40);
  1185. }
  1186. #[tokio::test]
  1187. async fn pay_moves_value_between_subaccounts() {
  1188. let ledger = setup_ledger().await;
  1189. let sub = AccountId::with_sub(1, 7);
  1190. ledger
  1191. .store()
  1192. .create_account(Account::debit_must_not_exceed_credit(sub))
  1193. .await
  1194. .unwrap();
  1195. deposit(&ledger, sub, usd(), 40, external()).await;
  1196. // Move 30 from subaccount (1, 7) to the main account (1, 0).
  1197. pay(&ledger, sub, account(1), usd(), 30).await;
  1198. assert_eq!(
  1199. ledger.balance(&sub, &usd()).await.unwrap().minor_units(),
  1200. 10
  1201. );
  1202. assert_eq!(
  1203. ledger
  1204. .balance(&account(1), &usd())
  1205. .await
  1206. .unwrap()
  1207. .minor_units(),
  1208. 30
  1209. );
  1210. }
  1211. #[tokio::test]
  1212. async fn closed_subaccounts_drop_out_of_aggregate_reads() {
  1213. let ledger = setup_ledger().await;
  1214. let sub = AccountId::with_sub(1, 7);
  1215. ledger
  1216. .store()
  1217. .create_account(Account::debit_must_not_exceed_credit(sub))
  1218. .await
  1219. .unwrap();
  1220. // The subaccount is created then closed while empty.
  1221. ledger.close(&sub).await.unwrap();
  1222. // list_subaccounts and balances exclude the closed subaccount.
  1223. let subs = ledger.list_subaccounts(&account(1)).await.unwrap();
  1224. assert_eq!(subs, vec![account(1)]);
  1225. let all = ledger.balances(&account(1), &usd(), None).await.unwrap();
  1226. assert!(all.iter().all(|b| b.account != sub));
  1227. }
  1228. #[tokio::test]
  1229. async fn registering_an_asset_makes_it_readable() {
  1230. let ledger = bare_ledger();
  1231. let usd = Asset::new(usd(), "USD", "$", 2);
  1232. ledger.create_asset(usd.clone()).await.unwrap();
  1233. let got = ledger.asset_by_id(&usd).await.unwrap();
  1234. assert_eq!(*got, usd);
  1235. // Built from the row the registry handed back, so the code and the scale in
  1236. // the rendering are the registered ones.
  1237. assert_eq!(Amount::from((65_000, got)).to_string(), "650.00 USD");
  1238. assert_eq!(ledger.list_assets().await.unwrap(), vec![usd]);
  1239. }
  1240. #[tokio::test]
  1241. async fn an_unregistered_asset_is_not_found() {
  1242. let ledger = bare_ledger();
  1243. let err = ledger.asset_by_id(&usd()).await.unwrap_err();
  1244. assert!(matches!(err, LedgerError::AssetNotFound(id) if id == usd()));
  1245. }
  1246. /// A second registration is refused rather than merged, because a row is
  1247. /// immutable: changing the precision would reinterpret every amount already
  1248. /// recorded against the asset.
  1249. #[tokio::test]
  1250. async fn registering_a_known_asset_is_refused() {
  1251. let ledger = bare_ledger();
  1252. ledger
  1253. .create_asset(Asset::new(usd(), "USD", "$", 2))
  1254. .await
  1255. .unwrap();
  1256. let err = ledger
  1257. .create_asset(Asset::new(usd(), "NOT-USD", "!", 8))
  1258. .await
  1259. .unwrap_err();
  1260. assert!(matches!(err, LedgerError::AssetAlreadyExists(id) if id == usd()));
  1261. assert_eq!(ledger.asset_by_id(&usd()).await.unwrap().decimals, 2);
  1262. }
  1263. /// A miss is not cached, so an asset registered after a failed lookup is found.
  1264. #[tokio::test]
  1265. async fn a_missed_lookup_does_not_poison_the_cache() {
  1266. let ledger = bare_ledger();
  1267. assert!(ledger.asset_by_id(&eur()).await.is_err());
  1268. ledger
  1269. .create_asset(Asset::new(eur(), "EUR", "\u{20ac}", 2))
  1270. .await
  1271. .unwrap();
  1272. assert_eq!(ledger.asset_by_id(&eur()).await.unwrap().code, "EUR");
  1273. }
  1274. /// A balance comes back denominated, so what a caller holds is a quantity of a
  1275. /// named asset rather than a bare number.
  1276. #[tokio::test]
  1277. async fn a_balance_carries_the_asset_it_was_read_for() {
  1278. let ledger = setup_ledger().await;
  1279. deposit(&ledger, account(1), usd(), 100, external()).await;
  1280. let bal = ledger.balance(&account(1), &usd()).await.unwrap();
  1281. assert_eq!(bal.asset_id(), usd());
  1282. assert_eq!(bal.minor_units(), 100);
  1283. assert_eq!(bal.to_string(), "1.00 USD");
  1284. assert_eq!(
  1285. ledger
  1286. .balance_exact(&account(1), &usd())
  1287. .await
  1288. .unwrap()
  1289. .asset_id(),
  1290. usd()
  1291. );
  1292. }
  1293. /// The bug the type exists to stop: two balances from one ledger, in different
  1294. /// assets, refusing to be added instead of producing a number denominated in
  1295. /// nothing.
  1296. #[tokio::test]
  1297. async fn two_assets_from_one_ledger_do_not_add() {
  1298. let ledger = setup_ledger().await;
  1299. deposit(&ledger, account(1), usd(), 100, external()).await;
  1300. deposit(&ledger, account(1), eur(), 50, external()).await;
  1301. let dollars = ledger.balance(&account(1), &usd()).await.unwrap();
  1302. let euros = ledger.balance(&account(1), &eur()).await.unwrap();
  1303. assert_eq!(
  1304. dollars.checked_add(&euros),
  1305. Err(AmountError::AssetMismatch {
  1306. left: usd(),
  1307. right: eur(),
  1308. })
  1309. );
  1310. assert_eq!(dollars.checked_add(&dollars).unwrap().minor_units(), 200);
  1311. }
  1312. /// A shortfall names the asset that fell short, so a caller reporting it does
  1313. /// not have to guess which one the two values are in.
  1314. #[tokio::test]
  1315. async fn insufficient_funds_names_the_asset() {
  1316. let ledger = setup_ledger().await;
  1317. deposit(&ledger, account(1), usd(), 40, external()).await;
  1318. let err = ledger
  1319. .commit(
  1320. TransferBuilder::new()
  1321. .pay(account(1), account(2), money(usd(), 100))
  1322. .build()
  1323. .unwrap(),
  1324. )
  1325. .await
  1326. .unwrap_err();
  1327. let LedgerError::Selection(shortfall) = err else {
  1328. panic!("expected a selection failure, got {err:?}");
  1329. };
  1330. assert_eq!(shortfall.available.asset_id(), usd());
  1331. assert_eq!(shortfall.available, money(usd(), 40));
  1332. assert_eq!(shortfall.requested, money(usd(), 100));
  1333. }
  1334. /// A commit in an unregistered asset is refused before anything is written.
  1335. /// Conservation puts every asset a transfer moves value in on its created side,
  1336. /// so that side is the whole set to check.
  1337. #[tokio::test]
  1338. async fn committing_an_unregistered_asset_is_refused() {
  1339. let ledger = setup_ledger().await;
  1340. let unknown = AssetId::new(77);
  1341. let err = ledger
  1342. .commit(
  1343. TransferBuilder::new()
  1344. .deposit(account(1), money(unknown, 100), external())
  1345. .build()
  1346. .unwrap(),
  1347. )
  1348. .await
  1349. .unwrap_err();
  1350. assert!(matches!(err, LedgerError::AssetNotFound(id) if id == unknown));
  1351. // Nothing landed: the account still holds only what it held before.
  1352. assert!(ledger.balance(&account(1), &usd()).await.unwrap().is_zero());
  1353. assert!(ledger.history(&account(1)).await.unwrap().is_empty());
  1354. }
  1355. /// Every way of naming an asset reaches the same read: the shared handle, the
  1356. /// registry row, and the bare id. A spelling the docs show and nothing compiles
  1357. /// is how two defects on this branch hid, so they are pinned here.
  1358. #[tokio::test]
  1359. async fn an_asset_can_be_named_by_handle_row_or_id() {
  1360. let ledger = setup_ledger().await;
  1361. deposit(&ledger, account(1), usd(), 100, external()).await;
  1362. let handle = ledger.asset_by_id(usd()).await.unwrap();
  1363. let row = Asset::clone(&handle);
  1364. let by_handle = ledger.balance(&account(1), &handle).await.unwrap();
  1365. let by_row = ledger.balance(&account(1), &row).await.unwrap();
  1366. let by_id = ledger.balance(&account(1), usd()).await.unwrap();
  1367. let by_id_ref = ledger.balance(&account(1), &usd()).await.unwrap();
  1368. assert_eq!(by_handle.minor_units(), 100);
  1369. assert_eq!(by_handle, by_row);
  1370. assert_eq!(by_handle, by_id);
  1371. assert_eq!(by_handle, by_id_ref);
  1372. // The same on a book policy, which is where the handle used to need `.id`.
  1373. let book = BookBuilder::new("mixed")
  1374. .allow_asset(&handle)
  1375. .allow_asset(row)
  1376. .allow_asset(usd())
  1377. .build();
  1378. assert_eq!(book.policy.allowed_assets, vec![usd(), usd(), usd()]);
  1379. }
  1380. /// Naming an asset by code registers it on first sight and returns the same
  1381. /// handle afterwards, so setup code calls it unconditionally.
  1382. #[tokio::test]
  1383. async fn naming_an_asset_by_code_registers_it_once() {
  1384. let ledger = bare_ledger();
  1385. let first = ledger.asset("EUR", "\u{20ac}", 2).await.unwrap();
  1386. let again = ledger.asset("EUR", "\u{20ac}", 2).await.unwrap();
  1387. assert_eq!(first.id, again.id);
  1388. assert_eq!(ledger.list_assets().await.unwrap().len(), 1);
  1389. // The id is minted, so it is whatever the generator gave, and the handle is
  1390. // the way back to it.
  1391. assert_eq!(ledger.asset_by_id(&first).await.unwrap().code, "EUR");
  1392. assert_eq!(first.amount("1.50").unwrap().to_string(), "1.50 EUR");
  1393. // A second code is a second asset, and amounts of the two do not combine.
  1394. let btc = ledger.asset("BTC", "\u{20bf}", 8).await.unwrap();
  1395. assert_ne!(btc.id, first.id);
  1396. assert!(
  1397. first
  1398. .amount(100)
  1399. .unwrap()
  1400. .checked_add(&btc.amount(100).unwrap())
  1401. .is_err()
  1402. );
  1403. }
  1404. /// A code already registered at another precision is refused. Returning the
  1405. /// stored row would format every later amount at a scale the caller did not ask
  1406. /// for, and the row cannot be rewritten.
  1407. #[tokio::test]
  1408. async fn redefining_an_asset_is_refused() {
  1409. let ledger = bare_ledger();
  1410. ledger.asset("EUR", "\u{20ac}", 2).await.unwrap();
  1411. let err = ledger.asset("EUR", "\u{20ac}", 8).await.unwrap_err();
  1412. assert!(matches!(
  1413. err,
  1414. LedgerError::AssetRedefined {
  1415. registered: 2,
  1416. requested: 8,
  1417. ..
  1418. }
  1419. ));
  1420. assert_eq!(
  1421. ledger.asset("EUR", "\u{20ac}", 2).await.unwrap().decimals,
  1422. 2
  1423. );
  1424. }
  1425. /// A minted asset id fits a signed 4-byte column, which is what the `asset`
  1426. /// columns are. An unmasked fold would store half of them as negative numbers.
  1427. #[tokio::test]
  1428. async fn minted_asset_ids_are_positive() {
  1429. let ledger = bare_ledger();
  1430. for n in 0..256 {
  1431. let asset = ledger.asset(format!("A{n}"), "?", 2).await.unwrap();
  1432. assert!(
  1433. asset.id.0 <= i32::MAX as u32,
  1434. "minted id {} does not fit a signed 4-byte column",
  1435. asset.id.0
  1436. );
  1437. }
  1438. assert_eq!(ledger.list_assets().await.unwrap().len(), 256);
  1439. }
  1440. /// Conservation nets to zero in each asset, read one account at a time.
  1441. ///
  1442. /// Value inside the ledger is mirrored by the offset postings that brought it
  1443. /// in, so the accounts in play net to zero. Summed from per-account reads
  1444. /// because that is the only balance read there is (ADR-0031), which also means
  1445. /// a missing account makes the total non-zero rather than quietly shrinking it.
  1446. #[tokio::test]
  1447. async fn conservation_nets_to_zero_across_the_accounts_in_play() {
  1448. let ledger = setup_ledger().await;
  1449. deposit(&ledger, account(1), usd(), 1000, external()).await;
  1450. deposit(&ledger, account(2), eur(), 500, external()).await;
  1451. pay(&ledger, account(1), account(2), usd(), 250).await;
  1452. pay(&ledger, account(2), account(3), usd(), 50).await;
  1453. let involved = [account(1), account(2), account(3), external()];
  1454. for asset in [usd(), eur()] {
  1455. let mut total = 0i128;
  1456. for id in &involved {
  1457. total += ledger.balance_exact(id, asset).await.unwrap().minor_units();
  1458. }
  1459. assert_eq!(total, 0, "{asset:?} did not net to zero");
  1460. }
  1461. // The external boundary holds the negative side of the USD deposit.
  1462. assert_eq!(
  1463. ledger
  1464. .balance_exact(&external(), usd())
  1465. .await
  1466. .unwrap()
  1467. .minor_units(),
  1468. -1000
  1469. );
  1470. }
  1471. /// What one account holds, across every registered asset, skipping the assets
  1472. /// it has no live posting of.
  1473. #[tokio::test]
  1474. async fn holdings_lists_every_asset_an_account_holds() {
  1475. let ledger = setup_ledger().await;
  1476. deposit(&ledger, account(1), usd(), 1000, external()).await;
  1477. let one = ledger.holdings(&account(1)).await.unwrap();
  1478. assert_eq!(one.len(), 1, "account 1 holds only USD");
  1479. assert_eq!(one[0].asset_id(), usd());
  1480. assert_eq!(one[0].minor_units(), 1000);
  1481. deposit(&ledger, account(1), eur(), 25, external()).await;
  1482. let two = ledger.holdings(&account(1)).await.unwrap();
  1483. assert_eq!(two.len(), 2);
  1484. assert_eq!(
  1485. two.iter().map(|a| a.minor_units()).sum::<i128>(),
  1486. 1025,
  1487. "both holdings are reported"
  1488. );
  1489. assert!(ledger.holdings(&account(3)).await.unwrap().is_empty());
  1490. }