Expose public resolution lifecycle and preserve arbitration after a reset
This commit is contained in:
@@ -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
|
||||
Reference in New Issue
Block a user