exchange.md 2.6 KB

Currency exchange

An exchange lets users deposit fiat, trade between currencies, and withdraw.

Setup:

use kuatia::prelude::*;

// Assets, named by code: each call registers on first sight and hands back the
// handle. An amount cannot be built without its asset, and a two-decimal
// string has nowhere else to learn its scale from.
let usd = ledger.asset("USD", "$", 2).await?;
let eur = ledger.asset("EUR", "\u{20ac}", 2).await?;

// Books: separate deposit/withdrawal flows from trading
let deposits_book = BookBuilder::new("deposits")
    .allow_asset(&usd)
    .allow_asset(&eur)
    .allow_flags(AccountFlags::USER_0 | AccountFlags::USER_1) // wallets + bank
    .build();

let trading_book = BookBuilder::new("trading")
    .allow_asset(&usd)
    .allow_asset(&eur)
    .allow_flags(AccountFlags::USER_0) // only user wallets
    .allow_account(exchange_pool)       // + the exchange pool
    .build();

ledger.create_book(deposits_book).await?;
ledger.create_book(trading_book).await?;

// Accounts — `Account::new` sets version 1, no flags, and the default book;
// set the other fields explicitly where the common case is not enough.
// Boundary account: overdraft allowed by default, so it can hold the offset.
let mut bank = Account::new(AccountId::default());
bank.flags = AccountFlags::USER_1; // bank flag
bank.book = deposits_book.id;

// Wallet: forbids overdraft, so its balance may not go negative.
let mut alice = Account::debit_must_not_exceed_credit(AccountId::default());
alice.flags |= AccountFlags::USER_0; // wallet flag
alice.book = deposits_book.id;

let mut exchange_pool = Account::new(AccountId::default());
exchange_pool.book = trading_book.id;

Deposit $100.00 into Alice's wallet:

let deposit = TransferBuilder::new()
    .book(deposits_book.id)
    .deposit(alice.id, ("100.00", &usd), bank.id)
    .build()?;
ledger.commit(deposit).await?;
// Alice: +$100.00
// Bank: -$100.00 (offset: value entered the ledger boundary)

Alice trades $50.00 for EUR at 1:0.92:

let trade = TransferBuilder::new()
    .book(trading_book.id)
    .pay(alice.id, exchange_pool, ("50.00", &usd))
    .pay(exchange_pool, alice.id, ("46.00", &eur))
    .build()?;
ledger.commit(trade).await?;
// Alice: $50.00 + 46.00 EUR
// Exchange pool: $50.00 - 46.00 EUR

Withdraw EUR to Alice's bank:

let withdrawal = TransferBuilder::new()
    .book(deposits_book.id)
    .withdraw(alice.id, ("46.00", &eur), bank.id)
    .build()?;
ledger.commit(withdrawal).await?;
// Alice: $50.00, 0.00 EUR
// Bank: -$100.00 + 46.00 EUR

Conservation holds at every step. The exchange pool absorbs the spread.