Files
eventbook-exchange/crates/exchange/src/ledger.rs
T

65 lines
2.4 KiB
Rust

use anyhow::{ensure, Result};
use rusqlite::{params, Connection, Transaction};
use serde_json::{json, Value};
pub(crate) fn cash(tx: &Transaction, account: &str, delta: i64) -> Result<()> {
ensure!(
tx.execute(
"UPDATE accounts SET cash=cash+? WHERE id=? AND cash+?>=0",
params![delta, account, delta]
)? == 1,
"unknown account or insufficient cash"
);
Ok(())
}
// Keep the legacy whole-cent column and the sub-cent remainder canonical.
pub(crate) fn cash_micros(tx: &Transaction, account: &str, delta: i64) -> Result<()> {
if delta % 10000 == 0 {
return cash(tx, account, delta / 10000);
}
let old: i64 = tx.query_row(
"SELECT COALESCE((SELECT micros FROM cash_remainders WHERE account=?),0)",
[account],
|r| r.get(0),
)?;
let remainder = old + delta.rem_euclid(10000);
cash(tx, account, delta.div_euclid(10000) + remainder / 10000)?;
tx.execute("INSERT INTO cash_remainders(account,micros) VALUES(?,?) ON CONFLICT(account) DO UPDATE SET micros=excluded.micros",
params![account, remainder % 10000])?;
Ok(())
}
pub(crate) fn balance(db: &Connection, account: &str) -> Result<Value> {
crate::validation::identifier(account)?;
let (cash, remainder, reserved): (i64, i64, i64) = db.query_row(
"SELECT a.cash,COALESCE(r.micros,0),
(SELECT COALESCE(SUM(price*remaining),0) FROM orders
WHERE account=a.id AND side='buy' AND status='live')
FROM accounts a LEFT JOIN cash_remainders r ON r.account=a.id WHERE a.id=?",
[account],
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
)?;
let available = i128::from(cash) * 10000 + i128::from(remainder);
let reserved = i128::from(reserved);
Ok(
json!({"account":account, "available_micros":available, "reserved_micros":reserved,
"total_cash_micros":available+reserved}),
)
}
pub(crate) fn position(
tx: &Transaction,
account: &str,
market: &str,
outcome: &str,
delta: i64,
) -> Result<()> {
tx.execute(
"INSERT OR IGNORE INTO positions VALUES(?,?,?,0)",
params![account, market, outcome],
)?;
ensure!(tx.execute("UPDATE positions SET quantity=quantity+? WHERE account=? AND market=? AND outcome=? AND quantity+?>=0",params![delta,account,market,outcome,delta])?==1,"insufficient position");
Ok(())
}