overdraft.rs 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. //! Overdraft: a shortfall becomes a negative posting on an account that permits
  2. //! it, and `InsufficientFunds` on an account that does not.
  3. //!
  4. //! Run with:
  5. //! ```sh
  6. //! cargo run -p kuatia --example overdraft
  7. //! ```
  8. use kuatia::error::LedgerError;
  9. use kuatia::ledger::Ledger;
  10. use kuatia_core::*;
  11. use kuatia_storage_sql::SqlStore;
  12. #[tokio::main]
  13. async fn main() -> Result<(), Box<dyn std::error::Error>> {
  14. let ledger = connect().await?;
  15. let treasury = AccountId::new(1);
  16. let wallet = AccountId::new(2);
  17. let merchant = AccountId::new(3);
  18. let external = AccountId::new(99);
  19. let usd = AssetId::new(1);
  20. let money = Amount::new(2);
  21. ledger.create_account(Account::new(treasury)).await?;
  22. ledger
  23. .create_account(Account::debit_must_not_exceed_credit(wallet))
  24. .await?;
  25. ledger
  26. .create_account(Account::debit_must_not_exceed_credit(merchant))
  27. .await?;
  28. ledger.create_account(Account::new(external)).await?;
  29. for account in [treasury, wallet] {
  30. ledger
  31. .commit(
  32. TransferBuilder::new()
  33. .deposit(account, usd, money.parse("30.00")?, external)?
  34. .build(),
  35. )
  36. .await?;
  37. }
  38. println!("Both accounts hold 30.00 USD. Both now try to pay 70.00 USD.\n");
  39. println!("treasury permits overdraft (Account::new):");
  40. print_postings(&ledger, treasury, usd).await?;
  41. ledger
  42. .commit(
  43. TransferBuilder::new()
  44. .pay(treasury, merchant, usd, money.parse("70.00")?)
  45. .build(),
  46. )
  47. .await?;
  48. println!(
  49. " commit succeeded, balance {} USD",
  50. money.format(ledger.balance(&treasury, &usd).await?)
  51. );
  52. println!(" the 30.00 posting was consumed and a 40.00 shortfall posting created:");
  53. print_postings(&ledger, treasury, usd).await?;
  54. println!("\nwallet forbids it (Account::debit_must_not_exceed_credit):");
  55. print_postings(&ledger, wallet, usd).await?;
  56. let refused = ledger
  57. .commit(
  58. TransferBuilder::new()
  59. .pay(wallet, merchant, usd, money.parse("70.00")?)
  60. .build(),
  61. )
  62. .await;
  63. match refused {
  64. Err(LedgerError::Selection(shortfall)) => println!(
  65. " commit refused: available {} USD, requested {} USD",
  66. money.format(shortfall.available),
  67. money.format(shortfall.requested),
  68. ),
  69. Err(other) => println!(" commit refused for another reason: {other}"),
  70. Ok(_) => println!(" commit succeeded, which it should not have"),
  71. }
  72. println!(
  73. " balance unchanged at {} USD",
  74. money.format(ledger.balance(&wallet, &usd).await?)
  75. );
  76. Ok(())
  77. }
  78. /// Prints each posting with its lifecycle state, so a consumed positive and a
  79. /// created negative are visible side by side rather than inferred from balances.
  80. async fn print_postings(
  81. ledger: &Ledger,
  82. account: AccountId,
  83. asset: AssetId,
  84. ) -> Result<(), Box<dyn std::error::Error>> {
  85. let money = Amount::new(2);
  86. for (posting, state) in ledger.postings_with_state(&account).await? {
  87. if posting.asset == asset {
  88. println!(" {:>10} USD {:?}", money.format(posting.value), state);
  89. }
  90. }
  91. Ok(())
  92. }
  93. async fn connect() -> Result<Ledger, Box<dyn std::error::Error>> {
  94. kuatia_storage_sql::install_drivers()?;
  95. let pool = sqlx::any::AnyPoolOptions::new()
  96. .max_connections(1)
  97. .connect("sqlite::memory:")
  98. .await?;
  99. let store = SqlStore::new(pool);
  100. store.migrate().await?;
  101. let ledger = Ledger::new(store);
  102. Ok(ledger)
  103. }