509 lines
18 KiB
Rust
509 lines
18 KiB
Rust
use crate::resident::Books;
|
|
use crate::{
|
|
book,
|
|
command::Command,
|
|
ledger, resolution,
|
|
validation::{amount, identifier, phase},
|
|
};
|
|
use anyhow::{ensure, Result};
|
|
use rusqlite::{params, OptionalExtension, Transaction};
|
|
use serde_json::{json, Value};
|
|
|
|
pub(crate) fn apply(
|
|
tx: &Transaction,
|
|
books: &Books,
|
|
command: Command,
|
|
request_id: &str,
|
|
) -> Result<Value> {
|
|
match command {
|
|
Command::Fund {
|
|
account,
|
|
cents,
|
|
micros,
|
|
} => {
|
|
identifier(&account)?;
|
|
let value = match (cents, micros) {
|
|
(Some(c), None) => {
|
|
amount(c)?;
|
|
c * 10000
|
|
}
|
|
(None, Some(m)) if (1..=10_000_000_000_000).contains(&m) => m,
|
|
_ => anyhow::bail!("fund requires exactly one valid amount in cents or micros"),
|
|
};
|
|
tx.execute(
|
|
"INSERT INTO accounts VALUES(?,?)",
|
|
params![account, value / 10000],
|
|
)?;
|
|
if value % 10000 != 0 {
|
|
ledger::cash_micros(tx, &account, value % 10000)?;
|
|
}
|
|
let mut receipt = json!({"funded":value/10000});
|
|
if micros.is_some() {
|
|
receipt["funded_micros"] = json!(value);
|
|
}
|
|
Ok(receipt)
|
|
}
|
|
Command::SetMarketVisibility {
|
|
market,
|
|
active,
|
|
archived,
|
|
} => {
|
|
identifier(&market)?;
|
|
tx.execute(
|
|
"INSERT INTO market_visibility(market,active,archived) VALUES(?,?,?)
|
|
ON CONFLICT(market) DO UPDATE SET active=excluded.active,archived=excluded.archived",
|
|
params![market,active,archived],
|
|
)?;
|
|
Ok(json!({"market":market,"active":active,"archived":archived}))
|
|
}
|
|
Command::TickSizeChange(change) => change.apply(tx, request_id),
|
|
Command::Event(event) => event.save(tx),
|
|
Command::RescheduleSports {
|
|
event,
|
|
previous_ms,
|
|
scheduled_at_ms,
|
|
} => crate::kickoff::reschedule(tx, &event, previous_ms, scheduled_at_ms),
|
|
Command::List {
|
|
market,
|
|
slug,
|
|
question,
|
|
rules,
|
|
listing,
|
|
resolution,
|
|
taker_fee_rate_ppm,
|
|
base_fees,
|
|
min_order_size,
|
|
tick_size,
|
|
} => {
|
|
identifier(&market)?;
|
|
ensure!(!rules.trim().is_empty(), "rules required");
|
|
tx.execute(
|
|
"INSERT INTO markets(id,rules,phase) VALUES(?,?,'preopen')",
|
|
params![market, rules],
|
|
)?;
|
|
if let Some(tick) = tick_size {
|
|
crate::tick_size::TickSize::configure(tx, &market, &tick)?;
|
|
}
|
|
if let Some(size) = min_order_size {
|
|
crate::minimum_size::MinimumSize::configure(tx, &market, &size)?;
|
|
}
|
|
if let Some(rate) = taker_fee_rate_ppm {
|
|
crate::fees::configure(tx, &market, rate)?;
|
|
}
|
|
if let Some(base) = base_fees {
|
|
base.save(tx, &market)?;
|
|
}
|
|
if let Some(policy) = resolution {
|
|
policy.save(tx, &market)?;
|
|
}
|
|
if let Some(question) = question.as_deref() {
|
|
ensure!(!question.trim().is_empty(), "market question is empty");
|
|
ensure!(
|
|
listing.is_none(),
|
|
"use listing.question on event-backed markets"
|
|
);
|
|
}
|
|
if let Some(listing) = listing {
|
|
listing.save(tx, &market)?;
|
|
}
|
|
let slug = slug.as_deref().unwrap_or(&market);
|
|
identifier(slug)?;
|
|
tx.execute(
|
|
"INSERT INTO market_directory_ids(market,slug,question) VALUES(?,?,?)",
|
|
params![market, slug, question],
|
|
)?;
|
|
Ok(json!({"phase":"preopen"}))
|
|
}
|
|
Command::DefineNegRisk {
|
|
group,
|
|
event,
|
|
markets,
|
|
augmented,
|
|
conversion_fee,
|
|
} => {
|
|
let result = crate::neg_risk::define(tx, &group, &event, &markets, conversion_fee)?;
|
|
if let Some(config) = augmented {
|
|
config.save(tx, &group, &markets)?;
|
|
}
|
|
Ok(result)
|
|
}
|
|
Command::PublishClarification {
|
|
market,
|
|
content,
|
|
clear_book,
|
|
} => crate::clarifications::publish(tx, &market, &content, clear_book),
|
|
Command::Clarify {
|
|
market,
|
|
name,
|
|
question,
|
|
evidence,
|
|
} => crate::augmented::clarify(tx, &market, &name, &question, &evidence),
|
|
Command::FinalizeAugmented {
|
|
group,
|
|
observed_name,
|
|
evidence,
|
|
} => crate::augmented::finalize(tx, &group, &observed_name, &evidence),
|
|
Command::Convert {
|
|
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,
|
|
qty,
|
|
qty_micros,
|
|
} => crate::inventory::pairs(tx, request_id, &account, &market, qty, qty_micros, true),
|
|
Command::Merge {
|
|
market,
|
|
account,
|
|
qty,
|
|
qty_micros,
|
|
} => crate::inventory::pairs(tx, request_id, &account, &market, qty, qty_micros, false),
|
|
Command::Order {
|
|
market,
|
|
account,
|
|
key_id,
|
|
outcome,
|
|
side,
|
|
price,
|
|
price_micros,
|
|
qty,
|
|
size_micros,
|
|
tif,
|
|
expiration,
|
|
post_only,
|
|
} => book::submit(
|
|
tx,
|
|
books,
|
|
book::NewOrder {
|
|
market,
|
|
account,
|
|
key_id,
|
|
outcome,
|
|
side,
|
|
price: crate::tick_size::required(price, price_micros)?,
|
|
qty: crate::lots::amount(qty, size_micros)?,
|
|
tif: tif.unwrap_or_else(|| {
|
|
if expiration.unwrap_or(0) != 0 {
|
|
crate::command::TimeInForce::Gtd
|
|
} else {
|
|
crate::command::TimeInForce::Gtc
|
|
}
|
|
}),
|
|
expiration,
|
|
post_only,
|
|
},
|
|
)
|
|
.map(|result| result.receipt()),
|
|
Command::MarketSell {
|
|
market,
|
|
account,
|
|
key_id,
|
|
outcome,
|
|
qty,
|
|
min_price,
|
|
min_price_micros,
|
|
size_micros,
|
|
tif,
|
|
} => {
|
|
let tif = tif.unwrap_or(crate::command::TimeInForce::Fak);
|
|
ensure!(
|
|
matches!(
|
|
tif,
|
|
crate::command::TimeInForce::Fak | crate::command::TimeInForce::Fok
|
|
),
|
|
"market sell requires FAK or FOK"
|
|
);
|
|
let qty = crate::lots::amount(qty, size_micros)?;
|
|
let limit = crate::tick_size::input(min_price, min_price_micros)?;
|
|
let price = books
|
|
.protection_price(&market, &outcome, matching::Side::Sell, qty, limit, tif)
|
|
.ok_or_else(|| {
|
|
anyhow::anyhow!("insufficient opposing depth for market sell protection price")
|
|
})?;
|
|
let tick = crate::tick_size::TickSize::load(tx, &market)?;
|
|
let amounts = crate::market_amounts::Amounts::for_order(
|
|
tick.as_ref(),
|
|
matching::Side::Sell,
|
|
qty,
|
|
price,
|
|
)?;
|
|
let result = book::submit(
|
|
tx,
|
|
books,
|
|
book::NewOrder {
|
|
market,
|
|
account,
|
|
key_id,
|
|
outcome,
|
|
side: "sell".to_owned(),
|
|
price,
|
|
qty,
|
|
tif,
|
|
expiration: None,
|
|
post_only: false,
|
|
},
|
|
)?;
|
|
let mut receipt = result.receipt();
|
|
if let Some(amounts) = amounts {
|
|
receipt["order_amounts"] = amounts.json();
|
|
}
|
|
receipt["protection_price_micros"] = json!(price * crate::tick_size::PRICE_MICROS);
|
|
receipt["proceeds_cents"] =
|
|
json!(crate::inventory::decimal(result.gross_micros.into(), 10000));
|
|
receipt["unsold_shares"] = json!(crate::lots::display(qty - result.filled));
|
|
if result.fee_micros > 0 {
|
|
receipt["net_proceeds_micros"] = json!(result.gross_micros - result.fee_micros);
|
|
}
|
|
Ok(receipt)
|
|
}
|
|
Command::MarketBuy {
|
|
market,
|
|
outcome,
|
|
account,
|
|
key_id,
|
|
amount_cents,
|
|
amount_micros,
|
|
max_price,
|
|
max_price_micros,
|
|
tif,
|
|
} => book::market_buy(
|
|
tx,
|
|
books,
|
|
book::BudgetBuy {
|
|
market,
|
|
outcome,
|
|
account,
|
|
key_id,
|
|
amount_cents: crate::market_amounts::cash_cents(amount_cents, amount_micros)?,
|
|
max_price: crate::tick_size::input(max_price, max_price_micros)?,
|
|
tif: tif.unwrap_or(crate::command::TimeInForce::Fak),
|
|
},
|
|
),
|
|
Command::Cancel { order, account } => {
|
|
identifier(&account)?;
|
|
let qty = book::release(tx, order, &account, book::CancelReason::Cancelled)?;
|
|
Ok(json!({"cancelled":crate::lots::display(qty)}))
|
|
}
|
|
Command::CancelOrders { account, orders } => {
|
|
crate::cancellation::by_id(tx, &account, &orders)
|
|
}
|
|
Command::CancelMarketOrders {
|
|
account,
|
|
market,
|
|
outcome,
|
|
} => crate::cancellation::in_scope(tx, &account, Some(&market), outcome.as_deref()),
|
|
Command::CancelAll { account } => crate::cancellation::in_scope(tx, &account, None, None),
|
|
Command::Open { market } => {
|
|
phase(tx, &market, &["preopen"])?;
|
|
// Run one auction. Using the earliest order's outcome as the quote unit
|
|
// preserves the existing low-tick tie break for a one-outcome auction.
|
|
let first:Option<String>=tx.query_row(
|
|
"SELECT outcome FROM orders WHERE market=? AND status='live' ORDER BY seq LIMIT 1",
|
|
[&market],|r|r.get(0)).optional()?;
|
|
if let Some(outcome) = first {
|
|
let book = books
|
|
.get(&market, &outcome)
|
|
.ok_or_else(|| anyhow::anyhow!("missing auction book"))?;
|
|
let step = crate::tick_size::TickSize::load(tx, &market)?
|
|
.map_or(std::num::NonZeroU32::new(100).unwrap(), |tick| {
|
|
tick.local_step()
|
|
});
|
|
book::settle(tx, &market, &outcome, book.opening_with_step(step), None)?;
|
|
}
|
|
tx.execute("UPDATE markets SET phase='continuous' WHERE id=?", [market])?;
|
|
Ok(json!({"phase":"continuous"}))
|
|
}
|
|
Command::Close { market } => {
|
|
close_market(tx, &market)?;
|
|
Ok(json!({"phase":"closed"}))
|
|
}
|
|
Command::Propose {
|
|
market,
|
|
winner,
|
|
proposer,
|
|
evidence,
|
|
} => resolution::propose(tx, &market, &winner, &proposer, &evidence),
|
|
Command::Dispute {
|
|
market,
|
|
proposal,
|
|
challenger,
|
|
evidence,
|
|
} => resolution::dispute(tx, &market, proposal, &challenger, &evidence),
|
|
Command::Adjudicate {
|
|
market,
|
|
proposal,
|
|
verdict,
|
|
evidence,
|
|
} => {
|
|
resolution::record_verdict(tx, &market, proposal, &verdict, &evidence)?;
|
|
if verdict == "TOO_EARLY" {
|
|
return Ok(json!({"status":"awaiting_proposal","proposal":proposal}));
|
|
}
|
|
let backing = finalize(tx, &market, &verdict)?;
|
|
Ok(
|
|
json!({"phase":"resolved","winner":verdict,"outstanding_cents":crate::inventory::decimal(i128::from(backing),10000)}),
|
|
)
|
|
}
|
|
Command::Observe {
|
|
market,
|
|
stream,
|
|
observed_at,
|
|
price,
|
|
evidence,
|
|
} => crate::twap::observe(tx, &market, &stream, observed_at, &price, &evidence),
|
|
Command::Finalize { market, winner } => {
|
|
let winner = match winner {
|
|
Some(winner) => winner,
|
|
None => tx
|
|
.query_row(
|
|
"SELECT result FROM twap_result WHERE market=? AND result IS NOT NULL",
|
|
[&market],
|
|
|r| r.get::<_, String>(0),
|
|
)
|
|
.optional()?
|
|
.ok_or_else(|| anyhow::anyhow!("no computed outcome available"))?,
|
|
};
|
|
let backing = finalize(tx, &market, &winner)?;
|
|
Ok(
|
|
json!({"phase":"resolved","winner":winner,"outstanding_cents":crate::inventory::decimal(i128::from(backing),10000)}),
|
|
)
|
|
}
|
|
Command::Redeem {
|
|
market,
|
|
account,
|
|
amounts_micros,
|
|
} => {
|
|
identifier(&account)?;
|
|
phase(tx, &market, &["resolved"])?;
|
|
let paid = redeem(tx, &market, &account, request_id, amounts_micros)?;
|
|
let mut receipt = json!({"market":market,"account":account,"paid":crate::inventory::decimal(i128::from(paid),10000)});
|
|
if let Some(amounts) = amounts_micros {
|
|
receipt["amounts_micros"] = json!(amounts);
|
|
receipt["paid_micros"] = json!(paid);
|
|
}
|
|
Ok(receipt)
|
|
}
|
|
Command::Resolve { market, winner } => {
|
|
let backing = finalize(tx, &market, &winner)?;
|
|
let mut holders = tx.prepare(
|
|
"SELECT DISTINCT account FROM position_units WHERE market=? AND available>0",
|
|
)?;
|
|
let accounts = holders
|
|
.query_map([&market], |row| row.get::<_, String>(0))?
|
|
.collect::<rusqlite::Result<Vec<_>>>()?;
|
|
let mut paid = 0;
|
|
for account in accounts {
|
|
paid += redeem(tx, &market, &account, request_id, None)?;
|
|
}
|
|
let dust: i64 = tx.query_row(
|
|
"SELECT COALESCE((SELECT micros FROM settlement_dust WHERE market=?),0)",
|
|
[&market],
|
|
|r| r.get(0),
|
|
)?;
|
|
ensure!(backing == paid + dust, "collateral mismatch");
|
|
Ok(json!({"phase":"resolved","paid":crate::inventory::decimal(i128::from(paid),10000)}))
|
|
}
|
|
}
|
|
}
|
|
|
|
pub(crate) fn close_market(tx: &Transaction, market: &str) -> Result<()> {
|
|
phase(tx, market, &["preopen", "continuous"])?;
|
|
clear_orders(tx, market)?;
|
|
tx.execute("UPDATE markets SET phase='closed' WHERE id=?", [market])?;
|
|
Ok(())
|
|
}
|
|
|
|
pub(crate) fn clear_orders(tx: &Transaction, market: &str) -> Result<usize> {
|
|
let mut stmt = tx.prepare("SELECT seq,account FROM orders WHERE market=? AND status='live'")?;
|
|
let orders = stmt
|
|
.query_map([market], |r| {
|
|
Ok((r.get::<_, i64>(0)?, r.get::<_, String>(1)?))
|
|
})?
|
|
.collect::<rusqlite::Result<Vec<_>>>()?;
|
|
let count = orders.len();
|
|
for (seq, account) in orders {
|
|
book::release(tx, seq, &account, book::CancelReason::Cancelled)?;
|
|
}
|
|
Ok(count)
|
|
}
|
|
|
|
pub(crate) fn finalize(tx: &Transaction, market: &str, winner: &str) -> Result<i64> {
|
|
phase(tx, market, &["closed"])?;
|
|
ensure!(matches!(winner, "YES" | "NO" | "VOID"), "invalid winner");
|
|
resolution::authorize_finalization(tx, market, winner)?;
|
|
crate::neg_risk::allocate_payout(tx, market, winner)?;
|
|
// Each outcome redeems in whole collateral base units. Half-payout rounding
|
|
// is per outcome balance, including when both balances belong to one wallet.
|
|
let (payout,odd):(i64,i64)=tx.query_row(
|
|
"SELECT COALESCE(SUM(CASE WHEN ?1='VOID' THEN available/2 WHEN outcome=?1 THEN available ELSE 0 END),0),
|
|
COALESCE(SUM(CASE WHEN ?1='VOID' THEN available%2 ELSE 0 END),0)
|
|
FROM position_units WHERE market=?2",params![winner,market],|r| Ok((r.get(0)?,r.get(1)?)))?;
|
|
let backing: i64 = tx.query_row(
|
|
"SELECT micros FROM market_backing WHERE market=?",
|
|
[market],
|
|
|r| r.get(0),
|
|
)?;
|
|
ensure!(
|
|
odd % 2 == 0 && backing.checked_sub(odd / 2) == Some(payout),
|
|
"collateral mismatch"
|
|
);
|
|
if odd > 0 {
|
|
tx.execute(
|
|
"INSERT INTO settlement_dust VALUES(?,?)",
|
|
params![market, odd / 2],
|
|
)?;
|
|
}
|
|
tx.execute(
|
|
"UPDATE markets SET phase='resolved',winner=? WHERE id=?",
|
|
params![winner, market],
|
|
)?;
|
|
Ok(backing)
|
|
}
|
|
|
|
fn redeem(
|
|
tx: &Transaction,
|
|
market: &str,
|
|
account: &str,
|
|
request_id: &str,
|
|
amounts: Option<[i64; 2]>,
|
|
) -> Result<i64> {
|
|
let (shares, paid) = match amounts {
|
|
Some(amounts) => crate::neg_risk::burn_for_redemption(tx, market, account, amounts)?,
|
|
None => burn_full_balance(tx, market, account)?,
|
|
};
|
|
crate::inventory::movement(tx, request_id, account, market, "REDEEM", shares, paid)?;
|
|
if paid > 0 {
|
|
crate::inventory::backing(tx, market, -paid)?;
|
|
ledger::cash_micros(tx, account, paid)?;
|
|
}
|
|
Ok(paid)
|
|
}
|
|
|
|
fn burn_full_balance(tx: &Transaction, market: &str, account: &str) -> Result<(i64, i64)> {
|
|
let (shares,paid):(Option<i64>,Option<i64>)=tx.query_row(
|
|
"SELECT SUM(available),SUM(CASE payout_per_share WHEN 50 THEN available/2 WHEN 100 THEN available ELSE 0 END)
|
|
FROM position_units WHERE market=? AND account=? AND available>0",params![market,account],|r|Ok((r.get(0)?,r.get(1)?)))?;
|
|
let paid = paid.ok_or_else(|| anyhow::anyhow!("no positions to redeem"))?;
|
|
tx.execute(
|
|
"DELETE FROM position_remainders WHERE market=? AND account=?",
|
|
params![market, account],
|
|
)?;
|
|
tx.execute(
|
|
"UPDATE positions SET quantity=0 WHERE market=? AND account=? AND quantity>0",
|
|
params![market, account],
|
|
)?;
|
|
Ok((shares.unwrap_or(0), paid))
|
|
}
|