164 lines
6.5 KiB
Rust
164 lines
6.5 KiB
Rust
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,
|
|
event: &str,
|
|
markets: &[String],
|
|
) -> Result<Value> {
|
|
identifier(group)?;
|
|
identifier(event)?;
|
|
ensure!(
|
|
(2..=256).contains(&markets.len()),
|
|
"expected 2 to 256 mutually exclusive markets"
|
|
);
|
|
tx.execute("INSERT INTO neg_risk_groups(id) VALUES(?)", [group])?;
|
|
for (ordinal, market) in markets.iter().enumerate() {
|
|
let added = tx.execute(
|
|
"INSERT INTO neg_risk_members(market,group_id,ordinal)
|
|
SELECT m.id,?1,?2 FROM markets m JOIN listed_markets l ON l.market=m.id
|
|
WHERE m.id=?3 AND l.event=?4 AND m.phase='preopen'
|
|
AND NOT EXISTS (SELECT 1 FROM orders WHERE market=m.id)
|
|
AND NOT EXISTS (SELECT 1 FROM positions WHERE market=m.id)
|
|
AND NOT EXISTS (SELECT 1 FROM optimistic_markets WHERE market=m.id)
|
|
AND NOT EXISTS (SELECT 1 FROM twap_markets WHERE market=m.id)",
|
|
params![group, ordinal as i64, market, event],
|
|
)?;
|
|
ensure!(
|
|
added == 1,
|
|
"members must be unused preopen markets of this event with manual resolution"
|
|
);
|
|
}
|
|
Ok(json!({"group":group,"markets":markets}))
|
|
}
|
|
|
|
pub(crate) fn convert(
|
|
tx: &Transaction,
|
|
request: &str,
|
|
group: &str,
|
|
account: &str,
|
|
no_markets: &[String],
|
|
qty: Option<i64>,
|
|
qty_micros: Option<i64>,
|
|
) -> Result<Value> {
|
|
identifier(group)?;
|
|
identifier(account)?;
|
|
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(),
|
|
"provide distinct NO markets"
|
|
);
|
|
let mut stmt = tx.prepare(
|
|
"SELECT n.market,m.phase FROM neg_risk_members n JOIN markets m ON m.id=n.market
|
|
WHERE n.group_id=? ORDER BY n.ordinal",
|
|
)?;
|
|
let members = stmt
|
|
.query_map([group], |r| {
|
|
Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?))
|
|
})?
|
|
.collect::<rusqlite::Result<Vec<_>>>()?;
|
|
ensure!(
|
|
selected
|
|
.iter()
|
|
.all(|id| members.iter().any(|(market, _)| market.as_str() == *id)),
|
|
"NO market outside group"
|
|
);
|
|
ensure!(
|
|
members.iter().all(|(_, phase)| phase != "resolved"),
|
|
"group already resolving"
|
|
);
|
|
let mut yes_markets = Vec::new();
|
|
for (market, _) in &members {
|
|
if selected.contains(market.as_str()) {
|
|
inventory::position(tx, account, market, "NO", -units)?;
|
|
inventory::backing(tx, market, -units)?;
|
|
} else {
|
|
inventory::position(tx, account, market, "YES", units)?;
|
|
yes_markets.push(market);
|
|
}
|
|
}
|
|
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),
|
|
)?;
|
|
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.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 {
|
|
return Ok(());
|
|
};
|
|
let valid: bool = tx.query_row(
|
|
"SELECT NOT EXISTS (SELECT 1 FROM augmented_outcomes a
|
|
LEFT JOIN augmented_results r ON r.group_id=a.group_id
|
|
WHERE a.market=?1 AND (r.winner IS NULL OR ?2<>CASE WHEN r.winner=?1 THEN 'YES' ELSE 'NO' END))",
|
|
params![market,outcome], |r|r.get(0))?;
|
|
ensure!(valid, "resolve the observed winner with finalize_augmented");
|
|
match outcome {
|
|
"YES" => {
|
|
ensure!(winner.is_none(), "group already has a winner");
|
|
inventory::backing(tx, market, reserve)?;
|
|
tx.execute(
|
|
"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",
|
|
params![market, group],
|
|
)?;
|
|
}
|
|
"NO" if winner.is_none() => {
|
|
let another: bool = tx.query_row(
|
|
"SELECT EXISTS(SELECT 1 FROM neg_risk_members n JOIN markets m ON m.id=n.market
|
|
WHERE n.group_id=?1 AND n.market<>?2 AND m.phase<>'resolved')",
|
|
params![group, market],
|
|
|r| r.get(0),
|
|
)?;
|
|
ensure!(another, "the last unresolved member must win");
|
|
}
|
|
"NO" => {}
|
|
_ => anyhow::bail!("a negative-risk member requires a binary outcome"),
|
|
}
|
|
Ok(())
|
|
}
|