diff --git a/crates/exchange/README.md b/crates/exchange/README.md index 8d56c02..2b52237 100644 --- a/crates/exchange/README.md +++ b/crates/exchange/README.md @@ -1459,3 +1459,5 @@ sequenceDiagram ``` `bind_polymarket_assets` 将完整协议配对绑定到已创建的本地市场。操作员用 zero_outcome 声明外场结果索引 0 对应本地 YES 或 NO。绑定和请求回执在同一事务提交。数字资产、外场条件和已绑定的结构条件可通过 GET /v2/tokens 反查;响应附带 local_asset_id。成交流程继续通过本地资产提交委托。 + +同一配对可携带 observed_at_ms 刷新外场状态。旧快照不会覆盖新状态,最终兑付冲突会回滚。 diff --git a/crates/exchange/src/schema.sql b/crates/exchange/src/schema.sql index 6e26e9f..813cbea 100644 --- a/crates/exchange/src/schema.sql +++ b/crates/exchange/src/schema.sql @@ -347,3 +347,9 @@ CREATE UNIQUE INDEX IF NOT EXISTS pm_alias_structure_slots ON polymarket_token_aliases(structure,slot) WHERE structure IS NOT NULL; CREATE UNIQUE INDEX IF NOT EXISTS pm_alias_question_slots ON polymarket_token_aliases(group_id,question,module,slot) WHERE group_id IS NOT NULL; + + +CREATE TABLE IF NOT EXISTS polymarket_token_observation_times ( + token_id TEXT PRIMARY KEY REFERENCES polymarket_token_aliases(token_id), + observed_at_ms INTEGER NOT NULL CHECK(observed_at_ms>0) +); diff --git a/crates/exchange/src/token_aliases.rs b/crates/exchange/src/token_aliases.rs index f430cc2..543c636 100644 --- a/crates/exchange/src/token_aliases.rs +++ b/crates/exchange/src/token_aliases.rs @@ -14,6 +14,7 @@ pub(crate) struct Bind { market: String, external_condition: String, zero_outcome: String, + observed_at_ms: Option, data: Vec, } @@ -118,6 +119,10 @@ impl<'a> Row<'a> { impl Bind { pub(crate) fn register(self, tx: &Transaction<'_>) -> Result { identifier(&self.market)?; + ensure!( + self.observed_at_ms.is_none_or(|ms| ms > 0), + "invalid observation time" + ); ensure!( matches!(self.zero_outcome.as_str(), "YES" | "NO"), "zero_outcome must be YES or NO" @@ -140,6 +145,27 @@ impl Bind { "repeated protocol outcome" ); } + if self.observed_at_ms.is_some() { + let mut states = BTreeMap::new(); + for value in &self.data { + let row = Row::read(value, &self.external_condition)?; + let state = SnapshotState::read(value)?; + let pair = states.entry(row.module).or_insert_with(|| [None, None]); + pair[row.slot] = Some(state); + } + for pair in states.values() { + let [Some(a), Some(b)] = pair else { + anyhow::bail!("incomplete protocol pair"); + }; + ensure!( + a.closed == b.closed && a.resolved == b.resolved, + "protocol pair has inconsistent lifecycle" + ); + if let (Some(a), Some(b)) = (a.price, b.price) { + ensure!((a + b - 1.0).abs() <= 1e-9, "final payouts must sum to one"); + } + } + } let v2_count = families.keys().filter(|m| **m != "v1_ctf").count(); ensure!(v2_count <= 1, "multiple V2 protocols for the same market"); let mut group_ref = None; @@ -218,6 +244,7 @@ impl Bind { .into_iter() .map(|key| (key.to_owned(), value[key].clone())) .collect(); + let observation = Value::Object(observation); tx.execute( "INSERT INTO polymarket_token_aliases VALUES(?1,?2,?3,?4,?5,?6,?7,?8) ON CONFLICT(token_id) DO NOTHING", @@ -229,7 +256,7 @@ impl Bind { row.group, row.question, row.slot as i64, - Value::Object(observation).to_string() + observation.to_string() ], )?; let observed: Option = tx @@ -240,16 +267,19 @@ impl Bind { ) .optional()?; let prior: Value = serde_json::from_str(&observed.context("missing stored token")?)?; - let prior = Row::read(&prior, &self.external_condition)?; + let prior_identity = Row::read(&prior, &self.external_condition)?; ensure!( - prior.module == row.module - && prior.structure == row.structure - && prior.slot == row.slot - && prior.group == row.group - && prior.question == row.question - && prior.opposite == row.opposite, + prior_identity.module == row.module + && prior_identity.structure == row.structure + && prior_identity.slot == row.slot + && prior_identity.group == row.group + && prior_identity.question == row.question + && prior_identity.opposite == row.opposite, "token already bound with different identity" ); + if let Some(observed_at_ms) = self.observed_at_ms { + refresh(tx, row.token, prior, &observation, observed_at_ms)?; + } } Ok( json!({"market":self.market,"external_condition":self.external_condition, @@ -257,3 +287,87 @@ impl Bind { ) } } + +struct SnapshotState { + closed: bool, + resolved: bool, + price: Option, +} + +impl SnapshotState { + fn read(data: &Value) -> Result { + let closed = data["closed"] + .as_bool() + .context("closed must be a boolean")?; + let resolved = data["resolved"] + .as_bool() + .context("resolved must be a boolean")?; + let price = data["final_price"].as_f64(); + if resolved { + ensure!( + closed && price.is_some_and(|p| (0.0..=1.0).contains(&p)), + "invalid final payout" + ); + } else { + ensure!( + data["final_price"].is_null(), + "unresolved asset has a final payout" + ); + } + Ok(Self { + closed, + resolved, + price, + }) + } +} + +const LIVE_FIELDS: &[&str] = &["closed", "resolved", "final_price", "outcome"]; + +fn refresh( + tx: &Transaction<'_>, + token: &str, + mut prior: Value, + incoming: &Value, + observed_at_ms: i64, +) -> Result<()> { + let last: Option = tx + .query_row( + "SELECT observed_at_ms FROM polymarket_token_observation_times WHERE token_id=?1", + [token], + |r| r.get(0), + ) + .optional()?; + if let Some(last) = last { + if observed_at_ms < last { + return Ok(()); + } + if observed_at_ms == last { + ensure!( + LIVE_FIELDS.iter().all(|&key| prior[key] == incoming[key]), + "conflicting observations at the same time" + ); + return Ok(()); + } + } + if prior["resolved"] == true { + ensure!( + incoming["resolved"] == true + && prior["final_price"].as_f64() == incoming["final_price"].as_f64(), + "observation contradicts a recorded final payout" + ); + } + for &key in LIVE_FIELDS { + prior[key] = incoming[key].clone(); + } + tx.execute( + "UPDATE polymarket_token_aliases SET observation=?1 WHERE token_id=?2", + params![prior.to_string(), token], + )?; + tx.execute( + "INSERT INTO polymarket_token_observation_times VALUES(?1,?2) + ON CONFLICT(token_id) DO UPDATE SET observed_at_ms=excluded.observed_at_ms", + params![token, observed_at_ms], + )?; + Ok(()) +} diff --git a/crates/exchange/src/token_aliases.sql b/crates/exchange/src/token_aliases.sql index f0b9910..321b482 100644 --- a/crates/exchange/src/token_aliases.sql +++ b/crates/exchange/src/token_aliases.sql @@ -5,11 +5,12 @@ WITH selectors AS ( ) SELECT s.ordinal,t.observation,m.market, CASE WHEN t.slot=0 THEN m.zero_outcome - WHEN m.zero_outcome='YES' THEN 'NO' ELSE 'YES' END AS outcome + WHEN m.zero_outcome='YES' THEN 'NO' ELSE 'YES' END AS outcome,o.observed_at_ms FROM selectors s JOIN polymarket_token_aliases t ON (s.kind='external_token' AND t.token_id=s.id) OR (s.kind='condition' AND (t.condition_id=s.id OR t.group_id=s.id OR t.structure=s.id OR t.structure=s.id||'00')) JOIN polymarket_market_aliases m ON m.condition_id=t.condition_id +LEFT JOIN polymarket_token_observation_times o ON o.token_id=t.token_id ORDER BY s.ordinal,t.question,t.condition_id,(t.module<>'v1_ctf'),t.slot diff --git a/crates/exchange/src/token_directory.rs b/crates/exchange/src/token_directory.rs index 707b2d3..dded500 100644 --- a/crates/exchange/src/token_directory.rs +++ b/crates/exchange/src/token_directory.rs @@ -118,17 +118,19 @@ impl Exchange { r.get::<_, String>(1)?, r.get::<_, String>(2)?, r.get::<_, String>(3)?, + r.get::<_, Option>(4)?, )) })?; rows.collect::>>()? }; let external_ordinals: HashSet<_> = externals.iter().map(|r| r.0).collect(); data.retain(|(ordinal, _)| !external_ordinals.contains(ordinal)); - for (ordinal, raw, market, outcome) in externals { + for (ordinal, raw, market, outcome, observed_at_ms) in externals { let mut row: Value = serde_json::from_str(&raw).map_err(|_| MarketDataError::Unavailable)?; row["local_condition_id"] = json!(market); row["local_asset_id"] = json!(assets::id(&market, &outcome)); + row["observed_at_ms"] = json!(observed_at_ms); data.push((ordinal, row)); } data.sort_by_key(|row| row.0); diff --git a/crates/exchange/tests/market.rs b/crates/exchange/tests/market.rs index af02811..5af8854 100644 --- a/crates/exchange/tests/market.rs +++ b/crates/exchange/tests/market.rs @@ -4262,3 +4262,55 @@ fn polymarket_asset_bindings_preserve_protocols_and_explicit_outcome_direction() rows[3] ); } + +#[test] +fn polymarket_observations_refresh_without_reverting_a_final_payout() { + let dir = tempdir().unwrap(); + let path = dir.path().join("refresh.db"); + let mut engine = Exchange::open(&path).unwrap(); + setup(&mut engine); + let fixture: Value = serde_json::from_str(include_str!( + "../../../docs/examples/polymarket-asset-refresh.json" + )) + .unwrap(); + let resolved = fixture["directory"]["body"]["data"].clone(); + let mut open = resolved.clone(); + for item in open.as_array_mut().unwrap() { + item["closed"] = json!(false); + item["resolved"] = json!(false); + item["final_price"] = Value::Null; + } + let late = fixture["directory"]["observed_at_ms"].as_i64().unwrap(); + let early = fixture["prior_book"]["observed_at_ms"].as_i64().unwrap(); + let condition = &resolved[0]["condition_id"]; + let obs = |id, stamp, rows: &Value| { + json!({ + "op":"bind_polymarket_assets", "id":id,"market":"e","zero_outcome":"YES", + "external_condition":condition,"observed_at_ms":stamp,"data":rows + }) + }; + engine.execute(obs("before", early, &open)).unwrap(); + engine.execute(obs("final", late, &resolved)).unwrap(); + engine.execute(obs("old", early, &open)).unwrap(); + assert!(engine + .execute(obs("same-time-conflict", late, &open)) + .is_err()); + assert!(engine + .execute(obs("new-conflict", late + 1, &open)) + .is_err()); + drop(engine); + let engine = Exchange::open(path).unwrap(); + let lookup = engine + .public_tokens(serde_json::from_value(json!({"condition":condition})).unwrap()) + .unwrap(); + let rows = lookup["data"].as_array().unwrap(); + assert_eq!(rows.len(), 4); + for row in rows { + assert_eq!(row["resolved"], true); + assert_eq!(row["observed_at_ms"], late); + } + let local = engine + .public_tokens(serde_json::from_value(json!({"condition":"e"})).unwrap()) + .unwrap(); + assert_eq!(local["data"][0]["resolved"], false); +} diff --git a/docs/examples/polymarket-asset-refresh.json b/docs/examples/polymarket-asset-refresh.json new file mode 100644 index 0000000..46b9225 --- /dev/null +++ b/docs/examples/polymarket-asset-refresh.json @@ -0,0 +1,110 @@ +{ + "prior_book": { + "url": "https://clob.polymarket.com/book?token_id=64069535502365350520464017439278800338614209934309608490621606944970108681676", + "date": "Thu, 03 Dec 2026 07:55:53 GMT", + "status": 200, + "body": { + "market": "0xe5febd2f236a15ef7c1cc70a481e081bb64223d3e67aa3870677cccd72530853", + "asset_id": "64069535502365350520464017439278800338614209934309608490621606944970108681676", + "timestamp": "1796284481649", + "hash": "575e315a02461b9280427591ba1fe7e48b3b70ce", + "bids": [], + "asks": [], + "min_order_size": "5", + "tick_size": "0.01", + "neg_risk": false, + "last_trade_price": "" + }, + "observed_at_ms": 1796284553000 + }, + "directory": { + "url": "https://data-api.polymarket.com/v2/tokens?condition=0xe5febd2f236a15ef7c1cc70a481e081bb64223d3e67aa3870677cccd72530853", + "status": 200, + "date": "Fri, 04 Dec 2026 21:11:06 GMT", + "body": { + "data": [ + { + "token_id": "64069535502365350520464017439278800338614209934309608490621606944970108681676", + "condition_id": "0xe5febd2f236a15ef7c1cc70a481e081bb64223d3e67aa3870677cccd72530853", + "structural_condition_id": null, + "module": "v1_ctf", + "outcome_index": 0, + "clob_index": 0, + "outcome": "Over", + "opposite_token_id": "24637903833591077899504141654082654473942967248855682279041797174393952421575", + "resolved": true, + "final_price": 0.0, + "title": "Map 1 Total Rounds: Over/Under 27.5", + "market_slug": "cs2-bb3-lgc-2026-12-03-game1-round-total-27pt5", + "closed": true, + "neg_risk": false, + "neg_risk_market_id": null, + "question_index": null, + "event_id": 1495714, + "event_slug": "cs2-bb3-lgc-2026-12-03" + }, + { + "token_id": "24637903833591077899504141654082654473942967248855682279041797174393952421575", + "condition_id": "0xe5febd2f236a15ef7c1cc70a481e081bb64223d3e67aa3870677cccd72530853", + "structural_condition_id": null, + "module": "v1_ctf", + "outcome_index": 1, + "clob_index": 1, + "outcome": "Under", + "opposite_token_id": "64069535502365350520464017439278800338614209934309608490621606944970108681676", + "resolved": true, + "final_price": 1.0, + "title": "Map 1 Total Rounds: Over/Under 27.5", + "market_slug": "cs2-bb3-lgc-2026-12-03-game1-round-total-27pt5", + "closed": true, + "neg_risk": false, + "neg_risk_market_id": null, + "question_index": null, + "event_id": 1495714, + "event_slug": "cs2-bb3-lgc-2026-12-03" + }, + { + "token_id": "774335495545660990871175894688282765790269993344601020630233166497523433472", + "condition_id": "0xe5febd2f236a15ef7c1cc70a481e081bb64223d3e67aa3870677cccd72530853", + "structural_condition_id": "0x01b64223d3e67aa3870677cccd72530853000000000000000000000000000000", + "module": "binary", + "outcome_index": 0, + "clob_index": null, + "outcome": "Over", + "opposite_token_id": "774335495545660990871175894688282765790269993344601020630233166497523433473", + "resolved": true, + "final_price": 0.0, + "title": "Map 1 Total Rounds: Over/Under 27.5", + "market_slug": "cs2-bb3-lgc-2026-12-03-game1-round-total-27pt5", + "closed": true, + "neg_risk": false, + "neg_risk_market_id": null, + "question_index": null, + "event_id": 1495714, + "event_slug": "cs2-bb3-lgc-2026-12-03" + }, + { + "token_id": "774335495545660990871175894688282765790269993344601020630233166497523433473", + "condition_id": "0xe5febd2f236a15ef7c1cc70a481e081bb64223d3e67aa3870677cccd72530853", + "structural_condition_id": "0x01b64223d3e67aa3870677cccd72530853000000000000000000000000000000", + "module": "binary", + "outcome_index": 1, + "clob_index": null, + "outcome": "Under", + "opposite_token_id": "774335495545660990871175894688282765790269993344601020630233166497523433472", + "resolved": true, + "final_price": 1.0, + "title": "Map 1 Total Rounds: Over/Under 27.5", + "market_slug": "cs2-bb3-lgc-2026-12-03-game1-round-total-27pt5", + "closed": true, + "neg_risk": false, + "neg_risk_market_id": null, + "question_index": null, + "event_id": 1495714, + "event_slug": "cs2-bb3-lgc-2026-12-03" + } + ] + }, + "observed_at_ms": 1796418666000 + } +} diff --git a/docs/prediction-parity.md b/docs/prediction-parity.md index 6f388b3..58438a0 100644 --- a/docs/prediction-parity.md +++ b/docs/prediction-parity.md @@ -474,4 +474,7 @@ GET /v2/tokens 接受 token_id / token_ids 或 condition / condition_id / condit ### 本地登记 Polymarket 资产对照 -可信 JSONL 命令 bind_polymarket_assets 接受本地市场、external_condition、zero_outcome 及官方 data 数组。每种协议必须提供互补一对。登记时核对 V2 编码、互斥组与题目归属,禁止冲突重绑。登记后用外场数字资产或条件查询 /v2/tokens 可得到原协议观察字段及 local_asset_id。互斥组查询仅返回已登记成员。保留的结果状态与兑付值来自登记时的外场快照,尚未自动刷新,也未接入真实下单路由。[生产登记样本](examples/polymarket-asset-binding.json) +可信 JSONL 命令 bind_polymarket_assets 接受本地市场、external_condition、zero_outcome 及官方 data 数组。每种协议必须提供互补一对。登记时核对 V2 编码、互斥组与题目归属,禁止冲突重绑。登记后用外场数字资产或条件查询 /v2/tokens 可得到原协议观察字段及 local_asset_id。互斥组查询仅返回已登记成员。外场状态与兑付值由观测快照提供。[生产登记样本](examples/polymarket-asset-binding.json) + + +对同一绑定重复提交带 observed_at_ms 的配对可刷新状态及结果标签。旧观测不会覆盖更新状态,同毫秒互相矛盾的快照和推翻最终兑付的请求会拒绝,整笔事务回滚。反查回执带观测时间。一个此前能公开读取盘口的电竞盘,后续 CTF 与 V2 目录均返回裁决输赢。回归使用它的真实裁决响应,并用同一资产生成开放快照来覆盖乱序。刷新由可信操作者提供观测,生产接口的传播时延和自动拉取仍待接入。[生产盘口及裁决快照](examples/polymarket-asset-refresh.json)