Expose negative-risk membership and convert fractional outcome balances
This commit is contained in:
@@ -65,7 +65,8 @@ pub(crate) enum Command {
|
||||
group: String,
|
||||
account: String,
|
||||
no_markets: Vec<String>,
|
||||
qty: i64,
|
||||
qty: Option<i64>,
|
||||
qty_micros: Option<i64>,
|
||||
},
|
||||
Split {
|
||||
market: String,
|
||||
|
||||
@@ -72,15 +72,20 @@ pub(crate) fn movement(
|
||||
tx: &Transaction,
|
||||
request: &str,
|
||||
account: &str,
|
||||
market: &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,shares,cash_delta,at_ms)
|
||||
VALUES(?,?,?,?,?,?,CAST(unixepoch('subsec')*1000 AS INTEGER))",
|
||||
params![request, account, kind, market, shares / UNIT, cash / 10000],
|
||||
"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(?,?,?,?)",
|
||||
@@ -89,6 +94,19 @@ pub(crate) fn movement(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn quantity_units(qty: Option<i64>, qty_micros: Option<i64>) -> Result<i64> {
|
||||
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,
|
||||
@@ -108,16 +126,7 @@ pub(crate) fn pairs(
|
||||
&["preopen", "continuous", "closed"][..]
|
||||
},
|
||||
)?;
|
||||
let units = 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"
|
||||
),
|
||||
};
|
||||
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"] {
|
||||
|
||||
@@ -245,6 +245,7 @@ impl Exchange {
|
||||
"fills",
|
||||
"paired_fills",
|
||||
"neg_risk_groups",
|
||||
"neg_risk_reserve_remainders",
|
||||
"augmented_results",
|
||||
] {
|
||||
let mut stmt = tx.prepare(&format!("SELECT * FROM {table} ORDER BY rowid"))?;
|
||||
|
||||
@@ -147,7 +147,16 @@ pub(crate) fn apply(
|
||||
account,
|
||||
no_markets,
|
||||
qty,
|
||||
} => crate::neg_risk::convert(tx, &group, &account, &no_markets, qty),
|
||||
qty_micros,
|
||||
} => crate::neg_risk::convert(
|
||||
tx,
|
||||
request_id,
|
||||
&group,
|
||||
&account,
|
||||
&no_markets,
|
||||
qty,
|
||||
qty_micros,
|
||||
),
|
||||
Command::Split {
|
||||
market,
|
||||
account,
|
||||
|
||||
@@ -1,12 +1,20 @@
|
||||
use crate::{
|
||||
ledger,
|
||||
validation::{amount, identifier},
|
||||
};
|
||||
use crate::{assets, inventory, ledger, validation::identifier, Exchange, MarketDataError};
|
||||
use anyhow::{ensure, Result};
|
||||
use rusqlite::{params, OptionalExtension, Transaction};
|
||||
use serde_json::{json, Value};
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
impl Exchange {
|
||||
pub fn token_neg_risk(&self, token: &str) -> Result<Option<bool>, MarketDataError> {
|
||||
let (_, market) = assets::parse_id(token)
|
||||
.map_err(|_| MarketDataError::Invalid("Invalid token id".into()))?;
|
||||
let mut stmt=self.db.prepare_cached(
|
||||
"SELECT EXISTS(SELECT 1 FROM neg_risk_members WHERE market=m.id) FROM markets m WHERE m.id=?1"
|
||||
)?;
|
||||
Ok(stmt.query_row([market], |row| row.get(0)).optional()?)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn define(
|
||||
tx: &Transaction,
|
||||
group: &str,
|
||||
@@ -41,14 +49,16 @@ pub(crate) fn define(
|
||||
|
||||
pub(crate) fn convert(
|
||||
tx: &Transaction,
|
||||
request: &str,
|
||||
group: &str,
|
||||
account: &str,
|
||||
no_markets: &[String],
|
||||
qty: i64,
|
||||
qty: Option<i64>,
|
||||
qty_micros: Option<i64>,
|
||||
) -> Result<Value> {
|
||||
identifier(group)?;
|
||||
identifier(account)?;
|
||||
amount(qty)?;
|
||||
let units = inventory::quantity_units(qty, qty_micros)?;
|
||||
let selected: BTreeSet<&str> = no_markets.iter().map(String::as_str).collect();
|
||||
ensure!(
|
||||
!selected.is_empty() && selected.len() == no_markets.len(),
|
||||
@@ -73,39 +83,46 @@ pub(crate) fn convert(
|
||||
members.iter().all(|(_, phase)| phase != "resolved"),
|
||||
"group already resolving"
|
||||
);
|
||||
let cents = qty * 100;
|
||||
let mut yes_markets = Vec::new();
|
||||
for (market, _) in &members {
|
||||
if selected.contains(market.as_str()) {
|
||||
ledger::position(tx, account, market, "NO", -qty)?;
|
||||
ensure!(
|
||||
tx.execute(
|
||||
"UPDATE markets SET collateral=collateral-?1 WHERE id=?2 AND collateral>=?1",
|
||||
params![cents, market]
|
||||
)? == 1,
|
||||
"insufficient market backing"
|
||||
);
|
||||
inventory::position(tx, account, market, "NO", -units)?;
|
||||
inventory::backing(tx, market, -units)?;
|
||||
} else {
|
||||
ledger::position(tx, account, market, "YES", qty)?;
|
||||
inventory::position(tx, account, market, "YES", units)?;
|
||||
yes_markets.push(market);
|
||||
}
|
||||
}
|
||||
let released = (selected.len() as i64 - 1) * cents;
|
||||
tx.execute(
|
||||
"UPDATE neg_risk_groups SET reserve_cents=reserve_cents+?1 WHERE id=?2",
|
||||
params![cents, group],
|
||||
let released = (selected.len() as i64 - 1) * units;
|
||||
let reserve: i64 = tx.query_row(
|
||||
"SELECT micros FROM neg_risk_reserves WHERE id=?",
|
||||
[group],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
ledger::cash(tx, account, released)?;
|
||||
Ok(
|
||||
json!({"group":group,"qty":qty,"no_markets":no_markets,"yes_markets":yes_markets,"released_cents":released}),
|
||||
)
|
||||
let reserve = reserve
|
||||
.checked_add(units)
|
||||
.ok_or_else(|| anyhow::anyhow!("group reserve overflow"))?;
|
||||
tx.execute(
|
||||
"UPDATE neg_risk_groups SET reserve_cents=? WHERE id=?",
|
||||
params![reserve / 10000, group],
|
||||
)?;
|
||||
tx.execute("INSERT INTO neg_risk_reserve_remainders(group_id,micros) VALUES(?,?) ON CONFLICT(group_id) DO UPDATE SET micros=excluded.micros",params![group,reserve%10000])?;
|
||||
ledger::cash_micros(tx, account, released)?;
|
||||
let mut receipt = json!({"group":group,"qty":inventory::decimal(units.into(),inventory::UNIT),
|
||||
"no_markets":no_markets,"yes_markets":yes_markets,"released_cents":inventory::decimal(released.into(),10000)});
|
||||
if qty_micros.is_some() {
|
||||
inventory::movement(tx, request, account, group, "CONVERSION", units, released)?;
|
||||
receipt["qty_micros"] = json!(units);
|
||||
receipt["released_micros"] = json!(released);
|
||||
}
|
||||
Ok(receipt)
|
||||
}
|
||||
|
||||
// Run in the same transaction as the binary payout check. A failing verdict
|
||||
// rolls back the transfer as well as any optimistic-resolution state change.
|
||||
pub(crate) fn allocate_payout(tx: &Transaction, market: &str, outcome: &str) -> Result<()> {
|
||||
let group: Option<(String, Option<String>, i64)> = tx.query_row(
|
||||
"SELECT g.id,g.winner,g.reserve_cents FROM neg_risk_members n JOIN neg_risk_groups g ON g.id=n.group_id WHERE n.market=?",
|
||||
"SELECT g.id,g.winner,g.micros FROM neg_risk_members n JOIN neg_risk_reserves g ON g.id=n.group_id WHERE n.market=?",
|
||||
[market], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
|
||||
).optional()?;
|
||||
let Some((group, winner, reserve)) = group else {
|
||||
@@ -120,9 +137,10 @@ pub(crate) fn allocate_payout(tx: &Transaction, market: &str, outcome: &str) ->
|
||||
match outcome {
|
||||
"YES" => {
|
||||
ensure!(winner.is_none(), "group already has a winner");
|
||||
inventory::backing(tx, market, reserve)?;
|
||||
tx.execute(
|
||||
"UPDATE markets SET collateral=collateral+?1 WHERE id=?2",
|
||||
params![reserve, market],
|
||||
"DELETE FROM neg_risk_reserve_remainders WHERE group_id=?",
|
||||
[&group],
|
||||
)?;
|
||||
tx.execute(
|
||||
"UPDATE neg_risk_groups SET winner=?1,reserve_cents=0 WHERE id=?2",
|
||||
|
||||
@@ -196,6 +196,12 @@ CREATE TABLE IF NOT EXISTS neg_risk_groups (
|
||||
id TEXT PRIMARY KEY, reserve_cents INTEGER NOT NULL DEFAULT 0 CHECK(reserve_cents>=0),
|
||||
winner TEXT REFERENCES markets
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS neg_risk_reserve_remainders (
|
||||
group_id TEXT PRIMARY KEY REFERENCES neg_risk_groups(id), micros INTEGER NOT NULL CHECK(micros BETWEEN 0 AND 9999)
|
||||
);
|
||||
CREATE VIEW IF NOT EXISTS neg_risk_reserves AS
|
||||
SELECT g.id,g.winner,g.reserve_cents*10000+COALESCE(r.micros,0) AS micros
|
||||
FROM neg_risk_groups g LEFT JOIN neg_risk_reserve_remainders r ON r.group_id=g.id;
|
||||
CREATE TABLE IF NOT EXISTS neg_risk_members (
|
||||
market TEXT PRIMARY KEY REFERENCES markets, group_id TEXT NOT NULL REFERENCES neg_risk_groups,
|
||||
ordinal INTEGER NOT NULL, UNIQUE(group_id,ordinal)
|
||||
|
||||
Reference in New Issue
Block a user