escrow.rs 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. //! Hold a buyer's money until a deal closes, then release it or refund it.
  2. //!
  3. //! Escrow is a pending state, and this ledger has no pending state: every
  4. //! transfer is final the moment it commits. So the state lives in an account.
  5. //! Value sits in an escrow account per agreement, and "in escrow" is not a flag
  6. //! anyone set, it is the balance of that account being non-zero.
  7. //!
  8. //! See `doc/pending-states.md`.
  9. //!
  10. //! Run with:
  11. //! ```sh
  12. //! cargo run -p kuatia --example escrow
  13. //! ```
  14. use kuatia::ledger::Ledger;
  15. use kuatia_core::*;
  16. use kuatia_storage_sql::SqlStore;
  17. /// Top-level account every agreement's escrow hangs off as a subaccount, so one
  18. /// agreement's money can never be spent by another and each closes on its own.
  19. const ESCROW: i64 = 50;
  20. fn escrow_for(agreement: i64) -> AccountId {
  21. AccountId::with_sub(ESCROW, agreement)
  22. }
  23. #[tokio::main]
  24. async fn main() -> Result<(), Box<dyn std::error::Error>> {
  25. let ledger = connect().await?;
  26. let buyer = AccountId::new(1);
  27. let seller = AccountId::new(2);
  28. let bank = AccountId::new(99);
  29. let usd = ledger.asset("USD", "$", 2).await?;
  30. ledger
  31. .create_account(Account::debit_must_not_exceed_credit(buyer))
  32. .await?;
  33. ledger
  34. .create_account(Account::debit_must_not_exceed_credit(seller))
  35. .await?;
  36. ledger.create_account(Account::new(bank)).await?;
  37. ledger
  38. .commit(
  39. TransferBuilder::new()
  40. .deposit(buyer, ("500.00", &usd), bank)
  41. .reference("funding-buyer")
  42. .build()?,
  43. )
  44. .await?;
  45. // Two agreements, so both endings are visible: one releases, one refunds.
  46. let sale = 7001;
  47. let cancelled = 7002;
  48. for agreement in [sale, cancelled] {
  49. // An escrow account forbids overdraft. That is what makes releasing
  50. // more than was deposited impossible rather than merely wrong.
  51. ledger
  52. .create_account(Account::debit_must_not_exceed_credit(escrow_for(agreement)))
  53. .await?;
  54. }
  55. // Enter escrow. An ordinary payment, final on commit.
  56. ledger
  57. .commit(
  58. TransferBuilder::new()
  59. .pay(buyer, escrow_for(sale), ("120.00", &usd))
  60. .reference("escrow-in-7001")
  61. .build()?,
  62. )
  63. .await?;
  64. ledger
  65. .commit(
  66. TransferBuilder::new()
  67. .pay(buyer, escrow_for(cancelled), ("80.00", &usd))
  68. .reference("escrow-in-7002")
  69. .build()?,
  70. )
  71. .await?;
  72. let watched = [
  73. ("buyer", buyer),
  74. ("seller", seller),
  75. ("escrow(7001)", escrow_for(sale)),
  76. ("escrow(7002)", escrow_for(cancelled)),
  77. ];
  78. report(&ledger, &usd, &watched).await?;
  79. // Nothing recorded that these are pending. Reading the escrow balance is
  80. // what tells you, and it is the same read that tells you how much.
  81. for agreement in [sale, cancelled] {
  82. let held = ledger.balance(&escrow_for(agreement), &usd.id).await?;
  83. println!("agreement {agreement}: {held} in escrow");
  84. }
  85. // The sale closes: release to the seller.
  86. let held = ledger.balance(&escrow_for(sale), &usd.id).await?;
  87. ledger
  88. .commit(
  89. TransferBuilder::new()
  90. .pay(escrow_for(sale), seller, held)
  91. .reference("escrow-release-7001")
  92. .build()?,
  93. )
  94. .await?;
  95. // The other falls through: refund the buyer, from the same account, by the
  96. // same kind of transfer. Only the destination differs.
  97. let held = ledger.balance(&escrow_for(cancelled), &usd.id).await?;
  98. ledger
  99. .commit(
  100. TransferBuilder::new()
  101. .pay(escrow_for(cancelled), buyer, held)
  102. .reference("escrow-refund-7002")
  103. .build()?,
  104. )
  105. .await?;
  106. report(&ledger, &usd, &watched).await?;
  107. // A drained escrow account holds no live postings, so it can be closed and
  108. // the agreement is provably finished rather than marked finished.
  109. for agreement in [sale, cancelled] {
  110. ledger.close(&escrow_for(agreement)).await?;
  111. println!(
  112. "agreement {agreement}: escrow closed = {}",
  113. ledger
  114. .get_account(&escrow_for(agreement))
  115. .await?
  116. .is_closed()
  117. );
  118. }
  119. Ok(())
  120. }
  121. async fn report(
  122. ledger: &Ledger,
  123. asset: &Asset,
  124. accounts: &[(&str, AccountId)],
  125. ) -> Result<(), Box<dyn std::error::Error>> {
  126. let mut line = String::new();
  127. for (label, account) in accounts {
  128. let balance = ledger.balance(account, asset.id).await?;
  129. line.push_str(&format!("{label} {balance} "));
  130. }
  131. println!("{}", line.trim_end());
  132. Ok(())
  133. }
  134. async fn connect() -> Result<Ledger, Box<dyn std::error::Error>> {
  135. kuatia_storage_sql::install_drivers()?;
  136. let pool = sqlx::any::AnyPoolOptions::new()
  137. .max_connections(1)
  138. .connect("sqlite::memory:")
  139. .await?;
  140. let store = SqlStore::new(pool);
  141. store.migrate().await?;
  142. let ledger = Ledger::new(store);
  143. Ok(ledger)
  144. }