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 = ledger.asset("USD", "$", 2).await?;
  20. ledger.create_account(Account::new(treasury)).await?;
  21. ledger
  22. .create_account(Account::debit_must_not_exceed_credit(wallet))
  23. .await?;
  24. ledger
  25. .create_account(Account::debit_must_not_exceed_credit(merchant))
  26. .await?;
  27. ledger.create_account(Account::new(external)).await?;
  28. for account in [treasury, wallet] {
  29. ledger
  30. .commit(
  31. TransferBuilder::new()
  32. .deposit(account, ("30.00", &usd), external)
  33. .build()?,
  34. )
  35. .await?;
  36. }
  37. println!("Both accounts hold 30.00 USD. Both now try to pay 70.00 USD.\n");
  38. println!("treasury permits overdraft (Account::new):");
  39. print_postings(&ledger, treasury, &usd).await?;
  40. ledger
  41. .commit(
  42. TransferBuilder::new()
  43. .pay(treasury, merchant, ("70.00", &usd))
  44. .build()?,
  45. )
  46. .await?;
  47. println!(
  48. " commit succeeded, balance {}",
  49. ledger.balance(&treasury, &usd).await?
  50. );
  51. println!(" the 30.00 posting was consumed and a 40.00 shortfall posting created:");
  52. print_postings(&ledger, treasury, &usd).await?;
  53. println!("\nwallet forbids it (Account::debit_must_not_exceed_credit):");
  54. print_postings(&ledger, wallet, &usd).await?;
  55. let refused = ledger
  56. .commit(
  57. TransferBuilder::new()
  58. .pay(wallet, merchant, ("70.00", &usd))
  59. .build()?,
  60. )
  61. .await;
  62. match refused {
  63. // The shortfall names its own asset, so this reports a quantity without
  64. // the example having to remember which asset it asked about.
  65. Err(LedgerError::Selection(shortfall)) => println!(
  66. " commit refused: available {}, requested {}",
  67. shortfall.available, 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 {}",
  74. 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: &std::sync::Arc<Asset>,
  84. ) -> Result<(), Box<dyn std::error::Error>> {
  85. for (posting, state) in ledger.postings_with_state(&account).await? {
  86. if posting.amount.asset_id() == asset.id {
  87. println!(" {:>12} {:?}", posting.amount.to_string(), state);
  88. }
  89. }
  90. Ok(())
  91. }
  92. async fn connect() -> Result<Ledger, Box<dyn std::error::Error>> {
  93. kuatia_storage_sql::install_drivers()?;
  94. let pool = sqlx::any::AnyPoolOptions::new()
  95. .max_connections(1)
  96. .connect("sqlite::memory:")
  97. .await?;
  98. let store = SqlStore::new(pool);
  99. store.migrate().await?;
  100. let ledger = Ledger::new(store);
  101. Ok(ledger)
  102. }