Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
07d15e573e | ||
|
|
1cc667542b | ||
|
|
d0fc875f88 |
No files matched your search
Generated
+49
@@ -2,6 +2,12 @@
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "adler2"
|
||||
version = "2.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
|
||||
|
||||
[[package]]
|
||||
name = "ahash"
|
||||
version = "0.8.15"
|
||||
@@ -117,6 +123,7 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"exchange",
|
||||
"flate2",
|
||||
"percent-encoding",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -143,6 +150,15 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crc32fast"
|
||||
version = "1.5.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fd9ae8fcb3ea71b0b26338b4ffb13006bb175de8fd07921089a906ce7e5e6945"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crypto-common"
|
||||
version = "0.1.7"
|
||||
@@ -231,6 +247,17 @@ version = "0.1.16"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3e44f110d1777dc6559a51e7d45083945ded4f1bf3305494350f693b6d20b9c8"
|
||||
|
||||
[[package]]
|
||||
name = "flate2"
|
||||
version = "1.1.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4"
|
||||
dependencies = [
|
||||
"crc32fast",
|
||||
"miniz_oxide",
|
||||
"zlib-rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "form_urlencoded"
|
||||
version = "1.2.3"
|
||||
@@ -647,6 +674,16 @@ version = "2.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
||||
|
||||
[[package]]
|
||||
name = "miniz_oxide"
|
||||
version = "0.9.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c"
|
||||
dependencies = [
|
||||
"adler2",
|
||||
"simd-adler32",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "mio"
|
||||
version = "1.2.5"
|
||||
@@ -1058,6 +1095,12 @@ version = "2.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
|
||||
|
||||
[[package]]
|
||||
name = "simd-adler32"
|
||||
version = "0.3.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
|
||||
|
||||
[[package]]
|
||||
name = "slab"
|
||||
version = "0.4.12"
|
||||
@@ -1692,6 +1735,12 @@ dependencies = [
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zlib-rs"
|
||||
version = "0.6.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "aa76918995d776d9dd34d371030be228d021137449771493d56e29f77e4148ac"
|
||||
|
||||
[[package]]
|
||||
name = "zmij"
|
||||
version = "1.0.23"
|
||||
|
||||
@@ -12,3 +12,4 @@ tungstenite = "0.28"
|
||||
tiny_http = "0.12"
|
||||
serde_urlencoded = "0.7"
|
||||
percent-encoding = "2"
|
||||
flate2 = "1"
|
||||
@@ -338,6 +338,14 @@ sequenceDiagram
|
||||
H-->>C: 200 data 数组,未找到返回空数组
|
||||
```
|
||||
|
||||
### 查询历史份额
|
||||
|
||||
JSONL 命令 `position_balances_at` 接受 `account` 和 UTC 毫秒 `before_ms`,返回该时点之前各结果的总份额,包含挂卖预留。数据库启用历史时登记已有余额作为起点。返回的 `history_start_ms` 界定可查范围。
|
||||
|
||||
### 日终持仓快照
|
||||
|
||||
GET /v2/positions/snapshot 使用 `user` 或 `user_address` 携带钱包地址,再传 UTC 日期 `date=YYYY-MM-DD`。请求头须包含 `Accept-Encoding: gzip`。首屏带全量汇总,续页使用同一个钱包和 `pagination.next_cursor`。本地按连接来源 IP 限制首屏在 30 秒内只能成功开始一次,续页不限。闭日按数据库历史起点及本地午夜后一小时确定。成本使用切点前的成交、拆分、合并和兑付流水重建。遇到缺少可核验成本的仓位,成本返回零。
|
||||
|
||||
### 查询持仓价值
|
||||
|
||||
`GET /v2/value?user=alice&condition=e` 返回该账户在市场 e 的持仓价值,单位为模拟美元。使用已登记的本地账户名或 20 字节钱包地址。省略 condition 查询所有已持有市场。无持仓的钱包返回零,仅有现金的账户也返回零。
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
mod market_http;
|
||||
mod market_ws;
|
||||
mod snapshot_http;
|
||||
mod stream;
|
||||
mod subscriptions;
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use crate::snapshot_http;
|
||||
use anyhow::Result;
|
||||
use exchange::{Exchange, HistoryError};
|
||||
use percent_encoding::percent_decode_str;
|
||||
@@ -323,9 +324,16 @@ fn clarifications(engine: &Mutex<Exchange>, query: &str) -> Reply {
|
||||
Ok(Value::Array(rows))
|
||||
}
|
||||
|
||||
fn respond(mut req: Request, engine: &Mutex<Exchange>) -> std::io::Result<()> {
|
||||
fn respond(
|
||||
mut req: Request,
|
||||
engine: &Mutex<Exchange>,
|
||||
snapshots: &snapshot_http::Starts,
|
||||
) -> std::io::Result<()> {
|
||||
let (path, params) = req.url().split_once('?').unwrap_or((req.url(), ""));
|
||||
let mut allow = None;
|
||||
if path == "/v2/positions/snapshot" {
|
||||
return snapshot_http::respond(req, engine, snapshots);
|
||||
}
|
||||
if req.method() == &Method::Get
|
||||
&& matches!(
|
||||
path,
|
||||
@@ -564,11 +572,12 @@ fn send(req: Request, status: u16, body: Value, allow: Option<&str>) -> std::io:
|
||||
pub(crate) fn serve(engine: Exchange, listener: TcpListener) -> Result<()> {
|
||||
let server = Server::from_listener(listener, None).map_err(anyhow::Error::from_boxed)?;
|
||||
let engine = Mutex::new(engine);
|
||||
let snapshots = snapshot_http::Starts::default();
|
||||
thread::scope(|scope| {
|
||||
for _ in 0..4 {
|
||||
scope.spawn(|| {
|
||||
for req in server.incoming_requests() {
|
||||
if let Err(err) = respond(req, &engine) {
|
||||
if let Err(err) = respond(req, &engine, &snapshots) {
|
||||
eprintln!("market HTTP response: {err}");
|
||||
}
|
||||
}
|
||||
@@ -861,6 +870,8 @@ mod tests {
|
||||
Some(json!({"data":[],"pagination":{"has_more":false,"next_cursor":null,"offset":0,"limit":10000}}))),
|
||||
("GET","/v2/prices-history?token_id=7&interval=1h",String::new(),400,None),
|
||||
("POST","/v2/prices-history",String::new(),405,None),
|
||||
("GET","/v2/positions/snapshot",String::new(),406,None),
|
||||
("POST","/v2/positions/snapshot",String::new(),405,None),
|
||||
("GET", "/books", String::new(), 405, None),
|
||||
("POST", "/order", "{}".into(), 404, None),
|
||||
];
|
||||
@@ -872,7 +883,7 @@ mod tests {
|
||||
.recv_timeout(Duration::from_secs(5))
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
respond(req, &db).unwrap();
|
||||
respond(req, &db, &snapshot_http::Starts::default()).unwrap();
|
||||
}
|
||||
});
|
||||
for (method, path, body, status, expected) in cases {
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
use exchange::{Exchange, MarketDataError, SnapshotQuery};
|
||||
use flate2::{write::GzEncoder, Compression};
|
||||
use serde_json::{json, Value};
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
io::{self, Write},
|
||||
net::IpAddr,
|
||||
sync::Mutex,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use tiny_http::{Header, Method, Request, Response};
|
||||
|
||||
const WINDOW: Duration = Duration::from_secs(30);
|
||||
pub(crate) type Starts = Mutex<HashMap<IpAddr, Instant>>;
|
||||
|
||||
fn accepts_gzip(req: &Request) -> bool {
|
||||
req.headers()
|
||||
.iter()
|
||||
.filter(|h| h.field.equiv("Accept-Encoding"))
|
||||
.any(|h| {
|
||||
h.value.as_str().split(',').any(|coding| {
|
||||
let mut parts = coding.split(';').map(str::trim);
|
||||
parts
|
||||
.next()
|
||||
.is_some_and(|name| name.eq_ignore_ascii_case("gzip"))
|
||||
&& parts.all(|part| {
|
||||
let Some((name, value)) = part.split_once('=') else {
|
||||
return false;
|
||||
};
|
||||
name.trim().eq_ignore_ascii_case("q")
|
||||
&& value
|
||||
.trim()
|
||||
.parse::<f32>()
|
||||
.is_ok_and(|q| q > 0.0 && q <= 1.0)
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn error(
|
||||
req: Request,
|
||||
status: u16,
|
||||
code: &str,
|
||||
message: &str,
|
||||
header: Option<Header>,
|
||||
) -> io::Result<()> {
|
||||
let body = json!({"code":code,"error":message,"retryable":matches!(status,429|503)});
|
||||
let mut response = Response::from_data(body.to_string().into_bytes())
|
||||
.with_status_code(status)
|
||||
.with_header(Header::from_bytes("Content-Type", "application/json").unwrap())
|
||||
.with_header(Header::from_bytes("Vary", "Accept-Encoding").unwrap());
|
||||
if let Some(header) = header {
|
||||
response.add_header(header);
|
||||
}
|
||||
req.respond(response)
|
||||
}
|
||||
|
||||
pub(crate) fn respond(req: Request, engine: &Mutex<Exchange>, starts: &Starts) -> io::Result<()> {
|
||||
if req.method() != &Method::Get {
|
||||
return error(
|
||||
req,
|
||||
405,
|
||||
"method_not_allowed",
|
||||
"Method not allowed",
|
||||
Header::from_bytes("Allow", "GET").ok(),
|
||||
);
|
||||
}
|
||||
if !accepts_gzip(&req) {
|
||||
return error(
|
||||
req,
|
||||
406,
|
||||
"not_acceptable",
|
||||
"Accept-Encoding: gzip is required",
|
||||
None,
|
||||
);
|
||||
}
|
||||
let params = req.url().split_once('?').map_or("", |(_, params)| params);
|
||||
let query: SnapshotQuery = match serde_urlencoded::from_str(params) {
|
||||
Ok(query) => query,
|
||||
Err(_) => {
|
||||
return error(
|
||||
req,
|
||||
400,
|
||||
"invalid_request",
|
||||
"invalid query parameters",
|
||||
None,
|
||||
)
|
||||
}
|
||||
};
|
||||
let ip = if query.is_first_page() {
|
||||
req.remote_addr().map(|addr| addr.ip())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut walks = starts
|
||||
.lock()
|
||||
.map_err(|_| io::Error::other("snapshot rate limit unavailable"))?;
|
||||
let now = Instant::now();
|
||||
if let Some(ip) = ip {
|
||||
walks.retain(|_, at| now.duration_since(*at) < WINDOW);
|
||||
if let Some(at) = walks.get(&ip) {
|
||||
let wait = WINDOW
|
||||
.saturating_sub(now.duration_since(*at))
|
||||
.as_millis()
|
||||
.div_ceil(1000);
|
||||
drop(walks);
|
||||
return error(
|
||||
req,
|
||||
429,
|
||||
"rate_limited",
|
||||
"snapshot first-page rate limit",
|
||||
Header::from_bytes("Retry-After", wait.to_string()).ok(),
|
||||
);
|
||||
}
|
||||
}
|
||||
let result = engine
|
||||
.lock()
|
||||
.map_err(|_| MarketDataError::Unavailable)
|
||||
.and_then(|engine| engine.public_position_snapshot(query));
|
||||
if let (Some(ip), Ok(_)) = (ip, &result) {
|
||||
walks.insert(ip, Instant::now());
|
||||
}
|
||||
drop(walks);
|
||||
match result {
|
||||
Ok(data) => gzip(req, &data),
|
||||
Err(MarketDataError::Invalid(message)) => {
|
||||
error(req, 400, "invalid_request", &message, None)
|
||||
}
|
||||
Err(MarketDataError::Unavailable) => error(
|
||||
req,
|
||||
503,
|
||||
"unavailable",
|
||||
"snapshot unavailable",
|
||||
Header::from_bytes("Retry-After", "1").ok(),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
fn gzip(req: Request, data: &Value) -> io::Result<()> {
|
||||
let mut gzip = GzEncoder::new(Vec::new(), Compression::default());
|
||||
gzip.write_all(data.to_string().as_bytes())?;
|
||||
let response = Response::from_data(gzip.finish()?)
|
||||
.with_header(Header::from_bytes("Content-Type", "application/json").unwrap())
|
||||
.with_header(Header::from_bytes("Content-Encoding", "gzip").unwrap())
|
||||
.with_header(Header::from_bytes("Cache-Control", "public, max-age=86400").unwrap())
|
||||
.with_header(Header::from_bytes("Vary", "Accept-Encoding").unwrap());
|
||||
req.respond(response)
|
||||
}
|
||||
@@ -223,6 +223,48 @@ sequenceDiagram
|
||||
E-->>C: 已退出的份额移入 CLOSED,可领取金额归零
|
||||
```
|
||||
|
||||
## 历史持仓余额
|
||||
|
||||
`{"op":"position_balances_at","account":"alice","before_ms":1800000000000}` 查询指定毫秒之前最后确认的各结果份额。查询上限不包含 `before_ms`。数据库首次启用历史记录时,把已有可用份额与挂卖预留一起作为余额起点,返回 `history_start_ms`。更早或未来的查询会报错。
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
E["lib.rs 与 expiry.rs"] --> H["position_balance_history.rs"]
|
||||
H --> S["position_balance_history_schema.sql"]
|
||||
H --> F["position_balance_history_flush.sql"]
|
||||
F --> P["position_units"]
|
||||
```
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as JSONL 客户端
|
||||
participant E as Exchange
|
||||
participant D as SQLite
|
||||
C->>E: 提交会影响余额的命令
|
||||
E->>D: 更新份额和订单,标记受影响的持仓
|
||||
E->>D: 写入变动后的总份额,并与命令同事务提交
|
||||
C->>E: position_balances_at,指定账户和 before_ms
|
||||
E->>D: 每个结果取切点之前最后一条余额
|
||||
E-->>C: 查询切点、历史覆盖起点和结果份额
|
||||
```
|
||||
|
||||
### 公开日终快照
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as 客户端
|
||||
participant H as snapshot_http.rs
|
||||
participant E as portfolio/snapshot.rs
|
||||
participant D as SQLite
|
||||
C->>H: GET /v2/positions/snapshot,wallet、date 和 gzip
|
||||
H->>E: 校验日期和钱包,按 UTC 次日零点取余额
|
||||
E->>D: 读取切点之前的裁决、行情及历史流水
|
||||
D-->>E: 份额、行情与按共同写入序号排序的成交及钱包操作
|
||||
E->>E: 重放成交、拆分、合并及兑付,与历史份额核对
|
||||
E-->>H: 首屏总额、当页持仓和签名游标
|
||||
H-->>C: gzip 响应
|
||||
```
|
||||
|
||||
## GTD 到期
|
||||
|
||||
```mermaid
|
||||
|
||||
@@ -261,6 +261,10 @@ pub(crate) enum Query {
|
||||
market: String,
|
||||
},
|
||||
Positions(crate::portfolio::Filter),
|
||||
PositionBalancesAt {
|
||||
account: String,
|
||||
before_ms: i64,
|
||||
},
|
||||
OpenInterest(crate::open_interest::Request),
|
||||
Holders(crate::holders::Request),
|
||||
Balance {
|
||||
@@ -329,6 +333,9 @@ impl Query {
|
||||
Self::Holders(request) => request.read(db),
|
||||
Self::OpenInterest(request) => request.read(db),
|
||||
Self::Positions(filter) => filter.read(db),
|
||||
Self::PositionBalancesAt { account, before_ms } => {
|
||||
crate::position_balance_history::read(db, &account, before_ms)
|
||||
}
|
||||
Self::PublicTrades(request) => request.read(db),
|
||||
Self::Trades(filter) => filter.read(db),
|
||||
Self::OpenOrders(filter) => filter.read(db),
|
||||
|
||||
@@ -51,6 +51,7 @@ pub(crate) fn transaction(
|
||||
crate::heartbeat::expire(&write)?;
|
||||
crate::quotes::flush(&write)?;
|
||||
crate::depth_feed::flush(&write)?;
|
||||
crate::position_balance_history::flush(&write)?;
|
||||
write.commit()?;
|
||||
}
|
||||
}
|
||||
@@ -34,6 +34,7 @@ mod minimum_size;
|
||||
mod neg_risk;
|
||||
mod open_interest;
|
||||
mod portfolio;
|
||||
mod position_balance_history;
|
||||
mod prices_history;
|
||||
mod public_trades;
|
||||
mod quotes;
|
||||
@@ -54,6 +55,7 @@ pub use gamma_directory::DirectoryKey;
|
||||
pub use gamma_list::DirectoryResource;
|
||||
pub use open_interest::InterestQuery;
|
||||
pub use portfolio::http::ValueQuery;
|
||||
pub use portfolio::snapshot::SnapshotQuery;
|
||||
pub use prices_history::http::HistoryQuery;
|
||||
pub use prices_history::legacy::ClobHistoryQuery;
|
||||
pub use public_trades::http::TradeQuery;
|
||||
@@ -135,6 +137,14 @@ impl Exchange {
|
||||
db.execute_batch(include_str!("valuation_schema.sql"))?;
|
||||
}
|
||||
lots::migrate(&mut db)?;
|
||||
let economics_order_ready: bool = db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='trigger' AND name='cost_order_wallet')",
|
||||
[], |r| r.get(0),
|
||||
)?;
|
||||
if !economics_order_ready {
|
||||
db.execute_batch(include_str!("portfolio/economics_schema.sql"))?;
|
||||
}
|
||||
position_balance_history::install(&mut db)?;
|
||||
let snapshot_ready: bool = db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='table' AND name='book_snapshot_times')", [], |r| r.get(0))?;
|
||||
if !snapshot_ready {
|
||||
@@ -239,6 +249,7 @@ impl Exchange {
|
||||
| "book"
|
||||
| "open_orders"
|
||||
| "positions"
|
||||
| "position_balances_at"
|
||||
| "holders"
|
||||
| "balance"
|
||||
| "portfolio_value"
|
||||
@@ -343,6 +354,7 @@ impl Exchange {
|
||||
params![id, payload.to_string(), result.to_string()],
|
||||
)?;
|
||||
depth_feed::flush(&tx)?;
|
||||
position_balance_history::flush(&tx)?;
|
||||
let changes = self.books.changes(&tx)?;
|
||||
tx.commit()?;
|
||||
self.books.apply(changes);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
pub(crate) mod http;
|
||||
mod protocol;
|
||||
pub(crate) mod snapshot;
|
||||
|
||||
use crate::{
|
||||
inventory::{decimal, UNIT},
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
BEGIN IMMEDIATE;
|
||||
-- Trade executions and wallet movements have independent ID sequences.
|
||||
-- Record their shared write order so a sale and a split in the same
|
||||
-- millisecond can be replayed in the order in which they committed.
|
||||
CREATE TABLE IF NOT EXISTS position_economics_order (
|
||||
seq INTEGER PRIMARY KEY,
|
||||
source INTEGER NOT NULL,
|
||||
record INTEGER NOT NULL,
|
||||
UNIQUE(source,record)
|
||||
);
|
||||
CREATE TRIGGER IF NOT EXISTS cost_order_fill AFTER INSERT ON fills BEGIN
|
||||
INSERT INTO position_economics_order(source,record) VALUES(1,NEW.seq);
|
||||
END;
|
||||
CREATE TRIGGER IF NOT EXISTS cost_order_paired AFTER INSERT ON paired_fills BEGIN
|
||||
INSERT INTO position_economics_order(source,record) VALUES(1,NEW.seq);
|
||||
END;
|
||||
CREATE TRIGGER IF NOT EXISTS cost_order_wallet AFTER INSERT ON wallet_movements
|
||||
WHEN NEW.kind IN ('SPLIT','MERGE','REDEEM','CONVERSION') BEGIN
|
||||
INSERT INTO position_economics_order(source,record) VALUES(0,NEW.id);
|
||||
END;
|
||||
COMMIT;
|
||||
@@ -0,0 +1,281 @@
|
||||
use crate::{
|
||||
assets,
|
||||
inventory::{decimal, UNIT},
|
||||
validation::hex_id,
|
||||
Exchange, MarketDataError,
|
||||
};
|
||||
use data_encoding::BASE64URL_NOPAD;
|
||||
use hmac::{Hmac, Mac};
|
||||
use rusqlite::{params, Connection};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
use sha2::Sha256;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct SnapshotQuery {
|
||||
#[serde(alias = "user_address")]
|
||||
user: String,
|
||||
date: Option<String>,
|
||||
limit: Option<usize>,
|
||||
cursor: Option<String>,
|
||||
}
|
||||
|
||||
impl SnapshotQuery {
|
||||
pub fn is_first_page(&self) -> bool {
|
||||
self.cursor.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct Cursor {
|
||||
wallet: String,
|
||||
date: String,
|
||||
limit: usize,
|
||||
offset: usize,
|
||||
}
|
||||
|
||||
fn invalid(message: &str) -> MarketDataError {
|
||||
MarketDataError::Invalid(message.to_owned())
|
||||
}
|
||||
|
||||
impl Cursor {
|
||||
fn mac(db: &Connection) -> Result<Hmac<Sha256>, MarketDataError> {
|
||||
let key: Vec<u8> = db.query_row(
|
||||
"SELECT secret FROM trade_cursor_key WHERE singleton=1",
|
||||
[],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
let mut mac =
|
||||
Hmac::<Sha256>::new_from_slice(&key).map_err(|_| MarketDataError::Unavailable)?;
|
||||
mac.update(b"eventbook:/v2/positions/snapshot:v1\0");
|
||||
Ok(mac)
|
||||
}
|
||||
|
||||
fn read(db: &Connection, text: &str) -> Result<Self, MarketDataError> {
|
||||
let bad = || invalid("invalid snapshot cursor");
|
||||
if text.len() > 2048 {
|
||||
return Err(bad());
|
||||
}
|
||||
let bytes = BASE64URL_NOPAD.decode(text.as_bytes()).map_err(|_| bad())?;
|
||||
let split = bytes.len().checked_sub(32).ok_or_else(bad)?;
|
||||
let (data, signature) = bytes.split_at(split);
|
||||
let mut mac = Self::mac(db)?;
|
||||
mac.update(data);
|
||||
mac.verify_slice(signature).map_err(|_| bad())?;
|
||||
serde_json::from_slice(data).map_err(|_| bad())
|
||||
}
|
||||
|
||||
fn write(&self, db: &Connection) -> Result<String, MarketDataError> {
|
||||
let mut data = serde_json::to_vec(self).map_err(|_| MarketDataError::Unavailable)?;
|
||||
let mut mac = Self::mac(db)?;
|
||||
mac.update(&data);
|
||||
data.extend_from_slice(&mac.finalize().into_bytes());
|
||||
Ok(BASE64URL_NOPAD.encode(&data))
|
||||
}
|
||||
}
|
||||
|
||||
fn cutoff(db: &Connection, date: &str) -> Result<(i64, String), MarketDataError> {
|
||||
let (start, end, point, cut): (String, String, Option<i64>, Option<String>) = db.query_row(
|
||||
"SELECT date(at_ms/1000.0,'unixepoch'),date('now','-1 hour','-1 day'),
|
||||
CASE WHEN date(?1)=?1 THEN unixepoch(?1,'+1 day')*1000 END,
|
||||
CASE WHEN date(?1)=?1 THEN strftime('%Y-%m-%dT%H:%M:%SZ',?1,'+1 day') END
|
||||
FROM position_balance_history_start WHERE singleton=1",
|
||||
[date],
|
||||
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)),
|
||||
)?;
|
||||
match (point, cut) {
|
||||
(Some(point), Some(cut)) if (start.as_str()..=end.as_str()).contains(&date) => {
|
||||
Ok((point, cut))
|
||||
}
|
||||
_ => Err(MarketDataError::Invalid(format!(
|
||||
"date must be a closed UTC day in {start}..={end}"
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
fn basis(
|
||||
db: &Connection,
|
||||
wallet: &str,
|
||||
market: &str,
|
||||
outcome: &str,
|
||||
cut: i64,
|
||||
expected: i64,
|
||||
) -> Result<(i128, i128), MarketDataError> {
|
||||
let mut stmt = db.prepare_cached(include_str!("snapshot_basis.sql"))?;
|
||||
let mut rows = stmt.query(params![wallet, market, outcome, cut])?;
|
||||
let mut held = 0i128;
|
||||
let mut cost = 0i128;
|
||||
while let Some(row) = rows.next()? {
|
||||
if row.get::<_, bool>(3)? {
|
||||
return Ok((0, 0));
|
||||
}
|
||||
let operation: String = row.get(0)?;
|
||||
if operation == "FULL_REDEEM" {
|
||||
held = 0;
|
||||
cost = 0;
|
||||
continue;
|
||||
}
|
||||
let Some(qty) = row.get::<_, Option<i64>>(1)?.map(i128::from) else {
|
||||
return Ok((0, 0));
|
||||
};
|
||||
let cash = i128::from(row.get::<_, i64>(2)?);
|
||||
match operation.as_str() {
|
||||
"buy" if qty > 0 && cash >= 0 => {
|
||||
held += qty;
|
||||
cost += cash;
|
||||
}
|
||||
"SPLIT" if qty > 0 && cash == -qty => {
|
||||
let yes = qty / 2;
|
||||
held += qty;
|
||||
cost += if outcome == "YES" { yes } else { qty - yes };
|
||||
}
|
||||
"sell" | "MERGE" | "REDEEM" if qty > 0 && qty <= held => {
|
||||
cost -= cost.checked_mul(qty).ok_or(MarketDataError::Unavailable)? / held;
|
||||
held -= qty;
|
||||
}
|
||||
"REDEEM" if qty == 0 => {}
|
||||
_ => return Ok((0, 0)),
|
||||
}
|
||||
}
|
||||
if held == 0 || held != i128::from(expected) {
|
||||
return Ok((0, 0));
|
||||
}
|
||||
let avg = cost
|
||||
.checked_mul(i128::from(UNIT))
|
||||
.ok_or(MarketDataError::Unavailable)?
|
||||
/ held;
|
||||
Ok((cost, avg))
|
||||
}
|
||||
|
||||
impl Exchange {
|
||||
pub fn public_position_snapshot(&self, query: SnapshotQuery) -> Result<Value, MarketDataError> {
|
||||
if !hex_id(&query.user, 40)
|
||||
|| super::protocol::CONTRACTS
|
||||
.iter()
|
||||
.any(|c| c.eq_ignore_ascii_case(&query.user))
|
||||
{
|
||||
return Err(invalid("invalid user wallet"));
|
||||
}
|
||||
let wallet = query.user.to_ascii_lowercase();
|
||||
let tx = self.db.unchecked_transaction()?;
|
||||
let first = query.cursor.is_none();
|
||||
let mut cursor = if let Some(text) = query.cursor {
|
||||
let c = Cursor::read(&tx, &text)?;
|
||||
if c.wallet != wallet || query.date.as_ref().is_some_and(|date| date != &c.date) {
|
||||
return Err(invalid("snapshot cursor wallet or date does not match"));
|
||||
}
|
||||
c
|
||||
} else {
|
||||
Cursor {
|
||||
wallet,
|
||||
date: query.date.ok_or_else(|| invalid("date is required"))?,
|
||||
limit: query.limit.unwrap_or(100),
|
||||
offset: 0,
|
||||
}
|
||||
};
|
||||
if cursor.limit > 1000 {
|
||||
return Err(invalid("snapshot limit exceeds 1000"));
|
||||
}
|
||||
let (point, cut) = cutoff(&tx, &cursor.date)?;
|
||||
let mut data = Vec::new();
|
||||
let mut totals = [0i128; 3];
|
||||
let mut basis_total = 0i128;
|
||||
let mut positions = 0;
|
||||
{
|
||||
let mut stmt = tx.prepare_cached(include_str!("snapshot_positions.sql"))?;
|
||||
let mut rows = stmt.query(params![cursor.wallet, point])?;
|
||||
while let Some(row) = rows.next()? {
|
||||
let i = positions;
|
||||
positions += 1;
|
||||
let in_page = i >= cursor.offset && i - cursor.offset < cursor.limit;
|
||||
if !first && !in_page {
|
||||
continue;
|
||||
}
|
||||
let market: String = row.get(0)?;
|
||||
let outcome: String = row.get(1)?;
|
||||
let size: i64 = row.get(2)?;
|
||||
let settled: Option<i64> = row.get(7)?;
|
||||
let winner: Option<String> = row.get(8)?;
|
||||
let payout = winner.as_deref().map(|winner| {
|
||||
if winner == "VOID" {
|
||||
UNIT / 2
|
||||
} else {
|
||||
i64::from(winner == outcome) * UNIT
|
||||
}
|
||||
});
|
||||
let quote_time: Option<i64> = row.get(9)?;
|
||||
let trade_time: Option<i64> = row.get(12)?;
|
||||
let mark = if quote_time > trade_time {
|
||||
let bid: i64 = row.get(10)?;
|
||||
let ask: i64 = row.get(11)?;
|
||||
let yes = ((ask + bid) * 50).clamp(0, UNIT);
|
||||
Some(if outcome == "YES" { yes } else { UNIT - yes })
|
||||
} else {
|
||||
row.get::<_, Option<i64>>(13)?
|
||||
.map(|price| price.clamp(0, UNIT))
|
||||
};
|
||||
let frozen = settled.filter(|_| payout == Some(0));
|
||||
let basis_size = match frozen {
|
||||
Some(settlement) => tx.query_row(
|
||||
"WITH balances AS (
|
||||
SELECT shares_micros, ROW_NUMBER() OVER (
|
||||
PARTITION BY account ORDER BY at_ms DESC,seq DESC) AS n
|
||||
FROM position_balance_history
|
||||
WHERE account COLLATE NOCASE=?1 AND market=?2 AND outcome=?3 AND at_ms<?4
|
||||
)
|
||||
SELECT COALESCE(SUM(shares_micros),0) FROM balances WHERE n=1",
|
||||
params![cursor.wallet,market,outcome,settlement],
|
||||
|row| row.get(0),
|
||||
)?,
|
||||
None => size,
|
||||
};
|
||||
let (cost, avg) = basis(
|
||||
&tx,
|
||||
&cursor.wallet,
|
||||
&market,
|
||||
&outcome,
|
||||
frozen.unwrap_or(point),
|
||||
basis_size,
|
||||
)?;
|
||||
let (price, source, bucket) = if let Some(price) = payout {
|
||||
(i128::from(price), "settlement", 2)
|
||||
} else if let Some(price) = mark {
|
||||
(i128::from(price), "mark", 1)
|
||||
} else {
|
||||
(avg, "basis", 0)
|
||||
};
|
||||
let value = if bucket == 0 {
|
||||
cost
|
||||
} else {
|
||||
price * i128::from(size) / i128::from(UNIT)
|
||||
};
|
||||
totals[bucket] += value;
|
||||
basis_total += cost;
|
||||
if in_page {
|
||||
data.push(json!({
|
||||
"asset":assets::id(&market,&outcome),
|
||||
"condition_id":market,"module":0,"outcome":row.get::<_,String>(5)?,
|
||||
"title":row.get::<_,String>(3)?,"slug":row.get::<_,String>(4)?,
|
||||
"event_slug":row.get::<_,Option<String>>(6)?,
|
||||
"size":decimal(size.into(),UNIT),"price":decimal(price,UNIT),
|
||||
"avg_price":decimal(avg,UNIT),"cost_basis":decimal(cost,UNIT),
|
||||
"value":decimal(value,UNIT),"price_source":source
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
let offset = cursor.offset;
|
||||
cursor.offset += data.len();
|
||||
let has_more = cursor.limit > 0 && cursor.offset < positions;
|
||||
let next = has_more.then(|| cursor.write(&tx)).transpose()?;
|
||||
let mut response = json!({"data":data,"pagination":{"limit":cursor.limit,"offset":offset,"has_more":has_more,"next_cursor":next}});
|
||||
if first {
|
||||
response["summary"] = json!({"date":cursor.date,"cut":cut,"closed_block":null,"positions":positions,
|
||||
"cost_basis":decimal(basis_total,UNIT),"value":decimal(totals.iter().sum(),UNIT),
|
||||
"value_by_source":{"basis":decimal(totals[0],UNIT),"mark":decimal(totals[1],UNIT),"settlement":decimal(totals[2],UNIT)}});
|
||||
}
|
||||
tx.commit()?;
|
||||
Ok(response)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
WITH legs AS (
|
||||
SELECT 1 AS source,t.execution AS record,t.order_seq AS leg,t.at_ms,
|
||||
t.side AS operation,t.quantity*10000 AS shares,t.quantity*t.price AS cash
|
||||
FROM wallet_trade_legs t
|
||||
WHERE t.account COLLATE NOCASE=?1 AND t.market=?2 AND t.outcome=?3
|
||||
AND (t.at_ms IS NULL OR t.at_ms<?4)
|
||||
UNION ALL
|
||||
SELECT 0,w.id,0,w.at_ms,
|
||||
CASE WHEN w.kind='REDEEM' AND json_extract(r.response,'$.amounts_micros') IS NULL
|
||||
THEN 'FULL_REDEEM' ELSE w.kind END,
|
||||
CASE WHEN w.kind='REDEEM' THEN json_extract(r.response,
|
||||
CASE ?3 WHEN 'YES' THEN '$.amounts_micros[0]' ELSE '$.amounts_micros[1]' END)
|
||||
ELSE COALESCE(p.shares_micros,w.shares*1000000) END,
|
||||
COALESCE(p.cash_micros,w.cash_delta*10000)
|
||||
FROM wallet_movements w
|
||||
LEFT JOIN precise_movements p ON p.request_id=w.request_id AND p.account=w.account
|
||||
JOIN requests r ON r.id=w.request_id
|
||||
WHERE w.account COLLATE NOCASE=?1 AND w.market=?2 AND w.kind IN ('SPLIT','MERGE','REDEEM')
|
||||
AND (w.at_ms IS NULL OR w.at_ms<?4)
|
||||
UNION ALL
|
||||
SELECT 0,w.id,0,w.at_ms,'CONVERSION',NULL,0
|
||||
FROM wallet_movements w JOIN requests r ON r.id=w.request_id
|
||||
WHERE w.kind='CONVERSION' AND (w.at_ms IS NULL OR w.at_ms<?4) AND (
|
||||
(w.account COLLATE NOCASE=?1 AND ?2 IN (
|
||||
SELECT value FROM json_each(r.response, CASE ?3 WHEN 'YES' THEN '$.yes_markets' ELSE '$.no_markets' END)
|
||||
)) OR (?3='YES' AND json_extract(r.response,'$.conversion_fee.yes_micros_per_market')>0
|
||||
AND json_extract(r.response,'$.conversion_fee.vault') COLLATE NOCASE=?1
|
||||
AND ?2 IN (SELECT value FROM json_each(r.response,'$.yes_markets')))
|
||||
)
|
||||
), ordered AS (
|
||||
SELECT l.*,o.seq AS write_seq
|
||||
FROM legs l LEFT JOIN position_economics_order o ON o.source=l.source AND o.record=l.record
|
||||
)
|
||||
-- The pre-journal records lack a shared order within a millisecond.
|
||||
SELECT operation,shares,cash,
|
||||
at_ms IS NULL OR (write_seq IS NULL AND
|
||||
MIN(source) OVER legacy_tick<>MAX(source) OVER legacy_tick) AS ambiguous
|
||||
FROM ordered
|
||||
WINDOW legacy_tick AS (PARTITION BY write_seq IS NULL,at_ms)
|
||||
ORDER BY write_seq IS NOT NULL,CASE WHEN write_seq IS NULL THEN at_ms END,
|
||||
write_seq,source,record,leg
|
||||
@@ -0,0 +1,31 @@
|
||||
WITH holdings AS (
|
||||
SELECT account,market,outcome,shares_micros,
|
||||
ROW_NUMBER() OVER (PARTITION BY account,market,outcome ORDER BY at_ms DESC,seq DESC) AS n
|
||||
FROM position_balance_history
|
||||
WHERE account COLLATE NOCASE=?1 AND at_ms<?2
|
||||
), totals AS (
|
||||
SELECT market,outcome,SUM(shares_micros) AS size FROM holdings WHERE n=1
|
||||
GROUP BY market,outcome HAVING SUM(shares_micros)>100000
|
||||
)
|
||||
SELECT p.market,p.outcome,p.size,w.question,w.slug,
|
||||
CASE p.outcome WHEN 'YES' THEN w.yes_label ELSE w.no_label END,
|
||||
event.slug,settlement.at_ms,settlement.winner,q.at_ms,q.yes_bid,q.yes_ask,
|
||||
trade.at_ms,trade.price
|
||||
FROM totals p
|
||||
JOIN market_wire_metadata w ON w.market=p.market
|
||||
LEFT JOIN listed_markets l ON l.market=p.market
|
||||
LEFT JOIN numbered_events event ON event.id=l.event
|
||||
LEFT JOIN price_settlements settlement ON settlement.market=p.market AND settlement.at_ms<?2
|
||||
LEFT JOIN quote_events q ON q.seq=(
|
||||
SELECT seq FROM quote_events WHERE market=p.market AND at_ms<?2
|
||||
AND yes_bid IS NOT NULL AND yes_ask BETWEEN yes_bid AND yes_bid+1000
|
||||
ORDER BY at_ms DESC,seq DESC LIMIT 1
|
||||
)
|
||||
LEFT JOIN (
|
||||
SELECT market,outcome,at_ms,price_micros AS price,fill
|
||||
FROM outcome_trade_prices WHERE at_ms<?2
|
||||
) trade ON trade.market=p.market AND trade.outcome=p.outcome AND trade.fill=(
|
||||
SELECT fill FROM outcome_trade_prices WHERE market=p.market AND outcome=p.outcome AND at_ms<?2
|
||||
ORDER BY at_ms DESC,fill DESC LIMIT 1
|
||||
)
|
||||
ORDER BY p.market,p.outcome
|
||||
@@ -0,0 +1,73 @@
|
||||
use crate::{assets, inventory, validation::identifier};
|
||||
use anyhow::{ensure, Result};
|
||||
use rusqlite::{params, Connection, Transaction, TransactionBehavior};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
pub(crate) fn install(db: &mut Connection) -> Result<()> {
|
||||
let installed = |db: &Connection| {
|
||||
db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM sqlite_schema
|
||||
WHERE type='table' AND name='position_balance_history_start')",
|
||||
[],
|
||||
|row| row.get::<_, bool>(0),
|
||||
)
|
||||
};
|
||||
if !installed(db)? {
|
||||
let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
||||
if !installed(&tx)? {
|
||||
tx.execute_batch(include_str!("position_balance_history_schema.sql"))?;
|
||||
}
|
||||
tx.commit()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Record only end-of-transaction ownership changes. Sell reservations can change
|
||||
/// the ledger's available and reserved columns without changing ownership.
|
||||
pub(crate) fn flush(tx: &Transaction<'_>) -> Result<()> {
|
||||
let pending: bool = tx.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM position_balance_pending)",
|
||||
[],
|
||||
|row| row.get(0),
|
||||
)?;
|
||||
if pending {
|
||||
tx.execute_batch(include_str!("position_balance_history_flush.sql"))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn read(tx: &Transaction<'_>, account: &str, before_ms: i64) -> Result<Value> {
|
||||
identifier(account)?;
|
||||
let (start, now): (i64, i64) = tx.query_row(
|
||||
"SELECT at_ms,CAST(unixepoch('subsec')*1000 AS INTEGER)
|
||||
FROM position_balance_history_start WHERE singleton=1",
|
||||
[],
|
||||
|row| Ok((row.get(0)?, row.get(1)?)),
|
||||
)?;
|
||||
ensure!(
|
||||
before_ms > start && before_ms <= now,
|
||||
"before_ms must be after the history baseline ({start}) and no later than now ({now})"
|
||||
);
|
||||
let mut stmt = tx.prepare_cached(
|
||||
"WITH balances AS (
|
||||
SELECT market,outcome,shares_micros,
|
||||
ROW_NUMBER() OVER (PARTITION BY market,outcome ORDER BY at_ms DESC,seq DESC) AS n
|
||||
FROM position_balance_history WHERE account=?1 AND at_ms<?2
|
||||
)
|
||||
SELECT market,outcome,shares_micros FROM balances
|
||||
WHERE n=1 AND shares_micros>0 ORDER BY market,outcome",
|
||||
)?;
|
||||
let data = stmt
|
||||
.query_map(params![account, before_ms], |row| {
|
||||
let market: String = row.get(0)?;
|
||||
let outcome: String = row.get(1)?;
|
||||
let shares: i64 = row.get(2)?;
|
||||
Ok(json!({
|
||||
"asset_id":assets::id(&market,&outcome),
|
||||
"market":market,"outcome":outcome,"shares_micros":shares,
|
||||
"size":inventory::decimal(shares.into(),inventory::UNIT)
|
||||
}))
|
||||
})?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
Ok(json!({"account":account,"before_ms":before_ms,"history_start_ms":start,"data":data}))
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
WITH clock(at_ms) AS MATERIALIZED (
|
||||
SELECT MAX(CAST(unixepoch('subsec')*1000 AS INTEGER),s.at_ms,
|
||||
COALESCE((SELECT MAX(at_ms) FROM position_balance_history),s.at_ms))
|
||||
FROM position_balance_history_start s
|
||||
), affected AS (
|
||||
SELECT p.account,p.market,p.outcome,c.at_ms,
|
||||
COALESCE(v.available+v.reserved,0) AS shares_micros,
|
||||
COALESCE((SELECT h.shares_micros FROM position_balance_history h
|
||||
WHERE h.account=p.account AND h.market=p.market AND h.outcome=p.outcome
|
||||
ORDER BY h.at_ms DESC,h.seq DESC LIMIT 1),0) AS previous
|
||||
FROM position_balance_pending p
|
||||
CROSS JOIN clock c
|
||||
LEFT JOIN position_units v USING(account,market,outcome)
|
||||
)
|
||||
INSERT INTO position_balance_history(account,market,outcome,at_ms,shares_micros)
|
||||
SELECT account,market,outcome,at_ms,shares_micros
|
||||
FROM affected WHERE shares_micros<>previous;
|
||||
DELETE FROM position_balance_pending;
|
||||
@@ -0,0 +1,62 @@
|
||||
CREATE TABLE position_balance_history_start (
|
||||
singleton INTEGER PRIMARY KEY CHECK(singleton=1),
|
||||
at_ms INTEGER NOT NULL
|
||||
);
|
||||
INSERT INTO position_balance_history_start VALUES(1,CAST(unixepoch('subsec')*1000 AS INTEGER));
|
||||
|
||||
CREATE TABLE position_balance_history (
|
||||
seq INTEGER PRIMARY KEY,
|
||||
account TEXT NOT NULL, market TEXT NOT NULL, outcome TEXT NOT NULL,
|
||||
at_ms INTEGER NOT NULL, shares_micros INTEGER NOT NULL CHECK(shares_micros>=0)
|
||||
);
|
||||
CREATE INDEX position_balance_history_by_holding
|
||||
ON position_balance_history(account,market,outcome,at_ms DESC,seq DESC);
|
||||
CREATE INDEX position_balance_history_by_time ON position_balance_history(at_ms);
|
||||
INSERT INTO position_balance_history(account,market,outcome,at_ms,shares_micros)
|
||||
SELECT account,market,outcome,s.at_ms,available+reserved
|
||||
FROM position_units CROSS JOIN position_balance_history_start s
|
||||
WHERE available+reserved>0;
|
||||
|
||||
CREATE TABLE position_balance_pending (
|
||||
account TEXT NOT NULL, market TEXT NOT NULL, outcome TEXT NOT NULL,
|
||||
PRIMARY KEY(account,market,outcome)
|
||||
) WITHOUT ROWID;
|
||||
|
||||
CREATE TRIGGER position_history_quantity AFTER UPDATE OF quantity ON positions
|
||||
WHEN NEW.quantity<>OLD.quantity BEGIN
|
||||
INSERT INTO position_balance_pending VALUES(NEW.account,NEW.market,NEW.outcome)
|
||||
ON CONFLICT(account,market,outcome) DO NOTHING;
|
||||
END;
|
||||
CREATE TRIGGER position_history_new_quantity AFTER INSERT ON positions
|
||||
WHEN NEW.quantity>0 BEGIN
|
||||
INSERT INTO position_balance_pending VALUES(NEW.account,NEW.market,NEW.outcome)
|
||||
ON CONFLICT(account,market,outcome) DO NOTHING;
|
||||
END;
|
||||
CREATE TRIGGER position_history_removed_quantity AFTER DELETE ON positions
|
||||
WHEN OLD.quantity>0 BEGIN
|
||||
INSERT INTO position_balance_pending VALUES(OLD.account,OLD.market,OLD.outcome)
|
||||
ON CONFLICT(account,market,outcome) DO NOTHING;
|
||||
END;
|
||||
CREATE TRIGGER position_history_new_remainder AFTER INSERT ON position_remainders
|
||||
WHEN NEW.micros<>0 BEGIN
|
||||
INSERT INTO position_balance_pending VALUES(NEW.account,NEW.market,NEW.outcome)
|
||||
ON CONFLICT(account,market,outcome) DO NOTHING;
|
||||
END;
|
||||
CREATE TRIGGER position_history_remainder AFTER UPDATE OF micros ON position_remainders
|
||||
WHEN NEW.micros<>OLD.micros BEGIN
|
||||
INSERT INTO position_balance_pending VALUES(NEW.account,NEW.market,NEW.outcome)
|
||||
ON CONFLICT(account,market,outcome) DO NOTHING;
|
||||
END;
|
||||
CREATE TRIGGER position_history_removed_remainder AFTER DELETE ON position_remainders
|
||||
WHEN OLD.micros<>0 BEGIN
|
||||
INSERT INTO position_balance_pending VALUES(OLD.account,OLD.market,OLD.outcome)
|
||||
ON CONFLICT(account,market,outcome) DO NOTHING;
|
||||
END;
|
||||
-- A seller can lose ownership through an execution that only changes a reserved order.
|
||||
CREATE TRIGGER position_history_execution AFTER UPDATE OF remaining,status ON orders
|
||||
WHEN OLD.side='sell' AND OLD.status='live'
|
||||
AND (OLD.remaining<>NEW.remaining OR OLD.status<>NEW.status)
|
||||
BEGIN
|
||||
INSERT INTO position_balance_pending VALUES(OLD.account,OLD.market,OLD.outcome)
|
||||
ON CONFLICT(account,market,outcome) DO NOTHING;
|
||||
END;
|
||||
@@ -4178,3 +4178,182 @@ fn order_submission_terms_survive_fills_cancel_retries_and_legacy_upgrade() {
|
||||
assert_eq!(e.execute(cmd.clone()).unwrap()["orders"][0], expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn balance_history_uses_committed_ownership_and_an_exclusive_cut() {
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("historical-balances.db");
|
||||
let mut engine = Exchange::open(&path).unwrap();
|
||||
setup(&mut engine);
|
||||
engine
|
||||
.execute(json!({"op":"open","id":"open-history","market":"e"}))
|
||||
.unwrap();
|
||||
let db = rusqlite::Connection::open(&path).unwrap();
|
||||
db.execute("UPDATE position_balance_history_start SET at_ms=1000", [])
|
||||
.unwrap();
|
||||
db.execute("UPDATE position_balance_history SET at_ms=2000", [])
|
||||
.unwrap();
|
||||
let count = || {
|
||||
db.query_row("SELECT COUNT(*) FROM position_balance_history", [], |r| {
|
||||
r.get::<_, i64>(0)
|
||||
})
|
||||
.unwrap()
|
||||
};
|
||||
let initial = count();
|
||||
assert_eq!(
|
||||
engine
|
||||
.execute(json!({"op":"position_balances_at","account":"alice","before_ms":2000}))
|
||||
.unwrap()["data"],
|
||||
json!([])
|
||||
);
|
||||
assert!(engine
|
||||
.execute(json!({"op":"position_balances_at","account":"alice","before_ms":1000}))
|
||||
.is_err());
|
||||
|
||||
let ask = order("history-ask", "alice", "sell", 50, 4);
|
||||
engine.execute(ask).unwrap();
|
||||
assert_eq!(count(), initial, "reserving shares preserves ownership");
|
||||
let buy = order("history-buy", "bob", "buy", 50, 2);
|
||||
engine.execute(buy.clone()).unwrap();
|
||||
assert_eq!(count(), initial + 2);
|
||||
engine.execute(buy).unwrap();
|
||||
assert_eq!(
|
||||
count(),
|
||||
initial + 2,
|
||||
"idempotent replay produces no second movement"
|
||||
);
|
||||
db.execute(
|
||||
"UPDATE position_balance_history SET at_ms=3000 WHERE at_ms>2000",
|
||||
[],
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
drop(engine);
|
||||
let mut engine = Exchange::open(&path).unwrap();
|
||||
let balance = |engine: &mut Exchange, account: &str, before_ms| {
|
||||
engine
|
||||
.execute(json!({"op":"position_balances_at","account":account,"before_ms":before_ms}))
|
||||
.unwrap()["data"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|row| row["outcome"] == "YES")
|
||||
.map(|row| row["shares_micros"].as_i64().unwrap())
|
||||
};
|
||||
assert_eq!(balance(&mut engine, "alice", 3000), Some(10_000_000));
|
||||
assert_eq!(balance(&mut engine, "alice", 3001), Some(8_000_000));
|
||||
assert_eq!(balance(&mut engine, "bob", 3001), Some(2_000_000));
|
||||
|
||||
engine
|
||||
.execute(json!({"op":"close","id":"history-close","market":"e"}))
|
||||
.unwrap();
|
||||
engine
|
||||
.execute(json!({"op":"finalize","id":"history-final","market":"e","winner":"YES"}))
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
count(),
|
||||
initial + 2,
|
||||
"closing the book releases reservations, not ownership"
|
||||
);
|
||||
engine
|
||||
.execute(json!({"op":"redeem","id":"history-redeem","account":"alice","market":"e"}))
|
||||
.unwrap();
|
||||
assert_eq!(count(), initial + 4);
|
||||
db.execute(
|
||||
"UPDATE position_balance_history SET at_ms=4000 WHERE at_ms>3000",
|
||||
[],
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(balance(&mut engine, "alice", 4000), Some(8_000_000));
|
||||
assert_eq!(balance(&mut engine, "alice", 4001), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn daily_position_snapshot_uses_the_cut_and_binds_cursor_scope() {
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("daily-positions.db");
|
||||
let mut engine = Exchange::open(&path).unwrap();
|
||||
let maker = "0x0000000000000000000000000000000000000011";
|
||||
let wallet = "0x0000000000000000000000000000000000000022";
|
||||
for cmd in [
|
||||
json!({"op":"fund","id":"daily-maker","account":maker,"cents":3000}),
|
||||
json!({"op":"fund","id":"daily-wallet","account":wallet,"cents":3000}),
|
||||
json!({"op":"list","id":"daily-market","market":"e","rules":"snapshot fixture"}),
|
||||
json!({"op":"list","id":"daily-basis-market","market":"f","rules":"unpriced fixture"}),
|
||||
json!({"op":"list","id":"daily-dust-market","market":"dust","rules":"dust fixture"}),
|
||||
json!({"op":"split","id":"daily-shares","account":maker,"market":"e","qty":4}),
|
||||
json!({"op":"split","id":"daily-both","account":wallet,"market":"f","qty":1}),
|
||||
json!({"op":"merge","id":"daily-merge","account":wallet,"market":"f","qty_micros":250000}),
|
||||
json!({"op":"split","id":"daily-dust","account":wallet,"market":"dust","qty_micros":100000}),
|
||||
json!({"op":"open","id":"daily-open","market":"e"}),
|
||||
order("daily-ask", maker, "sell", 40, 2),
|
||||
order("daily-buy", wallet, "buy", 40, 2),
|
||||
json!({"op":"close","id":"daily-close","market":"e"}),
|
||||
json!({"op":"finalize","id":"daily-final","market":"e","winner":"NO"}),
|
||||
] {
|
||||
engine.execute(cmd).unwrap();
|
||||
}
|
||||
let conn = rusqlite::Connection::open(&path).unwrap();
|
||||
let day = 1_699_920_000_000_i64;
|
||||
let cutoff = day + 86_400_000;
|
||||
conn.execute(
|
||||
"UPDATE position_balance_history_start SET at_ms=?",
|
||||
[day - 1],
|
||||
)
|
||||
.unwrap();
|
||||
for table in [
|
||||
"position_balance_history",
|
||||
"wallet_movements",
|
||||
"quote_events",
|
||||
"trade_prices",
|
||||
] {
|
||||
conn.execute(&format!("UPDATE {table} SET at_ms=?"), [day + 1000])
|
||||
.unwrap();
|
||||
}
|
||||
conn.execute("UPDATE price_settlements SET at_ms=?", [cutoff])
|
||||
.unwrap();
|
||||
let date: String = conn
|
||||
.query_row("SELECT date(?1/1000,'unixepoch')", [day], |r| r.get(0))
|
||||
.unwrap();
|
||||
let read = |engine: &Exchange, query| {
|
||||
engine.public_position_snapshot(serde_json::from_value(query).unwrap())
|
||||
};
|
||||
let first = read(&engine, json!({"user":wallet,"date":date,"limit":1})).unwrap();
|
||||
assert_eq!(first["summary"]["positions"], 3);
|
||||
assert_eq!(first["summary"]["cost_basis"], 1.55);
|
||||
assert_eq!(first["data"][0]["price_source"], "mark");
|
||||
assert_eq!(first["data"][0]["value"], 0.8);
|
||||
assert_eq!(first["summary"]["value_by_source"]["basis"], 0.75);
|
||||
assert!(first["summary"]["closed_block"].is_null());
|
||||
let cursor = first["pagination"]["next_cursor"].as_str().unwrap();
|
||||
drop(engine);
|
||||
let engine = Exchange::open(&path).unwrap();
|
||||
let second = read(
|
||||
&engine,
|
||||
json!({"user_address":wallet,"cursor":cursor,"limit":999}),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(second["pagination"]["limit"], 1);
|
||||
assert_eq!(second["pagination"]["offset"], 1);
|
||||
assert_eq!(second["data"][0]["price_source"], "basis");
|
||||
assert_eq!(second["data"][0]["size"], 0.75);
|
||||
assert_eq!(second["data"][0]["cost_basis"], 0.375);
|
||||
assert_eq!(second["data"][0]["avg_price"], 0.5);
|
||||
assert!(second.get("summary").is_none());
|
||||
assert!(read(&engine, json!({"user":maker,"cursor":cursor})).is_err());
|
||||
assert!(read(
|
||||
&engine,
|
||||
json!({"user":wallet,"cursor":cursor,"date":"2023-11-17"})
|
||||
)
|
||||
.is_err());
|
||||
assert!(read(&engine, json!({"user":wallet,"date":"2099-01-01"})).is_err());
|
||||
assert!(read(&engine, json!({"user":wallet,"date":"2023-02-30"})).is_err());
|
||||
|
||||
let next_day: String = conn
|
||||
.query_row("SELECT date(?1/1000,'unixepoch')", [cutoff], |r| r.get(0))
|
||||
.unwrap();
|
||||
let settled = read(&engine, json!({"user":wallet,"date":next_day})).unwrap();
|
||||
assert_eq!(settled["data"][0]["price_source"], "settlement");
|
||||
assert_eq!(settled["data"][0]["price"], 0);
|
||||
assert_eq!(settled["data"][0]["cost_basis"], 0.8);
|
||||
}
|
||||
@@ -8,11 +8,6 @@ cargo run --locked -p venue-probe
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
main -->|核对 CTF 权重| ctf["src/ctf_resolution.rs"]
|
||||
main -->|核对 V2 模块权重| position["src/position_resolution.rs"]
|
||||
position -->|解析目录及结果 ID| catalog
|
||||
position -->|读取最终确认区块| rpc["src/polygon_rpc.rs"]
|
||||
ctf -->|读取最终确认区块| rpc
|
||||
main["src/main.rs"] -->|依次调用两个只读探针| impls["src/probes.rs"]
|
||||
main -->|重放 Gamma 市场| catalog["src/catalog.rs"]
|
||||
impls -->|识别持仓协议及两套 ID| catalog
|
||||
@@ -128,55 +123,3 @@ sequenceDiagram
|
||||
2026-12-03 06:55 UTC 采集的[同侧报价快照](fixtures/live-side-prices.json)按请求保存前后盘口、报价、时间、方法及响应。双侧盘口最优价为 0.039 和 0.04。缺买盘的结果返回 BUY 字符串 0,缺卖盘的结果返回 SELL 字符串 1。批量 POST 返回相同字符串。文档列出的逗号分隔 GET 在这次生产取样返回 400。三个资产的前后盘口哈希各自一致。[官方单价接口](https://docs.polymarket.com/api-reference/market-data/get-market-price)
|
||||
|
||||
[电竞盘双空样本](fixtures/live-empty-prices.json)保留前后盘口和两次价格请求。两个深度数组均为空,公开 BUY 返回 "0",SELL 返回 "1"。探针把该结果计为已验证的空盘报价,实际可成交数量仍为零。
|
||||
|
||||
## Polygon CTF 裁决核对
|
||||
|
||||
`venue-probe --inspect-resolution CONDITION [EXPECTED]` 读取 Polygon 主网 CTF 的二元条件。默认使用 PublicNode,可通过 `EVENTBOOK_POLYGON_RPC_URL` 更换 HTTPS RPC。将输出保存为 JSON 后,`venue-probe --replay-resolution FILE [EXPECTED]` 可离线核对原始 ABI 字。`EXPECTED` 可用 `first`、`second`、`split`、`weighted`、`unresolved` 或 `unprepared`。前两个值指目录结果顺序,使用者应按已核实的结果映射指定预期。给出预期且不一致时,命令保留报告并以非零状态退出。
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
actor C as 调用者
|
||||
participant P as venue-probe
|
||||
participant N as Polygon RPC
|
||||
alt 现场读取
|
||||
C->>P: inspect-resolution CONDITION
|
||||
P->>N: 核对主网链 ID 及已最终确认区块
|
||||
P->>N: 在该区块读取结果数、分母和各侧权重
|
||||
P->>N: 复核区块哈希
|
||||
else 离线重放
|
||||
C->>P: replay-resolution FILE
|
||||
end
|
||||
P-->>C: 返回原始 ABI 字、十进制权重和对照结果
|
||||
```
|
||||
|
||||
[实测记录](fixtures/live-ctf-resolution.json)保存了两个独立节点一致返回的区块和权重。该市场的 Gamma 目录结果顺序为 Over、Under,链上分子为 0、1,分母为 1。探针只读取 CTF 的合约状态。结果由所选 RPC 提供,仅覆盖 CTF 二元条件。PositionManager 的读取路径见下节。链上状态证明仍待接入。[Gamma 封盘样本](../../docs/examples/public-closed-chart-history.json) · [Polymarket 合约清单](https://docs.polymarket.com/resources/contracts) · [Conditional Tokens 合约](https://github.com/gnosis/conditional-tokens-contracts/blob/master/contracts/ConditionalTokens.sol)
|
||||
|
||||
## Polygon PositionManager V2 裁决核对
|
||||
|
||||
`venue-probe --inspect-position-resolution MARKET_JSON [EXPECTED]` 读取一条原始 Gamma V2 市场。Gamma 可能将 31 字节条件以尾部补零的 32 字节形式返回。通过两个 Position ID 核对条件和结果顺序后,按条件首字节从 PositionManager 查找 Binary 或 NegRisk 模块,并从该模块读取兑付权重。与 CTF 命令共用 Polygon RPC 配置。两次调用都绑定到同一最终确认区块,并在返回结果前复核区块哈希。[模块注册表](https://github.com/Polymarket/polymarket-v2-external/blob/main/docs/position-manager.md) · [Position ID 编码](https://github.com/Polymarket/polymarket-v2-external/blob/main/docs/position-ids.md) · [模块源码说明](https://github.com/Polymarket/polymarket-v2-external/blob/main/docs/modules.md)
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
actor U as 调用者
|
||||
participant P as venue-probe
|
||||
participant R as Polygon RPC
|
||||
participant M as PositionManager
|
||||
participant S as Binary 或 NegRisk 模块
|
||||
U->>P: inspect-position-resolution MARKET_JSON
|
||||
P->>P: 从两个 Position ID 核对条件与结果顺序
|
||||
P->>R: eth_chainId 与 finalized 区块
|
||||
R-->>P: 137、区块号和哈希
|
||||
P->>R: 在指定区块调用 moduleById
|
||||
R->>M: moduleById(module_id)
|
||||
M-->>R: 已注册的模块代理
|
||||
R-->>P: 模块代理地址
|
||||
P->>R: 在同一区块调用 getResult
|
||||
R->>S: getResult(condition_id)
|
||||
S-->>R: 空数组或两个权重
|
||||
R-->>P: 原始 ABI 字
|
||||
P->>R: 复核同一区块哈希
|
||||
R-->>P: 区块号和哈希
|
||||
P-->>U: 目录结果、合约、区块、原始 ABI 和兑付状态
|
||||
```
|
||||
|
||||
`venue-probe --replay-position-resolution crates/venue-probe/fixtures/live-position-resolutions.json first` 可重放生产 Binary 样本。两个 Polygon 节点在区块 `0x5df5912` 返回同一模块地址与兑付权重 `[1000000, 0]`,对应目录第一结果获胜。空权重数组报告为 `unresolved`。已兑付状态按数组值报告为 `first`、`second`、`split` 或 `weighted`。提供预期时,任何结果不符都会在输出报告后返回非零状态。NegRisk 的权重约束有离线回归用例,生产目录与链上结果的对应仍待验证。组合盘使用独立模块,预言机证明和本地账本入账也仍待覆盖。[双节点原始样本](fixtures/live-position-resolutions.json) · [合约部署地址](https://docs.polymarket.com/resources/contracts)
|
||||
@@ -1,18 +0,0 @@
|
||||
{
|
||||
"chain_id": 137,
|
||||
"block_number": "0x5df5831",
|
||||
"block_hash": "0xf36806915eb4a8aa5ecb85d411a3259c9a65b1f1af65049e30e5098a32f6b45c",
|
||||
"condition_id": "0xdf04a0495b0a16dbce386acdc16d9aed19784db9888be53d150354b83b7c18b1",
|
||||
"contract": "0x4D97DCd97eC945f40cF65F87097ACe5EA0476045",
|
||||
"sources": [
|
||||
"https://polygon.drpc.org",
|
||||
"https://polygon-bor-rpc.publicnode.com"
|
||||
],
|
||||
"outcome_slots": "0x0000000000000000000000000000000000000000000000000000000000000002",
|
||||
"denominator": "0x0000000000000000000000000000000000000000000000000000000000000001",
|
||||
"numerators": [
|
||||
"0x0000000000000000000000000000000000000000000000000000000000000000",
|
||||
"0x0000000000000000000000000000000000000000000000000000000000000001"
|
||||
],
|
||||
"observed_at_ms": 1796490278240
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
[
|
||||
{
|
||||
"chain_id": 137,
|
||||
"block_number": "0x5df5912",
|
||||
"block_hash": "0x7bee6030d9cd7c98bc7f6ae18f89c5a5b8c3a912993f558658224cf0a98a4533",
|
||||
"market": {
|
||||
"id": "7543472",
|
||||
"slug": "setkameua-anat-illia-2026-12-03",
|
||||
"version": "v2",
|
||||
"conditionId": "0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000",
|
||||
"positionIds": [
|
||||
"759916398134244316868652908232832573045153963965173623897622651599218278400",
|
||||
"759916398134244316868652908232832573045153963965173623897622651599218278401"
|
||||
],
|
||||
"outcomePrices": "[\"1\", \"0\"]",
|
||||
"outcomes": "[\"Nikolenko Anatolii\", \"Fokin Illia\"]"
|
||||
},
|
||||
"registry": "0x0000000000000000000000001000008dd9001b968442c1000017eae6e0da00ba",
|
||||
"result": "0x0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000f42400000000000000000000000000000000000000000000000000000000000000000",
|
||||
"sources": [
|
||||
"https://polygon.drpc.org",
|
||||
"https://polygon-bor-rpc.publicnode.com"
|
||||
],
|
||||
"observed_at_ms": 1796490613542
|
||||
}
|
||||
]
|
||||
@@ -1,221 +0,0 @@
|
||||
use crate::polygon_rpc::{hex_data, quantity, word, FinalizedRpc, POLYGON_CHAIN_ID};
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use reqwest::blocking::Client;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
const CTF: &str = "0x4D97DCd97eC945f40cF65F87097ACe5EA0476045";
|
||||
// First four bytes of Keccak-256 of the public ABI signatures.
|
||||
const OUTCOME_SLOTS: &str = "d42dc0c2"; // getOutcomeSlotCount(bytes32)
|
||||
const PAYOUT_DENOMINATOR: &str = "dd34de67"; // payoutDenominator(bytes32)
|
||||
const PAYOUT_NUMERATOR: &str = "0504c814"; // payoutNumerators(bytes32,uint256)
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
struct Observation {
|
||||
chain_id: u64,
|
||||
block_number: String,
|
||||
block_hash: String,
|
||||
contract: String,
|
||||
condition_id: String,
|
||||
outcome_slots: String,
|
||||
denominator: String,
|
||||
numerators: Option<[String; 2]>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
observed_at_ms: Option<u64>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
sources: Vec<String>,
|
||||
}
|
||||
|
||||
fn add(a: [u8; 32], b: [u8; 32]) -> Result<[u8; 32]> {
|
||||
let mut result = [0; 32];
|
||||
let mut carry = 0;
|
||||
for i in (0..32).rev() {
|
||||
let sum = u16::from(a[i]) + u16::from(b[i]) + carry;
|
||||
result[i] = sum as u8;
|
||||
carry = sum >> 8;
|
||||
}
|
||||
ensure!(carry == 0, "CTF payout weights overflow uint256");
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
fn decimal(word: [u8; 32]) -> String {
|
||||
let mut digits = vec![0_u8];
|
||||
for byte in word {
|
||||
let mut carry = u16::from(byte);
|
||||
for digit in &mut digits {
|
||||
let n = u16::from(*digit) * 256 + carry;
|
||||
*digit = (n % 10) as u8;
|
||||
carry = n / 10;
|
||||
}
|
||||
while carry > 0 {
|
||||
digits.push((carry % 10) as u8);
|
||||
carry /= 10;
|
||||
}
|
||||
}
|
||||
digits
|
||||
.into_iter()
|
||||
.rev()
|
||||
.map(|digit| char::from(b'0' + digit))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn audit(obs: Observation, expected: Option<&str>) -> Result<Value> {
|
||||
ensure!(
|
||||
obs.chain_id == POLYGON_CHAIN_ID && obs.contract.eq_ignore_ascii_case(CTF),
|
||||
"observation is not from the configured Polygon CTF deployment"
|
||||
);
|
||||
let block = quantity(&obs.block_number)?;
|
||||
hex_data(&obs.block_hash, 32)?;
|
||||
hex_data(&obs.condition_id, 32)?;
|
||||
let n = word(&obs.outcome_slots)?;
|
||||
let d = word(&obs.denominator)?;
|
||||
let zero = [0; 32];
|
||||
let mut two = [0; 32];
|
||||
two[31] = 2;
|
||||
let (status, numerators) = match (n, obs.numerators.as_ref()) {
|
||||
(n, None) if n == zero && d == zero => ("unprepared", None),
|
||||
(n, Some(values)) if n == two => {
|
||||
let a = word(&values[0])?;
|
||||
let b = word(&values[1])?;
|
||||
ensure!(add(a, b)? == d, "CTF payout sum does not match denominator");
|
||||
let status = if d == zero {
|
||||
"unresolved"
|
||||
} else if a == zero {
|
||||
"second"
|
||||
} else if b == zero {
|
||||
"first"
|
||||
} else if a == b {
|
||||
"split"
|
||||
} else {
|
||||
"weighted"
|
||||
};
|
||||
(status, Some([decimal(a), decimal(b)]))
|
||||
}
|
||||
_ => anyhow::bail!("observation is not an unprepared or binary CTF condition"),
|
||||
};
|
||||
if let Some(expected) = expected {
|
||||
ensure!(
|
||||
matches!(
|
||||
expected,
|
||||
"unprepared" | "unresolved" | "first" | "second" | "split" | "weighted"
|
||||
),
|
||||
"invalid expected CTF payout status"
|
||||
);
|
||||
}
|
||||
Ok(
|
||||
json!({"observation":obs,"block":block,"status":status,"payout_denominator":decimal(d),
|
||||
"payout_numerators":numerators,"expected":expected,"matches":expected.map(|v|v==status)}),
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn inspect(client: &Client, condition: &str, expected: Option<&str>) -> Result<Value> {
|
||||
let cid = hex_data(condition, 32)?;
|
||||
let block = FinalizedRpc::connect(client)?;
|
||||
let slots = block.call(CTF, &format!("0x{OUTCOME_SLOTS}{cid}"))?;
|
||||
let slot_word = word(&slots)?;
|
||||
let mut two = [0; 32];
|
||||
two[31] = 2;
|
||||
ensure!(
|
||||
slot_word == [0; 32] || slot_word == two,
|
||||
"CTF condition has a nonbinary outcome count"
|
||||
);
|
||||
let denominator = block.call(CTF, &format!("0x{PAYOUT_DENOMINATOR}{cid}"))?;
|
||||
let numerators = if slot_word == two {
|
||||
Some([
|
||||
block.call(CTF, &format!("0x{PAYOUT_NUMERATOR}{cid}{:064x}", 0))?,
|
||||
block.call(CTF, &format!("0x{PAYOUT_NUMERATOR}{cid}{:064x}", 1))?,
|
||||
])
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let observed_at_ms = block.confirm()?;
|
||||
audit(
|
||||
Observation {
|
||||
chain_id: POLYGON_CHAIN_ID,
|
||||
block_number: block.number,
|
||||
block_hash: block.hash,
|
||||
contract: CTF.to_owned(),
|
||||
condition_id: condition.to_ascii_lowercase(),
|
||||
outcome_slots: slots,
|
||||
denominator,
|
||||
numerators,
|
||||
observed_at_ms: Some(observed_at_ms),
|
||||
sources: Vec::new(),
|
||||
},
|
||||
expected,
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn replay(file: &str, expected: Option<&str>) -> Result<Value> {
|
||||
let raw: Value = serde_json::from_reader(std::fs::File::open(file)?)?;
|
||||
let obs = serde_json::from_value(raw.get("observation").cloned().unwrap_or(raw))?;
|
||||
audit(obs, expected)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn fixture() -> Observation {
|
||||
serde_json::from_str(include_str!("../fixtures/live-ctf-resolution.json")).unwrap()
|
||||
}
|
||||
|
||||
fn abi(value: u64) -> String {
|
||||
format!("0x{value:064x}")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn captured_polymarket_ctf_paid_the_second_outcome() {
|
||||
let report = audit(fixture(), Some("second")).unwrap();
|
||||
assert_eq!(report["status"], "second");
|
||||
assert_eq!(report["payout_denominator"], "1");
|
||||
assert_eq!(report["payout_numerators"], json!(["0", "1"]));
|
||||
assert_eq!(report["matches"], true);
|
||||
assert_eq!(audit(fixture(), Some("first")).unwrap()["matches"], false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_split_and_invalid_payout_shapes_remain_distinct() {
|
||||
let mut obs = fixture();
|
||||
obs.outcome_slots = abi(0);
|
||||
obs.denominator = abi(0);
|
||||
obs.numerators = None;
|
||||
assert_eq!(audit(obs, None).unwrap()["status"], "unprepared");
|
||||
|
||||
let mut obs = fixture();
|
||||
obs.denominator = abi(0);
|
||||
obs.numerators = Some([abi(0), abi(0)]);
|
||||
assert_eq!(audit(obs, None).unwrap()["status"], "unresolved");
|
||||
|
||||
let mut obs = fixture();
|
||||
obs.denominator = abi(2);
|
||||
obs.numerators = Some([abi(1), abi(1)]);
|
||||
assert_eq!(audit(obs, Some("split")).unwrap()["status"], "split");
|
||||
|
||||
let mut obs = fixture();
|
||||
obs.denominator = abi(3);
|
||||
obs.numerators = Some([abi(1), abi(1)]);
|
||||
assert!(audit(obs, None).is_err());
|
||||
|
||||
let mut obs = fixture();
|
||||
obs.chain_id = 1;
|
||||
assert!(audit(obs, None).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uint256_payout_weights_do_not_round_or_wrap() {
|
||||
let max = format!("0x{}", "ff".repeat(32));
|
||||
let mut obs = fixture();
|
||||
obs.denominator = max.clone();
|
||||
obs.numerators = Some([max.clone(), abi(0)]);
|
||||
let report = audit(obs, None).unwrap();
|
||||
assert_eq!(
|
||||
report["payout_denominator"],
|
||||
"115792089237316195423570985008687907853269984665640564039457584007913129639935"
|
||||
);
|
||||
let mut obs = fixture();
|
||||
obs.denominator = abi(0);
|
||||
obs.numerators = Some([max, abi(1)]);
|
||||
assert!(audit(obs, None).is_err());
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,6 @@
|
||||
mod book_audit;
|
||||
mod books;
|
||||
mod catalog;
|
||||
mod ctf_resolution;
|
||||
mod polygon_rpc;
|
||||
mod position_resolution;
|
||||
mod price_check;
|
||||
mod probes;
|
||||
use anyhow::{ensure, Result};
|
||||
@@ -36,45 +33,7 @@ fn observe_book(client: &Client, url: reqwest::Url, token: &str) -> Result<()> {
|
||||
fn main() -> Result<()> {
|
||||
let args: Vec<_> = std::env::args().skip(1).collect();
|
||||
let usage =
|
||||
"usage: venue-probe [--compare-prices | --inspect-book TOKEN | --replay-book TOKEN FILE | --replay-market FILE | --inspect-resolution CONDITION [EXPECTED] | --replay-resolution FILE [EXPECTED] | --inspect-position-resolution MARKET_JSON [EXPECTED] | --replay-position-resolution FILE [EXPECTED]]";
|
||||
if let [mode, value, rest @ ..] = args.as_slice() {
|
||||
if matches!(
|
||||
mode.as_str(),
|
||||
"--inspect-resolution"
|
||||
| "--replay-resolution"
|
||||
| "--inspect-position-resolution"
|
||||
| "--replay-position-resolution"
|
||||
) {
|
||||
ensure!(rest.len() <= 1, usage);
|
||||
let expected = rest.first().map(String::as_str);
|
||||
let reports = match mode.as_str() {
|
||||
"--replay-resolution" => vec![ctf_resolution::replay(value, expected)?],
|
||||
"--replay-position-resolution" => position_resolution::replay(value, expected)?,
|
||||
_ => {
|
||||
let client = Client::builder()
|
||||
.connect_timeout(Duration::from_secs(5))
|
||||
.timeout(Duration::from_secs(10))
|
||||
.redirect(reqwest::redirect::Policy::none())
|
||||
.user_agent("eventbook-readonly-probe/0.1")
|
||||
.build()?;
|
||||
vec![if mode == "--inspect-resolution" {
|
||||
ctf_resolution::inspect(&client, value, expected)?
|
||||
} else {
|
||||
position_resolution::inspect(&client, value, expected)?
|
||||
}]
|
||||
}
|
||||
};
|
||||
for report in &reports {
|
||||
println!("{report}");
|
||||
}
|
||||
ensure!(
|
||||
reports.iter().all(|report| report["matches"] != false),
|
||||
"payout status differs from the expected result"
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
"usage: venue-probe [--compare-prices | --inspect-book TOKEN | --replay-book TOKEN FILE | --replay-market FILE]";
|
||||
if let [mode, file] = args.as_slice() {
|
||||
if mode == "--replay-market" {
|
||||
let raw = serde_json::from_reader(std::fs::File::open(file)?)?;
|
||||
|
||||
@@ -1,137 +0,0 @@
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use reqwest::{blocking::Client, Url};
|
||||
use serde_json::{json, Value};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
pub(crate) const POLYGON_CHAIN_ID: u64 = 137;
|
||||
const DEFAULT_RPC: &str = "https://polygon-bor-rpc.publicnode.com";
|
||||
|
||||
pub(crate) fn hex_data(raw: &str, bytes: usize) -> Result<&str> {
|
||||
let body = raw.strip_prefix("0x").context("invalid ABI hex prefix")?;
|
||||
ensure!(
|
||||
body.len() == 2 * bytes && body.bytes().all(|b| b.is_ascii_hexdigit()),
|
||||
"invalid ABI hex length or digit"
|
||||
);
|
||||
Ok(body)
|
||||
}
|
||||
|
||||
pub(crate) fn quantity(raw: &str) -> Result<u64> {
|
||||
let body = raw
|
||||
.strip_prefix("0x")
|
||||
.context("invalid RPC quantity prefix")?;
|
||||
ensure!(
|
||||
!body.is_empty()
|
||||
&& body.bytes().all(|b| b.is_ascii_hexdigit())
|
||||
&& (body.len() == 1 || !body.starts_with('0')),
|
||||
"invalid RPC quantity"
|
||||
);
|
||||
u64::from_str_radix(body, 16).context("invalid RPC quantity")
|
||||
}
|
||||
|
||||
pub(crate) fn word(raw: &str) -> Result<[u8; 32]> {
|
||||
let mut value = [0; 32];
|
||||
for (i, chunk) in hex_data(raw, 32)?.as_bytes().chunks_exact(2).enumerate() {
|
||||
value[i] = u8::from_str_radix(std::str::from_utf8(chunk)?, 16)?;
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn rpc(client: &Client, url: &Url, method: &str, params: Value) -> Result<Value> {
|
||||
let response: Value = client
|
||||
.post(url.clone())
|
||||
.json(&json!({
|
||||
"jsonrpc":"2.0","id":1,"method":method,"params":params
|
||||
}))
|
||||
.send()
|
||||
.map_err(reqwest::Error::without_url)?
|
||||
.error_for_status()
|
||||
.map_err(reqwest::Error::without_url)?
|
||||
.json()
|
||||
.map_err(reqwest::Error::without_url)?;
|
||||
ensure!(
|
||||
response["jsonrpc"] == "2.0" && response["id"] == 1,
|
||||
"invalid RPC envelope for {method}"
|
||||
);
|
||||
if let Some(error) = response.get("error") {
|
||||
anyhow::bail!("{method} RPC rejected the request (code {})", error["code"]);
|
||||
}
|
||||
response
|
||||
.get("result")
|
||||
.cloned()
|
||||
.with_context(|| format!("missing result for {method}"))
|
||||
}
|
||||
|
||||
pub(crate) struct FinalizedRpc<'a> {
|
||||
client: &'a Client,
|
||||
url: Url,
|
||||
pub number: String,
|
||||
pub hash: String,
|
||||
}
|
||||
|
||||
impl<'a> FinalizedRpc<'a> {
|
||||
pub(crate) fn connect(client: &'a Client) -> Result<Self> {
|
||||
let url = Url::parse(
|
||||
&std::env::var("EVENTBOOK_POLYGON_RPC_URL").unwrap_or_else(|_| DEFAULT_RPC.to_owned()),
|
||||
)
|
||||
.context("invalid Polygon RPC URL")?;
|
||||
ensure!(
|
||||
url.scheme() == "https" && url.username().is_empty() && url.password().is_none(),
|
||||
"Polygon RPC requires an HTTPS URL without embedded credentials"
|
||||
);
|
||||
let chain = rpc(client, &url, "eth_chainId", json!([]))?;
|
||||
let chain_id = quantity(chain.as_str().context("missing chain id")?)?;
|
||||
ensure!(chain_id == POLYGON_CHAIN_ID, "RPC is not Polygon mainnet");
|
||||
let anchor = rpc(
|
||||
client,
|
||||
&url,
|
||||
"eth_getBlockByNumber",
|
||||
json!(["finalized", false]),
|
||||
)?;
|
||||
let number = anchor["number"]
|
||||
.as_str()
|
||||
.context("RPC finalized block has no block number")?;
|
||||
quantity(number)?;
|
||||
let hash = anchor["hash"]
|
||||
.as_str()
|
||||
.context("RPC finalized block has no block hash")?;
|
||||
hex_data(hash, 32)?;
|
||||
Ok(Self {
|
||||
client,
|
||||
url,
|
||||
number: number.to_owned(),
|
||||
hash: hash.to_owned(),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn call(&self, contract: &str, data: &str) -> Result<String> {
|
||||
let value = rpc(
|
||||
self.client,
|
||||
&self.url,
|
||||
"eth_call",
|
||||
json!([{"to":contract,"data":data},self.number]),
|
||||
)?;
|
||||
value
|
||||
.as_str()
|
||||
.map(str::to_owned)
|
||||
.context("invalid eth_call ABI result")
|
||||
}
|
||||
|
||||
pub(crate) fn confirm(&self) -> Result<u64> {
|
||||
// Providers may lack EIP-1898 support. Read the finalized block number,
|
||||
// then verify its hash again before accepting any of the calls.
|
||||
let current = rpc(
|
||||
self.client,
|
||||
&self.url,
|
||||
"eth_getBlockByNumber",
|
||||
json!([self.number, false]),
|
||||
)?;
|
||||
ensure!(
|
||||
current["hash"] == self.hash && current["number"] == self.number,
|
||||
"RPC block changed during reads"
|
||||
);
|
||||
Ok(SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)?
|
||||
.as_millis()
|
||||
.try_into()?)
|
||||
}
|
||||
}
|
||||
@@ -1,274 +0,0 @@
|
||||
use crate::{
|
||||
catalog::Market,
|
||||
polygon_rpc::{hex_data, quantity, word, FinalizedRpc, POLYGON_CHAIN_ID},
|
||||
};
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use reqwest::blocking::Client;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
const POSITION_MANAGER: &str = "0x006F54F7f9A22e0000CC2AB60031000000ae9fEF";
|
||||
// moduleById(uint256), getResult(bytes31)
|
||||
const MODULE_BY_ID: &str = "4d51cdf1";
|
||||
const GET_RESULT: &str = "e4939c77";
|
||||
const DENOMINATOR: u64 = 1_000_000;
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
struct Observation {
|
||||
chain_id: u64,
|
||||
block_number: String,
|
||||
block_hash: String,
|
||||
market: Value,
|
||||
registry: String,
|
||||
result: String,
|
||||
observed_at_ms: u64,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
sources: Vec<String>,
|
||||
}
|
||||
|
||||
fn market_binding(raw: &Value) -> Result<(Market, u8, &'static str)> {
|
||||
ensure!(
|
||||
raw["version"] == "v2",
|
||||
"PositionManager probe requires a V2 Gamma market"
|
||||
);
|
||||
let market = Market::parse(raw)?;
|
||||
let cid = market.report["position_condition_id"]
|
||||
.as_str()
|
||||
.context("missing encoded condition")?;
|
||||
let hex = hex_data(cid, 31)?;
|
||||
let gamma_condition = market.report["condition_id"]
|
||||
.as_str()
|
||||
.context("missing Gamma condition ID")?;
|
||||
// Gamma can publish a bytes32 representation of the left-aligned bytes31.
|
||||
let gamma_condition = match gamma_condition.len() {
|
||||
64 => hex_data(gamma_condition, 31)?,
|
||||
66 => hex_data(gamma_condition, 32)?
|
||||
.strip_suffix("00")
|
||||
.context("invalid Gamma condition ID padding")?,
|
||||
_ => anyhow::bail!("invalid Gamma condition ID length"),
|
||||
};
|
||||
ensure!(
|
||||
gamma_condition.eq_ignore_ascii_case(hex),
|
||||
"Gamma condition ID disagrees with the Position IDs"
|
||||
);
|
||||
let (module, name) = match &hex[..2] {
|
||||
"01" => (1, "BinaryModule"),
|
||||
"02" => (2, "NegRiskModule"),
|
||||
_ => anyhow::bail!("PositionManager probe requires a Binary or NegRisk condition"),
|
||||
};
|
||||
Ok((market, module, name))
|
||||
}
|
||||
|
||||
fn module_address(registry: &str, module: u8) -> Result<String> {
|
||||
let raw = hex_data(registry, 32)?;
|
||||
ensure!(
|
||||
raw[..24].bytes().all(|digit| digit == b'0'),
|
||||
"invalid module registry address padding"
|
||||
);
|
||||
let address = format!("0x{}", &raw[24..]);
|
||||
let expected = match module {
|
||||
1 => "0x1000008dD9001B968442c1000017eaE6E0dA00Ba",
|
||||
2 => "0x200000900045e3B6259600682756002200028933",
|
||||
_ => anyhow::bail!("unsupported PositionManager module"),
|
||||
};
|
||||
ensure!(
|
||||
expected.eq_ignore_ascii_case(&address),
|
||||
"PositionManager registry differs from the published deployment"
|
||||
);
|
||||
Ok(address)
|
||||
}
|
||||
|
||||
fn uint(word_hex: &str) -> Result<u64> {
|
||||
let data = word(&format!("0x{word_hex}"))?;
|
||||
ensure!(
|
||||
data[..24].iter().all(|&byte| byte == 0),
|
||||
"unexpected ABI integer overflow"
|
||||
);
|
||||
Ok(u64::from_be_bytes(data[24..].try_into()?))
|
||||
}
|
||||
|
||||
fn result(raw: &str, module: u8) -> Result<Option<[u64; 2]>> {
|
||||
let bytes = match raw.len() {
|
||||
130 => 64,
|
||||
258 => 128,
|
||||
_ => anyhow::bail!("getResult must return an empty or two-element ABI array"),
|
||||
};
|
||||
let data = hex_data(raw, bytes)?;
|
||||
ensure!(uint(&data[..64])? == 32, "invalid getResult array offset");
|
||||
let length = uint(&data[64..128])?;
|
||||
if bytes == 64 {
|
||||
ensure!(length == 0, "invalid empty getResult array");
|
||||
return Ok(None);
|
||||
}
|
||||
ensure!(length == 2, "invalid getResult array length");
|
||||
let a = uint(&data[128..192])?;
|
||||
let b = uint(&data[192..256])?;
|
||||
ensure!(
|
||||
a.checked_add(b) == Some(DENOMINATOR),
|
||||
"invalid V2 payout denominator"
|
||||
);
|
||||
ensure!(module != 2 || a == 0 || b == 0, "nonbinary NegRisk payout");
|
||||
Ok(Some([a, b]))
|
||||
}
|
||||
|
||||
fn audit(obs: Observation, expected: Option<&str>) -> Result<Value> {
|
||||
ensure!(
|
||||
obs.chain_id == POLYGON_CHAIN_ID,
|
||||
"observation is not from Polygon mainnet"
|
||||
);
|
||||
let block = quantity(&obs.block_number)?;
|
||||
hex_data(&obs.block_hash, 32)?;
|
||||
let (market, module, name) = market_binding(&obs.market)?;
|
||||
let target = module_address(&obs.registry, module)?;
|
||||
let weights = result(&obs.result, module)?;
|
||||
let status = match weights {
|
||||
None => "unresolved",
|
||||
Some([0, _]) => "second",
|
||||
Some([_, 0]) => "first",
|
||||
Some([a, b]) if a == b => "split",
|
||||
Some(_) => "weighted",
|
||||
};
|
||||
if let Some(value) = expected {
|
||||
ensure!(
|
||||
matches!(
|
||||
value,
|
||||
"unresolved" | "first" | "second" | "split" | "weighted"
|
||||
),
|
||||
"invalid expected V2 payout status"
|
||||
);
|
||||
}
|
||||
Ok(
|
||||
json!({"observation":obs,"block":block,"position_manager":POSITION_MANAGER,"module":name,
|
||||
"module_id":module,"module_contract":target,
|
||||
"position_condition_id":market.report["position_condition_id"],
|
||||
"outcomes":market.report["outcomes"],"status":status,
|
||||
"payout_denominator":weights.map(|_|DENOMINATOR.to_string()),
|
||||
"payout_numerators":weights.map(|weights|weights.map(|v|v.to_string())),
|
||||
"expected":expected,"matches":expected.map(|v|v==status)}),
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn inspect(client: &Client, file: &str, expected: Option<&str>) -> Result<Value> {
|
||||
let market: Value = serde_json::from_reader(std::fs::File::open(file)?)?;
|
||||
let (binding, module, _) = market_binding(&market)?;
|
||||
let cid = hex_data(
|
||||
binding.report["position_condition_id"]
|
||||
.as_str()
|
||||
.context("missing condition")?,
|
||||
31,
|
||||
)?;
|
||||
let block = FinalizedRpc::connect(client)?;
|
||||
let registry = block.call(POSITION_MANAGER, &format!("0x{MODULE_BY_ID}{module:064x}"))?;
|
||||
let address = module_address(®istry, module)?;
|
||||
// Solidity bytes31 is left-aligned in its ABI word. The final byte is padding.
|
||||
let result = block.call(&address, &format!("0x{GET_RESULT}{cid}00"))?;
|
||||
let observed_at_ms = block.confirm()?;
|
||||
let market = Value::Object(
|
||||
[
|
||||
"id",
|
||||
"slug",
|
||||
"version",
|
||||
"conditionId",
|
||||
"positionIds",
|
||||
"outcomes",
|
||||
"outcomePrices",
|
||||
]
|
||||
.into_iter()
|
||||
.filter_map(|key| market.get(key).map(|value| (key.to_owned(), value.clone())))
|
||||
.collect(),
|
||||
);
|
||||
audit(
|
||||
Observation {
|
||||
chain_id: POLYGON_CHAIN_ID,
|
||||
block_number: block.number,
|
||||
block_hash: block.hash,
|
||||
market,
|
||||
registry,
|
||||
result,
|
||||
observed_at_ms,
|
||||
sources: Vec::new(),
|
||||
},
|
||||
expected,
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn replay(file: &str, expected: Option<&str>) -> Result<Vec<Value>> {
|
||||
let raw: Value = serde_json::from_reader(std::fs::File::open(file)?)?;
|
||||
let rows = match raw {
|
||||
Value::Array(rows) => rows,
|
||||
value => vec![value],
|
||||
};
|
||||
ensure!(!rows.is_empty(), "no V2 observations in file");
|
||||
rows.into_iter()
|
||||
.map(|row| {
|
||||
let obs = serde_json::from_value(row.get("observation").cloned().unwrap_or(row))?;
|
||||
audit(obs, expected)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn abi(values: &[u64]) -> String {
|
||||
let mut encoded = String::from("0x");
|
||||
for value in values {
|
||||
encoded.push_str(&format!("{value:064x}"));
|
||||
}
|
||||
encoded
|
||||
}
|
||||
|
||||
const LIVE: &str = include_str!("../fixtures/live-position-resolutions.json");
|
||||
|
||||
#[test]
|
||||
fn replay_binary_observation_preserves_gamma_outcome_order() -> Result<()> {
|
||||
let [obs]: [Observation; 1] = serde_json::from_str(LIVE)?;
|
||||
let report = audit(obs, Some("first"))?;
|
||||
assert_eq!(report["status"], "first");
|
||||
assert_eq!(report["matches"], true);
|
||||
assert_eq!(report["outcomes"][0]["label"], "Nikolenko Anatolii");
|
||||
assert_eq!(report["payout_numerators"], json!(["1000000", "0"]));
|
||||
assert_eq!(report["payout_denominator"], "1000000");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_mismatched_condition_and_unexpected_module_address() -> Result<()> {
|
||||
let [mut obs]: [Observation; 1] = serde_json::from_str(LIVE)?;
|
||||
assert!(module_address(&obs.registry, 2).is_err());
|
||||
let condition = obs.market["conditionId"].as_str().unwrap();
|
||||
let unpadded = condition.strip_suffix("00").unwrap().to_owned();
|
||||
let wrong_padding = format!("{unpadded}01");
|
||||
obs.market["conditionId"] = json!(unpadded);
|
||||
assert!(market_binding(&obs.market).is_ok());
|
||||
obs.market["conditionId"] = json!(wrong_padding);
|
||||
assert!(market_binding(&obs.market).is_err());
|
||||
obs.market["conditionId"] = json!(format!("0x02{}", "00".repeat(30)));
|
||||
assert!(market_binding(&obs.market).is_err());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_unresolved_and_resolved_weights_and_rejects_malformed_abi() -> Result<()> {
|
||||
assert_eq!(result(&abi(&[32, 0]), 1)?, None);
|
||||
assert_eq!(
|
||||
result(&abi(&[32, 2, 0, 1_000_000]), 2)?,
|
||||
Some([0, 1_000_000])
|
||||
);
|
||||
let fractional = abi(&[32, 2, 700_000, 300_000]);
|
||||
assert_eq!(result(&fractional, 1)?, Some([700_000, 300_000]));
|
||||
assert!(result(&fractional, 2).is_err());
|
||||
for bad in [
|
||||
abi(&[64, 0]),
|
||||
abi(&[32, 2]),
|
||||
abi(&[32, 1, 0, 1_000_000]),
|
||||
abi(&[32, 2, 0, 999_999]),
|
||||
abi(&[32, 2, 0, 1_000_000, 0]),
|
||||
format!("0x1{}", &fractional[3..]),
|
||||
] {
|
||||
assert!(result(&bad, 1).is_err());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -417,13 +417,9 @@ 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)
|
||||
官方日终快照在次日 UTC 零点切断,结合当时持仓、价格来源和历史成本。本地先提供交易账本的历史份额。首次启用时原子记录当前余额作为历史起点,之后逐事务记录变化,保留可用份额和挂卖预留的合计。同毫秒以写入序号定序;查询排除切点本身。旧流水里没有可信时间或分侧数量的部分不能精确回填。公开快照按钱包和闭日读取,份额小于或等于 0.1 的仓位被省略。价格取切点前兑付结果、最近可用的窄价差中点或末笔交易,再回退到成本。成本由切点前的成交、拆分、合并和兑付流水重放,并与历史份额核对。本地拆分将抵押成本各半分给 YES 和 NO,最小单位余数归 NO。合并及部分兑付按减少的份额移除平均成本。新流水用跨表写入序号定序。无法确认顺序的同毫秒旧流水及缺少逐腿成本的互斥转换返回零成本。模拟账本中的区块号为 null,资产字段使用本地 ID,只覆盖本地单盘。生产行情采样、结构仓位和组合成本仍待对照。[官方日终持仓快照](https://docs.polymarket.com/api-reference/wallet/snapshot-a-wallets-positions-at-the-end-of-a-day)
|
||||
|
||||
### Data API 账户持仓价值
|
||||
|
||||
|
||||
Reference in new issue
Block a user