withdraw.rs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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 = ledger.asset("USD", "$", 2).await?;
  16. ledger
  17. .create_account(Account::debit_must_not_exceed_credit(alice))
  18. .await?;
  19. ledger.create_account(Account::new(external)).await?;
  20. // Written form, parsed at the asset's own two decimals.
  21. ledger
  22. .commit(
  23. TransferBuilder::new()
  24. .deposit(alice, ("100.00", &usd), external)
  25. .build()?,
  26. )
  27. .await?;
  28. println!(
  29. "after deposit: alice = {}",
  30. ledger.balance(&alice, &usd).await?
  31. );
  32. ledger
  33. .commit(
  34. TransferBuilder::new()
  35. .withdraw(alice, ("30.00", &usd), external)
  36. .build()?,
  37. )
  38. .await?;
  39. println!(
  40. "after withdraw: alice = {}",
  41. ledger.balance(&alice, &usd).await?
  42. );
  43. // The external account carries the offset (negative) side: the mirror of the
  44. // value that currently sits inside the ledger.
  45. println!(
  46. "external boundary: {}",
  47. ledger.balance(&external, &usd).await?
  48. );
  49. Ok(())
  50. }
  51. async fn connect() -> Result<Ledger, Box<dyn std::error::Error>> {
  52. kuatia_storage_sql::install_drivers()?;
  53. let pool = sqlx::any::AnyPoolOptions::new()
  54. .max_connections(1)
  55. .connect("sqlite::memory:")
  56. .await?;
  57. let store = SqlStore::new(pool);
  58. store.migrate().await?;
  59. let ledger = Ledger::new(store);
  60. Ok(ledger)
  61. }