Publish settlement clarifications and atomically clear affected orders
This commit is contained in:
@@ -1134,3 +1134,31 @@ sequenceDiagram
|
||||
D-->>E: 观测时间和定点价格
|
||||
E-->>C: t 为 Unix 秒,p 为十进制数
|
||||
```
|
||||
|
||||
### 裁决规则的补充公告
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
C["command.rs"] --> M["market.rs"]
|
||||
M --> N["clarifications.rs"]
|
||||
N --> B["market.rs · clear_orders"] --> L["book.rs · release"]
|
||||
N --> S["schema.sql · market_clarifications"]
|
||||
R["resolution.rs"] --> N
|
||||
```
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant O as 操作员
|
||||
participant E as Exchange
|
||||
participant D as SQLite
|
||||
participant B as 常驻盘口
|
||||
O->>E: publish_clarification,携带请求 ID
|
||||
E->>D: 同一事务中保存原文和 clear_book
|
||||
opt 清盘
|
||||
E->>D: 撤销本市场所有存续委托,返还剩余现金或份额
|
||||
end
|
||||
E->>D: 保存回执并提交
|
||||
E->>B: 应用已提交的订单变更
|
||||
O->>E: resolution
|
||||
E-->>O: 原始规则、历次公告、裁决阶段和已确定的兑付权重
|
||||
```
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
use crate::{market, validation::phase, Exchange, MarketDataError};
|
||||
use anyhow::{ensure, Result};
|
||||
use rusqlite::{params, Connection, Transaction};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
pub(crate) fn publish(
|
||||
tx: &Transaction,
|
||||
market: &str,
|
||||
content: &str,
|
||||
clear_book: bool,
|
||||
) -> Result<Value> {
|
||||
phase(tx, market, &["preopen", "continuous", "closed"])?;
|
||||
ensure!(!content.trim().is_empty(), "clarification text required");
|
||||
tx.execute(
|
||||
"INSERT INTO market_clarifications(market,content,clear_book) VALUES(?1,?2,?3)",
|
||||
params![market, content, clear_book],
|
||||
)?;
|
||||
let id = tx.last_insert_rowid();
|
||||
let canceled = if clear_book {
|
||||
market::clear_orders(tx, market)?
|
||||
} else {
|
||||
0
|
||||
};
|
||||
Ok(json!({"id":id,"market":market,"clearBook":clear_book,"canceled_count":canceled}))
|
||||
}
|
||||
|
||||
fn read(
|
||||
db: &Connection,
|
||||
market: Option<&str>,
|
||||
ids: &[i64],
|
||||
limit: i64,
|
||||
offset: i64,
|
||||
ascending: bool,
|
||||
) -> rusqlite::Result<Vec<Value>> {
|
||||
let ids_json = json!(ids).to_string();
|
||||
let order = if ascending { "ASC" } else { "DESC" };
|
||||
let sql = format!(
|
||||
"SELECT n.id,d.id,n.content,n.clear_book,n.created_at
|
||||
FROM market_clarifications n JOIN market_directory_ids d ON d.market=n.market
|
||||
WHERE (?1 IS NULL OR n.market=?1)
|
||||
AND (?2='[]' OR d.id IN (SELECT value FROM json_each(?2)))
|
||||
ORDER BY n.id {order} LIMIT ?3 OFFSET ?4"
|
||||
);
|
||||
let mut stmt = db.prepare_cached(&sql)?;
|
||||
let rows = stmt.query_map(params![market, ids_json, limit, offset], |r| {
|
||||
Ok(
|
||||
json!({"id":r.get::<_,i64>(0)?,"marketId":r.get::<_,i64>(1)?,
|
||||
"content":r.get::<_,String>(2)?,"clearBook":r.get::<_,bool>(3)?,
|
||||
"createdAt":r.get::<_,String>(4)?,"showInFrontend":true,
|
||||
"txTimestamp":null,"txHash":null}),
|
||||
)
|
||||
})?;
|
||||
rows.collect()
|
||||
}
|
||||
|
||||
pub(crate) fn for_resolution(db: &Connection, market: &str) -> rusqlite::Result<Vec<Value>> {
|
||||
read(db, Some(market), &[], -1, 0, true)
|
||||
}
|
||||
|
||||
impl Exchange {
|
||||
pub fn market_clarifications(
|
||||
&self,
|
||||
ids: &[i64],
|
||||
limit: u32,
|
||||
offset: i64,
|
||||
ascending: bool,
|
||||
) -> Result<Vec<Value>, MarketDataError> {
|
||||
if ids.iter().any(|id| *id <= 0) || limit > 100 || offset < 0 {
|
||||
return Err(MarketDataError::Invalid(
|
||||
"invalid clarification filter".into(),
|
||||
));
|
||||
}
|
||||
Ok(read(
|
||||
&self.db,
|
||||
None,
|
||||
ids,
|
||||
i64::from(limit),
|
||||
offset,
|
||||
ascending,
|
||||
)?)
|
||||
}
|
||||
}
|
||||
@@ -36,6 +36,12 @@ pub(crate) enum Command {
|
||||
markets: Vec<String>,
|
||||
augmented: Option<crate::augmented::Config>,
|
||||
},
|
||||
#[serde(rename = "publish_clarification")]
|
||||
PublishClarification {
|
||||
market: String,
|
||||
content: String,
|
||||
clear_book: bool,
|
||||
},
|
||||
Clarify {
|
||||
market: String,
|
||||
name: String,
|
||||
|
||||
@@ -17,6 +17,7 @@ use validation::identifier;
|
||||
mod book;
|
||||
mod book_snapshot;
|
||||
mod cancellation;
|
||||
mod clarifications;
|
||||
mod clob_market;
|
||||
mod command;
|
||||
mod inventory;
|
||||
|
||||
@@ -109,6 +109,11 @@ pub(crate) fn apply(
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
Command::PublishClarification {
|
||||
market,
|
||||
content,
|
||||
clear_book,
|
||||
} => crate::clarifications::publish(tx, &market, &content, clear_book),
|
||||
Command::Clarify {
|
||||
market,
|
||||
name,
|
||||
@@ -381,17 +386,23 @@ pub(crate) fn apply(
|
||||
|
||||
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)?;
|
||||
}
|
||||
tx.execute("UPDATE markets SET phase='closed' WHERE id=?", [market])?;
|
||||
Ok(())
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
pub(crate) fn finalize(tx: &Transaction, market: &str, winner: &str) -> Result<i64> {
|
||||
|
||||
@@ -110,6 +110,25 @@ pub(crate) fn authorize_finalization(tx: &Transaction, market: &str, winner: &st
|
||||
}
|
||||
|
||||
pub(crate) fn read(db: &Connection, market: &str) -> Result<Value> {
|
||||
let mut state = policy_state(db, market)?;
|
||||
let (rules, resolved_at): (String, Option<i64>) = db.query_row(
|
||||
"SELECT m.rules,s.at_ms FROM markets m LEFT JOIN price_settlements s ON s.market=m.id WHERE m.id=?",
|
||||
[market], |row| Ok((row.get(0)?,row.get(1)?))
|
||||
)?;
|
||||
state["rules"] = json!(rules);
|
||||
state["resolved_at_ms"] = json!(resolved_at);
|
||||
// YES, NO token order from the binary CTF adapter. Only finalized markets have a winner.
|
||||
state["payouts"] = match state["winner"].as_str() {
|
||||
Some("YES") => json!([1, 0]),
|
||||
Some("NO") => json!([0, 1]),
|
||||
Some("VOID") => json!([1, 1]),
|
||||
_ => Value::Null,
|
||||
};
|
||||
state["clarifications"] = json!(crate::clarifications::for_resolution(db, market)?);
|
||||
Ok(state)
|
||||
}
|
||||
|
||||
fn policy_state(db: &Connection, market: &str) -> Result<Value> {
|
||||
if let Some(data) = crate::twap::read(db, market)? {
|
||||
return Ok(data);
|
||||
}
|
||||
|
||||
@@ -5,6 +5,13 @@ CREATE TABLE IF NOT EXISTS markets (
|
||||
id TEXT PRIMARY KEY, rules TEXT NOT NULL, phase TEXT NOT NULL,
|
||||
collateral INTEGER NOT NULL DEFAULT 0 CHECK(collateral >= 0), winner TEXT
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS market_clarifications (
|
||||
id INTEGER PRIMARY KEY, market TEXT NOT NULL REFERENCES markets(id),
|
||||
content TEXT NOT NULL CHECK(length(trim(content))>0),
|
||||
clear_book INTEGER NOT NULL CHECK(clear_book IN (0,1)),
|
||||
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now'))
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS clarifications_by_market ON market_clarifications(market,id);
|
||||
CREATE TABLE IF NOT EXISTS positions (
|
||||
account TEXT REFERENCES accounts, market TEXT REFERENCES markets, outcome TEXT,
|
||||
quantity INTEGER NOT NULL CHECK(quantity >= 0), PRIMARY KEY(account,market,outcome)
|
||||
|
||||
@@ -896,6 +896,8 @@ fn contested_resolution_blocks_both_payout_paths_until_a_verdict() {
|
||||
assert_eq!(e.execute(decision).unwrap(), finalized);
|
||||
let resolved = e.execute(status).unwrap();
|
||||
assert_eq!(resolved["winner"], "NO");
|
||||
assert_eq!(resolved["payouts"], json!([0, 1]));
|
||||
assert!(resolved["resolved_at_ms"].is_i64());
|
||||
assert_eq!(resolved["proposals"][1]["verdict"], "NO");
|
||||
assert_eq!(resolved["proposals"][0]["challenger"], "bob");
|
||||
assert_eq!(e.execute(redeem).unwrap()["paid"], 200);
|
||||
@@ -3163,3 +3165,75 @@ fn midpoint_keeps_half_a_tick_after_reopening_the_book() {
|
||||
assert_eq!(prices[&tokens[0]].as_deref(), Some("0.08505"));
|
||||
assert_eq!(prices[&tokens[1]].as_deref(), Some("0.91495"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn published_clarification_clears_only_its_market_and_replays_after_restart() {
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("clarifications.db");
|
||||
let mut e = Exchange::open(&path).unwrap();
|
||||
setup(&mut e);
|
||||
for cmd in [
|
||||
json!({"op":"list","id":"other-list","market":"other","rules":"other result"}),
|
||||
json!({"op":"open","id":"start","market":"e"}),
|
||||
order("rest-ask", "alice", "sell", 60, 2),
|
||||
order("rest-bid", "bob", "buy", 40, 1),
|
||||
json!({"op":"order","id":"other-bid","market":"other","outcome":"NO","account":"bob","side":"buy","price":10,"qty":1}),
|
||||
] {
|
||||
e.execute(cmd).unwrap();
|
||||
}
|
||||
let book = json!({"op":"clob_book","token_id":"eb:YES:e"});
|
||||
let original = e.execute(book.clone()).unwrap();
|
||||
let first = json!({"op":"publish_clarification","id":"n1","market":"e","content":"Use the official result sheet.","clear_book":false});
|
||||
assert_eq!(e.execute(first).unwrap()["canceled_count"], 0);
|
||||
assert_eq!(e.execute(book.clone()).unwrap()["asks"], original["asks"]);
|
||||
let next = json!({"op":"publish_clarification","id":"n2","market":"e","content":"The result includes overtime.","clear_book":true});
|
||||
let state = json!({"op":"resolution","market":"e"});
|
||||
let connection = rusqlite::Connection::open(&path).unwrap();
|
||||
connection.execute_batch("CREATE TRIGGER reject_clear BEFORE UPDATE OF status ON orders WHEN OLD.market='e' BEGIN SELECT RAISE(ABORT,'simulated release failure'); END;").unwrap();
|
||||
assert!(e.execute(next.clone()).is_err());
|
||||
assert_eq!(
|
||||
e.execute(state.clone()).unwrap()["clarifications"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.len(),
|
||||
1
|
||||
);
|
||||
assert_eq!(e.execute(book.clone()).unwrap()["bids"], original["bids"]);
|
||||
connection
|
||||
.execute_batch("DROP TRIGGER reject_clear")
|
||||
.unwrap();
|
||||
let receipt = e.execute(next.clone()).unwrap();
|
||||
assert_eq!(receipt["canceled_count"], 2);
|
||||
assert_eq!(e.execute(book.clone()).unwrap()["asks"], json!([]));
|
||||
assert_eq!(e.execute(book.clone()).unwrap()["bids"], json!([]));
|
||||
assert_eq!(
|
||||
e.execute(json!({"op":"balance","account":"bob"})).unwrap()["available_micros"],
|
||||
19_900_000
|
||||
);
|
||||
let other = e
|
||||
.execute(json!({"op":"clob_book","token_id":"eb:NO:other"}))
|
||||
.unwrap();
|
||||
assert_eq!(other["bids"].as_array().unwrap().len(), 1);
|
||||
e.execute(order("new-bid", "bob", "buy", 39, 1)).unwrap();
|
||||
drop(e);
|
||||
let mut e = Exchange::open(&path).unwrap();
|
||||
assert_eq!(e.execute(next).unwrap(), receipt);
|
||||
assert_eq!(
|
||||
e.execute(book).unwrap()["bids"].as_array().unwrap().len(),
|
||||
1
|
||||
);
|
||||
let resolution = e.execute(state).unwrap();
|
||||
assert_eq!(resolution["rules"], "official result");
|
||||
assert!(resolution["payouts"].is_null());
|
||||
assert!(resolution["resolved_at_ms"].is_null());
|
||||
assert_eq!(resolution["clarifications"][1]["clearBook"], true);
|
||||
assert!(resolution["clarifications"][1]["txTimestamp"].is_null());
|
||||
e.execute(json!({"op":"close","id":"end","market":"e"}))
|
||||
.unwrap();
|
||||
e.execute(json!({"op":"finalize","id":"void","market":"e","winner":"VOID"}))
|
||||
.unwrap();
|
||||
let settled = e.execute(json!({"op":"resolution","market":"e"})).unwrap();
|
||||
assert_eq!(settled["payouts"], json!([1, 1]));
|
||||
assert_eq!(settled["clarifications"], resolution["clarifications"]);
|
||||
assert!(e.execute(json!({"op":"publish_clarification","id":"late","market":"e","content":"late note","clear_book":false})).is_err());
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user