//! 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 = AssetId::new(1); let money = Amount::new(2); 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, usd, money.parse("30.00")?, 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, usd, money.parse("70.00")?) .build(), ) .await?; println!( " commit succeeded, balance {} USD", money.format(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, usd, money.parse("70.00")?) .build(), ) .await; match refused { Err(LedgerError::Selection(shortfall)) => println!( " commit refused: available {} USD, requested {} USD", money.format(shortfall.available), money.format(shortfall.requested), ), Err(other) => println!(" commit refused for another reason: {other}"), Ok(_) => println!(" commit succeeded, which it should not have"), } println!( " balance unchanged at {} USD", money.format(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: AssetId, ) -> Result<(), Box> { let money = Amount::new(2); for (posting, state) in ledger.postings_with_state(&account).await? { if posting.asset == asset { println!(" {:>10} USD {:?}", money.format(posting.value), 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) }