escrow.rs 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  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::prelude::*;
  15. /// Top-level account every agreement's escrow hangs off as a subaccount, so one
  16. /// agreement's money can never be spent by another and each closes on its own.
  17. const ESCROW: i64 = 50;
  18. fn escrow_for(agreement: i64) -> AccountId {
  19. AccountId::with_sub(ESCROW, agreement)
  20. }
  21. #[tokio::main]
  22. async fn main() -> Result<(), Box<dyn std::error::Error>> {
  23. let ledger = Ledger::connect("sqlite::memory:").await?;
  24. let buyer = AccountId::new(1);
  25. let seller = AccountId::new(2);
  26. let bank = AccountId::new(99);
  27. let usd = ledger.asset("USD", "$", 2).await?;
  28. ledger
  29. .create_account(Account::debit_must_not_exceed_credit(buyer))
  30. .await?;
  31. ledger
  32. .create_account(Account::debit_must_not_exceed_credit(seller))
  33. .await?;
  34. ledger.create_account(Account::new(bank)).await?;
  35. ledger
  36. .commit(
  37. TransferBuilder::new()
  38. .deposit(buyer, ("500.00", &usd), bank)
  39. .reference("funding-buyer")
  40. .build()?,
  41. )
  42. .await?;
  43. // Two agreements, so both endings are visible: one releases, one refunds.
  44. let sale = 7001;
  45. let cancelled = 7002;
  46. for agreement in [sale, cancelled] {
  47. // An escrow account forbids overdraft. That is what makes releasing
  48. // more than was deposited impossible rather than merely wrong.
  49. ledger
  50. .create_account(Account::debit_must_not_exceed_credit(escrow_for(agreement)))
  51. .await?;
  52. }
  53. // Enter escrow. An ordinary payment, final on commit.
  54. ledger
  55. .commit(
  56. TransferBuilder::new()
  57. .pay(buyer, escrow_for(sale), ("120.00", &usd))
  58. .reference("escrow-in-7001")
  59. .build()?,
  60. )
  61. .await?;
  62. ledger
  63. .commit(
  64. TransferBuilder::new()
  65. .pay(buyer, escrow_for(cancelled), ("80.00", &usd))
  66. .reference("escrow-in-7002")
  67. .build()?,
  68. )
  69. .await?;
  70. let watched = [
  71. ("buyer", buyer),
  72. ("seller", seller),
  73. ("escrow(7001)", escrow_for(sale)),
  74. ("escrow(7002)", escrow_for(cancelled)),
  75. ];
  76. report(&ledger, &usd, &watched).await?;
  77. // Nothing recorded that these are pending. Reading the escrow balance is
  78. // what tells you, and it is the same read that tells you how much.
  79. for agreement in [sale, cancelled] {
  80. let held = ledger.balance(&escrow_for(agreement), &usd.id).await?;
  81. println!("agreement {agreement}: {held} in escrow");
  82. }
  83. // The sale closes: release to the seller.
  84. let held = ledger.balance(&escrow_for(sale), &usd.id).await?;
  85. ledger
  86. .commit(
  87. TransferBuilder::new()
  88. .pay(escrow_for(sale), seller, held)
  89. .reference("escrow-release-7001")
  90. .build()?,
  91. )
  92. .await?;
  93. // The other falls through: refund the buyer, from the same account, by the
  94. // same kind of transfer. Only the destination differs.
  95. let held = ledger.balance(&escrow_for(cancelled), &usd.id).await?;
  96. ledger
  97. .commit(
  98. TransferBuilder::new()
  99. .pay(escrow_for(cancelled), buyer, held)
  100. .reference("escrow-refund-7002")
  101. .build()?,
  102. )
  103. .await?;
  104. report(&ledger, &usd, &watched).await?;
  105. // A drained escrow account holds no live postings, so it can be closed and
  106. // the agreement is provably finished rather than marked finished.
  107. for agreement in [sale, cancelled] {
  108. ledger.close(&escrow_for(agreement)).await?;
  109. println!(
  110. "agreement {agreement}: escrow closed = {}",
  111. ledger
  112. .get_account(&escrow_for(agreement))
  113. .await?
  114. .is_closed()
  115. );
  116. }
  117. Ok(())
  118. }
  119. async fn report(
  120. ledger: &Ledger,
  121. asset: &Asset,
  122. accounts: &[(&str, AccountId)],
  123. ) -> Result<(), Box<dyn std::error::Error>> {
  124. let mut line = String::new();
  125. for (label, account) in accounts {
  126. let balance = ledger.balance(account, asset.id).await?;
  127. line.push_str(&format!("{label} {balance} "));
  128. }
  129. println!("{}", line.trim_end());
  130. Ok(())
  131. }