Capture and replay CLOB depth ordering and SDK snapshot hashes
This commit is contained in:
@@ -7,3 +7,5 @@ edition.workspace = true
|
||||
anyhow.workspace = true
|
||||
serde_json.workspace = true
|
||||
reqwest = { version = "0.12", default-features = false, features = ["blocking", "rustls-tls", "json"] }
|
||||
serde.workspace = true
|
||||
sha1 = "0.10"
|
||||
|
||||
@@ -9,6 +9,8 @@ cargo run --locked -p venue-probe
|
||||
```mermaid
|
||||
flowchart LR
|
||||
main["src/main.rs"] -->|依次调用两个只读探针| impls["src/probes.rs"]
|
||||
main -->|指定资产取样或离线重放| audit["src/book_audit.rs"]
|
||||
audit -->|精确比较价格| books
|
||||
impls -->|可选买卖报价对照| check["src/price_check.rs"]
|
||||
check -->|精确价格与市场标识| books
|
||||
impls -->|目录标识、盘口校验和最优价| books["src/books.rs"]
|
||||
@@ -51,3 +53,26 @@ sequenceDiagram
|
||||
`venue-probe --compare-prices` 在常规输出上增加每个结果的 price_check。它把报价响应、HTTP 状态、前后盘口和哈希放在同一条记录中。两侧都有报价且买一低于卖一,前后盘口哈希和两侧最优档相同,才判断价格方向。BUY 等于卖一、SELL 等于买一记为 matches_documentation,二者正好对调记为 reversed,其他数值组合记为 different_prices。盘口变化记为 book_changed,缺哈希、缺边、买卖同价或报价失败记为 inconclusive。两个结果都符合文档时 price_check_passed 才为 true;其余情况保留观测并以非零状态退出。HTTP 读取之间可能发生变化又恢复,因此单次一致记录只说明这次观测。[官方买卖报价](https://docs.polymarket.com/market-data/prices-order-books.md#best-market-price)
|
||||
|
||||
[市场 559651 的目录字段摘录](fixtures/gamma-559651.json)来自公开 Gamma JSON 的网页读取,记录自身的更新时间为 2026-12-02 21:08:08 UTC。该 v1 市场同时返回两套 ID,盘口请求使用 clobTokenIds。目录买一为 0.012、卖一为 0.013、最小价格步长为 0.001。测试以这些真实目录值构造模拟的 CLOB 响应;本次工作站直连 Gamma 超时,网页读取该资产的 CLOB book 和 price 也未取得响应。目录观测与模拟样例均不能确认线上 BUY 和 SELL 返回了什么。[Gamma 公开市场目录](https://gamma-api.polymarket.com/markets?limit=1)
|
||||
|
||||
## 核对单个盘口的档位顺序和哈希
|
||||
|
||||
`venue-probe --inspect-book TOKEN` 只请求一次指定资产的官方 `GET /book`。输出含 URL、HTTP 状态、收到的完整 JSON 对象以及核对结果。保存该行后,`venue-probe --replay-book TOKEN FILE` 可以离线重新核对,也可以直接读取原始盘口 JSON。命令成功表示核对过程正常结束,是否与本地盘口规则一致由 `supports_local_snapshot` 单独报告。
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant U as 调用者
|
||||
participant P as venue-probe
|
||||
participant C as Polymarket CLOB
|
||||
alt 线上取样
|
||||
U->>P: inspect-book TOKEN
|
||||
P->>C: GET /book?token_id=TOKEN
|
||||
C-->>P: 单个时间戳的盘口与哈希
|
||||
else 离线重放
|
||||
U->>P: replay-book TOKEN FILE
|
||||
end
|
||||
P->>P: 校验资产 ID,检查两侧全部相邻价位
|
||||
P->>P: 保留档位与十进制字符串顺序,按 SDK 重算 SHA-1
|
||||
P-->>U: 首尾价、档位数、顺序、收到和计算的哈希
|
||||
```
|
||||
|
||||
两侧各有至少两个严格有序的不同价位、最优价均在末尾且哈希一致时,`supports_local_snapshot` 才为 true。空盘与单档记为 `insufficient_levels`。重复价格或非单调价格记为 `non_monotonic_or_repeated`。固定版 SDK 的哈希测试向量恰好买侧最优在末尾、卖侧最优在开头;重放它能核对序列化与分类,但无法判定生产端排序。仓库样例把测试期望的哈希填入原向量的空 hash 字段。[样例](fixtures/sdk-book.json) · [官方 SDK 哈希测试](https://github.com/Polymarket/py-clob-client-v2/blob/9c7c9e89cbbc11528daae90dc66ef65c9380cbdf/tests/test_utilities.py) · [官方序列化顺序](https://github.com/Polymarket/py-clob-client-v2/blob/9c7c9e89cbbc11528daae90dc66ef65c9380cbdf/py_clob_client_v2/utilities.py)
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"market": "0xaabbcc",
|
||||
"asset_id": "100",
|
||||
"bids": [
|
||||
{
|
||||
"price": "0.3",
|
||||
"size": "100"
|
||||
},
|
||||
{
|
||||
"price": "0.4",
|
||||
"size": "100"
|
||||
}
|
||||
],
|
||||
"asks": [
|
||||
{
|
||||
"price": "0.6",
|
||||
"size": "100"
|
||||
},
|
||||
{
|
||||
"price": "0.7",
|
||||
"size": "100"
|
||||
}
|
||||
],
|
||||
"hash": "0458ea5755c9f73d64a14636fa5c36ed460ec394",
|
||||
"timestamp": "123456789",
|
||||
"min_order_size": "100",
|
||||
"neg_risk": false,
|
||||
"tick_size": "0.01",
|
||||
"last_trade_price": "0.5"
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
use crate::books::price;
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
use sha1::{Digest, Sha1};
|
||||
|
||||
// Preserve decimal spellings and SDK field order independently of the JSON map implementation.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct Snapshot {
|
||||
market: String,
|
||||
asset_id: String,
|
||||
timestamp: String,
|
||||
hash: String,
|
||||
bids: Vec<Level>,
|
||||
asks: Vec<Level>,
|
||||
min_order_size: String,
|
||||
tick_size: String,
|
||||
neg_risk: bool,
|
||||
last_trade_price: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct Level {
|
||||
price: String,
|
||||
size: String,
|
||||
}
|
||||
|
||||
fn side(levels: &[Level], is_bid: bool) -> Result<Value> {
|
||||
let prices = levels
|
||||
.iter()
|
||||
.map(|l| price(&Value::String(l.price.clone())))
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
let order = if prices.len() < 2 {
|
||||
"insufficient_levels"
|
||||
} else if prices.windows(2).all(|p| p[0] < p[1]) {
|
||||
if is_bid {
|
||||
"best_last"
|
||||
} else {
|
||||
"best_first"
|
||||
}
|
||||
} else if prices.windows(2).all(|p| p[0] > p[1]) {
|
||||
if is_bid {
|
||||
"best_first"
|
||||
} else {
|
||||
"best_last"
|
||||
}
|
||||
} else {
|
||||
"non_monotonic_or_repeated"
|
||||
};
|
||||
Ok(
|
||||
json!({"levels":levels.len(),"first_price":levels.first().map(|l| &l.price),
|
||||
"last_price":levels.last().map(|l| &l.price),"order":order}),
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn inspect(raw: &Value, token: &str) -> Result<Value> {
|
||||
let mut book: Snapshot =
|
||||
serde_json::from_value(raw.clone()).context("invalid snapshot fields")?;
|
||||
ensure!(
|
||||
book.asset_id == token,
|
||||
"book asset differs from requested token"
|
||||
);
|
||||
let bids = side(&book.bids, true)?;
|
||||
let asks = side(&book.asks, false)?;
|
||||
let received = std::mem::take(&mut book.hash);
|
||||
let calculated = format!("{:x}", Sha1::digest(serde_json::to_vec(&book)?));
|
||||
let matches = !received.is_empty() && received == calculated;
|
||||
Ok(
|
||||
json!({"bids":bids,"asks":asks,"received_hash":received,"sdk_hash":calculated,
|
||||
"hash_matches":matches,"supports_local_snapshot":
|
||||
matches && bids["order"]=="best_last" && asks["order"]=="best_last"}),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn preserves_sdk_preimage_and_reports_each_side_independently() {
|
||||
let mut raw: Value =
|
||||
serde_json::from_str(include_str!("../fixtures/sdk-book.json")).unwrap();
|
||||
let audit = inspect(&raw, "100").unwrap();
|
||||
assert_eq!(audit["hash_matches"], true);
|
||||
assert_eq!(audit["bids"]["order"], "best_last");
|
||||
assert_eq!(audit["asks"]["order"], "best_first");
|
||||
assert_eq!(audit["supports_local_snapshot"], false);
|
||||
assert!(inspect(&raw, "101").is_err());
|
||||
raw["asks"].as_array_mut().unwrap().reverse();
|
||||
let changed = inspect(&raw, "100").unwrap();
|
||||
assert_eq!(changed["asks"]["order"], "best_last");
|
||||
assert_eq!(changed["hash_matches"], false);
|
||||
raw["hash"] = changed["sdk_hash"].clone();
|
||||
assert_eq!(
|
||||
inspect(&raw, "100").unwrap()["supports_local_snapshot"],
|
||||
true
|
||||
);
|
||||
raw["bids"][1]["price"] = json!("0.30");
|
||||
assert_eq!(
|
||||
inspect(&raw, "100").unwrap()["bids"]["order"],
|
||||
"non_monotonic_or_repeated"
|
||||
);
|
||||
raw["asks"] = json!([]);
|
||||
assert_eq!(
|
||||
inspect(&raw, "100").unwrap()["asks"]["order"],
|
||||
"insufficient_levels"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
mod book_audit;
|
||||
mod books;
|
||||
mod price_check;
|
||||
mod probes;
|
||||
@@ -6,16 +7,43 @@ use reqwest::blocking::Client;
|
||||
use std::time::Duration;
|
||||
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]";
|
||||
if let [mode, token, file] = args.as_slice() {
|
||||
ensure!(mode == "--replay-book", usage);
|
||||
let input: serde_json::Value = serde_json::from_reader(std::fs::File::open(file)?)?;
|
||||
let raw = input.get("book").unwrap_or(&input);
|
||||
let report = book_audit::inspect(raw, token)?;
|
||||
println!("{report}");
|
||||
return Ok(());
|
||||
}
|
||||
let compare = match args.as_slice() {
|
||||
[] => false,
|
||||
[flag] if flag == "--compare-prices" => true,
|
||||
_ => anyhow::bail!("usage: venue-probe [--compare-prices]"),
|
||||
[flag, _] if flag == "--inspect-book" => false,
|
||||
_ => anyhow::bail!(usage),
|
||||
};
|
||||
let client = Client::builder()
|
||||
.connect_timeout(Duration::from_secs(5))
|
||||
.timeout(Duration::from_secs(15))
|
||||
.user_agent("eventbook-readonly-probe/0.1")
|
||||
.build()?;
|
||||
if let [_, token] = args.as_slice() {
|
||||
let url = reqwest::Url::parse_with_params(
|
||||
"https://clob.polymarket.com/book",
|
||||
&[("token_id", token)],
|
||||
)?;
|
||||
let response = client.get(url.clone()).send()?;
|
||||
let status = response.status();
|
||||
let raw: serde_json::Value = response.json()?;
|
||||
let report = book_audit::inspect(&raw, token);
|
||||
let observation = serde_json::json!({"source":url.as_str(),"http_status":status.as_u16(),
|
||||
"book":raw,"audit":report.as_ref().ok(),"audit_error":report.as_ref().err().map(|e|format!("{e:#}"))});
|
||||
println!("{observation}");
|
||||
ensure!(status.is_success(), "venue returned HTTP {status}");
|
||||
report?;
|
||||
return Ok(());
|
||||
}
|
||||
let mut ok = true;
|
||||
for (name, result) in [
|
||||
("polymarket", probes::polymarket(&client, compare)),
|
||||
|
||||
Reference in New Issue
Block a user