259 lines
10 KiB
Rust
259 lines
10 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()?)
|
|
}
|
|
}
|
|
|
|
#[derive(serde::Deserialize, serde::Serialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub(crate) struct ConversionFee {
|
|
bps: i64,
|
|
vault: String,
|
|
}
|
|
|
|
pub(crate) fn define(
|
|
tx: &Transaction,
|
|
group: &str,
|
|
event: &str,
|
|
markets: &[String],
|
|
fee: Option<ConversionFee>,
|
|
) -> 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"
|
|
);
|
|
}
|
|
let mut receipt = json!({"group":group,"markets":markets});
|
|
if let Some(fee) = fee {
|
|
identifier(&fee.vault)?;
|
|
ensure!(
|
|
(0..=10000).contains(&fee.bps),
|
|
"conversion fee must be 0 to 10000 bps"
|
|
);
|
|
tx.execute(
|
|
"INSERT INTO accounts(id,cash) VALUES(?,0) ON CONFLICT(id) DO NOTHING",
|
|
[&fee.vault],
|
|
)?;
|
|
tx.execute(
|
|
"INSERT INTO neg_risk_conversion_fees(group_id,bps,vault) VALUES(?,?,?)",
|
|
params![group, fee.bps, fee.vault],
|
|
)?;
|
|
receipt["conversion_fee"] = json!(fee);
|
|
}
|
|
Ok(receipt)
|
|
}
|
|
|
|
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 = match (qty, qty_micros) {
|
|
(Some(0), None) | (None, Some(0)) => 0,
|
|
_ => 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 market FROM neg_risk_members WHERE group_id=? ORDER BY ordinal")?;
|
|
let members = stmt
|
|
.query_map([group], |r| r.get::<_, String>(0))?
|
|
.collect::<rusqlite::Result<Vec<_>>>()?;
|
|
ensure!(
|
|
selected
|
|
.iter()
|
|
.all(|id| members.iter().any(|market| market.as_str() == *id)),
|
|
"NO market outside group"
|
|
);
|
|
if units == 0 {
|
|
return Ok(
|
|
json!({"group":group,"no_markets":no_markets,"yes_markets":[],
|
|
"qty":0,"qty_micros":0,"released_cents":0,"released_micros":0,"noop":true}),
|
|
);
|
|
}
|
|
let (winner, reserve): (Option<String>, i64) = tx.query_row(
|
|
"SELECT winner,micros FROM neg_risk_reserves WHERE id=?",
|
|
[group],
|
|
|r| Ok((r.get(0)?, r.get(1)?)),
|
|
)?;
|
|
let policy = tx
|
|
.query_row(
|
|
"SELECT bps,vault FROM neg_risk_conversion_fees WHERE group_id=?",
|
|
[group],
|
|
|row| {
|
|
Ok(ConversionFee {
|
|
bps: row.get(0)?,
|
|
vault: row.get(1)?,
|
|
})
|
|
},
|
|
)
|
|
.optional()?;
|
|
// The adapter rounds each output before multiplying by the number of cash legs.
|
|
let bps = policy.as_ref().map_or(0, |fee| fee.bps);
|
|
let fee_units = i64::try_from(i128::from(units) * i128::from(bps) / 10_000)?;
|
|
let net_units = units - fee_units;
|
|
let mut yes_markets = Vec::new();
|
|
for market in &members {
|
|
let is_winner = winner.as_deref() == Some(market.as_str());
|
|
if selected.contains(market.as_str()) {
|
|
inventory::position(tx, account, market, "NO", -units)?;
|
|
// A determined winner's NO has no claim on that market's backing.
|
|
if !is_winner {
|
|
inventory::backing(tx, market, -units)?;
|
|
}
|
|
} else {
|
|
if is_winner {
|
|
inventory::backing(tx, market, units)?;
|
|
}
|
|
if net_units > 0 {
|
|
inventory::position(tx, account, market, "YES", net_units)?;
|
|
}
|
|
if let Some(fee) = policy.as_ref().filter(|_| fee_units > 0) {
|
|
inventory::position(tx, &fee.vault, market, "YES", fee_units)?;
|
|
}
|
|
yes_markets.push(market);
|
|
}
|
|
}
|
|
let cash_legs = selected.len() as i64 - 1;
|
|
let released = cash_legs * net_units;
|
|
let cash_fee = cash_legs * fee_units;
|
|
if winner.is_none() {
|
|
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 let Some(fee) = &policy {
|
|
if cash_fee > 0 {
|
|
ledger::cash_micros(tx, &fee.vault, cash_fee)?;
|
|
}
|
|
receipt["conversion_fee"] = json!({"bps":bps,"vault":fee.vault,
|
|
"cash_micros":cash_fee,"yes_micros_per_market":fee_units});
|
|
}
|
|
if qty_micros.is_some() || policy.is_some() {
|
|
inventory::movement(tx, request, account, group, "CONVERSION", units, released)?;
|
|
receipt["qty_micros"] = json!(units);
|
|
receipt["released_micros"] = json!(released);
|
|
}
|
|
Ok(receipt)
|
|
}
|
|
|
|
/// Burn the YES/NO amounts transferred by a negative-risk adapter caller.
|
|
/// The caller settles the returned (burned shares, collateral payout) in this transaction.
|
|
pub(crate) fn burn_for_redemption(
|
|
tx: &Transaction,
|
|
market: &str,
|
|
account: &str,
|
|
amounts: [i64; 2],
|
|
) -> Result<(i64, i64)> {
|
|
let winner: Option<String> = tx.query_row(
|
|
"SELECT m.winner FROM neg_risk_members n JOIN markets m ON m.id=n.market WHERE n.market=? AND m.phase='resolved'",
|
|
[market], |row| row.get(0),
|
|
).optional()?;
|
|
let [yes, no] = amounts;
|
|
let paid = match winner.as_deref() {
|
|
Some("YES") => yes,
|
|
Some("NO") => no,
|
|
_ => anyhow::bail!("explicit redemption amounts require a resolved negative-risk market"),
|
|
};
|
|
ensure!(yes >= 0 && no >= 0, "negative redemption amount");
|
|
let burned = yes
|
|
.checked_add(no)
|
|
.ok_or_else(|| anyhow::anyhow!("redemption share total overflow"))?;
|
|
for (outcome, units) in [("YES", yes), ("NO", no)] {
|
|
if units > 0 {
|
|
inventory::position(tx, account, market, outcome, -units)?;
|
|
}
|
|
}
|
|
Ok((burned, paid))
|
|
}
|
|
|
|
// 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(())
|
|
}
|