//! Overdraft: a shortfall becomes a negative posting on an account that permits //! it, and `InsufficientFunds` on an account that does not. //! //! Run with: //! ```sh //! cargo run -p kuatia --example overdraft //! ``` use kuatia::error::LedgerError; use kuatia::ledger::Ledger; use kuatia_core::*; use kuatia_storage_sql::SqlStore; #[tokio::main] async fn main() -> Result<(), Box> { let ledger = connect().await?; let treasury = AccountId::new(1); let wallet = AccountId::new(2); let merchant = AccountId::new(3); let external = AccountId::new(99); let usd = ledger.asset("USD", "$", 2).await?; ledger.create_account(Account::new(treasury)).await?; ledger .create_account(Account::debit_must_not_exceed_credit(wallet)) .await?; ledger .create_account(Account::debit_must_not_exceed_credit(merchant)) .await?; ledger.create_account(Account::new(external)).await?; for account in [treasury, wallet] { ledger .commit( TransferBuilder::new() .deposit(account, ("30.00", &usd), external) .build()?, ) .await?; } println!("Both accounts hold 30.00 USD. Both now try to pay 70.00 USD.\n"); println!("treasury permits overdraft (Account::new):"); print_postings(&ledger, treasury, &usd).await?; ledger .commit( TransferBuilder::new() .pay(treasury, merchant, ("70.00", &usd)) .build()?, ) .await?; println!( " commit succeeded, balance {}", ledger.balance(&treasury, &usd).await? ); println!(" the 30.00 posting was consumed and a 40.00 shortfall posting created:"); print_postings(&ledger, treasury, &usd).await?; println!("\nwallet forbids it (Account::debit_must_not_exceed_credit):"); print_postings(&ledger, wallet, &usd).await?; let refused = ledger .commit( TransferBuilder::new() .pay(wallet, merchant, ("70.00", &usd)) .build()?, ) .await; match refused { // The shortfall names its own asset, so this reports a quantity without // the example having to remember which asset it asked about. Err(LedgerError::Selection(shortfall)) => println!( " commit refused: available {}, requested {}", shortfall.available, shortfall.requested, ), Err(other) => println!(" commit refused for another reason: {other}"), Ok(_) => println!(" commit succeeded, which it should not have"), } println!( " balance unchanged at {}", ledger.balance(&wallet, &usd).await? ); Ok(()) } /// Prints each posting with its lifecycle state, so a consumed positive and a /// created negative are visible side by side rather than inferred from balances. async fn print_postings( ledger: &Ledger, account: AccountId, asset: &std::sync::Arc, ) -> Result<(), Box> { for (posting, state) in ledger.postings_with_state(&account).await? { if posting.amount.asset_id() == asset.id { println!(" {:>12} {:?}", posting.amount.to_string(), state); } } 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) }