escrow.rs 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  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 = AssetId::new(1);
  30. let money = Amount::new(2);
  31. ledger
  32. .create_account(Account::debit_must_not_exceed_credit(buyer))
  33. .await?;
  34. ledger
  35. .create_account(Account::debit_must_not_exceed_credit(seller))
  36. .await?;
  37. ledger.create_account(Account::new(bank)).await?;
  38. ledger
  39. .commit(
  40. TransferBuilder::new()
  41. .deposit(buyer, usd, money.parse("500.00")?, bank)?
  42. .reference("funding-buyer")
  43. .build(),
  44. )
  45. .await?;
  46. // Two agreements, so both endings are visible: one releases, one refunds.
  47. let sale = 7001;
  48. let cancelled = 7002;
  49. for agreement in [sale, cancelled] {
  50. // An escrow account forbids overdraft. That is what makes releasing
  51. // more than was deposited impossible rather than merely wrong.
  52. ledger
  53. .create_account(Account::debit_must_not_exceed_credit(escrow_for(agreement)))
  54. .await?;
  55. }
  56. // Enter escrow. An ordinary payment, final on commit.
  57. ledger
  58. .commit(
  59. TransferBuilder::new()
  60. .pay(buyer, escrow_for(sale), usd, money.parse("120.00")?)
  61. .reference("escrow-in-7001")
  62. .build(),
  63. )
  64. .await?;
  65. ledger
  66. .commit(
  67. TransferBuilder::new()
  68. .pay(buyer, escrow_for(cancelled), usd, money.parse("80.00")?)
  69. .reference("escrow-in-7002")
  70. .build(),
  71. )
  72. .await?;
  73. let watched = [
  74. ("buyer", buyer),
  75. ("seller", seller),
  76. ("escrow(7001)", escrow_for(sale)),
  77. ("escrow(7002)", escrow_for(cancelled)),
  78. ];
  79. report(&ledger, &money, usd, &watched).await?;
  80. // Nothing recorded that these are pending. Reading the escrow balance is
  81. // what tells you, and it is the same read that tells you how much.
  82. for agreement in [sale, cancelled] {
  83. let held = ledger.balance(&escrow_for(agreement), &usd).await?;
  84. println!(
  85. "agreement {agreement}: {} USD in escrow",
  86. money.format(held)
  87. );
  88. }
  89. // The sale closes: release to the seller.
  90. let held = ledger.balance(&escrow_for(sale), &usd).await?;
  91. ledger
  92. .commit(
  93. TransferBuilder::new()
  94. .pay(escrow_for(sale), seller, usd, held)
  95. .reference("escrow-release-7001")
  96. .build(),
  97. )
  98. .await?;
  99. // The other falls through: refund the buyer, from the same account, by the
  100. // same kind of transfer. Only the destination differs.
  101. let held = ledger.balance(&escrow_for(cancelled), &usd).await?;
  102. ledger
  103. .commit(
  104. TransferBuilder::new()
  105. .pay(escrow_for(cancelled), buyer, usd, held)
  106. .reference("escrow-refund-7002")
  107. .build(),
  108. )
  109. .await?;
  110. report(&ledger, &money, usd, &watched).await?;
  111. // A drained escrow account holds no live postings, so it can be closed and
  112. // the agreement is provably finished rather than marked finished.
  113. for agreement in [sale, cancelled] {
  114. ledger.close(&escrow_for(agreement)).await?;
  115. println!(
  116. "agreement {agreement}: escrow closed = {}",
  117. ledger
  118. .get_account(&escrow_for(agreement))
  119. .await?
  120. .is_closed()
  121. );
  122. }
  123. Ok(())
  124. }
  125. async fn report(
  126. ledger: &Ledger,
  127. money: &Amount,
  128. asset: AssetId,
  129. accounts: &[(&str, AccountId)],
  130. ) -> Result<(), Box<dyn std::error::Error>> {
  131. let mut line = String::new();
  132. for (label, account) in accounts {
  133. let balance = ledger.balance(account, &asset).await?;
  134. line.push_str(&format!("{label} {} ", money.format(balance)));
  135. }
  136. println!("{}", line.trim_end());
  137. Ok(())
  138. }
  139. async fn connect() -> Result<Ledger, Box<dyn std::error::Error>> {
  140. kuatia_storage_sql::install_drivers()?;
  141. let pool = sqlx::any::AnyPoolOptions::new()
  142. .max_connections(1)
  143. .connect("sqlite::memory:")
  144. .await?;
  145. let store = SqlStore::new(pool);
  146. store.migrate().await?;
  147. let ledger = Ledger::new(store);
  148. Ok(ledger)
  149. }