withdraw.rs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. //! Fund an account, then withdraw value out of the ledger.
  2. //!
  3. //! Run with:
  4. //! ```sh
  5. //! cargo run -p kuatia --example withdraw
  6. //! ```
  7. use kuatia::ledger::Ledger;
  8. use kuatia_core::*;
  9. use kuatia_storage_sql::SqlStore;
  10. #[tokio::main]
  11. async fn main() -> Result<(), Box<dyn std::error::Error>> {
  12. let ledger = connect().await?;
  13. let alice = AccountId::new(1);
  14. let external = AccountId::new(99);
  15. let usd = AssetId::new(1);
  16. let money = Amount::new(2);
  17. ledger
  18. .create_account(Account::debit_must_not_exceed_credit(alice))
  19. .await?;
  20. ledger.create_account(Account::new(external)).await?;
  21. // Fund Alice with $100.00.
  22. ledger
  23. .commit(
  24. TransferBuilder::new()
  25. .deposit(alice, usd, money.parse("100.00")?, external)?
  26. .build(),
  27. )
  28. .await?;
  29. println!(
  30. "after deposit: alice = {} USD",
  31. money.format(ledger.balance(&alice, &usd).await?)
  32. );
  33. // Withdraw $30.00 from Alice out to the external boundary account.
  34. ledger
  35. .commit(
  36. TransferBuilder::new()
  37. .withdraw(alice, usd, money.parse("30.00")?, external)
  38. .build(),
  39. )
  40. .await?;
  41. println!(
  42. "after withdraw: alice = {} USD",
  43. money.format(ledger.balance(&alice, &usd).await?)
  44. );
  45. // The external account carries the offset (negative) side: the mirror of the
  46. // value that currently sits inside the ledger.
  47. println!(
  48. "external boundary: {} USD",
  49. money.format(ledger.balance(&external, &usd).await?)
  50. );
  51. Ok(())
  52. }
  53. async fn connect() -> Result<Ledger, Box<dyn std::error::Error>> {
  54. kuatia_storage_sql::install_drivers()?;
  55. let pool = sqlx::any::AnyPoolOptions::new()
  56. .max_connections(1)
  57. .connect("sqlite::memory:")
  58. .await?;
  59. let store = SqlStore::new(pool);
  60. store.migrate().await?;
  61. let ledger = Ledger::new(store);
  62. Ok(ledger)
  63. }