Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c377947ea1 | ||
|
|
2d4e7012cd | ||
|
|
5b244eb54f | ||
|
|
4bc9f8a326 | ||
|
|
f8fbd68d19 | ||
|
|
2888563723 |
No files matched your search
Generated
+2
@@ -117,7 +117,9 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"exchange",
|
||||
"httpdate",
|
||||
"percent-encoding",
|
||||
"reqwest",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"serde_urlencoded",
|
||||
|
||||
@@ -12,3 +12,5 @@ tungstenite = "0.28"
|
||||
tiny_http = "0.12"
|
||||
serde_urlencoded = "0.7"
|
||||
percent-encoding = "2"
|
||||
reqwest = { version = "0.12", default-features = false, features = ["blocking", "rustls-tls", "json"] }
|
||||
httpdate = "1"
|
||||
@@ -9,8 +9,11 @@
|
||||
```mermaid
|
||||
flowchart LR
|
||||
main["src/main.rs"] -->|把标准输入输出交给 serve| stream["src/stream.rs"]
|
||||
main --> refresh["src/polymarket_refresh.rs"]
|
||||
main -.->|打开数据库| api["exchange crate"]
|
||||
stream -.->|执行命令| api
|
||||
refresh -.->|读取绑定并写入观测| api
|
||||
refresh -->|HTTPS GET| pm["Polymarket Data API"]
|
||||
```
|
||||
|
||||
## 一次命令会话
|
||||
@@ -425,3 +428,30 @@ sequenceDiagram
|
||||
E-->>H: true
|
||||
H-->>C: 200,neg_risk 为真
|
||||
```
|
||||
|
||||
GET /v2/tokens 支持逗号分隔的资产 ID 或条件及事件 ID。两个选择器择一,回执按资产关联市场、事件和裁决结果。完整的 V2 Neg Risk 事件 ID 返回已登记成员的仓位对,62 位十六进制条件 ID 返回该条件的仓位对。
|
||||
|
||||
### 刷新已登记的 Polymarket 资产
|
||||
|
||||
`cli DATABASE --refresh-polymarket MARKET` 刷新指定本地市场。省略 `MARKET` 则按本地市场 ID 顺序刷新所有已登记的市场。每盘输出一行 JSON。任一盘失败时命令最终以非零状态退出,其他盘仍可提交。上游 HTTP `Date` 用作观测时间,旧观测保留已有目录状态。
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
actor U as 操作员
|
||||
participant C as polymarket_refresh.rs
|
||||
participant E as Exchange
|
||||
participant P as Polymarket Data API
|
||||
U->>C: 指定数据库和可选市场 ID
|
||||
C->>E: 查询已登记的外场条件、资产和结果映射
|
||||
loop 每个市场
|
||||
C->>P: GET /v2/tokens?condition=...
|
||||
P-->>C: HTTP Date 和资产数组
|
||||
alt 所有已登记资产齐全
|
||||
C->>E: 提交 bind_polymarket_assets
|
||||
E-->>C: 单盘事务回执或校验错误
|
||||
else 请求或响应校验失败
|
||||
C->>C: 记录本盘错误
|
||||
end
|
||||
C-->>U: 输出本盘结果
|
||||
end
|
||||
```
|
||||
+11
-1
@@ -1,5 +1,6 @@
|
||||
mod market_http;
|
||||
mod market_ws;
|
||||
mod polymarket_refresh;
|
||||
mod stream;
|
||||
mod subscriptions;
|
||||
|
||||
@@ -12,9 +13,18 @@ use std::{
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let mut args = env::args_os().skip(1);
|
||||
let usage = "usage: cli DATABASE [--market-ws HOST:PORT | --market-http HOST:PORT]";
|
||||
let usage = "usage: cli DATABASE [--market-ws HOST:PORT | --market-http HOST:PORT | --refresh-polymarket [MARKET]]";
|
||||
let path = args.next().context(usage)?;
|
||||
if let Some(mode) = args.next() {
|
||||
if mode == "--refresh-polymarket" {
|
||||
let market = args
|
||||
.next()
|
||||
.map(|s| s.into_string().map_err(|_| anyhow::anyhow!(usage)))
|
||||
.transpose()?;
|
||||
ensure!(args.next().is_none(), usage);
|
||||
let mut exchange = Exchange::open(path)?;
|
||||
return polymarket_refresh::run(&mut exchange, market.as_deref(), io::stdout().lock());
|
||||
}
|
||||
ensure!(mode == "--market-ws" || mode == "--market-http", usage);
|
||||
let addr: SocketAddr = args
|
||||
.next()
|
||||
|
||||
@@ -329,7 +329,12 @@ fn respond(mut req: Request, engine: &Mutex<Exchange>) -> std::io::Result<()> {
|
||||
if req.method() == &Method::Get
|
||||
&& matches!(
|
||||
path,
|
||||
"/v2/prices-history" | "/v2/trades" | "/v2/resolutions" | "/v2/value" | "/v2/oi"
|
||||
"/v2/tokens"
|
||||
| "/v2/prices-history"
|
||||
| "/v2/trades"
|
||||
| "/v2/resolutions"
|
||||
| "/v2/value"
|
||||
| "/v2/oi"
|
||||
)
|
||||
{
|
||||
let (status, body) = data_page(path, params, engine);
|
||||
@@ -473,6 +478,7 @@ fn respond(mut req: Request, engine: &Mutex<Exchange>) -> std::io::Result<()> {
|
||||
| "/market-clarifications"
|
||||
| "/v2/oi"
|
||||
| "/v2/value"
|
||||
| "/v2/tokens"
|
||||
| "/v2/trades"
|
||||
| "/v2/resolutions"
|
||||
| "/v2/prices-history",
|
||||
@@ -513,6 +519,7 @@ fn read_page<Q: serde::de::DeserializeOwned>(
|
||||
|
||||
fn data_page(path: &str, params: &str, engine: &Mutex<Exchange>) -> (u16, Value) {
|
||||
let page = match path {
|
||||
"/v2/tokens" => read_page(params, engine, Exchange::public_tokens),
|
||||
"/v2/oi" => read_page(params, engine, Exchange::public_open_interest),
|
||||
"/v2/value" => read_page(params, engine, Exchange::public_portfolio_value),
|
||||
"/v2/trades" => read_page(params, engine, Exchange::public_trade_feed),
|
||||
@@ -525,6 +532,10 @@ fn data_page(path: &str, params: &str, engine: &Mutex<Exchange>) -> (u16, Value)
|
||||
400,
|
||||
json!({"code":"invalid_request","error":message,"retryable":false}),
|
||||
),
|
||||
Err(HistoryError::Unavailable) if path == "/v2/tokens" => (
|
||||
503,
|
||||
json!({"code":"unavailable","error":"token directory unavailable","retryable":true}),
|
||||
),
|
||||
Err(HistoryError::Unavailable) if path == "/v2/oi" => (
|
||||
503,
|
||||
json!({"code":"unavailable","error":"open interest unavailable","retryable":true}),
|
||||
@@ -692,6 +703,10 @@ mod tests {
|
||||
assert_eq!(quoted["outcomePrices"], r#"["0.4","0.6"]"#);
|
||||
let empty_trades = json!({"data":[],"pagination":{"limit":100,"offset":0,"has_more":false,"next_cursor":null}});
|
||||
let cases = [
|
||||
("GET","/v2/tokens?token_ids=eb:NO:s,00123,eb:NO:s,eb:YES:s",String::new(),200,Some(db.public_tokens(serde_json::from_value(json!({"token_id":"eb:NO:s,123,eb:YES:s"})).unwrap()).unwrap())),
|
||||
("GET","/v2/tokens?condition=s&token_id=eb:YES:s",String::new(),400,None),
|
||||
("GET","/v2/tokens?token_id=00123,123",String::new(),200,Some(json!({"data":[]}))),
|
||||
("POST","/v2/tokens",String::new(),405,None),
|
||||
("GET","/v2/oi?conditionId=s,s",String::new(),200,Some(json!({"data":[{"condition_id":"s","value":0}]}))),
|
||||
("GET","/v2/oi?condition_id=0x0000000000000000000000000000000000000000000000000000000000000001",String::new(),200,Some(json!({"data":[]}))),
|
||||
("GET","/v2/oi?condition=bad-hash",String::new(),400,Some(json!({"code":"invalid_request","error":"invalid condition: bad-hash","retryable":false}))),
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use exchange::{Exchange, PolymarketBinding};
|
||||
use reqwest::{blocking::Client, header, Url};
|
||||
use serde_json::{json, Value};
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
io::{Read, Write},
|
||||
time::{Duration, UNIX_EPOCH},
|
||||
};
|
||||
|
||||
const MAX_BODY_BYTES: u64 = 1_048_576;
|
||||
|
||||
fn fetch(client: &Client, binding: &PolymarketBinding) -> Result<(i64, Value)> {
|
||||
let url = Url::parse_with_params(
|
||||
"https://data-api.polymarket.com/v2/tokens",
|
||||
&[("condition", binding.condition.as_str())],
|
||||
)?;
|
||||
let response = client
|
||||
.get(url)
|
||||
.header(header::CACHE_CONTROL, "no-cache")
|
||||
.send()?;
|
||||
ensure!(
|
||||
response.status().is_success(),
|
||||
"directory returned HTTP {}",
|
||||
response.status()
|
||||
);
|
||||
let date = response
|
||||
.headers()
|
||||
.get(header::DATE)
|
||||
.context("missing Date")?
|
||||
.to_str()?;
|
||||
let observed_at = httpdate::parse_http_date(date)?.duration_since(UNIX_EPOCH)?;
|
||||
let observed_at = i64::try_from(observed_at.as_millis())?;
|
||||
let mut body = Vec::new();
|
||||
response.take(MAX_BODY_BYTES + 1).read_to_end(&mut body)?;
|
||||
ensure!(
|
||||
body.len() as u64 <= MAX_BODY_BYTES,
|
||||
"directory response too large"
|
||||
);
|
||||
Ok((observed_at, serde_json::from_slice(&body)?))
|
||||
}
|
||||
|
||||
fn command(binding: &PolymarketBinding, observed_at_ms: i64, body: Value) -> Result<Value> {
|
||||
let rows = body["data"].as_array().context("missing directory rows")?;
|
||||
let mut matched = BTreeMap::new();
|
||||
for row in rows {
|
||||
let token = row["token_id"]
|
||||
.as_str()
|
||||
.context("invalid token ID in response")?;
|
||||
if binding.token_ids.iter().any(|known| known == token) {
|
||||
ensure!(
|
||||
row["condition_id"] == binding.condition,
|
||||
"registered token changed condition"
|
||||
);
|
||||
ensure!(
|
||||
matched.insert(token, row).is_none(),
|
||||
"duplicate registered token"
|
||||
);
|
||||
}
|
||||
}
|
||||
ensure!(
|
||||
matched.len() == binding.token_ids.len(),
|
||||
"directory response omits a registered token"
|
||||
);
|
||||
let data: Vec<_> = matched.into_values().collect();
|
||||
Ok(json!({
|
||||
"id":format!("polymarket-observation:{}:{observed_at_ms}", binding.condition),
|
||||
"op":"bind_polymarket_assets","market":binding.market,
|
||||
"external_condition":binding.condition,"zero_outcome":binding.zero_outcome,
|
||||
"observed_at_ms":observed_at_ms,"data":data
|
||||
}))
|
||||
}
|
||||
|
||||
fn refresh(
|
||||
exchange: &mut Exchange,
|
||||
bindings: &[PolymarketBinding],
|
||||
mut fetch: impl FnMut(&PolymarketBinding) -> Result<(i64, Value)>,
|
||||
mut output: impl Write,
|
||||
) -> Result<()> {
|
||||
let mut failures = 0;
|
||||
for binding in bindings {
|
||||
let result = fetch(binding)
|
||||
.and_then(|(timestamp, body)| command(binding, timestamp, body))
|
||||
.and_then(|request| exchange.execute(request));
|
||||
let report = match result {
|
||||
Ok(receipt) => json!({"market":binding.market,"ok":true,"receipt":receipt}),
|
||||
Err(error) => {
|
||||
failures += 1;
|
||||
json!({"market":binding.market,"ok":false,"error":format!("{error:#}")})
|
||||
}
|
||||
};
|
||||
writeln!(output, "{report}")?;
|
||||
}
|
||||
ensure!(
|
||||
failures == 0,
|
||||
"{failures} Polymarket market(s) could not be refreshed"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn run(exchange: &mut Exchange, market: Option<&str>, output: impl Write) -> Result<()> {
|
||||
let bindings = exchange.polymarket_bindings(market)?;
|
||||
let client = Client::builder()
|
||||
.redirect(reqwest::redirect::Policy::none())
|
||||
.connect_timeout(Duration::from_secs(5))
|
||||
.timeout(Duration::from_secs(15))
|
||||
.user_agent("eventbook-readonly-refresh/0.1")
|
||||
.build()?;
|
||||
refresh(
|
||||
exchange,
|
||||
&bindings,
|
||||
|binding| fetch(&client, binding),
|
||||
output,
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn refresh_survives_one_failed_market_and_retries_the_next_snapshot() {
|
||||
let fixture: Value = serde_json::from_str(include_str!(
|
||||
"../../../docs/examples/polymarket-asset-refresh.json"
|
||||
))
|
||||
.unwrap();
|
||||
let late = fixture["directory"]["observed_at_ms"].as_i64().unwrap();
|
||||
let resolved = fixture["directory"]["body"].clone();
|
||||
let mut e = Exchange::open(":memory:").unwrap();
|
||||
e.execute(json!({"op":"list","id":"list","market":"match","rules":"fixture"}))
|
||||
.unwrap();
|
||||
let bound_ids = resolved["data"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|row| row["token_id"].as_str().unwrap().to_owned())
|
||||
.collect();
|
||||
let good = PolymarketBinding {
|
||||
market: "match".into(),
|
||||
condition: resolved["data"][0]["condition_id"].as_str().unwrap().into(),
|
||||
zero_outcome: "NO".into(),
|
||||
token_ids: bound_ids,
|
||||
};
|
||||
let mut partial = resolved.clone();
|
||||
partial["data"].as_array_mut().unwrap().pop();
|
||||
assert!(command(&good, late, partial).is_err());
|
||||
let mut reordered = resolved.clone();
|
||||
reordered["data"].as_array_mut().unwrap().reverse();
|
||||
assert_eq!(
|
||||
command(&good, late, reordered).unwrap(),
|
||||
command(&good, late, resolved.clone()).unwrap()
|
||||
);
|
||||
let mut initial = command(&good, late - 1000, resolved.clone()).unwrap();
|
||||
initial.as_object_mut().unwrap().remove("observed_at_ms");
|
||||
e.execute(initial).unwrap();
|
||||
let mut out = Vec::new();
|
||||
let bad = PolymarketBinding {
|
||||
market: "unreachable".into(),
|
||||
condition: "unknown".into(),
|
||||
zero_outcome: "YES".into(),
|
||||
token_ids: vec![],
|
||||
};
|
||||
let bindings = [bad, good];
|
||||
assert!(refresh(
|
||||
&mut e,
|
||||
&bindings,
|
||||
|m| {
|
||||
ensure!(m.market != "unreachable", "simulated timeout");
|
||||
Ok((late, resolved.clone()))
|
||||
},
|
||||
&mut out
|
||||
)
|
||||
.is_err());
|
||||
let reports: Vec<Value> = std::str::from_utf8(&out)
|
||||
.unwrap()
|
||||
.lines()
|
||||
.map(|line| serde_json::from_str(line).unwrap())
|
||||
.collect();
|
||||
assert_eq!(reports[0]["ok"], false);
|
||||
assert_eq!(reports[1]["ok"], true);
|
||||
refresh(
|
||||
&mut e,
|
||||
&bindings[1..],
|
||||
|_| Ok((late, resolved.clone())),
|
||||
Vec::new(),
|
||||
)
|
||||
.unwrap();
|
||||
let recorded = e.polymarket_bindings(Some("match")).unwrap();
|
||||
assert_eq!(recorded[0].token_ids.len(), 4);
|
||||
let data = e
|
||||
.public_tokens(
|
||||
serde_json::from_value(json!({"condition":bindings[1].condition})).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(data["data"][0]["observed_at_ms"], late);
|
||||
}
|
||||
}
|
||||
@@ -1434,3 +1434,30 @@ sequenceDiagram
|
||||
E-->>C: 返回本次两侧销毁量和实付金额
|
||||
end
|
||||
```
|
||||
|
||||
|
||||
### Data API 资产目录
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
http["cli/market_http.rs"] --> directory["token_directory.rs"]
|
||||
directory --> ids["assets.rs"]
|
||||
directory --> sql["token_directory.sql"]
|
||||
sql --> catalog["市场、事件目录和互斥组"]
|
||||
```
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant H as HTTP
|
||||
participant E as public_tokens
|
||||
participant D as SQLite
|
||||
H->>E: 结果资产、市场条件或互斥组
|
||||
E->>E: 校验选择器、合并重复值
|
||||
E->>D: 同一快照读取目录、结果及裁决
|
||||
D-->>E: 结果标签、互补资产、事件及兑付
|
||||
E-->>H: 按请求顺序返回 data
|
||||
```
|
||||
|
||||
`bind_polymarket_assets` 将完整协议配对绑定到已创建的本地市场。操作员用 zero_outcome 声明外场结果索引 0 对应本地 YES 或 NO。绑定和请求回执在同一事务提交。数字资产、外场条件和已绑定的结构条件可通过 GET /v2/tokens 反查,响应附带 local_asset_id。完整的 V2 Neg Risk 事件 ID 展开该事件已绑定的仓位对,并按题目和结果位置排序。62 位十六进制结构条件只查询该题。旧 CTF 互斥组查询继续返回该组已绑定的两类资产。成交流程继续通过本地资产提交委托。
|
||||
|
||||
同一配对可携带 observed_at_ms 刷新外场状态。旧快照不会覆盖新状态,最终兑付冲突会回滚。
|
||||
@@ -9,6 +9,8 @@ pub(crate) enum Command {
|
||||
micros: Option<i64>,
|
||||
},
|
||||
Event(crate::catalog::Event),
|
||||
#[serde(rename = "bind_polymarket_assets")]
|
||||
BindPolymarketAssets(crate::token_aliases::Bind),
|
||||
#[serde(rename = "reschedule_sports")]
|
||||
RescheduleSports {
|
||||
event: String,
|
||||
|
||||
@@ -41,6 +41,8 @@ mod resident;
|
||||
mod resolution;
|
||||
mod tick_changes;
|
||||
mod tick_size;
|
||||
mod token_aliases;
|
||||
mod token_directory;
|
||||
use resident::Books;
|
||||
|
||||
use anyhow::{ensure, Context, Result};
|
||||
@@ -59,6 +61,8 @@ pub use prices_history::legacy::ClobHistoryQuery;
|
||||
pub use public_trades::http::TradeQuery;
|
||||
pub use quotes::{PriceQueryError, PriceRequest, PriceSide};
|
||||
pub use resolution::http::ResolutionQuery;
|
||||
pub use token_aliases::PolymarketBinding;
|
||||
pub use token_directory::TokenDirectoryQuery;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum MarketDataError {
|
||||
|
||||
@@ -16,6 +16,7 @@ pub(crate) fn apply(
|
||||
request_id: &str,
|
||||
) -> Result<Value> {
|
||||
match command {
|
||||
Command::BindPolymarketAssets(binding) => binding.register(tx),
|
||||
Command::Fund {
|
||||
account,
|
||||
cents,
|
||||
|
||||
@@ -327,3 +327,29 @@ CREATE TABLE IF NOT EXISTS trade_cursor_key (
|
||||
);
|
||||
INSERT INTO trade_cursor_key(singleton,secret)
|
||||
SELECT 1,randomblob(32) WHERE NOT EXISTS(SELECT 1 FROM trade_cursor_key);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS polymarket_market_aliases (
|
||||
condition_id TEXT PRIMARY KEY,
|
||||
market TEXT NOT NULL UNIQUE REFERENCES markets(id),
|
||||
zero_outcome TEXT NOT NULL CHECK(zero_outcome IN ('YES','NO'))
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS polymarket_token_aliases (
|
||||
token_id TEXT PRIMARY KEY,
|
||||
condition_id TEXT NOT NULL REFERENCES polymarket_market_aliases(condition_id),
|
||||
module TEXT NOT NULL, structure TEXT, group_id TEXT, question INTEGER,
|
||||
slot INTEGER NOT NULL CHECK(slot IN (0,1)),
|
||||
observation TEXT NOT NULL CHECK(json_valid(observation)),
|
||||
UNIQUE(condition_id,module,slot)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS pm_alias_structures ON polymarket_token_aliases(structure);
|
||||
CREATE INDEX IF NOT EXISTS pm_alias_groups ON polymarket_token_aliases(group_id,question);
|
||||
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)
|
||||
);
|
||||
@@ -0,0 +1,412 @@
|
||||
use crate::{
|
||||
assets,
|
||||
token_directory::{condition_hex, decimal_token},
|
||||
validation::identifier,
|
||||
};
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use rusqlite::{params, OptionalExtension, Transaction};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub(crate) struct Bind {
|
||||
market: String,
|
||||
external_condition: String,
|
||||
zero_outcome: String,
|
||||
observed_at_ms: Option<i64>,
|
||||
data: Vec<Value>,
|
||||
}
|
||||
|
||||
struct Row<'a> {
|
||||
token: &'a str,
|
||||
opposite: &'a str,
|
||||
module: &'a str,
|
||||
structure: Option<&'a str>,
|
||||
group: Option<&'a str>,
|
||||
slot: usize,
|
||||
question: Option<i64>,
|
||||
}
|
||||
|
||||
fn full_condition(id: &str) -> bool {
|
||||
id.len() == 66 && condition_hex(id).as_deref() == Some(id)
|
||||
}
|
||||
|
||||
fn position_id(raw: &str) -> [u8; 32] {
|
||||
// The decimal string has already been checked against uint256::MAX.
|
||||
let mut bytes = [0u8; 32];
|
||||
for digit in raw.bytes() {
|
||||
let mut carry = u16::from(digit - b'0');
|
||||
for byte in bytes.iter_mut().rev() {
|
||||
let next = u16::from(*byte) * 10 + carry;
|
||||
*byte = next as u8;
|
||||
carry = next >> 8;
|
||||
}
|
||||
}
|
||||
bytes
|
||||
}
|
||||
|
||||
impl<'a> Row<'a> {
|
||||
fn read(row: &'a Value, condition: &str) -> Result<Self> {
|
||||
let token = row["token_id"].as_str().context("token_id is required")?;
|
||||
let opposite = row["opposite_token_id"]
|
||||
.as_str()
|
||||
.context("opposite_token_id is required")?;
|
||||
ensure!(
|
||||
decimal_token(token) == Some(token)
|
||||
&& decimal_token(opposite) == Some(opposite)
|
||||
&& token != opposite,
|
||||
"invalid external outcome identifiers"
|
||||
);
|
||||
ensure!(
|
||||
row["condition_id"] == condition,
|
||||
"external condition mismatch"
|
||||
);
|
||||
let module = row["module"].as_str().context("module is required")?;
|
||||
let slot = row["outcome_index"]
|
||||
.as_u64()
|
||||
.filter(|i| *i < 2)
|
||||
.context("invalid outcome index")? as usize;
|
||||
let structure = row["structural_condition_id"].as_str();
|
||||
let group = row["neg_risk_market_id"].as_str();
|
||||
let question = row["question_index"].as_i64();
|
||||
ensure!(
|
||||
group.is_some() == question.is_some()
|
||||
&& group.is_none_or(full_condition)
|
||||
&& question.is_none_or(|q| q >= 0),
|
||||
"invalid negative-risk question reference"
|
||||
);
|
||||
match module {
|
||||
"v1_ctf" => ensure!(
|
||||
row["structural_condition_id"].is_null(),
|
||||
"CTF has no structure ID"
|
||||
),
|
||||
"binary" | "neg_risk" => {
|
||||
ensure!(
|
||||
(module == "neg_risk") == group.is_some(),
|
||||
"V2 module mismatch"
|
||||
);
|
||||
let bytes = position_id(token);
|
||||
let other = position_id(opposite);
|
||||
let mut expected = String::from("0x");
|
||||
use std::fmt::Write;
|
||||
for byte in &bytes[..31] {
|
||||
write!(expected, "{byte:02x}")?;
|
||||
}
|
||||
expected.push_str("00");
|
||||
ensure!(
|
||||
structure == Some(expected.as_str())
|
||||
&& usize::from(bytes[31]) == slot
|
||||
&& bytes[..31] == other[..31]
|
||||
&& usize::from(other[31]) == 1 - slot,
|
||||
"V2 token does not encode the supplied condition and outcome"
|
||||
);
|
||||
}
|
||||
_ => anyhow::bail!("unsupported external token module"),
|
||||
}
|
||||
Ok(Self {
|
||||
token,
|
||||
opposite,
|
||||
module,
|
||||
structure,
|
||||
group,
|
||||
slot,
|
||||
question,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Bind {
|
||||
pub(crate) fn register(self, tx: &Transaction<'_>) -> Result<Value> {
|
||||
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"
|
||||
);
|
||||
ensure!(
|
||||
full_condition(&self.external_condition),
|
||||
"expected a canonical external market condition"
|
||||
);
|
||||
ensure!(
|
||||
(2..=4).contains(&self.data.len()),
|
||||
"provide a complete outcome pair for each protocol"
|
||||
);
|
||||
let mut families = BTreeMap::new();
|
||||
for value in &self.data {
|
||||
let token = Row::read(value, &self.external_condition)?;
|
||||
let slot = token.slot;
|
||||
let pair = families.entry(token.module).or_insert_with(|| [None, None]);
|
||||
ensure!(
|
||||
pair[slot].replace(token).is_none(),
|
||||
"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;
|
||||
for pair in families.values() {
|
||||
let [Some(a), Some(b)] = pair else {
|
||||
anyhow::bail!("incomplete protocol pair");
|
||||
};
|
||||
ensure!(
|
||||
a.opposite == b.token
|
||||
&& b.opposite == a.token
|
||||
&& a.structure == b.structure
|
||||
&& a.group == b.group
|
||||
&& a.question == b.question,
|
||||
"outcomes do not form one pair"
|
||||
);
|
||||
if let Some((group, question)) = group_ref {
|
||||
ensure!(
|
||||
(a.group, a.question) == (group, question),
|
||||
"protocols identify different questions"
|
||||
);
|
||||
}
|
||||
group_ref = Some((a.group, a.question));
|
||||
}
|
||||
let listed: bool = tx.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM markets WHERE id=?1)",
|
||||
[&self.market],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
ensure!(listed, "unknown local market");
|
||||
tx.execute("INSERT INTO polymarket_market_aliases VALUES(?1,?2,?3) ON CONFLICT(condition_id) DO NOTHING",
|
||||
params![self.external_condition,self.market,self.zero_outcome])?;
|
||||
let bound: (String, String) = tx.query_row(
|
||||
"SELECT market,zero_outcome FROM polymarket_market_aliases WHERE condition_id=?1",
|
||||
[&self.external_condition],
|
||||
|r| Ok((r.get(0)?, r.get(1)?)),
|
||||
)?;
|
||||
ensure!(
|
||||
bound == (self.market.clone(), self.zero_outcome.clone()),
|
||||
"market condition already bound with different identity"
|
||||
);
|
||||
let current_group: Option<(Option<String>, Option<i64>)> = tx.query_row(
|
||||
"SELECT group_id,question FROM polymarket_token_aliases WHERE condition_id=?1 LIMIT 1",
|
||||
[&self.external_condition], |row| Ok((row.get(0)?,row.get(1)?)),
|
||||
).optional()?;
|
||||
if let (Some((stored_group, stored_question)), Some((group, question))) =
|
||||
(current_group, group_ref)
|
||||
{
|
||||
ensure!(
|
||||
(stored_group.as_deref(), stored_question) == (group, question),
|
||||
"market already bound to a different question"
|
||||
);
|
||||
}
|
||||
for value in &self.data {
|
||||
let row = Row::read(value, &self.external_condition)?;
|
||||
// Only retain fields exposed by the external directory.
|
||||
let observation: serde_json::Map<_, _> = [
|
||||
"token_id",
|
||||
"condition_id",
|
||||
"structural_condition_id",
|
||||
"module",
|
||||
"outcome_index",
|
||||
"clob_index",
|
||||
"outcome",
|
||||
"opposite_token_id",
|
||||
"resolved",
|
||||
"final_price",
|
||||
"title",
|
||||
"market_slug",
|
||||
"closed",
|
||||
"neg_risk",
|
||||
"neg_risk_market_id",
|
||||
"question_index",
|
||||
"event_id",
|
||||
"event_slug",
|
||||
]
|
||||
.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",
|
||||
params![
|
||||
row.token,
|
||||
self.external_condition,
|
||||
row.module,
|
||||
row.structure,
|
||||
row.group,
|
||||
row.question,
|
||||
row.slot as i64,
|
||||
observation.to_string()
|
||||
],
|
||||
)?;
|
||||
let observed: Option<String> = tx
|
||||
.query_row(
|
||||
"SELECT observation FROM polymarket_token_aliases WHERE token_id=?1",
|
||||
[row.token],
|
||||
|r| r.get(0),
|
||||
)
|
||||
.optional()?;
|
||||
let prior: Value = serde_json::from_str(&observed.context("missing stored token")?)?;
|
||||
let prior_identity = Row::read(&prior, &self.external_condition)?;
|
||||
ensure!(
|
||||
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,
|
||||
"zero_asset_id":assets::id(&self.market,&self.zero_outcome),"tokens":self.data.len()}),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
struct SnapshotState {
|
||||
closed: bool,
|
||||
resolved: bool,
|
||||
price: Option<f64>,
|
||||
}
|
||||
|
||||
impl SnapshotState {
|
||||
fn read(data: &Value) -> Result<Self> {
|
||||
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<i64> = 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(())
|
||||
}
|
||||
|
||||
/// An existing market mapping that can be refreshed from its upstream directory.
|
||||
pub struct PolymarketBinding {
|
||||
pub market: String,
|
||||
pub condition: String,
|
||||
pub zero_outcome: String,
|
||||
pub token_ids: Vec<String>,
|
||||
}
|
||||
|
||||
impl crate::Exchange {
|
||||
pub fn polymarket_bindings(&self, market: Option<&str>) -> Result<Vec<PolymarketBinding>> {
|
||||
let mut stmt = self.db.prepare_cached(
|
||||
"SELECT m.market,m.condition_id,m.zero_outcome,t.token_id
|
||||
FROM polymarket_market_aliases m JOIN polymarket_token_aliases t USING(condition_id)
|
||||
WHERE ?1 IS NULL OR m.market=?1
|
||||
ORDER BY m.market,t.token_id",
|
||||
)?;
|
||||
let mut rows = stmt.query([market])?;
|
||||
let mut bindings: Vec<PolymarketBinding> = Vec::new();
|
||||
while let Some(row) = rows.next()? {
|
||||
let market: String = row.get(0)?;
|
||||
if let Some(last) = bindings.last_mut().filter(|last| last.market == market) {
|
||||
last.token_ids.push(row.get(3)?);
|
||||
} else {
|
||||
bindings.push(PolymarketBinding {
|
||||
market,
|
||||
condition: row.get(1)?,
|
||||
zero_outcome: row.get(2)?,
|
||||
token_ids: vec![row.get(3)?],
|
||||
});
|
||||
}
|
||||
}
|
||||
ensure!(
|
||||
market.is_none() || !bindings.is_empty(),
|
||||
"market has no Polymarket binding"
|
||||
);
|
||||
Ok(bindings)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
WITH selectors AS (
|
||||
SELECT key AS ordinal, json_extract(value,'$[0]') AS id,
|
||||
json_extract(value,'$[2]') AS kind
|
||||
FROM json_each(?1)
|
||||
), selector_ranges AS (
|
||||
-- The full Neg Risk event ID has a zero question index and outcome byte.
|
||||
-- Its 62-digit form still selects just the first condition.
|
||||
SELECT *,
|
||||
CASE WHEN kind='condition' AND length(id)=66
|
||||
AND substr(id,1,4)='0x02' AND substr(id,61)='000000'
|
||||
THEN substr(id,1,60)||'ffff00' END AS structural_event_end
|
||||
FROM selectors
|
||||
)
|
||||
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,o.observed_at_ms
|
||||
FROM selector_ranges 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'
|
||||
OR (t.module='neg_risk' AND t.structure BETWEEN s.id AND s.structural_event_end)))
|
||||
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
|
||||
@@ -0,0 +1,141 @@
|
||||
use crate::{assets, inventory::decimal, Exchange, MarketDataError};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
use std::collections::HashSet;
|
||||
|
||||
const MAX_TOKEN: &str =
|
||||
"115792089237316195423570985008687907853269984665640564039457584007913129639935";
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct TokenDirectoryQuery {
|
||||
#[serde(alias = "token_ids")]
|
||||
token_id: Option<String>,
|
||||
#[serde(alias = "condition_id", alias = "conditionId")]
|
||||
condition: Option<String>,
|
||||
}
|
||||
|
||||
fn invalid(message: impl Into<String>) -> MarketDataError {
|
||||
MarketDataError::Invalid(message.into())
|
||||
}
|
||||
|
||||
pub(crate) fn condition_hex(value: &str) -> Option<String> {
|
||||
let hex = value
|
||||
.strip_prefix("0x")
|
||||
.or_else(|| value.strip_prefix("0X"))?;
|
||||
if !matches!(hex.len(), 62 | 64) || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
|
||||
return None;
|
||||
}
|
||||
Some(format!("0x{}", hex.to_ascii_lowercase()))
|
||||
}
|
||||
|
||||
pub(crate) fn decimal_token(value: &str) -> Option<&str> {
|
||||
let digits = value.trim_start_matches('0');
|
||||
if value.is_empty()
|
||||
|| !value.bytes().all(|b| b.is_ascii_digit())
|
||||
|| digits.len() > MAX_TOKEN.len()
|
||||
|| (digits.len() == MAX_TOKEN.len() && digits > MAX_TOKEN)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some(if digits.is_empty() { "0" } else { digits })
|
||||
}
|
||||
|
||||
impl Exchange {
|
||||
pub fn public_tokens(&self, query: TokenDirectoryQuery) -> Result<Value, MarketDataError> {
|
||||
let token = query.token_id.as_deref().filter(|s| !s.trim().is_empty());
|
||||
let condition = query.condition.as_deref().filter(|s| !s.trim().is_empty());
|
||||
let (raw, is_token, limit, selector) = match (token, condition) {
|
||||
(Some(raw), None) => (raw, true, 50, "token_id"),
|
||||
(None, Some(raw)) => (raw, false, 10, "condition"),
|
||||
_ => return Err(invalid("provide exactly one of 'token_id' or 'condition'")),
|
||||
};
|
||||
let tx = self.db.unchecked_transaction()?;
|
||||
let mut seen = HashSet::new();
|
||||
let mut keys = Vec::new();
|
||||
for value in raw.split(',').map(str::trim) {
|
||||
let (key, outcome, kind) = if is_token {
|
||||
if let Ok((outcome, market)) = assets::parse_id(value) {
|
||||
(market.to_owned(), Some(outcome), "local_token")
|
||||
} else {
|
||||
let token = decimal_token(value)
|
||||
.ok_or_else(|| invalid(format!("invalid token id: {value}")))?;
|
||||
(token.to_owned(), None, "external_token")
|
||||
}
|
||||
} else if let Some(hex) = condition_hex(value) {
|
||||
(hex, None, "condition")
|
||||
} else {
|
||||
let listed: bool = tx.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM markets WHERE id=?1)
|
||||
OR EXISTS(SELECT 1 FROM neg_risk_groups WHERE id=?1)",
|
||||
[value],
|
||||
|row| row.get(0),
|
||||
)?;
|
||||
if !listed {
|
||||
return Err(invalid(format!("invalid condition id: {value}")));
|
||||
}
|
||||
(value.to_owned(), None, "condition")
|
||||
};
|
||||
if seen.insert((key.clone(), outcome)) {
|
||||
if seen.len() > limit {
|
||||
return Err(invalid(format!(
|
||||
"'{selector}' accepts at most {limit} distinct values"
|
||||
)));
|
||||
}
|
||||
keys.push((key, outcome, kind));
|
||||
}
|
||||
}
|
||||
let input = serde_json::to_string(&keys).map_err(|_| MarketDataError::Unavailable)?;
|
||||
let mut data = {
|
||||
let mut stmt = tx.prepare_cached(include_str!("token_directory.sql"))?;
|
||||
let rows = stmt.query_map([&input], |r| {
|
||||
let market: String = r.get(0)?;
|
||||
let phase: String = r.get(5)?;
|
||||
let winner: Option<String> = r.get(6)?;
|
||||
let index: i64 = r.get(7)?;
|
||||
let (outcome, other) = if index == 0 { ("YES", "NO") } else { ("NO", "YES") };
|
||||
let group: Option<String> = r.get(8)?;
|
||||
let price = winner.as_deref().filter(|_| phase=="resolved").map(|winner| {
|
||||
if winner == "VOID" { decimal(5,10) } else { decimal(i128::from(winner == outcome),1) }
|
||||
});
|
||||
Ok((r.get::<_, i64>(12)?, json!({
|
||||
"token_id":assets::id(&market,outcome),"condition_id":market,
|
||||
"structural_condition_id":null,"module":if group.is_some() { "local_neg_risk" } else { "local_binary" },
|
||||
"outcome_index":index,"clob_index":null,"outcome":r.get::<_,String>(if index==0 {3} else {4})?,
|
||||
"opposite_token_id":assets::id(&market,other),
|
||||
"resolved":phase=="resolved","closed":matches!(phase.as_str(),"closed"|"resolved"),
|
||||
"final_price":price,"title":r.get::<_,String>(1)?,"market_slug":r.get::<_,String>(2)?,
|
||||
"neg_risk":group.is_some(),"neg_risk_market_id":group,"question_index":r.get::<_,Option<i64>>(9)?,
|
||||
"event_id":r.get::<_,Option<i64>>(10)?,"event_slug":r.get::<_,Option<String>>(11)?
|
||||
})))
|
||||
})?;
|
||||
rows.collect::<rusqlite::Result<Vec<_>>>()?
|
||||
};
|
||||
let externals = {
|
||||
let mut stmt = tx.prepare_cached(include_str!("token_aliases.sql"))?;
|
||||
let rows = stmt.query_map([&input], |r| {
|
||||
Ok((
|
||||
r.get::<_, i64>(0)?,
|
||||
r.get::<_, String>(1)?,
|
||||
r.get::<_, String>(2)?,
|
||||
r.get::<_, String>(3)?,
|
||||
r.get::<_, Option<i64>>(4)?,
|
||||
))
|
||||
})?;
|
||||
rows.collect::<rusqlite::Result<Vec<_>>>()?
|
||||
};
|
||||
let external_ordinals: HashSet<_> = externals.iter().map(|r| r.0).collect();
|
||||
data.retain(|(ordinal, _)| !external_ordinals.contains(ordinal));
|
||||
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);
|
||||
let data: Vec<_> = data.into_iter().map(|(_, row)| row).collect();
|
||||
tx.commit()?;
|
||||
Ok(json!({"data":data}))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
WITH selectors AS (
|
||||
SELECT key AS ordinal, json_extract(value,'$[0]') AS market,
|
||||
json_extract(value,'$[1]') AS outcome, json_extract(value,'$[2]') AS kind
|
||||
FROM json_each(?1)
|
||||
), markets_selected AS (
|
||||
SELECT s.ordinal,m.id AS market,s.outcome
|
||||
FROM selectors s JOIN markets m ON m.id=s.market
|
||||
WHERE s.kind<>'external_token'
|
||||
UNION ALL
|
||||
SELECT s.ordinal,n.market,NULL
|
||||
FROM selectors s JOIN neg_risk_members n ON n.group_id=s.market
|
||||
WHERE s.kind='condition' AND s.outcome IS NULL AND NOT EXISTS (SELECT 1 FROM markets m WHERE m.id=s.market)
|
||||
), slots(outcome, outcome_index) AS (VALUES ('YES',0),('NO',1))
|
||||
SELECT m.id,w.question,w.slug,w.yes_label,w.no_label,m.phase,m.winner,s.outcome_index,
|
||||
n.group_id,n.ordinal,e.event_id,e.slug,x.ordinal
|
||||
FROM markets_selected x JOIN markets m ON m.id=x.market
|
||||
JOIN market_wire_metadata w ON w.market=x.market
|
||||
JOIN slots s ON x.outcome IS NULL OR s.outcome=x.outcome
|
||||
LEFT JOIN neg_risk_members n ON n.market=x.market
|
||||
LEFT JOIN listed_markets l ON l.market=x.market
|
||||
LEFT JOIN numbered_events e ON e.id=l.event
|
||||
ORDER BY x.ordinal,n.ordinal,m.id,s.outcome_index
|
||||
@@ -4178,3 +4178,193 @@ fn order_submission_terms_survive_fills_cancel_retries_and_legacy_upgrade() {
|
||||
assert_eq!(e.execute(cmd.clone()).unwrap()["orders"][0], expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn public_token_directory_routes_results_and_expands_negative_risk_groups() {
|
||||
let mut exchange = Exchange::open(":memory:").unwrap();
|
||||
for line in include_str!("../../../docs/examples/neg-risk.jsonl")
|
||||
.lines()
|
||||
.take(5)
|
||||
{
|
||||
exchange
|
||||
.execute(serde_json::from_str(line).unwrap())
|
||||
.unwrap();
|
||||
}
|
||||
let read = |e: &Exchange, value| {
|
||||
e.public_tokens(serde_json::from_value(value).unwrap())
|
||||
.unwrap()["data"]
|
||||
.clone()
|
||||
};
|
||||
let group = read(&exchange, json!({"condition":"winner"}));
|
||||
assert_eq!(group.as_array().unwrap().len(), 6);
|
||||
assert_eq!(group[0]["condition_id"], "a");
|
||||
assert_eq!(group[0]["question_index"], 0);
|
||||
assert_eq!(group[1]["opposite_token_id"], group[0]["token_id"]);
|
||||
assert_eq!(group[4]["condition_id"], "other");
|
||||
assert!(group[0]["event_id"].is_number());
|
||||
let rows = read(
|
||||
&exchange,
|
||||
json!({"token_ids":"eb:NO:a,123,eb:YES:a,eb:NO:a"}),
|
||||
);
|
||||
assert_eq!(rows, json!([group[1], group[0]]));
|
||||
assert_eq!(rows[0]["final_price"], Value::Null);
|
||||
setup(&mut exchange);
|
||||
exchange
|
||||
.execute(json!({"op":"close","id":"close-e","market":"e"}))
|
||||
.unwrap();
|
||||
exchange
|
||||
.execute(json!({"op":"finalize","id":"void-e","market":"e","winner":"VOID"}))
|
||||
.unwrap();
|
||||
let voided = read(&exchange, json!({"conditionId":"e"}));
|
||||
assert_eq!(voided[0]["closed"], true);
|
||||
assert_eq!(voided[1]["resolved"], true);
|
||||
assert_eq!(voided[0]["final_price"], 0.5);
|
||||
assert_eq!(voided[1]["final_price"], 0.5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn polymarket_asset_bindings_preserve_protocols_and_explicit_outcome_direction() {
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("venue-ids.db");
|
||||
let mut e = Exchange::open(&path).unwrap();
|
||||
setup(&mut e);
|
||||
let fixture: Value = serde_json::from_str(include_str!(
|
||||
"../../../docs/examples/polymarket-asset-binding.json"
|
||||
))
|
||||
.unwrap();
|
||||
let mut command = json!({"op":"bind_polymarket_assets","id":"bind","market":"e","zero_outcome":"NO",
|
||||
"external_condition":fixture["external_condition"], "data":fixture["data"]});
|
||||
let receipt = e.execute(command.clone()).unwrap();
|
||||
assert_eq!(receipt["tokens"], 4);
|
||||
assert_eq!(e.execute(command.clone()).unwrap(), receipt);
|
||||
command["id"] = json!("flipped");
|
||||
command["zero_outcome"] = json!("YES");
|
||||
assert!(e.execute(command).is_err());
|
||||
drop(e);
|
||||
let e = Exchange::open(path).unwrap();
|
||||
let lookup = |query| {
|
||||
e.public_tokens(serde_json::from_value(query).unwrap())
|
||||
.unwrap()
|
||||
};
|
||||
let condition = lookup(json!({"condition":fixture["external_condition"]}));
|
||||
let rows = condition["data"].as_array().unwrap();
|
||||
assert_eq!(rows.len(), 4);
|
||||
assert_eq!(rows[0]["module"], "v1_ctf");
|
||||
assert_eq!(rows[2]["module"], "neg_risk");
|
||||
assert_eq!(rows[2]["local_asset_id"], "eb:NO:e");
|
||||
assert_eq!(rows[3]["local_asset_id"], "eb:YES:e");
|
||||
let structural = rows[2]["structural_condition_id"].as_str().unwrap();
|
||||
assert_eq!(
|
||||
lookup(json!({"condition":&structural[..64]}))["data"],
|
||||
json!([rows[2], rows[3]])
|
||||
);
|
||||
let token = rows[3]["token_id"].as_str().unwrap();
|
||||
assert_eq!(
|
||||
lookup(json!({"token_id":format!("00{token},00123,eb:NO:e")}))["data"][0],
|
||||
rows[3]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn structural_event_expands_registered_position_pairs_and_compact_condition_selects_one() {
|
||||
let mut engine = Exchange::open(":memory:").unwrap();
|
||||
let fixture: Value = serde_json::from_str(include_str!(
|
||||
"../../../docs/examples/polymarket-token-event.json"
|
||||
))
|
||||
.unwrap();
|
||||
let rows = fixture["data"].as_array().unwrap();
|
||||
// Register in reverse order so lookup cannot rely on insertion order.
|
||||
for pair in rows.chunks_exact(4).rev() {
|
||||
let question = pair[0]["question_index"].as_i64().unwrap();
|
||||
let market = format!("match-winner-{question}");
|
||||
engine
|
||||
.execute(json!({"op":"list","id":format!("list-{question}"),
|
||||
"market":market,"rules":"Registered match winner"}))
|
||||
.unwrap();
|
||||
engine
|
||||
.execute(
|
||||
json!({"op":"bind_polymarket_assets","id":format!("bind-{question}"),
|
||||
"market":market,"zero_outcome":"YES","external_condition":pair[0]["condition_id"],
|
||||
"data":pair}),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
let lookup = |condition: &str| {
|
||||
engine
|
||||
.public_tokens(serde_json::from_value(json!({"condition":condition})).unwrap())
|
||||
.unwrap()["data"]
|
||||
.clone()
|
||||
};
|
||||
let event = rows[2]["structural_condition_id"].as_str().unwrap();
|
||||
let expanded = lookup(event);
|
||||
let positions = expanded.as_array().unwrap();
|
||||
assert_eq!(positions.len(), 6);
|
||||
for (position, captured) in positions
|
||||
.iter()
|
||||
.zip(rows.iter().filter(|r| r["module"] == "neg_risk"))
|
||||
{
|
||||
assert_eq!(position["token_id"], captured["token_id"]);
|
||||
assert_eq!(position["question_index"], captured["question_index"]);
|
||||
}
|
||||
|
||||
let compact = &event[..64];
|
||||
assert_eq!(lookup(compact), json!([positions[0], positions[1]]));
|
||||
let question_two = rows[10]["structural_condition_id"].as_str().unwrap();
|
||||
assert_eq!(lookup(question_two), json!([positions[4], positions[5]]));
|
||||
let legacy_group = rows[0]["neg_risk_market_id"].as_str().unwrap();
|
||||
assert_eq!(lookup(legacy_group).as_array().unwrap().len(), 12);
|
||||
let legacy_condition = rows[0]["condition_id"].as_str().unwrap();
|
||||
assert_eq!(lookup(legacy_condition).as_array().unwrap().len(), 4);
|
||||
}
|
||||
|
||||
#[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);
|
||||
}
|
||||
@@ -8,17 +8,6 @@ cargo run --locked -p venue-probe
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
main -->|核对 CTF 权重| ctf["src/ctf_resolution.rs"]
|
||||
main -->|核对 V2 模块权重| position["src/position_resolution.rs"]
|
||||
main -->|核对组合盘兑付| combo["src/combo_payout.rs"]
|
||||
main -->|区分互斥组直接与推导兑付| negrisk["src/neg_risk_resolution.rs"]
|
||||
negrisk -->|模块和 ABI 校验| position
|
||||
negrisk -->|最终确认区块与合约错误| rpc
|
||||
combo -->|查询模块注册表| position
|
||||
combo -->|执行最终区块调用| rpc
|
||||
position -->|解析目录及结果 ID| catalog
|
||||
position -->|读取最终确认区块| rpc["src/polygon_rpc.rs"]
|
||||
ctf -->|读取最终确认区块| rpc
|
||||
main["src/main.rs"] -->|依次调用两个只读探针| impls["src/probes.rs"]
|
||||
main -->|重放 Gamma 市场| catalog["src/catalog.rs"]
|
||||
impls -->|识别持仓协议及两套 ID| catalog
|
||||
@@ -134,118 +123,3 @@ sequenceDiagram
|
||||
2026-12-03 06:55 UTC 采集的[同侧报价快照](fixtures/live-side-prices.json)按请求保存前后盘口、报价、时间、方法及响应。双侧盘口最优价为 0.039 和 0.04。缺买盘的结果返回 BUY 字符串 0,缺卖盘的结果返回 SELL 字符串 1。批量 POST 返回相同字符串。文档列出的逗号分隔 GET 在这次生产取样返回 400。三个资产的前后盘口哈希各自一致。[官方单价接口](https://docs.polymarket.com/api-reference/market-data/get-market-price)
|
||||
|
||||
[电竞盘双空样本](fixtures/live-empty-prices.json)保留前后盘口和两次价格请求。两个深度数组均为空,公开 BUY 返回 "0",SELL 返回 "1"。探针把该结果计为已验证的空盘报价,实际可成交数量仍为零。
|
||||
|
||||
## Polygon CTF 裁决核对
|
||||
|
||||
`venue-probe --inspect-resolution CONDITION [EXPECTED]` 读取 Polygon 主网 CTF 的二元条件。默认使用 PublicNode,可通过 `EVENTBOOK_POLYGON_RPC_URL` 更换 HTTPS RPC。将输出保存为 JSON 后,`venue-probe --replay-resolution FILE [EXPECTED]` 可离线核对原始 ABI 字。`EXPECTED` 可用 `first`、`second`、`split`、`weighted`、`unresolved` 或 `unprepared`。前两个值指目录结果顺序,使用者应按已核实的结果映射指定预期。给出预期且不一致时,命令保留报告并以非零状态退出。
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
actor C as 调用者
|
||||
participant P as venue-probe
|
||||
participant N as Polygon RPC
|
||||
alt 现场读取
|
||||
C->>P: inspect-resolution CONDITION
|
||||
P->>N: 核对主网链 ID 及已最终确认区块
|
||||
P->>N: 在该区块读取结果数、分母和各侧权重
|
||||
P->>N: 复核区块哈希
|
||||
else 离线重放
|
||||
C->>P: replay-resolution FILE
|
||||
end
|
||||
P-->>C: 返回原始 ABI 字、十进制权重和对照结果
|
||||
```
|
||||
|
||||
[实测记录](fixtures/live-ctf-resolution.json)保存了两个独立节点一致返回的区块和权重。该市场的 Gamma 目录结果顺序为 Over、Under,链上分子为 0、1,分母为 1。探针只读取 CTF 的合约状态。结果由所选 RPC 提供,仅覆盖 CTF 二元条件。PositionManager 的读取路径见下节。链上状态证明仍待接入。[Gamma 封盘样本](../../docs/examples/public-closed-chart-history.json) · [Polymarket 合约清单](https://docs.polymarket.com/resources/contracts) · [Conditional Tokens 合约](https://github.com/gnosis/conditional-tokens-contracts/blob/master/contracts/ConditionalTokens.sol)
|
||||
|
||||
## Polygon PositionManager V2 裁决核对
|
||||
|
||||
`venue-probe --inspect-position-resolution MARKET_JSON [EXPECTED]` 读取一条原始 Gamma V2 市场。Gamma 可能将 31 字节条件以尾部补零的 32 字节形式返回。通过两个 Position ID 核对条件和结果顺序后,按条件首字节从 PositionManager 查找 Binary 或 NegRisk 模块,并从该模块读取兑付权重。与 CTF 命令共用 Polygon RPC 配置。两次调用都绑定到同一最终确认区块,并在返回结果前复核区块哈希。[模块注册表](https://github.com/Polymarket/polymarket-v2-external/blob/main/docs/position-manager.md) · [Position ID 编码](https://github.com/Polymarket/polymarket-v2-external/blob/main/docs/position-ids.md) · [模块源码说明](https://github.com/Polymarket/polymarket-v2-external/blob/main/docs/modules.md)
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
actor U as 调用者
|
||||
participant P as venue-probe
|
||||
participant R as Polygon RPC
|
||||
participant M as PositionManager
|
||||
participant S as Binary 或 NegRisk 模块
|
||||
U->>P: inspect-position-resolution MARKET_JSON
|
||||
P->>P: 从两个 Position ID 核对条件与结果顺序
|
||||
P->>R: eth_chainId 与 finalized 区块
|
||||
R-->>P: 137、区块号和哈希
|
||||
P->>R: 在指定区块调用 moduleById
|
||||
R->>M: moduleById(module_id)
|
||||
M-->>R: 已注册的模块代理
|
||||
R-->>P: 模块代理地址
|
||||
P->>R: 在同一区块调用 getResult
|
||||
R->>S: getResult(condition_id)
|
||||
S-->>R: 空数组或两个权重
|
||||
R-->>P: 原始 ABI 字
|
||||
P->>R: 复核同一区块哈希
|
||||
R-->>P: 区块号和哈希
|
||||
P-->>U: 目录结果、合约、区块、原始 ABI 和兑付状态
|
||||
```
|
||||
|
||||
`venue-probe --replay-position-resolution crates/venue-probe/fixtures/live-position-resolutions.json first` 可重放生产 Binary 样本。两个 Polygon 节点在区块 `0x5df5912` 返回同一模块地址与兑付权重 `[1000000, 0]`,对应目录第一结果获胜。空权重数组报告为 `unresolved`。已兑付状态按数组值报告为 `first`、`second`、`split` 或 `weighted`。提供预期时,任何结果不符都会在输出报告后返回非零状态。NegRisk 的权重约束有离线回归用例,生产目录与链上结果的对应仍待验证。组合盘使用下节介绍的独立模块。预言机证明和本地账本入账仍待覆盖。[双节点原始样本](fixtures/live-position-resolutions.json) · [合约部署地址](https://docs.polymarket.com/resources/contracts)
|
||||
|
||||
## Polygon 组合盘兑付核对
|
||||
|
||||
`venue-probe --inspect-combo-payout CONDITION AMOUNT_MICROS` 读取组合条件。有登记的腿时,以同一个正整数微份数分别查询 YES 与 NO。当前结论由状态和逐侧兑付金额表达。空腿数组表示 `unprepared`,两侧均返回合约的 `PositionNotRedeemable()` 表示 `unresolved`,两侧都成功返回金额表示 `redeemable`。其他错误会使探针退出。即使 NO 兑付全额,也可能还有腿尚未裁决。[官方组合模块](https://github.com/Polymarket/polymarket-v2-external/blob/main/src/modules/CombinatorialModule.sol)
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
actor U as 调用者
|
||||
participant P as venue-probe
|
||||
participant R as Polygon RPC
|
||||
participant M as PositionManager
|
||||
participant C as CombinatorialModule
|
||||
U->>P: inspect-combo-payout CONDITION AMOUNT_MICROS
|
||||
P->>R: 获取 Polygon 最终确认区块
|
||||
P->>R: 在指定区块查询 moduleById(3)
|
||||
R->>M: 查询组合模块代理
|
||||
M-->>R: 模块地址
|
||||
R-->>P: 已登记的模块地址
|
||||
P->>R: 在同一区块查询 getLegs
|
||||
R->>C: 查询组合的腿
|
||||
C-->>R: Position ID 数组
|
||||
R-->>P: 原始数组
|
||||
opt 有登记的腿
|
||||
loop YES 和 NO 各一次
|
||||
P->>R: 在同一区块查询 getPayout
|
||||
R->>C: 当前方向 Position ID 和份额
|
||||
C-->>R: 兑付整数金额或合约错误
|
||||
R-->>P: 原始结果
|
||||
end
|
||||
end
|
||||
P->>R: 复核同一区块哈希
|
||||
P-->>U: 组合腿、待裁决状态或逐侧兑付
|
||||
```
|
||||
|
||||
`venue-probe --replay-combo-payout crates/venue-probe/fixtures/live-combo-payouts.json` 重放两个真实链上组合。一个组合的两侧均待裁决,另一个按 1000001 微份查询,YES 兑付 0,NO 兑付全部 1000001 微美元。该组合的 4 条腿中,一条已裁决为零赔付,另外三条仍待裁决。样本包含登记交易哈希、区块及 ABI 原始返回,仍缺少前端和 RFQ 的同盘关联。[原始样本](fixtures/live-combo-payouts.json)
|
||||
|
||||
## Polygon 互斥组的直接报告与推导
|
||||
|
||||
`venue-probe --inspect-neg-risk-event EVENT_ID INDICES` 接受 V2 互斥事件 ID 和逗号分隔的条件索引。索引从零开始,等于真实条件总数时表示合成的「其他」。命令从已确认区块读取计数与旧版迁移标记,并分别读取各选定条件的有效兑付 `getResult` 与原始存储 `result(conditionId, 0)`。有效兑付和事件计数符合推导规则且原始结果为空时,标为 `derived`。存储里有结果时标为 `stored`。RPC 或 ABI 异常会终止核对。[官方 NegRisk 模块](https://github.com/Polymarket/polymarket-v2-external/blob/main/docs/modules.md#negriskmodule-moduleid--2) · [合约原始结果定义](https://github.com/Polymarket/polymarket-v2-external/blob/main/src/modules/abstract/BaseModule.sol)
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
actor U as 调用者
|
||||
participant P as venue-probe
|
||||
participant R as Polygon RPC
|
||||
participant N as NegRiskModule
|
||||
U->>P: inspect-neg-risk-event EVENT_ID INDICES
|
||||
P->>R: 读取最终确认区块和模块注册表
|
||||
P->>R: 查询真实条件数、直接报告数、YES 总权重和迁移标记
|
||||
R->>N: 在指定区块读取计数
|
||||
N-->>R: 事件计数与权重
|
||||
R-->>P: ABI 整数字
|
||||
loop 选中的每个条件索引
|
||||
P->>R: 读取 getResult 和原始 result
|
||||
R->>N: 查询有效兑付和直接存储
|
||||
N-->>R: 有效数组及存储整数或空回退
|
||||
R-->>P: 两种结果的原始返回
|
||||
end
|
||||
P->>R: 复核区块哈希
|
||||
P-->>U: 逐条件兑付与可核对的来源
|
||||
```
|
||||
|
||||
离线命令为 `venue-probe --replay-neg-risk-event crates/venue-probe/fixtures/live-negrisk-resolution.json`。样本记录赢家出现前后的有效结果与直接存储。区块 `0x5df5c44` 的三条件组中,「其他」没有直接存储,但已经可以按 NO 兑付。区块 `0x5df5c62` 的 37 条件组有 33 个直接报告,四个尚未报告的真实条件仍待裁决,合成「其他」已可按 NO 兑付。旧版事件标识和链上反向映射将这些条件对应到 Gamma 的足球精确比分盘。同一区块中,四个待裁决条件对应的旧 CTF 合约兑付分母均为 1,V2 仍等待迁移裁决。[原始样本](fixtures/live-negrisk-resolution.json)
|
||||
@@ -1,42 +0,0 @@
|
||||
[
|
||||
{
|
||||
"chain_id": 137,
|
||||
"block_number": "0x5df5ab2",
|
||||
"block_hash": "0x14e566bc1e5b4acf05706c9a59f0ba01d9064db8404fd020317c32894d49a83d",
|
||||
"condition_id": "0x034bd7384b7f58f2a267c90e5f2c45d865000000000000000000000000000000",
|
||||
"amount_micros": 1000001,
|
||||
"registry": "0x00000000000000000000000030000034706c7d8e12009dab006be20000c031a8",
|
||||
"legs": "0x0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000b011006ceb374e5e03e0646de13010aaf710000000000000000000000000000010125dcc4e3014cac67374ad55d3bfa5039000000000000000000000000000000014ad9e4ceaa2d864b3e9eb9e685e7bf97000000000000000000000000000000015de9f8160adc8328f91acc2e9ab4465800000000000000000000000000000001820b68526eae7c48b92d51a512d4cd81000000000000000000000000000000019a1cc98bc041fbdd4ac95af0e5982dd000000000000000000000000000000101b9dec220c321c5006459f9acd1ea36ff00000000000000000000000000000101c3e3697c82867662dfcc4efa4747aaa900000000000000000000000000000101c6cc49ab6b18b159edfacedb661dcc0a00000000000000000000000000000001c8b8bb7625efac202c3857d38cc6ad0e00000000000000000000000000000001d06efb76e1836bce7f92507344277933000000000000000000000000000001",
|
||||
"payouts": [
|
||||
{
|
||||
"revert": "0xc003777b"
|
||||
},
|
||||
{
|
||||
"revert": "0xc003777b"
|
||||
}
|
||||
],
|
||||
"source": "https://polygon-bor-rpc.publicnode.com",
|
||||
"preparation_tx": "0xb826cb8d1e00086bdbb9aaecd29800cbb9b72a4311de0eac0f9cf3cfad0e81f7",
|
||||
"observed_at_ms": 1796491240143
|
||||
},
|
||||
{
|
||||
"chain_id": 137,
|
||||
"block_number": "0x5df5ab2",
|
||||
"block_hash": "0x14e566bc1e5b4acf05706c9a59f0ba01d9064db8404fd020317c32894d49a83d",
|
||||
"condition_id": "0x033f568c0a6209ea4beb141ae1e137177d000000000000000000000000000000",
|
||||
"amount_micros": 1000001,
|
||||
"registry": "0x00000000000000000000000030000034706c7d8e12009dab006be20000c031a8",
|
||||
"legs": "0x00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000004014375f1cab1f5e5e98c9014fff1de38c1000000000000000000000000000000019d2d7100e42a913a5a13db0380d3aba900000000000000000000000000000101c157597d55e31bbf2a93bc0b524c189200000000000000000000000000000101e23cbfdde8c236499dd947c83faf57a6000000000000000000000000000000",
|
||||
"payouts": [
|
||||
{
|
||||
"return": "0x0000000000000000000000000000000000000000000000000000000000000000"
|
||||
},
|
||||
{
|
||||
"return": "0x00000000000000000000000000000000000000000000000000000000000f4241"
|
||||
}
|
||||
],
|
||||
"source": "https://polygon-bor-rpc.publicnode.com",
|
||||
"preparation_tx": "0x8d77f8741cfbf4c6388d87aa90a6f4c2c238ac35fbecc02ab39671e2f0f8a7b9",
|
||||
"observed_at_ms": 1796491315981
|
||||
}
|
||||
]
|
||||
@@ -1,18 +0,0 @@
|
||||
{
|
||||
"chain_id": 137,
|
||||
"block_number": "0x5df5831",
|
||||
"block_hash": "0xf36806915eb4a8aa5ecb85d411a3259c9a65b1f1af65049e30e5098a32f6b45c",
|
||||
"condition_id": "0xdf04a0495b0a16dbce386acdc16d9aed19784db9888be53d150354b83b7c18b1",
|
||||
"contract": "0x4D97DCd97eC945f40cF65F87097ACe5EA0476045",
|
||||
"sources": [
|
||||
"https://polygon.drpc.org",
|
||||
"https://polygon-bor-rpc.publicnode.com"
|
||||
],
|
||||
"outcome_slots": "0x0000000000000000000000000000000000000000000000000000000000000002",
|
||||
"denominator": "0x0000000000000000000000000000000000000000000000000000000000000001",
|
||||
"numerators": [
|
||||
"0x0000000000000000000000000000000000000000000000000000000000000000",
|
||||
"0x0000000000000000000000000000000000000000000000000000000000000001"
|
||||
],
|
||||
"observed_at_ms": 1796490278240
|
||||
}
|
||||
@@ -1,242 +0,0 @@
|
||||
[
|
||||
{
|
||||
"chain_id": 137,
|
||||
"event_id": "0x026b8d75bfa676ec6e8c8d496b03036400000300000000000000000000000000",
|
||||
"block_number": "0x5df5c43",
|
||||
"block_hash": "0x210e92e62a26f17bb75c26b905f96c83180e54b51ab634f64da83c16c30130ca",
|
||||
"registry": "0x000000000000000000000000200000900045e3b6259600682756002200028933",
|
||||
"condition_count": "0x0000000000000000000000000000000000000000000000000000000000000003",
|
||||
"conditions_reported": "0x0000000000000000000000000000000000000000000000000000000000000000",
|
||||
"results_sum": "0x0000000000000000000000000000000000000000000000000000000000000000",
|
||||
"conditions": [
|
||||
{
|
||||
"index": 0,
|
||||
"effective": "0x00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000000",
|
||||
"stored_yes": {
|
||||
"revert": "0x"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 1,
|
||||
"effective": "0x00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000000",
|
||||
"stored_yes": {
|
||||
"revert": "0x"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 2,
|
||||
"effective": "0x00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000000",
|
||||
"stored_yes": {
|
||||
"revert": "0x"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 3,
|
||||
"effective": "0x00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000000",
|
||||
"stored_yes": {
|
||||
"revert": "0x"
|
||||
}
|
||||
}
|
||||
],
|
||||
"sources": [
|
||||
"https://polygon.drpc.org"
|
||||
],
|
||||
"legacy_event_id": "0x0a0374c2418aac1d34f5b9ee14f5a0446b8d75bfa676ec6e8c8d496b03036400"
|
||||
},
|
||||
{
|
||||
"chain_id": 137,
|
||||
"event_id": "0x026b8d75bfa676ec6e8c8d496b03036400000300000000000000000000000000",
|
||||
"block_number": "0x5df5c44",
|
||||
"block_hash": "0xee7aa65f66a4260474fcec3934ea21ab93f6003af041934a55d2547286cfaedb",
|
||||
"registry": "0x000000000000000000000000200000900045e3b6259600682756002200028933",
|
||||
"condition_count": "0x0000000000000000000000000000000000000000000000000000000000000003",
|
||||
"conditions_reported": "0x0000000000000000000000000000000000000000000000000000000000000003",
|
||||
"results_sum": "0x00000000000000000000000000000000000000000000000000000000000f4240",
|
||||
"conditions": [
|
||||
{
|
||||
"index": 0,
|
||||
"effective": "0x00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f4240",
|
||||
"stored_yes": {
|
||||
"return": "0x0000000000000000000000000000000000000000000000000000000000000000"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 1,
|
||||
"effective": "0x0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000f42400000000000000000000000000000000000000000000000000000000000000000",
|
||||
"stored_yes": {
|
||||
"return": "0x00000000000000000000000000000000000000000000000000000000000f4240"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 2,
|
||||
"effective": "0x00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f4240",
|
||||
"stored_yes": {
|
||||
"return": "0x0000000000000000000000000000000000000000000000000000000000000000"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 3,
|
||||
"effective": "0x00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f4240",
|
||||
"stored_yes": {
|
||||
"revert": "0x"
|
||||
}
|
||||
}
|
||||
],
|
||||
"sources": [
|
||||
"https://polygon.drpc.org"
|
||||
],
|
||||
"transition_tx": "0xaef081eb07769e30c2d79c45deff68f2c697b250d4b7c0f04afc2390e1d50250",
|
||||
"legacy_event_id": "0x0a0374c2418aac1d34f5b9ee14f5a0446b8d75bfa676ec6e8c8d496b03036400",
|
||||
"legacy_catalog": [
|
||||
{
|
||||
"condition_index": 0,
|
||||
"id": "7420052",
|
||||
"slug": "serc-acd-cit-2026-12-05-acd",
|
||||
"version": "v1",
|
||||
"conditionId": "0x031de2fd1570ce33ad6e59b50c5bf58d24661741bcc42c0dfd5e718fc4960128",
|
||||
"outcomes": "[\"Yes\", \"No\"]",
|
||||
"outcomePrices": "[\"0\", \"1\"]",
|
||||
"position_condition_id": "0x026b8d75bfa676ec6e8c8d496b03036400000300000000000000000000000000",
|
||||
"legacy_ctf_denominator": "0x0000000000000000000000000000000000000000000000000000000000000001"
|
||||
},
|
||||
{
|
||||
"condition_index": 1,
|
||||
"id": "7420053",
|
||||
"slug": "serc-acd-cit-2026-12-05-draw",
|
||||
"version": "v1",
|
||||
"conditionId": "0x71e48af45160c9f56010f46ad2d0915a29c861a3250d6592c1f1977c3fbfc8cc",
|
||||
"outcomes": "[\"Yes\", \"No\"]",
|
||||
"outcomePrices": "[\"1\", \"0\"]",
|
||||
"position_condition_id": "0x026b8d75bfa676ec6e8c8d496b03036400000300000000000000000000000100",
|
||||
"legacy_ctf_denominator": "0x0000000000000000000000000000000000000000000000000000000000000001"
|
||||
},
|
||||
{
|
||||
"condition_index": 2,
|
||||
"id": "7420054",
|
||||
"slug": "serc-acd-cit-2026-12-05-cit",
|
||||
"version": "v1",
|
||||
"conditionId": "0xc0671fbf4755c8b5b4eb94352e7c92b832f0263a9a0460225ad04412d45ac34e",
|
||||
"outcomes": "[\"Yes\", \"No\"]",
|
||||
"outcomePrices": "[\"0\", \"1\"]",
|
||||
"position_condition_id": "0x026b8d75bfa676ec6e8c8d496b03036400000300000000000000000000000200",
|
||||
"legacy_ctf_denominator": "0x0000000000000000000000000000000000000000000000000000000000000001"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"chain_id": 137,
|
||||
"event_id": "0x02a28dc7d450aef445cdcfc3b43a566800002500000000000000000000000000",
|
||||
"block_number": "0x5df5c62",
|
||||
"block_hash": "0xc60a077a550b53bb5dc4f960047b5be961f196574f6af91b799ed0f109e9e5d7",
|
||||
"registry": "0x000000000000000000000000200000900045e3b6259600682756002200028933",
|
||||
"condition_count": "0x0000000000000000000000000000000000000000000000000000000000000025",
|
||||
"conditions_reported": "0x0000000000000000000000000000000000000000000000000000000000000021",
|
||||
"results_sum": "0x00000000000000000000000000000000000000000000000000000000000f4240",
|
||||
"conditions": [
|
||||
{
|
||||
"index": 0,
|
||||
"effective": "0x00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f4240",
|
||||
"stored_yes": {
|
||||
"return": "0x0000000000000000000000000000000000000000000000000000000000000000"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 32,
|
||||
"effective": "0x00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000000",
|
||||
"stored_yes": {
|
||||
"revert": "0x"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 33,
|
||||
"effective": "0x00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000000",
|
||||
"stored_yes": {
|
||||
"revert": "0x"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 34,
|
||||
"effective": "0x00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000000",
|
||||
"stored_yes": {
|
||||
"revert": "0x"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 35,
|
||||
"effective": "0x00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000000",
|
||||
"stored_yes": {
|
||||
"revert": "0x"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 37,
|
||||
"effective": "0x00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f4240",
|
||||
"stored_yes": {
|
||||
"revert": "0x"
|
||||
}
|
||||
}
|
||||
],
|
||||
"sources": [
|
||||
"https://polygon.drpc.org"
|
||||
],
|
||||
"transition_tx": "0xa066409b2da62eab52aeae7e439cb11e1e28124a2e94d06c87a74bf42acc8286",
|
||||
"legacy_event_id": "0x1ec6befb358b06cb59c12fddd306b970a28dc7d450aef445cdcfc3b43a566800",
|
||||
"legacy_catalog": [
|
||||
{
|
||||
"condition_index": 0,
|
||||
"id": "7421956",
|
||||
"slug": "serc-acd-cit-2026-12-05-exact-score-0-0",
|
||||
"version": "v1",
|
||||
"conditionId": "0xaa7d72c3addfbd60609d2762ca945e39307da5e05c9aa9c24a8e979d6e2f52c0",
|
||||
"outcomes": "[\"Yes\", \"No\"]",
|
||||
"outcomePrices": "[\"0\", \"1\"]",
|
||||
"position_condition_id": "0x02a28dc7d450aef445cdcfc3b43a566800002500000000000000000000000000",
|
||||
"legacy_ctf_denominator": "0x0000000000000000000000000000000000000000000000000000000000000001"
|
||||
},
|
||||
{
|
||||
"condition_index": 32,
|
||||
"id": "7421988",
|
||||
"slug": "serc-acd-cit-2026-12-05-exact-score-5-3",
|
||||
"version": "v1",
|
||||
"conditionId": "0x99ba4cc23d2eb8733fc92c3775951f5d020b3304134015f7b60233d24cfb77a7",
|
||||
"outcomes": "[\"Yes\", \"No\"]",
|
||||
"outcomePrices": "[\"0\", \"1\"]",
|
||||
"position_condition_id": "0x02a28dc7d450aef445cdcfc3b43a566800002500000000000000000000002000",
|
||||
"legacy_ctf_denominator": "0x0000000000000000000000000000000000000000000000000000000000000001"
|
||||
},
|
||||
{
|
||||
"condition_index": 33,
|
||||
"id": "7421989",
|
||||
"slug": "serc-acd-cit-2026-12-05-exact-score-4-5",
|
||||
"version": "v1",
|
||||
"conditionId": "0xf2a796cbeefc2bce1bd00ce006464082eb47d08e1d0d65c93363388925e61c2c",
|
||||
"outcomes": "[\"Yes\", \"No\"]",
|
||||
"outcomePrices": "[\"0\", \"1\"]",
|
||||
"position_condition_id": "0x02a28dc7d450aef445cdcfc3b43a566800002500000000000000000000002100",
|
||||
"legacy_ctf_denominator": "0x0000000000000000000000000000000000000000000000000000000000000001"
|
||||
},
|
||||
{
|
||||
"condition_index": 34,
|
||||
"id": "7421990",
|
||||
"slug": "serc-acd-cit-2026-12-05-exact-score-5-4",
|
||||
"version": "v1",
|
||||
"conditionId": "0xb37245a4a512fef2f2e8b687fd2820896548f5d7f54ef080b8077f457d3aca91",
|
||||
"outcomes": "[\"Yes\", \"No\"]",
|
||||
"outcomePrices": "[\"0\", \"1\"]",
|
||||
"position_condition_id": "0x02a28dc7d450aef445cdcfc3b43a566800002500000000000000000000002200",
|
||||
"legacy_ctf_denominator": "0x0000000000000000000000000000000000000000000000000000000000000001"
|
||||
},
|
||||
{
|
||||
"condition_index": 35,
|
||||
"id": "7421991",
|
||||
"slug": "serc-acd-cit-2026-12-05-exact-score-5-5",
|
||||
"version": "v1",
|
||||
"conditionId": "0x8ff38f5d3a32276d5ec8cb5a6232652fa838fec77e22e081a7fd1cf1c45a33d3",
|
||||
"outcomes": "[\"Yes\", \"No\"]",
|
||||
"outcomePrices": "[\"0\", \"1\"]",
|
||||
"position_condition_id": "0x02a28dc7d450aef445cdcfc3b43a566800002500000000000000000000002300",
|
||||
"legacy_ctf_denominator": "0x0000000000000000000000000000000000000000000000000000000000000001"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
@@ -1,26 +0,0 @@
|
||||
[
|
||||
{
|
||||
"chain_id": 137,
|
||||
"block_number": "0x5df5912",
|
||||
"block_hash": "0x7bee6030d9cd7c98bc7f6ae18f89c5a5b8c3a912993f558658224cf0a98a4533",
|
||||
"market": {
|
||||
"id": "7543472",
|
||||
"slug": "setkameua-anat-illia-2026-12-03",
|
||||
"version": "v2",
|
||||
"conditionId": "0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000",
|
||||
"positionIds": [
|
||||
"759916398134244316868652908232832573045153963965173623897622651599218278400",
|
||||
"759916398134244316868652908232832573045153963965173623897622651599218278401"
|
||||
],
|
||||
"outcomePrices": "[\"1\", \"0\"]",
|
||||
"outcomes": "[\"Nikolenko Anatolii\", \"Fokin Illia\"]"
|
||||
},
|
||||
"registry": "0x0000000000000000000000001000008dd9001b968442c1000017eae6e0da00ba",
|
||||
"result": "0x0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000f42400000000000000000000000000000000000000000000000000000000000000000",
|
||||
"sources": [
|
||||
"https://polygon.drpc.org",
|
||||
"https://polygon-bor-rpc.publicnode.com"
|
||||
],
|
||||
"observed_at_ms": 1796490613542
|
||||
}
|
||||
]
|
||||
@@ -1,241 +0,0 @@
|
||||
use crate::{
|
||||
polygon_rpc::{hex_data, quantity, CallOutcome, FinalizedRpc, POLYGON_CHAIN_ID},
|
||||
position_resolution::{lookup_module, module_address, uint, POSITION_MANAGER},
|
||||
};
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use reqwest::blocking::Client;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
const MODULE: u8 = 3;
|
||||
const GET_LEGS: &str = "9989b1ed"; // getLegs(bytes31)
|
||||
const GET_PAYOUT: &str = "4c619e4c"; // getPayout(uint256,uint256)
|
||||
const NOT_REDEEMABLE: &str = "0xc003777b"; // PositionNotRedeemable()
|
||||
const MAX_LEGS: usize = 50;
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct Observation {
|
||||
chain_id: u64,
|
||||
block_number: String,
|
||||
block_hash: String,
|
||||
condition_id: String,
|
||||
amount_micros: u64,
|
||||
registry: String,
|
||||
legs: String,
|
||||
payouts: Option<[CallOutcome; 2]>,
|
||||
observed_at_ms: u64,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
source: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
preparation_tx: Option<String>,
|
||||
}
|
||||
|
||||
fn condition_word(condition: &str) -> Result<String> {
|
||||
let word = match condition.len() {
|
||||
64 => format!("{}00", hex_data(condition, 31)?),
|
||||
66 => hex_data(condition, 32)?.to_owned(),
|
||||
_ => anyhow::bail!("invalid combo condition ID length"),
|
||||
};
|
||||
ensure!(
|
||||
word.starts_with("03") && word.ends_with("00"),
|
||||
"expected a combinatorial condition with an empty outcome byte"
|
||||
);
|
||||
Ok(word.to_ascii_lowercase())
|
||||
}
|
||||
|
||||
fn legs(raw: &str) -> Result<Vec<&str>> {
|
||||
ensure!(
|
||||
(130..=130 + 64 * MAX_LEGS).contains(&raw.len()) && (raw.len() - 130) % 64 == 0,
|
||||
"invalid getLegs ABI size"
|
||||
);
|
||||
let data = hex_data(raw, (raw.len() - 2) / 2)?;
|
||||
let count = (data.len() - 128) / 64;
|
||||
ensure!(uint(&data[..64])? == 32, "invalid getLegs ABI offset");
|
||||
ensure!(
|
||||
uint(&data[64..128])? == count as u64,
|
||||
"invalid getLegs length"
|
||||
);
|
||||
let mut ids: Vec<&str> = Vec::with_capacity(count);
|
||||
for index in 0..count {
|
||||
let start = 128 + 64 * index;
|
||||
let id = &data[start..start + 64];
|
||||
ensure!(
|
||||
matches!(&id[..2], "01" | "02") && matches!(&id[62..], "00" | "01"),
|
||||
"invalid underlying position ID"
|
||||
);
|
||||
if let Some(previous) = ids.last() {
|
||||
ensure!(
|
||||
previous[..62].to_ascii_lowercase() < id[..62].to_ascii_lowercase(),
|
||||
"combo legs must be sorted with distinct conditions"
|
||||
);
|
||||
}
|
||||
ids.push(id);
|
||||
}
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
fn payout_status(
|
||||
payouts: Option<&[CallOutcome; 2]>,
|
||||
has_legs: bool,
|
||||
amount: u64,
|
||||
) -> Result<(&'static str, Option<[String; 2]>)> {
|
||||
match (has_legs, payouts) {
|
||||
(false, None) => Ok(("unprepared", None)),
|
||||
(true, Some([CallOutcome::Revert(yes), CallOutcome::Revert(no)]))
|
||||
if [yes, no]
|
||||
.iter()
|
||||
.all(|value| value.eq_ignore_ascii_case(NOT_REDEEMABLE)) =>
|
||||
{
|
||||
Ok(("unresolved", None))
|
||||
}
|
||||
(true, Some([CallOutcome::Return(yes), CallOutcome::Return(no)])) => {
|
||||
let yes = uint(hex_data(yes, 32)?)?;
|
||||
let no = uint(hex_data(no, 32)?)?;
|
||||
ensure!(
|
||||
yes.checked_add(no).is_some_and(|total| total <= amount),
|
||||
"combo payouts exceed the position amount"
|
||||
);
|
||||
Ok(("redeemable", Some([yes.to_string(), no.to_string()])))
|
||||
}
|
||||
_ => anyhow::bail!("inconsistent combo legs and payout responses"),
|
||||
}
|
||||
}
|
||||
|
||||
fn audit(obs: Observation) -> Result<Value> {
|
||||
ensure!(
|
||||
obs.chain_id == POLYGON_CHAIN_ID,
|
||||
"observation is not Polygon mainnet"
|
||||
);
|
||||
ensure!(obs.amount_micros > 0, "position amount must be positive");
|
||||
let block = quantity(&obs.block_number)?;
|
||||
hex_data(&obs.block_hash, 32)?;
|
||||
let condition = condition_word(&obs.condition_id)?;
|
||||
let target = module_address(&obs.registry, MODULE)?;
|
||||
let ids = legs(&obs.legs)?;
|
||||
let (status, payouts) =
|
||||
payout_status(obs.payouts.as_ref(), !ids.is_empty(), obs.amount_micros)?;
|
||||
let legs: Vec<_> = ids.iter().map(|id| format!("0x{id}")).collect();
|
||||
Ok(json!({
|
||||
"observation": obs,
|
||||
"block": block,
|
||||
"position_manager": POSITION_MANAGER,
|
||||
"module_contract": target,
|
||||
"condition_id": format!("0x{condition}"),
|
||||
"leg_position_ids": legs,
|
||||
"status": status,
|
||||
"payout_micros_yes_no": payouts,
|
||||
}))
|
||||
}
|
||||
|
||||
pub(crate) fn inspect(client: &Client, condition: &str, amount: &str) -> Result<Value> {
|
||||
let condition = condition_word(condition)?;
|
||||
let amount_micros: u64 = amount.parse().context("invalid microshare amount")?;
|
||||
ensure!(amount_micros > 0, "position amount must be positive");
|
||||
let block = FinalizedRpc::connect(client)?;
|
||||
let registry = lookup_module(&block, MODULE)?;
|
||||
let address = module_address(®istry, MODULE)?;
|
||||
let raw_legs = block.call(&address, &format!("0x{GET_LEGS}{condition}"))?;
|
||||
let payouts = if legs(&raw_legs)?.is_empty() {
|
||||
None
|
||||
} else {
|
||||
let call = |side: u8| {
|
||||
block.call_with_revert(
|
||||
&address,
|
||||
&format!(
|
||||
"0x{GET_PAYOUT}{}{side:02x}{amount_micros:064x}",
|
||||
&condition[..62]
|
||||
),
|
||||
NOT_REDEEMABLE,
|
||||
)
|
||||
};
|
||||
Some([call(0)?, call(1)?])
|
||||
};
|
||||
let observed_at_ms = block.confirm()?;
|
||||
audit(Observation {
|
||||
chain_id: POLYGON_CHAIN_ID,
|
||||
block_number: block.number,
|
||||
block_hash: block.hash,
|
||||
condition_id: format!("0x{condition}"),
|
||||
amount_micros,
|
||||
registry,
|
||||
legs: raw_legs,
|
||||
payouts,
|
||||
observed_at_ms,
|
||||
source: None,
|
||||
preparation_tx: None,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn replay(file: &str) -> Result<Vec<Value>> {
|
||||
let raw: Value = serde_json::from_reader(std::fs::File::open(file)?)?;
|
||||
let rows = match raw {
|
||||
Value::Array(rows) => rows,
|
||||
value => vec![value],
|
||||
};
|
||||
ensure!(!rows.is_empty(), "no combo observations in file");
|
||||
rows.into_iter()
|
||||
.map(|row| {
|
||||
audit(serde_json::from_value(
|
||||
row.get("observation").cloned().unwrap_or(row),
|
||||
)?)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn replays_production_combos_in_both_states() -> Result<()> {
|
||||
let [pending, terminal]: [Observation; 2] =
|
||||
serde_json::from_str(include_str!("../fixtures/live-combo-payouts.json"))?;
|
||||
let pending = audit(pending)?;
|
||||
let terminal = audit(terminal)?;
|
||||
assert_eq!(pending["status"], "unresolved");
|
||||
assert_eq!(pending["leg_position_ids"].as_array().unwrap().len(), 11);
|
||||
assert!(pending["payout_micros_yes_no"].is_null());
|
||||
assert_eq!(terminal["status"], "redeemable");
|
||||
assert_eq!(terminal["payout_micros_yes_no"], json!(["0", "1000001"]));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn separates_unprepared_zero_fractional_and_inconsistent_amounts() -> Result<()> {
|
||||
assert_eq!(payout_status(None, false, 10)?, ("unprepared", None));
|
||||
assert!(payout_status(None, true, 10).is_err());
|
||||
let success = |value: u64| CallOutcome::Return(format!("0x{value:064x}"));
|
||||
for amounts in [[0, 0], [2, 7], [10, 0]] {
|
||||
let payouts = amounts.map(success);
|
||||
assert_eq!(
|
||||
payout_status(Some(&payouts), true, 10)?,
|
||||
("redeemable", Some(amounts.map(|value| value.to_string())))
|
||||
);
|
||||
}
|
||||
assert!(payout_status(Some(&[success(4), success(7)]), true, 10).is_err());
|
||||
let pending = CallOutcome::Revert(NOT_REDEEMABLE.to_owned());
|
||||
assert!(payout_status(Some(&[success(0), pending]), true, 10).is_err());
|
||||
let unknown = || CallOutcome::Revert("0x00000000".to_owned());
|
||||
assert!(payout_status(Some(&[unknown(), unknown()]), true, 10).is_err());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validates_combo_condition_and_returned_leg_array() -> Result<()> {
|
||||
let condition = format!("03{}", "00".repeat(31));
|
||||
assert_eq!(
|
||||
condition_word(&format!("0x{}", &condition[..62]))?,
|
||||
condition
|
||||
);
|
||||
assert!(condition_word(&format!("0x{}01", &condition[..62])).is_err());
|
||||
let first = format!("01{}", "00".repeat(31));
|
||||
let opposite = format!("{}01", &first[..62]);
|
||||
let second = format!("02{}", "00".repeat(31));
|
||||
let array = |a: &str, b: &str| format!("0x{:064x}{:064x}{a}{b}", 32, 2);
|
||||
assert_eq!(legs(&array(&first, &second))?.len(), 2);
|
||||
assert!(legs(&array(&first, &opposite)).is_err());
|
||||
assert!(legs(&array(&second, &first)).is_err());
|
||||
assert!(legs(&array(&first, &condition)).is_err());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1,221 +0,0 @@
|
||||
use crate::polygon_rpc::{hex_data, quantity, word, FinalizedRpc, POLYGON_CHAIN_ID};
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use reqwest::blocking::Client;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
const CTF: &str = "0x4D97DCd97eC945f40cF65F87097ACe5EA0476045";
|
||||
// First four bytes of Keccak-256 of the public ABI signatures.
|
||||
const OUTCOME_SLOTS: &str = "d42dc0c2"; // getOutcomeSlotCount(bytes32)
|
||||
const PAYOUT_DENOMINATOR: &str = "dd34de67"; // payoutDenominator(bytes32)
|
||||
const PAYOUT_NUMERATOR: &str = "0504c814"; // payoutNumerators(bytes32,uint256)
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
struct Observation {
|
||||
chain_id: u64,
|
||||
block_number: String,
|
||||
block_hash: String,
|
||||
contract: String,
|
||||
condition_id: String,
|
||||
outcome_slots: String,
|
||||
denominator: String,
|
||||
numerators: Option<[String; 2]>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
observed_at_ms: Option<u64>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
sources: Vec<String>,
|
||||
}
|
||||
|
||||
fn add(a: [u8; 32], b: [u8; 32]) -> Result<[u8; 32]> {
|
||||
let mut result = [0; 32];
|
||||
let mut carry = 0;
|
||||
for i in (0..32).rev() {
|
||||
let sum = u16::from(a[i]) + u16::from(b[i]) + carry;
|
||||
result[i] = sum as u8;
|
||||
carry = sum >> 8;
|
||||
}
|
||||
ensure!(carry == 0, "CTF payout weights overflow uint256");
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
fn decimal(word: [u8; 32]) -> String {
|
||||
let mut digits = vec![0_u8];
|
||||
for byte in word {
|
||||
let mut carry = u16::from(byte);
|
||||
for digit in &mut digits {
|
||||
let n = u16::from(*digit) * 256 + carry;
|
||||
*digit = (n % 10) as u8;
|
||||
carry = n / 10;
|
||||
}
|
||||
while carry > 0 {
|
||||
digits.push((carry % 10) as u8);
|
||||
carry /= 10;
|
||||
}
|
||||
}
|
||||
digits
|
||||
.into_iter()
|
||||
.rev()
|
||||
.map(|digit| char::from(b'0' + digit))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn audit(obs: Observation, expected: Option<&str>) -> Result<Value> {
|
||||
ensure!(
|
||||
obs.chain_id == POLYGON_CHAIN_ID && obs.contract.eq_ignore_ascii_case(CTF),
|
||||
"observation is not from the configured Polygon CTF deployment"
|
||||
);
|
||||
let block = quantity(&obs.block_number)?;
|
||||
hex_data(&obs.block_hash, 32)?;
|
||||
hex_data(&obs.condition_id, 32)?;
|
||||
let n = word(&obs.outcome_slots)?;
|
||||
let d = word(&obs.denominator)?;
|
||||
let zero = [0; 32];
|
||||
let mut two = [0; 32];
|
||||
two[31] = 2;
|
||||
let (status, numerators) = match (n, obs.numerators.as_ref()) {
|
||||
(n, None) if n == zero && d == zero => ("unprepared", None),
|
||||
(n, Some(values)) if n == two => {
|
||||
let a = word(&values[0])?;
|
||||
let b = word(&values[1])?;
|
||||
ensure!(add(a, b)? == d, "CTF payout sum does not match denominator");
|
||||
let status = if d == zero {
|
||||
"unresolved"
|
||||
} else if a == zero {
|
||||
"second"
|
||||
} else if b == zero {
|
||||
"first"
|
||||
} else if a == b {
|
||||
"split"
|
||||
} else {
|
||||
"weighted"
|
||||
};
|
||||
(status, Some([decimal(a), decimal(b)]))
|
||||
}
|
||||
_ => anyhow::bail!("observation is not an unprepared or binary CTF condition"),
|
||||
};
|
||||
if let Some(expected) = expected {
|
||||
ensure!(
|
||||
matches!(
|
||||
expected,
|
||||
"unprepared" | "unresolved" | "first" | "second" | "split" | "weighted"
|
||||
),
|
||||
"invalid expected CTF payout status"
|
||||
);
|
||||
}
|
||||
Ok(
|
||||
json!({"observation":obs,"block":block,"status":status,"payout_denominator":decimal(d),
|
||||
"payout_numerators":numerators,"expected":expected,"matches":expected.map(|v|v==status)}),
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn inspect(client: &Client, condition: &str, expected: Option<&str>) -> Result<Value> {
|
||||
let cid = hex_data(condition, 32)?;
|
||||
let block = FinalizedRpc::connect(client)?;
|
||||
let slots = block.call(CTF, &format!("0x{OUTCOME_SLOTS}{cid}"))?;
|
||||
let slot_word = word(&slots)?;
|
||||
let mut two = [0; 32];
|
||||
two[31] = 2;
|
||||
ensure!(
|
||||
slot_word == [0; 32] || slot_word == two,
|
||||
"CTF condition has a nonbinary outcome count"
|
||||
);
|
||||
let denominator = block.call(CTF, &format!("0x{PAYOUT_DENOMINATOR}{cid}"))?;
|
||||
let numerators = if slot_word == two {
|
||||
Some([
|
||||
block.call(CTF, &format!("0x{PAYOUT_NUMERATOR}{cid}{:064x}", 0))?,
|
||||
block.call(CTF, &format!("0x{PAYOUT_NUMERATOR}{cid}{:064x}", 1))?,
|
||||
])
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let observed_at_ms = block.confirm()?;
|
||||
audit(
|
||||
Observation {
|
||||
chain_id: POLYGON_CHAIN_ID,
|
||||
block_number: block.number,
|
||||
block_hash: block.hash,
|
||||
contract: CTF.to_owned(),
|
||||
condition_id: condition.to_ascii_lowercase(),
|
||||
outcome_slots: slots,
|
||||
denominator,
|
||||
numerators,
|
||||
observed_at_ms: Some(observed_at_ms),
|
||||
sources: Vec::new(),
|
||||
},
|
||||
expected,
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn replay(file: &str, expected: Option<&str>) -> Result<Value> {
|
||||
let raw: Value = serde_json::from_reader(std::fs::File::open(file)?)?;
|
||||
let obs = serde_json::from_value(raw.get("observation").cloned().unwrap_or(raw))?;
|
||||
audit(obs, expected)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn fixture() -> Observation {
|
||||
serde_json::from_str(include_str!("../fixtures/live-ctf-resolution.json")).unwrap()
|
||||
}
|
||||
|
||||
fn abi(value: u64) -> String {
|
||||
format!("0x{value:064x}")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn captured_polymarket_ctf_paid_the_second_outcome() {
|
||||
let report = audit(fixture(), Some("second")).unwrap();
|
||||
assert_eq!(report["status"], "second");
|
||||
assert_eq!(report["payout_denominator"], "1");
|
||||
assert_eq!(report["payout_numerators"], json!(["0", "1"]));
|
||||
assert_eq!(report["matches"], true);
|
||||
assert_eq!(audit(fixture(), Some("first")).unwrap()["matches"], false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_split_and_invalid_payout_shapes_remain_distinct() {
|
||||
let mut obs = fixture();
|
||||
obs.outcome_slots = abi(0);
|
||||
obs.denominator = abi(0);
|
||||
obs.numerators = None;
|
||||
assert_eq!(audit(obs, None).unwrap()["status"], "unprepared");
|
||||
|
||||
let mut obs = fixture();
|
||||
obs.denominator = abi(0);
|
||||
obs.numerators = Some([abi(0), abi(0)]);
|
||||
assert_eq!(audit(obs, None).unwrap()["status"], "unresolved");
|
||||
|
||||
let mut obs = fixture();
|
||||
obs.denominator = abi(2);
|
||||
obs.numerators = Some([abi(1), abi(1)]);
|
||||
assert_eq!(audit(obs, Some("split")).unwrap()["status"], "split");
|
||||
|
||||
let mut obs = fixture();
|
||||
obs.denominator = abi(3);
|
||||
obs.numerators = Some([abi(1), abi(1)]);
|
||||
assert!(audit(obs, None).is_err());
|
||||
|
||||
let mut obs = fixture();
|
||||
obs.chain_id = 1;
|
||||
assert!(audit(obs, None).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uint256_payout_weights_do_not_round_or_wrap() {
|
||||
let max = format!("0x{}", "ff".repeat(32));
|
||||
let mut obs = fixture();
|
||||
obs.denominator = max.clone();
|
||||
obs.numerators = Some([max.clone(), abi(0)]);
|
||||
let report = audit(obs, None).unwrap();
|
||||
assert_eq!(
|
||||
report["payout_denominator"],
|
||||
"115792089237316195423570985008687907853269984665640564039457584007913129639935"
|
||||
);
|
||||
let mut obs = fixture();
|
||||
obs.denominator = abi(0);
|
||||
obs.numerators = Some([max, abi(1)]);
|
||||
assert!(audit(obs, None).is_err());
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,6 @@
|
||||
mod book_audit;
|
||||
mod books;
|
||||
mod catalog;
|
||||
mod combo_payout;
|
||||
mod ctf_resolution;
|
||||
mod neg_risk_resolution;
|
||||
mod polygon_rpc;
|
||||
mod position_resolution;
|
||||
mod price_check;
|
||||
mod probes;
|
||||
use anyhow::{ensure, Result};
|
||||
@@ -35,81 +30,10 @@ fn observe_book(client: &Client, url: reqwest::Url, token: &str) -> Result<()> {
|
||||
result
|
||||
}
|
||||
|
||||
fn polygon_client() -> Result<Client> {
|
||||
Ok(Client::builder()
|
||||
.connect_timeout(Duration::from_secs(5))
|
||||
.timeout(Duration::from_secs(10))
|
||||
.redirect(reqwest::redirect::Policy::none())
|
||||
.user_agent("eventbook-readonly-probe/0.1")
|
||||
.build()?)
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let args: Vec<_> = std::env::args().skip(1).collect();
|
||||
let usage =
|
||||
"usage: venue-probe [--compare-prices | --inspect-book TOKEN | --replay-book TOKEN FILE | --replay-market FILE | --inspect-resolution CONDITION [EXPECTED] | --replay-resolution FILE [EXPECTED] | --inspect-position-resolution MARKET_JSON [EXPECTED] | --replay-position-resolution FILE [EXPECTED] | --inspect-combo-payout CONDITION AMOUNT_MICROS | --replay-combo-payout FILE | --inspect-neg-risk-event EVENT_ID INDICES | --replay-neg-risk-event FILE]";
|
||||
match args.as_slice() {
|
||||
[mode, condition, amount] if mode == "--inspect-combo-payout" => {
|
||||
println!(
|
||||
"{}",
|
||||
combo_payout::inspect(&polygon_client()?, condition, amount)?
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
[mode, file] if mode == "--replay-combo-payout" => {
|
||||
for report in combo_payout::replay(file)? {
|
||||
println!("{report}");
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
[mode, event, indices] if mode == "--inspect-neg-risk-event" => {
|
||||
println!(
|
||||
"{}",
|
||||
neg_risk_resolution::inspect(&polygon_client()?, event, indices)?
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
[mode, file] if mode == "--replay-neg-risk-event" => {
|
||||
for report in neg_risk_resolution::replay(file)? {
|
||||
println!("{report}");
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if let [mode, value, rest @ ..] = args.as_slice() {
|
||||
if matches!(
|
||||
mode.as_str(),
|
||||
"--inspect-resolution"
|
||||
| "--replay-resolution"
|
||||
| "--inspect-position-resolution"
|
||||
| "--replay-position-resolution"
|
||||
) {
|
||||
ensure!(rest.len() <= 1, usage);
|
||||
let expected = rest.first().map(String::as_str);
|
||||
let reports = match mode.as_str() {
|
||||
"--replay-resolution" => vec![ctf_resolution::replay(value, expected)?],
|
||||
"--replay-position-resolution" => position_resolution::replay(value, expected)?,
|
||||
_ => {
|
||||
let client = polygon_client()?;
|
||||
vec![if mode == "--inspect-resolution" {
|
||||
ctf_resolution::inspect(&client, value, expected)?
|
||||
} else {
|
||||
position_resolution::inspect(&client, value, expected)?
|
||||
}]
|
||||
}
|
||||
};
|
||||
for report in &reports {
|
||||
println!("{report}");
|
||||
}
|
||||
ensure!(
|
||||
reports.iter().all(|report| report["matches"] != false),
|
||||
"payout status differs from the expected result"
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
"usage: venue-probe [--compare-prices | --inspect-book TOKEN | --replay-book TOKEN FILE | --replay-market FILE]";
|
||||
if let [mode, file] = args.as_slice() {
|
||||
if mode == "--replay-market" {
|
||||
let raw = serde_json::from_reader(std::fs::File::open(file)?)?;
|
||||
|
||||
@@ -1,323 +0,0 @@
|
||||
use crate::{
|
||||
polygon_rpc::{hex_data, quantity, CallOutcome, FinalizedRpc, POLYGON_CHAIN_ID},
|
||||
position_resolution::{
|
||||
lookup_module, module_address, result, uint, DENOMINATOR, GET_RESULT, POSITION_MANAGER,
|
||||
},
|
||||
};
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use reqwest::blocking::Client;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
const MODULE: u8 = 2;
|
||||
const CONDITION_COUNT: &str = "dacc07ce"; // conditionCount(bytes29)
|
||||
const REPORTED: &str = "936830bc"; // conditionsResolved(bytes29)
|
||||
const LEGACY_EVENT: &str = "b2915f84"; // legacyEventId(bytes29)
|
||||
const RESULTS_SUM: &str = "65fe9636"; // resultsSum(bytes29)
|
||||
const STORED_RESULT: &str = "91f7d1bf"; // result(bytes31,uint256)
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
struct Condition {
|
||||
index: u16,
|
||||
effective: String,
|
||||
stored_yes: CallOutcome,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
struct Observation {
|
||||
chain_id: u64,
|
||||
event_id: String,
|
||||
block_number: String,
|
||||
block_hash: String,
|
||||
registry: String,
|
||||
condition_count: String,
|
||||
conditions_reported: String,
|
||||
results_sum: String,
|
||||
legacy_event_id: String,
|
||||
conditions: Vec<Condition>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
legacy_catalog: Vec<Value>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
sources: Vec<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
transition_tx: Option<String>,
|
||||
}
|
||||
|
||||
fn event_id(raw: &str) -> Result<(String, u16)> {
|
||||
let full = match raw.len() {
|
||||
60 => format!("{}000000", hex_data(raw, 29)?),
|
||||
66 => hex_data(raw, 32)?.to_owned(),
|
||||
_ => anyhow::bail!("invalid V2 event ID length"),
|
||||
};
|
||||
ensure!(
|
||||
full.starts_with("02") && full.ends_with("000000"),
|
||||
"expected a V2 NegRisk event ID"
|
||||
);
|
||||
let count = u16::from_str_radix(&full[34..38], 16)?;
|
||||
ensure!(count >= 2, "invalid V2 NegRisk event condition count");
|
||||
Ok((full.to_ascii_lowercase(), count))
|
||||
}
|
||||
|
||||
fn value(raw: &str) -> Result<u64> {
|
||||
uint(hex_data(raw, 32)?)
|
||||
}
|
||||
|
||||
fn condition_word(event: &str, index: u16) -> String {
|
||||
format!("{}{index:04x}00", &event[..58])
|
||||
}
|
||||
|
||||
fn output_condition(
|
||||
condition: &Condition,
|
||||
event: &str,
|
||||
count: u16,
|
||||
reported: u64,
|
||||
sum: u64,
|
||||
migrated_event: bool,
|
||||
) -> Result<Value> {
|
||||
ensure!(
|
||||
condition.index <= count,
|
||||
"condition index is outside this event"
|
||||
);
|
||||
let weights = result(&condition.effective, MODULE)?;
|
||||
let synthetic = condition.index == count;
|
||||
let migrated = migrated_event && !synthetic;
|
||||
// The generated array getter returns an empty revert for index 0
|
||||
// when the stored result array has no entries.
|
||||
let origin = match (&condition.stored_yes, weights) {
|
||||
(CallOutcome::Return(raw), Some([yes, _])) if value(raw)? == yes => {
|
||||
ensure!(
|
||||
yes == 0 || sum == DENOMINATOR,
|
||||
"stored YES payout is missing from the event sum"
|
||||
);
|
||||
ensure!(
|
||||
synthetic || reported > 0,
|
||||
"stored market is missing from the report count"
|
||||
);
|
||||
"stored"
|
||||
}
|
||||
(CallOutcome::Revert(data), weights) if data == "0x" => match weights {
|
||||
None => "unresolved",
|
||||
Some([0, DENOMINATOR]) if !migrated && sum == DENOMINATOR => "derived",
|
||||
Some([DENOMINATOR, 0]) if synthetic && sum == 0 && reported == u64::from(count) => {
|
||||
"derived"
|
||||
}
|
||||
_ => anyhow::bail!("unstored payout disagrees with the event counters"),
|
||||
},
|
||||
_ => anyhow::bail!("stored payout disagrees with the effective result"),
|
||||
};
|
||||
Ok(json!({
|
||||
"condition_index":condition.index,
|
||||
"condition_id":format!("0x{}",condition_word(event,condition.index)),
|
||||
"synthetic_other":synthetic,
|
||||
"legacy_migration":migrated,
|
||||
"source":origin,
|
||||
"payout_numerators":weights,
|
||||
}))
|
||||
}
|
||||
|
||||
fn audit(obs: Observation) -> Result<Value> {
|
||||
ensure!(
|
||||
obs.chain_id == POLYGON_CHAIN_ID,
|
||||
"observation is not from Polygon"
|
||||
);
|
||||
let block = quantity(&obs.block_number)?;
|
||||
hex_data(&obs.block_hash, 32)?;
|
||||
if let Some(tx) = &obs.transition_tx {
|
||||
hex_data(tx, 32)?;
|
||||
}
|
||||
let (event, count) = event_id(&obs.event_id)?;
|
||||
let module = module_address(&obs.registry, MODULE)?;
|
||||
let reported = value(&obs.conditions_reported)?;
|
||||
let sum = value(&obs.results_sum)?;
|
||||
let migrated = hex_data(&obs.legacy_event_id, 32)?
|
||||
.bytes()
|
||||
.any(|digit| digit != b'0');
|
||||
ensure!(
|
||||
value(&obs.condition_count)? == u64::from(count),
|
||||
"condition count disagrees with the event ID"
|
||||
);
|
||||
ensure!(
|
||||
reported <= u64::from(count) + 1 && matches!(sum, 0 | DENOMINATOR),
|
||||
"invalid NegRisk counters"
|
||||
);
|
||||
let mut seen = BTreeSet::new();
|
||||
ensure!(!obs.conditions.is_empty(), "no observed conditions");
|
||||
let conditions = obs
|
||||
.conditions
|
||||
.iter()
|
||||
.map(|condition| {
|
||||
ensure!(
|
||||
seen.insert(condition.index),
|
||||
"duplicate condition observation"
|
||||
);
|
||||
output_condition(condition, &event, count, reported, sum, migrated)
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
for market in &obs.legacy_catalog {
|
||||
let index = market["condition_index"]
|
||||
.as_u64()
|
||||
.context("missing legacy condition index")?;
|
||||
let index = u16::try_from(index).context("invalid legacy condition index")?;
|
||||
ensure!(
|
||||
migrated && index < count && seen.contains(&index),
|
||||
"legacy market does not identify an observed migrated condition"
|
||||
);
|
||||
let mapped = market["position_condition_id"]
|
||||
.as_str()
|
||||
.context("missing on-chain legacy mapping")?;
|
||||
ensure!(
|
||||
hex_data(mapped, 32)?.eq_ignore_ascii_case(&condition_word(&event, index)),
|
||||
"legacy market points to another condition"
|
||||
);
|
||||
hex_data(
|
||||
market["conditionId"]
|
||||
.as_str()
|
||||
.context("missing legacy CTF condition")?,
|
||||
32,
|
||||
)?;
|
||||
hex_data(
|
||||
market["legacy_ctf_denominator"]
|
||||
.as_str()
|
||||
.context("missing legacy CTF denominator")?,
|
||||
32,
|
||||
)?;
|
||||
}
|
||||
Ok(json!({
|
||||
"observation":obs,
|
||||
"event_id":format!("0x{event}"),
|
||||
"position_manager":POSITION_MANAGER,
|
||||
"module_contract":module,
|
||||
"block":block,
|
||||
"condition_count":count,
|
||||
"reported_count":reported,
|
||||
"results_sum":sum,
|
||||
"legacy_event_id":migrated.then_some(&obs.legacy_event_id),
|
||||
"payout_denominator":DENOMINATOR,
|
||||
"conditions":conditions,
|
||||
}))
|
||||
}
|
||||
|
||||
pub(crate) fn inspect(client: &Client, event: &str, indices: &str) -> Result<Value> {
|
||||
let (event, count) = event_id(event)?;
|
||||
let mut selected = BTreeSet::new();
|
||||
for raw in indices.split(',') {
|
||||
let index: u16 = raw.parse().context("invalid condition index")?;
|
||||
ensure!(index <= count, "condition index is outside this event");
|
||||
ensure!(selected.insert(index), "duplicate condition index");
|
||||
}
|
||||
let block = FinalizedRpc::connect(client)?;
|
||||
let registry = lookup_module(&block, MODULE)?;
|
||||
let module = module_address(®istry, MODULE)?;
|
||||
let counter = |selector| block.call(&module, &format!("0x{selector}{event}"));
|
||||
let condition_count = counter(CONDITION_COUNT)?;
|
||||
let conditions_reported = counter(REPORTED)?;
|
||||
let results_sum = counter(RESULTS_SUM)?;
|
||||
let legacy_event_id = counter(LEGACY_EVENT)?;
|
||||
let conditions = selected
|
||||
.into_iter()
|
||||
.map(|index| {
|
||||
let id = condition_word(&event, index);
|
||||
Ok(Condition {
|
||||
index,
|
||||
effective: block.call(&module, &format!("0x{GET_RESULT}{id}"))?,
|
||||
stored_yes: block.call_with_revert(
|
||||
&module,
|
||||
&format!("0x{STORED_RESULT}{id}{:064x}", 0),
|
||||
"0x",
|
||||
)?,
|
||||
})
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
block.confirm()?;
|
||||
audit(Observation {
|
||||
chain_id: POLYGON_CHAIN_ID,
|
||||
event_id: format!("0x{event}"),
|
||||
block_number: block.number,
|
||||
block_hash: block.hash,
|
||||
registry,
|
||||
condition_count,
|
||||
conditions_reported,
|
||||
results_sum,
|
||||
legacy_event_id,
|
||||
conditions,
|
||||
legacy_catalog: Vec::new(),
|
||||
sources: Vec::new(),
|
||||
transition_tx: None,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn replay(file: &str) -> Result<Vec<Value>> {
|
||||
let raw: Value = serde_json::from_reader(std::fs::File::open(file)?)?;
|
||||
let rows = match raw {
|
||||
Value::Array(rows) => rows,
|
||||
value => vec![value],
|
||||
};
|
||||
ensure!(!rows.is_empty(), "no NegRisk event observations in file");
|
||||
rows.into_iter()
|
||||
.map(|row| {
|
||||
audit(serde_json::from_value(
|
||||
row.get("observation").cloned().unwrap_or(row),
|
||||
)?)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn replays_reported_derived_and_legacy_pending_results() -> Result<()> {
|
||||
let [before, after, migrated]: [Observation; 3] =
|
||||
serde_json::from_str(include_str!("../fixtures/live-negrisk-resolution.json"))?;
|
||||
let before = audit(before)?;
|
||||
let after = audit(after)?;
|
||||
let migrated = audit(migrated)?;
|
||||
assert_eq!(before["reported_count"], 0);
|
||||
assert_eq!(before["conditions"][3]["source"], "unresolved");
|
||||
assert_eq!(after["reported_count"], 3);
|
||||
assert_eq!(after["conditions"][1]["source"], "stored");
|
||||
assert_eq!(
|
||||
after["conditions"][1]["payout_numerators"],
|
||||
json!([1_000_000, 0])
|
||||
);
|
||||
assert_eq!(after["conditions"][3]["source"], "derived");
|
||||
assert_eq!(
|
||||
after["conditions"][3]["payout_numerators"],
|
||||
json!([0, 1_000_000])
|
||||
);
|
||||
assert_eq!(migrated["reported_count"], 33);
|
||||
assert_eq!(migrated["condition_count"], 37);
|
||||
assert_eq!(migrated["conditions"][1]["source"], "unresolved");
|
||||
assert_eq!(migrated["conditions"][1]["legacy_migration"], true);
|
||||
assert_eq!(migrated["conditions"][5]["source"], "derived");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validates_synthetic_yes_rule_and_rejects_derived_migrated_sibling() -> Result<()> {
|
||||
let event = format!("02{}0002{}", "00".repeat(16), "00".repeat(13));
|
||||
let encoded = |a: u64, b: u64| format!("0x{:064x}{:064x}{a:064x}{b:064x}", 32, 2);
|
||||
let mut condition = Condition {
|
||||
index: 2,
|
||||
effective: encoded(DENOMINATOR, 0),
|
||||
stored_yes: CallOutcome::Revert("0x".into()),
|
||||
};
|
||||
assert_eq!(
|
||||
output_condition(&condition, &event, 2, 2, 0, false)?["source"],
|
||||
"derived"
|
||||
);
|
||||
assert!(output_condition(&condition, &event, 2, 1, 0, false).is_err());
|
||||
condition.index = 1;
|
||||
condition.effective = encoded(0, DENOMINATOR);
|
||||
assert_eq!(
|
||||
output_condition(&condition, &event, 2, 1, DENOMINATOR, false)?["source"],
|
||||
"derived"
|
||||
);
|
||||
assert!(output_condition(&condition, &event, 2, 1, DENOMINATOR, true).is_err());
|
||||
condition.stored_yes = CallOutcome::Return(format!("0x{DENOMINATOR:064x}"));
|
||||
assert!(output_condition(&condition, &event, 2, 1, DENOMINATOR, true).is_err());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1,182 +0,0 @@
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use reqwest::{blocking::Client, Url};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
pub(crate) const POLYGON_CHAIN_ID: u64 = 137;
|
||||
const DEFAULT_RPC: &str = "https://polygon-bor-rpc.publicnode.com";
|
||||
|
||||
pub(crate) fn hex_data(raw: &str, bytes: usize) -> Result<&str> {
|
||||
let body = raw.strip_prefix("0x").context("invalid ABI hex prefix")?;
|
||||
ensure!(
|
||||
body.len() == 2 * bytes && body.bytes().all(|b| b.is_ascii_hexdigit()),
|
||||
"invalid ABI hex length or digit"
|
||||
);
|
||||
Ok(body)
|
||||
}
|
||||
|
||||
pub(crate) fn quantity(raw: &str) -> Result<u64> {
|
||||
let body = raw
|
||||
.strip_prefix("0x")
|
||||
.context("invalid RPC quantity prefix")?;
|
||||
ensure!(
|
||||
!body.is_empty()
|
||||
&& body.bytes().all(|b| b.is_ascii_hexdigit())
|
||||
&& (body.len() == 1 || !body.starts_with('0')),
|
||||
"invalid RPC quantity"
|
||||
);
|
||||
u64::from_str_radix(body, 16).context("invalid RPC quantity")
|
||||
}
|
||||
|
||||
pub(crate) fn word(raw: &str) -> Result<[u8; 32]> {
|
||||
let mut value = [0; 32];
|
||||
for (i, chunk) in hex_data(raw, 32)?.as_bytes().chunks_exact(2).enumerate() {
|
||||
value[i] = u8::from_str_radix(std::str::from_utf8(chunk)?, 16)?;
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct RpcFailure {
|
||||
code: Value,
|
||||
data: Option<String>,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for RpcFailure {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "RPC rejected the request (code {})", self.code)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for RpcFailure {}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub(crate) enum CallOutcome {
|
||||
Return(String),
|
||||
Revert(String),
|
||||
}
|
||||
|
||||
fn rpc(client: &Client, url: &Url, method: &str, params: Value) -> Result<Value> {
|
||||
let response: Value = client
|
||||
.post(url.clone())
|
||||
.json(&json!({
|
||||
"jsonrpc":"2.0","id":1,"method":method,"params":params
|
||||
}))
|
||||
.send()
|
||||
.map_err(reqwest::Error::without_url)?
|
||||
.error_for_status()
|
||||
.map_err(reqwest::Error::without_url)?
|
||||
.json()
|
||||
.map_err(reqwest::Error::without_url)?;
|
||||
ensure!(
|
||||
response["jsonrpc"] == "2.0" && response["id"] == 1,
|
||||
"invalid RPC envelope for {method}"
|
||||
);
|
||||
if let Some(error) = response.get("error") {
|
||||
return Err(anyhow::Error::new(RpcFailure {
|
||||
code: error["code"].clone(),
|
||||
data: error["data"].as_str().map(str::to_owned),
|
||||
})
|
||||
.context(format!("{method} RPC failed")));
|
||||
}
|
||||
response
|
||||
.get("result")
|
||||
.cloned()
|
||||
.with_context(|| format!("missing result for {method}"))
|
||||
}
|
||||
|
||||
pub(crate) struct FinalizedRpc<'a> {
|
||||
client: &'a Client,
|
||||
url: Url,
|
||||
pub number: String,
|
||||
pub hash: String,
|
||||
}
|
||||
|
||||
impl<'a> FinalizedRpc<'a> {
|
||||
pub(crate) fn connect(client: &'a Client) -> Result<Self> {
|
||||
let url = Url::parse(
|
||||
&std::env::var("EVENTBOOK_POLYGON_RPC_URL").unwrap_or_else(|_| DEFAULT_RPC.to_owned()),
|
||||
)
|
||||
.context("invalid Polygon RPC URL")?;
|
||||
ensure!(
|
||||
url.scheme() == "https" && url.username().is_empty() && url.password().is_none(),
|
||||
"Polygon RPC requires an HTTPS URL without embedded credentials"
|
||||
);
|
||||
let chain = rpc(client, &url, "eth_chainId", json!([]))?;
|
||||
let chain_id = quantity(chain.as_str().context("missing chain id")?)?;
|
||||
ensure!(chain_id == POLYGON_CHAIN_ID, "RPC is not Polygon mainnet");
|
||||
let anchor = rpc(
|
||||
client,
|
||||
&url,
|
||||
"eth_getBlockByNumber",
|
||||
json!(["finalized", false]),
|
||||
)?;
|
||||
let number = anchor["number"]
|
||||
.as_str()
|
||||
.context("RPC finalized block has no block number")?;
|
||||
quantity(number)?;
|
||||
let hash = anchor["hash"]
|
||||
.as_str()
|
||||
.context("RPC finalized block has no block hash")?;
|
||||
hex_data(hash, 32)?;
|
||||
Ok(Self {
|
||||
client,
|
||||
url,
|
||||
number: number.to_owned(),
|
||||
hash: hash.to_owned(),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn call(&self, contract: &str, data: &str) -> Result<String> {
|
||||
let value = rpc(
|
||||
self.client,
|
||||
&self.url,
|
||||
"eth_call",
|
||||
json!([{"to":contract,"data":data},self.number]),
|
||||
)?;
|
||||
value
|
||||
.as_str()
|
||||
.map(str::to_owned)
|
||||
.context("invalid eth_call ABI result")
|
||||
}
|
||||
|
||||
pub(crate) fn call_with_revert(
|
||||
&self,
|
||||
contract: &str,
|
||||
data: &str,
|
||||
selector: &str,
|
||||
) -> Result<CallOutcome> {
|
||||
match self.call(contract, data) {
|
||||
Ok(value) => Ok(CallOutcome::Return(value)),
|
||||
Err(error) => match error
|
||||
.downcast_ref::<RpcFailure>()
|
||||
.and_then(|failure| failure.data.as_deref())
|
||||
.filter(|data| data.eq_ignore_ascii_case(selector))
|
||||
{
|
||||
Some(data) => Ok(CallOutcome::Revert(data.to_owned())),
|
||||
None => Err(error),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn confirm(&self) -> Result<u64> {
|
||||
// Providers may lack EIP-1898 support. Read the finalized block number,
|
||||
// then verify its hash again before accepting any of the calls.
|
||||
let current = rpc(
|
||||
self.client,
|
||||
&self.url,
|
||||
"eth_getBlockByNumber",
|
||||
json!([self.number, false]),
|
||||
)?;
|
||||
ensure!(
|
||||
current["hash"] == self.hash && current["number"] == self.number,
|
||||
"RPC block changed during reads"
|
||||
);
|
||||
Ok(SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)?
|
||||
.as_millis()
|
||||
.try_into()?)
|
||||
}
|
||||
}
|
||||
@@ -1,279 +0,0 @@
|
||||
use crate::{
|
||||
catalog::Market,
|
||||
polygon_rpc::{hex_data, quantity, word, FinalizedRpc, POLYGON_CHAIN_ID},
|
||||
};
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use reqwest::blocking::Client;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
pub(crate) const POSITION_MANAGER: &str = "0x006F54F7f9A22e0000CC2AB60031000000ae9fEF";
|
||||
// moduleById(uint256), getResult(bytes31)
|
||||
const MODULE_BY_ID: &str = "4d51cdf1";
|
||||
pub(crate) const GET_RESULT: &str = "e4939c77";
|
||||
pub(crate) const DENOMINATOR: u64 = 1_000_000;
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
struct Observation {
|
||||
chain_id: u64,
|
||||
block_number: String,
|
||||
block_hash: String,
|
||||
market: Value,
|
||||
registry: String,
|
||||
result: String,
|
||||
observed_at_ms: u64,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
sources: Vec<String>,
|
||||
}
|
||||
|
||||
fn market_binding(raw: &Value) -> Result<(Market, u8, &'static str)> {
|
||||
ensure!(
|
||||
raw["version"] == "v2",
|
||||
"PositionManager probe requires a V2 Gamma market"
|
||||
);
|
||||
let market = Market::parse(raw)?;
|
||||
let cid = market.report["position_condition_id"]
|
||||
.as_str()
|
||||
.context("missing encoded condition")?;
|
||||
let hex = hex_data(cid, 31)?;
|
||||
let gamma_condition = market.report["condition_id"]
|
||||
.as_str()
|
||||
.context("missing Gamma condition ID")?;
|
||||
// Gamma can publish a bytes32 representation of the left-aligned bytes31.
|
||||
let gamma_condition = match gamma_condition.len() {
|
||||
64 => hex_data(gamma_condition, 31)?,
|
||||
66 => hex_data(gamma_condition, 32)?
|
||||
.strip_suffix("00")
|
||||
.context("invalid Gamma condition ID padding")?,
|
||||
_ => anyhow::bail!("invalid Gamma condition ID length"),
|
||||
};
|
||||
ensure!(
|
||||
gamma_condition.eq_ignore_ascii_case(hex),
|
||||
"Gamma condition ID disagrees with the Position IDs"
|
||||
);
|
||||
let (module, name) = match &hex[..2] {
|
||||
"01" => (1, "BinaryModule"),
|
||||
"02" => (2, "NegRiskModule"),
|
||||
_ => anyhow::bail!("PositionManager probe requires a Binary or NegRisk condition"),
|
||||
};
|
||||
Ok((market, module, name))
|
||||
}
|
||||
|
||||
pub(crate) fn module_address(registry: &str, module: u8) -> Result<String> {
|
||||
let raw = hex_data(registry, 32)?;
|
||||
ensure!(
|
||||
raw[..24].bytes().all(|digit| digit == b'0'),
|
||||
"invalid module registry address padding"
|
||||
);
|
||||
let address = format!("0x{}", &raw[24..]);
|
||||
let expected = match module {
|
||||
1 => "0x1000008dD9001B968442c1000017eaE6E0dA00Ba",
|
||||
2 => "0x200000900045e3B6259600682756002200028933",
|
||||
3 => "0x30000034706C7d8e12009DAB006Be20000c031A8",
|
||||
_ => anyhow::bail!("unsupported PositionManager module"),
|
||||
};
|
||||
ensure!(
|
||||
expected.eq_ignore_ascii_case(&address),
|
||||
"PositionManager registry differs from the published deployment"
|
||||
);
|
||||
Ok(address)
|
||||
}
|
||||
|
||||
pub(crate) fn uint(word_hex: &str) -> Result<u64> {
|
||||
let data = word(&format!("0x{word_hex}"))?;
|
||||
ensure!(
|
||||
data[..24].iter().all(|&byte| byte == 0),
|
||||
"unexpected ABI integer overflow"
|
||||
);
|
||||
Ok(u64::from_be_bytes(data[24..].try_into()?))
|
||||
}
|
||||
|
||||
pub(crate) fn result(raw: &str, module: u8) -> Result<Option<[u64; 2]>> {
|
||||
let bytes = match raw.len() {
|
||||
130 => 64,
|
||||
258 => 128,
|
||||
_ => anyhow::bail!("getResult must return an empty or two-element ABI array"),
|
||||
};
|
||||
let data = hex_data(raw, bytes)?;
|
||||
ensure!(uint(&data[..64])? == 32, "invalid getResult array offset");
|
||||
let length = uint(&data[64..128])?;
|
||||
if bytes == 64 {
|
||||
ensure!(length == 0, "invalid empty getResult array");
|
||||
return Ok(None);
|
||||
}
|
||||
ensure!(length == 2, "invalid getResult array length");
|
||||
let a = uint(&data[128..192])?;
|
||||
let b = uint(&data[192..256])?;
|
||||
ensure!(
|
||||
a.checked_add(b) == Some(DENOMINATOR),
|
||||
"invalid V2 payout denominator"
|
||||
);
|
||||
ensure!(module != 2 || a == 0 || b == 0, "nonbinary NegRisk payout");
|
||||
Ok(Some([a, b]))
|
||||
}
|
||||
|
||||
fn audit(obs: Observation, expected: Option<&str>) -> Result<Value> {
|
||||
ensure!(
|
||||
obs.chain_id == POLYGON_CHAIN_ID,
|
||||
"observation is not from Polygon mainnet"
|
||||
);
|
||||
let block = quantity(&obs.block_number)?;
|
||||
hex_data(&obs.block_hash, 32)?;
|
||||
let (market, module, name) = market_binding(&obs.market)?;
|
||||
let target = module_address(&obs.registry, module)?;
|
||||
let weights = result(&obs.result, module)?;
|
||||
let status = match weights {
|
||||
None => "unresolved",
|
||||
Some([0, _]) => "second",
|
||||
Some([_, 0]) => "first",
|
||||
Some([a, b]) if a == b => "split",
|
||||
Some(_) => "weighted",
|
||||
};
|
||||
if let Some(value) = expected {
|
||||
ensure!(
|
||||
matches!(
|
||||
value,
|
||||
"unresolved" | "first" | "second" | "split" | "weighted"
|
||||
),
|
||||
"invalid expected V2 payout status"
|
||||
);
|
||||
}
|
||||
Ok(
|
||||
json!({"observation":obs,"block":block,"position_manager":POSITION_MANAGER,"module":name,
|
||||
"module_id":module,"module_contract":target,
|
||||
"position_condition_id":market.report["position_condition_id"],
|
||||
"outcomes":market.report["outcomes"],"status":status,
|
||||
"payout_denominator":weights.map(|_|DENOMINATOR.to_string()),
|
||||
"payout_numerators":weights.map(|weights|weights.map(|v|v.to_string())),
|
||||
"expected":expected,"matches":expected.map(|v|v==status)}),
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn lookup_module(block: &FinalizedRpc<'_>, module: u8) -> Result<String> {
|
||||
block.call(POSITION_MANAGER, &format!("0x{MODULE_BY_ID}{module:064x}"))
|
||||
}
|
||||
|
||||
pub(crate) fn inspect(client: &Client, file: &str, expected: Option<&str>) -> Result<Value> {
|
||||
let market: Value = serde_json::from_reader(std::fs::File::open(file)?)?;
|
||||
let (binding, module, _) = market_binding(&market)?;
|
||||
let cid = hex_data(
|
||||
binding.report["position_condition_id"]
|
||||
.as_str()
|
||||
.context("missing condition")?,
|
||||
31,
|
||||
)?;
|
||||
let block = FinalizedRpc::connect(client)?;
|
||||
let registry = lookup_module(&block, module)?;
|
||||
let address = module_address(®istry, module)?;
|
||||
// Solidity bytes31 is left-aligned in its ABI word. The final byte is padding.
|
||||
let result = block.call(&address, &format!("0x{GET_RESULT}{cid}00"))?;
|
||||
let observed_at_ms = block.confirm()?;
|
||||
let market = Value::Object(
|
||||
[
|
||||
"id",
|
||||
"slug",
|
||||
"version",
|
||||
"conditionId",
|
||||
"positionIds",
|
||||
"outcomes",
|
||||
"outcomePrices",
|
||||
]
|
||||
.into_iter()
|
||||
.filter_map(|key| market.get(key).map(|value| (key.to_owned(), value.clone())))
|
||||
.collect(),
|
||||
);
|
||||
audit(
|
||||
Observation {
|
||||
chain_id: POLYGON_CHAIN_ID,
|
||||
block_number: block.number,
|
||||
block_hash: block.hash,
|
||||
market,
|
||||
registry,
|
||||
result,
|
||||
observed_at_ms,
|
||||
sources: Vec::new(),
|
||||
},
|
||||
expected,
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn replay(file: &str, expected: Option<&str>) -> Result<Vec<Value>> {
|
||||
let raw: Value = serde_json::from_reader(std::fs::File::open(file)?)?;
|
||||
let rows = match raw {
|
||||
Value::Array(rows) => rows,
|
||||
value => vec![value],
|
||||
};
|
||||
ensure!(!rows.is_empty(), "no V2 observations in file");
|
||||
rows.into_iter()
|
||||
.map(|row| {
|
||||
let obs = serde_json::from_value(row.get("observation").cloned().unwrap_or(row))?;
|
||||
audit(obs, expected)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn abi(values: &[u64]) -> String {
|
||||
let mut encoded = String::from("0x");
|
||||
for value in values {
|
||||
encoded.push_str(&format!("{value:064x}"));
|
||||
}
|
||||
encoded
|
||||
}
|
||||
|
||||
const LIVE: &str = include_str!("../fixtures/live-position-resolutions.json");
|
||||
|
||||
#[test]
|
||||
fn replay_binary_observation_preserves_gamma_outcome_order() -> Result<()> {
|
||||
let [obs]: [Observation; 1] = serde_json::from_str(LIVE)?;
|
||||
let report = audit(obs, Some("first"))?;
|
||||
assert_eq!(report["status"], "first");
|
||||
assert_eq!(report["matches"], true);
|
||||
assert_eq!(report["outcomes"][0]["label"], "Nikolenko Anatolii");
|
||||
assert_eq!(report["payout_numerators"], json!(["1000000", "0"]));
|
||||
assert_eq!(report["payout_denominator"], "1000000");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_mismatched_condition_and_unexpected_module_address() -> Result<()> {
|
||||
let [mut obs]: [Observation; 1] = serde_json::from_str(LIVE)?;
|
||||
assert!(module_address(&obs.registry, 2).is_err());
|
||||
let condition = obs.market["conditionId"].as_str().unwrap();
|
||||
let unpadded = condition.strip_suffix("00").unwrap().to_owned();
|
||||
let wrong_padding = format!("{unpadded}01");
|
||||
obs.market["conditionId"] = json!(unpadded);
|
||||
assert!(market_binding(&obs.market).is_ok());
|
||||
obs.market["conditionId"] = json!(wrong_padding);
|
||||
assert!(market_binding(&obs.market).is_err());
|
||||
obs.market["conditionId"] = json!(format!("0x02{}", "00".repeat(30)));
|
||||
assert!(market_binding(&obs.market).is_err());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_unresolved_and_resolved_weights_and_rejects_malformed_abi() -> Result<()> {
|
||||
assert_eq!(result(&abi(&[32, 0]), 1)?, None);
|
||||
assert_eq!(
|
||||
result(&abi(&[32, 2, 0, 1_000_000]), 2)?,
|
||||
Some([0, 1_000_000])
|
||||
);
|
||||
let fractional = abi(&[32, 2, 700_000, 300_000]);
|
||||
assert_eq!(result(&fractional, 1)?, Some([700_000, 300_000]));
|
||||
assert!(result(&fractional, 2).is_err());
|
||||
for bad in [
|
||||
abi(&[64, 0]),
|
||||
abi(&[32, 2]),
|
||||
abi(&[32, 1, 0, 1_000_000]),
|
||||
abi(&[32, 2, 0, 999_999]),
|
||||
abi(&[32, 2, 0, 1_000_000, 0]),
|
||||
format!("0x1{}", &fractional[3..]),
|
||||
] {
|
||||
assert!(result(&bad, 1).is_err());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
{
|
||||
"source": "https://data-api.polymarket.com/v2/tokens?condition=0xdfb674d9eb1ca2f4b1c38d36562b725d6dca8364b3b1eea2dafc773608959c80",
|
||||
"date": "Fri, 04 Dec 2026 21:03:26 GMT",
|
||||
"external_condition": "0xdfb674d9eb1ca2f4b1c38d36562b725d6dca8364b3b1eea2dafc773608959c80",
|
||||
"data": [
|
||||
{
|
||||
"token_id": "56766704504589537417119461476407464198158915644205212964421261364010493123785",
|
||||
"condition_id": "0xdfb674d9eb1ca2f4b1c38d36562b725d6dca8364b3b1eea2dafc773608959c80",
|
||||
"structural_condition_id": null,
|
||||
"module": "v1_ctf",
|
||||
"outcome_index": 0,
|
||||
"clob_index": 0,
|
||||
"outcome": "Yes",
|
||||
"opposite_token_id": "33748178601941852783056114873418965902944929138778460252404676407918318867810",
|
||||
"resolved": false,
|
||||
"final_price": null,
|
||||
"title": "Will Paris Saint-Germain FC win on 2026-12-04?",
|
||||
"market_slug": "fl1-tou-psg-2026-12-04-psg",
|
||||
"closed": false,
|
||||
"neg_risk": true,
|
||||
"neg_risk_market_id": "0xbac6a2a3e5faf30fdabab133b0258ed9bf5052dd0f75c60464fe2f290bc93000",
|
||||
"question_index": 2,
|
||||
"event_id": 1465085,
|
||||
"event_slug": "fl1-tou-psg-2026-12-04"
|
||||
},
|
||||
{
|
||||
"token_id": "33748178601941852783056114873418965902944929138778460252404676407918318867810",
|
||||
"condition_id": "0xdfb674d9eb1ca2f4b1c38d36562b725d6dca8364b3b1eea2dafc773608959c80",
|
||||
"structural_condition_id": null,
|
||||
"module": "v1_ctf",
|
||||
"outcome_index": 1,
|
||||
"clob_index": 1,
|
||||
"outcome": "No",
|
||||
"opposite_token_id": "56766704504589537417119461476407464198158915644205212964421261364010493123785",
|
||||
"resolved": false,
|
||||
"final_price": null,
|
||||
"title": "Will Paris Saint-Germain FC win on 2026-12-04?",
|
||||
"market_slug": "fl1-tou-psg-2026-12-04-psg",
|
||||
"closed": false,
|
||||
"neg_risk": true,
|
||||
"neg_risk_market_id": "0xbac6a2a3e5faf30fdabab133b0258ed9bf5052dd0f75c60464fe2f290bc93000",
|
||||
"question_index": 2,
|
||||
"event_id": 1465085,
|
||||
"event_slug": "fl1-tou-psg-2026-12-04"
|
||||
},
|
||||
{
|
||||
"token_id": "1242647860242950490718683690862688823036949349322148957738072940768458179072",
|
||||
"condition_id": "0xdfb674d9eb1ca2f4b1c38d36562b725d6dca8364b3b1eea2dafc773608959c80",
|
||||
"structural_condition_id": "0x02bf5052dd0f75c60464fe2f290bc93000000300000000000000000000000200",
|
||||
"module": "neg_risk",
|
||||
"outcome_index": 0,
|
||||
"clob_index": null,
|
||||
"outcome": "Yes",
|
||||
"opposite_token_id": "1242647860242950490718683690862688823036949349322148957738072940768458179073",
|
||||
"resolved": false,
|
||||
"final_price": null,
|
||||
"title": "Will Paris Saint-Germain FC win on 2026-12-04?",
|
||||
"market_slug": "fl1-tou-psg-2026-12-04-psg",
|
||||
"closed": false,
|
||||
"neg_risk": true,
|
||||
"neg_risk_market_id": "0xbac6a2a3e5faf30fdabab133b0258ed9bf5052dd0f75c60464fe2f290bc93000",
|
||||
"question_index": 2,
|
||||
"event_id": 1465085,
|
||||
"event_slug": "fl1-tou-psg-2026-12-04"
|
||||
},
|
||||
{
|
||||
"token_id": "1242647860242950490718683690862688823036949349322148957738072940768458179073",
|
||||
"condition_id": "0xdfb674d9eb1ca2f4b1c38d36562b725d6dca8364b3b1eea2dafc773608959c80",
|
||||
"structural_condition_id": "0x02bf5052dd0f75c60464fe2f290bc93000000300000000000000000000000200",
|
||||
"module": "neg_risk",
|
||||
"outcome_index": 1,
|
||||
"clob_index": null,
|
||||
"outcome": "No",
|
||||
"opposite_token_id": "1242647860242950490718683690862688823036949349322148957738072940768458179072",
|
||||
"resolved": false,
|
||||
"final_price": null,
|
||||
"title": "Will Paris Saint-Germain FC win on 2026-12-04?",
|
||||
"market_slug": "fl1-tou-psg-2026-12-04-psg",
|
||||
"closed": false,
|
||||
"neg_risk": true,
|
||||
"neg_risk_market_id": "0xbac6a2a3e5faf30fdabab133b0258ed9bf5052dd0f75c60464fe2f290bc93000",
|
||||
"question_index": 2,
|
||||
"event_id": 1465085,
|
||||
"event_slug": "fl1-tou-psg-2026-12-04"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
{
|
||||
"source_url": "https://data-api.polymarket.com/v2/tokens?condition=0xbac6a2a3e5faf30fdabab133b0258ed9bf5052dd0f75c60464fe2f290bc93000",
|
||||
"captured_at": "Fri, 04 Dec 2026 21:03:58 GMT",
|
||||
"data": [
|
||||
{
|
||||
"token_id": "40384919342148672870770945432101495451968327778097401039020519003208568963549",
|
||||
"condition_id": "0x5364a90051fdd64d447207fe670842efab39bf873d37d88bbb77f7aa282a3577",
|
||||
"structural_condition_id": null,
|
||||
"module": "v1_ctf",
|
||||
"outcome_index": 0,
|
||||
"clob_index": 0,
|
||||
"outcome": "Yes",
|
||||
"opposite_token_id": "13408982299269116806894777758021694013482652654029730596500219066110331544576",
|
||||
"resolved": false,
|
||||
"final_price": null,
|
||||
"title": "Will Toulouse FC win on 2026-12-04?",
|
||||
"market_slug": "fl1-tou-psg-2026-12-04-tou",
|
||||
"closed": false,
|
||||
"neg_risk": true,
|
||||
"neg_risk_market_id": "0xbac6a2a3e5faf30fdabab133b0258ed9bf5052dd0f75c60464fe2f290bc93000",
|
||||
"question_index": 0,
|
||||
"event_id": 1465085,
|
||||
"event_slug": "fl1-tou-psg-2026-12-04"
|
||||
},
|
||||
{
|
||||
"token_id": "13408982299269116806894777758021694013482652654029730596500219066110331544576",
|
||||
"condition_id": "0x5364a90051fdd64d447207fe670842efab39bf873d37d88bbb77f7aa282a3577",
|
||||
"structural_condition_id": null,
|
||||
"module": "v1_ctf",
|
||||
"outcome_index": 1,
|
||||
"clob_index": 1,
|
||||
"outcome": "No",
|
||||
"opposite_token_id": "40384919342148672870770945432101495451968327778097401039020519003208568963549",
|
||||
"resolved": false,
|
||||
"final_price": null,
|
||||
"title": "Will Toulouse FC win on 2026-12-04?",
|
||||
"market_slug": "fl1-tou-psg-2026-12-04-tou",
|
||||
"closed": false,
|
||||
"neg_risk": true,
|
||||
"neg_risk_market_id": "0xbac6a2a3e5faf30fdabab133b0258ed9bf5052dd0f75c60464fe2f290bc93000",
|
||||
"question_index": 0,
|
||||
"event_id": 1465085,
|
||||
"event_slug": "fl1-tou-psg-2026-12-04"
|
||||
},
|
||||
{
|
||||
"token_id": "1242647860242950490718683690862688823036949349322148957738072940768458178560",
|
||||
"condition_id": "0x5364a90051fdd64d447207fe670842efab39bf873d37d88bbb77f7aa282a3577",
|
||||
"structural_condition_id": "0x02bf5052dd0f75c60464fe2f290bc93000000300000000000000000000000000",
|
||||
"module": "neg_risk",
|
||||
"outcome_index": 0,
|
||||
"clob_index": null,
|
||||
"outcome": "Yes",
|
||||
"opposite_token_id": "1242647860242950490718683690862688823036949349322148957738072940768458178561",
|
||||
"resolved": false,
|
||||
"final_price": null,
|
||||
"title": "Will Toulouse FC win on 2026-12-04?",
|
||||
"market_slug": "fl1-tou-psg-2026-12-04-tou",
|
||||
"closed": false,
|
||||
"neg_risk": true,
|
||||
"neg_risk_market_id": "0xbac6a2a3e5faf30fdabab133b0258ed9bf5052dd0f75c60464fe2f290bc93000",
|
||||
"question_index": 0,
|
||||
"event_id": 1465085,
|
||||
"event_slug": "fl1-tou-psg-2026-12-04"
|
||||
},
|
||||
{
|
||||
"token_id": "1242647860242950490718683690862688823036949349322148957738072940768458178561",
|
||||
"condition_id": "0x5364a90051fdd64d447207fe670842efab39bf873d37d88bbb77f7aa282a3577",
|
||||
"structural_condition_id": "0x02bf5052dd0f75c60464fe2f290bc93000000300000000000000000000000000",
|
||||
"module": "neg_risk",
|
||||
"outcome_index": 1,
|
||||
"clob_index": null,
|
||||
"outcome": "No",
|
||||
"opposite_token_id": "1242647860242950490718683690862688823036949349322148957738072940768458178560",
|
||||
"resolved": false,
|
||||
"final_price": null,
|
||||
"title": "Will Toulouse FC win on 2026-12-04?",
|
||||
"market_slug": "fl1-tou-psg-2026-12-04-tou",
|
||||
"closed": false,
|
||||
"neg_risk": true,
|
||||
"neg_risk_market_id": "0xbac6a2a3e5faf30fdabab133b0258ed9bf5052dd0f75c60464fe2f290bc93000",
|
||||
"question_index": 0,
|
||||
"event_id": 1465085,
|
||||
"event_slug": "fl1-tou-psg-2026-12-04"
|
||||
},
|
||||
{
|
||||
"token_id": "103333010293518730378106572744460037514611059173916399171749440880269466461468",
|
||||
"condition_id": "0x80c4b761829cd055b8bd990cbb04c9f0bad007aeaae6cc0ff39807cf3303d604",
|
||||
"structural_condition_id": null,
|
||||
"module": "v1_ctf",
|
||||
"outcome_index": 0,
|
||||
"clob_index": 0,
|
||||
"outcome": "Yes",
|
||||
"opposite_token_id": "98082619073142377808975564447235447133706299255372243296223031730369079572279",
|
||||
"resolved": false,
|
||||
"final_price": null,
|
||||
"title": "Will Toulouse FC vs. Paris Saint-Germain FC end in a draw?",
|
||||
"market_slug": "fl1-tou-psg-2026-12-04-draw",
|
||||
"closed": false,
|
||||
"neg_risk": true,
|
||||
"neg_risk_market_id": "0xbac6a2a3e5faf30fdabab133b0258ed9bf5052dd0f75c60464fe2f290bc93000",
|
||||
"question_index": 1,
|
||||
"event_id": 1465085,
|
||||
"event_slug": "fl1-tou-psg-2026-12-04"
|
||||
},
|
||||
{
|
||||
"token_id": "98082619073142377808975564447235447133706299255372243296223031730369079572279",
|
||||
"condition_id": "0x80c4b761829cd055b8bd990cbb04c9f0bad007aeaae6cc0ff39807cf3303d604",
|
||||
"structural_condition_id": null,
|
||||
"module": "v1_ctf",
|
||||
"outcome_index": 1,
|
||||
"clob_index": 1,
|
||||
"outcome": "No",
|
||||
"opposite_token_id": "103333010293518730378106572744460037514611059173916399171749440880269466461468",
|
||||
"resolved": false,
|
||||
"final_price": null,
|
||||
"title": "Will Toulouse FC vs. Paris Saint-Germain FC end in a draw?",
|
||||
"market_slug": "fl1-tou-psg-2026-12-04-draw",
|
||||
"closed": false,
|
||||
"neg_risk": true,
|
||||
"neg_risk_market_id": "0xbac6a2a3e5faf30fdabab133b0258ed9bf5052dd0f75c60464fe2f290bc93000",
|
||||
"question_index": 1,
|
||||
"event_id": 1465085,
|
||||
"event_slug": "fl1-tou-psg-2026-12-04"
|
||||
},
|
||||
{
|
||||
"token_id": "1242647860242950490718683690862688823036949349322148957738072940768458178816",
|
||||
"condition_id": "0x80c4b761829cd055b8bd990cbb04c9f0bad007aeaae6cc0ff39807cf3303d604",
|
||||
"structural_condition_id": "0x02bf5052dd0f75c60464fe2f290bc93000000300000000000000000000000100",
|
||||
"module": "neg_risk",
|
||||
"outcome_index": 0,
|
||||
"clob_index": null,
|
||||
"outcome": "Yes",
|
||||
"opposite_token_id": "1242647860242950490718683690862688823036949349322148957738072940768458178817",
|
||||
"resolved": false,
|
||||
"final_price": null,
|
||||
"title": "Will Toulouse FC vs. Paris Saint-Germain FC end in a draw?",
|
||||
"market_slug": "fl1-tou-psg-2026-12-04-draw",
|
||||
"closed": false,
|
||||
"neg_risk": true,
|
||||
"neg_risk_market_id": "0xbac6a2a3e5faf30fdabab133b0258ed9bf5052dd0f75c60464fe2f290bc93000",
|
||||
"question_index": 1,
|
||||
"event_id": 1465085,
|
||||
"event_slug": "fl1-tou-psg-2026-12-04"
|
||||
},
|
||||
{
|
||||
"token_id": "1242647860242950490718683690862688823036949349322148957738072940768458178817",
|
||||
"condition_id": "0x80c4b761829cd055b8bd990cbb04c9f0bad007aeaae6cc0ff39807cf3303d604",
|
||||
"structural_condition_id": "0x02bf5052dd0f75c60464fe2f290bc93000000300000000000000000000000100",
|
||||
"module": "neg_risk",
|
||||
"outcome_index": 1,
|
||||
"clob_index": null,
|
||||
"outcome": "No",
|
||||
"opposite_token_id": "1242647860242950490718683690862688823036949349322148957738072940768458178816",
|
||||
"resolved": false,
|
||||
"final_price": null,
|
||||
"title": "Will Toulouse FC vs. Paris Saint-Germain FC end in a draw?",
|
||||
"market_slug": "fl1-tou-psg-2026-12-04-draw",
|
||||
"closed": false,
|
||||
"neg_risk": true,
|
||||
"neg_risk_market_id": "0xbac6a2a3e5faf30fdabab133b0258ed9bf5052dd0f75c60464fe2f290bc93000",
|
||||
"question_index": 1,
|
||||
"event_id": 1465085,
|
||||
"event_slug": "fl1-tou-psg-2026-12-04"
|
||||
},
|
||||
{
|
||||
"token_id": "56766704504589537417119461476407464198158915644205212964421261364010493123785",
|
||||
"condition_id": "0xdfb674d9eb1ca2f4b1c38d36562b725d6dca8364b3b1eea2dafc773608959c80",
|
||||
"structural_condition_id": null,
|
||||
"module": "v1_ctf",
|
||||
"outcome_index": 0,
|
||||
"clob_index": 0,
|
||||
"outcome": "Yes",
|
||||
"opposite_token_id": "33748178601941852783056114873418965902944929138778460252404676407918318867810",
|
||||
"resolved": false,
|
||||
"final_price": null,
|
||||
"title": "Will Paris Saint-Germain FC win on 2026-12-04?",
|
||||
"market_slug": "fl1-tou-psg-2026-12-04-psg",
|
||||
"closed": false,
|
||||
"neg_risk": true,
|
||||
"neg_risk_market_id": "0xbac6a2a3e5faf30fdabab133b0258ed9bf5052dd0f75c60464fe2f290bc93000",
|
||||
"question_index": 2,
|
||||
"event_id": 1465085,
|
||||
"event_slug": "fl1-tou-psg-2026-12-04"
|
||||
},
|
||||
{
|
||||
"token_id": "33748178601941852783056114873418965902944929138778460252404676407918318867810",
|
||||
"condition_id": "0xdfb674d9eb1ca2f4b1c38d36562b725d6dca8364b3b1eea2dafc773608959c80",
|
||||
"structural_condition_id": null,
|
||||
"module": "v1_ctf",
|
||||
"outcome_index": 1,
|
||||
"clob_index": 1,
|
||||
"outcome": "No",
|
||||
"opposite_token_id": "56766704504589537417119461476407464198158915644205212964421261364010493123785",
|
||||
"resolved": false,
|
||||
"final_price": null,
|
||||
"title": "Will Paris Saint-Germain FC win on 2026-12-04?",
|
||||
"market_slug": "fl1-tou-psg-2026-12-04-psg",
|
||||
"closed": false,
|
||||
"neg_risk": true,
|
||||
"neg_risk_market_id": "0xbac6a2a3e5faf30fdabab133b0258ed9bf5052dd0f75c60464fe2f290bc93000",
|
||||
"question_index": 2,
|
||||
"event_id": 1465085,
|
||||
"event_slug": "fl1-tou-psg-2026-12-04"
|
||||
},
|
||||
{
|
||||
"token_id": "1242647860242950490718683690862688823036949349322148957738072940768458179072",
|
||||
"condition_id": "0xdfb674d9eb1ca2f4b1c38d36562b725d6dca8364b3b1eea2dafc773608959c80",
|
||||
"structural_condition_id": "0x02bf5052dd0f75c60464fe2f290bc93000000300000000000000000000000200",
|
||||
"module": "neg_risk",
|
||||
"outcome_index": 0,
|
||||
"clob_index": null,
|
||||
"outcome": "Yes",
|
||||
"opposite_token_id": "1242647860242950490718683690862688823036949349322148957738072940768458179073",
|
||||
"resolved": false,
|
||||
"final_price": null,
|
||||
"title": "Will Paris Saint-Germain FC win on 2026-12-04?",
|
||||
"market_slug": "fl1-tou-psg-2026-12-04-psg",
|
||||
"closed": false,
|
||||
"neg_risk": true,
|
||||
"neg_risk_market_id": "0xbac6a2a3e5faf30fdabab133b0258ed9bf5052dd0f75c60464fe2f290bc93000",
|
||||
"question_index": 2,
|
||||
"event_id": 1465085,
|
||||
"event_slug": "fl1-tou-psg-2026-12-04"
|
||||
},
|
||||
{
|
||||
"token_id": "1242647860242950490718683690862688823036949349322148957738072940768458179073",
|
||||
"condition_id": "0xdfb674d9eb1ca2f4b1c38d36562b725d6dca8364b3b1eea2dafc773608959c80",
|
||||
"structural_condition_id": "0x02bf5052dd0f75c60464fe2f290bc93000000300000000000000000000000200",
|
||||
"module": "neg_risk",
|
||||
"outcome_index": 1,
|
||||
"clob_index": null,
|
||||
"outcome": "No",
|
||||
"opposite_token_id": "1242647860242950490718683690862688823036949349322148957738072940768458179072",
|
||||
"resolved": false,
|
||||
"final_price": null,
|
||||
"title": "Will Paris Saint-Germain FC win on 2026-12-04?",
|
||||
"market_slug": "fl1-tou-psg-2026-12-04-psg",
|
||||
"closed": false,
|
||||
"neg_risk": true,
|
||||
"neg_risk_market_id": "0xbac6a2a3e5faf30fdabab133b0258ed9bf5052dd0f75c60464fe2f290bc93000",
|
||||
"question_index": 2,
|
||||
"event_id": 1465085,
|
||||
"event_slug": "fl1-tou-psg-2026-12-04"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"one": {"url":"https://data-api.polymarket.com/v2/tokens?token_id=759916398134244316868652908232832573045153963965173623897622651599218278400","status":200,"date":"Fri, 04 Dec 2026 20:59:33 GMT","body":{"data":[{"token_id":"759916398134244316868652908232832573045153963965173623897622651599218278400","condition_id":"0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","structural_condition_id":"0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","module":"binary","outcome_index":0,"clob_index":null,"outcome":"Nikolenko Anatolii","opposite_token_id":"759916398134244316868652908232832573045153963965173623897622651599218278401","resolved":true,"final_price":1.0,"title":"Nikolenko Anatolii vs. Fokin Illia","market_slug":"setkameua-anat-illia-2026-12-03","closed":true,"neg_risk":false,"neg_risk_market_id":null,"question_index":null,"event_id":1496938,"event_slug":"setkameua-anat-illia-2026-12-03"}]}},
|
||||
"alias": {"url":"https://data-api.polymarket.com/v2/tokens?tokenId=759916398134244316868652908232832573045153963965173623897622651599218278400","status":400,"date":"Fri, 04 Dec 2026 20:59:33 GMT","body":{"error":"provide exactly one of 'token_id' or 'condition'","code":"invalid_request","retryable":false}},
|
||||
"pair": {"url":"https://data-api.polymarket.com/v2/tokens?condition=0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","status":200,"date":"Fri, 04 Dec 2026 20:59:34 GMT","body":{"data":[{"token_id":"759916398134244316868652908232832573045153963965173623897622651599218278400","condition_id":"0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","structural_condition_id":"0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","module":"binary","outcome_index":0,"clob_index":null,"outcome":"Nikolenko Anatolii","opposite_token_id":"759916398134244316868652908232832573045153963965173623897622651599218278401","resolved":true,"final_price":1.0,"title":"Nikolenko Anatolii vs. Fokin Illia","market_slug":"setkameua-anat-illia-2026-12-03","closed":true,"neg_risk":false,"neg_risk_market_id":null,"question_index":null,"event_id":1496938,"event_slug":"setkameua-anat-illia-2026-12-03"},{"token_id":"759916398134244316868652908232832573045153963965173623897622651599218278401","condition_id":"0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","structural_condition_id":"0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","module":"binary","outcome_index":1,"clob_index":null,"outcome":"Fokin Illia","opposite_token_id":"759916398134244316868652908232832573045153963965173623897622651599218278400","resolved":true,"final_price":0.0,"title":"Nikolenko Anatolii vs. Fokin Illia","market_slug":"setkameua-anat-illia-2026-12-03","closed":true,"neg_risk":false,"neg_risk_market_id":null,"question_index":null,"event_id":1496938,"event_slug":"setkameua-anat-illia-2026-12-03"}]}},
|
||||
"pair_alias": {"url":"https://data-api.polymarket.com/v2/tokens?conditionId=0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","status":200,"date":"Fri, 04 Dec 2026 20:59:33 GMT","body":{"data":[{"token_id":"759916398134244316868652908232832573045153963965173623897622651599218278400","condition_id":"0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","structural_condition_id":"0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","module":"binary","outcome_index":0,"clob_index":null,"outcome":"Nikolenko Anatolii","opposite_token_id":"759916398134244316868652908232832573045153963965173623897622651599218278401","resolved":true,"final_price":1.0,"title":"Nikolenko Anatolii vs. Fokin Illia","market_slug":"setkameua-anat-illia-2026-12-03","closed":true,"neg_risk":false,"neg_risk_market_id":null,"question_index":null,"event_id":1496938,"event_slug":"setkameua-anat-illia-2026-12-03"},{"token_id":"759916398134244316868652908232832573045153963965173623897622651599218278401","condition_id":"0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","structural_condition_id":"0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","module":"binary","outcome_index":1,"clob_index":null,"outcome":"Fokin Illia","opposite_token_id":"759916398134244316868652908232832573045153963965173623897622651599218278400","resolved":true,"final_price":0.0,"title":"Nikolenko Anatolii vs. Fokin Illia","market_slug":"setkameua-anat-illia-2026-12-03","closed":true,"neg_risk":false,"neg_risk_market_id":null,"question_index":null,"event_id":1496938,"event_slug":"setkameua-anat-illia-2026-12-03"}]}},
|
||||
"v1": {"url":"https://data-api.polymarket.com/v2/tokens?token_id=73979342585906843441145134109923710004884703083095161594360108477170435492453","status":200,"date":"Fri, 04 Dec 2026 20:59:34 GMT","body":{"data":[{"token_id":"73979342585906843441145134109923710004884703083095161594360108477170435492453","condition_id":"0xdf04a0495b0a16dbce386acdc16d9aed19784db9888be53d150354b83b7c18b1","structural_condition_id":null,"module":"v1_ctf","outcome_index":0,"clob_index":0,"outcome":"Over","opposite_token_id":"78188826358032258311424545486331333398838521699262460256542567713692269401385","resolved":true,"final_price":0.0,"title":"Map 1 Total Rounds: Over/Under 30.5","market_slug":"cs2-bb3-lgc-2026-12-03-game1-round-total-30pt5","closed":true,"neg_risk":false,"neg_risk_market_id":null,"question_index":null,"event_id":1495714,"event_slug":"cs2-bb3-lgc-2026-12-03"}]}},
|
||||
"multi": {"url":"https://data-api.polymarket.com/v2/tokens?token_id=759916398134244316868652908232832573045153963965173623897622651599218278401%2C123%2C759916398134244316868652908232832573045153963965173623897622651599218278400%2C759916398134244316868652908232832573045153963965173623897622651599218278401","status":200,"date":"Fri, 04 Dec 2026 20:59:34 GMT","body":{"data":[{"token_id":"759916398134244316868652908232832573045153963965173623897622651599218278401","condition_id":"0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","structural_condition_id":"0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","module":"binary","outcome_index":1,"clob_index":null,"outcome":"Fokin Illia","opposite_token_id":"759916398134244316868652908232832573045153963965173623897622651599218278400","resolved":true,"final_price":0.0,"title":"Nikolenko Anatolii vs. Fokin Illia","market_slug":"setkameua-anat-illia-2026-12-03","closed":true,"neg_risk":false,"neg_risk_market_id":null,"question_index":null,"event_id":1496938,"event_slug":"setkameua-anat-illia-2026-12-03"},{"token_id":"759916398134244316868652908232832573045153963965173623897622651599218278400","condition_id":"0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","structural_condition_id":"0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","module":"binary","outcome_index":0,"clob_index":null,"outcome":"Nikolenko Anatolii","opposite_token_id":"759916398134244316868652908232832573045153963965173623897622651599218278401","resolved":true,"final_price":1.0,"title":"Nikolenko Anatolii vs. Fokin Illia","market_slug":"setkameua-anat-illia-2026-12-03","closed":true,"neg_risk":false,"neg_risk_market_id":null,"question_index":null,"event_id":1496938,"event_slug":"setkameua-anat-illia-2026-12-03"}]}},
|
||||
"both": {"url":"https://data-api.polymarket.com/v2/tokens?token_id=759916398134244316868652908232832573045153963965173623897622651599218278400&condition=0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","status":400,"date":"Fri, 04 Dec 2026 20:59:34 GMT","body":{"error":"provide exactly one of 'token_id' or 'condition'","code":"invalid_request","retryable":false}},
|
||||
"none": {"url":"https://data-api.polymarket.com/v2/tokens?","status":400,"date":"Fri, 04 Dec 2026 20:59:34 GMT","body":{"error":"provide exactly one of 'token_id' or 'condition'","code":"invalid_request","retryable":false}},
|
||||
"missing": {"url":"https://data-api.polymarket.com/v2/tokens?token_id=123","status":200,"date":"Fri, 04 Dec 2026 20:59:34 GMT","body":{"data":[]}},
|
||||
"malformed": {"url":"https://data-api.polymarket.com/v2/tokens?token_id=abc","status":400,"date":"Fri, 04 Dec 2026 20:59:34 GMT","body":{"error":"invalid token id: abc","code":"invalid_request","parameter":"token_id","retryable":false}},
|
||||
"bad_condition": {"url":"https://data-api.polymarket.com/v2/tokens?condition=invalid","status":400,"date":"Fri, 04 Dec 2026 20:59:34 GMT","body":{"error":"invalid condition id: invalid","code":"invalid_request","parameter":"condition","retryable":false}},
|
||||
"unknown_condition": {"url":"https://data-api.polymarket.com/v2/tokens?condition=0x0000000000000000000000000000000000000000000000000000000000000000","status":200,"date":"Fri, 04 Dec 2026 20:59:34 GMT","body":{"data":[]}},
|
||||
"multi_condition": {"url":"https://data-api.polymarket.com/v2/tokens?condition=0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000%2C0xdf04a0495b0a16dbce386acdc16d9aed19784db9888be53d150354b83b7c18b1","status":200,"date":"Fri, 04 Dec 2026 20:59:35 GMT","body":{"data":[{"token_id":"759916398134244316868652908232832573045153963965173623897622651599218278400","condition_id":"0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","structural_condition_id":"0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","module":"binary","outcome_index":0,"clob_index":null,"outcome":"Nikolenko Anatolii","opposite_token_id":"759916398134244316868652908232832573045153963965173623897622651599218278401","resolved":true,"final_price":1.0,"title":"Nikolenko Anatolii vs. Fokin Illia","market_slug":"setkameua-anat-illia-2026-12-03","closed":true,"neg_risk":false,"neg_risk_market_id":null,"question_index":null,"event_id":1496938,"event_slug":"setkameua-anat-illia-2026-12-03"},{"token_id":"759916398134244316868652908232832573045153963965173623897622651599218278401","condition_id":"0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","structural_condition_id":"0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","module":"binary","outcome_index":1,"clob_index":null,"outcome":"Fokin Illia","opposite_token_id":"759916398134244316868652908232832573045153963965173623897622651599218278400","resolved":true,"final_price":0.0,"title":"Nikolenko Anatolii vs. Fokin Illia","market_slug":"setkameua-anat-illia-2026-12-03","closed":true,"neg_risk":false,"neg_risk_market_id":null,"question_index":null,"event_id":1496938,"event_slug":"setkameua-anat-illia-2026-12-03"},{"token_id":"73979342585906843441145134109923710004884703083095161594360108477170435492453","condition_id":"0xdf04a0495b0a16dbce386acdc16d9aed19784db9888be53d150354b83b7c18b1","structural_condition_id":null,"module":"v1_ctf","outcome_index":0,"clob_index":0,"outcome":"Over","opposite_token_id":"78188826358032258311424545486331333398838521699262460256542567713692269401385","resolved":true,"final_price":0.0,"title":"Map 1 Total Rounds: Over/Under 30.5","market_slug":"cs2-bb3-lgc-2026-12-03-game1-round-total-30pt5","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":"78188826358032258311424545486331333398838521699262460256542567713692269401385","condition_id":"0xdf04a0495b0a16dbce386acdc16d9aed19784db9888be53d150354b83b7c18b1","structural_condition_id":null,"module":"v1_ctf","outcome_index":1,"clob_index":1,"outcome":"Under","opposite_token_id":"73979342585906843441145134109923710004884703083095161594360108477170435492453","resolved":true,"final_price":1.0,"title":"Map 1 Total Rounds: Over/Under 30.5","market_slug":"cs2-bb3-lgc-2026-12-03-game1-round-total-30pt5","closed":true,"neg_risk":false,"neg_risk_market_id":null,"question_index":null,"event_id":1495714,"event_slug":"cs2-bb3-lgc-2026-12-03"}]}},
|
||||
"plural": {"url":"https://data-api.polymarket.com/v2/tokens?token_ids=759916398134244316868652908232832573045153963965173623897622651599218278400","status":200,"date":"Fri, 04 Dec 2026 21:00:05 GMT","body":{"data":[{"token_id":"759916398134244316868652908232832573045153963965173623897622651599218278400","condition_id":"0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","structural_condition_id":"0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","module":"binary","outcome_index":0,"clob_index":null,"outcome":"Nikolenko Anatolii","opposite_token_id":"759916398134244316868652908232832573045153963965173623897622651599218278401","resolved":true,"final_price":1.0,"title":"Nikolenko Anatolii vs. Fokin Illia","market_slug":"setkameua-anat-illia-2026-12-03","closed":true,"neg_risk":false,"neg_risk_market_id":null,"question_index":null,"event_id":1496938,"event_slug":"setkameua-anat-illia-2026-12-03"}]}},
|
||||
"zero_prefix": {"url":"https://data-api.polymarket.com/v2/tokens?token_id=000759916398134244316868652908232832573045153963965173623897622651599218278400","status":200,"date":"Fri, 04 Dec 2026 21:00:05 GMT","body":{"data":[{"token_id":"759916398134244316868652908232832573045153963965173623897622651599218278400","condition_id":"0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","structural_condition_id":"0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","module":"binary","outcome_index":0,"clob_index":null,"outcome":"Nikolenko Anatolii","opposite_token_id":"759916398134244316868652908232832573045153963965173623897622651599218278401","resolved":true,"final_price":1.0,"title":"Nikolenko Anatolii vs. Fokin Illia","market_slug":"setkameua-anat-illia-2026-12-03","closed":true,"neg_risk":false,"neg_risk_market_id":null,"question_index":null,"event_id":1496938,"event_slug":"setkameua-anat-illia-2026-12-03"}]}},
|
||||
"empty_token": {"url":"https://data-api.polymarket.com/v2/tokens?token_id=","status":400,"date":"Fri, 04 Dec 2026 21:00:05 GMT","body":{"error":"provide exactly one of 'token_id' or 'condition'","code":"invalid_request","retryable":false}},
|
||||
"huge": {"url":"https://data-api.polymarket.com/v2/tokens?token_id=999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999","status":400,"date":"Fri, 04 Dec 2026 21:00:05 GMT","body":{"error":"invalid token id: 999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999","code":"invalid_request","parameter":"token_id","retryable":false}},
|
||||
"short_condition": {"url":"https://data-api.polymarket.com/v2/tokens?condition=0x01ae18f1c798f53d0efe0903889e57483c0000000000000000000000000000","status":200,"date":"Fri, 04 Dec 2026 21:00:05 GMT","body":{"data":[{"token_id":"759916398134244316868652908232832573045153963965173623897622651599218278400","condition_id":"0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","structural_condition_id":"0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","module":"binary","outcome_index":0,"clob_index":null,"outcome":"Nikolenko Anatolii","opposite_token_id":"759916398134244316868652908232832573045153963965173623897622651599218278401","resolved":true,"final_price":1.0,"title":"Nikolenko Anatolii vs. Fokin Illia","market_slug":"setkameua-anat-illia-2026-12-03","closed":true,"neg_risk":false,"neg_risk_market_id":null,"question_index":null,"event_id":1496938,"event_slug":"setkameua-anat-illia-2026-12-03"},{"token_id":"759916398134244316868652908232832573045153963965173623897622651599218278401","condition_id":"0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","structural_condition_id":"0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","module":"binary","outcome_index":1,"clob_index":null,"outcome":"Fokin Illia","opposite_token_id":"759916398134244316868652908232832573045153963965173623897622651599218278400","resolved":true,"final_price":0.0,"title":"Nikolenko Anatolii vs. Fokin Illia","market_slug":"setkameua-anat-illia-2026-12-03","closed":true,"neg_risk":false,"neg_risk_market_id":null,"question_index":null,"event_id":1496938,"event_slug":"setkameua-anat-illia-2026-12-03"}]}},
|
||||
"cap_tokens": {"url":"https://data-api.polymarket.com/v2/tokens?token_id=0%2C1%2C2%2C3%2C4%2C5%2C6%2C7%2C8%2C9%2C10%2C11%2C12%2C13%2C14%2C15%2C16%2C17%2C18%2C19%2C20%2C21%2C22%2C23%2C24%2C25%2C26%2C27%2C28%2C29%2C30%2C31%2C32%2C33%2C34%2C35%2C36%2C37%2C38%2C39%2C40%2C41%2C42%2C43%2C44%2C45%2C46%2C47%2C48%2C49%2C50","status":400,"date":"Fri, 04 Dec 2026 21:00:05 GMT","body":{"error":"'token_id' accepts at most 50 distinct values","code":"invalid_request","parameter":"token_id","retryable":false}}
|
||||
}
|
||||
+11
-18
@@ -417,24 +417,6 @@ fidelity 以分钟为单位;省略或不大于零时按 1 分钟处理。相
|
||||
|
||||
官方 OpenAPI 给出的 condition 和 event 查询按条件返回,question 查询以问题为单位。两种查询的更新时间分别是 UTC 时间和 Unix 秒数字符串。本地使用记录下来的提案、争议和兑付时间。早期数据库缺失的时间保留为空。本地未接入链上事件,交易哈希和日志序号保留空串,区块号、报告人及投票截止估计省略。new_version_q 采用 OpenAPI 对规则修订的定义,本地原始规则不可改。旧版官方子图在 QuestionInitialized 上直接置 true,这一点存在口径差异。提案到期后需按模拟系统的最终确认流程兑付。本次按规范、合约及子图核对,生产端点没有取得可重放的响应。[官方接口](https://docs.polymarket.com/api-reference/markets/get-resolution-state) · [OpenAPI](https://data-api.polymarket.com/v2/openapi.json) · [UMA 适配器](https://github.com/Polymarket/uma-ctf-adapter/blob/main/src/UmaCtfAdapter.sol) · [裁决子图](https://github.com/Polymarket/resolution-subgraph/blob/main/src/uma-ctf-adapter.ts)
|
||||
|
||||
### CTF 链上兑付核对
|
||||
|
||||
从已封盘的 CS2 市场目录读取 `conditionId` 和结果顺序,在两个 Polygon 节点用同一最终确认区块 `0x5df5831` 读取 CTF。结果数为 2,按目录顺序的兑付分子为 [0,1],分母为 1,对应 Under 胜出。实测 ABI 字可由 `venue-probe --replay-resolution` 离线核对,也可指定 `second` 作为预期。此次取样验证了该 CTF 条件,真实预言机证明及链上同步入账仍待覆盖。[生产目录记录](examples/public-closed-chart-history.json) · [双节点链上记录](../crates/venue-probe/fixtures/live-ctf-resolution.json)
|
||||
|
||||
### PositionManager V2 链上兑付核对
|
||||
|
||||
V2 市场以两项 Position ID 共享的高 31 字节表示条件,首字节标记模块。探针用该模块编号查询 PositionManager 注册表,再从模块读取按目录顺序排列的兑付权重。生产 Binary 样本在两个 Polygon 节点的最终确认区块 `0x5df5912` 均返回 `[1000000, 0]`,与 Gamma 第一结果获胜一致。两个权重的分母固定为 100 万,空数组表示合约当前没有可读取的结果。NegRisk 的二元约束有离线用例,仍缺少生产目录关联样本。组合盘的只读核对见下节。独立链上状态证明和同步入账仍待覆盖。[探针时序与重放](../crates/venue-probe/README.md#polygon-positionmanager-v2-裁决核对) · [双节点记录](../crates/venue-probe/fixtures/live-position-resolutions.json) · [官方 V2 模块文档](https://github.com/Polymarket/polymarket-v2-external/blob/main/docs/modules.md)
|
||||
|
||||
### PositionManager V2 组合兑付核对
|
||||
|
||||
组合模块保存排序后的 Binary 或 NegRisk Position ID。探针在同一最终确认区块读取登记的腿,向合约查询同样份额的 YES 和 NO 兑付。只在两侧均返回已知的待兑付错误时报告待裁决。一条已裁决腿的兑付为零时,YES 已确定为零,NO 可取得全部对应金额;其余腿仍可处于待裁决状态。其余可兑付情况以合约返回的逐侧金额为准,两个方向分别取整,兑付合计可以少于原份额对应的抵押。[官方合约](https://github.com/Polymarket/polymarket-v2-external/blob/main/src/modules/CombinatorialModule.sol)
|
||||
|
||||
区块 `0x5df5ab2` 的原始记录涵盖一份双侧待裁决的组合和一份已经可兑付的组合。后者按 1000001 微份查询返回 YES 0、NO 1000001 微美元。按链上腿顺序复查,四个兑付权重分别为待裁决、零、待裁决、待裁决。样本来自链上登记交易,仍缺少对应前端及 RFQ 的同盘关联。进一步把链上裁决导入本地账本仍待实现。[原始样本](../crates/venue-probe/fixtures/live-combo-payouts.json)
|
||||
|
||||
### V2 互斥组的推导与迁移例外
|
||||
|
||||
`getResult` 提供有效兑付,原始 `result` getter 可以核对结果是否直接写入。Polygon 区块 `0x5df5c43` 至 `0x5df5c44` 的样本中,组内出现赢家后,合成「其他」的有效权重由空变为 `[0,1000000]`,直接存储仍为空。区块 `0x5df5c62` 的另一组有 37 个真实条件,直接报告 33 个。四个未报告真实条件的有效权重仍为空,合成「其他」已有 NO 兑付。该组的链上旧盘映射将四个条件对应到 Gamma 的 5–3、4–5、5–4 和 5–5 精确比分盘。同一区块的旧 CTF 兑付分母均为 1,V2 仍待裁决。本地组合账本尚未接入这条迁移路径。原生组的未报告输家与通过全 NO 推导「其他」为 YES,仍缺生产样本。[链上样本](../crates/venue-probe/fixtures/live-negrisk-resolution.json) · [官方 NegRisk 逻辑](https://github.com/Polymarket/polymarket-v2-external/blob/main/src/modules/NegRiskModule.sol)
|
||||
|
||||
### Data API 账户持仓价值
|
||||
|
||||
官方 `GET /v2/value` 要求传 user,可选最多 20 个不同 condition。结果是 data 对象,内含 proxy_wallet 和四位小数精度的美元金额。一个无持仓的钱包值为零。官方总额还包括未终结组合的成本基础,指定 condition 时仅统计选中的单盘。资金余额不计入持仓价值。[官方 OpenAPI](https://data-api.polymarket.com/v2/openapi.json)
|
||||
@@ -489,3 +471,14 @@ SDK 使用 `GET /neg-risk?token_id=…`,也可以从已缓存的 CLOB 市场
|
||||
### 已裁决市场的公开盘口
|
||||
|
||||
对电竞、乒乓球和 SOL 涨跌盘的六个已裁决结果单查 /book,全部返回 404。批量 /books 和 /prices 忽略已裁决资产,混合批次保留可用资产。中点和价差多数同样返回 404,但一个 V2 市场的两侧分别仍能读到价差 1 或中点 0.5。Eventbook 对已裁决结果统一省略四种公开行情,保留内部快照供交易状态和回放。封盘待裁决阶段、外场淘汰时延和例外是否由服务缓存触发仍待验证。[生产响应](examples/public-resolved-books.json)
|
||||
|
||||
### Data API 资产反查
|
||||
|
||||
GET /v2/tokens 接受 token_id / token_ids 或 condition / condition_id / conditionId,二选一。生产样本中,资产查询保持请求顺序并合并重复项,数字标识的前导零会被归一。合法的未知资产返回空数组。用本地市场 ID 返回 YES、NO 两侧,用本地互斥组 ID 按题目序号展开成员。已裁决市场可返回最终兑付值,VOID 有两项 0.5。回执保留稳定的本地 eb 标识并自描述本地模块。对照样本覆盖原生 V2、CTF 和短条件 ID。外场同一市场的多协议资产通过后文的绑定命令接入本地目录。[生产请求和响应](examples/public-token-directory.json) · [官方 OpenAPI](https://data-api.polymarket.com/v2/openapi.json)
|
||||
|
||||
### 本地登记 Polymarket 资产对照
|
||||
|
||||
可信 JSONL 命令 bind_polymarket_assets 接受本地市场、external_condition、zero_outcome 及官方 data 数组。每种协议必须提供互补一对。登记时核对 V2 编码、互斥组与题目归属,禁止冲突重绑。登记后用外场数字资产或条件查询 /v2/tokens 可得到原协议观察字段及 local_asset_id。旧 CTF 互斥组查询返回已登记的两类资产,完整 V2 Neg Risk 事件 ID 只展开已登记的结构仓位。以 62 位十六进制条件查询题目零时,仍只返回单个题目。外场状态与兑付值由观测快照提供。[三题生产样本](examples/polymarket-token-event.json) · [生产登记样本](examples/polymarket-asset-binding.json)
|
||||
|
||||
|
||||
对同一绑定重复提交带 observed_at_ms 的配对可刷新状态及结果标签。旧观测不会覆盖更新状态,同毫秒互相矛盾的快照和推翻最终兑付的请求会拒绝,整笔事务回滚。反查回执带观测时间。一个此前能公开读取盘口的电竞盘,后续 CTF 与 V2 目录均返回裁决输赢。回归使用它的真实裁决响应,并用同一资产生成开放快照来覆盖乱序。`cli DATABASE --refresh-polymarket [MARKET]` 可按需拉取已登记资产的完整快照。HTTP Date 表示响应时间,裁决数据的实际发布时间和传播时延仍待验证。[生产盘口及裁决快照](examples/polymarket-asset-refresh.json)
|
||||
Reference in new issue
Block a user