//! Hold a buyer's money until a deal closes, then release it or refund it. //! //! Escrow is a pending state, and this ledger has no pending state: every //! transfer is final the moment it commits. So the state lives in an account. //! Value sits in an escrow account per agreement, and "in escrow" is not a flag //! anyone set, it is the balance of that account being non-zero. //! //! See `doc/pending-states.md`. //! //! Run with: //! ```sh //! cargo run -p kuatia --example escrow //! ``` use kuatia::ledger::Ledger; use kuatia_core::*; use kuatia_storage_sql::SqlStore; /// Top-level account every agreement's escrow hangs off as a subaccount, so one /// agreement's money can never be spent by another and each closes on its own. const ESCROW: i64 = 50; fn escrow_for(agreement: i64) -> AccountId { AccountId::with_sub(ESCROW, agreement) } #[tokio::main] async fn main() -> Result<(), Box> { let ledger = connect().await?; let buyer = AccountId::new(1); let seller = AccountId::new(2); let bank = AccountId::new(99); let usd = AssetId::new(1); let money = Amount::new(2); ledger .create_account(Account::debit_must_not_exceed_credit(buyer)) .await?; ledger .create_account(Account::debit_must_not_exceed_credit(seller)) .await?; ledger.create_account(Account::new(bank)).await?; ledger .commit( TransferBuilder::new() .deposit(buyer, usd, money.parse("500.00")?, bank)? .reference("funding-buyer") .build(), ) .await?; // Two agreements, so both endings are visible: one releases, one refunds. let sale = 7001; let cancelled = 7002; for agreement in [sale, cancelled] { // An escrow account forbids overdraft. That is what makes releasing // more than was deposited impossible rather than merely wrong. ledger .create_account(Account::debit_must_not_exceed_credit(escrow_for(agreement))) .await?; } // Enter escrow. An ordinary payment, final on commit. ledger .commit( TransferBuilder::new() .pay(buyer, escrow_for(sale), usd, money.parse("120.00")?) .reference("escrow-in-7001") .build(), ) .await?; ledger .commit( TransferBuilder::new() .pay(buyer, escrow_for(cancelled), usd, money.parse("80.00")?) .reference("escrow-in-7002") .build(), ) .await?; let watched = [ ("buyer", buyer), ("seller", seller), ("escrow(7001)", escrow_for(sale)), ("escrow(7002)", escrow_for(cancelled)), ]; report(&ledger, &money, usd, &watched).await?; // Nothing recorded that these are pending. Reading the escrow balance is // what tells you, and it is the same read that tells you how much. for agreement in [sale, cancelled] { let held = ledger.balance(&escrow_for(agreement), &usd).await?; println!( "agreement {agreement}: {} USD in escrow", money.format(held) ); } // The sale closes: release to the seller. let held = ledger.balance(&escrow_for(sale), &usd).await?; ledger .commit( TransferBuilder::new() .pay(escrow_for(sale), seller, usd, held) .reference("escrow-release-7001") .build(), ) .await?; // The other falls through: refund the buyer, from the same account, by the // same kind of transfer. Only the destination differs. let held = ledger.balance(&escrow_for(cancelled), &usd).await?; ledger .commit( TransferBuilder::new() .pay(escrow_for(cancelled), buyer, usd, held) .reference("escrow-refund-7002") .build(), ) .await?; report(&ledger, &money, usd, &watched).await?; // A drained escrow account holds no live postings, so it can be closed and // the agreement is provably finished rather than marked finished. for agreement in [sale, cancelled] { ledger.close(&escrow_for(agreement)).await?; println!( "agreement {agreement}: escrow closed = {}", ledger .get_account(&escrow_for(agreement)) .await? .is_closed() ); } Ok(()) } async fn report( ledger: &Ledger, money: &Amount, asset: AssetId, accounts: &[(&str, AccountId)], ) -> Result<(), Box> { let mut line = String::new(); for (label, account) in accounts { let balance = ledger.balance(account, &asset).await?; line.push_str(&format!("{label} {} ", money.format(balance))); } println!("{}", line.trim_end()); Ok(()) } async fn connect() -> Result> { kuatia_storage_sql::install_drivers()?; let pool = sqlx::any::AnyPoolOptions::new() .max_connections(1) .connect("sqlite::memory:") .await?; let store = SqlStore::new(pool); store.migrate().await?; let ledger = Ledger::new(store); Ok(ledger) }