use crate::{ ledger, validation::{identifier, phase}, }; use anyhow::{ensure, Result}; use rusqlite::{params, Transaction}; use serde_json::{json, Number, Value}; pub(crate) const UNIT: i64 = 1_000_000; // Render a fixed-point amount as a JSON number without passing through f64. // All callers use a power of ten as the scale. pub(crate) fn decimal(value: i128, scale: i64) -> Number { let scale = i128::from(scale); if value % scale == 0 { return Number::from_i128(value / scale).expect("integer JSON number"); } let sign = if value < 0 { "-" } else { "" }; let value = value.unsigned_abs(); let width = scale.ilog10() as usize; let scale = scale as u128; format!("{sign}{}.{:0width$}", value / scale, value % scale) .trim_end_matches('0') .parse() .expect("fixed-point JSON number") } pub(crate) fn backing(tx: &Transaction, market: &str, delta: i64) -> Result<()> { let old: i64 = tx.query_row( "SELECT micros FROM market_backing WHERE market=?", [market], |r| r.get(0), )?; let new = old .checked_add(delta) .filter(|v| *v >= 0) .ok_or_else(|| anyhow::anyhow!("insufficient collateral or balance overflow"))?; tx.execute( "UPDATE markets SET collateral=? WHERE id=?", params![new / 10000, market], )?; tx.execute("INSERT INTO collateral_remainders VALUES(?,?) ON CONFLICT(market) DO UPDATE SET micros=excluded.micros",params![market,new%10000])?; Ok(()) } pub(crate) fn position( tx: &Transaction, account: &str, market: &str, outcome: &str, delta: i64, ) -> Result<()> { if delta % UNIT == 0 { return ledger::position(tx, account, market, outcome, delta / UNIT); } let old:i64=tx.query_row("SELECT COALESCE((SELECT micros FROM position_remainders WHERE account=? AND market=? AND outcome=?),0)", params![account,market,outcome],|r|r.get(0))?; let rest = old + delta.rem_euclid(UNIT); ledger::position( tx, account, market, outcome, delta.div_euclid(UNIT) + rest / UNIT, )?; tx.execute("INSERT INTO position_remainders VALUES(?,?,?,?) ON CONFLICT(account,market,outcome) DO UPDATE SET micros=excluded.micros", params![account,market,outcome,rest%UNIT])?; Ok(()) } pub(crate) fn movement( tx: &Transaction, request: &str, account: &str, target: &str, kind: &str, shares: i64, cash: i64, ) -> Result<()> { let (market, group_id) = if kind == "CONVERSION" { (None, Some(target)) } else { (Some(target), None) }; tx.execute( "INSERT INTO wallet_movements(request_id,account,kind,market,group_id,shares,cash_delta,at_ms) VALUES(?,?,?,?,?,?,?,CAST(unixepoch('subsec')*1000 AS INTEGER))", params![request, account, kind, market, group_id, shares / UNIT, cash / 10000], )?; tx.execute( "INSERT INTO precise_movements VALUES(?,?,?,?)", params![request, account, shares, cash], )?; Ok(()) } pub(crate) fn quantity_units(qty: Option, qty_micros: Option) -> Result { Ok(match (qty, qty_micros) { (Some(q), None) => { crate::validation::amount(q)?; q * UNIT } (None, Some(u)) if (1..=1_000_000_000 * UNIT).contains(&u) => u, _ => anyhow::bail!( "provide exactly one positive qty or qty_micros within the quantity limit" ), }) } pub(crate) fn pairs( tx: &Transaction, request: &str, account: &str, market: &str, qty: Option, qty_micros: Option, split: bool, ) -> Result { identifier(account)?; phase( tx, market, if split { &["preopen", "continuous"][..] } else { &["preopen", "continuous", "closed"][..] }, )?; let units = quantity_units(qty, qty_micros)?; let delta = if split { units } else { -units }; ledger::cash_micros(tx, account, -delta)?; for outcome in ["YES", "NO"] { position(tx, account, market, outcome, delta)?; } backing(tx, market, delta)?; let mut result = json!({"pairs":decimal(i128::from(units),UNIT)}); if !split { result["released_cents"] = json!(decimal(i128::from(units), 10000)); } if qty_micros.is_some() { movement( tx, request, account, market, if split { "SPLIT" } else { "MERGE" }, units, -delta, )?; result["pairs_micros"] = json!(units); } Ok(result) }