create_accounts.rs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. //! Connect to a SQLite-backed ledger and create accounts.
  2. //!
  3. //! Run with:
  4. //! ```sh
  5. //! cargo run -p kuatia --example create_accounts
  6. //! ```
  7. use std::collections::BTreeMap;
  8. use std::sync::Arc;
  9. use kuatia::ledger::Ledger;
  10. use kuatia_core::*;
  11. use kuatia_storage_sql::SqlStore;
  12. #[tokio::main]
  13. async fn main() -> Result<(), Box<dyn std::error::Error>> {
  14. let ledger = connect().await?;
  15. // The common case is one line: a version-1 account with the given policy.
  16. ledger
  17. .create_account(Account::new(AccountId::new(1), AccountPolicy::NoOverdraft))
  18. .await?;
  19. ledger
  20. .create_account(Account::new(AccountId::new(2), AccountPolicy::NoOverdraft))
  21. .await?;
  22. // A system account (fees, settlement, market-making) — no balance floor.
  23. ledger
  24. .create_account(Account::new(AccountId::new(50), AccountPolicy::SystemAccount))
  25. .await?;
  26. // The same thing spelled out, so you can see every field of an `Account`.
  27. // This boundary account is where value enters/leaves the ledger.
  28. let external = Account {
  29. id: AccountId::new(99),
  30. version: 1, // accounts always start at version 1
  31. policy: AccountPolicy::ExternalAccount, // boundary for deposits/withdrawals
  32. flags: AccountFlags::empty(), // not frozen, not closed
  33. book: DEFAULT_BOOK, // the implicit default book
  34. user_data: UserData::default(), // fixed-width correlation slots
  35. metadata: BTreeMap::new(), // free-form key/value metadata
  36. };
  37. ledger.create_account(external).await?;
  38. // Read them back (latest version of each).
  39. println!("accounts:");
  40. let mut accounts = ledger.list_accounts().await?;
  41. accounts.sort_by_key(|a| a.id.0);
  42. for a in &accounts {
  43. println!(" {:?} policy={:?} v{}", a.id, a.policy, a.version);
  44. }
  45. Ok(())
  46. }
  47. /// Open a fresh in-memory SQLite database, run migrations, and wrap it in a
  48. /// `Ledger`. Point the connection string at a file (e.g.
  49. /// `"sqlite://ledger.db?mode=rwc"`) or a Postgres URL for a persistent ledger.
  50. async fn connect() -> Result<Arc<Ledger>, Box<dyn std::error::Error>> {
  51. sqlx::any::install_default_drivers();
  52. let pool = sqlx::any::AnyPoolOptions::new()
  53. .max_connections(1)
  54. .connect("sqlite::memory:")
  55. .await?;
  56. let store = SqlStore::new(pool);
  57. store.migrate().await?;
  58. Ok(Arc::new(Ledger::new(store)))
  59. }