Resolve up-down markets from exact same-stream TWAP observations

This commit is contained in:
2026-12-03 04:19:49 +08:00
parent 8aa33385fb
commit 67426ae617
11 changed files with 294 additions and 21 deletions
+34 -12
View File
@@ -160,18 +160,7 @@ pub(crate) fn apply(tx: &Transaction, books: &Books, command: Command) -> Result
Ok(json!({"phase":"continuous"}))
}
Command::Close { market } => {
phase(tx, &market, &["preopen", "continuous"])?;
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<_>>>()?;
for (seq, account) in orders {
book::release(tx, seq, &account, book::CancelReason::Cancelled)?;
}
tx.execute("UPDATE markets SET phase='closed' WHERE id=?", [market])?;
close_market(tx, &market)?;
Ok(json!({"phase":"closed"}))
}
Command::Propose {
@@ -199,7 +188,25 @@ pub(crate) fn apply(tx: &Transaction, books: &Books, command: Command) -> Result
let backing = finalize(tx, &market, &verdict)?;
Ok(json!({"phase":"resolved","winner":verdict,"outstanding_cents":backing}))
}
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":backing}))
}
@@ -226,6 +233,21 @@ pub(crate) fn apply(tx: &Transaction, books: &Books, command: Command) -> Result
}
}
pub(crate) fn close_market(tx: &Transaction, market: &str) -> Result<()> {
phase(tx, market, &["preopen", "continuous"])?;
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<_>>>()?;
for (seq, account) in orders {
book::release(tx, seq, &account, book::CancelReason::Cancelled)?;
}
tx.execute("UPDATE markets SET phase='closed' WHERE id=?", [market])?;
Ok(())
}
fn finalize(tx: &Transaction, market: &str, winner: &str) -> Result<i64> {
phase(tx, market, &["closed"])?;
ensure!(matches!(winner, "YES" | "NO" | "VOID"), "invalid winner");