Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
77b5304d08 | ||
|
|
284c6ee4ec | ||
|
|
f220cd4b58 | ||
|
|
30e4a5cd17 | ||
|
|
74b7655723 | ||
|
|
9d541c563b | ||
|
|
e6a914b381 |
No files matched your search
+3
-18
@@ -183,6 +183,8 @@ sequenceDiagram
|
||||
|
||||
路径参数使用百分号编码。即使查询从 NO 开始,primary_token_id 仍对应 YES。可重放请求见[行情 HTTP 示例](../../docs/examples/clob-http.http)。
|
||||
|
||||
已裁决资产的公开盘口、买卖报价、中点和价差单查返回 404,批查跳过该资产。
|
||||
|
||||
### 查询盘口价差与中点
|
||||
|
||||
```mermaid
|
||||
@@ -221,7 +223,7 @@ sequenceDiagram
|
||||
participant E as prices_history/legacy.rs
|
||||
C->>H: GET /prices-history,market 与 interval 或 startTs、endTs
|
||||
H->>E: clob_price_history,fidelity 以分钟计
|
||||
E-->>H: 返回窗口内盘口中点样本,末尾追加最近可用点
|
||||
E-->>H: 返回窗口内盘口中点样本,未封盘时追加最近可用点
|
||||
H-->>C: history 数组,每点包含 t 和 p
|
||||
```
|
||||
|
||||
@@ -336,23 +338,6 @@ sequenceDiagram
|
||||
H-->>C: 200 data 数组,未找到返回空数组
|
||||
```
|
||||
|
||||
### 查询公开持仓榜
|
||||
|
||||
`GET /v2/holders?condition=cup&limit=10` 按每个结果资产返回净持仓排名。传入 include_pnl=true 改查毛持仓,并返回可计算的持仓成本和盈亏。该模式限单个市场、每侧最多 100 行。续页要重新传 condition 及需要的筛选条件,并使用 pagination.next_cursor。按 token_id 合并翻页结果。
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as 客户端
|
||||
participant H as market_http.rs
|
||||
participant E as Exchange
|
||||
C->>H: GET /v2/holders,指定 condition 和可选 include_pnl
|
||||
H->>E: 查各结果资产的排名
|
||||
opt 毛持仓模式
|
||||
E->>E: 重放本页账户的账本流水,补充成本和盈亏
|
||||
end
|
||||
E-->>C: data 按 token_id 分组,pagination 提供续页游标
|
||||
```
|
||||
|
||||
### 查询持仓价值
|
||||
|
||||
`GET /v2/value?user=alice&condition=e` 返回该账户在市场 e 的持仓价值,单位为模拟美元。使用已登记的本地账户名或 20 字节钱包地址。省略 condition 查询所有已持有市场。无持仓的钱包返回零,仅有现金的账户也返回零。
|
||||
|
||||
@@ -329,12 +329,7 @@ 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/holders"
|
||||
"/v2/prices-history" | "/v2/trades" | "/v2/resolutions" | "/v2/value" | "/v2/oi"
|
||||
)
|
||||
{
|
||||
let (status, body) = data_page(path, params, engine);
|
||||
@@ -479,7 +474,6 @@ fn respond(mut req: Request, engine: &Mutex<Exchange>) -> std::io::Result<()> {
|
||||
| "/v2/oi"
|
||||
| "/v2/value"
|
||||
| "/v2/trades"
|
||||
| "/v2/holders"
|
||||
| "/v2/resolutions"
|
||||
| "/v2/prices-history",
|
||||
) => {
|
||||
@@ -522,28 +516,15 @@ fn data_page(path: &str, params: &str, engine: &Mutex<Exchange>) -> (u16, Value)
|
||||
"/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),
|
||||
"/v2/holders" => read_page(params, engine, Exchange::public_holders),
|
||||
"/v2/resolutions" => read_page(params, engine, Exchange::public_resolutions),
|
||||
_ => read_page(params, engine, Exchange::public_price_history),
|
||||
};
|
||||
match page {
|
||||
Ok(data) => (200, data),
|
||||
Err(HistoryError::Invalid(message)) => {
|
||||
let mut error = json!({"code":"invalid_request","error":message,"retryable":false});
|
||||
if path == "/v2/holders" {
|
||||
let parameter = match message.as_str() {
|
||||
"required query param 'condition' not provided"
|
||||
| "include_pnl accepts exactly one 'condition' per call" => Some("condition"),
|
||||
"limit must be at most 100 with include_pnl" => Some("limit"),
|
||||
msg if msg.starts_with("invalid condition id:") => Some("condition"),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(parameter) = parameter {
|
||||
error["parameter"] = json!(parameter);
|
||||
}
|
||||
}
|
||||
(400, error)
|
||||
}
|
||||
Err(HistoryError::Invalid(message)) => (
|
||||
400,
|
||||
json!({"code":"invalid_request","error":message,"retryable":false}),
|
||||
),
|
||||
Err(HistoryError::Unavailable) if path == "/v2/oi" => (
|
||||
503,
|
||||
json!({"code":"unavailable","error":"open interest unavailable","retryable":true}),
|
||||
@@ -556,10 +537,6 @@ fn data_page(path: &str, params: &str, engine: &Mutex<Exchange>) -> (u16, Value)
|
||||
500,
|
||||
json!({"code":"internal","error":"resolution state unavailable","retryable":true}),
|
||||
),
|
||||
Err(HistoryError::Unavailable) if path == "/v2/holders" => (
|
||||
500,
|
||||
json!({"code":"internal","error":"holders unavailable","retryable":true}),
|
||||
),
|
||||
Err(HistoryError::Unavailable) if path == "/v2/trades" => (
|
||||
500,
|
||||
json!({"code":"internal","error":"trade feed unavailable","retryable":true}),
|
||||
@@ -640,6 +617,9 @@ mod tests {
|
||||
let lookup_info = json!({"mbf":0,"tbf":30,"fd":{"r":0.05,"e":1,"to":true},"gst":null,"nr":false,"rfqe":false,"ibce":false,"oas":0,"mos":0.01,"mts":0.0025,
|
||||
"t":[{"o":"YES","t":"eb:YES:map+2/1"},{"o":"NO","t":"eb:NO:map+2/1"}]});
|
||||
for command in [
|
||||
json!({"op":"list","id":"resolved-list","market":"resolved-test","rules":"resolved fixture"}),
|
||||
json!({"op":"close","id":"resolved-close","market":"resolved-test"}),
|
||||
json!({"op":"finalize","id":"resolved-final","market":"resolved-test","winner":"YES"}),
|
||||
json!({"op":"fund","id":"v-fund","account":"unpriced-owner","cents":100}),
|
||||
json!({"op":"list","id":"v-list","market":"unpriced","rules":"valuation fixture"}),
|
||||
json!({"op":"split","id":"v-split","account":"unpriced-owner","market":"unpriced","qty":1}),
|
||||
@@ -726,11 +706,6 @@ mod tests {
|
||||
("GET","/v2/trades?user=unknown&conditionId=unknown&takerOnly=false",String::new(),200,Some(empty_trades)),
|
||||
("GET","/v2/trades?offset=2",String::new(),400,None),
|
||||
("GET","/v2/trades?cursor=invalid",String::new(),400,None),
|
||||
("GET","/v2/holders",String::new(),400,Some(json!({"code":"invalid_request","error":"required query param 'condition' not provided","parameter":"condition","retryable":false}))),
|
||||
("GET","/v2/holders?condition=s&limit=0",String::new(),200,Some(json!({"data":[],"pagination":{"limit":0,"offset":0,"has_more":false,"next_cursor":null}}))),
|
||||
("GET","/v2/holders?condition=s&includePnl=true&limit=101",String::new(),400,Some(json!({"code":"invalid_request","error":"limit must be at most 100 with include_pnl","parameter":"limit","retryable":false}))),
|
||||
("GET","/v2/holders?condition=s&offset=0",String::new(),400,None),
|
||||
("POST","/v2/holders","{}".into(),405,None),
|
||||
("GET","/v2/resolutions?condition=unknown",String::new(),200,Some(json!({"data":[]}))),
|
||||
("GET","/v2/resolutions?condition=m&eventId=1",String::new(),400,None),
|
||||
("GET","/v2/resolutions?questionId=invalid",String::new(),400,None),
|
||||
@@ -783,6 +758,14 @@ mod tests {
|
||||
("POST","/prices",json!([{"token_id":"eb:YES:s"}]).to_string(),200,Some(json!({"eb:YES:s":{"SELL":"0.41"}}))),
|
||||
("POST","/prices",json!(vec![json!({"token_id":"eb:YES:s","side":"BUY"}); MAX_BOOKS+1]).to_string(),400,None),
|
||||
("DELETE","/prices",String::new(),405,None),
|
||||
("GET","/book?token_id=eb:YES:resolved-test",String::new(),404,Some(json!({"error":MISSING}))),
|
||||
("GET","/price?token_id=eb:YES:resolved-test&side=BUY",String::new(),404,Some(json!({"error":MISSING}))),
|
||||
("GET","/midpoint?token_id=eb:NO:resolved-test",String::new(),404,Some(json!({"error":MISSING}))),
|
||||
("GET","/spread?token_id=eb:NO:resolved-test",String::new(),404,Some(json!({"error":MISSING}))),
|
||||
("POST","/books",json!([{"token_id":"eb:YES:resolved-test"},{"token_id":yes}]).to_string(),200,Some(json!([expected_yes.clone()]))),
|
||||
("POST","/prices",json!([{"token_id":"eb:YES:resolved-test","side":"BUY"},{"token_id":"eb:YES:s","side":"BUY"}]).to_string(),200,Some(json!({"eb:YES:s":{"BUY":"0.39"}}))),
|
||||
("POST","/midpoints",json!([{"token_id":"eb:YES:resolved-test"},{"token_id":"eb:YES:s"}]).to_string(),200,Some(json!({"eb:YES:s":"0.4"}))),
|
||||
("POST","/spreads",json!([{"token_id":"eb:YES:resolved-test"}]).to_string(),200,Some(json!({}))),
|
||||
("GET","/midpoint?token_id=eb:YES:mid-example",String::new(),200,Some(json!({"mid":"0.085"}))),
|
||||
("POST","/midpoints",json!([{"token_id":"eb:YES:mid-example"},{"token_id":"eb:NO:mid-example"}]).to_string(),200,Some(sample)),
|
||||
("GET","/midpoint?token_id=eb:YES:s",String::new(),200,Some(json!({"mid":"0.4"}))),
|
||||
|
||||
@@ -716,17 +716,6 @@ sequenceDiagram
|
||||
E-->>C: 返回该结果资产的旧步长、新步长、时间和游标
|
||||
```
|
||||
|
||||
公开榜单经 `holders/http.rs` 复用同一排名与估值。毛持仓模式中,`holders/economics.sql` 回读本页账户的成交与钱包操作,`holders/economics.rs` 计算成本和盈亏。账本顺序由 `holders/economics_schema.sql` 的触发器记录。同一毫秒发生的成交和持仓操作也能按写入顺序重放。旧数据缺少明确顺序或转换成本时,相关经济字段返回 null。
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
H["holders/http.rs"] --> L["holders.rs / holders.sql"]
|
||||
H --> E["holders/economics.rs"]
|
||||
E --> Q["holders/economics.sql"]
|
||||
Q --> S["holders/economics_schema.sql"]
|
||||
I["lib.rs · Exchange::open"] --> S
|
||||
```
|
||||
|
||||
### 体育赛事开赛撤单
|
||||
|
||||
```mermaid
|
||||
@@ -1118,7 +1107,7 @@ sequenceDiagram
|
||||
E->>D: 先处理到期订单,再从同一快照读取各市场最新 quote_events
|
||||
D-->>E: 返回 YES 的买一和卖一
|
||||
E->>E: 换算结果方向,缺买盘取 0、缺卖盘取 1,计算价差或中点
|
||||
E-->>C: 按结果资产索引,未上市资产无条目
|
||||
E-->>C: 按结果资产索引,跳过未上市和已裁决资产
|
||||
```
|
||||
|
||||
HTTP 盘口查询由 public_book_prices 读取 quote_events,先清理到期任务,再在同一快照中读取各市场。BUY 取买一,SELL 取卖一。下单面板的 JSONL 命令继续查询最优对手价。
|
||||
@@ -1144,7 +1133,7 @@ flowchart LR
|
||||
L --> A["assets.rs"]
|
||||
L --> Q["prices_history/legacy.sql"]
|
||||
Q --> T["quote_schema.sql 中的 quote_events"]
|
||||
Q --> O["prices_history/chart_schema.sql 中的采样起点和时间索引"]
|
||||
Q --> O["prices_history/chart_schema.sql 中的采样起点、封盘时间和时间索引"]
|
||||
API["lib.rs"] --> O
|
||||
Q --> S["schema.sql 中的 price_settlements"]
|
||||
```
|
||||
@@ -1156,7 +1145,7 @@ sequenceDiagram
|
||||
participant D as SQLite
|
||||
C->>E: clob_price_history
|
||||
E->>D: 清理到期委托并取得读快照与数据库时钟
|
||||
E->>D: 按 UTC 分钟网格重放各采样点当时的盘口,再读取最近可用点
|
||||
E->>D: 按 UTC 分钟网格重放盘口,封盘后只取窗口内的封盘前样本
|
||||
D-->>E: 观测时间和定点价格
|
||||
E-->>C: t 为 Unix 秒,p 为十进制数
|
||||
```
|
||||
|
||||
@@ -45,7 +45,7 @@ impl Snapshot {
|
||||
|
||||
fn build(tx: &Transaction, books: &Books, token: &str) -> Result<Snapshot> {
|
||||
let (outcome, market) = assets::parse_id(token)?;
|
||||
find(tx, books, token, outcome, market)?
|
||||
find(tx, books, token, outcome, market, false)?
|
||||
.context("No orderbook exists for the requested token id")
|
||||
}
|
||||
|
||||
@@ -55,12 +55,14 @@ fn find(
|
||||
token: &str,
|
||||
outcome: &str,
|
||||
market: &str,
|
||||
public_only: bool,
|
||||
) -> Result<Option<Snapshot>> {
|
||||
let row: Option<(i64, bool)> = tx
|
||||
.query_row(
|
||||
"SELECT at_ms,EXISTS(SELECT 1 FROM neg_risk_members WHERE market=?1)
|
||||
FROM book_snapshot_times WHERE market=?1",
|
||||
[market],
|
||||
FROM book_snapshot_times b JOIN markets m ON m.id=b.market
|
||||
WHERE b.market=?1 AND (NOT ?2 OR m.phase<>'resolved')",
|
||||
rusqlite::params![market, public_only],
|
||||
|r| Ok((r.get(0)?, r.get(1)?)),
|
||||
)
|
||||
.optional()?;
|
||||
@@ -114,7 +116,7 @@ pub(crate) fn read_many(
|
||||
let mut result = Vec::with_capacity(tokens.len());
|
||||
for token in tokens {
|
||||
if let Ok((outcome, market)) = assets::parse_id(token) {
|
||||
if let Some(book) = find(tx, books, token, outcome, market)? {
|
||||
if let Some(book) = find(tx, books, token, outcome, market, true)? {
|
||||
result.push(serde_json::to_value(book)?);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
mod economics;
|
||||
pub(crate) mod http;
|
||||
|
||||
use crate::{assets, portfolio, validation::identifier};
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use rusqlite::{params, Connection};
|
||||
@@ -130,22 +127,9 @@ impl Request {
|
||||
|
||||
pub fn read(self, db: &Connection) -> Result<Value> {
|
||||
let mut page = self.page()?;
|
||||
let (data, more) = page.read(db)?;
|
||||
page.offset = page
|
||||
.offset
|
||||
.checked_add(i64::from(page.limit))
|
||||
.context("holders offset overflow")?;
|
||||
let cursor = more.then(|| serde_json::to_string(&page)).transpose()?;
|
||||
Ok(json!({"basis":page.basis,"data":data,"next_cursor":cursor}))
|
||||
}
|
||||
}
|
||||
|
||||
impl Page {
|
||||
fn read(&self, db: &Connection) -> Result<(Vec<Value>, bool)> {
|
||||
let page = self;
|
||||
let minimum = minimum_units(&page.min_balance)?;
|
||||
if page.limit == 0 || minimum.is_none() {
|
||||
return Ok((Vec::new(), false));
|
||||
return Ok(json!({"basis":page.basis,"data":[],"next_cursor":null}));
|
||||
}
|
||||
let end = page
|
||||
.offset
|
||||
@@ -202,6 +186,12 @@ impl Page {
|
||||
data.push(json!({"market":market,"asset_id":assets::id(market,outcome),"outcome":outcome,"holders":holders}));
|
||||
}
|
||||
}
|
||||
Ok((data, more))
|
||||
page.offset = end;
|
||||
let cursor = if more {
|
||||
Some(serde_json::to_string(&page)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok(json!({"basis":page.basis,"data":data,"next_cursor":cursor}))
|
||||
}
|
||||
}
|
||||
@@ -1,174 +0,0 @@
|
||||
use crate::inventory::{decimal, UNIT};
|
||||
use rusqlite::{params, Connection, Row};
|
||||
use serde_json::{json, Value};
|
||||
use std::collections::HashMap;
|
||||
|
||||
#[derive(Default)]
|
||||
struct Side {
|
||||
units: i128,
|
||||
cost: i128,
|
||||
realized: i128,
|
||||
}
|
||||
|
||||
impl Side {
|
||||
fn acquire(&mut self, units: i128, cost: i128) -> bool {
|
||||
if units < 0 || !(0..=units).contains(&cost) || self.units + units > i128::from(i64::MAX) {
|
||||
return false;
|
||||
}
|
||||
self.units += units;
|
||||
self.cost += cost;
|
||||
true
|
||||
}
|
||||
|
||||
fn dispose(&mut self, units: i128, proceeds: i128) -> bool {
|
||||
if units < 0 || units > self.units {
|
||||
return false;
|
||||
}
|
||||
if units > 0 {
|
||||
let removed = self.cost * units / self.units;
|
||||
self.cost -= removed;
|
||||
self.units -= units;
|
||||
self.realized += proceeds - removed;
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Account {
|
||||
sides: [Side; 2],
|
||||
incomplete: bool,
|
||||
last_legacy: Option<(i64, i64)>,
|
||||
}
|
||||
|
||||
fn side_index(outcome: &str) -> Option<usize> {
|
||||
match outcome {
|
||||
"YES" => Some(0),
|
||||
"NO" => Some(1),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
impl Account {
|
||||
fn apply(&mut self, row: &Row<'_>, payout: [i128; 2]) -> rusqlite::Result<bool> {
|
||||
let operation: String = row.get(4)?;
|
||||
let shares = row.get::<_, Option<i64>>(6)?.map(i128::from);
|
||||
let cash = i128::from(row.get::<_, i64>(7)?);
|
||||
let fee = i128::from(row.get::<_, i64>(8)?);
|
||||
let units = match shares {
|
||||
Some(shares) if shares >= 0 => shares,
|
||||
_ => return Ok(false),
|
||||
};
|
||||
Ok(match operation.as_str() {
|
||||
"buy" | "sell" => {
|
||||
let outcome: String = row.get(5)?;
|
||||
let Some(idx) = side_index(&outcome) else {
|
||||
return Ok(false);
|
||||
};
|
||||
if operation == "buy" {
|
||||
self.sides[idx].acquire(units, cash)
|
||||
} else {
|
||||
self.sides[idx].dispose(units, cash - fee)
|
||||
}
|
||||
}
|
||||
"SPLIT" => {
|
||||
let first = -cash / 2;
|
||||
self.sides[0].acquire(units, first) && self.sides[1].acquire(units, -cash - first)
|
||||
}
|
||||
"MERGE" => {
|
||||
let first = cash / 2;
|
||||
self.sides[0].dispose(units, first) && self.sides[1].dispose(units, cash - first)
|
||||
}
|
||||
"REDEEM" => {
|
||||
let raw: Option<String> = row.get(9)?;
|
||||
let amounts: [i128; 2] = if let Some(raw) = raw {
|
||||
let Ok(values) = serde_json::from_str::<[i64; 2]>(&raw) else {
|
||||
return Ok(false);
|
||||
};
|
||||
values.map(i128::from)
|
||||
} else {
|
||||
[self.sides[0].units, self.sides[1].units]
|
||||
};
|
||||
let settled = [amounts[0] * payout[0] / 100, amounts[1] * payout[1] / 100];
|
||||
amounts.iter().sum::<i128>() == units
|
||||
&& settled.iter().sum::<i128>() == cash
|
||||
&& self.sides[0].dispose(amounts[0], settled[0])
|
||||
&& self.sides[1].dispose(amounts[1], settled[1])
|
||||
}
|
||||
// The conversion journal has group totals but no per-leg cost allocation.
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) struct Economics(HashMap<String, Account>);
|
||||
|
||||
impl Economics {
|
||||
pub fn read(db: &Connection, market: &str, accounts: &[&str]) -> rusqlite::Result<Self> {
|
||||
let winner: Option<String> =
|
||||
db.query_row("SELECT winner FROM markets WHERE id=?", [market], |r| {
|
||||
r.get(0)
|
||||
})?;
|
||||
let payout = match winner.as_deref() {
|
||||
Some("YES") => [100, 0],
|
||||
Some("NO") => [0, 100],
|
||||
Some("VOID") => [50, 50],
|
||||
_ => [0, 0],
|
||||
};
|
||||
let mut out: HashMap<String, Account> = HashMap::new();
|
||||
let mut stmt = db.prepare_cached(include_str!("economics.sql"))?;
|
||||
let mut rows = stmt.query(params![market, json!(accounts).to_string()])?;
|
||||
while let Some(row) = rows.next()? {
|
||||
let account = out.entry(row.get(0)?).or_default();
|
||||
if account.incomplete {
|
||||
continue;
|
||||
}
|
||||
if row.get::<_, Option<i64>>(3)?.is_none() {
|
||||
let source: i64 = row.get(1)?;
|
||||
let Some(at) = row.get::<_, Option<i64>>(2)? else {
|
||||
account.incomplete = true;
|
||||
continue;
|
||||
};
|
||||
if account
|
||||
.last_legacy
|
||||
.is_some_and(|(time, old_source)| time == at && source != old_source)
|
||||
{
|
||||
account.incomplete = true;
|
||||
continue;
|
||||
}
|
||||
account.last_legacy = Some((at, source));
|
||||
}
|
||||
account.incomplete = !account.apply(row, payout)?;
|
||||
}
|
||||
Ok(Self(out))
|
||||
}
|
||||
|
||||
pub fn fields(
|
||||
&self,
|
||||
account: &str,
|
||||
outcome: &str,
|
||||
units: i64,
|
||||
value: Option<i128>,
|
||||
) -> [(&'static str, Value); 5] {
|
||||
let known = self
|
||||
.0
|
||||
.get(account)
|
||||
.filter(|a| !a.incomplete)
|
||||
.and_then(|a| side_index(outcome).map(|idx| &a.sides[idx]))
|
||||
.filter(|side| side.units == i128::from(units) && side.units > 0);
|
||||
let avg = known.map(|s| decimal(s.cost * i128::from(UNIT) / s.units, UNIT));
|
||||
let cost = known.map(|s| decimal(s.cost, UNIT));
|
||||
let realized = known.map(|s| decimal(s.realized, UNIT));
|
||||
let unrealized = known.zip(value).map(|(s, v)| decimal(v - s.cost, UNIT));
|
||||
let total = known
|
||||
.zip(value)
|
||||
.map(|(s, v)| decimal(s.realized + v - s.cost, UNIT));
|
||||
[
|
||||
("avg_price", json!(avg)),
|
||||
("entry_cost_usdc", json!(cost)),
|
||||
("realized_pnl", json!(realized)),
|
||||
("unrealized_pnl", json!(unrealized)),
|
||||
("total_pnl", json!(total)),
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
WITH requested(account) AS MATERIALIZED (
|
||||
SELECT DISTINCT value FROM json_each(?2)
|
||||
), legs AS (
|
||||
SELECT t.account,1 AS source,t.execution AS record,t.order_seq AS leg,t.at_ms,
|
||||
t.side AS operation,t.outcome,
|
||||
t.quantity*10000 AS shares,t.quantity*t.price AS cash,
|
||||
COALESCE(f.fee_micros,0) AS fee,NULL AS redemption_amounts
|
||||
FROM wallet_trade_legs t JOIN requested a USING(account)
|
||||
LEFT JOIN execution_fees f ON f.execution=t.execution AND f.taker_order=t.order_seq
|
||||
WHERE t.market=?1
|
||||
UNION ALL
|
||||
SELECT w.account,0,w.id,0,w.at_ms,w.kind,NULL,
|
||||
COALESCE(p.shares_micros,w.shares*1000000),
|
||||
COALESCE(p.cash_micros,w.cash_delta*10000),0,
|
||||
CASE WHEN w.kind='REDEEM' THEN json_extract(r.response,'$.amounts_micros') END
|
||||
FROM wallet_movements w JOIN requested a USING(account)
|
||||
LEFT JOIN precise_movements p ON p.request_id=w.request_id AND p.account=w.account
|
||||
LEFT JOIN requests r ON r.id=w.request_id
|
||||
WHERE (w.market=?1 AND w.kind IN ('SPLIT','MERGE','REDEEM'))
|
||||
OR (w.kind='CONVERSION' AND EXISTS (
|
||||
SELECT 1 FROM neg_risk_members n WHERE n.market=?1 AND n.group_id=w.group_id
|
||||
))
|
||||
)
|
||||
SELECT l.account,l.source,l.at_ms,o.seq,l.operation,l.outcome,
|
||||
l.shares,l.cash,l.fee,l.redemption_amounts
|
||||
FROM legs l LEFT JOIN position_economics_order o ON o.source=l.source AND o.record=l.record
|
||||
ORDER BY l.account,o.seq IS NOT NULL,
|
||||
CASE WHEN o.seq IS NULL THEN l.at_ms END,o.seq,l.source,l.record,l.leg
|
||||
@@ -1,21 +0,0 @@
|
||||
BEGIN IMMEDIATE;
|
||||
-- Trade executions and wallet movements have independent ID sequences.
|
||||
-- Record their shared write order so a sale and a split in the same
|
||||
-- millisecond can be replayed in the order in which they committed.
|
||||
CREATE TABLE IF NOT EXISTS position_economics_order (
|
||||
seq INTEGER PRIMARY KEY,
|
||||
source INTEGER NOT NULL,
|
||||
record INTEGER NOT NULL,
|
||||
UNIQUE(source,record)
|
||||
);
|
||||
CREATE TRIGGER IF NOT EXISTS cost_order_fill AFTER INSERT ON fills BEGIN
|
||||
INSERT INTO position_economics_order(source,record) VALUES(1,NEW.seq);
|
||||
END;
|
||||
CREATE TRIGGER IF NOT EXISTS cost_order_paired AFTER INSERT ON paired_fills BEGIN
|
||||
INSERT INTO position_economics_order(source,record) VALUES(1,NEW.seq);
|
||||
END;
|
||||
CREATE TRIGGER IF NOT EXISTS cost_order_wallet AFTER INSERT ON wallet_movements
|
||||
WHEN NEW.kind IN ('SPLIT','MERGE','REDEEM','CONVERSION') BEGIN
|
||||
INSERT INTO position_economics_order(source,record) VALUES(0,NEW.id);
|
||||
END;
|
||||
COMMIT;
|
||||
@@ -1,229 +0,0 @@
|
||||
use super::{economics::Economics, minimum_units, Basis, Page};
|
||||
use crate::{
|
||||
inventory::{decimal, UNIT},
|
||||
validation::{condition_filter, hex_id},
|
||||
Exchange, MarketDataError,
|
||||
};
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use data_encoding::BASE64URL_NOPAD;
|
||||
use hmac::{Hmac, Mac};
|
||||
use rusqlite::{Connection, OptionalExtension};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Number, Value};
|
||||
use sha2::Sha256;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct HoldersQuery {
|
||||
#[serde(alias = "condition_id", alias = "conditionId")]
|
||||
condition: Option<String>,
|
||||
limit: Option<u32>,
|
||||
cursor: Option<String>,
|
||||
#[serde(alias = "minBalance")]
|
||||
min_balance: Option<String>,
|
||||
#[serde(alias = "includePnl")]
|
||||
include_pnl: Option<bool>,
|
||||
offset: Option<String>,
|
||||
#[serde(alias = "market_id", alias = "marketId")]
|
||||
market: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct Window {
|
||||
limit: u32,
|
||||
offset: i64,
|
||||
}
|
||||
|
||||
fn cursor_mac(db: &Connection) -> Result<Hmac<Sha256>> {
|
||||
let secret: Vec<u8> = db.query_row(
|
||||
"SELECT secret FROM trade_cursor_key WHERE singleton=1",
|
||||
[],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
let mut mac = Hmac::<Sha256>::new_from_slice(&secret).expect("HMAC accepts any key length");
|
||||
mac.update(b"eventbook:/v2/holders:v1\0");
|
||||
Ok(mac)
|
||||
}
|
||||
|
||||
impl Window {
|
||||
fn decode(db: &Connection, token: &str) -> Result<Self> {
|
||||
ensure!(token.len() <= 256, "invalid cursor");
|
||||
let bytes = BASE64URL_NOPAD
|
||||
.decode(token.as_bytes())
|
||||
.context("invalid cursor")?;
|
||||
let split = bytes.len().checked_sub(32).context("invalid cursor")?;
|
||||
let (payload, signature) = bytes.split_at(split);
|
||||
let mut mac = cursor_mac(db)?;
|
||||
mac.update(payload);
|
||||
mac.verify_slice(signature)
|
||||
.map_err(|_| anyhow::anyhow!("invalid cursor"))?;
|
||||
Ok(serde_json::from_slice(payload).context("invalid cursor")?)
|
||||
}
|
||||
|
||||
fn encode(&self, db: &Connection) -> Result<String> {
|
||||
let mut bytes = serde_json::to_vec(self)?;
|
||||
let mut mac = cursor_mac(db)?;
|
||||
mac.update(&bytes);
|
||||
bytes.extend_from_slice(&mac.finalize().into_bytes());
|
||||
Ok(BASE64URL_NOPAD.encode(&bytes))
|
||||
}
|
||||
}
|
||||
|
||||
fn wire_group(group: &Value, economics: Option<&Economics>) -> Result<Value> {
|
||||
let outcome = group["outcome"]
|
||||
.as_str()
|
||||
.context("missing holder outcome")?;
|
||||
let token = group["asset_id"].as_str().context("missing holder token")?;
|
||||
let index = if outcome == "YES" { 0 } else { 1 };
|
||||
let holders = group["holders"].as_array().context("missing holder rows")?;
|
||||
let holders = holders
|
||||
.iter()
|
||||
.map(|holder| -> Result<Value> {
|
||||
let account = holder["account"]
|
||||
.as_str()
|
||||
.context("missing holder wallet")?;
|
||||
let amount = holder["amount"]
|
||||
.as_number()
|
||||
.context("missing holder amount")?;
|
||||
let mut row = json!({
|
||||
"proxy_wallet":account,"amount":amount,"token_id":token,"outcome_index":index,
|
||||
"bio":"","name":"","pseudonym":"","profile_image":"","profile_image_optimized":"",
|
||||
"display_username_public":false,"verified":false
|
||||
});
|
||||
if let Some(economics) = economics {
|
||||
let mark = holder["current_price_micros"].as_i64().map(i128::from);
|
||||
let value = holder["current_value_micros"].as_i64().map(i128::from);
|
||||
let units = minimum_units(amount)?.context("holder amount overflow")?;
|
||||
row["current_price"] = json!(mark.map(|p| decimal(p, UNIT)));
|
||||
row["current_value"] = json!(value.map(|p| decimal(p, UNIT)));
|
||||
for (key, value) in economics.fields(account, outcome, units, value) {
|
||||
row[key] = value;
|
||||
}
|
||||
}
|
||||
Ok(row)
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
Ok(json!({"token_id":token,"holders":holders}))
|
||||
}
|
||||
|
||||
impl HoldersQuery {
|
||||
fn read(self, db: &Connection) -> Result<Value> {
|
||||
ensure!(self.offset.is_none(), "'offset' is not a query param on this API: pages are cursor-only, pass 'cursor' from a prior response's next_cursor");
|
||||
ensure!(self.market.is_none(), "'market' is not a query param on this API: filter by condition id with 'condition' (aliases 'condition_id', 'conditionId')");
|
||||
let conditions = self
|
||||
.condition
|
||||
.as_deref()
|
||||
.filter(|s| !s.trim().is_empty())
|
||||
.context("required query param 'condition' not provided")?;
|
||||
let ids = condition_filter(Some(conditions), db)
|
||||
.map_err(|error| match error {
|
||||
MarketDataError::Invalid(message) => anyhow::anyhow!(
|
||||
"{}",
|
||||
message.replacen("invalid condition:", "invalid condition id:", 1)
|
||||
),
|
||||
MarketDataError::Unavailable => anyhow::Error::new(rusqlite::Error::InvalidQuery),
|
||||
})?
|
||||
.context("required query param 'condition' not provided")?;
|
||||
let mut markets: Vec<String> = serde_json::from_str(&ids)?;
|
||||
let gross = self.include_pnl.unwrap_or(false);
|
||||
ensure!(
|
||||
!gross || markets.len() == 1,
|
||||
"include_pnl accepts exactly one 'condition' per call"
|
||||
);
|
||||
for market in &mut markets {
|
||||
if hex_id(market, 64) {
|
||||
let canonical = db
|
||||
.query_row(
|
||||
"SELECT id FROM markets WHERE id=? COLLATE NOCASE ORDER BY id LIMIT 1",
|
||||
[&*market],
|
||||
|r| r.get(0),
|
||||
)
|
||||
.optional()?;
|
||||
if let Some(id) = canonical {
|
||||
*market = id;
|
||||
}
|
||||
}
|
||||
}
|
||||
let raw_limit = self.limit.unwrap_or(100);
|
||||
ensure!(
|
||||
raw_limit <= 1000,
|
||||
"Failed to deserialize query string: limit: limit must be between 0 and 1000"
|
||||
);
|
||||
let window = self
|
||||
.cursor
|
||||
.as_deref()
|
||||
.map(|cursor| Window::decode(db, cursor))
|
||||
.transpose()?
|
||||
.unwrap_or(Window {
|
||||
limit: raw_limit,
|
||||
offset: 0,
|
||||
});
|
||||
ensure!(
|
||||
!gross || window.limit <= 100,
|
||||
"limit must be at most 100 with include_pnl"
|
||||
);
|
||||
let min_balance = self
|
||||
.min_balance
|
||||
.as_deref()
|
||||
.filter(|raw| !raw.trim().is_empty())
|
||||
.map(|raw| raw.trim().parse::<Number>().context("invalid min_balance"))
|
||||
.transpose()?
|
||||
.filter(|number| !number.to_string().starts_with('-'))
|
||||
.unwrap_or_else(|| 0.into());
|
||||
let page = Page {
|
||||
markets,
|
||||
basis: if gross { Basis::Gross } else { Basis::Net },
|
||||
min_balance,
|
||||
limit: window.limit,
|
||||
offset: window.offset,
|
||||
};
|
||||
let (groups, more) = page.read(db)?;
|
||||
let economics = if gross && !groups.is_empty() {
|
||||
let accounts: Vec<_> = groups
|
||||
.iter()
|
||||
.filter_map(|g| g["holders"].as_array())
|
||||
.flatten()
|
||||
.filter_map(|h| h["account"].as_str())
|
||||
.collect();
|
||||
Some(Economics::read(db, &page.markets[0], &accounts)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let data = groups
|
||||
.iter()
|
||||
.map(|group| wire_group(group, economics.as_ref()))
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
let next = if more {
|
||||
let offset = window
|
||||
.offset
|
||||
.checked_add(i64::from(window.limit))
|
||||
.context("holders offset overflow")?;
|
||||
Some(
|
||||
Window {
|
||||
limit: window.limit,
|
||||
offset,
|
||||
}
|
||||
.encode(db)?,
|
||||
)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok(json!({"data":data,"pagination":{
|
||||
"limit":window.limit,"offset":window.offset,"has_more":more,"next_cursor":next
|
||||
}}))
|
||||
}
|
||||
}
|
||||
|
||||
impl Exchange {
|
||||
pub fn public_holders(&self, query: HoldersQuery) -> Result<Value, MarketDataError> {
|
||||
let tx = self.db.unchecked_transaction()?;
|
||||
let result = query.read(&tx).map_err(|error| {
|
||||
if error.downcast_ref::<rusqlite::Error>().is_some() {
|
||||
MarketDataError::Unavailable
|
||||
} else {
|
||||
MarketDataError::Invalid(error.to_string())
|
||||
}
|
||||
})?;
|
||||
tx.commit()?;
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
@@ -52,7 +52,6 @@ pub use assets::parse_id as parse_asset_id;
|
||||
pub use depth_feed::MarketPage;
|
||||
pub use gamma_directory::DirectoryKey;
|
||||
pub use gamma_list::DirectoryResource;
|
||||
pub use holders::http::HoldersQuery;
|
||||
pub use open_interest::InterestQuery;
|
||||
pub use portfolio::http::ValueQuery;
|
||||
pub use prices_history::http::HistoryQuery;
|
||||
@@ -122,7 +121,7 @@ impl Exchange {
|
||||
db.execute_batch(include_str!("quote_schema.sql"))?;
|
||||
}
|
||||
let history_ready: bool = db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='trigger' AND name='chart_market_listed')",
|
||||
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='trigger' AND name='chart_market_closed')",
|
||||
[], |r| r.get(0),
|
||||
)?;
|
||||
if !history_ready {
|
||||
@@ -136,13 +135,6 @@ impl Exchange {
|
||||
db.execute_batch(include_str!("valuation_schema.sql"))?;
|
||||
}
|
||||
lots::migrate(&mut db)?;
|
||||
let economics_order_ready: bool = db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='trigger' AND name='cost_order_wallet')",
|
||||
[], |r| r.get(0),
|
||||
)?;
|
||||
if !economics_order_ready {
|
||||
db.execute_batch(include_str!("holders/economics_schema.sql"))?;
|
||||
}
|
||||
let snapshot_ready: bool = db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='table' AND name='book_snapshot_times')", [], |r| r.get(0))?;
|
||||
if !snapshot_ready {
|
||||
|
||||
@@ -12,4 +12,12 @@ END;
|
||||
INSERT OR IGNORE INTO chart_origins
|
||||
SELECT id,COALESCE((SELECT MIN(at_ms) FROM quote_events WHERE market=m.id),
|
||||
CAST(unixepoch('subsec')*1000 AS INTEGER)) FROM markets m;
|
||||
CREATE TABLE IF NOT EXISTS chart_closures (
|
||||
market TEXT PRIMARY KEY REFERENCES markets,
|
||||
at_ms INTEGER NOT NULL
|
||||
);
|
||||
CREATE TRIGGER IF NOT EXISTS chart_market_closed AFTER UPDATE OF phase ON markets
|
||||
WHEN NEW.phase='closed' AND OLD.phase<>'closed' BEGIN
|
||||
INSERT INTO chart_closures VALUES(NEW.id,CAST(unixepoch('subsec')*1000 AS INTEGER));
|
||||
END;
|
||||
COMMIT;
|
||||
@@ -2,14 +2,16 @@
|
||||
-- The local sampler uses a UTC minute grid. The venue's collector has clock jitter.
|
||||
WITH RECURSIVE horizon AS (
|
||||
SELECT (SELECT at_ms FROM chart_origins WHERE market=?1) AS first_ms,
|
||||
(SELECT at_ms FROM price_settlements WHERE market=?1) AS resolved_ms,
|
||||
(SELECT winner FROM price_settlements WHERE market=?1) AS winner,
|
||||
(SELECT phase FROM markets WHERE id=?1) AS phase
|
||||
(SELECT at_ms FROM chart_closures WHERE market=?1) AS closed_ms,
|
||||
(SELECT phase IN ('closed','resolved') FROM markets WHERE id=?1) AS closed
|
||||
), bounds AS (
|
||||
SELECT first_ms, resolved_ms, winner,
|
||||
CASE WHEN phase='resolved' THEN COALESCE(resolved_ms,
|
||||
(SELECT MAX(at_ms) FROM quote_events WHERE market=?1))
|
||||
ELSE ?6/60000*60000 END AS last_ms
|
||||
SELECT first_ms, closed,
|
||||
CASE WHEN NOT closed THEN ?6/60000*60000
|
||||
WHEN closed_ms IS NOT NULL THEN closed_ms-1
|
||||
-- Old closed markets lack the close time. Use the last
|
||||
-- recorded nonempty quote and exclude the closing clear.
|
||||
ELSE (SELECT MAX(at_ms) FROM quote_events WHERE market=?1
|
||||
AND (yes_bid IS NOT NULL OR yes_ask IS NOT NULL)) END AS last_ms
|
||||
FROM horizon
|
||||
), grid(ms) AS (
|
||||
SELECT ((MAX(?3,first_ms)+?5-1)/?5)*?5 FROM bounds
|
||||
@@ -19,14 +21,12 @@ WITH RECURSIVE horizon AS (
|
||||
), points(ms,tail) AS (
|
||||
SELECT ms,0 FROM grid
|
||||
UNION ALL
|
||||
SELECT last_ms,1 FROM bounds WHERE resolved_ms IS NOT NULL OR first_ms<=last_ms
|
||||
SELECT last_ms,1 FROM bounds WHERE NOT closed AND first_ms<=last_ms
|
||||
)
|
||||
SELECT points.ms/1000,
|
||||
CASE WHEN points.ms=b.resolved_ms THEN
|
||||
CASE WHEN b.winner='VOID' THEN 500000 WHEN b.winner=?2 THEN 1000000 ELSE 0 END
|
||||
WHEN ?2='YES' THEN (COALESCE(q.yes_bid,0)+COALESCE(q.yes_ask,10000))*50
|
||||
CASE WHEN ?2='YES' THEN (COALESCE(q.yes_bid,0)+COALESCE(q.yes_ask,10000))*50
|
||||
ELSE 1000000-(COALESCE(q.yes_bid,0)+COALESCE(q.yes_ask,10000))*50 END
|
||||
FROM points CROSS JOIN bounds b
|
||||
FROM points
|
||||
LEFT JOIN quote_events q ON q.seq=(
|
||||
SELECT seq FROM quote_events WHERE market=?1 AND at_ms<=points.ms
|
||||
ORDER BY at_ms DESC,seq DESC LIMIT 1
|
||||
|
||||
@@ -200,7 +200,7 @@ impl PriceRequest {
|
||||
// Use the last committed top of book, even when only one side has liquidity.
|
||||
// All requested markets share the caller's read snapshot.
|
||||
fn price_rows(db: &Connection, requests: &[PriceRequest]) -> Result<Vec<Option<String>>> {
|
||||
quote_rows(db, requests)?
|
||||
quote_rows(db, requests, false)?
|
||||
.into_iter()
|
||||
.zip(requests)
|
||||
.map(|(quote, request)| {
|
||||
@@ -220,7 +220,11 @@ fn price_rows(db: &Connection, requests: &[PriceRequest]) -> Result<Vec<Option<S
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn quote_rows(db: &Connection, requests: &[PriceRequest]) -> Result<Vec<Option<Quote>>> {
|
||||
fn quote_rows(
|
||||
db: &Connection,
|
||||
requests: &[PriceRequest],
|
||||
public_only: bool,
|
||||
) -> Result<Vec<Option<Quote>>> {
|
||||
if !(1..=500).contains(&requests.len()) {
|
||||
return Err(PriceQueryError::RequestCount.into());
|
||||
}
|
||||
@@ -234,11 +238,11 @@ fn quote_rows(db: &Connection, requests: &[PriceRequest]) -> Result<Vec<Option<Q
|
||||
}
|
||||
let mut stmt = db.prepare_cached(
|
||||
"SELECT COALESCE(q.seq,0),q.yes_bid,q.yes_ask,q.at_ms,m.id,j.key
|
||||
FROM json_each(?1) j LEFT JOIN markets m ON m.id=j.value
|
||||
FROM json_each(?1) j LEFT JOIN markets m ON m.id=j.value AND (NOT ?2 OR m.phase<>'resolved')
|
||||
LEFT JOIN quote_events q ON q.seq=(SELECT MAX(seq) FROM quote_events WHERE market=m.id)
|
||||
ORDER BY j.key",
|
||||
)?;
|
||||
let mut rows = stmt.query([serde_json::to_string(&markets)?])?;
|
||||
let mut rows = stmt.query(params![serde_json::to_string(&markets)?, public_only])?;
|
||||
let mut quotes = Vec::with_capacity(requests.len());
|
||||
while let Some(row) = rows.next()? {
|
||||
let index: usize = row.get(5)?;
|
||||
@@ -284,7 +288,7 @@ impl crate::Exchange {
|
||||
pub fn public_book_prices(&self, requests: &[PriceRequest]) -> Result<Value> {
|
||||
let tx = crate::expiry::transaction(&self.db, rusqlite::TransactionBehavior::Deferred)?;
|
||||
let mut result = json!({});
|
||||
for (request, quote) in requests.iter().zip(quote_rows(&tx, requests)?) {
|
||||
for (request, quote) in requests.iter().zip(quote_rows(&tx, requests, true)?) {
|
||||
if let Some(quote) = quote {
|
||||
let (bid, ask) = quote.public_sides();
|
||||
let ticks = match request.side {
|
||||
@@ -333,7 +337,7 @@ impl crate::Exchange {
|
||||
.map_err(|_| crate::MarketDataError::Unavailable)?;
|
||||
let mut stmt = tx.prepare_cached(
|
||||
"SELECT COALESCE(q.seq,0),q.yes_bid,q.yes_ask,q.at_ms,j.key FROM json_each(?1) j
|
||||
JOIN markets m ON m.id=json_extract(j.value,'$[1]')
|
||||
JOIN markets m ON m.id=json_extract(j.value,'$[1]') AND m.phase<>'resolved'
|
||||
LEFT JOIN quote_events q ON q.seq=(SELECT MAX(seq) FROM quote_events WHERE market=m.id)"
|
||||
)?;
|
||||
let mut rows = stmt.query([input])?;
|
||||
|
||||
@@ -1553,21 +1553,23 @@ fn legacy_history_samples_the_book_without_fills_and_appends_the_latest_mark() {
|
||||
exchange
|
||||
.execute(json!({"op":"close","id":"close","market":"mid-example"}))
|
||||
.unwrap();
|
||||
db.execute("UPDATE chart_closures SET at_ms=273000", [])
|
||||
.unwrap();
|
||||
db.execute(
|
||||
"UPDATE quote_events SET at_ms=273000 WHERE yes_bid IS NULL AND yes_ask IS NULL",
|
||||
[],
|
||||
)
|
||||
.unwrap();
|
||||
let before_close = vec![json!({"t":240,"p":0.915})];
|
||||
assert_eq!(read(&exchange, "NO", 180.001, 400.0), before_close);
|
||||
exchange
|
||||
.execute(json!({"op":"finalize","id":"verdict","market":"mid-example","winner":"NO"}))
|
||||
.unwrap();
|
||||
db.execute("UPDATE price_settlements SET at_ms=273000", [])
|
||||
.unwrap();
|
||||
drop(exchange);
|
||||
let reopened = Exchange::open(path).unwrap();
|
||||
assert_eq!(
|
||||
read(&reopened, "NO", 180.001, 240.0),
|
||||
vec![json!({"t":240,"p":0.915}), json!({"t":273,"p":1})]
|
||||
);
|
||||
assert_eq!(
|
||||
read(&reopened, "YES", 5.0, 5.0),
|
||||
vec![json!({"t":273,"p":0})]
|
||||
);
|
||||
assert_eq!(read(&reopened, "NO", 180.001, 400.0), before_close);
|
||||
assert!(read(&reopened, "YES", 273.0, 400.0).is_empty());
|
||||
assert!(read(&reopened, "YES", 5.0, 5.0).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1879,52 +1881,6 @@ fn holders_net_reserved_and_hedged_balances_and_page_each_token() {
|
||||
assert!(e
|
||||
.execute(json!({"op":"holders","cursor":first["next_cursor"],"market":"different"}))
|
||||
.is_err());
|
||||
let request = |value| serde_json::from_value::<exchange::HoldersQuery>(value).unwrap();
|
||||
let first_public = e
|
||||
.public_holders(request(json!({"condition":"cup","limit":1})))
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
first_public["data"][0]["holders"][0]["proxy_wallet"],
|
||||
"alice"
|
||||
);
|
||||
assert_eq!(first_public["data"][0]["holders"][0]["amount"], 3);
|
||||
assert!(first_public["data"][0]["holders"][0]
|
||||
.get("entry_cost_usdc")
|
||||
.is_none());
|
||||
let cursor = first_public["pagination"]["next_cursor"].as_str().unwrap();
|
||||
let next_public = e
|
||||
.public_holders(request(
|
||||
json!({"condition":"cup","cursor":cursor,"limit":9}),
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(next_public["pagination"]["limit"], 1);
|
||||
assert_eq!(next_public["pagination"]["offset"], 1);
|
||||
assert_eq!(next_public["data"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(
|
||||
next_public["data"][0]["holders"][0]["proxy_wallet"],
|
||||
"carol"
|
||||
);
|
||||
assert_eq!(next_public["data"][0]["holders"][0]["amount"], 0);
|
||||
|
||||
let pnl = e
|
||||
.public_holders(request(json!({"condition":"cup","includePnl":true})))
|
||||
.unwrap();
|
||||
let alice_yes = &pnl["data"][0]["holders"][0];
|
||||
let alice_no = &pnl["data"][1]["holders"][0];
|
||||
let bob_no = &pnl["data"][1]["holders"][1];
|
||||
assert_eq!(alice_yes["amount"], 10);
|
||||
assert_eq!(alice_yes["entry_cost_usdc"], 5);
|
||||
assert_eq!(alice_no["amount"], 7);
|
||||
assert_eq!(alice_no["entry_cost_usdc"], json!(3.5));
|
||||
assert_eq!(alice_no["realized_pnl"], json!(-0.3));
|
||||
assert_eq!(bob_no["proxy_wallet"], "bob");
|
||||
assert_eq!(bob_no["entry_cost_usdc"], json!(3.2));
|
||||
assert!(
|
||||
(bob_no["unrealized_pnl"].as_f64().unwrap() + bob_no["realized_pnl"].as_f64().unwrap()
|
||||
- bob_no["total_pnl"].as_f64().unwrap())
|
||||
.abs()
|
||||
< 1e-9
|
||||
);
|
||||
assert_eq!(gross["data"][0]["holders"][0]["amount"], 10);
|
||||
assert_eq!(gross["data"][1]["holders"][0]["amount"], 7);
|
||||
assert_eq!(
|
||||
|
||||
@@ -8,6 +8,14 @@ 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"]
|
||||
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
|
||||
@@ -123,3 +131,90 @@ 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)
|
||||
@@ -0,0 +1,42 @@
|
||||
[
|
||||
{
|
||||
"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
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"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
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
[
|
||||
{
|
||||
"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
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,241 @@
|
||||
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(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
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,6 +1,10 @@
|
||||
mod book_audit;
|
||||
mod books;
|
||||
mod catalog;
|
||||
mod combo_payout;
|
||||
mod ctf_resolution;
|
||||
mod polygon_rpc;
|
||||
mod position_resolution;
|
||||
mod price_check;
|
||||
mod probes;
|
||||
use anyhow::{ensure, Result};
|
||||
@@ -30,10 +34,68 @@ 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]";
|
||||
"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]";
|
||||
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(());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
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(());
|
||||
}
|
||||
}
|
||||
|
||||
if let [mode, file] = args.as_slice() {
|
||||
if mode == "--replay-market" {
|
||||
let raw = serde_json::from_reader(std::fs::File::open(file)?)?;
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
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()?)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
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";
|
||||
const GET_RESULT: &str = "e4939c77";
|
||||
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()?))
|
||||
}
|
||||
|
||||
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,597 @@
|
||||
[
|
||||
{
|
||||
"catalog_url": "https://gamma-api.polymarket.com/markets?closed=true&limit=100&order=closedTime&ascending=false",
|
||||
"catalog": {
|
||||
"id": "7554899",
|
||||
"slug": "cs2-bb3-lgc-2026-12-03-game1-round-total-30pt5",
|
||||
"version": "v1",
|
||||
"conditionId": "0xdf04a0495b0a16dbce386acdc16d9aed19784db9888be53d150354b83b7c18b1",
|
||||
"closed": true,
|
||||
"closedTime": "2026-12-03 08:32:03.519799+00",
|
||||
"acceptingOrders": false,
|
||||
"umaResolutionStatus": "resolved",
|
||||
"outcomePrices": "[\"0\", \"1\"]",
|
||||
"outcomes": "[\"Over\", \"Under\"]",
|
||||
"positionIds": null,
|
||||
"clobTokenIds": "[\"73979342585906843441145134109923710004884703083095161594360108477170435492453\", \"78188826358032258311424545486331333398838521699262460256542567713692269401385\"]"
|
||||
},
|
||||
"sides": [
|
||||
{
|
||||
"asset": "73979342585906843441145134109923710004884703083095161594360108477170435492453",
|
||||
"around": {
|
||||
"method": "GET",
|
||||
"url": "https://clob.polymarket.com/prices-history?market=73979342585906843441145134109923710004884703083095161594360108477170435492453&startTs=1796284923&endTs=1796288523&fidelity=2",
|
||||
"payload": null,
|
||||
"status": 200,
|
||||
"date": "Thu, 03 Dec 2026 08:34:56 GMT",
|
||||
"body": {
|
||||
"history": [
|
||||
{
|
||||
"t": 1796285541,
|
||||
"p": 0.1
|
||||
},
|
||||
{
|
||||
"t": 1796285655,
|
||||
"p": 0.1
|
||||
},
|
||||
{
|
||||
"t": 1796285780,
|
||||
"p": 0.1
|
||||
},
|
||||
{
|
||||
"t": 1796285889,
|
||||
"p": 0.1
|
||||
},
|
||||
{
|
||||
"t": 1796286038,
|
||||
"p": 0.1
|
||||
},
|
||||
{
|
||||
"t": 1796286155,
|
||||
"p": 0.1
|
||||
},
|
||||
{
|
||||
"t": 1796286252,
|
||||
"p": 0.005
|
||||
},
|
||||
{
|
||||
"t": 1796286383,
|
||||
"p": 0.0005
|
||||
},
|
||||
{
|
||||
"t": 1796286495,
|
||||
"p": 0.0005
|
||||
},
|
||||
{
|
||||
"t": 1796286646,
|
||||
"p": 0.0005
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"after": {
|
||||
"method": "GET",
|
||||
"url": "https://clob.polymarket.com/prices-history?market=73979342585906843441145134109923710004884703083095161594360108477170435492453&startTs=1796290323&endTs=1796290623&fidelity=2",
|
||||
"payload": null,
|
||||
"status": 200,
|
||||
"date": "Thu, 03 Dec 2026 08:34:56 GMT",
|
||||
"body": {
|
||||
"history": []
|
||||
}
|
||||
},
|
||||
"ancient": {
|
||||
"method": "GET",
|
||||
"url": "https://clob.polymarket.com/prices-history?market=73979342585906843441145134109923710004884703083095161594360108477170435492453&startTs=120&endTs=245",
|
||||
"payload": null,
|
||||
"status": 200,
|
||||
"date": "Thu, 03 Dec 2026 08:34:56 GMT",
|
||||
"body": {
|
||||
"history": []
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"asset": "78188826358032258311424545486331333398838521699262460256542567713692269401385",
|
||||
"around": {
|
||||
"method": "GET",
|
||||
"url": "https://clob.polymarket.com/prices-history?market=78188826358032258311424545486331333398838521699262460256542567713692269401385&startTs=1796284923&endTs=1796288523&fidelity=2",
|
||||
"payload": null,
|
||||
"status": 200,
|
||||
"date": "Thu, 03 Dec 2026 08:34:58 GMT",
|
||||
"body": {
|
||||
"history": [
|
||||
{
|
||||
"t": 1796285540,
|
||||
"p": 0.9
|
||||
},
|
||||
{
|
||||
"t": 1796285654,
|
||||
"p": 0.9
|
||||
},
|
||||
{
|
||||
"t": 1796285780,
|
||||
"p": 0.9
|
||||
},
|
||||
{
|
||||
"t": 1796285889,
|
||||
"p": 0.9
|
||||
},
|
||||
{
|
||||
"t": 1796286037,
|
||||
"p": 0.9
|
||||
},
|
||||
{
|
||||
"t": 1796286155,
|
||||
"p": 0.9
|
||||
},
|
||||
{
|
||||
"t": 1796286252,
|
||||
"p": 0.995
|
||||
},
|
||||
{
|
||||
"t": 1796286383,
|
||||
"p": 0.9995
|
||||
},
|
||||
{
|
||||
"t": 1796286495,
|
||||
"p": 0.9995
|
||||
},
|
||||
{
|
||||
"t": 1796286646,
|
||||
"p": 0.9995
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"after": {
|
||||
"method": "GET",
|
||||
"url": "https://clob.polymarket.com/prices-history?market=78188826358032258311424545486331333398838521699262460256542567713692269401385&startTs=1796290323&endTs=1796290623&fidelity=2",
|
||||
"payload": null,
|
||||
"status": 200,
|
||||
"date": "Thu, 03 Dec 2026 08:34:58 GMT",
|
||||
"body": {
|
||||
"history": []
|
||||
}
|
||||
},
|
||||
"ancient": {
|
||||
"method": "GET",
|
||||
"url": "https://clob.polymarket.com/prices-history?market=78188826358032258311424545486331333398838521699262460256542567713692269401385&startTs=120&endTs=245",
|
||||
"payload": null,
|
||||
"status": 200,
|
||||
"date": "Thu, 03 Dec 2026 08:34:58 GMT",
|
||||
"body": {
|
||||
"history": []
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"catalog_url": "https://gamma-api.polymarket.com/markets?closed=true&limit=100&order=closedTime&ascending=false",
|
||||
"catalog": {
|
||||
"id": "7543472",
|
||||
"slug": "setkameua-anat-illia-2026-12-03",
|
||||
"version": "v2",
|
||||
"conditionId": "0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000",
|
||||
"closed": true,
|
||||
"closedTime": "2026-12-03 08:31:00.370625+00",
|
||||
"acceptingOrders": false,
|
||||
"umaResolutionStatus": null,
|
||||
"outcomePrices": "[\"1\", \"0\"]",
|
||||
"outcomes": "[\"Nikolenko Anatolii\", \"Fokin Illia\"]",
|
||||
"positionIds": [
|
||||
"759916398134244316868652908232832573045153963965173623897622651599218278400",
|
||||
"759916398134244316868652908232832573045153963965173623897622651599218278401"
|
||||
],
|
||||
"clobTokenIds": "[\"759916398134244316868652908232832573045153963965173623897622651599218278400\", \"759916398134244316868652908232832573045153963965173623897622651599218278401\"]"
|
||||
},
|
||||
"sides": [
|
||||
{
|
||||
"asset": "759916398134244316868652908232832573045153963965173623897622651599218278400",
|
||||
"around": {
|
||||
"method": "GET",
|
||||
"url": "https://clob.polymarket.com/prices-history?market=759916398134244316868652908232832573045153963965173623897622651599218278400&startTs=1796284860&endTs=1796288460&fidelity=2",
|
||||
"payload": null,
|
||||
"status": 200,
|
||||
"date": "Thu, 03 Dec 2026 08:34:59 GMT",
|
||||
"body": {
|
||||
"history": [
|
||||
{
|
||||
"t": 1796284969,
|
||||
"p": 0.999
|
||||
},
|
||||
{
|
||||
"t": 1796285059,
|
||||
"p": 0.999
|
||||
},
|
||||
{
|
||||
"t": 1796285176,
|
||||
"p": 0.999
|
||||
},
|
||||
{
|
||||
"t": 1796285310,
|
||||
"p": 0.999
|
||||
},
|
||||
{
|
||||
"t": 1796285335,
|
||||
"p": 0.999
|
||||
},
|
||||
{
|
||||
"t": 1796285416,
|
||||
"p": 0.999
|
||||
},
|
||||
{
|
||||
"t": 1796285540,
|
||||
"p": 0.999
|
||||
},
|
||||
{
|
||||
"t": 1796285654,
|
||||
"p": 0.999
|
||||
},
|
||||
{
|
||||
"t": 1796285779,
|
||||
"p": 0.999
|
||||
},
|
||||
{
|
||||
"t": 1796285889,
|
||||
"p": 0.999
|
||||
},
|
||||
{
|
||||
"t": 1796286037,
|
||||
"p": 0.999
|
||||
},
|
||||
{
|
||||
"t": 1796286154,
|
||||
"p": 0.999
|
||||
},
|
||||
{
|
||||
"t": 1796286252,
|
||||
"p": 0.999
|
||||
},
|
||||
{
|
||||
"t": 1796286382,
|
||||
"p": 0.999
|
||||
},
|
||||
{
|
||||
"t": 1796286494,
|
||||
"p": 0.999
|
||||
},
|
||||
{
|
||||
"t": 1796286645,
|
||||
"p": 0.999
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"after": {
|
||||
"method": "GET",
|
||||
"url": "https://clob.polymarket.com/prices-history?market=759916398134244316868652908232832573045153963965173623897622651599218278400&startTs=1796290260&endTs=1796290560&fidelity=2",
|
||||
"payload": null,
|
||||
"status": 200,
|
||||
"date": "Thu, 03 Dec 2026 08:34:59 GMT",
|
||||
"body": {
|
||||
"history": []
|
||||
}
|
||||
},
|
||||
"ancient": {
|
||||
"method": "GET",
|
||||
"url": "https://clob.polymarket.com/prices-history?market=759916398134244316868652908232832573045153963965173623897622651599218278400&startTs=120&endTs=245",
|
||||
"payload": null,
|
||||
"status": 200,
|
||||
"date": "Thu, 03 Dec 2026 08:34:59 GMT",
|
||||
"body": {
|
||||
"history": []
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"asset": "759916398134244316868652908232832573045153963965173623897622651599218278401",
|
||||
"around": {
|
||||
"method": "GET",
|
||||
"url": "https://clob.polymarket.com/prices-history?market=759916398134244316868652908232832573045153963965173623897622651599218278401&startTs=1796284860&endTs=1796288460&fidelity=2",
|
||||
"payload": null,
|
||||
"status": 200,
|
||||
"date": "Thu, 03 Dec 2026 08:35:00 GMT",
|
||||
"body": {
|
||||
"history": [
|
||||
{
|
||||
"t": 1796284969,
|
||||
"p": 0.001
|
||||
},
|
||||
{
|
||||
"t": 1796285059,
|
||||
"p": 0.001
|
||||
},
|
||||
{
|
||||
"t": 1796285176,
|
||||
"p": 0.001
|
||||
},
|
||||
{
|
||||
"t": 1796285310,
|
||||
"p": 0.001
|
||||
},
|
||||
{
|
||||
"t": 1796285335,
|
||||
"p": 0.001
|
||||
},
|
||||
{
|
||||
"t": 1796285416,
|
||||
"p": 0.001
|
||||
},
|
||||
{
|
||||
"t": 1796285540,
|
||||
"p": 0.001
|
||||
},
|
||||
{
|
||||
"t": 1796285654,
|
||||
"p": 0.001
|
||||
},
|
||||
{
|
||||
"t": 1796285779,
|
||||
"p": 0.001
|
||||
},
|
||||
{
|
||||
"t": 1796285889,
|
||||
"p": 0.001
|
||||
},
|
||||
{
|
||||
"t": 1796286037,
|
||||
"p": 0.001
|
||||
},
|
||||
{
|
||||
"t": 1796286154,
|
||||
"p": 0.001
|
||||
},
|
||||
{
|
||||
"t": 1796286252,
|
||||
"p": 0.001
|
||||
},
|
||||
{
|
||||
"t": 1796286382,
|
||||
"p": 0.001
|
||||
},
|
||||
{
|
||||
"t": 1796286494,
|
||||
"p": 0.001
|
||||
},
|
||||
{
|
||||
"t": 1796286645,
|
||||
"p": 0.001
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"after": {
|
||||
"method": "GET",
|
||||
"url": "https://clob.polymarket.com/prices-history?market=759916398134244316868652908232832573045153963965173623897622651599218278401&startTs=1796290260&endTs=1796290560&fidelity=2",
|
||||
"payload": null,
|
||||
"status": 200,
|
||||
"date": "Thu, 03 Dec 2026 08:35:00 GMT",
|
||||
"body": {
|
||||
"history": []
|
||||
}
|
||||
},
|
||||
"ancient": {
|
||||
"method": "GET",
|
||||
"url": "https://clob.polymarket.com/prices-history?market=759916398134244316868652908232832573045153963965173623897622651599218278401&startTs=120&endTs=245",
|
||||
"payload": null,
|
||||
"status": 200,
|
||||
"date": "Thu, 03 Dec 2026 08:35:01 GMT",
|
||||
"body": {
|
||||
"history": []
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"catalog_url": "https://gamma-api.polymarket.com/markets?closed=true&limit=100&order=closedTime&ascending=false",
|
||||
"catalog": {
|
||||
"id": "7528433",
|
||||
"slug": "sol-updown-15m-1796285700",
|
||||
"version": "v2",
|
||||
"conditionId": "0x0190f69570a8ebb0d5608f8f773ffc068b000000000000000000000000000000",
|
||||
"closed": true,
|
||||
"closedTime": "2026-12-03 08:30:28.231292+00",
|
||||
"acceptingOrders": false,
|
||||
"umaResolutionStatus": null,
|
||||
"outcomePrices": "[\"1\", \"0\"]",
|
||||
"outcomes": "[\"Up\", \"Down\"]",
|
||||
"positionIds": [
|
||||
"708440684409184214698552699176045036593002385654320616860038876849074339840",
|
||||
"708440684409184214698552699176045036593002385654320616860038876849074339841"
|
||||
],
|
||||
"clobTokenIds": "[\"708440684409184214698552699176045036593002385654320616860038876849074339840\", \"708440684409184214698552699176045036593002385654320616860038876849074339841\"]"
|
||||
},
|
||||
"sides": [
|
||||
{
|
||||
"asset": "708440684409184214698552699176045036593002385654320616860038876849074339840",
|
||||
"around": {
|
||||
"method": "GET",
|
||||
"url": "https://clob.polymarket.com/prices-history?market=708440684409184214698552699176045036593002385654320616860038876849074339840&startTs=1796284828&endTs=1796288428&fidelity=2",
|
||||
"payload": null,
|
||||
"status": 200,
|
||||
"date": "Thu, 03 Dec 2026 08:35:02 GMT",
|
||||
"body": {
|
||||
"history": [
|
||||
{
|
||||
"t": 1796284968,
|
||||
"p": 0.5
|
||||
},
|
||||
{
|
||||
"t": 1796285058,
|
||||
"p": 0.5
|
||||
},
|
||||
{
|
||||
"t": 1796285173,
|
||||
"p": 0.5
|
||||
},
|
||||
{
|
||||
"t": 1796285310,
|
||||
"p": 0.5
|
||||
},
|
||||
{
|
||||
"t": 1796285334,
|
||||
"p": 0.5
|
||||
},
|
||||
{
|
||||
"t": 1796285414,
|
||||
"p": 0.505
|
||||
},
|
||||
{
|
||||
"t": 1796285539,
|
||||
"p": 0.505
|
||||
},
|
||||
{
|
||||
"t": 1796285653,
|
||||
"p": 0.5
|
||||
},
|
||||
{
|
||||
"t": 1796285778,
|
||||
"p": 0.395
|
||||
},
|
||||
{
|
||||
"t": 1796285888,
|
||||
"p": 0.55
|
||||
},
|
||||
{
|
||||
"t": 1796286036,
|
||||
"p": 0.675
|
||||
},
|
||||
{
|
||||
"t": 1796286153,
|
||||
"p": 0.8
|
||||
},
|
||||
{
|
||||
"t": 1796286251,
|
||||
"p": 0.83
|
||||
},
|
||||
{
|
||||
"t": 1796286382,
|
||||
"p": 0.83
|
||||
},
|
||||
{
|
||||
"t": 1796286494,
|
||||
"p": 0.96
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"after": {
|
||||
"method": "GET",
|
||||
"url": "https://clob.polymarket.com/prices-history?market=708440684409184214698552699176045036593002385654320616860038876849074339840&startTs=1796290228&endTs=1796290528&fidelity=2",
|
||||
"payload": null,
|
||||
"status": 200,
|
||||
"date": "Thu, 03 Dec 2026 08:35:02 GMT",
|
||||
"body": {
|
||||
"history": []
|
||||
}
|
||||
},
|
||||
"ancient": {
|
||||
"method": "GET",
|
||||
"url": "https://clob.polymarket.com/prices-history?market=708440684409184214698552699176045036593002385654320616860038876849074339840&startTs=120&endTs=245",
|
||||
"payload": null,
|
||||
"status": 200,
|
||||
"date": "Thu, 03 Dec 2026 08:35:02 GMT",
|
||||
"body": {
|
||||
"history": []
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"asset": "708440684409184214698552699176045036593002385654320616860038876849074339841",
|
||||
"around": {
|
||||
"method": "GET",
|
||||
"url": "https://clob.polymarket.com/prices-history?market=708440684409184214698552699176045036593002385654320616860038876849074339841&startTs=1796284828&endTs=1796288428&fidelity=2",
|
||||
"payload": null,
|
||||
"status": 200,
|
||||
"date": "Thu, 03 Dec 2026 08:35:03 GMT",
|
||||
"body": {
|
||||
"history": [
|
||||
{
|
||||
"t": 1796284969,
|
||||
"p": 0.5
|
||||
},
|
||||
{
|
||||
"t": 1796285059,
|
||||
"p": 0.5
|
||||
},
|
||||
{
|
||||
"t": 1796285176,
|
||||
"p": 0.5
|
||||
},
|
||||
{
|
||||
"t": 1796285310,
|
||||
"p": 0.5
|
||||
},
|
||||
{
|
||||
"t": 1796285335,
|
||||
"p": 0.5
|
||||
},
|
||||
{
|
||||
"t": 1796285416,
|
||||
"p": 0.495
|
||||
},
|
||||
{
|
||||
"t": 1796285540,
|
||||
"p": 0.495
|
||||
},
|
||||
{
|
||||
"t": 1796285654,
|
||||
"p": 0.5
|
||||
},
|
||||
{
|
||||
"t": 1796285779,
|
||||
"p": 0.605
|
||||
},
|
||||
{
|
||||
"t": 1796285888,
|
||||
"p": 0.455
|
||||
},
|
||||
{
|
||||
"t": 1796286036,
|
||||
"p": 0.335
|
||||
},
|
||||
{
|
||||
"t": 1796286154,
|
||||
"p": 0.205
|
||||
},
|
||||
{
|
||||
"t": 1796286252,
|
||||
"p": 0.17
|
||||
},
|
||||
{
|
||||
"t": 1796286382,
|
||||
"p": 0.175
|
||||
},
|
||||
{
|
||||
"t": 1796286494,
|
||||
"p": 0.08
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"after": {
|
||||
"method": "GET",
|
||||
"url": "https://clob.polymarket.com/prices-history?market=708440684409184214698552699176045036593002385654320616860038876849074339841&startTs=1796290228&endTs=1796290528&fidelity=2",
|
||||
"payload": null,
|
||||
"status": 200,
|
||||
"date": "Thu, 03 Dec 2026 08:35:03 GMT",
|
||||
"body": {
|
||||
"history": []
|
||||
}
|
||||
},
|
||||
"ancient": {
|
||||
"method": "GET",
|
||||
"url": "https://clob.polymarket.com/prices-history?market=708440684409184214698552699176045036593002385654320616860038876849074339841&startTs=120&endTs=245",
|
||||
"payload": null,
|
||||
"status": 200,
|
||||
"date": "Thu, 03 Dec 2026 08:35:04 GMT",
|
||||
"body": {
|
||||
"history": []
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,10 @@
|
||||
{"markets":[
|
||||
{"catalog":{"id":"7554899","slug":"cs2-bb3-lgc-2026-12-03-game1-round-total-30pt5","version":"v1","conditionId":"0xdf04a0495b0a16dbce386acdc16d9aed19784db9888be53d150354b83b7c18b1","closed":true,"closedTime":"2026-12-03 08:32:03.519799+00","acceptingOrders":false,"umaResolutionStatus":"resolved","outcomePrices":"[\"0\", \"1\"]","outcomes":"[\"Over\", \"Under\"]","positionIds":null,"clobTokenIds":"[\"73979342585906843441145134109923710004884703083095161594360108477170435492453\", \"78188826358032258311424545486331333398838521699262460256542567713692269401385\"]"},"book_responses":[{"method":"GET","url":"https://clob.polymarket.com/midpoint?token_id=73979342585906843441145134109923710004884703083095161594360108477170435492453","payload":null,"status":404,"date":"Thu, 03 Dec 2026 08:37:31 GMT","body":{"error":"No orderbook exists for the requested token id"}},{"method":"GET","url":"https://clob.polymarket.com/spread?token_id=73979342585906843441145134109923710004884703083095161594360108477170435492453","payload":null,"status":404,"date":"Thu, 03 Dec 2026 08:37:31 GMT","body":{"error":"No orderbook exists for the requested token id"}},{"method":"GET","url":"https://clob.polymarket.com/book?token_id=73979342585906843441145134109923710004884703083095161594360108477170435492453","payload":null,"status":404,"date":"Thu, 03 Dec 2026 08:37:31 GMT","body":{"error":"No orderbook exists for the requested token id"}},{"method":"GET","url":"https://clob.polymarket.com/midpoint?token_id=78188826358032258311424545486331333398838521699262460256542567713692269401385","payload":null,"status":404,"date":"Thu, 03 Dec 2026 08:37:32 GMT","body":{"error":"No orderbook exists for the requested token id"}},{"method":"GET","url":"https://clob.polymarket.com/spread?token_id=78188826358032258311424545486331333398838521699262460256542567713692269401385","payload":null,"status":404,"date":"Thu, 03 Dec 2026 08:37:32 GMT","body":{"error":"No orderbook exists for the requested token id"}},{"method":"GET","url":"https://clob.polymarket.com/book?token_id=78188826358032258311424545486331333398838521699262460256542567713692269401385","payload":null,"status":404,"date":"Thu, 03 Dec 2026 08:37:32 GMT","body":{"error":"No orderbook exists for the requested token id"}}],"quotes":[{"method":"GET","url":"https://clob.polymarket.com/midpoint?token_id=73979342585906843441145134109923710004884703083095161594360108477170435492453","payload":null,"status":404,"date":"Thu, 03 Dec 2026 08:36:26 GMT","body":{"error":"No orderbook exists for the requested token id"}},{"method":"GET","url":"https://clob.polymarket.com/spread?token_id=73979342585906843441145134109923710004884703083095161594360108477170435492453","payload":null,"status":404,"date":"Thu, 03 Dec 2026 08:36:26 GMT","body":{"error":"No orderbook exists for the requested token id"}},{"method":"GET","url":"https://clob.polymarket.com/price?token_id=73979342585906843441145134109923710004884703083095161594360108477170435492453&side=BUY","payload":null,"status":404,"date":"Thu, 03 Dec 2026 08:36:26 GMT","body":{"error":"No orderbook exists for the requested token id"}},{"method":"POST","url":"https://clob.polymarket.com/books","payload":[{"token_id":"73979342585906843441145134109923710004884703083095161594360108477170435492453","side":"BUY"},{"token_id":"78188826358032258311424545486331333398838521699262460256542567713692269401385","side":"BUY"}],"status":200,"date":"Thu, 03 Dec 2026 08:36:26 GMT","body":[]},{"method":"POST","url":"https://clob.polymarket.com/midpoints","payload":[{"token_id":"73979342585906843441145134109923710004884703083095161594360108477170435492453","side":"BUY"},{"token_id":"78188826358032258311424545486331333398838521699262460256542567713692269401385","side":"BUY"}],"status":200,"date":"Thu, 03 Dec 2026 08:36:26 GMT","body":{}},{"method":"POST","url":"https://clob.polymarket.com/spreads","payload":[{"token_id":"73979342585906843441145134109923710004884703083095161594360108477170435492453","side":"BUY"},{"token_id":"78188826358032258311424545486331333398838521699262460256542567713692269401385","side":"BUY"}],"status":200,"date":"Thu, 03 Dec 2026 08:36:26 GMT","body":{}},{"method":"POST","url":"https://clob.polymarket.com/prices","payload":[{"token_id":"73979342585906843441145134109923710004884703083095161594360108477170435492453","side":"BUY"},{"token_id":"78188826358032258311424545486331333398838521699262460256542567713692269401385","side":"BUY"}],"status":200,"date":"Thu, 03 Dec 2026 08:36:26 GMT","body":{}}]},
|
||||
{"catalog":{"id":"7543472","slug":"setkameua-anat-illia-2026-12-03","version":"v2","conditionId":"0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","closed":true,"closedTime":"2026-12-03 08:31:00.370625+00","acceptingOrders":false,"umaResolutionStatus":null,"outcomePrices":"[\"1\", \"0\"]","outcomes":"[\"Nikolenko Anatolii\", \"Fokin Illia\"]","positionIds":["759916398134244316868652908232832573045153963965173623897622651599218278400","759916398134244316868652908232832573045153963965173623897622651599218278401"],"clobTokenIds":"[\"759916398134244316868652908232832573045153963965173623897622651599218278400\", \"759916398134244316868652908232832573045153963965173623897622651599218278401\"]"},"book_responses":[{"method":"GET","url":"https://clob.polymarket.com/midpoint?token_id=759916398134244316868652908232832573045153963965173623897622651599218278400","payload":null,"status":404,"date":"Thu, 03 Dec 2026 08:37:32 GMT","body":{"error":"No orderbook exists for the requested token id"}},{"method":"GET","url":"https://clob.polymarket.com/spread?token_id=759916398134244316868652908232832573045153963965173623897622651599218278400","payload":null,"status":200,"date":"Thu, 03 Dec 2026 08:37:32 GMT","body":{"spread":"1"}},{"method":"GET","url":"https://clob.polymarket.com/book?token_id=759916398134244316868652908232832573045153963965173623897622651599218278400","payload":null,"status":404,"date":"Thu, 03 Dec 2026 08:37:32 GMT","body":{"error":"No orderbook exists for the requested token id"}},{"method":"GET","url":"https://clob.polymarket.com/midpoint?token_id=759916398134244316868652908232832573045153963965173623897622651599218278401","payload":null,"status":200,"date":"Thu, 03 Dec 2026 08:37:32 GMT","body":{"mid":"0.5"}},{"method":"GET","url":"https://clob.polymarket.com/spread?token_id=759916398134244316868652908232832573045153963965173623897622651599218278401","payload":null,"status":404,"date":"Thu, 03 Dec 2026 08:37:33 GMT","body":{"error":"No orderbook exists for the requested token id"}},{"method":"GET","url":"https://clob.polymarket.com/book?token_id=759916398134244316868652908232832573045153963965173623897622651599218278401","payload":null,"status":404,"date":"Thu, 03 Dec 2026 08:37:32 GMT","body":{"error":"No orderbook exists for the requested token id"}}],"quotes":[{"method":"GET","url":"https://clob.polymarket.com/midpoint?token_id=759916398134244316868652908232832573045153963965173623897622651599218278400","payload":null,"status":404,"date":"Thu, 03 Dec 2026 08:36:27 GMT","body":{"error":"No orderbook exists for the requested token id"}},{"method":"GET","url":"https://clob.polymarket.com/spread?token_id=759916398134244316868652908232832573045153963965173623897622651599218278400","payload":null,"status":200,"date":"Thu, 03 Dec 2026 08:36:27 GMT","body":{"spread":"1"}},{"method":"GET","url":"https://clob.polymarket.com/price?token_id=759916398134244316868652908232832573045153963965173623897622651599218278400&side=BUY","payload":null,"status":404,"date":"Thu, 03 Dec 2026 08:36:27 GMT","body":{"error":"No orderbook exists for the requested token id"}},{"method":"POST","url":"https://clob.polymarket.com/books","payload":[{"token_id":"759916398134244316868652908232832573045153963965173623897622651599218278400","side":"BUY"},{"token_id":"759916398134244316868652908232832573045153963965173623897622651599218278401","side":"BUY"}],"status":200,"date":"Thu, 03 Dec 2026 08:36:27 GMT","body":[]},{"method":"POST","url":"https://clob.polymarket.com/midpoints","payload":[{"token_id":"759916398134244316868652908232832573045153963965173623897622651599218278400","side":"BUY"},{"token_id":"759916398134244316868652908232832573045153963965173623897622651599218278401","side":"BUY"}],"status":200,"date":"Thu, 03 Dec 2026 08:36:27 GMT","body":{"759916398134244316868652908232832573045153963965173623897622651599218278401":"0.5"}},{"method":"POST","url":"https://clob.polymarket.com/spreads","payload":[{"token_id":"759916398134244316868652908232832573045153963965173623897622651599218278400","side":"BUY"},{"token_id":"759916398134244316868652908232832573045153963965173623897622651599218278401","side":"BUY"}],"status":200,"date":"Thu, 03 Dec 2026 08:36:27 GMT","body":{"759916398134244316868652908232832573045153963965173623897622651599218278400":"1"}},{"method":"POST","url":"https://clob.polymarket.com/prices","payload":[{"token_id":"759916398134244316868652908232832573045153963965173623897622651599218278400","side":"BUY"},{"token_id":"759916398134244316868652908232832573045153963965173623897622651599218278401","side":"BUY"}],"status":200,"date":"Thu, 03 Dec 2026 08:36:28 GMT","body":{}}]},
|
||||
{"catalog":{"id":"7528433","slug":"sol-updown-15m-1796285700","version":"v2","conditionId":"0x0190f69570a8ebb0d5608f8f773ffc068b000000000000000000000000000000","closed":true,"closedTime":"2026-12-03 08:30:28.231292+00","acceptingOrders":false,"umaResolutionStatus":null,"outcomePrices":"[\"1\", \"0\"]","outcomes":"[\"Up\", \"Down\"]","positionIds":["708440684409184214698552699176045036593002385654320616860038876849074339840","708440684409184214698552699176045036593002385654320616860038876849074339841"],"clobTokenIds":"[\"708440684409184214698552699176045036593002385654320616860038876849074339840\", \"708440684409184214698552699176045036593002385654320616860038876849074339841\"]"},"book_responses":[{"method":"GET","url":"https://clob.polymarket.com/midpoint?token_id=708440684409184214698552699176045036593002385654320616860038876849074339840","payload":null,"status":404,"date":"Thu, 03 Dec 2026 08:37:35 GMT","body":{"error":"No orderbook exists for the requested token id"}},{"method":"GET","url":"https://clob.polymarket.com/spread?token_id=708440684409184214698552699176045036593002385654320616860038876849074339840","payload":null,"status":404,"date":"Thu, 03 Dec 2026 08:37:33 GMT","body":{"error":"No orderbook exists for the requested token id"}},{"method":"GET","url":"https://clob.polymarket.com/book?token_id=708440684409184214698552699176045036593002385654320616860038876849074339840","payload":null,"status":404,"date":"Thu, 03 Dec 2026 08:37:33 GMT","body":{"error":"No orderbook exists for the requested token id"}},{"method":"GET","url":"https://clob.polymarket.com/midpoint?token_id=708440684409184214698552699176045036593002385654320616860038876849074339841","payload":null,"status":404,"date":"Thu, 03 Dec 2026 08:37:34 GMT","body":{"error":"No orderbook exists for the requested token id"}},{"method":"GET","url":"https://clob.polymarket.com/spread?token_id=708440684409184214698552699176045036593002385654320616860038876849074339841","payload":null,"status":404,"date":"Thu, 03 Dec 2026 08:37:33 GMT","body":{"error":"No orderbook exists for the requested token id"}},{"method":"GET","url":"https://clob.polymarket.com/book?token_id=708440684409184214698552699176045036593002385654320616860038876849074339841","payload":null,"status":404,"date":"Thu, 03 Dec 2026 08:37:34 GMT","body":{"error":"No orderbook exists for the requested token id"}}],"quotes":[{"method":"GET","url":"https://clob.polymarket.com/midpoint?token_id=708440684409184214698552699176045036593002385654320616860038876849074339840","payload":null,"status":404,"date":"Thu, 03 Dec 2026 08:36:28 GMT","body":{"error":"No orderbook exists for the requested token id"}},{"method":"GET","url":"https://clob.polymarket.com/spread?token_id=708440684409184214698552699176045036593002385654320616860038876849074339840","payload":null,"status":404,"date":"Thu, 03 Dec 2026 08:36:28 GMT","body":{"error":"No orderbook exists for the requested token id"}},{"method":"GET","url":"https://clob.polymarket.com/price?token_id=708440684409184214698552699176045036593002385654320616860038876849074339840&side=BUY","payload":null,"status":404,"date":"Thu, 03 Dec 2026 08:36:28 GMT","body":{"error":"No orderbook exists for the requested token id"}},{"method":"POST","url":"https://clob.polymarket.com/books","payload":[{"token_id":"708440684409184214698552699176045036593002385654320616860038876849074339840","side":"BUY"},{"token_id":"708440684409184214698552699176045036593002385654320616860038876849074339841","side":"BUY"}],"status":200,"date":"Thu, 03 Dec 2026 08:36:28 GMT","body":[]},{"method":"POST","url":"https://clob.polymarket.com/midpoints","payload":[{"token_id":"708440684409184214698552699176045036593002385654320616860038876849074339840","side":"BUY"},{"token_id":"708440684409184214698552699176045036593002385654320616860038876849074339841","side":"BUY"}],"status":200,"date":"Thu, 03 Dec 2026 08:36:28 GMT","body":{}},{"method":"POST","url":"https://clob.polymarket.com/spreads","payload":[{"token_id":"708440684409184214698552699176045036593002385654320616860038876849074339840","side":"BUY"},{"token_id":"708440684409184214698552699176045036593002385654320616860038876849074339841","side":"BUY"}],"status":200,"date":"Thu, 03 Dec 2026 08:36:29 GMT","body":{}},{"method":"POST","url":"https://clob.polymarket.com/prices","payload":[{"token_id":"708440684409184214698552699176045036593002385654320616860038876849074339840","side":"BUY"},{"token_id":"708440684409184214698552699176045036593002385654320616860038876849074339841","side":"BUY"}],"status":200,"date":"Thu, 03 Dec 2026 08:36:29 GMT","body":{}}]}
|
||||
],"mixed_batch":[
|
||||
{"method":"POST","url":"https://clob.polymarket.com/books","payload":[{"token_id":"73979342585906843441145134109923710004884703083095161594360108477170435492453","side":"BUY"},{"token_id":"35090254409399344650860070211816464534198960801264823587796928404808383727584","side":"BUY"}],"status":200,"date":"Thu, 03 Dec 2026 08:36:29 GMT","body":[{"market":"0xa5f8a44504de30fa36fff2406b2b27b3d15476ed50448e4fc3ead4861d8a5e3e","asset_id":"35090254409399344650860070211816464534198960801264823587796928404808383727584","hash":"a4e1311a77002cac23f8be77c8e355df22551c4f"}]},
|
||||
{"method":"POST","url":"https://clob.polymarket.com/midpoints","payload":[{"token_id":"73979342585906843441145134109923710004884703083095161594360108477170435492453","side":"BUY"},{"token_id":"35090254409399344650860070211816464534198960801264823587796928404808383727584","side":"BUY"}],"status":200,"date":"Thu, 03 Dec 2026 08:36:29 GMT","body":{"35090254409399344650860070211816464534198960801264823587796928404808383727584":"0.0375"}},
|
||||
{"method":"POST","url":"https://clob.polymarket.com/spreads","payload":[{"token_id":"73979342585906843441145134109923710004884703083095161594360108477170435492453","side":"BUY"},{"token_id":"35090254409399344650860070211816464534198960801264823587796928404808383727584","side":"BUY"}],"status":200,"date":"Thu, 03 Dec 2026 08:36:29 GMT","body":{"35090254409399344650860070211816464534198960801264823587796928404808383727584":"0.001"}},
|
||||
{"method":"POST","url":"https://clob.polymarket.com/prices","payload":[{"token_id":"73979342585906843441145134109923710004884703083095161594360108477170435492453","side":"BUY"},{"token_id":"35090254409399344650860070211816464534198960801264823587796928404808383727584","side":"BUY"}],"status":200,"date":"Thu, 03 Dec 2026 08:36:29 GMT","body":{"35090254409399344650860070211816464534198960801264823587796928404808383727584":{"BUY":"0.037"}}}
|
||||
]}
|
||||
@@ -306,10 +306,6 @@ order、market_sell 和卖出 estimate 可用 size_micros 输入数量,也可
|
||||
|
||||
本地覆盖盘口快照、档位变化、最优报价和文本心跳。最近成交、步长调整和启用扩展功能后的市场生命周期事件也可经同一连接订阅。初始快照使用数组发送;生产端帧分组、延迟和断线时机尚待实测。Rust 回环测试入口为 `market_socket_sends_snapshots_deltas_and_application_pongs`。
|
||||
|
||||
#### V2 公开持仓榜
|
||||
|
||||
2026-12-05 的生产对照中,limit=1 分别返回两个结果各一位,负数 min_balance 与零门槛一致。恰好一位达标时下一页为空指针。续页必须重送 condition,页宽和偏移由游标保留,min_balance 与 include_pnl 可在请求中重传。Eventbook 的 `/v2/holders` 对齐这些边界,并复用实际份额、冻结卖单和盘口估值。新账本保存成交与钱包操作的共同写入顺序。已知历史按移动平均成本重放,买入成本排除手续费,卖出用实收额计算已实现盈亏,拆分和合并按等额分摊。旧流水缺时钟、同毫秒顺序有歧义、转换缺少分腿成本或账本与持仓不符时,成本及盈亏留空。公开钱包资料和生产成本算法仍待逐户对照。一次生产样本中同一资产的榜单 avg_price 为 0.2578,持仓接口为 0.2536,两者的 entry_cost_usdc 相同。本地使用账本成本除以持有份额。[官方持仓榜接口](https://docs.polymarket.com/api-reference/markets/list-a-markets-top-holders)
|
||||
|
||||
### 最近成交和步长变化
|
||||
|
||||
[回放样例](examples/market-stream-trades.jsonl)先将空盘步长由 0.01 调到 0.001,再以 0.40 美元成交 2 份 YES,最后通过互补买单以 0.35 美元成交 1 份 YES。订阅 YES 的客户端收到新的步长、两笔最近成交和相应的档位变化;订阅 NO 的客户端也收到该结果的步长变化,以及互补成交对应的 0.65 美元成交价。[官方原始报文字段](https://docs.polymarket.com/market-data/realtime-data.md)
|
||||
@@ -380,7 +376,7 @@ Polymarket 的单资产最近成交接口规定,无成交时返回价格字符
|
||||
|
||||
旧版 CLOB 客户端用 market 指定结果资产。单侧盘口的生产曲线末点为 0.0005,同批中点为 0.0005、最近成交为 0.001。一个近端成交记录为空的资产也有连续的 0.5 历史点。取早于上市的绝对区间时,有历史的资产仍返回最近可用点;新资产在中点已经可查时也可能返回空曲线。[生产请求和对照样本](examples/public-clob-history.json) · [CLOB OpenAPI](https://docs.polymarket.com/api-reference/markets/get-prices-history)
|
||||
|
||||
本地用已经提交的盘口变更重建历史中点。到每个 UTC 采样边界,取该时刻之前(含该时刻)最近一次盘口;缺买侧用 0,缺卖侧用 1。没有挂单变化时延续上次观测。窗口之外也追加最近一分钟的可用点;若与窗口最后一点重合,可出现重复时间戳。模拟裁决后在裁决时刻以兑付值收尾。已裁决的旧盘若缺少裁决时间,只使用最后有时间记录的报价。升级旧库时从第一条可信报价开始,没有报价记录的资产从迁移时刻开始。生产采集存在秒级抖动,新盘首个采样的延迟、长期历史保留和裁决后取点尚未逐点验证。V2 的成交与兑付历史保留其独立数据源。
|
||||
本地用已经提交的盘口变更重建历史中点。到每个 UTC 采样边界,取该时刻之前(含该时刻)最近一次盘口;缺买侧用 0,缺卖侧用 1。没有挂单变化时延续上次观测。窗口之外也追加最近一分钟的可用点;若与窗口最后一点重合,可出现重复时间戳。封盘后,曲线只返回请求窗口内、封盘之前的采样点。电竞、乒乓球和 SOL 涨跌盘的六个生产结果均符合这一规则。电竞负侧、胜侧的末点分别为 0.0005 和 0.9995,目录最终兑付为 0 和 1。旧库没有封盘记录时,最多采样到最后一笔非空盘口记录。生产采样时钟有秒级偏移,新盘首个采样延迟和长期保留仍待核验。V2 曲线使用成交与兑付数据。[已裁决生产样本](examples/public-closed-chart-history.json)
|
||||
|
||||
fidelity 以分钟为单位;省略或不大于零时按 1 分钟处理。相对窗口 1w 至少需要 5 分钟、1m 至少需要 10 分钟。显式起止时间最多相隔 15 天,多一秒即拒绝。单给 startTs 时读到当前;两个时间相等时仍可返回末点。合法但未上市的本地资产返回空数组。[HTTP 样例](examples/clob-http.http)
|
||||
|
||||
@@ -421,6 +417,20 @@ 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)
|
||||
|
||||
### Data API 账户持仓价值
|
||||
|
||||
官方 `GET /v2/value` 要求传 user,可选最多 20 个不同 condition。结果是 data 对象,内含 proxy_wallet 和四位小数精度的美元金额。一个无持仓的钱包值为零。官方总额还包括未终结组合的成本基础,指定 condition 时仅统计选中的单盘。资金余额不计入持仓价值。[官方 OpenAPI](https://data-api.polymarket.com/v2/openapi.json)
|
||||
@@ -470,3 +480,8 @@ SDK 使用 `GET /neg-risk?token_id=…`,也可以从已缓存的 CLOB 市场
|
||||
用空数据库重放[原单状态样例](examples/order-status.jsonl)。卖方以 0.60 挂 5 份 post-only 卖单,买方按金额吃掉 2 份。卖方撤回余单后,按原订单号查询,累计成交仍为 2,可成交余量为 0,`order_type` 为 GTC。买方的原单类型为 FAK。按卖方订单号查询 `trades`,这笔执行的份额也是 2。重启和重发相同命令沿用原回执与受理时间。
|
||||
|
||||
`open_orders` 的列表和精确查询均返回 `created_at`(Unix 秒)、`order_type` 和本地扩展 `post_only`。升级已有数据库时,用已受理的命令回执和 GTD 截止记录恢复提交指令;没有原始时钟记录的受理时间为 null。缺少原始回执的历史行仍可查询,未知字段保留为 null。官方当前将累计成交和逐笔对账分别放在订单的 size_matched 和账户成交记录;其单笔订单 HTTP 接口需要账户认证。本地验证使用可信操作员的 JSONL 接口,订单号与账户是模拟环境的标识。生产私有接口尚未实测。[官方订单查询](https://docs.polymarket.com/trading/manage-orders)
|
||||
|
||||
|
||||
### 已裁决市场的公开盘口
|
||||
|
||||
对电竞、乒乓球和 SOL 涨跌盘的六个已裁决结果单查 /book,全部返回 404。批量 /books 和 /prices 忽略已裁决资产,混合批次保留可用资产。中点和价差多数同样返回 404,但一个 V2 市场的两侧分别仍能读到价差 1 或中点 0.5。Eventbook 对已裁决结果统一省略四种公开行情,保留内部快照供交易状态和回放。封盘待裁决阶段、外场淘汰时延和例外是否由服务缓存触发仍待验证。[生产响应](examples/public-resolved-books.json)
|
||||
Reference in new issue
Block a user