Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 2e95c5a631 |
@@ -247,6 +247,23 @@ sequenceDiagram
|
||||
|
||||
event_id 取自本地 events 或 catalog 查询,market_id 取自 assets 查询。两个参数均可重复,同类 ID 取并集,同时指定事件与市场时取交集。独立市场的公告也能通过 market_id 查询。默认按公告 ID 降序,每页 20 条;支持 order=id、ascending、offset 和 0 到 100 的 limit。当前查询对其他筛选参数返回 400。
|
||||
|
||||
### 组合账本
|
||||
|
||||
重放[组合样例](../../docs/examples/combo-ledger.jsonl),或自选两个已上架市场的结果,向 `prepare_combo` 提交 `legs`。取回的 `combo` ID 可用于 `split_combo`、`merge_combo`、`redeem_combo` 和只读的 `combo`。拆分和合并的数量表示成对的 YES 和 NO 份额,兑付需要指定一侧。数量可使用整数份额 `qty` 或微份 `qty_micros`。只读查询加 `account` 可查看该账户的两侧份额。
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
actor U as 操作员
|
||||
participant S as stream.rs
|
||||
participant E as Exchange
|
||||
U->>S: prepare_combo,提交腿的市场与选择
|
||||
S->>E: 执行组合定义命令
|
||||
E-->>U: 组合 ID、腿和可兑奖状态
|
||||
U->>S: split_combo,再查询 combo
|
||||
S->>E: 冻结模拟现金,生成 YES 和 NO
|
||||
E-->>U: 账户两侧的微份额及当前兑付状态
|
||||
```
|
||||
|
||||
### 从事件页进入订单簿
|
||||
|
||||
```mermaid
|
||||
|
||||
@@ -29,6 +29,11 @@ flowchart LR
|
||||
holders -->|按余额及结果分页| holderrows["src/holders.sql"]
|
||||
holderrows -->|读取含挂单预留的持仓| markschema
|
||||
holders -->|按毛持仓估值| portfolio
|
||||
api -->|迁移组合账本| combo_schema["src/combo_schema.sql"]
|
||||
market -->|建立组合与处理抵押| combo["src/combo.rs"]
|
||||
queries -->|读取定义、腿状态及余额| combo
|
||||
combo -->|复用现金微单位账本| ledger["src/ledger.rs"]
|
||||
combo --> combo_schema
|
||||
api -->|接收轮换心跳 ID| beat["src/heartbeat.rs"]
|
||||
book -->|记录订单所属 key| beat
|
||||
expiry -->|清理到期注册| beat
|
||||
@@ -400,6 +405,30 @@ sequenceDiagram
|
||||
E-->>U: 提交后新增的赢家 YES 即可赎回
|
||||
```
|
||||
|
||||
## 组合份额与兑付
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
actor O as 操作员
|
||||
participant E as Exchange
|
||||
participant C as combo.rs
|
||||
participant D as SQLite
|
||||
O->>E: prepare_combo,提交各市场及选择结果
|
||||
E->>C: 规范化腿并生成组合 ID
|
||||
C->>D: 保存组合定义与腿
|
||||
O->>E: split_combo,抵押模拟现金
|
||||
E->>C: 铸出等量 YES 和 NO
|
||||
C->>D: 提交现金扣减、份额和流水
|
||||
O->>E: combo,查询可兑奖状态
|
||||
E->>C: 读取各腿实际裁决
|
||||
alt 任一腿兑付为零或全部腿已裁决
|
||||
O->>E: redeem_combo,指定一侧与数量
|
||||
C->>D: 扣减份额、释放抵押、写流水
|
||||
else 仍有悬而未决的腿
|
||||
E-->>O: 返回待裁决状态
|
||||
end
|
||||
```
|
||||
|
||||
## 开盘后出现新候选人
|
||||
|
||||
`command.rs` 和 `market.rs` 把增强型组合的定义、命名和裁决交给 `augmented.rs`。成员编号和转换沿用 `neg_risk.rs`;`schema.sql` 拦截未命名盘口的直接订单。`catalog.rs`、`assets.rs` 和 `portfolio.rs` 从同一条命名记录生成展示字段。
|
||||
|
||||
@@ -294,6 +294,10 @@ pub(crate) enum Query {
|
||||
event: Option<String>,
|
||||
slug: Option<String>,
|
||||
},
|
||||
Combo {
|
||||
combo: String,
|
||||
account: Option<String>,
|
||||
},
|
||||
History {
|
||||
market: String,
|
||||
outcome: String,
|
||||
@@ -313,6 +317,7 @@ impl Query {
|
||||
.response(),
|
||||
)
|
||||
}
|
||||
Self::Combo { combo, account } => crate::combo::read(db, &combo, account.as_deref()),
|
||||
Self::Price(request) => request.single(db),
|
||||
Self::Prices { requests } => crate::quotes::prices(db, &requests),
|
||||
Self::QuoteHistory(request) => request.read(db),
|
||||
|
||||
@@ -0,0 +1,317 @@
|
||||
use crate::{
|
||||
assets,
|
||||
inventory::{quantity_units, UNIT},
|
||||
ledger,
|
||||
validation::identifier,
|
||||
};
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use rusqlite::{params, Connection, OptionalExtension, Transaction};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
const FACTOR_UNIT: u128 = 10u128.pow(36);
|
||||
const FACTOR_LIMB: u128 = 10u128.pow(18);
|
||||
|
||||
#[derive(Clone, Copy, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "UPPERCASE")]
|
||||
pub(crate) enum Side {
|
||||
Yes,
|
||||
No,
|
||||
}
|
||||
|
||||
impl Side {
|
||||
fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Yes => "YES",
|
||||
Self::No => "NO",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct Leg {
|
||||
market: String,
|
||||
outcome: Side,
|
||||
}
|
||||
|
||||
pub(crate) fn prepare(tx: &Transaction, mut legs: Vec<Leg>) -> Result<Value> {
|
||||
ensure!(
|
||||
(2..=50).contains(&legs.len()),
|
||||
"a combo requires 2 to 50 legs"
|
||||
);
|
||||
legs.sort_unstable_by(|a, b| a.market.cmp(&b.market));
|
||||
ensure!(
|
||||
legs.windows(2).all(|pair| pair[0].market != pair[1].market),
|
||||
"duplicate or conflicting combo market"
|
||||
);
|
||||
let canonical = serde_json::to_string(&legs)?;
|
||||
let hash = Sha256::digest(canonical.as_bytes());
|
||||
let id = format!("combo:{}", data_encoding::HEXLOWER.encode(&hash));
|
||||
let stored = tx
|
||||
.query_row(
|
||||
"SELECT canonical_legs FROM combo_conditions WHERE id=?",
|
||||
[&id],
|
||||
|r| r.get::<_, String>(0),
|
||||
)
|
||||
.optional()?;
|
||||
if let Some(stored) = stored {
|
||||
ensure!(stored == canonical, "combo definition mismatch");
|
||||
return read(tx, &id, None);
|
||||
}
|
||||
tx.execute(
|
||||
"INSERT INTO combo_conditions(id,canonical_legs) VALUES(?,?)",
|
||||
params![id, canonical],
|
||||
)?;
|
||||
let mut insert = tx.prepare_cached(
|
||||
"INSERT INTO combo_legs(combo,market,outcome)
|
||||
SELECT ?1,m.id,?3 FROM markets m LEFT JOIN augmented_outcomes a ON a.market=m.id
|
||||
WHERE m.id=?2 AND COALESCE(a.role,'')<>'placeholder'",
|
||||
)?;
|
||||
for leg in &legs {
|
||||
identifier(&leg.market)?;
|
||||
ensure!(
|
||||
insert.execute(params![id, leg.market, leg.outcome.name()])? == 1,
|
||||
"unknown or hidden combo leg"
|
||||
);
|
||||
}
|
||||
read(tx, &id, None)
|
||||
}
|
||||
|
||||
struct Factor {
|
||||
down: u128,
|
||||
up: u128,
|
||||
}
|
||||
|
||||
impl Factor {
|
||||
fn resolved(payouts: &[Option<i64>]) -> Option<Self> {
|
||||
if payouts.contains(&Some(0)) {
|
||||
return Some(Self { down: 0, up: 0 });
|
||||
}
|
||||
if payouts.iter().any(Option::is_none) {
|
||||
return None;
|
||||
}
|
||||
// The local binary ledger has only full, zero and half payouts.
|
||||
let halves = payouts
|
||||
.iter()
|
||||
.filter(|payout| **payout == Some(UNIT / 2))
|
||||
.count();
|
||||
let denominator = 1u128 << halves;
|
||||
Some(Self {
|
||||
down: FACTOR_UNIT / denominator,
|
||||
up: FACTOR_UNIT.div_ceil(denominator),
|
||||
})
|
||||
}
|
||||
|
||||
fn payout(&self, side: Side, quantity: i64) -> i64 {
|
||||
match side {
|
||||
Side::Yes => product(quantity, self.down, false),
|
||||
Side::No => quantity - product(quantity, self.up, true),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn product(quantity: i64, factor: u128, round_up: bool) -> i64 {
|
||||
// Use base 10^18 limbs so an i64-sized share balance never needs a wide multiply.
|
||||
let qty = quantity as u128;
|
||||
let low = qty * (factor % FACTOR_LIMB);
|
||||
let high = qty * (factor / FACTOR_LIMB) + low / FACTOR_LIMB;
|
||||
let floor = high / FACTOR_LIMB;
|
||||
let has_remainder = high % FACTOR_LIMB != 0 || low % FACTOR_LIMB != 0;
|
||||
(floor + u128::from(round_up && has_remainder)) as i64
|
||||
}
|
||||
|
||||
const SELECT_LEGS: &str = "
|
||||
SELECT l.market,l.outcome,
|
||||
CASE m.winner WHEN 'VOID' THEN 500000 WHEN l.outcome THEN 1000000
|
||||
WHEN 'YES' THEN 0 WHEN 'NO' THEN 0 END AS payout,
|
||||
s.at_ms
|
||||
FROM combo_legs l JOIN markets m ON m.id=l.market
|
||||
LEFT JOIN price_settlements s ON s.market=m.id
|
||||
WHERE l.combo=?
|
||||
ORDER BY l.market";
|
||||
|
||||
pub(crate) fn read(db: &Connection, combo: &str, account: Option<&str>) -> Result<Value> {
|
||||
let Some((collateral, dust)) = db
|
||||
.query_row(
|
||||
"SELECT collateral_micros,rounding_dust_micros FROM combo_conditions WHERE id=?",
|
||||
[combo],
|
||||
|r| Ok((r.get::<_, i64>(0)?, r.get::<_, i64>(1)?)),
|
||||
)
|
||||
.optional()?
|
||||
else {
|
||||
anyhow::bail!("unknown combo")
|
||||
};
|
||||
let mut legs = Vec::new();
|
||||
let mut payouts = Vec::new();
|
||||
let mut stmt = db.prepare_cached(SELECT_LEGS)?;
|
||||
let mut rows = stmt.query([combo])?;
|
||||
while let Some(row) = rows.next()? {
|
||||
let market = row.get::<_, String>(0)?;
|
||||
let outcome = row.get::<_, String>(1)?;
|
||||
let payout: Option<i64> = row.get(2)?;
|
||||
payouts.push(payout);
|
||||
legs.push(json!({
|
||||
"market":market,"outcome":outcome,"position_id":assets::id(&market,&outcome),
|
||||
"payout_micros_per_share":payout,"resolved_at_ms":row.get::<_,Option<i64>>(3)?
|
||||
}));
|
||||
}
|
||||
let factor = Factor::resolved(&payouts);
|
||||
let mut detail = json!({
|
||||
"combo":combo,"position_ids":[position_id(combo,Side::Yes),position_id(combo,Side::No)],
|
||||
"legs":legs,"redeemable":factor.is_some(),
|
||||
"payout_micros_per_share":factor.as_ref().map(|f| [f.payout(Side::Yes,UNIT),f.payout(Side::No,UNIT)]),
|
||||
"collateral_micros":collateral,"rounding_dust_micros":dust
|
||||
});
|
||||
if let Some(account) = account {
|
||||
identifier(account)?;
|
||||
detail["account"] = json!(account);
|
||||
detail["balances_micros"] = json!([
|
||||
balance(db, combo, account, Side::Yes)?,
|
||||
balance(db, combo, account, Side::No)?,
|
||||
]);
|
||||
}
|
||||
Ok(detail)
|
||||
}
|
||||
|
||||
fn position_id(combo: &str, side: Side) -> String {
|
||||
format!(
|
||||
"ebc:{}:{}",
|
||||
side.name(),
|
||||
combo.strip_prefix("combo:").unwrap_or(combo)
|
||||
)
|
||||
}
|
||||
|
||||
fn balance(db: &Connection, combo: &str, account: &str, side: Side) -> rusqlite::Result<i64> {
|
||||
db.query_row("SELECT COALESCE((SELECT shares_micros FROM combo_balances WHERE combo=? AND account=? AND outcome=?),0)",
|
||||
params![combo,account,side.name()], |r| r.get(0))
|
||||
}
|
||||
|
||||
fn change_balance(
|
||||
tx: &Transaction,
|
||||
combo: &str,
|
||||
account: &str,
|
||||
side: Side,
|
||||
change: i64,
|
||||
) -> Result<()> {
|
||||
let qty = balance(tx, combo, account, side)?
|
||||
.checked_add(change)
|
||||
.context("combo balance overflow")?;
|
||||
ensure!(qty >= 0, "insufficient combo balance");
|
||||
if qty == 0 {
|
||||
tx.execute(
|
||||
"DELETE FROM combo_balances WHERE combo=? AND account=? AND outcome=?",
|
||||
params![combo, account, side.name()],
|
||||
)?;
|
||||
} else {
|
||||
tx.execute(
|
||||
"INSERT INTO combo_balances VALUES(?,?,?,?)
|
||||
ON CONFLICT(combo,account,outcome) DO UPDATE SET shares_micros=excluded.shares_micros",
|
||||
params![combo, account, side.name(), qty],
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn change_backing(tx: &Transaction, combo: &str, change: i64) -> Result<()> {
|
||||
let (old, dust) = tx.query_row(
|
||||
"SELECT collateral_micros,rounding_dust_micros FROM combo_conditions WHERE id=?",
|
||||
[combo],
|
||||
|r| Ok((r.get::<_, i64>(0)?, r.get::<_, i64>(1)?)),
|
||||
)?;
|
||||
let new = old
|
||||
.checked_add(change)
|
||||
.context("combo collateral overflow")?;
|
||||
ensure!(new >= 0, "insufficient combo collateral");
|
||||
let held: bool = tx.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM combo_balances WHERE combo=?)",
|
||||
[combo],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
let (locked, dust) = if held {
|
||||
(new, dust)
|
||||
} else {
|
||||
(0, dust.checked_add(new).context("combo dust overflow")?)
|
||||
};
|
||||
tx.execute(
|
||||
"UPDATE combo_conditions SET collateral_micros=?,rounding_dust_micros=? WHERE id=?",
|
||||
params![locked, dust, combo],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct Amount {
|
||||
combo: String,
|
||||
account: String,
|
||||
qty: Option<i64>,
|
||||
qty_micros: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct Redemption {
|
||||
combo: String,
|
||||
account: String,
|
||||
outcome: Side,
|
||||
qty: Option<i64>,
|
||||
qty_micros: Option<i64>,
|
||||
}
|
||||
|
||||
impl Amount {
|
||||
pub(crate) fn apply(self, tx: &Transaction, request: &str, split: bool) -> Result<Value> {
|
||||
identifier(&self.account)?;
|
||||
let qty = quantity_units(self.qty, self.qty_micros)?;
|
||||
let delta = if split { qty } else { -qty };
|
||||
change_balance(tx, &self.combo, &self.account, Side::Yes, delta)?;
|
||||
change_balance(tx, &self.combo, &self.account, Side::No, delta)?;
|
||||
change_backing(tx, &self.combo, delta)?;
|
||||
ledger::cash_micros(tx, &self.account, -delta)?;
|
||||
let kind = if split { "SPLIT" } else { "MERGE" };
|
||||
tx.execute("INSERT INTO combo_movements(request_id,combo,account,kind,shares_micros,cash_delta_micros)
|
||||
VALUES(?,?,?,?,?,?)",params![request,self.combo,self.account,kind,qty,-delta])?;
|
||||
Ok(json!({"combo":self.combo,"pairs_micros":qty,"cash_delta_micros":-delta}))
|
||||
}
|
||||
}
|
||||
|
||||
impl Redemption {
|
||||
pub(crate) fn apply(self, tx: &Transaction, request: &str) -> Result<Value> {
|
||||
identifier(&self.account)?;
|
||||
let qty = quantity_units(self.qty, self.qty_micros)?;
|
||||
let mut stmt = tx.prepare_cached(SELECT_LEGS)?;
|
||||
let payouts = stmt
|
||||
.query_map([&self.combo], |r| r.get(2))?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
ensure!(!payouts.is_empty(), "unknown combo");
|
||||
let factor = Factor::resolved(&payouts).context("combo payout is pending")?;
|
||||
let paid = factor.payout(self.outcome, qty);
|
||||
change_balance(tx, &self.combo, &self.account, self.outcome, -qty)?;
|
||||
change_backing(tx, &self.combo, -paid)?;
|
||||
if paid > 0 {
|
||||
ledger::cash_micros(tx, &self.account, paid)?;
|
||||
}
|
||||
tx.execute("INSERT INTO combo_movements(request_id,combo,account,kind,outcome,shares_micros,cash_delta_micros)
|
||||
VALUES(?,?,?,'REDEEM',?,?,?)",params![request,self.combo,self.account,self.outcome.name(),qty,paid])?;
|
||||
Ok(
|
||||
json!({"combo":self.combo,"outcome":self.outcome,"burned_micros":qty,"paid_micros":paid}),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn high_precision_uses_separate_down_and_up_accumulators() {
|
||||
let factor = Factor::resolved(&[Some(500000); 37]).unwrap();
|
||||
let qty = 1_i64 << 37;
|
||||
assert_eq!(factor.payout(Side::Yes, qty), 0);
|
||||
assert_eq!(factor.payout(Side::No, qty), qty - 2);
|
||||
let full = Factor::resolved(&[Some(1000000); 50]).unwrap();
|
||||
assert_eq!(full.payout(Side::Yes, i64::MAX), i64::MAX);
|
||||
assert_eq!(full.payout(Side::No, i64::MAX), 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
BEGIN IMMEDIATE;
|
||||
CREATE TABLE IF NOT EXISTS combo_conditions (
|
||||
id TEXT PRIMARY KEY,
|
||||
canonical_legs TEXT NOT NULL UNIQUE,
|
||||
collateral_micros INTEGER NOT NULL DEFAULT 0 CHECK(collateral_micros>=0),
|
||||
rounding_dust_micros INTEGER NOT NULL DEFAULT 0 CHECK(rounding_dust_micros>=0)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS combo_legs (
|
||||
combo TEXT NOT NULL REFERENCES combo_conditions(id),
|
||||
market TEXT NOT NULL REFERENCES markets(id),
|
||||
outcome TEXT NOT NULL CHECK(outcome IN ('YES','NO')),
|
||||
PRIMARY KEY(combo,market)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS combo_balances (
|
||||
combo TEXT NOT NULL REFERENCES combo_conditions(id),
|
||||
account TEXT NOT NULL REFERENCES accounts(id),
|
||||
outcome TEXT NOT NULL CHECK(outcome IN ('YES','NO')),
|
||||
shares_micros INTEGER NOT NULL CHECK(shares_micros>0),
|
||||
PRIMARY KEY(combo,account,outcome)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS combo_movements (
|
||||
seq INTEGER PRIMARY KEY,
|
||||
request_id TEXT NOT NULL UNIQUE REFERENCES requests(id) DEFERRABLE INITIALLY DEFERRED,
|
||||
combo TEXT NOT NULL REFERENCES combo_conditions(id),
|
||||
account TEXT NOT NULL REFERENCES accounts(id),
|
||||
kind TEXT NOT NULL CHECK(kind IN ('SPLIT','MERGE','REDEEM')),
|
||||
outcome TEXT CHECK(outcome IN ('YES','NO')),
|
||||
shares_micros INTEGER NOT NULL CHECK(shares_micros>0),
|
||||
cash_delta_micros INTEGER NOT NULL,
|
||||
at_ms INTEGER NOT NULL DEFAULT(CAST(unixepoch('subsec')*1000 AS INTEGER)),
|
||||
CHECK((kind='REDEEM')=(outcome IS NOT NULL))
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS combo_movements_by_account ON combo_movements(account,at_ms,seq);
|
||||
COMMIT;
|
||||
@@ -36,6 +36,16 @@ pub(crate) enum Command {
|
||||
listing: Option<crate::catalog::Listing>,
|
||||
resolution: Option<crate::resolution::Policy>,
|
||||
},
|
||||
#[serde(rename = "prepare_combo")]
|
||||
PrepareCombo {
|
||||
legs: Vec<crate::combo::Leg>,
|
||||
},
|
||||
#[serde(rename = "split_combo")]
|
||||
SplitCombo(crate::combo::Amount),
|
||||
#[serde(rename = "merge_combo")]
|
||||
MergeCombo(crate::combo::Amount),
|
||||
#[serde(rename = "redeem_combo")]
|
||||
RedeemCombo(crate::combo::Redemption),
|
||||
#[serde(rename = "define_neg_risk")]
|
||||
DefineNegRisk {
|
||||
group: String,
|
||||
|
||||
@@ -4,6 +4,7 @@ mod activity;
|
||||
mod assets;
|
||||
mod augmented;
|
||||
mod catalog;
|
||||
mod combo;
|
||||
mod depth_feed;
|
||||
mod estimate;
|
||||
mod expiry;
|
||||
@@ -127,6 +128,13 @@ impl Exchange {
|
||||
if !history_ready {
|
||||
db.execute_batch(include_str!("prices_history/chart_schema.sql"))?;
|
||||
}
|
||||
let combo_ready: bool = db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='table' AND name='combo_movements')",
|
||||
[], |r| r.get(0),
|
||||
)?;
|
||||
if !combo_ready {
|
||||
db.execute_batch(include_str!("combo_schema.sql"))?;
|
||||
}
|
||||
let marks_ready: bool = db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='table' AND name='last_asset_trades')",
|
||||
[], |row| row.get(0),
|
||||
@@ -226,6 +234,7 @@ impl Exchange {
|
||||
| "market_amounts"
|
||||
| "tick_history"
|
||||
| "catalog"
|
||||
| "combo"
|
||||
| "events"
|
||||
| "history"
|
||||
| "prices_history"
|
||||
|
||||
@@ -114,6 +114,10 @@ pub(crate) fn apply(
|
||||
)?;
|
||||
Ok(json!({"phase":"preopen"}))
|
||||
}
|
||||
Command::PrepareCombo { legs } => crate::combo::prepare(tx, legs),
|
||||
Command::SplitCombo(amount) => amount.apply(tx, request_id, true),
|
||||
Command::MergeCombo(amount) => amount.apply(tx, request_id, false),
|
||||
Command::RedeemCombo(redemption) => redemption.apply(tx, request_id),
|
||||
Command::DefineNegRisk {
|
||||
group,
|
||||
event,
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
use exchange::Exchange;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
#[test]
|
||||
fn combo_replays_canonical_definition_and_keeps_rounding_dust() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("combo.sqlite");
|
||||
let mut db = Exchange::open(&path).unwrap();
|
||||
let commands = include_str!("../../../docs/examples/combo-ledger.jsonl")
|
||||
.lines()
|
||||
.map(|line| serde_json::from_str::<Value>(line).unwrap())
|
||||
.collect::<Vec<_>>();
|
||||
for command in &commands[..3] {
|
||||
db.execute(command.clone()).unwrap();
|
||||
}
|
||||
let definition = db.execute(commands[3].clone()).unwrap();
|
||||
let combo = definition["combo"].as_str().unwrap();
|
||||
assert_eq!(commands[4]["combo"], combo);
|
||||
assert_eq!(definition["legs"][0]["market"], "combo-a");
|
||||
let same = db
|
||||
.execute(json!({
|
||||
"op":"prepare_combo","id":"reordered","legs":[{"market":"combo-a","outcome":"YES"},
|
||||
{"market":"combo-b","outcome":"NO"}]
|
||||
}))
|
||||
.unwrap();
|
||||
assert_eq!(same, definition);
|
||||
assert!(db
|
||||
.execute(json!({
|
||||
"op":"prepare_combo","id":"contradiction","legs":[{"market":"combo-a","outcome":"YES"},
|
||||
{"market":"combo-a","outcome":"NO"}]
|
||||
}))
|
||||
.is_err());
|
||||
let split = db.execute(commands[4].clone()).unwrap();
|
||||
let view = json!({"op":"combo","combo":combo,"account":"alice"});
|
||||
assert!(!db.execute(view.clone()).unwrap()["redeemable"]
|
||||
.as_bool()
|
||||
.unwrap());
|
||||
assert!(db.execute(commands[10].clone()).is_err());
|
||||
|
||||
drop(db);
|
||||
let mut db = Exchange::open(&path).unwrap();
|
||||
assert_eq!(db.execute(commands[4].clone()).unwrap(), split);
|
||||
assert_eq!(
|
||||
db.execute(view.clone()).unwrap()["balances_micros"],
|
||||
json!([1000003, 1000003])
|
||||
);
|
||||
for command in &commands[5..10] {
|
||||
db.execute(command.clone()).unwrap();
|
||||
}
|
||||
let settled = db.execute(view.clone()).unwrap();
|
||||
assert_eq!(settled["payout_micros_per_share"], json!([250000, 750000]));
|
||||
assert_eq!(
|
||||
db.execute(commands[10].clone()).unwrap()["paid_micros"],
|
||||
250000
|
||||
);
|
||||
assert_eq!(
|
||||
db.execute(commands[11].clone()).unwrap()["paid_micros"],
|
||||
750000
|
||||
);
|
||||
let final_state = db.execute(view).unwrap();
|
||||
assert_eq!(final_state["balances_micros"], json!([0, 0]));
|
||||
assert_eq!(final_state["collateral_micros"], 0);
|
||||
assert_eq!(final_state["rounding_dust_micros"], 1);
|
||||
assert_eq!(
|
||||
db.execute(json!({"op":"balance","account":"alice"}))
|
||||
.unwrap()["available_micros"],
|
||||
9999999
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_leg_allows_early_redemption_even_after_an_unresolved_leg() {
|
||||
let mut db = Exchange::open(":memory:").unwrap();
|
||||
for command in [
|
||||
json!({"op":"fund","id":"fund","account":"alice","cents":200}),
|
||||
json!({"op":"list","id":"a","market":"a-pending","rules":"pending"}),
|
||||
json!({"op":"list","id":"b","market":"b-loss","rules":"settle early"}),
|
||||
] {
|
||||
db.execute(command).unwrap();
|
||||
}
|
||||
let prepared = db
|
||||
.execute(json!({
|
||||
"op":"prepare_combo","id":"combo","legs":[{"market":"a-pending","outcome":"YES"},
|
||||
{"market":"b-loss","outcome":"NO"}]
|
||||
}))
|
||||
.unwrap();
|
||||
let combo = prepared["combo"].as_str().unwrap();
|
||||
for command in [
|
||||
json!({"op":"split_combo","id":"split","combo":combo,"account":"alice","qty":2}),
|
||||
json!({"op":"close","id":"close","market":"b-loss"}),
|
||||
json!({"op":"finalize","id":"final","market":"b-loss","winner":"YES"}),
|
||||
] {
|
||||
db.execute(command).unwrap();
|
||||
}
|
||||
let view = json!({"op":"combo","combo":combo,"account":"alice"});
|
||||
let settled = db.execute(view.clone()).unwrap();
|
||||
assert!(settled["legs"][0]["payout_micros_per_share"].is_null());
|
||||
assert_eq!(settled["payout_micros_per_share"], json!([0, 1000000]));
|
||||
let yes=db.execute(json!({"op":"redeem_combo","id":"yes","combo":combo,"account":"alice","qty":2,"outcome":"YES"})).unwrap();
|
||||
let no=db.execute(json!({"op":"redeem_combo","id":"no","combo":combo,"account":"alice","qty":2,"outcome":"NO"})).unwrap();
|
||||
assert_eq!(yes["paid_micros"], 0);
|
||||
assert_eq!(no["paid_micros"], 2000000);
|
||||
assert_eq!(db.execute(view).unwrap()["rounding_dust_micros"], 0);
|
||||
}
|
||||
@@ -8,11 +8,6 @@ cargo run --locked -p venue-probe
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
main -->|核对 CTF 权重| ctf["src/ctf_resolution.rs"]
|
||||
main -->|核对 V2 模块权重| position["src/position_resolution.rs"]
|
||||
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
|
||||
@@ -128,55 +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)
|
||||
|
||||
## 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)
|
||||
|
||||
@@ -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,26 +0,0 @@
|
||||
[
|
||||
{
|
||||
"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
|
||||
}
|
||||
]
|
||||
@@ -1,221 +0,0 @@
|
||||
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,9 +1,6 @@
|
||||
mod book_audit;
|
||||
mod books;
|
||||
mod catalog;
|
||||
mod ctf_resolution;
|
||||
mod polygon_rpc;
|
||||
mod position_resolution;
|
||||
mod price_check;
|
||||
mod probes;
|
||||
use anyhow::{ensure, Result};
|
||||
@@ -36,45 +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] | --inspect-position-resolution MARKET_JSON [EXPECTED] | --replay-position-resolution FILE [EXPECTED]]";
|
||||
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 = 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()?;
|
||||
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(());
|
||||
}
|
||||
}
|
||||
|
||||
"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)?)?;
|
||||
|
||||
@@ -1,137 +0,0 @@
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use reqwest::{blocking::Client, Url};
|
||||
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)
|
||||
}
|
||||
|
||||
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}"))
|
||||
}
|
||||
|
||||
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 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()?)
|
||||
}
|
||||
}
|
||||
@@ -1,274 +0,0 @@
|
||||
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};
|
||||
|
||||
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))
|
||||
}
|
||||
|
||||
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",
|
||||
_ => anyhow::bail!("unsupported PositionManager module"),
|
||||
};
|
||||
ensure!(
|
||||
expected.eq_ignore_ascii_case(&address),
|
||||
"PositionManager registry differs from the published deployment"
|
||||
);
|
||||
Ok(address)
|
||||
}
|
||||
|
||||
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 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 = block.call(POSITION_MANAGER, &format!("0x{MODULE_BY_ID}{module:064x}"))?;
|
||||
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,13 @@
|
||||
{"op":"fund","id":"combo-fund","account":"alice","micros":10000000}
|
||||
{"op":"list","id":"combo-list-a","market":"combo-a","rules":"按模拟赛果 A 裁决。"}
|
||||
{"op":"list","id":"combo-list-b","market":"combo-b","rules":"按模拟赛果 B 裁决。"}
|
||||
{"op":"prepare_combo","id":"combo-prepare","legs":[{"market":"combo-b","outcome":"NO"},{"market":"combo-a","outcome":"YES"}]}
|
||||
{"op":"split_combo","id":"combo-split","combo":"combo:1131b7195fad3ca3c7ae8ebe3739ac78a765c241aa74fccf91236b6caa08cb1e","account":"alice","qty_micros":1000003}
|
||||
{"op":"merge_combo","id":"combo-merge","combo":"combo:1131b7195fad3ca3c7ae8ebe3739ac78a765c241aa74fccf91236b6caa08cb1e","account":"alice","qty_micros":2}
|
||||
{"op":"close","id":"combo-close-a","market":"combo-a"}
|
||||
{"op":"finalize","id":"combo-final-a","market":"combo-a","winner":"VOID"}
|
||||
{"op":"close","id":"combo-close-b","market":"combo-b"}
|
||||
{"op":"finalize","id":"combo-final-b","market":"combo-b","winner":"VOID"}
|
||||
{"op":"redeem_combo","id":"combo-redeem-yes","combo":"combo:1131b7195fad3ca3c7ae8ebe3739ac78a765c241aa74fccf91236b6caa08cb1e","account":"alice","outcome":"YES","qty_micros":1000001}
|
||||
{"op":"redeem_combo","id":"combo-redeem-no","combo":"combo:1131b7195fad3ca3c7ae8ebe3739ac78a765c241aa74fccf91236b6caa08cb1e","account":"alice","outcome":"NO","qty_micros":1000001}
|
||||
{"op":"combo","combo":"combo:1131b7195fad3ca3c7ae8ebe3739ac78a765c241aa74fccf91236b6caa08cb1e","account":"alice"}
|
||||
@@ -417,14 +417,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 条件,真实预言机证明及链上同步入账仍待覆盖。[生产目录记录](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)
|
||||
|
||||
### Data API 账户持仓价值
|
||||
|
||||
官方 `GET /v2/value` 要求传 user,可选最多 20 个不同 condition。结果是 data 对象,内含 proxy_wallet 和四位小数精度的美元金额。一个无持仓的钱包值为零。官方总额还包括未终结组合的成本基础,指定 condition 时仅统计选中的单盘。资金余额不计入持仓价值。[官方 OpenAPI](https://data-api.polymarket.com/v2/openapi.json)
|
||||
@@ -463,6 +455,14 @@ SDK 使用 `GET /neg-risk?token_id=…`,也可以从已缓存的 CLOB 市场
|
||||
|
||||
在同一数据库先重放[费用样例](examples/neg-risk-fee.jsonl),再重放[裁决后转换样例](examples/neg-risk-after-verdict.jsonl)。甲先判 NO,新增转换把准备金增至 500002 微美元。「其他」判 YES 后,用户和金库分别领取 493752 和 6250 微美元;赢家抵押归零。乙也判 NO 后,用户交回剩余的甲 NO 和乙 NO,各 250001 微份。转换当场向「其他」补入 250001 微美元抵押,用户和金库可再领取 246876 和 3125。每次领取使用独立的请求 ID。另一种情形中,如果输入包含赢家自己的 NO,这些份额的兑付价值已经为零,现存赢家 YES 的抵押须全额保留。
|
||||
|
||||
### 组合定义、抵押与兑付
|
||||
|
||||
官方 CombinatorialModule 以规范腿集合标识组合。重复腿、同一条件的相反结果和非二元腿受到限制。组合 YES 的兑付乘各腿权重,NO 用其补数。若已有零兑付腿,未裁决的其他腿不会阻止兑付。合约保留 36 位累积精度,YES 用向下系数,NO 用向上系数的补数,每次实际兑付按抵押币最小单位向下取整。[组合合约](https://github.com/Polymarket/polymarket-v2-external/blob/main/src/modules/CombinatorialModule.sol) · [官方日终估值规则](https://docs.polymarket.com/api-reference/wallet/snapshot-a-wallets-positions-at-the-end-of-a-day)
|
||||
|
||||
本地接受 2 至 50 条已经上架的二元腿。按市场 ID 排序后生成独立的本地组合 ID,两侧份额使用其各自的本地标识。拆分、合并和兑付与抵押账本及请求回执同事务写入,不改动底层市场的份额。组合账本在最后一笔份额烧毁后登记无法兑付的尾差。重放[组合样例](examples/combo-ledger.jsonl),分别选择 A 的 YES 和 B 的 NO。拆分 1000003 微份后合并 2 微份。两条腿都作废时,YES 每份为 0.25,NO 每份为 0.75,实际分别兑付 250000 与 750000 微美元,最后记录 1 微美元尾差。
|
||||
|
||||
本轮公开组合候选目录返回 HTTP 403。生产 RFQ 资格、报价和成交,链上标识以及组合持仓对账仍待接入和验证。[公开候选目录规范](https://docs.polymarket.com/api-reference/combo-markets/get-combo-markets)
|
||||
|
||||
### 互斥适配器按量赎回
|
||||
|
||||
当前 SDK 的 `redeem_positions(condition_id)` 选择该市场的协议路径,领取持有人两侧的余额。另一个公开入口是 NegRiskAdapter 的 `redeemPositions(conditionId, amounts)`,先将调用人指定的 YES 和 NO 转入适配器,再执行底层兑付。即使兑付额为零,适配器仍发出带有输入数量和兑付额的事件。以下样例验证该适配器的数量语义;生产协议版本、批量交易及链上回执尚待比对。[官方持仓接口](https://docs.polymarket.com/trading/positions/manage) · [适配器源码](https://github.com/Polymarket/neg-risk-ctf-adapter/blob/main/src/NegRiskAdapter.sol#L191-L207)
|
||||
|
||||
Reference in New Issue
Block a user