Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6dcc88b4f0 | ||
|
|
2e95c5a631 |
No files matched your search
@@ -247,6 +247,40 @@ 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: 账户两侧的微份额及当前兑付状态
|
||||
```
|
||||
|
||||
### 组合询价
|
||||
|
||||
重放[组合询价样例](../../docs/examples/combo-rfq.jsonl)。样例先用双方现金生成互补的组合份额,再用已有份额合并并卖出。报价方通过 `combo_rfq_open` 发现尚未结束的询价。请求方用 `combo_rfq` 查看报价,再接受指定报价。报价与接受命令使用各自的请求 ID,账户余额查询会列出已受理询价的现金预留。
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
actor T as 请求方
|
||||
participant J as JSONL 命令入口
|
||||
actor M as 报价方
|
||||
T->>J: request_combo_quote
|
||||
M->>J: combo_rfq_open 与 quote_combo
|
||||
T->>J: accept_combo_quote,指定报价 ID
|
||||
J-->>T: 确认期限与预留状态
|
||||
M->>J: respond_combo_quote,提交最后确认
|
||||
T->>J: combo_rfq,读取成交或失败状态
|
||||
```
|
||||
|
||||
### 从事件页进入订单簿
|
||||
|
||||
```mermaid
|
||||
|
||||
@@ -29,6 +29,15 @@ 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
|
||||
market -->|处理组合询价和最后确认| combo_rfq["src/combo_rfq.rs"]
|
||||
combo_rfq -->|预留与转移份额| combo
|
||||
combo_rfq -->|读写询价和成交| combo_rfq_sql["src/combo_rfq_schema.sql"]
|
||||
expiry["src/expiry.rs"] -->|独立提交到期退款| combo_rfq
|
||||
api -->|接收轮换心跳 ID| beat["src/heartbeat.rs"]
|
||||
book -->|记录订单所属 key| beat
|
||||
expiry -->|清理到期注册| beat
|
||||
@@ -400,6 +409,51 @@ 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
|
||||
```
|
||||
|
||||
## 组合 RFQ 的预留与成交
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
actor T as 请求方
|
||||
participant E as exchange / SQLite
|
||||
actor M as 报价方
|
||||
T->>E: request_combo_quote,选择方向、结果和数量
|
||||
M->>E: combo_rfq_open,再提交 quote_combo
|
||||
T->>E: accept_combo_quote
|
||||
E->>E: 原子预留双方现金或份额
|
||||
alt 报价方在期限内确认且腿仍可交易
|
||||
M->>E: respond_combo_quote,确认
|
||||
E->>E: 转让、拆分或合并,提交唯一成交
|
||||
E-->>T: FILLED
|
||||
else 拒绝、腿关闭或期限届满
|
||||
E->>E: 释放预留,保留终态
|
||||
E-->>T: FAILED 或 EXPIRED
|
||||
end
|
||||
```
|
||||
|
||||
## 开盘后出现新候选人
|
||||
|
||||
`command.rs` 和 `market.rs` 把增强型组合的定义、命名和裁决交给 `augmented.rs`。成员编号和转换沿用 `neg_risk.rs`;`schema.sql` 拦截未命名盘口的直接订单。`catalog.rs`、`assets.rs` 和 `portfolio.rs` 从同一条命名记录生成展示字段。
|
||||
|
||||
@@ -294,6 +294,17 @@ pub(crate) enum Query {
|
||||
event: Option<String>,
|
||||
slug: Option<String>,
|
||||
},
|
||||
ComboRfq {
|
||||
rfq: String,
|
||||
account: String,
|
||||
},
|
||||
ComboRfqOpen {
|
||||
limit: Option<u32>,
|
||||
},
|
||||
Combo {
|
||||
combo: String,
|
||||
account: Option<String>,
|
||||
},
|
||||
History {
|
||||
market: String,
|
||||
outcome: String,
|
||||
@@ -313,6 +324,9 @@ impl Query {
|
||||
.response(),
|
||||
)
|
||||
}
|
||||
Self::ComboRfq { rfq, account } => crate::combo_rfq::read(db, &rfq, &account),
|
||||
Self::ComboRfqOpen { limit } => crate::combo_rfq::open_requests(db, limit),
|
||||
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,349 @@
|
||||
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 {
|
||||
pub(super) fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Yes => "YES",
|
||||
Self::No => "NO",
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn opposite(self) -> Self {
|
||||
match self {
|
||||
Self::Yes => Self::No,
|
||||
Self::No => Self::Yes,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[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);
|
||||
let available = [
|
||||
balance(db, combo, account, Side::Yes)?,
|
||||
balance(db, combo, account, Side::No)?,
|
||||
];
|
||||
let (yes, no): (i64,i64) = db.query_row(
|
||||
"SELECT COALESCE(SUM(h.shares_micros) FILTER (WHERE h.outcome='YES'),0),
|
||||
COALESCE(SUM(h.shares_micros) FILTER (WHERE h.outcome='NO'),0)
|
||||
FROM combo_rfq_holds h JOIN combo_rfqs r ON r.id=h.rfq WHERE r.combo=? AND h.account=?",
|
||||
params![combo,account], |r| Ok((r.get(0)?,r.get(1)?)),
|
||||
)?;
|
||||
detail["balances_micros"] = json!([
|
||||
available[0]
|
||||
.checked_add(yes)
|
||||
.context("combo balance overflow")?,
|
||||
available[1]
|
||||
.checked_add(no)
|
||||
.context("combo balance overflow")?,
|
||||
]);
|
||||
if yes > 0 || no > 0 {
|
||||
detail["available_micros"] = json!(available);
|
||||
detail["reserved_micros"] = json!([yes, no]);
|
||||
}
|
||||
}
|
||||
Ok(detail)
|
||||
}
|
||||
|
||||
fn position_id(combo: &str, side: Side) -> String {
|
||||
format!(
|
||||
"ebc:{}:{}",
|
||||
side.name(),
|
||||
combo.strip_prefix("combo:").unwrap_or(combo)
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) 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))
|
||||
}
|
||||
|
||||
pub(super) 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(())
|
||||
}
|
||||
|
||||
pub(super) 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=?1)
|
||||
OR EXISTS(SELECT 1 FROM combo_rfq_holds h JOIN combo_rfqs r ON r.id=h.rfq
|
||||
WHERE r.combo=?1 AND h.outcome IS NOT NULL)",
|
||||
[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,565 @@
|
||||
use crate::{
|
||||
combo::{self, Side},
|
||||
inventory::UNIT,
|
||||
ledger,
|
||||
validation::identifier,
|
||||
};
|
||||
use anyhow::{ensure, Result};
|
||||
use rusqlite::{params, Connection, OptionalExtension, Row, Transaction};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
const REQUESTER: &str = "AWAITING_REQUESTER_ACCEPTANCE";
|
||||
const MAKER: &str = "AWAITING_MAKER_CONFIRMATION";
|
||||
const MAX_MICROS: i64 = 1_000_000_000 * UNIT;
|
||||
const DB_NOW: &str = "SELECT CAST(unixepoch('subsec')*1000 AS INTEGER)";
|
||||
|
||||
#[derive(Clone, Copy, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "UPPERCASE")]
|
||||
enum Direction {
|
||||
Buy,
|
||||
Sell,
|
||||
}
|
||||
|
||||
impl Direction {
|
||||
fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Buy => "BUY",
|
||||
Self::Sell => "SELL",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
enum Source {
|
||||
Collateral,
|
||||
Inventory,
|
||||
}
|
||||
|
||||
impl Source {
|
||||
fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Collateral => "collateral",
|
||||
Self::Inventory => "inventory",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct Request {
|
||||
combo: String,
|
||||
requester: String,
|
||||
direction: Direction,
|
||||
side: Side,
|
||||
shares_micros: Option<i64>,
|
||||
notional_micros: Option<i64>,
|
||||
submission_window_ms: Option<i64>,
|
||||
acceptance_window_ms: Option<i64>,
|
||||
last_look_ms: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct Quote {
|
||||
rfq: String,
|
||||
maker: String,
|
||||
price_micros: i64,
|
||||
shares_micros: i64,
|
||||
source: Source,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct Accept {
|
||||
rfq: String,
|
||||
requester: String,
|
||||
quote: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct Respond {
|
||||
rfq: String,
|
||||
quote: String,
|
||||
maker: String,
|
||||
confirm: bool,
|
||||
}
|
||||
|
||||
struct Rfq {
|
||||
combo: String,
|
||||
requester: String,
|
||||
direction: Direction,
|
||||
side: Side,
|
||||
size_unit: String,
|
||||
requested: i64,
|
||||
submission_deadline: i64,
|
||||
expires_at: i64,
|
||||
last_look_ms: i64,
|
||||
status: String,
|
||||
selected_quote: Option<String>,
|
||||
confirm_by: Option<i64>,
|
||||
failure: Option<String>,
|
||||
}
|
||||
|
||||
struct QuoteRow {
|
||||
id: String,
|
||||
maker: String,
|
||||
price: i64,
|
||||
shares: i64,
|
||||
cash: i64,
|
||||
source: Source,
|
||||
canceled: bool,
|
||||
}
|
||||
|
||||
fn now(db: &Connection) -> rusqlite::Result<i64> {
|
||||
db.query_row(DB_NOW, [], |r| r.get(0))
|
||||
}
|
||||
|
||||
fn window(value: Option<i64>, default: i64) -> Result<i64> {
|
||||
let ms = value.unwrap_or(default);
|
||||
ensure!((1..=300_000).contains(&ms), "invalid RFQ window");
|
||||
Ok(ms)
|
||||
}
|
||||
|
||||
fn tradable(db: &Connection, combo: &str) -> rusqlite::Result<bool> {
|
||||
db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM combo_rfq_tradable WHERE id=?)",
|
||||
[combo],
|
||||
|r| r.get(0),
|
||||
)
|
||||
}
|
||||
|
||||
fn stored_side(side: &str) -> Side {
|
||||
if side == "YES" {
|
||||
Side::Yes
|
||||
} else {
|
||||
Side::No
|
||||
}
|
||||
}
|
||||
|
||||
fn request(db: &Connection, id: &str) -> rusqlite::Result<Rfq> {
|
||||
db.query_row(
|
||||
"SELECT combo,requester,direction,outcome,size_unit,requested_micros,submission_deadline,
|
||||
expires_at,last_look_ms,status,selected_quote,confirm_by,failure
|
||||
FROM combo_rfqs WHERE id=?",
|
||||
[id],
|
||||
|r| {
|
||||
Ok(Rfq {
|
||||
combo: r.get(0)?,
|
||||
requester: r.get(1)?,
|
||||
direction: if r.get::<_, String>(2)? == "BUY" {
|
||||
Direction::Buy
|
||||
} else {
|
||||
Direction::Sell
|
||||
},
|
||||
side: stored_side(&r.get::<_, String>(3)?),
|
||||
size_unit: r.get(4)?,
|
||||
requested: r.get(5)?,
|
||||
submission_deadline: r.get(6)?,
|
||||
expires_at: r.get(7)?,
|
||||
last_look_ms: r.get(8)?,
|
||||
status: r.get(9)?,
|
||||
selected_quote: r.get(10)?,
|
||||
confirm_by: r.get(11)?,
|
||||
failure: r.get(12)?,
|
||||
})
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
const QUOTE_COLUMNS: &str =
|
||||
"SELECT id,maker,price_micros,shares_micros,cash_micros,source,canceled FROM combo_rfq_quotes";
|
||||
|
||||
fn quote_row(r: &Row<'_>) -> rusqlite::Result<QuoteRow> {
|
||||
Ok(QuoteRow {
|
||||
id: r.get(0)?,
|
||||
maker: r.get(1)?,
|
||||
price: r.get(2)?,
|
||||
shares: r.get(3)?,
|
||||
cash: r.get(4)?,
|
||||
source: if r.get::<_, String>(5)? == "collateral" {
|
||||
Source::Collateral
|
||||
} else {
|
||||
Source::Inventory
|
||||
},
|
||||
canceled: r.get(6)?,
|
||||
})
|
||||
}
|
||||
|
||||
fn quote(db: &Connection, rfq: &str, id: &str) -> rusqlite::Result<QuoteRow> {
|
||||
db.prepare_cached(&format!("{QUOTE_COLUMNS} WHERE rfq=? AND id=?"))?
|
||||
.query_row(params![rfq, id], quote_row)
|
||||
}
|
||||
|
||||
impl Request {
|
||||
pub(crate) fn apply(self, tx: &Transaction, id: &str) -> Result<Value> {
|
||||
identifier(&self.requester)?;
|
||||
ensure!(
|
||||
tradable(tx, &self.combo)?,
|
||||
"unknown combo or unavailable leg"
|
||||
);
|
||||
let (unit, size) = match (self.shares_micros, self.notional_micros, self.direction) {
|
||||
(Some(q), None, _) => ("shares", q),
|
||||
(None, Some(q), Direction::Buy) => ("notional", q),
|
||||
_ => anyhow::bail!("provide one share size or a BUY notional budget"),
|
||||
};
|
||||
ensure!((1..=MAX_MICROS).contains(&size), "invalid RFQ size");
|
||||
let submitted = now(tx)?;
|
||||
let submission_deadline = submitted + window(self.submission_window_ms, 10_000)?;
|
||||
let expires_at = submission_deadline + window(self.acceptance_window_ms, 20_000)?;
|
||||
let last_look_ms = window(self.last_look_ms, 5_000)?;
|
||||
tx.execute(
|
||||
"INSERT INTO combo_rfqs(id,combo,requester,direction,outcome,size_unit,requested_micros,
|
||||
submission_deadline,expires_at,last_look_ms,status)
|
||||
VALUES(?,?,?,?,?,?,?,?,?,?,'AWAITING_REQUESTER_ACCEPTANCE')",
|
||||
params![id,self.combo,self.requester,self.direction.name(),self.side.name(),unit,size,
|
||||
submission_deadline,expires_at,last_look_ms],
|
||||
)?;
|
||||
read(tx, id, &self.requester)
|
||||
}
|
||||
}
|
||||
|
||||
impl Quote {
|
||||
pub(crate) fn apply(self, tx: &Transaction, id: &str) -> Result<Value> {
|
||||
identifier(&self.maker)?;
|
||||
let rfq = request(tx, &self.rfq)?;
|
||||
ensure!(
|
||||
rfq.status == REQUESTER && now(tx)? < rfq.submission_deadline,
|
||||
"submission window closed"
|
||||
);
|
||||
ensure!(self.maker != rfq.requester, "no self RFQ quotes");
|
||||
ensure!(tradable(tx, &rfq.combo)?, "unavailable combo leg");
|
||||
ensure!(
|
||||
(1..UNIT).contains(&self.price_micros)
|
||||
&& (1..=MAX_MICROS).contains(&self.shares_micros),
|
||||
"invalid quote amounts"
|
||||
);
|
||||
let cash = (i128::from(self.price_micros) * i128::from(self.shares_micros)
|
||||
/ i128::from(UNIT)) as i64;
|
||||
ensure!(
|
||||
cash > 0
|
||||
&& if rfq.size_unit == "notional" {
|
||||
cash <= rfq.requested
|
||||
} else {
|
||||
self.shares_micros <= rfq.requested
|
||||
},
|
||||
"quote exceeds requested size or rounds to zero"
|
||||
);
|
||||
let candidate = QuoteRow {
|
||||
id: id.into(),
|
||||
maker: self.maker,
|
||||
price: self.price_micros,
|
||||
shares: self.shares_micros,
|
||||
cash,
|
||||
source: self.source,
|
||||
canceled: false,
|
||||
};
|
||||
let maker_funding = funding(&rfq, &candidate).1;
|
||||
maker_funding.check(tx, &rfq.combo, &candidate.maker)?;
|
||||
tx.execute(
|
||||
"INSERT INTO combo_rfq_quotes(id,rfq,maker,price_micros,shares_micros,cash_micros,source,seq)
|
||||
SELECT ?1,?2,?3,?4,?5,?6,?7,COALESCE(MAX(seq),0)+1 FROM combo_rfq_quotes WHERE rfq=?2",
|
||||
params![id,self.rfq,candidate.maker,candidate.price,candidate.shares,cash,candidate.source.name()],
|
||||
)?;
|
||||
Ok(
|
||||
json!({"rfq_id":self.rfq,"quote_id":id,"price_micros":candidate.price,
|
||||
"shares_micros":candidate.shares,"cash_micros":cash}),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
enum Funding {
|
||||
Cash(i64),
|
||||
Shares(Side, i64),
|
||||
}
|
||||
|
||||
impl Funding {
|
||||
fn check(&self, tx: &Transaction, combo: &str, account: &str) -> Result<()> {
|
||||
match *self {
|
||||
Self::Cash(amount) => {
|
||||
let (cents, remainder) = tx.query_row(
|
||||
"SELECT a.cash,COALESCE(r.micros,0) FROM accounts a
|
||||
LEFT JOIN cash_remainders r ON r.account=a.id WHERE a.id=?",
|
||||
[account],
|
||||
|r| Ok((r.get::<_, i64>(0)?, r.get::<_, i64>(1)?)),
|
||||
)?;
|
||||
ensure!(
|
||||
i128::from(cents) * 10000 + i128::from(remainder) >= i128::from(amount),
|
||||
"insufficient RFQ cash"
|
||||
);
|
||||
}
|
||||
Self::Shares(side, amount) => {
|
||||
ensure!(
|
||||
combo::balance(tx, combo, account, side)? >= amount,
|
||||
"insufficient RFQ shares"
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn reserve(self, tx: &Transaction, id: &str, combo: &str, account: &str) -> Result<()> {
|
||||
match self {
|
||||
Self::Cash(amount) => {
|
||||
ledger::cash_micros(tx, account, -amount)?;
|
||||
tx.execute(
|
||||
"INSERT INTO combo_rfq_holds(rfq,account,cash_micros) VALUES(?,?,?)",
|
||||
params![id, account, amount],
|
||||
)?;
|
||||
}
|
||||
Self::Shares(side, amount) => {
|
||||
combo::change_balance(tx, combo, account, side, -amount)?;
|
||||
tx.execute("INSERT INTO combo_rfq_holds(rfq,account,outcome,shares_micros) VALUES(?,?,?,?)",
|
||||
params![id,account,side.name(),amount])?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn funding(rfq: &Rfq, q: &QuoteRow) -> (Funding, Funding) {
|
||||
use Funding::{Cash, Shares};
|
||||
match (rfq.direction, q.source) {
|
||||
(Direction::Buy, Source::Collateral) => (Cash(q.cash), Cash(q.shares - q.cash)),
|
||||
(Direction::Buy, Source::Inventory) => (Cash(q.cash), Shares(rfq.side, q.shares)),
|
||||
(Direction::Sell, Source::Collateral) => (Shares(rfq.side, q.shares), Cash(q.cash)),
|
||||
(Direction::Sell, Source::Inventory) => (
|
||||
Shares(rfq.side, q.shares),
|
||||
Shares(rfq.side.opposite(), q.shares),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
impl Accept {
|
||||
pub(crate) fn apply(self, tx: &Transaction) -> Result<Value> {
|
||||
let rfq = request(tx, &self.rfq)?;
|
||||
ensure!(self.requester == rfq.requester, "RFQ requester mismatch");
|
||||
let now = now(tx)?;
|
||||
ensure!(
|
||||
rfq.status == REQUESTER && now < rfq.expires_at,
|
||||
"RFQ acceptance window closed"
|
||||
);
|
||||
ensure!(tradable(tx, &rfq.combo)?, "unavailable combo leg");
|
||||
let quote = quote(tx, &self.rfq, &self.quote)?;
|
||||
ensure!(!quote.canceled, "quote unavailable");
|
||||
let (requester, maker) = funding(&rfq, "e);
|
||||
requester.reserve(tx, &self.rfq, &rfq.combo, &rfq.requester)?;
|
||||
maker.reserve(tx, &self.rfq, &rfq.combo, "e.maker)?;
|
||||
tx.execute("UPDATE combo_rfqs SET status='AWAITING_MAKER_CONFIRMATION',selected_quote=?,confirm_by=? WHERE id=?",
|
||||
params![self.quote,now+rfq.last_look_ms,self.rfq])?;
|
||||
read(tx, &self.rfq, &self.requester)
|
||||
}
|
||||
}
|
||||
|
||||
fn refund(tx: &Transaction, id: &str, combo: &str) -> Result<()> {
|
||||
let mut stmt = tx.prepare_cached(
|
||||
"SELECT account,outcome,shares_micros,cash_micros FROM combo_rfq_holds WHERE rfq=?",
|
||||
)?;
|
||||
let mut rows = stmt.query([id])?;
|
||||
while let Some(r) = rows.next()? {
|
||||
let account = r.get::<_, String>(0)?;
|
||||
if let Some(side) = r.get::<_, Option<String>>(1)? {
|
||||
combo::change_balance(tx, combo, &account, stored_side(&side), r.get(2)?)?;
|
||||
} else {
|
||||
ledger::cash_micros(tx, &account, r.get(3)?)?;
|
||||
}
|
||||
}
|
||||
tx.execute("DELETE FROM combo_rfq_holds WHERE rfq=?", [id])?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl Respond {
|
||||
pub(crate) fn apply(self, tx: &Transaction, request_id: &str) -> Result<Value> {
|
||||
let rfq = request(tx, &self.rfq)?;
|
||||
let quote = quote(tx, &self.rfq, &self.quote)?;
|
||||
ensure!(quote.maker == self.maker, "RFQ maker mismatch");
|
||||
let clock = now(tx)?;
|
||||
ensure!(
|
||||
rfq.status == MAKER
|
||||
&& rfq.selected_quote.as_deref() == Some(self.quote.as_str())
|
||||
&& rfq.confirm_by.is_some_and(|by| clock < by),
|
||||
"last-look window closed"
|
||||
);
|
||||
if !self.confirm || !tradable(tx, &rfq.combo)? {
|
||||
let reason = if self.confirm {
|
||||
"LEG_UNAVAILABLE"
|
||||
} else {
|
||||
"MAKER_DECLINED"
|
||||
};
|
||||
refund(tx, &self.rfq, &rfq.combo)?;
|
||||
tx.execute(
|
||||
"UPDATE combo_rfqs SET status='FAILED',failure=? WHERE id=?",
|
||||
params![reason, self.rfq],
|
||||
)?;
|
||||
return read(tx, &self.rfq, &self.maker);
|
||||
}
|
||||
let changed = tx.execute("DELETE FROM combo_rfq_holds WHERE rfq=?", [&self.rfq])?;
|
||||
ensure!(changed == 2, "RFQ funding missing");
|
||||
let flow = settle(tx, &rfq, "e)?;
|
||||
tx.execute(
|
||||
"INSERT INTO combo_rfq_trades(rfq,quote,request_id,flow,executed_at) VALUES(?,?,?,?,?)",
|
||||
params![self.rfq, self.quote, request_id, flow, clock],
|
||||
)?;
|
||||
tx.execute(
|
||||
"UPDATE combo_rfqs SET status='FILLED' WHERE id=?",
|
||||
[&self.rfq],
|
||||
)?;
|
||||
read(tx, &self.rfq, &self.maker)
|
||||
}
|
||||
}
|
||||
|
||||
fn settle(tx: &Transaction, r: &Rfq, q: &QuoteRow) -> Result<&'static str> {
|
||||
match (r.direction, q.source) {
|
||||
(Direction::Buy, Source::Collateral) => {
|
||||
combo::change_balance(tx, &r.combo, &r.requester, r.side, q.shares)?;
|
||||
combo::change_balance(tx, &r.combo, &q.maker, r.side.opposite(), q.shares)?;
|
||||
combo::change_backing(tx, &r.combo, q.shares)?;
|
||||
Ok("MINT")
|
||||
}
|
||||
(Direction::Sell, Source::Inventory) => {
|
||||
combo::change_backing(tx, &r.combo, -q.shares)?;
|
||||
ledger::cash_micros(tx, &r.requester, q.cash)?;
|
||||
ledger::cash_micros(tx, &q.maker, q.shares - q.cash)?;
|
||||
Ok("MERGE")
|
||||
}
|
||||
(direction, _) => {
|
||||
let (buyer, seller) = match direction {
|
||||
Direction::Buy => (&r.requester, &q.maker),
|
||||
Direction::Sell => (&q.maker, &r.requester),
|
||||
};
|
||||
combo::change_balance(tx, &r.combo, buyer, r.side, q.shares)?;
|
||||
ledger::cash_micros(tx, seller, q.cash)?;
|
||||
Ok("TRANSFER")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn cancel_quote(
|
||||
tx: &Transaction,
|
||||
id: &str,
|
||||
quote_id: &str,
|
||||
maker: &str,
|
||||
) -> Result<Value> {
|
||||
let q = quote(tx, id, quote_id)?;
|
||||
ensure!(
|
||||
!q.canceled && q.maker == maker && request(tx, id)?.status == REQUESTER,
|
||||
"quote cannot be canceled"
|
||||
);
|
||||
tx.execute(
|
||||
"UPDATE combo_rfq_quotes SET canceled=1 WHERE id=?",
|
||||
[quote_id],
|
||||
)?;
|
||||
Ok(json!({"rfq_id":id,"quote_id":quote_id,"canceled":true}))
|
||||
}
|
||||
|
||||
pub(crate) fn cancel_request(tx: &Transaction, id: &str, owner: &str) -> Result<Value> {
|
||||
let r = request(tx, id)?;
|
||||
ensure!(
|
||||
r.requester == owner && r.status == REQUESTER,
|
||||
"RFQ cannot be canceled"
|
||||
);
|
||||
tx.execute("UPDATE combo_rfqs SET status='CANCELED' WHERE id=?", [id])?;
|
||||
read(tx, id, owner)
|
||||
}
|
||||
|
||||
pub(crate) fn expire(tx: &Transaction) -> Result<()> {
|
||||
let due = {
|
||||
let mut stmt = tx.prepare_cached(include_str!("combo_rfq_due.sql"))?;
|
||||
let rows = stmt.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?;
|
||||
rows.collect::<rusqlite::Result<Vec<_>>>()?
|
||||
};
|
||||
for (id, combo) in due {
|
||||
refund(tx, &id, &combo)?;
|
||||
tx.execute(
|
||||
"UPDATE combo_rfqs SET status='EXPIRED',failure='DEADLINE_ELAPSED' WHERE id=?",
|
||||
[id],
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn open_requests(db: &Connection, limit: Option<u32>) -> Result<Value> {
|
||||
let limit = limit.unwrap_or(50);
|
||||
ensure!((1..=100).contains(&limit), "invalid RFQ listing limit");
|
||||
let mut stmt=db.prepare_cached(
|
||||
"SELECT r.id,r.combo,r.direction,r.outcome,r.size_unit,r.requested_micros,r.submission_deadline,
|
||||
c.canonical_legs
|
||||
FROM combo_rfqs r JOIN combo_rfq_tradable c ON c.id=r.combo
|
||||
WHERE r.status='AWAITING_REQUESTER_ACCEPTANCE'
|
||||
AND r.submission_deadline>CAST(unixepoch('subsec')*1000 AS INTEGER)
|
||||
ORDER BY r.submission_deadline,r.id LIMIT ?",
|
||||
)?;
|
||||
let mut result = Vec::new();
|
||||
let mut rows = stmt.query([limit])?;
|
||||
while let Some(r) = rows.next()? {
|
||||
let legs: Value = serde_json::from_str(&r.get::<_, String>(7)?)?;
|
||||
result.push(json!({
|
||||
"rfq_id":r.get::<_,String>(0)?,"combo":r.get::<_,String>(1)?,
|
||||
"direction":r.get::<_,String>(2)?,"side":r.get::<_,String>(3)?,
|
||||
"requested_size":{"unit":r.get::<_,String>(4)?,"value_micros":r.get::<_,i64>(5)?},
|
||||
"submission_deadline":r.get::<_,i64>(6)?,"legs":legs
|
||||
}));
|
||||
}
|
||||
Ok(json!({"rfqs":result}))
|
||||
}
|
||||
|
||||
pub(crate) fn read(db: &Connection, id: &str, viewer: &str) -> Result<Value> {
|
||||
let r = request(db, id)?;
|
||||
let owner = r.requester == viewer;
|
||||
let quoted: bool = db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM combo_rfq_quotes WHERE rfq=? AND maker=?)",
|
||||
params![id, viewer],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
ensure!(owner || quoted, "RFQ not visible to account");
|
||||
let ranks = if matches!(r.direction, Direction::Buy) {
|
||||
"ASC"
|
||||
} else {
|
||||
"DESC"
|
||||
};
|
||||
let mut stmt = db.prepare_cached(&format!(
|
||||
"{QUOTE_COLUMNS} WHERE rfq=?1 AND (?2 OR maker=?3) AND canceled=0
|
||||
ORDER BY price_micros {ranks},shares_micros DESC,seq"
|
||||
))?;
|
||||
let quotes = stmt
|
||||
.query_map(params![id, owner, viewer], quote_row)?
|
||||
.map(|q| {
|
||||
q.map(|q| {
|
||||
json!({"quote_id":q.id,"maker":q.maker,"price_micros":q.price,
|
||||
"shares_micros":q.shares,"cash_micros":q.cash,"source":q.source})
|
||||
})
|
||||
})
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
let selected = r.selected_quote.filter(|id| {
|
||||
owner
|
||||
|| quotes
|
||||
.iter()
|
||||
.any(|q| q["quote_id"].as_str() == Some(id.as_str()))
|
||||
});
|
||||
let fill = if selected.is_some() && r.status == "FILLED" {
|
||||
db.query_row(
|
||||
"SELECT t.executed_at,t.flow,q.price_micros,q.shares_micros,q.cash_micros
|
||||
FROM combo_rfq_trades t JOIN combo_rfq_quotes q ON q.id=t.quote WHERE t.rfq=?",
|
||||
[id],
|
||||
|r| {
|
||||
Ok(
|
||||
json!({"executed_at":r.get::<_,i64>(0)?,"flow":r.get::<_,String>(1)?,
|
||||
"price_micros":r.get::<_,i64>(2)?,"shares_micros":r.get::<_,i64>(3)?,
|
||||
"cash_micros":r.get::<_,i64>(4)?}),
|
||||
)
|
||||
},
|
||||
)
|
||||
.optional()?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok(json!({
|
||||
"rfq_id":id,"combo":r.combo,"direction":r.direction,"side":r.side,"status":r.status,
|
||||
"requested_size":{"unit":r.size_unit,"value_micros":r.requested},
|
||||
"submission_deadline":r.submission_deadline,"expires_at":r.expires_at,"quotes":quotes,
|
||||
"confirm_by":r.confirm_by.filter(|_|selected.is_some()),"selected_quote":selected,
|
||||
"failure":r.failure,"fill":fill
|
||||
}))
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
SELECT id,combo FROM combo_rfqs
|
||||
WHERE (status='AWAITING_REQUESTER_ACCEPTANCE' AND expires_at<=CAST(unixepoch('subsec')*1000 AS INTEGER))
|
||||
OR (status='AWAITING_MAKER_CONFIRMATION' AND confirm_by<=CAST(unixepoch('subsec')*1000 AS INTEGER))
|
||||
@@ -0,0 +1,65 @@
|
||||
BEGIN IMMEDIATE;
|
||||
CREATE TABLE IF NOT EXISTS combo_rfqs (
|
||||
id TEXT PRIMARY KEY REFERENCES requests(id) DEFERRABLE INITIALLY DEFERRED,
|
||||
combo TEXT NOT NULL REFERENCES combo_conditions(id),
|
||||
requester TEXT NOT NULL REFERENCES accounts(id),
|
||||
direction TEXT NOT NULL CHECK(direction IN ('BUY','SELL')),
|
||||
outcome TEXT NOT NULL CHECK(outcome IN ('YES','NO')),
|
||||
size_unit TEXT NOT NULL CHECK(size_unit IN ('shares','notional')),
|
||||
requested_micros INTEGER NOT NULL CHECK(requested_micros>0),
|
||||
submission_deadline INTEGER NOT NULL,
|
||||
expires_at INTEGER NOT NULL,
|
||||
last_look_ms INTEGER NOT NULL,
|
||||
status TEXT NOT NULL CHECK(status IN (
|
||||
'AWAITING_REQUESTER_ACCEPTANCE','AWAITING_MAKER_CONFIRMATION','FILLED','FAILED','EXPIRED','CANCELED'
|
||||
)),
|
||||
selected_quote TEXT,
|
||||
confirm_by INTEGER,
|
||||
failure TEXT,
|
||||
FOREIGN KEY(id,selected_quote) REFERENCES combo_rfq_quotes(rfq,id)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS combo_rfq_open_deadline ON combo_rfqs(expires_at)
|
||||
WHERE status='AWAITING_REQUESTER_ACCEPTANCE';
|
||||
CREATE INDEX IF NOT EXISTS combo_rfq_last_look ON combo_rfqs(confirm_by)
|
||||
WHERE status='AWAITING_MAKER_CONFIRMATION';
|
||||
CREATE TABLE IF NOT EXISTS combo_rfq_quotes (
|
||||
id TEXT PRIMARY KEY REFERENCES requests(id) DEFERRABLE INITIALLY DEFERRED,
|
||||
rfq TEXT NOT NULL REFERENCES combo_rfqs(id),
|
||||
maker TEXT NOT NULL REFERENCES accounts(id),
|
||||
price_micros INTEGER NOT NULL CHECK(price_micros BETWEEN 1 AND 999999),
|
||||
shares_micros INTEGER NOT NULL CHECK(shares_micros>0),
|
||||
cash_micros INTEGER NOT NULL CHECK(cash_micros>0),
|
||||
source TEXT NOT NULL CHECK(source IN ('collateral','inventory')),
|
||||
canceled INTEGER NOT NULL DEFAULT 0 CHECK(canceled IN (0,1)),
|
||||
seq INTEGER NOT NULL,
|
||||
UNIQUE(rfq,id),
|
||||
UNIQUE(rfq,seq)
|
||||
);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS combo_rfq_live_maker_quote ON combo_rfq_quotes(rfq,maker)
|
||||
WHERE canceled=0;
|
||||
CREATE TABLE IF NOT EXISTS combo_rfq_holds (
|
||||
rfq TEXT NOT NULL REFERENCES combo_rfqs(id),
|
||||
account TEXT NOT NULL REFERENCES accounts(id),
|
||||
outcome TEXT CHECK(outcome IN ('YES','NO')),
|
||||
shares_micros INTEGER NOT NULL DEFAULT 0 CHECK(shares_micros>=0),
|
||||
cash_micros INTEGER NOT NULL DEFAULT 0 CHECK(cash_micros>=0),
|
||||
PRIMARY KEY(rfq,account),
|
||||
CHECK((outcome IS NULL AND shares_micros=0 AND cash_micros>0)
|
||||
OR (outcome IS NOT NULL AND shares_micros>0 AND cash_micros=0))
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS combo_rfq_holds_account ON combo_rfq_holds(account);
|
||||
CREATE INDEX IF NOT EXISTS combo_rfq_by_condition ON combo_rfqs(combo);
|
||||
CREATE TABLE IF NOT EXISTS combo_rfq_trades (
|
||||
rfq TEXT PRIMARY KEY REFERENCES combo_rfqs(id),
|
||||
quote TEXT NOT NULL REFERENCES combo_rfq_quotes(id),
|
||||
request_id TEXT NOT NULL UNIQUE REFERENCES requests(id) DEFERRABLE INITIALLY DEFERRED,
|
||||
flow TEXT NOT NULL CHECK(flow IN ('TRANSFER','MINT','MERGE')),
|
||||
executed_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE VIEW IF NOT EXISTS combo_rfq_tradable AS
|
||||
SELECT c.id,c.canonical_legs FROM combo_conditions c
|
||||
WHERE NOT EXISTS(SELECT 1 FROM combo_legs l JOIN markets m ON m.id=l.market
|
||||
LEFT JOIN market_visibility v ON v.market=m.id
|
||||
WHERE l.combo=c.id AND (m.phase NOT IN ('preopen','continuous')
|
||||
OR COALESCE(v.active,1)=0 OR COALESCE(v.archived,0)=1));
|
||||
COMMIT;
|
||||
@@ -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,35 @@ 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 = "request_combo_quote")]
|
||||
RequestComboQuote(crate::combo_rfq::Request),
|
||||
#[serde(rename = "quote_combo")]
|
||||
QuoteCombo(crate::combo_rfq::Quote),
|
||||
#[serde(rename = "accept_combo_quote")]
|
||||
AcceptComboQuote(crate::combo_rfq::Accept),
|
||||
#[serde(rename = "respond_combo_quote")]
|
||||
RespondComboQuote(crate::combo_rfq::Respond),
|
||||
#[serde(rename = "cancel_combo_quote")]
|
||||
CancelComboQuote {
|
||||
rfq: String,
|
||||
quote: String,
|
||||
maker: String,
|
||||
},
|
||||
#[serde(rename = "cancel_combo_rfq")]
|
||||
CancelComboRfq {
|
||||
rfq: String,
|
||||
requester: String,
|
||||
},
|
||||
#[serde(rename = "define_neg_risk")]
|
||||
DefineNegRisk {
|
||||
group: String,
|
||||
|
||||
@@ -10,14 +10,14 @@ pub(crate) fn transaction(
|
||||
) -> Result<Transaction<'_>> {
|
||||
loop {
|
||||
let tx = Transaction::new_unchecked(db, behavior)?;
|
||||
let due: bool = tx.query_row(
|
||||
let due: bool = tx.prepare_cached(concat!(
|
||||
"SELECT EXISTS(SELECT 1 FROM order_deadlines WHERE pending=1 AND expiration<=unixepoch()+60)
|
||||
OR EXISTS(SELECT 1 FROM twap_markets WHERE pending_close=1 AND end_at<=unixepoch())
|
||||
OR EXISTS(SELECT 1 FROM order_heartbeats WHERE deadline_ms<=CAST(unixepoch('subsec')*1000 AS INTEGER))
|
||||
OR EXISTS(SELECT 1 FROM sports_kickoffs WHERE cleared_at_ms IS NULL AND due_ms<=CAST(unixepoch('subsec')*1000 AS INTEGER))
|
||||
OR EXISTS(SELECT 1 FROM quote_pending)",
|
||||
[], |row| row.get(0),
|
||||
)?;
|
||||
OR EXISTS(SELECT 1 FROM quote_pending) OR EXISTS(",
|
||||
include_str!("combo_rfq_due.sql"), ")",
|
||||
))?.query_row([], |row| row.get(0))?;
|
||||
if !due {
|
||||
return Ok(tx);
|
||||
}
|
||||
@@ -49,6 +49,7 @@ pub(crate) fn transaction(
|
||||
}
|
||||
crate::kickoff::clear_due(&write)?;
|
||||
crate::heartbeat::expire(&write)?;
|
||||
crate::combo_rfq::expire(&write)?;
|
||||
crate::quotes::flush(&write)?;
|
||||
crate::depth_feed::flush(&write)?;
|
||||
write.commit()?;
|
||||
|
||||
@@ -32,16 +32,17 @@ pub(crate) fn cash_micros(tx: &Transaction, account: &str, delta: i64) -> Result
|
||||
|
||||
pub(crate) fn balance(db: &Connection, account: &str) -> Result<Value> {
|
||||
crate::validation::identifier(account)?;
|
||||
let (cash, remainder, reserved): (i64, i64, i64) = db.query_row(
|
||||
let (cash, remainder, reserved, rfq_reserved): (i64, i64, i64, i64) = db.query_row(
|
||||
"SELECT a.cash,COALESCE(r.micros,0),
|
||||
(SELECT COALESCE(SUM(price*remaining),0) FROM orders
|
||||
WHERE account=a.id AND side='buy' AND status='live')
|
||||
WHERE account=a.id AND side='buy' AND status='live'),
|
||||
(SELECT COALESCE(SUM(cash_micros),0) FROM combo_rfq_holds WHERE account=a.id)
|
||||
FROM accounts a LEFT JOIN cash_remainders r ON r.account=a.id WHERE a.id=?",
|
||||
[account],
|
||||
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
|
||||
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)),
|
||||
)?;
|
||||
let available = i128::from(cash) * 10000 + i128::from(remainder);
|
||||
let reserved = i128::from(reserved);
|
||||
let reserved = i128::from(reserved) + i128::from(rfq_reserved);
|
||||
Ok(
|
||||
json!({"account":account, "available_micros":available, "reserved_micros":reserved,
|
||||
"total_cash_micros":available+reserved}),
|
||||
|
||||
@@ -4,6 +4,8 @@ mod activity;
|
||||
mod assets;
|
||||
mod augmented;
|
||||
mod catalog;
|
||||
mod combo;
|
||||
mod combo_rfq;
|
||||
mod depth_feed;
|
||||
mod estimate;
|
||||
mod expiry;
|
||||
@@ -127,6 +129,20 @@ 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 combo_rfq_ready: bool = db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='table' AND name='combo_rfq_trades')",
|
||||
[], |r| r.get(0),
|
||||
)?;
|
||||
if !combo_rfq_ready {
|
||||
db.execute_batch(include_str!("combo_rfq_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 +242,9 @@ impl Exchange {
|
||||
| "market_amounts"
|
||||
| "tick_history"
|
||||
| "catalog"
|
||||
| "combo"
|
||||
| "combo_rfq"
|
||||
| "combo_rfq_open"
|
||||
| "events"
|
||||
| "history"
|
||||
| "prices_history"
|
||||
|
||||
@@ -114,6 +114,20 @@ 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::RequestComboQuote(request) => request.apply(tx, request_id),
|
||||
Command::QuoteCombo(quote) => quote.apply(tx, request_id),
|
||||
Command::AcceptComboQuote(accept) => accept.apply(tx),
|
||||
Command::RespondComboQuote(response) => response.apply(tx, request_id),
|
||||
Command::CancelComboQuote { rfq, quote, maker } => {
|
||||
crate::combo_rfq::cancel_quote(tx, &rfq, "e, &maker)
|
||||
}
|
||||
Command::CancelComboRfq { rfq, requester } => {
|
||||
crate::combo_rfq::cancel_request(tx, &rfq, &requester)
|
||||
}
|
||||
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);
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
use exchange::Exchange;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
fn commands() -> Vec<Value> {
|
||||
include_str!("../../../docs/examples/combo-rfq.jsonl")
|
||||
.lines()
|
||||
.map(|line| {
|
||||
let mut cmd: Value = serde_json::from_str(line).unwrap();
|
||||
if cmd["op"] == "request_combo_quote" {
|
||||
cmd["submission_window_ms"] = json!(300000);
|
||||
cmd["acceptance_window_ms"] = json!(300000);
|
||||
cmd["last_look_ms"] = json!(300000);
|
||||
}
|
||||
cmd
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn combo_rfq_reserves_then_mints_merges_and_transfers() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("rfq.sqlite");
|
||||
let mut db = Exchange::open(&path).unwrap();
|
||||
let cmds = commands();
|
||||
for cmd in &cmds[..6] {
|
||||
db.execute(cmd.clone()).unwrap();
|
||||
}
|
||||
let combo = cmds[5]["combo"].as_str().unwrap();
|
||||
assert_eq!(
|
||||
db.execute(cmds[6].clone()).unwrap()["rfqs"][0]["rfq_id"],
|
||||
"rfq-buy"
|
||||
);
|
||||
db.execute(cmds[7].clone()).unwrap();
|
||||
assert_eq!(
|
||||
db.execute(cmds[8].clone()).unwrap()["status"],
|
||||
"AWAITING_MAKER_CONFIRMATION"
|
||||
);
|
||||
let cash = json!({"op":"balance","account":"taker"});
|
||||
let held = db.execute(cash.clone()).unwrap();
|
||||
assert_eq!(held["reserved_micros"], 1400000);
|
||||
assert_eq!(held["total_cash_micros"], 5000000);
|
||||
assert!(db
|
||||
.execute(
|
||||
json!({"op":"respond_combo_quote","id":"wrong-maker","rfq":"rfq-buy",
|
||||
"quote":"rfq-mint-quote","maker":"taker","confirm":true})
|
||||
)
|
||||
.is_err());
|
||||
drop(db);
|
||||
|
||||
let mut db = Exchange::open(&path).unwrap();
|
||||
let mint = db.execute(cmds[9].clone()).unwrap();
|
||||
assert_eq!(mint["fill"]["flow"], "MINT");
|
||||
assert_eq!(db.execute(cmds[9].clone()).unwrap(), mint);
|
||||
assert_eq!(db.execute(cash.clone()).unwrap()["reserved_micros"], 0);
|
||||
for cmd in &cmds[11..14] {
|
||||
db.execute(cmd.clone()).unwrap();
|
||||
}
|
||||
let held = db.execute(cmds[15].clone()).unwrap();
|
||||
assert_eq!(held["balances_micros"], json!([4000000, 0]));
|
||||
assert_eq!(held["available_micros"], json!([2500000, 0]));
|
||||
let merge = db.execute(cmds[14].clone()).unwrap();
|
||||
assert_eq!(merge["fill"]["flow"], "MERGE");
|
||||
assert_eq!(
|
||||
db.execute(cmds[15].clone()).unwrap()["collateral_micros"],
|
||||
2500000
|
||||
);
|
||||
assert_eq!(
|
||||
db.execute(cash.clone()).unwrap()["available_micros"],
|
||||
4200000
|
||||
);
|
||||
|
||||
for cmd in [
|
||||
json!({"op":"request_combo_quote","id":"transfer","combo":combo,"requester":"taker",
|
||||
"direction":"SELL","side":"YES","shares_micros":1000000}),
|
||||
json!({"op":"quote_combo","id":"transfer-quote","rfq":"transfer","maker":"maker",
|
||||
"source":"collateral","price_micros":500000,"shares_micros":1000000}),
|
||||
json!({"op":"accept_combo_quote","id":"transfer-accept","rfq":"transfer","requester":"taker","quote":"transfer-quote"}),
|
||||
] {
|
||||
db.execute(cmd).unwrap();
|
||||
}
|
||||
let transfer = db
|
||||
.execute(
|
||||
json!({"op":"respond_combo_quote","id":"transfer-fill","rfq":"transfer",
|
||||
"quote":"transfer-quote","maker":"maker","confirm":true}),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(transfer["fill"]["flow"], "TRANSFER");
|
||||
assert_eq!(db.execute(cash).unwrap()["available_micros"], 4700000);
|
||||
assert_eq!(
|
||||
db.execute(cmds[15].clone()).unwrap()["collateral_micros"],
|
||||
2500000
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn combo_rfq_recovers_locks_on_expiry_and_rejects_competing_acceptance() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("rfq-expiry.sqlite");
|
||||
let mut db = Exchange::open(&path).unwrap();
|
||||
let cmds = commands();
|
||||
for cmd in &cmds[..9] {
|
||||
db.execute(cmd.clone()).unwrap();
|
||||
}
|
||||
let combo = cmds[5]["combo"].as_str().unwrap();
|
||||
for cmd in [
|
||||
json!({"op":"request_combo_quote","id":"second","combo":combo,"requester":"taker",
|
||||
"direction":"BUY","side":"NO","notional_micros":4000000}),
|
||||
json!({"op":"quote_combo","id":"second-quote","rfq":"second","maker":"maker",
|
||||
"source":"collateral","price_micros":800000,"shares_micros":5000000}),
|
||||
] {
|
||||
db.execute(cmd).unwrap();
|
||||
}
|
||||
let accept = json!({"op":"accept_combo_quote","id":"second-accept","rfq":"second","requester":"taker","quote":"second-quote"});
|
||||
assert!(db.execute(accept.clone()).is_err());
|
||||
let status = json!({"op":"combo_rfq","rfq":"second","account":"taker"});
|
||||
assert_eq!(
|
||||
db.execute(status.clone()).unwrap()["status"],
|
||||
"AWAITING_REQUESTER_ACCEPTANCE"
|
||||
);
|
||||
let conn = rusqlite::Connection::open(&path).unwrap();
|
||||
conn.execute("UPDATE combo_rfqs SET confirm_by=0 WHERE id='rfq-buy'", [])
|
||||
.unwrap();
|
||||
drop(conn);
|
||||
drop(db);
|
||||
|
||||
let mut db = Exchange::open(&path).unwrap();
|
||||
assert_eq!(db.execute(cmds[10].clone()).unwrap()["status"], "EXPIRED");
|
||||
assert!(db.execute(cmds[9].clone()).is_err());
|
||||
db.execute(accept).unwrap();
|
||||
let decline = db
|
||||
.execute(json!({"op":"respond_combo_quote","id":"decline",
|
||||
"rfq":"second","maker":"maker","quote":"second-quote","confirm":false}))
|
||||
.unwrap();
|
||||
assert_eq!(decline["status"], "FAILED");
|
||||
assert_eq!(decline["failure"], "MAKER_DECLINED");
|
||||
for account in ["taker", "maker"] {
|
||||
let cash = db
|
||||
.execute(json!({"op":"balance","account":account}))
|
||||
.unwrap();
|
||||
assert_eq!(cash["available_micros"], 5000000);
|
||||
assert_eq!(cash["reserved_micros"], 0);
|
||||
}
|
||||
assert_eq!(
|
||||
db.execute(cmds[15].clone()).unwrap()["collateral_micros"],
|
||||
0
|
||||
);
|
||||
}
|
||||
@@ -8,17 +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"]
|
||||
main -->|核对组合盘兑付| combo["src/combo_payout.rs"]
|
||||
main -->|区分互斥组直接与推导兑付| negrisk["src/neg_risk_resolution.rs"]
|
||||
negrisk -->|模块和 ABI 校验| position
|
||||
negrisk -->|最终确认区块与合约错误| rpc
|
||||
combo -->|查询模块注册表| position
|
||||
combo -->|执行最终区块调用| rpc
|
||||
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
|
||||
@@ -134,118 +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)
|
||||
|
||||
## Polygon 组合盘兑付核对
|
||||
|
||||
`venue-probe --inspect-combo-payout CONDITION AMOUNT_MICROS` 读取组合条件。有登记的腿时,以同一个正整数微份数分别查询 YES 与 NO。当前结论由状态和逐侧兑付金额表达。空腿数组表示 `unprepared`,两侧均返回合约的 `PositionNotRedeemable()` 表示 `unresolved`,两侧都成功返回金额表示 `redeemable`。其他错误会使探针退出。即使 NO 兑付全额,也可能还有腿尚未裁决。[官方组合模块](https://github.com/Polymarket/polymarket-v2-external/blob/main/src/modules/CombinatorialModule.sol)
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
actor U as 调用者
|
||||
participant P as venue-probe
|
||||
participant R as Polygon RPC
|
||||
participant M as PositionManager
|
||||
participant C as CombinatorialModule
|
||||
U->>P: inspect-combo-payout CONDITION AMOUNT_MICROS
|
||||
P->>R: 获取 Polygon 最终确认区块
|
||||
P->>R: 在指定区块查询 moduleById(3)
|
||||
R->>M: 查询组合模块代理
|
||||
M-->>R: 模块地址
|
||||
R-->>P: 已登记的模块地址
|
||||
P->>R: 在同一区块查询 getLegs
|
||||
R->>C: 查询组合的腿
|
||||
C-->>R: Position ID 数组
|
||||
R-->>P: 原始数组
|
||||
opt 有登记的腿
|
||||
loop YES 和 NO 各一次
|
||||
P->>R: 在同一区块查询 getPayout
|
||||
R->>C: 当前方向 Position ID 和份额
|
||||
C-->>R: 兑付整数金额或合约错误
|
||||
R-->>P: 原始结果
|
||||
end
|
||||
end
|
||||
P->>R: 复核同一区块哈希
|
||||
P-->>U: 组合腿、待裁决状态或逐侧兑付
|
||||
```
|
||||
|
||||
`venue-probe --replay-combo-payout crates/venue-probe/fixtures/live-combo-payouts.json` 重放两个真实链上组合。一个组合的两侧均待裁决,另一个按 1000001 微份查询,YES 兑付 0,NO 兑付全部 1000001 微美元。该组合的 4 条腿中,一条已裁决为零赔付,另外三条仍待裁决。样本包含登记交易哈希、区块及 ABI 原始返回,仍缺少前端和 RFQ 的同盘关联。[原始样本](fixtures/live-combo-payouts.json)
|
||||
|
||||
## Polygon 互斥组的直接报告与推导
|
||||
|
||||
`venue-probe --inspect-neg-risk-event EVENT_ID INDICES` 接受 V2 互斥事件 ID 和逗号分隔的条件索引。索引从零开始,等于真实条件总数时表示合成的「其他」。命令从已确认区块读取计数与旧版迁移标记,并分别读取各选定条件的有效兑付 `getResult` 与原始存储 `result(conditionId, 0)`。有效兑付和事件计数符合推导规则且原始结果为空时,标为 `derived`。存储里有结果时标为 `stored`。RPC 或 ABI 异常会终止核对。[官方 NegRisk 模块](https://github.com/Polymarket/polymarket-v2-external/blob/main/docs/modules.md#negriskmodule-moduleid--2) · [合约原始结果定义](https://github.com/Polymarket/polymarket-v2-external/blob/main/src/modules/abstract/BaseModule.sol)
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
actor U as 调用者
|
||||
participant P as venue-probe
|
||||
participant R as Polygon RPC
|
||||
participant N as NegRiskModule
|
||||
U->>P: inspect-neg-risk-event EVENT_ID INDICES
|
||||
P->>R: 读取最终确认区块和模块注册表
|
||||
P->>R: 查询真实条件数、直接报告数、YES 总权重和迁移标记
|
||||
R->>N: 在指定区块读取计数
|
||||
N-->>R: 事件计数与权重
|
||||
R-->>P: ABI 整数字
|
||||
loop 选中的每个条件索引
|
||||
P->>R: 读取 getResult 和原始 result
|
||||
R->>N: 查询有效兑付和直接存储
|
||||
N-->>R: 有效数组及存储整数或空回退
|
||||
R-->>P: 两种结果的原始返回
|
||||
end
|
||||
P->>R: 复核区块哈希
|
||||
P-->>U: 逐条件兑付与可核对的来源
|
||||
```
|
||||
|
||||
离线命令为 `venue-probe --replay-neg-risk-event crates/venue-probe/fixtures/live-negrisk-resolution.json`。样本记录赢家出现前后的有效结果与直接存储。区块 `0x5df5c44` 的三条件组中,「其他」没有直接存储,但已经可以按 NO 兑付。区块 `0x5df5c62` 的 37 条件组有 33 个直接报告,四个尚未报告的真实条件仍待裁决,合成「其他」已可按 NO 兑付。旧版事件标识和链上反向映射将这些条件对应到 Gamma 的足球精确比分盘。同一区块中,四个待裁决条件对应的旧 CTF 合约兑付分母均为 1,V2 仍等待迁移裁决。[原始样本](fixtures/live-negrisk-resolution.json)
|
||||
@@ -1,42 +0,0 @@
|
||||
[
|
||||
{
|
||||
"chain_id": 137,
|
||||
"block_number": "0x5df5ab2",
|
||||
"block_hash": "0x14e566bc1e5b4acf05706c9a59f0ba01d9064db8404fd020317c32894d49a83d",
|
||||
"condition_id": "0x034bd7384b7f58f2a267c90e5f2c45d865000000000000000000000000000000",
|
||||
"amount_micros": 1000001,
|
||||
"registry": "0x00000000000000000000000030000034706c7d8e12009dab006be20000c031a8",
|
||||
"legs": "0x0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000b011006ceb374e5e03e0646de13010aaf710000000000000000000000000000010125dcc4e3014cac67374ad55d3bfa5039000000000000000000000000000000014ad9e4ceaa2d864b3e9eb9e685e7bf97000000000000000000000000000000015de9f8160adc8328f91acc2e9ab4465800000000000000000000000000000001820b68526eae7c48b92d51a512d4cd81000000000000000000000000000000019a1cc98bc041fbdd4ac95af0e5982dd000000000000000000000000000000101b9dec220c321c5006459f9acd1ea36ff00000000000000000000000000000101c3e3697c82867662dfcc4efa4747aaa900000000000000000000000000000101c6cc49ab6b18b159edfacedb661dcc0a00000000000000000000000000000001c8b8bb7625efac202c3857d38cc6ad0e00000000000000000000000000000001d06efb76e1836bce7f92507344277933000000000000000000000000000001",
|
||||
"payouts": [
|
||||
{
|
||||
"revert": "0xc003777b"
|
||||
},
|
||||
{
|
||||
"revert": "0xc003777b"
|
||||
}
|
||||
],
|
||||
"source": "https://polygon-bor-rpc.publicnode.com",
|
||||
"preparation_tx": "0xb826cb8d1e00086bdbb9aaecd29800cbb9b72a4311de0eac0f9cf3cfad0e81f7",
|
||||
"observed_at_ms": 1796491240143
|
||||
},
|
||||
{
|
||||
"chain_id": 137,
|
||||
"block_number": "0x5df5ab2",
|
||||
"block_hash": "0x14e566bc1e5b4acf05706c9a59f0ba01d9064db8404fd020317c32894d49a83d",
|
||||
"condition_id": "0x033f568c0a6209ea4beb141ae1e137177d000000000000000000000000000000",
|
||||
"amount_micros": 1000001,
|
||||
"registry": "0x00000000000000000000000030000034706c7d8e12009dab006be20000c031a8",
|
||||
"legs": "0x00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000004014375f1cab1f5e5e98c9014fff1de38c1000000000000000000000000000000019d2d7100e42a913a5a13db0380d3aba900000000000000000000000000000101c157597d55e31bbf2a93bc0b524c189200000000000000000000000000000101e23cbfdde8c236499dd947c83faf57a6000000000000000000000000000000",
|
||||
"payouts": [
|
||||
{
|
||||
"return": "0x0000000000000000000000000000000000000000000000000000000000000000"
|
||||
},
|
||||
{
|
||||
"return": "0x00000000000000000000000000000000000000000000000000000000000f4241"
|
||||
}
|
||||
],
|
||||
"source": "https://polygon-bor-rpc.publicnode.com",
|
||||
"preparation_tx": "0x8d77f8741cfbf4c6388d87aa90a6f4c2c238ac35fbecc02ab39671e2f0f8a7b9",
|
||||
"observed_at_ms": 1796491315981
|
||||
}
|
||||
]
|
||||
@@ -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,242 +0,0 @@
|
||||
[
|
||||
{
|
||||
"chain_id": 137,
|
||||
"event_id": "0x026b8d75bfa676ec6e8c8d496b03036400000300000000000000000000000000",
|
||||
"block_number": "0x5df5c43",
|
||||
"block_hash": "0x210e92e62a26f17bb75c26b905f96c83180e54b51ab634f64da83c16c30130ca",
|
||||
"registry": "0x000000000000000000000000200000900045e3b6259600682756002200028933",
|
||||
"condition_count": "0x0000000000000000000000000000000000000000000000000000000000000003",
|
||||
"conditions_reported": "0x0000000000000000000000000000000000000000000000000000000000000000",
|
||||
"results_sum": "0x0000000000000000000000000000000000000000000000000000000000000000",
|
||||
"conditions": [
|
||||
{
|
||||
"index": 0,
|
||||
"effective": "0x00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000000",
|
||||
"stored_yes": {
|
||||
"revert": "0x"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 1,
|
||||
"effective": "0x00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000000",
|
||||
"stored_yes": {
|
||||
"revert": "0x"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 2,
|
||||
"effective": "0x00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000000",
|
||||
"stored_yes": {
|
||||
"revert": "0x"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 3,
|
||||
"effective": "0x00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000000",
|
||||
"stored_yes": {
|
||||
"revert": "0x"
|
||||
}
|
||||
}
|
||||
],
|
||||
"sources": [
|
||||
"https://polygon.drpc.org"
|
||||
],
|
||||
"legacy_event_id": "0x0a0374c2418aac1d34f5b9ee14f5a0446b8d75bfa676ec6e8c8d496b03036400"
|
||||
},
|
||||
{
|
||||
"chain_id": 137,
|
||||
"event_id": "0x026b8d75bfa676ec6e8c8d496b03036400000300000000000000000000000000",
|
||||
"block_number": "0x5df5c44",
|
||||
"block_hash": "0xee7aa65f66a4260474fcec3934ea21ab93f6003af041934a55d2547286cfaedb",
|
||||
"registry": "0x000000000000000000000000200000900045e3b6259600682756002200028933",
|
||||
"condition_count": "0x0000000000000000000000000000000000000000000000000000000000000003",
|
||||
"conditions_reported": "0x0000000000000000000000000000000000000000000000000000000000000003",
|
||||
"results_sum": "0x00000000000000000000000000000000000000000000000000000000000f4240",
|
||||
"conditions": [
|
||||
{
|
||||
"index": 0,
|
||||
"effective": "0x00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f4240",
|
||||
"stored_yes": {
|
||||
"return": "0x0000000000000000000000000000000000000000000000000000000000000000"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 1,
|
||||
"effective": "0x0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000f42400000000000000000000000000000000000000000000000000000000000000000",
|
||||
"stored_yes": {
|
||||
"return": "0x00000000000000000000000000000000000000000000000000000000000f4240"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 2,
|
||||
"effective": "0x00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f4240",
|
||||
"stored_yes": {
|
||||
"return": "0x0000000000000000000000000000000000000000000000000000000000000000"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 3,
|
||||
"effective": "0x00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f4240",
|
||||
"stored_yes": {
|
||||
"revert": "0x"
|
||||
}
|
||||
}
|
||||
],
|
||||
"sources": [
|
||||
"https://polygon.drpc.org"
|
||||
],
|
||||
"transition_tx": "0xaef081eb07769e30c2d79c45deff68f2c697b250d4b7c0f04afc2390e1d50250",
|
||||
"legacy_event_id": "0x0a0374c2418aac1d34f5b9ee14f5a0446b8d75bfa676ec6e8c8d496b03036400",
|
||||
"legacy_catalog": [
|
||||
{
|
||||
"condition_index": 0,
|
||||
"id": "7420052",
|
||||
"slug": "serc-acd-cit-2026-12-05-acd",
|
||||
"version": "v1",
|
||||
"conditionId": "0x031de2fd1570ce33ad6e59b50c5bf58d24661741bcc42c0dfd5e718fc4960128",
|
||||
"outcomes": "[\"Yes\", \"No\"]",
|
||||
"outcomePrices": "[\"0\", \"1\"]",
|
||||
"position_condition_id": "0x026b8d75bfa676ec6e8c8d496b03036400000300000000000000000000000000",
|
||||
"legacy_ctf_denominator": "0x0000000000000000000000000000000000000000000000000000000000000001"
|
||||
},
|
||||
{
|
||||
"condition_index": 1,
|
||||
"id": "7420053",
|
||||
"slug": "serc-acd-cit-2026-12-05-draw",
|
||||
"version": "v1",
|
||||
"conditionId": "0x71e48af45160c9f56010f46ad2d0915a29c861a3250d6592c1f1977c3fbfc8cc",
|
||||
"outcomes": "[\"Yes\", \"No\"]",
|
||||
"outcomePrices": "[\"1\", \"0\"]",
|
||||
"position_condition_id": "0x026b8d75bfa676ec6e8c8d496b03036400000300000000000000000000000100",
|
||||
"legacy_ctf_denominator": "0x0000000000000000000000000000000000000000000000000000000000000001"
|
||||
},
|
||||
{
|
||||
"condition_index": 2,
|
||||
"id": "7420054",
|
||||
"slug": "serc-acd-cit-2026-12-05-cit",
|
||||
"version": "v1",
|
||||
"conditionId": "0xc0671fbf4755c8b5b4eb94352e7c92b832f0263a9a0460225ad04412d45ac34e",
|
||||
"outcomes": "[\"Yes\", \"No\"]",
|
||||
"outcomePrices": "[\"0\", \"1\"]",
|
||||
"position_condition_id": "0x026b8d75bfa676ec6e8c8d496b03036400000300000000000000000000000200",
|
||||
"legacy_ctf_denominator": "0x0000000000000000000000000000000000000000000000000000000000000001"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"chain_id": 137,
|
||||
"event_id": "0x02a28dc7d450aef445cdcfc3b43a566800002500000000000000000000000000",
|
||||
"block_number": "0x5df5c62",
|
||||
"block_hash": "0xc60a077a550b53bb5dc4f960047b5be961f196574f6af91b799ed0f109e9e5d7",
|
||||
"registry": "0x000000000000000000000000200000900045e3b6259600682756002200028933",
|
||||
"condition_count": "0x0000000000000000000000000000000000000000000000000000000000000025",
|
||||
"conditions_reported": "0x0000000000000000000000000000000000000000000000000000000000000021",
|
||||
"results_sum": "0x00000000000000000000000000000000000000000000000000000000000f4240",
|
||||
"conditions": [
|
||||
{
|
||||
"index": 0,
|
||||
"effective": "0x00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f4240",
|
||||
"stored_yes": {
|
||||
"return": "0x0000000000000000000000000000000000000000000000000000000000000000"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 32,
|
||||
"effective": "0x00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000000",
|
||||
"stored_yes": {
|
||||
"revert": "0x"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 33,
|
||||
"effective": "0x00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000000",
|
||||
"stored_yes": {
|
||||
"revert": "0x"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 34,
|
||||
"effective": "0x00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000000",
|
||||
"stored_yes": {
|
||||
"revert": "0x"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 35,
|
||||
"effective": "0x00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000000",
|
||||
"stored_yes": {
|
||||
"revert": "0x"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 37,
|
||||
"effective": "0x00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f4240",
|
||||
"stored_yes": {
|
||||
"revert": "0x"
|
||||
}
|
||||
}
|
||||
],
|
||||
"sources": [
|
||||
"https://polygon.drpc.org"
|
||||
],
|
||||
"transition_tx": "0xa066409b2da62eab52aeae7e439cb11e1e28124a2e94d06c87a74bf42acc8286",
|
||||
"legacy_event_id": "0x1ec6befb358b06cb59c12fddd306b970a28dc7d450aef445cdcfc3b43a566800",
|
||||
"legacy_catalog": [
|
||||
{
|
||||
"condition_index": 0,
|
||||
"id": "7421956",
|
||||
"slug": "serc-acd-cit-2026-12-05-exact-score-0-0",
|
||||
"version": "v1",
|
||||
"conditionId": "0xaa7d72c3addfbd60609d2762ca945e39307da5e05c9aa9c24a8e979d6e2f52c0",
|
||||
"outcomes": "[\"Yes\", \"No\"]",
|
||||
"outcomePrices": "[\"0\", \"1\"]",
|
||||
"position_condition_id": "0x02a28dc7d450aef445cdcfc3b43a566800002500000000000000000000000000",
|
||||
"legacy_ctf_denominator": "0x0000000000000000000000000000000000000000000000000000000000000001"
|
||||
},
|
||||
{
|
||||
"condition_index": 32,
|
||||
"id": "7421988",
|
||||
"slug": "serc-acd-cit-2026-12-05-exact-score-5-3",
|
||||
"version": "v1",
|
||||
"conditionId": "0x99ba4cc23d2eb8733fc92c3775951f5d020b3304134015f7b60233d24cfb77a7",
|
||||
"outcomes": "[\"Yes\", \"No\"]",
|
||||
"outcomePrices": "[\"0\", \"1\"]",
|
||||
"position_condition_id": "0x02a28dc7d450aef445cdcfc3b43a566800002500000000000000000000002000",
|
||||
"legacy_ctf_denominator": "0x0000000000000000000000000000000000000000000000000000000000000001"
|
||||
},
|
||||
{
|
||||
"condition_index": 33,
|
||||
"id": "7421989",
|
||||
"slug": "serc-acd-cit-2026-12-05-exact-score-4-5",
|
||||
"version": "v1",
|
||||
"conditionId": "0xf2a796cbeefc2bce1bd00ce006464082eb47d08e1d0d65c93363388925e61c2c",
|
||||
"outcomes": "[\"Yes\", \"No\"]",
|
||||
"outcomePrices": "[\"0\", \"1\"]",
|
||||
"position_condition_id": "0x02a28dc7d450aef445cdcfc3b43a566800002500000000000000000000002100",
|
||||
"legacy_ctf_denominator": "0x0000000000000000000000000000000000000000000000000000000000000001"
|
||||
},
|
||||
{
|
||||
"condition_index": 34,
|
||||
"id": "7421990",
|
||||
"slug": "serc-acd-cit-2026-12-05-exact-score-5-4",
|
||||
"version": "v1",
|
||||
"conditionId": "0xb37245a4a512fef2f2e8b687fd2820896548f5d7f54ef080b8077f457d3aca91",
|
||||
"outcomes": "[\"Yes\", \"No\"]",
|
||||
"outcomePrices": "[\"0\", \"1\"]",
|
||||
"position_condition_id": "0x02a28dc7d450aef445cdcfc3b43a566800002500000000000000000000002200",
|
||||
"legacy_ctf_denominator": "0x0000000000000000000000000000000000000000000000000000000000000001"
|
||||
},
|
||||
{
|
||||
"condition_index": 35,
|
||||
"id": "7421991",
|
||||
"slug": "serc-acd-cit-2026-12-05-exact-score-5-5",
|
||||
"version": "v1",
|
||||
"conditionId": "0x8ff38f5d3a32276d5ec8cb5a6232652fa838fec77e22e081a7fd1cf1c45a33d3",
|
||||
"outcomes": "[\"Yes\", \"No\"]",
|
||||
"outcomePrices": "[\"0\", \"1\"]",
|
||||
"position_condition_id": "0x02a28dc7d450aef445cdcfc3b43a566800002500000000000000000000002300",
|
||||
"legacy_ctf_denominator": "0x0000000000000000000000000000000000000000000000000000000000000001"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
@@ -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,241 +0,0 @@
|
||||
use crate::{
|
||||
polygon_rpc::{hex_data, quantity, CallOutcome, FinalizedRpc, POLYGON_CHAIN_ID},
|
||||
position_resolution::{lookup_module, module_address, uint, POSITION_MANAGER},
|
||||
};
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use reqwest::blocking::Client;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
const MODULE: u8 = 3;
|
||||
const GET_LEGS: &str = "9989b1ed"; // getLegs(bytes31)
|
||||
const GET_PAYOUT: &str = "4c619e4c"; // getPayout(uint256,uint256)
|
||||
const NOT_REDEEMABLE: &str = "0xc003777b"; // PositionNotRedeemable()
|
||||
const MAX_LEGS: usize = 50;
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct Observation {
|
||||
chain_id: u64,
|
||||
block_number: String,
|
||||
block_hash: String,
|
||||
condition_id: String,
|
||||
amount_micros: u64,
|
||||
registry: String,
|
||||
legs: String,
|
||||
payouts: Option<[CallOutcome; 2]>,
|
||||
observed_at_ms: u64,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
source: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
preparation_tx: Option<String>,
|
||||
}
|
||||
|
||||
fn condition_word(condition: &str) -> Result<String> {
|
||||
let word = match condition.len() {
|
||||
64 => format!("{}00", hex_data(condition, 31)?),
|
||||
66 => hex_data(condition, 32)?.to_owned(),
|
||||
_ => anyhow::bail!("invalid combo condition ID length"),
|
||||
};
|
||||
ensure!(
|
||||
word.starts_with("03") && word.ends_with("00"),
|
||||
"expected a combinatorial condition with an empty outcome byte"
|
||||
);
|
||||
Ok(word.to_ascii_lowercase())
|
||||
}
|
||||
|
||||
fn legs(raw: &str) -> Result<Vec<&str>> {
|
||||
ensure!(
|
||||
(130..=130 + 64 * MAX_LEGS).contains(&raw.len()) && (raw.len() - 130) % 64 == 0,
|
||||
"invalid getLegs ABI size"
|
||||
);
|
||||
let data = hex_data(raw, (raw.len() - 2) / 2)?;
|
||||
let count = (data.len() - 128) / 64;
|
||||
ensure!(uint(&data[..64])? == 32, "invalid getLegs ABI offset");
|
||||
ensure!(
|
||||
uint(&data[64..128])? == count as u64,
|
||||
"invalid getLegs length"
|
||||
);
|
||||
let mut ids: Vec<&str> = Vec::with_capacity(count);
|
||||
for index in 0..count {
|
||||
let start = 128 + 64 * index;
|
||||
let id = &data[start..start + 64];
|
||||
ensure!(
|
||||
matches!(&id[..2], "01" | "02") && matches!(&id[62..], "00" | "01"),
|
||||
"invalid underlying position ID"
|
||||
);
|
||||
if let Some(previous) = ids.last() {
|
||||
ensure!(
|
||||
previous[..62].to_ascii_lowercase() < id[..62].to_ascii_lowercase(),
|
||||
"combo legs must be sorted with distinct conditions"
|
||||
);
|
||||
}
|
||||
ids.push(id);
|
||||
}
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
fn payout_status(
|
||||
payouts: Option<&[CallOutcome; 2]>,
|
||||
has_legs: bool,
|
||||
amount: u64,
|
||||
) -> Result<(&'static str, Option<[String; 2]>)> {
|
||||
match (has_legs, payouts) {
|
||||
(false, None) => Ok(("unprepared", None)),
|
||||
(true, Some([CallOutcome::Revert(yes), CallOutcome::Revert(no)]))
|
||||
if [yes, no]
|
||||
.iter()
|
||||
.all(|value| value.eq_ignore_ascii_case(NOT_REDEEMABLE)) =>
|
||||
{
|
||||
Ok(("unresolved", None))
|
||||
}
|
||||
(true, Some([CallOutcome::Return(yes), CallOutcome::Return(no)])) => {
|
||||
let yes = uint(hex_data(yes, 32)?)?;
|
||||
let no = uint(hex_data(no, 32)?)?;
|
||||
ensure!(
|
||||
yes.checked_add(no).is_some_and(|total| total <= amount),
|
||||
"combo payouts exceed the position amount"
|
||||
);
|
||||
Ok(("redeemable", Some([yes.to_string(), no.to_string()])))
|
||||
}
|
||||
_ => anyhow::bail!("inconsistent combo legs and payout responses"),
|
||||
}
|
||||
}
|
||||
|
||||
fn audit(obs: Observation) -> Result<Value> {
|
||||
ensure!(
|
||||
obs.chain_id == POLYGON_CHAIN_ID,
|
||||
"observation is not Polygon mainnet"
|
||||
);
|
||||
ensure!(obs.amount_micros > 0, "position amount must be positive");
|
||||
let block = quantity(&obs.block_number)?;
|
||||
hex_data(&obs.block_hash, 32)?;
|
||||
let condition = condition_word(&obs.condition_id)?;
|
||||
let target = module_address(&obs.registry, MODULE)?;
|
||||
let ids = legs(&obs.legs)?;
|
||||
let (status, payouts) =
|
||||
payout_status(obs.payouts.as_ref(), !ids.is_empty(), obs.amount_micros)?;
|
||||
let legs: Vec<_> = ids.iter().map(|id| format!("0x{id}")).collect();
|
||||
Ok(json!({
|
||||
"observation": obs,
|
||||
"block": block,
|
||||
"position_manager": POSITION_MANAGER,
|
||||
"module_contract": target,
|
||||
"condition_id": format!("0x{condition}"),
|
||||
"leg_position_ids": legs,
|
||||
"status": status,
|
||||
"payout_micros_yes_no": payouts,
|
||||
}))
|
||||
}
|
||||
|
||||
pub(crate) fn inspect(client: &Client, condition: &str, amount: &str) -> Result<Value> {
|
||||
let condition = condition_word(condition)?;
|
||||
let amount_micros: u64 = amount.parse().context("invalid microshare amount")?;
|
||||
ensure!(amount_micros > 0, "position amount must be positive");
|
||||
let block = FinalizedRpc::connect(client)?;
|
||||
let registry = lookup_module(&block, MODULE)?;
|
||||
let address = module_address(®istry, MODULE)?;
|
||||
let raw_legs = block.call(&address, &format!("0x{GET_LEGS}{condition}"))?;
|
||||
let payouts = if legs(&raw_legs)?.is_empty() {
|
||||
None
|
||||
} else {
|
||||
let call = |side: u8| {
|
||||
block.call_with_revert(
|
||||
&address,
|
||||
&format!(
|
||||
"0x{GET_PAYOUT}{}{side:02x}{amount_micros:064x}",
|
||||
&condition[..62]
|
||||
),
|
||||
NOT_REDEEMABLE,
|
||||
)
|
||||
};
|
||||
Some([call(0)?, call(1)?])
|
||||
};
|
||||
let observed_at_ms = block.confirm()?;
|
||||
audit(Observation {
|
||||
chain_id: POLYGON_CHAIN_ID,
|
||||
block_number: block.number,
|
||||
block_hash: block.hash,
|
||||
condition_id: format!("0x{condition}"),
|
||||
amount_micros,
|
||||
registry,
|
||||
legs: raw_legs,
|
||||
payouts,
|
||||
observed_at_ms,
|
||||
source: None,
|
||||
preparation_tx: None,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn replay(file: &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 combo observations in file");
|
||||
rows.into_iter()
|
||||
.map(|row| {
|
||||
audit(serde_json::from_value(
|
||||
row.get("observation").cloned().unwrap_or(row),
|
||||
)?)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn replays_production_combos_in_both_states() -> Result<()> {
|
||||
let [pending, terminal]: [Observation; 2] =
|
||||
serde_json::from_str(include_str!("../fixtures/live-combo-payouts.json"))?;
|
||||
let pending = audit(pending)?;
|
||||
let terminal = audit(terminal)?;
|
||||
assert_eq!(pending["status"], "unresolved");
|
||||
assert_eq!(pending["leg_position_ids"].as_array().unwrap().len(), 11);
|
||||
assert!(pending["payout_micros_yes_no"].is_null());
|
||||
assert_eq!(terminal["status"], "redeemable");
|
||||
assert_eq!(terminal["payout_micros_yes_no"], json!(["0", "1000001"]));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn separates_unprepared_zero_fractional_and_inconsistent_amounts() -> Result<()> {
|
||||
assert_eq!(payout_status(None, false, 10)?, ("unprepared", None));
|
||||
assert!(payout_status(None, true, 10).is_err());
|
||||
let success = |value: u64| CallOutcome::Return(format!("0x{value:064x}"));
|
||||
for amounts in [[0, 0], [2, 7], [10, 0]] {
|
||||
let payouts = amounts.map(success);
|
||||
assert_eq!(
|
||||
payout_status(Some(&payouts), true, 10)?,
|
||||
("redeemable", Some(amounts.map(|value| value.to_string())))
|
||||
);
|
||||
}
|
||||
assert!(payout_status(Some(&[success(4), success(7)]), true, 10).is_err());
|
||||
let pending = CallOutcome::Revert(NOT_REDEEMABLE.to_owned());
|
||||
assert!(payout_status(Some(&[success(0), pending]), true, 10).is_err());
|
||||
let unknown = || CallOutcome::Revert("0x00000000".to_owned());
|
||||
assert!(payout_status(Some(&[unknown(), unknown()]), true, 10).is_err());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validates_combo_condition_and_returned_leg_array() -> Result<()> {
|
||||
let condition = format!("03{}", "00".repeat(31));
|
||||
assert_eq!(
|
||||
condition_word(&format!("0x{}", &condition[..62]))?,
|
||||
condition
|
||||
);
|
||||
assert!(condition_word(&format!("0x{}01", &condition[..62])).is_err());
|
||||
let first = format!("01{}", "00".repeat(31));
|
||||
let opposite = format!("{}01", &first[..62]);
|
||||
let second = format!("02{}", "00".repeat(31));
|
||||
let array = |a: &str, b: &str| format!("0x{:064x}{:064x}{a}{b}", 32, 2);
|
||||
assert_eq!(legs(&array(&first, &second))?.len(), 2);
|
||||
assert!(legs(&array(&first, &opposite)).is_err());
|
||||
assert!(legs(&array(&second, &first)).is_err());
|
||||
assert!(legs(&array(&first, &condition)).is_err());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -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,11 +1,6 @@
|
||||
mod book_audit;
|
||||
mod books;
|
||||
mod catalog;
|
||||
mod combo_payout;
|
||||
mod ctf_resolution;
|
||||
mod neg_risk_resolution;
|
||||
mod polygon_rpc;
|
||||
mod position_resolution;
|
||||
mod price_check;
|
||||
mod probes;
|
||||
use anyhow::{ensure, Result};
|
||||
@@ -35,81 +30,10 @@ fn observe_book(client: &Client, url: reqwest::Url, token: &str) -> Result<()> {
|
||||
result
|
||||
}
|
||||
|
||||
fn polygon_client() -> Result<Client> {
|
||||
Ok(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()?)
|
||||
}
|
||||
|
||||
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] | --inspect-combo-payout CONDITION AMOUNT_MICROS | --replay-combo-payout FILE | --inspect-neg-risk-event EVENT_ID INDICES | --replay-neg-risk-event FILE]";
|
||||
match args.as_slice() {
|
||||
[mode, condition, amount] if mode == "--inspect-combo-payout" => {
|
||||
println!(
|
||||
"{}",
|
||||
combo_payout::inspect(&polygon_client()?, condition, amount)?
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
[mode, file] if mode == "--replay-combo-payout" => {
|
||||
for report in combo_payout::replay(file)? {
|
||||
println!("{report}");
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
[mode, event, indices] if mode == "--inspect-neg-risk-event" => {
|
||||
println!(
|
||||
"{}",
|
||||
neg_risk_resolution::inspect(&polygon_client()?, event, indices)?
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
[mode, file] if mode == "--replay-neg-risk-event" => {
|
||||
for report in neg_risk_resolution::replay(file)? {
|
||||
println!("{report}");
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
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 = polygon_client()?;
|
||||
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,323 +0,0 @@
|
||||
use crate::{
|
||||
polygon_rpc::{hex_data, quantity, CallOutcome, FinalizedRpc, POLYGON_CHAIN_ID},
|
||||
position_resolution::{
|
||||
lookup_module, module_address, result, uint, DENOMINATOR, GET_RESULT, POSITION_MANAGER,
|
||||
},
|
||||
};
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use reqwest::blocking::Client;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
const MODULE: u8 = 2;
|
||||
const CONDITION_COUNT: &str = "dacc07ce"; // conditionCount(bytes29)
|
||||
const REPORTED: &str = "936830bc"; // conditionsResolved(bytes29)
|
||||
const LEGACY_EVENT: &str = "b2915f84"; // legacyEventId(bytes29)
|
||||
const RESULTS_SUM: &str = "65fe9636"; // resultsSum(bytes29)
|
||||
const STORED_RESULT: &str = "91f7d1bf"; // result(bytes31,uint256)
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
struct Condition {
|
||||
index: u16,
|
||||
effective: String,
|
||||
stored_yes: CallOutcome,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
struct Observation {
|
||||
chain_id: u64,
|
||||
event_id: String,
|
||||
block_number: String,
|
||||
block_hash: String,
|
||||
registry: String,
|
||||
condition_count: String,
|
||||
conditions_reported: String,
|
||||
results_sum: String,
|
||||
legacy_event_id: String,
|
||||
conditions: Vec<Condition>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
legacy_catalog: Vec<Value>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
sources: Vec<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
transition_tx: Option<String>,
|
||||
}
|
||||
|
||||
fn event_id(raw: &str) -> Result<(String, u16)> {
|
||||
let full = match raw.len() {
|
||||
60 => format!("{}000000", hex_data(raw, 29)?),
|
||||
66 => hex_data(raw, 32)?.to_owned(),
|
||||
_ => anyhow::bail!("invalid V2 event ID length"),
|
||||
};
|
||||
ensure!(
|
||||
full.starts_with("02") && full.ends_with("000000"),
|
||||
"expected a V2 NegRisk event ID"
|
||||
);
|
||||
let count = u16::from_str_radix(&full[34..38], 16)?;
|
||||
ensure!(count >= 2, "invalid V2 NegRisk event condition count");
|
||||
Ok((full.to_ascii_lowercase(), count))
|
||||
}
|
||||
|
||||
fn value(raw: &str) -> Result<u64> {
|
||||
uint(hex_data(raw, 32)?)
|
||||
}
|
||||
|
||||
fn condition_word(event: &str, index: u16) -> String {
|
||||
format!("{}{index:04x}00", &event[..58])
|
||||
}
|
||||
|
||||
fn output_condition(
|
||||
condition: &Condition,
|
||||
event: &str,
|
||||
count: u16,
|
||||
reported: u64,
|
||||
sum: u64,
|
||||
migrated_event: bool,
|
||||
) -> Result<Value> {
|
||||
ensure!(
|
||||
condition.index <= count,
|
||||
"condition index is outside this event"
|
||||
);
|
||||
let weights = result(&condition.effective, MODULE)?;
|
||||
let synthetic = condition.index == count;
|
||||
let migrated = migrated_event && !synthetic;
|
||||
// The generated array getter returns an empty revert for index 0
|
||||
// when the stored result array has no entries.
|
||||
let origin = match (&condition.stored_yes, weights) {
|
||||
(CallOutcome::Return(raw), Some([yes, _])) if value(raw)? == yes => {
|
||||
ensure!(
|
||||
yes == 0 || sum == DENOMINATOR,
|
||||
"stored YES payout is missing from the event sum"
|
||||
);
|
||||
ensure!(
|
||||
synthetic || reported > 0,
|
||||
"stored market is missing from the report count"
|
||||
);
|
||||
"stored"
|
||||
}
|
||||
(CallOutcome::Revert(data), weights) if data == "0x" => match weights {
|
||||
None => "unresolved",
|
||||
Some([0, DENOMINATOR]) if !migrated && sum == DENOMINATOR => "derived",
|
||||
Some([DENOMINATOR, 0]) if synthetic && sum == 0 && reported == u64::from(count) => {
|
||||
"derived"
|
||||
}
|
||||
_ => anyhow::bail!("unstored payout disagrees with the event counters"),
|
||||
},
|
||||
_ => anyhow::bail!("stored payout disagrees with the effective result"),
|
||||
};
|
||||
Ok(json!({
|
||||
"condition_index":condition.index,
|
||||
"condition_id":format!("0x{}",condition_word(event,condition.index)),
|
||||
"synthetic_other":synthetic,
|
||||
"legacy_migration":migrated,
|
||||
"source":origin,
|
||||
"payout_numerators":weights,
|
||||
}))
|
||||
}
|
||||
|
||||
fn audit(obs: Observation) -> Result<Value> {
|
||||
ensure!(
|
||||
obs.chain_id == POLYGON_CHAIN_ID,
|
||||
"observation is not from Polygon"
|
||||
);
|
||||
let block = quantity(&obs.block_number)?;
|
||||
hex_data(&obs.block_hash, 32)?;
|
||||
if let Some(tx) = &obs.transition_tx {
|
||||
hex_data(tx, 32)?;
|
||||
}
|
||||
let (event, count) = event_id(&obs.event_id)?;
|
||||
let module = module_address(&obs.registry, MODULE)?;
|
||||
let reported = value(&obs.conditions_reported)?;
|
||||
let sum = value(&obs.results_sum)?;
|
||||
let migrated = hex_data(&obs.legacy_event_id, 32)?
|
||||
.bytes()
|
||||
.any(|digit| digit != b'0');
|
||||
ensure!(
|
||||
value(&obs.condition_count)? == u64::from(count),
|
||||
"condition count disagrees with the event ID"
|
||||
);
|
||||
ensure!(
|
||||
reported <= u64::from(count) + 1 && matches!(sum, 0 | DENOMINATOR),
|
||||
"invalid NegRisk counters"
|
||||
);
|
||||
let mut seen = BTreeSet::new();
|
||||
ensure!(!obs.conditions.is_empty(), "no observed conditions");
|
||||
let conditions = obs
|
||||
.conditions
|
||||
.iter()
|
||||
.map(|condition| {
|
||||
ensure!(
|
||||
seen.insert(condition.index),
|
||||
"duplicate condition observation"
|
||||
);
|
||||
output_condition(condition, &event, count, reported, sum, migrated)
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
for market in &obs.legacy_catalog {
|
||||
let index = market["condition_index"]
|
||||
.as_u64()
|
||||
.context("missing legacy condition index")?;
|
||||
let index = u16::try_from(index).context("invalid legacy condition index")?;
|
||||
ensure!(
|
||||
migrated && index < count && seen.contains(&index),
|
||||
"legacy market does not identify an observed migrated condition"
|
||||
);
|
||||
let mapped = market["position_condition_id"]
|
||||
.as_str()
|
||||
.context("missing on-chain legacy mapping")?;
|
||||
ensure!(
|
||||
hex_data(mapped, 32)?.eq_ignore_ascii_case(&condition_word(&event, index)),
|
||||
"legacy market points to another condition"
|
||||
);
|
||||
hex_data(
|
||||
market["conditionId"]
|
||||
.as_str()
|
||||
.context("missing legacy CTF condition")?,
|
||||
32,
|
||||
)?;
|
||||
hex_data(
|
||||
market["legacy_ctf_denominator"]
|
||||
.as_str()
|
||||
.context("missing legacy CTF denominator")?,
|
||||
32,
|
||||
)?;
|
||||
}
|
||||
Ok(json!({
|
||||
"observation":obs,
|
||||
"event_id":format!("0x{event}"),
|
||||
"position_manager":POSITION_MANAGER,
|
||||
"module_contract":module,
|
||||
"block":block,
|
||||
"condition_count":count,
|
||||
"reported_count":reported,
|
||||
"results_sum":sum,
|
||||
"legacy_event_id":migrated.then_some(&obs.legacy_event_id),
|
||||
"payout_denominator":DENOMINATOR,
|
||||
"conditions":conditions,
|
||||
}))
|
||||
}
|
||||
|
||||
pub(crate) fn inspect(client: &Client, event: &str, indices: &str) -> Result<Value> {
|
||||
let (event, count) = event_id(event)?;
|
||||
let mut selected = BTreeSet::new();
|
||||
for raw in indices.split(',') {
|
||||
let index: u16 = raw.parse().context("invalid condition index")?;
|
||||
ensure!(index <= count, "condition index is outside this event");
|
||||
ensure!(selected.insert(index), "duplicate condition index");
|
||||
}
|
||||
let block = FinalizedRpc::connect(client)?;
|
||||
let registry = lookup_module(&block, MODULE)?;
|
||||
let module = module_address(®istry, MODULE)?;
|
||||
let counter = |selector| block.call(&module, &format!("0x{selector}{event}"));
|
||||
let condition_count = counter(CONDITION_COUNT)?;
|
||||
let conditions_reported = counter(REPORTED)?;
|
||||
let results_sum = counter(RESULTS_SUM)?;
|
||||
let legacy_event_id = counter(LEGACY_EVENT)?;
|
||||
let conditions = selected
|
||||
.into_iter()
|
||||
.map(|index| {
|
||||
let id = condition_word(&event, index);
|
||||
Ok(Condition {
|
||||
index,
|
||||
effective: block.call(&module, &format!("0x{GET_RESULT}{id}"))?,
|
||||
stored_yes: block.call_with_revert(
|
||||
&module,
|
||||
&format!("0x{STORED_RESULT}{id}{:064x}", 0),
|
||||
"0x",
|
||||
)?,
|
||||
})
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
block.confirm()?;
|
||||
audit(Observation {
|
||||
chain_id: POLYGON_CHAIN_ID,
|
||||
event_id: format!("0x{event}"),
|
||||
block_number: block.number,
|
||||
block_hash: block.hash,
|
||||
registry,
|
||||
condition_count,
|
||||
conditions_reported,
|
||||
results_sum,
|
||||
legacy_event_id,
|
||||
conditions,
|
||||
legacy_catalog: Vec::new(),
|
||||
sources: Vec::new(),
|
||||
transition_tx: None,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn replay(file: &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 NegRisk event observations in file");
|
||||
rows.into_iter()
|
||||
.map(|row| {
|
||||
audit(serde_json::from_value(
|
||||
row.get("observation").cloned().unwrap_or(row),
|
||||
)?)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn replays_reported_derived_and_legacy_pending_results() -> Result<()> {
|
||||
let [before, after, migrated]: [Observation; 3] =
|
||||
serde_json::from_str(include_str!("../fixtures/live-negrisk-resolution.json"))?;
|
||||
let before = audit(before)?;
|
||||
let after = audit(after)?;
|
||||
let migrated = audit(migrated)?;
|
||||
assert_eq!(before["reported_count"], 0);
|
||||
assert_eq!(before["conditions"][3]["source"], "unresolved");
|
||||
assert_eq!(after["reported_count"], 3);
|
||||
assert_eq!(after["conditions"][1]["source"], "stored");
|
||||
assert_eq!(
|
||||
after["conditions"][1]["payout_numerators"],
|
||||
json!([1_000_000, 0])
|
||||
);
|
||||
assert_eq!(after["conditions"][3]["source"], "derived");
|
||||
assert_eq!(
|
||||
after["conditions"][3]["payout_numerators"],
|
||||
json!([0, 1_000_000])
|
||||
);
|
||||
assert_eq!(migrated["reported_count"], 33);
|
||||
assert_eq!(migrated["condition_count"], 37);
|
||||
assert_eq!(migrated["conditions"][1]["source"], "unresolved");
|
||||
assert_eq!(migrated["conditions"][1]["legacy_migration"], true);
|
||||
assert_eq!(migrated["conditions"][5]["source"], "derived");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validates_synthetic_yes_rule_and_rejects_derived_migrated_sibling() -> Result<()> {
|
||||
let event = format!("02{}0002{}", "00".repeat(16), "00".repeat(13));
|
||||
let encoded = |a: u64, b: u64| format!("0x{:064x}{:064x}{a:064x}{b:064x}", 32, 2);
|
||||
let mut condition = Condition {
|
||||
index: 2,
|
||||
effective: encoded(DENOMINATOR, 0),
|
||||
stored_yes: CallOutcome::Revert("0x".into()),
|
||||
};
|
||||
assert_eq!(
|
||||
output_condition(&condition, &event, 2, 2, 0, false)?["source"],
|
||||
"derived"
|
||||
);
|
||||
assert!(output_condition(&condition, &event, 2, 1, 0, false).is_err());
|
||||
condition.index = 1;
|
||||
condition.effective = encoded(0, DENOMINATOR);
|
||||
assert_eq!(
|
||||
output_condition(&condition, &event, 2, 1, DENOMINATOR, false)?["source"],
|
||||
"derived"
|
||||
);
|
||||
assert!(output_condition(&condition, &event, 2, 1, DENOMINATOR, true).is_err());
|
||||
condition.stored_yes = CallOutcome::Return(format!("0x{DENOMINATOR:064x}"));
|
||||
assert!(output_condition(&condition, &event, 2, 1, DENOMINATOR, true).is_err());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1,182 +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};
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct RpcFailure {
|
||||
code: Value,
|
||||
data: Option<String>,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for RpcFailure {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "RPC rejected the request (code {})", self.code)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for RpcFailure {}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub(crate) enum CallOutcome {
|
||||
Return(String),
|
||||
Revert(String),
|
||||
}
|
||||
|
||||
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") {
|
||||
return Err(anyhow::Error::new(RpcFailure {
|
||||
code: error["code"].clone(),
|
||||
data: error["data"].as_str().map(str::to_owned),
|
||||
})
|
||||
.context(format!("{method} RPC failed")));
|
||||
}
|
||||
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 call_with_revert(
|
||||
&self,
|
||||
contract: &str,
|
||||
data: &str,
|
||||
selector: &str,
|
||||
) -> Result<CallOutcome> {
|
||||
match self.call(contract, data) {
|
||||
Ok(value) => Ok(CallOutcome::Return(value)),
|
||||
Err(error) => match error
|
||||
.downcast_ref::<RpcFailure>()
|
||||
.and_then(|failure| failure.data.as_deref())
|
||||
.filter(|data| data.eq_ignore_ascii_case(selector))
|
||||
{
|
||||
Some(data) => Ok(CallOutcome::Revert(data.to_owned())),
|
||||
None => Err(error),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
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,279 +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};
|
||||
|
||||
pub(crate) const POSITION_MANAGER: &str = "0x006F54F7f9A22e0000CC2AB60031000000ae9fEF";
|
||||
// moduleById(uint256), getResult(bytes31)
|
||||
const MODULE_BY_ID: &str = "4d51cdf1";
|
||||
pub(crate) const GET_RESULT: &str = "e4939c77";
|
||||
pub(crate) 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))
|
||||
}
|
||||
|
||||
pub(crate) 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",
|
||||
3 => "0x30000034706C7d8e12009DAB006Be20000c031A8",
|
||||
_ => anyhow::bail!("unsupported PositionManager module"),
|
||||
};
|
||||
ensure!(
|
||||
expected.eq_ignore_ascii_case(&address),
|
||||
"PositionManager registry differs from the published deployment"
|
||||
);
|
||||
Ok(address)
|
||||
}
|
||||
|
||||
pub(crate) 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()?))
|
||||
}
|
||||
|
||||
pub(crate) 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 lookup_module(block: &FinalizedRpc<'_>, module: u8) -> Result<String> {
|
||||
block.call(POSITION_MANAGER, &format!("0x{MODULE_BY_ID}{module:064x}"))
|
||||
}
|
||||
|
||||
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 = lookup_module(&block, module)?;
|
||||
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"}
|
||||
@@ -0,0 +1,16 @@
|
||||
{"op":"fund","id":"rfq-taker-fund","account":"taker","micros":5000000}
|
||||
{"op":"fund","id":"rfq-maker-fund","account":"maker","micros":5000000}
|
||||
{"op":"list","id":"rfq-a","market":"combo-a","rules":"按模拟赛果 A 裁决。"}
|
||||
{"op":"list","id":"rfq-b","market":"combo-b","rules":"按模拟赛果 B 裁决。"}
|
||||
{"op":"prepare_combo","id":"rfq-combo","legs":[{"market":"combo-a","outcome":"YES"},{"market":"combo-b","outcome":"NO"}]}
|
||||
{"op":"request_combo_quote","id":"rfq-buy","combo":"combo:1131b7195fad3ca3c7ae8ebe3739ac78a765c241aa74fccf91236b6caa08cb1e","requester":"taker","direction":"BUY","side":"YES","shares_micros":4000000}
|
||||
{"op":"combo_rfq_open"}
|
||||
{"op":"quote_combo","id":"rfq-mint-quote","rfq":"rfq-buy","maker":"maker","source":"collateral","price_micros":350000,"shares_micros":4000000}
|
||||
{"op":"accept_combo_quote","id":"rfq-buy-accept","rfq":"rfq-buy","requester":"taker","quote":"rfq-mint-quote"}
|
||||
{"op":"respond_combo_quote","id":"rfq-buy-fill","rfq":"rfq-buy","quote":"rfq-mint-quote","maker":"maker","confirm":true}
|
||||
{"op":"combo_rfq","rfq":"rfq-buy","account":"taker"}
|
||||
{"op":"request_combo_quote","id":"rfq-sell","combo":"combo:1131b7195fad3ca3c7ae8ebe3739ac78a765c241aa74fccf91236b6caa08cb1e","requester":"taker","direction":"SELL","side":"YES","shares_micros":1500000}
|
||||
{"op":"quote_combo","id":"rfq-merge-quote","rfq":"rfq-sell","maker":"maker","source":"inventory","price_micros":400000,"shares_micros":1500000}
|
||||
{"op":"accept_combo_quote","id":"rfq-sell-accept","rfq":"rfq-sell","requester":"taker","quote":"rfq-merge-quote"}
|
||||
{"op":"respond_combo_quote","id":"rfq-sell-fill","rfq":"rfq-sell","quote":"rfq-merge-quote","maker":"maker","confirm":true}
|
||||
{"op":"combo","combo":"combo:1131b7195fad3ca3c7ae8ebe3739ac78a765c241aa74fccf91236b6caa08cb1e","account":"taker"}
|
||||
+16
-18
@@ -417,24 +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)
|
||||
|
||||
### PositionManager V2 组合兑付核对
|
||||
|
||||
组合模块保存排序后的 Binary 或 NegRisk Position ID。探针在同一最终确认区块读取登记的腿,向合约查询同样份额的 YES 和 NO 兑付。只在两侧均返回已知的待兑付错误时报告待裁决。一条已裁决腿的兑付为零时,YES 已确定为零,NO 可取得全部对应金额;其余腿仍可处于待裁决状态。其余可兑付情况以合约返回的逐侧金额为准,两个方向分别取整,兑付合计可以少于原份额对应的抵押。[官方合约](https://github.com/Polymarket/polymarket-v2-external/blob/main/src/modules/CombinatorialModule.sol)
|
||||
|
||||
区块 `0x5df5ab2` 的原始记录涵盖一份双侧待裁决的组合和一份已经可兑付的组合。后者按 1000001 微份查询返回 YES 0、NO 1000001 微美元。按链上腿顺序复查,四个兑付权重分别为待裁决、零、待裁决、待裁决。样本来自链上登记交易,仍缺少对应前端及 RFQ 的同盘关联。进一步把链上裁决导入本地账本仍待实现。[原始样本](../crates/venue-probe/fixtures/live-combo-payouts.json)
|
||||
|
||||
### V2 互斥组的推导与迁移例外
|
||||
|
||||
`getResult` 提供有效兑付,原始 `result` getter 可以核对结果是否直接写入。Polygon 区块 `0x5df5c43` 至 `0x5df5c44` 的样本中,组内出现赢家后,合成「其他」的有效权重由空变为 `[0,1000000]`,直接存储仍为空。区块 `0x5df5c62` 的另一组有 37 个真实条件,直接报告 33 个。四个未报告真实条件的有效权重仍为空,合成「其他」已有 NO 兑付。该组的链上旧盘映射将四个条件对应到 Gamma 的 5–3、4–5、5–4 和 5–5 精确比分盘。同一区块的旧 CTF 兑付分母均为 1,V2 仍待裁决。本地组合账本尚未接入这条迁移路径。原生组的未报告输家与通过全 NO 推导「其他」为 YES,仍缺生产样本。[链上样本](../crates/venue-probe/fixtures/live-negrisk-resolution.json) · [官方 NegRisk 逻辑](https://github.com/Polymarket/polymarket-v2-external/blob/main/src/modules/NegRiskModule.sol)
|
||||
|
||||
### Data API 账户持仓价值
|
||||
|
||||
官方 `GET /v2/value` 要求传 user,可选最多 20 个不同 condition。结果是 data 对象,内含 proxy_wallet 和四位小数精度的美元金额。一个无持仓的钱包值为零。官方总额还包括未终结组合的成本基础,指定 condition 时仅统计选中的单盘。资金余额不计入持仓价值。[官方 OpenAPI](https://data-api.polymarket.com/v2/openapi.json)
|
||||
@@ -473,6 +455,22 @@ 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)
|
||||
|
||||
### 组合 RFQ 的状态、预留与成交
|
||||
|
||||
官方请求与报价模型区分 BUY/SELL、YES/NO,以及份额或名义金额。询价有报价提交期限,接受选定报价后,系统向报价方发带 `confirm_by` 的最后确认消息。确认后线上另有执行状态。本地可信 JSONL 实现这一流程,以数据库时钟约束期限。提交、接受和最后确认窗口默认分别为 10、20 和 5 秒,可由模拟请求显式设定。接受报价后立即复核并冻结双方资金或份额。报价可供请求方选择,同价时优先较大数量,再按提交顺序。选择和预留不走公开盘口。[官方报价网关](https://docs.polymarket.com/api-reference/wss/rfq) · [最后确认](https://docs.polymarket.com/api-reference/maker/confirm-or-decline-last-look) · [请求方 SDK](https://github.com/Polymarket/ts-sdk/blob/main/packages/bindings/src/combos/builder-rfq.ts)
|
||||
|
||||
报价的微美元本金是数量乘微美元价格后向下取整。本地份额询价可接受不超请求数量的单个报价,名义金额用于限制 BUY 的预算。按方向与报价资金来源,结算可转让已持有份额、用双方资金拆分、或用互补库存合并。重放[样例](examples/combo-rfq.jsonl),双方分别出资 1.40 和 2.60 生成四对份额。再合并 1.5 对后,报价方和请求方分别收回 0.90 和 0.60,组合抵押剩 2.50。相同确认请求重放原成交。拒绝和到期释放全部预留,重启后检查已到期请求。
|
||||
|
||||
当前交付采用本地单报价选中、无手续费和同步结算。外场签名、报价聚合、费率、线上限额、联网做市商的报价投递和链上异步执行还有待接入。
|
||||
|
||||
### 互斥适配器按量赎回
|
||||
|
||||
当前 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