Expose public resolution lifecycle and preserve arbitration after a reset
This commit is contained in:
@@ -56,6 +56,7 @@ pub use prices_history::http::HistoryQuery;
|
||||
pub use prices_history::legacy::ClobHistoryQuery;
|
||||
pub use public_trades::http::TradeQuery;
|
||||
pub use quotes::{PriceQueryError, PriceRequest, PriceSide};
|
||||
pub use resolution::http::ResolutionQuery;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum MarketDataError {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::{Anchor, Filters, Scan};
|
||||
use crate::{
|
||||
assets, inventory, lots,
|
||||
validation::{identifier, IdSelector},
|
||||
validation::{directory_selector, identifier},
|
||||
Exchange, MarketDataError,
|
||||
};
|
||||
use anyhow::{ensure, Context, Result};
|
||||
@@ -79,35 +79,6 @@ impl Cursor {
|
||||
}
|
||||
}
|
||||
|
||||
fn selector(db: &Connection, raw: Option<&str>, numeric: bool) -> Result<Option<IdSelector>> {
|
||||
raw.map(|raw| {
|
||||
let mut keys = Vec::new();
|
||||
for id in raw.split(',').map(str::trim) {
|
||||
identifier(id)?;
|
||||
if numeric {
|
||||
let n = id.parse::<i64>().context("invalid event_id")?;
|
||||
ensure!(n > 0, "invalid event_id");
|
||||
keys.push(n.to_string());
|
||||
} else {
|
||||
if id.starts_with("0x")
|
||||
&& !(id.len() == 66 && id[2..].bytes().all(|b| b.is_ascii_hexdigit()))
|
||||
{
|
||||
// Locally listed condition IDs may legitimately use a short 0x prefix.
|
||||
let listed: bool = db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM markets WHERE id=?1)",
|
||||
[id],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
ensure!(listed, "invalid condition: {id}");
|
||||
}
|
||||
keys.push(id.to_owned());
|
||||
}
|
||||
}
|
||||
Ok(IdSelector::Many(keys))
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
|
||||
fn trade(row: &Row<'_>) -> rusqlite::Result<Value> {
|
||||
let market: String = row.get(4)?;
|
||||
let outcome: String = row.get(5)?;
|
||||
@@ -128,8 +99,8 @@ impl TradeQuery {
|
||||
if let Some(user) = &self.user {
|
||||
identifier(user)?;
|
||||
}
|
||||
let market = selector(db, self.condition.as_deref(), false)?;
|
||||
let event = selector(db, self.event_id.as_deref(), true)?;
|
||||
let market = directory_selector(db, self.condition.as_deref(), false)?;
|
||||
let event = directory_selector(db, self.event_id.as_deref(), true)?;
|
||||
let scoped = self.user.is_some() || market.is_some() || event.is_some();
|
||||
let (now,default_start):(i64,i64)=db.query_row(
|
||||
"SELECT CAST(unixepoch('subsec')*1000 AS INTEGER),CASE WHEN ?1 THEN CAST(unixepoch('now','-3 years','subsec')*1000 AS INTEGER) ELSE unixepoch('now','start of month','-1 month')*1000 END",
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
pub(crate) mod http;
|
||||
|
||||
use crate::validation::identifier;
|
||||
use anyhow::{ensure, Result};
|
||||
use rusqlite::{params, Connection, Transaction};
|
||||
@@ -9,6 +11,7 @@ use serde_json::{json, Value};
|
||||
pub(crate) enum Policy {
|
||||
Optimistic {
|
||||
eligible_at: i64,
|
||||
question_id: Option<String>,
|
||||
},
|
||||
Twap {
|
||||
stream: String,
|
||||
@@ -19,8 +22,11 @@ pub(crate) enum Policy {
|
||||
|
||||
impl Policy {
|
||||
pub fn save(self, tx: &Transaction, market: &str) -> Result<()> {
|
||||
let eligible_at = match self {
|
||||
Self::Optimistic { eligible_at } => eligible_at,
|
||||
let (eligible_at, question_id) = match self {
|
||||
Self::Optimistic {
|
||||
eligible_at,
|
||||
question_id,
|
||||
} => (eligible_at, question_id),
|
||||
Self::Twap {
|
||||
stream,
|
||||
start_at,
|
||||
@@ -32,10 +38,24 @@ impl Policy {
|
||||
"INSERT INTO optimistic_markets(market,eligible_at) VALUES(?,?)",
|
||||
params![market, eligible_at],
|
||||
)?;
|
||||
if let Some(id) = question_id {
|
||||
tx.execute(
|
||||
"INSERT INTO resolution_questions(market,question_id) VALUES(?,?)",
|
||||
params![market, question_key(&id)?],
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn question_key(raw: &str) -> Result<String> {
|
||||
ensure!(
|
||||
raw.len() == 66 && raw.starts_with("0x") && raw[2..].bytes().all(|b| b.is_ascii_hexdigit()),
|
||||
"invalid question_id"
|
||||
);
|
||||
Ok(raw.to_ascii_lowercase())
|
||||
}
|
||||
|
||||
pub(crate) fn propose(
|
||||
tx: &Transaction,
|
||||
market: &str,
|
||||
@@ -50,7 +70,7 @@ pub(crate) fn propose(
|
||||
);
|
||||
let changed=tx.execute(
|
||||
"INSERT INTO resolution_proposals(market,round,result,proposer,evidence,proposed_at)
|
||||
SELECT market,CASE status WHEN 'awaiting_second_proposal' THEN 2 ELSE 1 END,?2,?3,?4,unixepoch()
|
||||
SELECT market,CASE WHEN status='awaiting_second_proposal' OR verdict='TOO_EARLY' THEN 2 ELSE 1 END,?2,?3,?4,unixepoch()
|
||||
FROM market_resolution WHERE market=?1 AND status IN ('awaiting_proposal','awaiting_second_proposal')",
|
||||
params![market,winner,proposer,evidence])?;
|
||||
ensure!(changed == 1, "market is not accepting proposals");
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
use super::question_key;
|
||||
use crate::{validation::directory_selector, Exchange, MarketDataError};
|
||||
use anyhow::{ensure, Result};
|
||||
use rusqlite::{named_params, Connection, Row};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ResolutionQuery {
|
||||
#[serde(alias = "questionId")]
|
||||
question_id: Option<String>,
|
||||
#[serde(alias = "condition_id", alias = "conditionId")]
|
||||
condition: Option<String>,
|
||||
#[serde(alias = "eventId")]
|
||||
event_id: Option<String>,
|
||||
}
|
||||
|
||||
fn oracle_price(result: Option<&str>) -> &'static str {
|
||||
match result {
|
||||
Some("YES") => "1000000000000000000",
|
||||
Some("NO") => "0",
|
||||
Some("VOID") => "500000000000000000",
|
||||
_ => "69",
|
||||
}
|
||||
}
|
||||
|
||||
fn resolution(row: &Row<'_>, by_question: bool) -> rusqlite::Result<Value> {
|
||||
let value = |key: &str| row.get::<_, Option<String>>(key);
|
||||
let winner = value("winner")?;
|
||||
let updated = if by_question {
|
||||
row.get::<_, Option<i64>>("updated_ms")?
|
||||
.map(|ms| (ms / 1000).to_string())
|
||||
} else {
|
||||
value("updated_at")?
|
||||
};
|
||||
let mut entry = json!({
|
||||
"status": row.get::<_,String>("status")?, "last_update_timestamp": updated.unwrap_or_default(),
|
||||
"was_disputed": row.get::<_,bool>("disputed")?, "was_arbitrated": row.get::<_,bool>("arbitrated")?,
|
||||
"extended_review": false, "new_version_q": false, "transaction_hash": "", "log_index": ""
|
||||
});
|
||||
if let Some(id) = value("question_id")? {
|
||||
entry["question_id"] = json!(id);
|
||||
}
|
||||
if let Some(expiry) = value("expires")? {
|
||||
entry["expected_settlement_time"] = json!(expiry);
|
||||
entry["settlement_time_basis"] = json!("proposal_expiration");
|
||||
}
|
||||
if by_question {
|
||||
entry["proposed_price"] = json!(oracle_price(value("first_price")?.as_deref()));
|
||||
entry["reproposed_price"] = json!(oracle_price(value("second_price")?.as_deref()));
|
||||
entry["price"] = json!(oracle_price(winner.as_deref()));
|
||||
} else {
|
||||
entry["condition_id"] = json!(row.get::<_, String>("market")?);
|
||||
if let Some(kind) = value("market_type")? {
|
||||
entry["market_type"] = json!(kind);
|
||||
}
|
||||
if let Some(time) = value("settled")? {
|
||||
entry["resolved_at"] = json!(time);
|
||||
}
|
||||
if let Some(result) = winner {
|
||||
entry["payouts"] = match result.as_str() {
|
||||
"YES" => json!([1_000_000, 0]),
|
||||
"NO" => json!([0, 1_000_000]),
|
||||
"VOID" => json!([500_000, 500_000]),
|
||||
_ => return Err(rusqlite::Error::InvalidQuery),
|
||||
};
|
||||
}
|
||||
}
|
||||
Ok(entry)
|
||||
}
|
||||
|
||||
impl ResolutionQuery {
|
||||
fn read(self, db: &Connection) -> Result<Value> {
|
||||
ensure!(
|
||||
[
|
||||
self.question_id.is_some(),
|
||||
self.condition.is_some(),
|
||||
self.event_id.is_some()
|
||||
]
|
||||
.into_iter()
|
||||
.filter(|set| *set)
|
||||
.count()
|
||||
== 1,
|
||||
"supply exactly one of question_id, condition, event_id"
|
||||
);
|
||||
let question = self.question_id.as_deref().map(question_key).transpose()?;
|
||||
let ids = |raw: Option<&str>, numeric| -> Result<Option<String>> {
|
||||
directory_selector(db, raw, numeric)?
|
||||
.map(|s| Ok(serde_json::to_string(&s.ids()?)?))
|
||||
.transpose()
|
||||
};
|
||||
let mut stmt = db.prepare(include_str!("state.sql"))?;
|
||||
let data = stmt
|
||||
.query_map(
|
||||
named_params! {
|
||||
":question": question, ":conditions": ids(self.condition.as_deref(),false)?,
|
||||
":events": ids(self.event_id.as_deref(),true)?,
|
||||
},
|
||||
|row| resolution(row, question.is_some()),
|
||||
)?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
Ok(json!({"data":data}))
|
||||
}
|
||||
}
|
||||
|
||||
impl Exchange {
|
||||
pub fn public_resolutions(&self, query: ResolutionQuery) -> Result<Value, MarketDataError> {
|
||||
let tx = self.db.unchecked_transaction()?;
|
||||
let page = query.read(&tx).map_err(|err| {
|
||||
if err.downcast_ref::<rusqlite::Error>().is_some() {
|
||||
MarketDataError::Unavailable
|
||||
} else {
|
||||
MarketDataError::Invalid(err.to_string())
|
||||
}
|
||||
})?;
|
||||
tx.commit()?;
|
||||
Ok(page)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
WITH selected(market) AS (
|
||||
SELECT value FROM json_each(:conditions)
|
||||
UNION SELECT market FROM resolution_questions WHERE question_id=:question
|
||||
UNION SELECT l.market FROM listed_markets l JOIN event_directory_ids d ON d.event=l.event
|
||||
WHERE d.id IN (SELECT value FROM json_each(:events))
|
||||
), lifecycle AS (
|
||||
SELECT m.market,m.winner,q.question_id,
|
||||
CASE WHEN m.phase='resolved' THEN 'resolved'
|
||||
WHEN p.verdict='TOO_EARLY' THEN 'challenged'
|
||||
WHEN p.challenged_at IS NOT NULL THEN CASE p.round WHEN 1 THEN 'challenged' ELSE 'disputed' END
|
||||
WHEN p.id IS NOT NULL THEN CASE p.round WHEN 1 THEN 'proposed' ELSE 'reproposed' END
|
||||
WHEN m.eligible_at IS NOT NULL THEN 'posed' ELSE 'active' END AS status,
|
||||
(SELECT EXISTS(SELECT 1 FROM resolution_proposals d WHERE d.market=m.market AND d.challenged_at IS NOT NULL)) AS disputed,
|
||||
(SELECT EXISTS(SELECT 1 FROM resolution_proposals d WHERE d.market=m.market AND d.round=2 AND d.challenged_at IS NOT NULL)) AS arbitrated,
|
||||
CASE WHEN p.round=1 OR p.verdict='TOO_EARLY' THEN p.result ELSE prev.result END AS first_price,
|
||||
CASE WHEN p.round=2 AND p.verdict IS NOT 'TOO_EARLY' THEN p.result END AS second_price,
|
||||
CASE WHEN m.winner IS NULL AND p.challenged_at IS NULL AND unixepoch()<p.proposed_at+7200
|
||||
THEN strftime('%Y-%m-%dT%H:%M:%SZ',p.proposed_at+7200,'unixepoch') END AS expires,
|
||||
strftime('%Y-%m-%dT%H:%M:%fZ',s.at_ms/1000.0,'unixepoch') AS settled,
|
||||
COALESCE(s.at_ms,1000*COALESCE(p.decided_at,p.challenged_at,p.proposed_at),
|
||||
CAST(json_extract(f.payload,'$.timestamp') AS INTEGER)) AS updated_ms,
|
||||
CASE WHEN g.market IS NULL THEN 'BINARY' END AS market_type
|
||||
FROM market_resolution m
|
||||
LEFT JOIN resolution_questions q ON q.market=m.market
|
||||
LEFT JOIN resolution_proposals p ON p.id=m.proposal
|
||||
LEFT JOIN resolution_proposals prev ON prev.id=(
|
||||
SELECT id FROM resolution_proposals WHERE market=m.market AND id<p.id ORDER BY id DESC LIMIT 1)
|
||||
LEFT JOIN price_settlements s ON s.market=m.market
|
||||
LEFT JOIN market_lifecycle_frames f ON f.market=m.market AND f.kind='new_market'
|
||||
LEFT JOIN augmented_outcomes a ON a.market=m.market
|
||||
LEFT JOIN neg_risk_members g ON g.market=m.market
|
||||
WHERE m.market IN (SELECT market FROM selected) AND (a.role IS NULL OR a.role<>'placeholder')
|
||||
)
|
||||
SELECT lifecycle.*,strftime('%Y-%m-%dT%H:%M:%fZ',updated_ms/1000.0,'unixepoch') AS updated_at
|
||||
FROM lifecycle ORDER BY market
|
||||
@@ -127,6 +127,9 @@ CREATE INDEX IF NOT EXISTS fills_by_ask ON fills(ask,seq);
|
||||
CREATE TABLE IF NOT EXISTS optimistic_markets (
|
||||
market TEXT PRIMARY KEY REFERENCES markets(id), eligible_at INTEGER NOT NULL CHECK(eligible_at>=0)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS resolution_questions (
|
||||
market TEXT PRIMARY KEY REFERENCES optimistic_markets(market), question_id TEXT NOT NULL UNIQUE
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS resolution_proposals (
|
||||
id INTEGER PRIMARY KEY, market TEXT NOT NULL REFERENCES optimistic_markets(market),
|
||||
round INTEGER NOT NULL CHECK(round IN (1,2)),
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use anyhow::{ensure, Result};
|
||||
use rusqlite::Transaction;
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use rusqlite::{Connection, Transaction};
|
||||
pub(crate) fn identifier(id: &str) -> Result<()> {
|
||||
ensure!(
|
||||
!id.trim().is_empty() && id.trim().chars().count() <= 256,
|
||||
@@ -46,3 +46,36 @@ impl IdSelector {
|
||||
Ok(ids)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn directory_selector(
|
||||
db: &Connection,
|
||||
raw: Option<&str>,
|
||||
numeric: bool,
|
||||
) -> Result<Option<IdSelector>> {
|
||||
raw.map(|raw| {
|
||||
let mut keys = Vec::new();
|
||||
for id in raw.split(',').map(str::trim) {
|
||||
identifier(id)?;
|
||||
if numeric {
|
||||
let n = id.parse::<i64>().context("invalid event_id")?;
|
||||
ensure!(n > 0, "invalid event_id");
|
||||
keys.push(n.to_string());
|
||||
} else {
|
||||
if id.starts_with("0x")
|
||||
&& !(id.len() == 66 && id[2..].bytes().all(|b| b.is_ascii_hexdigit()))
|
||||
{
|
||||
// Locally listed condition IDs may legitimately use a short 0x prefix.
|
||||
let listed: bool = db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM markets WHERE id=?1)",
|
||||
[id],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
ensure!(listed, "invalid condition: {id}");
|
||||
}
|
||||
keys.push(id.to_owned());
|
||||
}
|
||||
}
|
||||
Ok(IdSelector::Many(keys))
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user