Capture and replay CLOB depth ordering and SDK snapshot hashes
This commit is contained in:
Generated
+68
-1
@@ -45,6 +45,15 @@ version = "2.13.2"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
|
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "block-buffer"
|
||||||
|
version = "0.10.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
|
||||||
|
dependencies = [
|
||||||
|
"generic-array",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "bumpalo"
|
name = "bumpalo"
|
||||||
version = "3.20.3"
|
version = "3.20.3"
|
||||||
@@ -86,7 +95,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"
|
checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"cfg-if",
|
"cfg-if",
|
||||||
"cpufeatures",
|
"cpufeatures 0.3.1",
|
||||||
"rand_core",
|
"rand_core",
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -99,6 +108,15 @@ dependencies = [
|
|||||||
"serde_json",
|
"serde_json",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "cpufeatures"
|
||||||
|
version = "0.2.17"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
|
||||||
|
dependencies = [
|
||||||
|
"libc",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "cpufeatures"
|
name = "cpufeatures"
|
||||||
version = "0.3.1"
|
version = "0.3.1"
|
||||||
@@ -108,6 +126,26 @@ dependencies = [
|
|||||||
"libc",
|
"libc",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "crypto-common"
|
||||||
|
version = "0.1.7"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
|
||||||
|
dependencies = [
|
||||||
|
"generic-array",
|
||||||
|
"typenum",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "digest"
|
||||||
|
version = "0.10.7"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
|
||||||
|
dependencies = [
|
||||||
|
"block-buffer",
|
||||||
|
"crypto-common",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "displaydoc"
|
name = "displaydoc"
|
||||||
version = "0.2.7"
|
version = "0.2.7"
|
||||||
@@ -223,6 +261,16 @@ dependencies = [
|
|||||||
"slab",
|
"slab",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "generic-array"
|
||||||
|
version = "0.14.7"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
|
||||||
|
dependencies = [
|
||||||
|
"typenum",
|
||||||
|
"version_check",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "getrandom"
|
name = "getrandom"
|
||||||
version = "0.2.17"
|
version = "0.2.17"
|
||||||
@@ -883,6 +931,17 @@ dependencies = [
|
|||||||
"serde",
|
"serde",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "sha1"
|
||||||
|
version = "0.10.7"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8"
|
||||||
|
dependencies = [
|
||||||
|
"cfg-if",
|
||||||
|
"cpufeatures 0.2.17",
|
||||||
|
"digest",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "shlex"
|
name = "shlex"
|
||||||
version = "2.0.1"
|
version = "2.0.1"
|
||||||
@@ -1108,6 +1167,12 @@ version = "0.2.5"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
|
checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "typenum"
|
||||||
|
version = "1.20.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "unicode-ident"
|
name = "unicode-ident"
|
||||||
version = "1.0.27"
|
version = "1.0.27"
|
||||||
@@ -1159,7 +1224,9 @@ version = "0.1.0"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"reqwest",
|
"reqwest",
|
||||||
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
|
"sha1",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|||||||
@@ -7,3 +7,5 @@ edition.workspace = true
|
|||||||
anyhow.workspace = true
|
anyhow.workspace = true
|
||||||
serde_json.workspace = true
|
serde_json.workspace = true
|
||||||
reqwest = { version = "0.12", default-features = false, features = ["blocking", "rustls-tls", "json"] }
|
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
|
```mermaid
|
||||||
flowchart LR
|
flowchart LR
|
||||||
main["src/main.rs"] -->|依次调用两个只读探针| impls["src/probes.rs"]
|
main["src/main.rs"] -->|依次调用两个只读探针| impls["src/probes.rs"]
|
||||||
|
main -->|指定资产取样或离线重放| audit["src/book_audit.rs"]
|
||||||
|
audit -->|精确比较价格| books
|
||||||
impls -->|可选买卖报价对照| check["src/price_check.rs"]
|
impls -->|可选买卖报价对照| check["src/price_check.rs"]
|
||||||
check -->|精确价格与市场标识| books
|
check -->|精确价格与市场标识| books
|
||||||
impls -->|目录标识、盘口校验和最优价| books["src/books.rs"]
|
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)
|
`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)
|
[市场 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 books;
|
||||||
mod price_check;
|
mod price_check;
|
||||||
mod probes;
|
mod probes;
|
||||||
@@ -6,16 +7,43 @@ use reqwest::blocking::Client;
|
|||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
fn main() -> Result<()> {
|
fn main() -> Result<()> {
|
||||||
let args: Vec<_> = std::env::args().skip(1).collect();
|
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() {
|
let compare = match args.as_slice() {
|
||||||
[] => false,
|
[] => false,
|
||||||
[flag] if flag == "--compare-prices" => true,
|
[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()
|
let client = Client::builder()
|
||||||
.connect_timeout(Duration::from_secs(5))
|
.connect_timeout(Duration::from_secs(5))
|
||||||
.timeout(Duration::from_secs(15))
|
.timeout(Duration::from_secs(15))
|
||||||
.user_agent("eventbook-readonly-probe/0.1")
|
.user_agent("eventbook-readonly-probe/0.1")
|
||||||
.build()?;
|
.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;
|
let mut ok = true;
|
||||||
for (name, result) in [
|
for (name, result) in [
|
||||||
("polymarket", probes::polymarket(&client, compare)),
|
("polymarket", probes::polymarket(&client, compare)),
|
||||||
|
|||||||
Reference in New Issue
Block a user