Compare commits

..
Author SHA1 Message Date
codex-bot f220cd4b58 Verify Polygon CTF payouts at a finalized block 2026-12-06 01:07:09 +08:00
14 changed files with 419 additions and 249 deletions

No files matched your search

-15
View File
@@ -13,21 +13,6 @@ flowchart LR
stream -.->|执行命令| api
```
## 定时免手续费
JSONL `schedule_fee_holiday` 接受 `market`、可选 `starts_at_ms` 和必需的 `ends_at_ms`。公开费率和市场详情读取当前生效的配置,市场 WebSocket 成交帧保留实际撮合所用的费率。
```mermaid
sequenceDiagram
participant C as 客户端
participant H as 市场 HTTP
participant E as Exchange
C->>H: 查询市场详情或费率
H->>E: 读取当前生效的费率
E-->>H: 返回有效费率和交易参数
H-->>C: 返回报价所需参数
```
## 一次命令会话
```mermaid
-19
View File
@@ -476,25 +476,6 @@ sequenceDiagram
E-->>C: 顺序返回报价、价差、中点、时间和游标
```
## 市场费率与免手续费窗口
`list` 可通过 `fee_category` 选择当前公开费率表。显式 `taker_fee_rate_ppm` 优先,未设置两者的市场继续沿用零费率。操作员可用 `schedule_fee_holiday` 设定 UTC 毫秒区间 `[starts_at_ms, ends_at_ms)`,省略开始时间表示立即生效。结束后自动恢复配置费率。
```mermaid
sequenceDiagram
actor O as 操作员
participant E as Exchange
participant F as fees.rs
participant D as SQLite
O->>E: 上架市场并配置类别或费率
E->>F: 保存基础费率
O->>E: 安排免手续费窗口
E->>D: 保存生效与结束时间
E->>F: 下单时读取有效费率
F->>D: 查询 effective_market_fee_terms
E->>D: 记录撮合实际使用的费率和费用
```
## 赛事目录与成交量
```mermaid
+1 -19
View File
@@ -264,7 +264,7 @@ pub(crate) fn market_buy(tx: &Transaction, books: &Books, order: BudgetBuy) -> R
"INSERT INTO budget_spend_micros VALUES(?,?)",
params![seq, spent],
)?;
let fee = settle_with_rate(tx, &market, &outcome, fills, Some(Taker::Budget(seq)), rate)?;
let fee = settle(tx, &market, &outcome, fills, Some(Taker::Budget(seq)))?;
ledger::cash_micros(tx, &account, gross_remainder - fee)?;
let status = if unspent_micros == 0 {
"filled"
@@ -362,17 +362,6 @@ pub(crate) fn settle(
} else {
0
};
settle_with_rate(tx, market, outcome, fills, taker, rate)
}
fn settle_with_rate(
tx: &Transaction,
market: &str,
outcome: &str,
fills: Vec<Fill>,
taker: Option<Taker>,
rate: i64,
) -> Result<i64> {
let mut fees = 0;
for f in fills {
let first = book_leg(tx, market, outcome, &f, f.bid, taker)?;
@@ -421,13 +410,6 @@ fn settle_with_rate(
params![execution, taker.map(Taker::seq)],
)?;
if let Some(taker) = taker {
// The stream trigger seeds the configured base rate. Save the
// coefficient actually used by this order before publishing.
tx.prepare_cached(
"UPDATE market_stream_events SET fee_ppm=?2
WHERE kind='trade' AND source=?1 AND fee_ppm<>?2",
)?
.execute(params![execution, rate])?;
let fee = crate::fees::lot_fee(rate, f.price * 100, f.quantity);
if fee > 0 {
tx.execute(
+1 -1
View File
@@ -4,7 +4,7 @@ SELECT w.yes_label, w.no_label, tick.step_micros, minimum.microshares,
FROM market_wire_metadata w
LEFT JOIN market_tick_sizes tick ON tick.market=w.market
LEFT JOIN market_minimum_sizes minimum ON minimum.market=w.market
JOIN effective_market_fee_terms fee ON fee.market=w.market
JOIN market_fee_terms fee ON fee.market=w.market
LEFT JOIN neg_risk_members member ON member.market=w.market
LEFT JOIN sports_markets sport ON sport.market=w.market
LEFT JOIN events event ON event.id=sport.event
-7
View File
@@ -29,7 +29,6 @@ pub(crate) enum Command {
question: Option<String>,
rules: String,
taker_fee_rate_ppm: Option<i64>,
fee_category: Option<crate::fees::Category>,
base_fees: Option<crate::fees::BaseFees>,
min_order_size: Option<String>,
tick_size: Option<String>,
@@ -141,12 +140,6 @@ pub(crate) enum Command {
CancelAll {
account: String,
},
#[serde(rename = "schedule_fee_holiday")]
ScheduleFeeHoliday {
market: String,
starts_at_ms: Option<i64>,
ends_at_ms: i64,
},
Open {
market: String,
},
+2 -151
View File
@@ -3,7 +3,6 @@ use anyhow::{ensure, Result};
use matching::Fill;
use rusqlite::{params, Connection, OptionalExtension, Transaction};
use serde::Deserialize;
use serde_json::{json, Value};
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
@@ -26,78 +25,13 @@ impl BaseFees {
}
}
#[derive(Clone, Copy, Deserialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum Category {
#[serde(rename = "btc_5m_15m")]
Btc5m15m,
Crypto,
Sports,
Finance,
Tech,
Elections,
Politics,
Economics,
Culture,
Weather,
Mentions,
Geopolitics,
Combos,
General,
}
impl Category {
pub(crate) fn rate(self) -> i64 {
match self {
Self::Btc5m15m
| Self::Sports
| Self::Finance
| Self::Tech
| Self::Elections
| Self::Combos
| Self::General => 50_000,
Self::Crypto
| Self::Politics
| Self::Economics
| Self::Culture
| Self::Weather
| Self::Mentions => 10_000,
Self::Geopolitics => 0,
}
}
}
pub(crate) fn schedule_holiday(
tx: &Transaction,
market: &str,
starts_at: Option<i64>,
ends_at: i64,
) -> Result<Value> {
crate::validation::identifier(market)?;
let now: i64 = tx.query_row(
"SELECT CAST(unixepoch('subsec')*1000 AS INTEGER)",
[],
|r| r.get(0),
)?;
let start = starts_at.unwrap_or(now);
ensure!(
start >= now && ends_at > start,
"invalid fee holiday window"
);
tx.execute(
"INSERT INTO market_fee_holidays VALUES(?1,?2,?3)",
params![market, start, ends_at],
)?;
Ok(json!({"market":market,"starts_at_ms":start,"ends_at_ms":ends_at}))
}
impl Exchange {
pub fn base_fee_bps(&self, token: &str) -> Result<Option<i64>, MarketDataError> {
let (_, market) = assets::parse_id(token)
.map_err(|_| MarketDataError::Invalid("Invalid token id".into()))?;
let mut stmt = self
.db
.prepare_cached("SELECT taker_bps FROM effective_market_fee_terms WHERE market=?1")?;
.prepare_cached("SELECT taker_bps FROM market_fee_terms WHERE market=?1")?;
Ok(stmt
.query_row([market], |r| r.get::<_, Option<i64>>(0))
.optional()?
@@ -106,9 +40,7 @@ impl Exchange {
}
pub(crate) fn rate(db: &Connection, market: &str) -> Result<i64> {
Ok(db
.prepare_cached("SELECT rate_ppm FROM effective_market_fee_terms WHERE market=?1")?
.query_row([market], |r| r.get(0))?)
Ok(db.query_row("SELECT COALESCE(f.rate_ppm,0) FROM markets m LEFT JOIN market_fee_rates f ON f.market=m.id WHERE m.id=?", [market], |r|r.get(0))?)
}
// Price and rate both have six decimals. Round the fee only after the
@@ -204,85 +136,4 @@ mod tests {
assert_eq!(micros(rate, (100 - price) * 10000, size), expected);
}
}
#[test]
fn category_rate_and_holiday_share_public_and_execution_configuration() {
use crate::Exchange;
use serde_json::json;
let dir = tempfile::tempdir().unwrap();
let mut db = Exchange::open(dir.path().join("fee-schedule.sqlite")).unwrap();
for cmd in [
json!({"op":"list","id":"short-btc","market":"btc","rules":"btc","fee_category":"btc_5m_15m"}),
json!({"op":"list","id":"sports","market":"sport","rules":"result","fee_category":"sports","base_fees":{"maker_bps":0,"taker_bps":120}}),
json!({"op":"list","id":"crypto","market":"crypto","rules":"result","fee_category":"crypto"}),
json!({"op":"list","id":"explicit","market":"explicit","rules":"result","fee_category":"sports","taker_fee_rate_ppm":22000}),
json!({"op":"list","id":"geo","market":"geo","rules":"result","fee_category":"geopolitics"}),
json!({"op":"list","id":"legacy","market":"legacy","rules":"result"}),
] {
db.execute(cmd).unwrap();
}
for (market, rate) in [
("btc", 50000),
("sport", 50000),
("crypto", 10000),
("explicit", 22000),
("geo", 0),
("legacy", 0),
] {
assert_eq!(super::rate(&db.db, market).unwrap(), rate);
}
let token = crate::assets::id("sport", "YES");
assert_eq!(db.base_fee_bps(&token).unwrap(), Some(120));
let now: i64 = db
.db
.query_row(
"SELECT CAST(unixepoch('subsec')*1000 AS INTEGER)",
[],
|r| r.get(0),
)
.unwrap();
let command = json!({"op":"schedule_fee_holiday","id":"holiday","market":"sport","ends_at_ms":now+60000});
assert_eq!(
db.execute(command.clone()).unwrap(),
db.execute(command).unwrap()
);
assert_eq!(db.base_fee_bps(&token).unwrap(), Some(0));
assert_eq!(super::rate(&db.db, "sport").unwrap(), 0);
let data = db.clob_market_info("sport").unwrap().unwrap();
assert_eq!(data["tbf"], 0);
assert!(data.get("fd").is_none());
assert_eq!(super::rate(&db.db, "crypto").unwrap(), 10000);
for command in [
json!({"op":"fund","id":"maker","account":"maker","cents":15000}),
json!({"op":"fund","id":"taker","account":"taker","cents":6000}),
json!({"op":"split","id":"split","market":"sport","account":"maker","qty":100}),
json!({"op":"open","id":"open","market":"sport"}),
json!({"op":"order","id":"ask","market":"sport","outcome":"YES","account":"maker","side":"sell","price":50,"qty":100}),
] {
db.execute(command).unwrap();
}
let bought = db.execute(
json!({"op":"market_buy","id":"buy","market":"sport","outcome":"YES","account":"taker","amount_cents":5000,"max_price":50,"tif":"FOK"})
).unwrap();
assert_eq!(bought["status"], "filled");
assert_eq!(bought["unspent_cents"], 0);
let (saved_rate, fees): (i64, i64) = db
.db
.query_row(
"SELECT fee_ppm,(SELECT COUNT(*) FROM execution_fees)
FROM market_stream_events WHERE kind='trade' AND market='sport'",
[],
|row| Ok((row.get(0)?, row.get(1)?)),
)
.unwrap();
assert_eq!((saved_rate, fees), (0, 0));
db.db
.execute(
"UPDATE market_fee_holidays SET starts_at_ms=0,ends_at_ms=1 WHERE market='sport'",
[],
)
.unwrap();
assert_eq!(super::rate(&db.db, "sport").unwrap(), 50000);
}
}
+1 -1
View File
@@ -13,7 +13,7 @@ LEFT JOIN augmented_outcomes a ON a.market=w.market
LEFT JOIN market_tick_sizes tick ON tick.market=w.market
LEFT JOIN market_minimum_sizes minimum ON minimum.market=w.market
LEFT JOIN neg_risk_members member ON member.market=w.market
JOIN effective_market_fee_terms fee ON fee.market=w.market
JOIN market_fee_terms fee ON fee.market=w.market
LEFT JOIN quote_events quotes ON quotes.seq=(SELECT MAX(seq) FROM quote_events WHERE market=w.market)
LEFT JOIN last_asset_trades yes_trade ON yes_trade.market=w.market AND yes_trade.outcome='YES'
LEFT JOIN last_asset_trades no_trade ON no_trade.market=w.market AND no_trade.outcome='NO'
+1 -9
View File
@@ -63,11 +63,6 @@ pub(crate) fn apply(
previous_ms,
scheduled_at_ms,
} => crate::kickoff::reschedule(tx, &event, previous_ms, scheduled_at_ms),
Command::ScheduleFeeHoliday {
market,
starts_at_ms,
ends_at_ms,
} => crate::fees::schedule_holiday(tx, &market, starts_at_ms, ends_at_ms),
Command::List {
market,
slug,
@@ -76,7 +71,6 @@ pub(crate) fn apply(
listing,
resolution,
taker_fee_rate_ppm,
fee_category,
base_fees,
min_order_size,
tick_size,
@@ -93,9 +87,7 @@ pub(crate) fn apply(
if let Some(size) = min_order_size {
crate::minimum_size::MinimumSize::configure(tx, &market, &size)?;
}
if let Some(rate) =
taker_fee_rate_ppm.or_else(|| fee_category.map(crate::fees::Category::rate))
{
if let Some(rate) = taker_fee_rate_ppm {
crate::fees::configure(tx, &market, rate)?;
}
if let Some(base) = base_fees {
-20
View File
@@ -254,26 +254,6 @@ CREATE VIEW IF NOT EXISTS market_fee_terms AS
SELECT m.id AS market, COALESCE(f.rate_ppm,0) AS rate_ppm, COALESCE(b.maker_bps,0) AS maker_bps,
COALESCE(b.taker_bps,CASE WHEN COALESCE(f.rate_ppm,0)%100=0 THEN COALESCE(f.rate_ppm,0)/100 END) AS taker_bps
FROM markets m LEFT JOIN market_fee_rates f ON f.market=m.id LEFT JOIN market_base_fees b ON b.market=m.id;
CREATE TABLE IF NOT EXISTS market_fee_holidays (
market TEXT NOT NULL REFERENCES markets(id),
starts_at_ms INTEGER NOT NULL CHECK(starts_at_ms>=0),
ends_at_ms INTEGER NOT NULL CHECK(ends_at_ms>starts_at_ms),
PRIMARY KEY(market,starts_at_ms)
) WITHOUT ROWID;
CREATE VIEW IF NOT EXISTS effective_market_fee_terms AS
SELECT base.market,
CASE WHEN holiday.market IS NOT NULL THEN 0 ELSE base.rate_ppm END AS rate_ppm,
CASE WHEN holiday.market IS NOT NULL THEN 0 ELSE base.maker_bps END AS maker_bps,
CASE WHEN holiday.market IS NOT NULL THEN 0 ELSE base.taker_bps END AS taker_bps
FROM market_fee_terms base
LEFT JOIN market_fee_holidays holiday
ON holiday.market=base.market AND holiday.starts_at_ms=(
SELECT h.starts_at_ms FROM market_fee_holidays h
WHERE h.market=base.market AND h.starts_at_ms<=unixepoch('subsec')*1000
AND h.ends_at_ms>unixepoch('subsec')*1000
ORDER BY h.starts_at_ms DESC LIMIT 1
);
CREATE TABLE IF NOT EXISTS cash_remainders (
account TEXT PRIMARY KEY REFERENCES accounts(id), micros INTEGER NOT NULL CHECK(micros BETWEEN 0 AND 9999)
);
+23
View File
@@ -8,6 +8,7 @@ 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
@@ -123,3 +124,25 @@ 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)
@@ -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
}
+340
View File
@@ -0,0 +1,340 @@
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());
}
}
+28 -1
View File
@@ -1,6 +1,7 @@
mod book_audit;
mod books;
mod catalog;
mod ctf_resolution;
mod price_check;
mod probes;
use anyhow::{ensure, Result};
@@ -33,7 +34,33 @@ 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]";
"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(());
}
}
if let [mode, file] = args.as_slice() {
if mode == "--replay-market" {
let raw = serde_json::from_reader(std::fs::File::open(file)?)?;
+4 -6
View File
@@ -135,12 +135,6 @@ FOK 要求整笔金额成交,无法用完预算时交易回滚。超过最高
官方文档描述页面隐藏未命名项,并提示只交易已命名项、避免直接交易「其他」。本地在订单写入时也拦截未命名项,显式「其他」维持可见并标记角色。输入获胜者名称按去除首尾空白后的精确文本匹配;操作员负责按公告统一姓名和别名。全组一次提交裁决、命名证据格式及订单拒绝位置均为本地实现。真实场所的公告传递时序、错误码和预留位链上标识尚待实测。
### 分类费率与免手续费窗口
`list` 可给定 `fee_category` 选择公开费率表。短周期 BTC(`btc_5m_15m`)、体育、金融、科技、选举、组合和通用类别使用 0.05。普通加密、普通政治、经济、文化、天气和 Mentions 使用 0.01,地缘政治使用 0。显式 `taker_fee_rate_ppm` 优先,未配置的旧市场继续以原费率运行。[官方费率表](https://docs.polymarket.com/trading/fees)
`schedule_fee_holiday` 可配置立即或未来生效的半开 UTC 时间窗口。在窗口内撮合、预算估算和公开费率读取同一有效配置,结束后自动恢复。单笔预算买单使用固定费率完成预算和入账。成交帧保存执行时的费率,旧记录不回填。生产如何选择需要收费的旧市场、识别类别与安排活动时间仍待外场比对。
## 账户活动明细
`{"op":"activity","account":"alice","types":["TRADE","SPLIT","MERGE","REDEEM","CONVERSION"],"limit":20}` 查询该账户已执行的普通市场活动。官方示例买入 25 份、每份 0.49 美元,金额为 12.25 美元。本地对应 `shares=25`、`price_micros=490000`、`cash_delta_cents=-1225`。卖出、合并和兑现按实际收到的分数记正值。成交金额按成交价计算,挂单预留或释放的余额不单独算成交。互补订单成交仍归 TRADE。转换显示组 ID、每个输入的份额数和释放的现金。赎回的 shares 是核销的两侧份额之和,输方也可产生实付为零的活动。[官方钱包活动示例](https://docs.polymarket.com/trading/wallet-activity.md) · [Data API v2 类型与游标规范](https://data-api.polymarket.com/v2/openapi.json)
@@ -423,6 +417,10 @@ 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)