Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
33b3991c69 |
No files matched your search
@@ -425,3 +425,18 @@ sequenceDiagram
|
||||
E-->>H: true
|
||||
H-->>C: 200,neg_risk 为真
|
||||
```
|
||||
|
||||
### 钱包成交量
|
||||
|
||||
`GET /v2/user-volume?user=alice&start=1785542400&end=1785628800` 返回 `data.volume`(份数)、`data.volume_usdc` 和 `data.trade_count`。省略边界或填 0 表示该侧不限。
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as 客户端
|
||||
participant H as market_http.rs
|
||||
participant E as Exchange
|
||||
C->>H: GET /v2/user-volume
|
||||
H->>E: 钱包、起止时间
|
||||
E-->>H: UTC 整日成交汇总
|
||||
H-->>C: data 对象
|
||||
```
|
||||
@@ -335,6 +335,13 @@ fn respond(mut req: Request, engine: &Mutex<Exchange>) -> std::io::Result<()> {
|
||||
let (status, body) = data_page(path, params, engine);
|
||||
return send(req, status, body, None);
|
||||
}
|
||||
if path == "/v2/user-volume" {
|
||||
if req.method() != &Method::Get {
|
||||
return send(req, 405, json!({"error":"Method not allowed"}), Some("GET"));
|
||||
}
|
||||
let (status, body) = data_page(path, params, engine);
|
||||
return send(req, status, body, None);
|
||||
}
|
||||
let route = path.strip_prefix('/').unwrap_or(path);
|
||||
let (name, segment) = route
|
||||
.split_once('/')
|
||||
@@ -515,6 +522,7 @@ fn data_page(path: &str, params: &str, engine: &Mutex<Exchange>) -> (u16, Value)
|
||||
let page = match path {
|
||||
"/v2/oi" => read_page(params, engine, Exchange::public_open_interest),
|
||||
"/v2/value" => read_page(params, engine, Exchange::public_portfolio_value),
|
||||
"/v2/user-volume" => read_page(params, engine, Exchange::public_user_volume),
|
||||
"/v2/trades" => read_page(params, engine, Exchange::public_trade_feed),
|
||||
"/v2/resolutions" => read_page(params, engine, Exchange::public_resolutions),
|
||||
_ => read_page(params, engine, Exchange::public_price_history),
|
||||
@@ -533,6 +541,10 @@ fn data_page(path: &str, params: &str, engine: &Mutex<Exchange>) -> (u16, Value)
|
||||
503,
|
||||
json!({"code":"unavailable","error":"portfolio valuation unavailable","retryable":true}),
|
||||
),
|
||||
Err(HistoryError::Unavailable) if path == "/v2/user-volume" => (
|
||||
503,
|
||||
json!({"code":"unavailable","error":"user volume unavailable","retryable":true}),
|
||||
),
|
||||
Err(HistoryError::Unavailable) if path == "/v2/resolutions" => (
|
||||
500,
|
||||
json!({"code":"internal","error":"resolution state unavailable","retryable":true}),
|
||||
@@ -703,6 +715,10 @@ mod tests {
|
||||
("GET","/v2/value?user=a&condition=",String::new(),400,None),
|
||||
("GET","/v2/value?user=0x4d97dcd97ec945f40cf65f87097ace5ea0476045",String::new(),400,None),
|
||||
("POST","/v2/value",String::new(),405,None),
|
||||
("GET","/v2/user-volume?user=unknown",String::new(),200,Some(json!({"data":{"volume":0,"volume_usdc":0,"trade_count":0}}))),
|
||||
("GET","/v2/user-volume?user=0x4d97dcd97ec945f40cf65f87097ace5ea0476045",String::new(),400,None),
|
||||
("GET","/v2/user-volume",String::new(),400,None),
|
||||
("POST","/v2/user-volume",String::new(),405,None),
|
||||
("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),
|
||||
|
||||
@@ -2,6 +2,19 @@
|
||||
|
||||
维护一个 SQLite 模拟市场。每条写命令在同一事务内完成资金或份额预留、订单更新和幂等回执。成交明细由 matching 计算。只读 state 使用一个一致快照。
|
||||
|
||||
## 钱包成交量
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant H as HTTP
|
||||
participant E as portfolio/user_volume.rs
|
||||
participant D as SQLite
|
||||
H->>E: 钱包与 Unix 秒起止参数
|
||||
E->>E: 校验钱包,把有效边界转换为 UTC 日
|
||||
E->>D: 读取该钱包的买卖成交,汇总窗口内份数、成交额和笔数
|
||||
E-->>H: 单个数据对象
|
||||
```
|
||||
|
||||
## 文件依赖
|
||||
|
||||
箭头从使用方指向提供类型或功能的文件。虚线连到 workspace 内的另一个 crate。图中省略标准库及第三方 crate。
|
||||
@@ -41,6 +54,9 @@ flowchart LR
|
||||
api -->|事务内派发| market["src/market.rs"]
|
||||
api -->|解析只读查询| queries["src/catalog.rs"]
|
||||
queries -->|查询各盘及赛事成交量| volume["src/volume.rs"]
|
||||
api -->|查询钱包成交量| user_volume["src/portfolio/user_volume.rs"]
|
||||
user_volume -->|按 UTC 日期汇总钱包成交| user_volume_sql["src/portfolio/user_volume.sql"]
|
||||
user_volume_sql -->|读取按账户拆开的成交| wallet_legs["src/price_migration.sql"]
|
||||
volume -->|按市场汇总普通及互补成交| volumesql["src/volume.sql"]
|
||||
volumesql -->|成交、时间及吃单方| schema
|
||||
queries -->|市价预估| estimate["src/estimate.rs"]
|
||||
|
||||
@@ -54,6 +54,7 @@ pub use gamma_directory::DirectoryKey;
|
||||
pub use gamma_list::DirectoryResource;
|
||||
pub use open_interest::InterestQuery;
|
||||
pub use portfolio::http::ValueQuery;
|
||||
pub use portfolio::UserVolumeQuery;
|
||||
pub use prices_history::http::HistoryQuery;
|
||||
pub use prices_history::legacy::ClobHistoryQuery;
|
||||
pub use public_trades::http::TradeQuery;
|
||||
|
||||
@@ -10,6 +10,9 @@ use rusqlite::{params, Connection};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
mod user_volume;
|
||||
pub use user_volume::UserVolumeQuery;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct Filter {
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
use super::protocol::CONTRACTS;
|
||||
use crate::{
|
||||
inventory::decimal,
|
||||
lots::PER_SHARE,
|
||||
tick_size::PAR,
|
||||
validation::{hex_id, identifier},
|
||||
Exchange, MarketDataError,
|
||||
};
|
||||
use rusqlite::params;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct UserVolumeQuery {
|
||||
user: String,
|
||||
start: Option<i64>,
|
||||
end: Option<i64>,
|
||||
}
|
||||
|
||||
impl Exchange {
|
||||
pub fn public_user_volume(&self, query: UserVolumeQuery) -> Result<Value, MarketDataError> {
|
||||
let user = &query.user;
|
||||
identifier(user).map_err(|_| MarketDataError::Invalid("invalid user".into()))?;
|
||||
if CONTRACTS.iter().any(|c| c.eq_ignore_ascii_case(user)) {
|
||||
return Err(MarketDataError::Invalid(
|
||||
"protocol contract is not a user".into(),
|
||||
));
|
||||
}
|
||||
let start = query.start.filter(|&at| at != 0);
|
||||
let end = query.end.filter(|&at| at != 0);
|
||||
if matches!(start.zip(end), Some((start, end)) if start > end) {
|
||||
return Ok(json!({"data":{"volume":0,"volume_usdc":0,"trade_count":0}}));
|
||||
}
|
||||
let day = |at: i64| at.div_euclid(86_400);
|
||||
let (shares, notional, count): (i64, i64, i64) = self
|
||||
.db
|
||||
.prepare_cached(include_str!("user_volume.sql"))?
|
||||
.query_row(
|
||||
params![user, hex_id(user, 40), start.map(day), end.map(day)],
|
||||
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
|
||||
)?;
|
||||
Ok(json!({"data":{
|
||||
"volume":decimal(shares.into(), PER_SHARE),
|
||||
"volume_usdc":decimal(notional.into(), PER_SHARE * PAR),
|
||||
"trade_count":count
|
||||
}}))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
WITH owners AS (
|
||||
SELECT ?1 AS id WHERE NOT ?2
|
||||
UNION ALL
|
||||
SELECT id FROM accounts WHERE ?2 AND id=?1 COLLATE NOCASE
|
||||
), legs AS (
|
||||
SELECT execution, quantity, price,
|
||||
at_ms/86400000 - (at_ms%86400000<0) AS utc_day
|
||||
FROM wallet_trade_legs
|
||||
WHERE account IN (SELECT id FROM owners)
|
||||
)
|
||||
SELECT COALESCE(SUM(quantity),0), COALESCE(SUM(quantity*price),0), COUNT(DISTINCT execution)
|
||||
FROM legs
|
||||
WHERE (?3 IS NULL OR utc_day>=?3) AND (?4 IS NULL OR utc_day<=?4)
|
||||
@@ -0,0 +1,67 @@
|
||||
use exchange::Exchange;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
fn volume(db: &Exchange, query: Value) -> Value {
|
||||
db.public_user_volume(serde_json::from_value(query).unwrap())
|
||||
.unwrap()["data"]
|
||||
.clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wallet_volume_counts_both_roles_and_rounds_bounds_to_utc_days() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("wallet-volume.sqlite");
|
||||
let mut db = Exchange::open(&path).unwrap();
|
||||
for line in include_str!("../../../docs/examples/valuation.jsonl")
|
||||
.lines()
|
||||
.take(7)
|
||||
{
|
||||
db.execute(serde_json::from_str(line).unwrap()).unwrap();
|
||||
}
|
||||
for cmd in [
|
||||
json!({"op":"list","id":"list-pair","market":"pair","rules":"赛果"}),
|
||||
json!({"op":"open","id":"open-pair","market":"pair"}),
|
||||
json!({"op":"order","id":"buy-no","market":"pair","account":"alice","outcome":"NO","side":"buy","price":40,"qty":3}),
|
||||
json!({"op":"order","id":"buy-yes","market":"pair","account":"bob","outcome":"YES","side":"buy","price":60,"qty":3}),
|
||||
] {
|
||||
db.execute(cmd).unwrap();
|
||||
}
|
||||
// Put the executions on opposite sides of UTC midnight.
|
||||
let sqlite = rusqlite::Connection::open(&path).unwrap();
|
||||
assert_eq!(
|
||||
sqlite
|
||||
.execute("UPDATE trade_prices SET at_ms=86399999", [])
|
||||
.unwrap(),
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
sqlite
|
||||
.execute("UPDATE paired_fills SET at_ms=86400000", [])
|
||||
.unwrap(),
|
||||
1
|
||||
);
|
||||
drop(sqlite);
|
||||
|
||||
let zero = json!({"volume":0,"volume_usdc":0,"trade_count":0});
|
||||
assert_eq!(volume(&db, json!({"user":"unknown"})), zero);
|
||||
assert_eq!(
|
||||
volume(&db, json!({"user":"alice","start":86500,"end":86400})),
|
||||
zero
|
||||
);
|
||||
assert_eq!(
|
||||
volume(&db, json!({"user":"alice","start":1,"end":1})),
|
||||
json!({"volume":2,"volume_usdc":1.2,"trade_count":1})
|
||||
);
|
||||
assert_eq!(
|
||||
volume(&db, json!({"user":"alice","start":86500,"end":86500})),
|
||||
json!({"volume":3,"volume_usdc":1.2,"trade_count":1})
|
||||
);
|
||||
assert_eq!(
|
||||
volume(&db, json!({"user":"alice","start":0,"end":0})),
|
||||
json!({"volume":5,"volume_usdc":2.4,"trade_count":2})
|
||||
);
|
||||
assert_eq!(
|
||||
volume(&db, json!({"user":"bob"})),
|
||||
json!({"volume":5,"volume_usdc":3,"trade_count":2})
|
||||
);
|
||||
}
|
||||
@@ -8,7 +8,6 @@ cargo run --locked -p venue-probe
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
main -->|核对链上兑付权重| ctf["src/ctf_resolution.rs"]
|
||||
main["src/main.rs"] -->|依次调用两个只读探针| impls["src/probes.rs"]
|
||||
main -->|重放 Gamma 市场| catalog["src/catalog.rs"]
|
||||
impls -->|识别持仓协议及两套 ID| catalog
|
||||
@@ -124,25 +123,3 @@ sequenceDiagram
|
||||
2026-12-03 06:55 UTC 采集的[同侧报价快照](fixtures/live-side-prices.json)按请求保存前后盘口、报价、时间、方法及响应。双侧盘口最优价为 0.039 和 0.04。缺买盘的结果返回 BUY 字符串 0,缺卖盘的结果返回 SELL 字符串 1。批量 POST 返回相同字符串。文档列出的逗号分隔 GET 在这次生产取样返回 400。三个资产的前后盘口哈希各自一致。[官方单价接口](https://docs.polymarket.com/api-reference/market-data/get-market-price)
|
||||
|
||||
[电竞盘双空样本](fixtures/live-empty-prices.json)保留前后盘口和两次价格请求。两个深度数组均为空,公开 BUY 返回 "0",SELL 返回 "1"。探针把该结果计为已验证的空盘报价,实际可成交数量仍为零。
|
||||
|
||||
## Polygon CTF 裁决核对
|
||||
|
||||
`venue-probe --inspect-resolution CONDITION [EXPECTED]` 读取 Polygon 主网 CTF 的二元条件。默认使用 PublicNode,可通过 `EVENTBOOK_POLYGON_RPC_URL` 更换 HTTPS RPC。将输出保存为 JSON 后,`venue-probe --replay-resolution FILE [EXPECTED]` 可离线核对原始 ABI 字。`EXPECTED` 可用 `first`、`second`、`split`、`weighted`、`unresolved` 或 `unprepared`。前两个值指目录结果顺序,使用者应按已核实的结果映射指定预期。给出预期且不一致时,命令保留报告并以非零状态退出。
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
actor C as 调用者
|
||||
participant P as venue-probe
|
||||
participant N as Polygon RPC
|
||||
alt 现场读取
|
||||
C->>P: inspect-resolution CONDITION
|
||||
P->>N: 核对主网链 ID 及已最终确认区块
|
||||
P->>N: 在该区块读取结果数、分母和各侧权重
|
||||
P->>N: 复核区块哈希
|
||||
else 离线重放
|
||||
C->>P: replay-resolution FILE
|
||||
end
|
||||
P-->>C: 返回原始 ABI 字、十进制权重和对照结果
|
||||
```
|
||||
|
||||
[实测记录](fixtures/live-ctf-resolution.json)保存了两个独立节点一致返回的区块和权重。该市场的 Gamma 目录结果顺序为 Over、Under,链上分子为 0、1,分母为 1。探针只读取 CTF 的合约状态。结果由所选 RPC 提供,仅覆盖 CTF 二元条件。PositionManager 市场和链上状态证明需要额外的验证路径。[Gamma 封盘样本](../../docs/examples/public-closed-chart-history.json) · [Polymarket 合约清单](https://docs.polymarket.com/resources/contracts) · [Conditional Tokens 合约](https://github.com/gnosis/conditional-tokens-contracts/blob/master/contracts/ConditionalTokens.sol)
|
||||
@@ -1,18 +0,0 @@
|
||||
{
|
||||
"chain_id": 137,
|
||||
"block_number": "0x5df5831",
|
||||
"block_hash": "0xf36806915eb4a8aa5ecb85d411a3259c9a65b1f1af65049e30e5098a32f6b45c",
|
||||
"condition_id": "0xdf04a0495b0a16dbce386acdc16d9aed19784db9888be53d150354b83b7c18b1",
|
||||
"contract": "0x4D97DCd97eC945f40cF65F87097ACe5EA0476045",
|
||||
"sources": [
|
||||
"https://polygon.drpc.org",
|
||||
"https://polygon-bor-rpc.publicnode.com"
|
||||
],
|
||||
"outcome_slots": "0x0000000000000000000000000000000000000000000000000000000000000002",
|
||||
"denominator": "0x0000000000000000000000000000000000000000000000000000000000000001",
|
||||
"numerators": [
|
||||
"0x0000000000000000000000000000000000000000000000000000000000000000",
|
||||
"0x0000000000000000000000000000000000000000000000000000000000000001"
|
||||
],
|
||||
"observed_at_ms": 1796490278240
|
||||
}
|
||||
@@ -1,340 +0,0 @@
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use reqwest::{blocking::Client, Url};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
const POLYGON_CHAIN_ID: u64 = 137;
|
||||
const CTF: &str = "0x4D97DCd97eC945f40cF65F87097ACe5EA0476045";
|
||||
const DEFAULT_RPC: &str = "https://polygon-bor-rpc.publicnode.com";
|
||||
// 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 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)
|
||||
}
|
||||
|
||||
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")
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
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)}),
|
||||
)
|
||||
}
|
||||
|
||||
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") {
|
||||
anyhow::bail!("{method} RPC rejected the request (code {})", error["code"]);
|
||||
}
|
||||
response
|
||||
.get("result")
|
||||
.cloned()
|
||||
.with_context(|| format!("missing result for {method}"))
|
||||
}
|
||||
|
||||
fn call(client: &Client, url: &Url, block: &str, data: &str) -> Result<String> {
|
||||
let value = rpc(
|
||||
client,
|
||||
url,
|
||||
"eth_call",
|
||||
json!([{"to":CTF,"data":data},block]),
|
||||
)?;
|
||||
let raw = value.as_str().context("invalid eth_call ABI result")?;
|
||||
hex_data(raw, 32)?;
|
||||
Ok(raw.to_owned())
|
||||
}
|
||||
|
||||
pub(crate) fn inspect(client: &Client, condition: &str, expected: Option<&str>) -> Result<Value> {
|
||||
let cid = hex_data(condition, 32)?;
|
||||
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 pending = rpc(
|
||||
client,
|
||||
&url,
|
||||
"eth_getBlockByNumber",
|
||||
json!(["finalized", false]),
|
||||
)?;
|
||||
let number = pending["number"]
|
||||
.as_str()
|
||||
.context("RPC finalized block has no block number")?;
|
||||
quantity(number)?;
|
||||
let hash = pending["hash"]
|
||||
.as_str()
|
||||
.context("RPC finalized block has no block hash")?;
|
||||
hex_data(hash, 32)?;
|
||||
let slots = call(client, &url, number, &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 = call(
|
||||
client,
|
||||
&url,
|
||||
number,
|
||||
&format!("0x{PAYOUT_DENOMINATOR}{cid}"),
|
||||
)?;
|
||||
let numerators = if slot_word == two {
|
||||
Some([
|
||||
call(
|
||||
client,
|
||||
&url,
|
||||
number,
|
||||
&format!("0x{PAYOUT_NUMERATOR}{cid}{:064x}", 0),
|
||||
)?,
|
||||
call(
|
||||
client,
|
||||
&url,
|
||||
number,
|
||||
&format!("0x{PAYOUT_NUMERATOR}{cid}{:064x}", 1),
|
||||
)?,
|
||||
])
|
||||
} else {
|
||||
None
|
||||
};
|
||||
// The provider may lack EIP-1898 support. All calls use the finalized block
|
||||
// number, then the block hash is checked again before accepting the read.
|
||||
let current = rpc(client, &url, "eth_getBlockByNumber", json!([number, false]))?;
|
||||
ensure!(
|
||||
current["hash"] == hash && current["number"] == number,
|
||||
"RPC block changed during CTF reads"
|
||||
);
|
||||
audit(
|
||||
Observation {
|
||||
chain_id,
|
||||
block_number: number.to_owned(),
|
||||
block_hash: hash.to_owned(),
|
||||
contract: CTF.to_owned(),
|
||||
condition_id: condition.to_ascii_lowercase(),
|
||||
outcome_slots: slots,
|
||||
denominator,
|
||||
numerators,
|
||||
observed_at_ms: Some(
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)?
|
||||
.as_millis()
|
||||
.try_into()?,
|
||||
),
|
||||
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,7 +1,6 @@
|
||||
mod book_audit;
|
||||
mod books;
|
||||
mod catalog;
|
||||
mod ctf_resolution;
|
||||
mod price_check;
|
||||
mod probes;
|
||||
use anyhow::{ensure, Result};
|
||||
@@ -34,33 +33,7 @@ fn observe_book(client: &Client, url: reqwest::Url, token: &str) -> Result<()> {
|
||||
fn main() -> Result<()> {
|
||||
let args: Vec<_> = std::env::args().skip(1).collect();
|
||||
let usage =
|
||||
"usage: venue-probe [--compare-prices | --inspect-book TOKEN | --replay-book TOKEN FILE | --replay-market FILE | --inspect-resolution CONDITION [EXPECTED] | --replay-resolution FILE [EXPECTED]]";
|
||||
if let [mode, value, rest @ ..] = args.as_slice() {
|
||||
if matches!(
|
||||
mode.as_str(),
|
||||
"--inspect-resolution" | "--replay-resolution"
|
||||
) {
|
||||
ensure!(rest.len() <= 1, usage);
|
||||
let expected = rest.first().map(String::as_str);
|
||||
let report = if mode == "--replay-resolution" {
|
||||
ctf_resolution::replay(value, expected)?
|
||||
} else {
|
||||
let client = 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()?;
|
||||
ctf_resolution::inspect(&client, value, expected)?
|
||||
};
|
||||
println!("{report}");
|
||||
ensure!(
|
||||
report["matches"] != false,
|
||||
"CTF payout status differs from the expected result"
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
"usage: venue-probe [--compare-prices | --inspect-book TOKEN | --replay-book TOKEN FILE | --replay-market FILE]";
|
||||
if let [mode, file] = args.as_slice() {
|
||||
if mode == "--replay-market" {
|
||||
let raw = serde_json::from_reader(std::fs::File::open(file)?)?;
|
||||
|
||||
@@ -223,6 +223,12 @@ JSONL 下单面板的 `price` 接受 token_id 和方向,BUY 读取最低卖价
|
||||
|
||||
[可重放样例](examples/execution-prices.jsonl)开始时只有 YES 买单,买入 YES 的报价为 null。随后有人以 0.89 挂买 NO,YES 买入价变成 0.11,卖出价为 0.09。NO 买入价为 0.91,卖出价为 0.89。这四个报价均来自挂单,无需先发生交易。单侧没有对手时保留该键并返回 null。重复项合并,未知资产使整批失败。空批次拒绝,盘前返回待集合竞价的挂单报价。上述边界属于本地约定。本地 token_id 使用 Eventbook 的结果资产 ID,公开接口的生产响应、原生资产编号与无流动性时的处理仍待对照。
|
||||
|
||||
### 钱包成交量 Data API
|
||||
|
||||
官方 `GET /v2/user-volume` 按 UTC 整日统计钱包的买卖成交,返回份数、USDC 金额和成交笔数。起止参数以 Unix 秒表示,省略或填 0 关闭该侧边界。倒置窗口及无成交钱包返回零。[官方接口](https://docs.polymarket.com/api-reference/wallet/get-a-users-trading-volume)
|
||||
|
||||
在空数据库重放 [估值样例](examples/valuation.jsonl) 的前七条命令。Alice 和 Bob 分别查询 `/v2/user-volume`,均应得到 2 份、1.2 USDC 和 1 笔。互补成交使用各自的结果资产价格。金额为成交价乘份数,费用与抵押拆并不计。盘口关闭后历史成交仍可查询。本地按成交编号去重计笔数,无可信时间的旧成交只进入不限日期的汇总。独立的组合 RFQ 账本及生产端点的持续对账仍待接入。
|
||||
|
||||
## 精确抵押币现金余额
|
||||
|
||||
`balance` 返回账户可用现金、有效买单预留现金及二者之和,单位均为百万分之一模拟美元。拆分完整结果集所用的抵押和已买入的份额另由仓位账本记录。模拟 fund 可以用整数 micros 建立账户,也可以沿用 cents。入金回执和 activity 的 net_cash_delta_micros 可用于精确对账,原 funded 和 cash_delta_cents 字段保留整分部分。一个账户只接受首次 fund;相同请求可幂等重放。
|
||||
@@ -417,10 +423,6 @@ fidelity 以分钟为单位;省略或不大于零时按 1 分钟处理。相
|
||||
|
||||
官方 OpenAPI 给出的 condition 和 event 查询按条件返回,question 查询以问题为单位。两种查询的更新时间分别是 UTC 时间和 Unix 秒数字符串。本地使用记录下来的提案、争议和兑付时间。早期数据库缺失的时间保留为空。本地未接入链上事件,交易哈希和日志序号保留空串,区块号、报告人及投票截止估计省略。new_version_q 采用 OpenAPI 对规则修订的定义,本地原始规则不可改。旧版官方子图在 QuestionInitialized 上直接置 true,这一点存在口径差异。提案到期后需按模拟系统的最终确认流程兑付。本次按规范、合约及子图核对,生产端点没有取得可重放的响应。[官方接口](https://docs.polymarket.com/api-reference/markets/get-resolution-state) · [OpenAPI](https://data-api.polymarket.com/v2/openapi.json) · [UMA 适配器](https://github.com/Polymarket/uma-ctf-adapter/blob/main/src/UmaCtfAdapter.sol) · [裁决子图](https://github.com/Polymarket/resolution-subgraph/blob/main/src/uma-ctf-adapter.ts)
|
||||
|
||||
### CTF 链上兑付核对
|
||||
|
||||
从已封盘的 CS2 市场目录读取 `conditionId` 和结果顺序,在两个 Polygon 节点用同一最终确认区块 `0x5df5831` 读取 CTF。结果数为 2,按目录顺序的兑付分子为 [0,1],分母为 1,对应 Under 胜出。实测 ABI 字可由 `venue-probe --replay-resolution` 离线核对,也可指定 `second` 作为预期。此次取样验证了该 CTF 条件,PositionManager 市场、真实预言机证明及链上同步入账仍待覆盖。[生产目录记录](examples/public-closed-chart-history.json) · [双节点链上记录](../crates/venue-probe/fixtures/live-ctf-resolution.json)
|
||||
|
||||
### Data API 账户持仓价值
|
||||
|
||||
官方 `GET /v2/value` 要求传 user,可选最多 20 个不同 condition。结果是 data 对象,内含 proxy_wallet 和四位小数精度的美元金额。一个无持仓的钱包值为零。官方总额还包括未终结组合的成本基础,指定 condition 时仅统计选中的单盘。资金余额不计入持仓价值。[官方 OpenAPI](https://data-api.polymarket.com/v2/openapi.json)
|
||||
|
||||
Reference in new issue
Block a user