Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 284c6ee4ec | |||
| f220cd4b58 |
Generated
-49
@@ -2,12 +2,6 @@
|
||||
# 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"
|
||||
@@ -123,7 +117,6 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"exchange",
|
||||
"flate2",
|
||||
"percent-encoding",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -150,15 +143,6 @@ 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"
|
||||
@@ -247,17 +231,6 @@ 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"
|
||||
@@ -674,16 +647,6 @@ 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"
|
||||
@@ -1095,12 +1058,6 @@ 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"
|
||||
@@ -1735,12 +1692,6 @@ 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,4 +12,3 @@ tungstenite = "0.28"
|
||||
tiny_http = "0.12"
|
||||
serde_urlencoded = "0.7"
|
||||
percent-encoding = "2"
|
||||
flate2 = "1"
|
||||
|
||||
@@ -247,40 +247,6 @@ 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
|
||||
@@ -351,23 +317,6 @@ sequenceDiagram
|
||||
E-->>C: 剩余成交,末页 next_cursor 为空
|
||||
```
|
||||
|
||||
### 组合持仓与活动 HTTP
|
||||
|
||||
重放[组合账本样例](../../docs/examples/combo-ledger.jsonl)后,`GET /v2/positions/combos?user=alice&status=RESOLVED_PARTIAL` 返回已兑付的两侧持仓。要查询这些操作的记录,使用 `GET /v2/activity/combos?user=alice&limit=1`,然后按返回的 `pagination.next_cursor` 续读。只传原来的 `user` 和 `cursor` 即可。若重放[询价样例](../../docs/examples/combo-rfq.jsonl),用 `user=taker` 或 `user=maker` 查看成交后的剩余份额和成本。
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
actor C as 目录客户端
|
||||
participant H as market_http.rs
|
||||
participant E as Exchange
|
||||
C->>H: GET /v2/activity/combos?user=alice&limit=1
|
||||
H->>E: 读取第一页
|
||||
E-->>H: 最新的兑付记录与游标
|
||||
C->>H: 同一个 user 和 next_cursor
|
||||
H->>E: 验证游标签名并向后寻址
|
||||
H-->>C: 较早的生命周期活动
|
||||
```
|
||||
|
||||
### 裁决状态
|
||||
|
||||
`GET /v2/resolutions?condition=m` 读取单盘状态,`?event_id=1` 读取事件的各个盘口。已登记问题标识的乐观裁决市场也支持 question_id 查询。多个条件或多个事件用逗号分隔,每次选择一种查询方式。
|
||||
@@ -389,16 +338,6 @@ 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 秒内只能成功开始一次,续页不限。闭日按数据库历史起点及本地午夜后一小时确定。成本使用切点前的成交、拆分、合并和兑付流水重建。遇到缺少可核验成本的仓位,成本返回零。
|
||||
|
||||
日终响应的 `data` 同时包含单盘和组合,组合使用 `module=3`,标题和 slug 字段为 null。组合依次按切点前的结算、同侧实际成交价和成本估值。第一页的 `summary` 汇总两类仓位,续页继续使用原游标。
|
||||
|
||||
### 查询持仓价值
|
||||
|
||||
`GET /v2/value?user=alice&condition=e` 返回该账户在市场 e 的持仓价值,单位为模拟美元。使用已登记的本地账户名或 20 字节钱包地址。省略 condition 查询所有已持有市场。无持仓的钱包返回零,仅有现金的账户也返回零。
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
mod market_http;
|
||||
mod market_ws;
|
||||
mod snapshot_http;
|
||||
mod stream;
|
||||
mod subscriptions;
|
||||
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
use crate::snapshot_http;
|
||||
use anyhow::Result;
|
||||
use exchange::{Exchange, HistoryError};
|
||||
use percent_encoding::percent_decode_str;
|
||||
@@ -324,26 +323,13 @@ fn clarifications(engine: &Mutex<Exchange>, query: &str) -> Reply {
|
||||
Ok(Value::Array(rows))
|
||||
}
|
||||
|
||||
fn respond(
|
||||
mut req: Request,
|
||||
engine: &Mutex<Exchange>,
|
||||
snapshots: &snapshot_http::Starts,
|
||||
) -> std::io::Result<()> {
|
||||
fn respond(mut req: Request, engine: &Mutex<Exchange>) -> 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,
|
||||
"/v2/prices-history"
|
||||
| "/v2/trades"
|
||||
| "/v2/resolutions"
|
||||
| "/v2/value"
|
||||
| "/v2/oi"
|
||||
| "/v2/positions/combos"
|
||||
| "/v2/activity/combos"
|
||||
"/v2/prices-history" | "/v2/trades" | "/v2/resolutions" | "/v2/value" | "/v2/oi"
|
||||
)
|
||||
{
|
||||
let (status, body) = data_page(path, params, engine);
|
||||
@@ -489,8 +475,6 @@ fn respond(
|
||||
| "/v2/value"
|
||||
| "/v2/trades"
|
||||
| "/v2/resolutions"
|
||||
| "/v2/positions/combos"
|
||||
| "/v2/activity/combos"
|
||||
| "/v2/prices-history",
|
||||
) => {
|
||||
allow = Some("GET");
|
||||
@@ -532,8 +516,6 @@ fn data_page(path: &str, params: &str, engine: &Mutex<Exchange>) -> (u16, Value)
|
||||
"/v2/oi" => read_page(params, engine, Exchange::public_open_interest),
|
||||
"/v2/value" => read_page(params, engine, Exchange::public_portfolio_value),
|
||||
"/v2/trades" => read_page(params, engine, Exchange::public_trade_feed),
|
||||
"/v2/positions/combos" => read_page(params, engine, Exchange::public_combo_positions),
|
||||
"/v2/activity/combos" => read_page(params, engine, Exchange::public_combo_activity),
|
||||
"/v2/resolutions" => read_page(params, engine, Exchange::public_resolutions),
|
||||
_ => read_page(params, engine, Exchange::public_price_history),
|
||||
};
|
||||
@@ -555,14 +537,6 @@ fn data_page(path: &str, params: &str, engine: &Mutex<Exchange>) -> (u16, Value)
|
||||
500,
|
||||
json!({"code":"internal","error":"resolution state unavailable","retryable":true}),
|
||||
),
|
||||
Err(HistoryError::Unavailable)
|
||||
if matches!(path, "/v2/positions/combos" | "/v2/activity/combos") =>
|
||||
{
|
||||
(
|
||||
503,
|
||||
json!({"code":"dependency_unavailable","error":"combo portfolio unavailable","retryable":true}),
|
||||
)
|
||||
}
|
||||
Err(HistoryError::Unavailable) if path == "/v2/trades" => (
|
||||
500,
|
||||
json!({"code":"internal","error":"trade feed unavailable","retryable":true}),
|
||||
@@ -590,12 +564,11 @@ 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, &snapshots) {
|
||||
if let Err(err) = respond(req, &engine) {
|
||||
eprintln!("market HTTP response: {err}");
|
||||
}
|
||||
}
|
||||
@@ -719,11 +692,6 @@ mod tests {
|
||||
assert_eq!(quoted["outcomePrices"], r#"["0.4","0.6"]"#);
|
||||
let empty_trades = json!({"data":[],"pagination":{"limit":100,"offset":0,"has_more":false,"next_cursor":null}});
|
||||
let cases = [
|
||||
("GET","/v2/positions/combos?user=unknown",String::new(),200,Some(json!({"data":[],"pagination":{"limit":100,"offset":0,"has_more":false,"next_cursor":null}}))),
|
||||
("GET","/v2/activity/combos?user=unknown",String::new(),200,Some(json!({"data":[],"pagination":{"limit":100,"offset":0,"has_more":false,"next_cursor":null}}))),
|
||||
("GET","/v2/activity/combos",String::new(),400,None),
|
||||
("GET","/v2/positions/combos?user=alice&condition=no",String::new(),400,None),
|
||||
("POST","/v2/activity/combos",String::new(),405,None),
|
||||
("GET","/v2/oi?conditionId=s,s",String::new(),200,Some(json!({"data":[{"condition_id":"s","value":0}]}))),
|
||||
("GET","/v2/oi?condition_id=0x0000000000000000000000000000000000000000000000000000000000000001",String::new(),200,Some(json!({"data":[]}))),
|
||||
("GET","/v2/oi?condition=bad-hash",String::new(),400,Some(json!({"code":"invalid_request","error":"invalid condition: bad-hash","retryable":false}))),
|
||||
@@ -893,8 +861,6 @@ 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),
|
||||
];
|
||||
@@ -906,7 +872,7 @@ mod tests {
|
||||
.recv_timeout(Duration::from_secs(5))
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
respond(req, &db, &snapshot_http::Starts::default()).unwrap();
|
||||
respond(req, &db).unwrap();
|
||||
}
|
||||
});
|
||||
for (method, path, body, status, expected) in cases {
|
||||
|
||||
@@ -1,148 +0,0 @@
|
||||
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)
|
||||
}
|
||||
@@ -29,24 +29,6 @@ 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"]
|
||||
api -->|读取公开组合持仓和活动| combo_portfolio["src/combo_portfolio/http.rs"]
|
||||
snapshot["src/portfolio/snapshot.rs"] -->|计算组合日终余额和估值| combo_snapshot["src/combo_portfolio/snapshot.rs"]
|
||||
combo_snapshot -->|重放历史组合成本| combo_basis
|
||||
combo_snapshot --> combo_mark["src/combo_portfolio/snapshot_prices.sql"]
|
||||
combo_snapshot --> combo_legs["src/combo_portfolio/snapshot_legs.sql"]
|
||||
combo_portfolio -->|重放与核对组合份额| combo_basis["src/combo_portfolio.rs"]
|
||||
combo_basis -->|按共同写入序号取成交和钱包操作| combo_events["src/combo_portfolio_events.sql"]
|
||||
combo_basis -->|核对可用与预留份额| combo_balances["src/combo_portfolio_balances.sql"]
|
||||
combo_events --> combo_order["src/combo_portfolio_schema.sql"]
|
||||
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
|
||||
@@ -241,50 +223,6 @@ 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->>D: 重放切点前的组合流水并读取腿裁决与组合成交价
|
||||
E->>E: 按结算价、成交价或成本估值组合,合并两类持仓
|
||||
E-->>H: 首屏总额、当页持仓和签名游标
|
||||
H-->>C: gzip 响应
|
||||
```
|
||||
|
||||
## GTD 到期
|
||||
|
||||
```mermaid
|
||||
@@ -462,51 +400,6 @@ 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` 从同一条命名记录生成展示字段。
|
||||
@@ -1399,24 +1292,6 @@ sequenceDiagram
|
||||
E-->>C: resolved,每份 YES 和 NO 各兑付 500000 微单位
|
||||
```
|
||||
|
||||
### 组合持仓与生命周期活动
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
actor C as 客户端
|
||||
participant H as 组合 Data API
|
||||
participant E as combo_portfolio.rs
|
||||
participant D as SQLite
|
||||
C->>H: GET /v2/positions/combos,传钱包和可选游标
|
||||
H->>E: 校验分页范围并读取一致快照
|
||||
E->>D: 按共同写入序号重放成交、拆分、合并和兑付
|
||||
E->>D: 核对可用及预留份额,并读取各腿裁决
|
||||
H-->>C: 成本、状态及续页游标
|
||||
C->>H: GET /v2/activity/combos
|
||||
H->>D: 按本地序号倒序读取钱包操作
|
||||
H-->>C: 拆分、合并、兑付及各腿详情
|
||||
```
|
||||
|
||||
### 账户持仓估值
|
||||
|
||||
公开估值在同一份账本快照中读取可用份额、挂卖锁定份额、盘口和裁决。若所选市场有非零持仓缺少估值依据,客户端可以重试;JSONL 的 portfolio_value 另提供已定价的小计和缺价数量。
|
||||
|
||||
@@ -261,10 +261,6 @@ 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 {
|
||||
@@ -298,17 +294,6 @@ 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,
|
||||
@@ -328,9 +313,6 @@ 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),
|
||||
@@ -347,9 +329,6 @@ 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),
|
||||
|
||||
@@ -1,357 +0,0 @@
|
||||
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)
|
||||
}
|
||||
|
||||
pub(super) struct Factor {
|
||||
down: u128,
|
||||
up: u128,
|
||||
}
|
||||
|
||||
impl Factor {
|
||||
pub(super) 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),
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) 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),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn status(&self, side: Side) -> &'static str {
|
||||
match (side, self.down, self.up) {
|
||||
(Side::Yes, 0, _) | (Side::No, _, FACTOR_UNIT) => "RESOLVED_LOSS",
|
||||
(Side::Yes, FACTOR_UNIT, _) | (Side::No, _, 0) => "RESOLVED_WIN",
|
||||
_ => "RESOLVED_PARTIAL",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
pub(super) 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)
|
||||
}
|
||||
|
||||
pub(super) 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);
|
||||
}
|
||||
}
|
||||
@@ -1,301 +0,0 @@
|
||||
mod http;
|
||||
pub(super) mod snapshot;
|
||||
|
||||
pub use http::{ComboActivityQuery, ComboPositionsQuery};
|
||||
|
||||
use crate::{
|
||||
assets,
|
||||
combo::{Factor, Side, SELECT_LEGS},
|
||||
gamma_directory::market,
|
||||
inventory::{decimal, UNIT},
|
||||
MarketDataError,
|
||||
};
|
||||
use rusqlite::{params, Connection};
|
||||
use serde_json::{json, Value};
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
|
||||
#[derive(Clone, Copy, Default)]
|
||||
struct Basis {
|
||||
held: i128,
|
||||
principal: i128,
|
||||
redeemed: i128,
|
||||
redeemed_principal: i128,
|
||||
payout: i128,
|
||||
first: i64,
|
||||
updated: i64,
|
||||
}
|
||||
|
||||
impl Basis {
|
||||
fn apply(
|
||||
&mut self,
|
||||
operation: &str,
|
||||
at: i64,
|
||||
qty: i128,
|
||||
cash: i128,
|
||||
) -> Result<(), MarketDataError> {
|
||||
match operation {
|
||||
"BUY" if qty > 0 && cash >= 0 => {
|
||||
if self.first == 0 {
|
||||
self.first = at;
|
||||
}
|
||||
self.held += qty;
|
||||
self.principal += cash;
|
||||
}
|
||||
"SELL" | "REDEEM" if qty > 0 && qty <= self.held => {
|
||||
let removed = self
|
||||
.principal
|
||||
.checked_mul(qty)
|
||||
.ok_or(MarketDataError::Unavailable)?
|
||||
/ self.held;
|
||||
self.held -= qty;
|
||||
self.principal -= removed;
|
||||
if operation == "REDEEM" {
|
||||
self.redeemed += qty;
|
||||
self.redeemed_principal += removed;
|
||||
self.payout += cash;
|
||||
}
|
||||
}
|
||||
_ => return Err(MarketDataError::Unavailable),
|
||||
}
|
||||
self.updated = self.updated.max(at);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn basis(self) -> (i128, i128, i128) {
|
||||
let (principal, qty) = if self.held > 0 {
|
||||
(self.principal, self.held)
|
||||
} else {
|
||||
(self.redeemed_principal, self.redeemed)
|
||||
};
|
||||
let scale = i128::from(UNIT);
|
||||
let avg = if qty == 0 {
|
||||
0
|
||||
} else {
|
||||
(principal * scale + qty / 2) / qty
|
||||
};
|
||||
(avg, (avg * qty + scale / 2) / scale, principal)
|
||||
}
|
||||
}
|
||||
|
||||
struct Settlement {
|
||||
factor: Option<Factor>,
|
||||
total: usize,
|
||||
pending: usize,
|
||||
updated: i64,
|
||||
resolved: Option<i64>,
|
||||
}
|
||||
|
||||
impl Settlement {
|
||||
fn read(db: &Connection, combo: &str) -> rusqlite::Result<Self> {
|
||||
let mut stmt = db.prepare_cached(SELECT_LEGS)?;
|
||||
let mut payouts = Vec::new();
|
||||
let mut dated = 0;
|
||||
let mut updated = 0;
|
||||
let mut rows = stmt.query([combo])?;
|
||||
while let Some(row) = rows.next()? {
|
||||
payouts.push(row.get::<_, Option<i64>>(2)?);
|
||||
if let Some(at) = row.get::<_, Option<i64>>(3)? {
|
||||
dated += 1;
|
||||
updated = updated.max(at);
|
||||
}
|
||||
}
|
||||
let total = payouts.len();
|
||||
let pending = payouts.iter().filter(|p| p.is_none()).count();
|
||||
Ok(Self {
|
||||
factor: Factor::resolved(&payouts),
|
||||
total,
|
||||
pending,
|
||||
updated,
|
||||
resolved: (total > 0 && dated == total).then_some(updated),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct Position {
|
||||
combo: String,
|
||||
index: u8,
|
||||
basis: Basis,
|
||||
status: &'static str,
|
||||
redeemable: bool,
|
||||
}
|
||||
|
||||
fn side(index: u8) -> Side {
|
||||
if index == 0 {
|
||||
Side::Yes
|
||||
} else {
|
||||
Side::No
|
||||
}
|
||||
}
|
||||
|
||||
fn basis_entries(
|
||||
db: &Connection,
|
||||
user: &str,
|
||||
conditions: &str,
|
||||
before: Option<i64>,
|
||||
) -> Result<BTreeMap<(String, u8), Basis>, MarketDataError> {
|
||||
let mut stmt = db.prepare_cached(include_str!("combo_portfolio_events.sql"))?;
|
||||
let mut rows = stmt.query(params![user, conditions, before])?;
|
||||
let mut entries = BTreeMap::<(String, u8), Basis>::new();
|
||||
while let Some(row) = rows.next()? {
|
||||
let outcome = row.get::<_, String>(1)?;
|
||||
let entry = entries
|
||||
.entry((row.get(0)?, u8::from(outcome == "NO")))
|
||||
.or_default();
|
||||
entry.apply(
|
||||
&row.get::<_, String>(3)?,
|
||||
row.get(2)?,
|
||||
i128::from(row.get::<_, i64>(4)?),
|
||||
i128::from(row.get::<_, i64>(5)?),
|
||||
)?;
|
||||
}
|
||||
Ok(entries)
|
||||
}
|
||||
|
||||
fn load_positions(
|
||||
db: &Connection,
|
||||
user: &str,
|
||||
conditions: &str,
|
||||
) -> Result<(Vec<Position>, HashMap<String, Settlement>), MarketDataError> {
|
||||
let entries = basis_entries(db, user, conditions, None)?;
|
||||
let mut balance_stmt = db.prepare_cached(include_str!("combo_portfolio_balances.sql"))?;
|
||||
let mut balances = balance_stmt.query(params![user, conditions])?;
|
||||
let mut held = BTreeMap::new();
|
||||
while let Some(row) = balances.next()? {
|
||||
let outcome = row.get::<_, String>(1)?;
|
||||
held.insert(
|
||||
(row.get::<_, String>(0)?, u8::from(outcome == "NO")),
|
||||
i128::from(row.get::<_, i64>(2)?),
|
||||
);
|
||||
}
|
||||
if entries
|
||||
.iter()
|
||||
.any(|(key, basis)| held.remove(key).unwrap_or(0) != basis.held)
|
||||
|| !held.is_empty()
|
||||
{
|
||||
return Err(MarketDataError::Unavailable);
|
||||
}
|
||||
let mut states = HashMap::new();
|
||||
let mut positions = Vec::new();
|
||||
for ((combo, index), mut basis) in entries {
|
||||
if !states.contains_key(&combo) {
|
||||
states.insert(combo.clone(), Settlement::read(db, &combo)?);
|
||||
}
|
||||
let settlement = &states[&combo];
|
||||
basis.updated = basis.updated.max(settlement.updated);
|
||||
let (status, redeemable) = match &settlement.factor {
|
||||
Some(factor) => {
|
||||
let status = factor.status(side(index));
|
||||
let held = i64::try_from(basis.held).map_err(|_| MarketDataError::Unavailable)?;
|
||||
if held > 0 && factor.payout(side(index), held) > 0 {
|
||||
("REDEEMABLE", true)
|
||||
} else {
|
||||
(status, false)
|
||||
}
|
||||
}
|
||||
None if settlement.pending < settlement.total => ("PARTIAL", false),
|
||||
None => ("OPEN", false),
|
||||
};
|
||||
positions.push(Position {
|
||||
combo,
|
||||
index,
|
||||
basis,
|
||||
status,
|
||||
redeemable,
|
||||
});
|
||||
}
|
||||
Ok((positions, states))
|
||||
}
|
||||
|
||||
fn iso(db: &Connection, at: Option<i64>) -> rusqlite::Result<Option<String>> {
|
||||
db.prepare_cached("SELECT strftime('%Y-%m-%dT%H:%M:%fZ',?/1000.0,'unixepoch')")?
|
||||
.query_row([at], |r| r.get(0))
|
||||
}
|
||||
|
||||
fn leg_details(db: &Connection, combo: &str) -> Result<Vec<Value>, MarketDataError> {
|
||||
let sql=concat!(
|
||||
"SELECT g.*,l.outcome AS leg_outcome,s.at_ms AS leg_at,
|
||||
e.event_id AS leg_event_id,e.slug AS leg_event_slug,e.title AS leg_event_title,e.category AS leg_category
|
||||
FROM combo_legs l JOIN (",include_str!("gamma_market.sql"),") g ON g.market=l.market
|
||||
LEFT JOIN price_settlements s ON s.market=l.market
|
||||
LEFT JOIN numbered_events e ON e.id=g.parent
|
||||
WHERE l.combo=? ORDER BY l.market",
|
||||
);
|
||||
let mut stmt = db.prepare_cached(sql)?;
|
||||
let mut rows = stmt.query([combo])?;
|
||||
let mut result = Vec::new();
|
||||
while let Some(row) = rows.next()? {
|
||||
let condition = row.get::<_, String>("market")?;
|
||||
let outcome = row.get::<_, String>("leg_outcome")?;
|
||||
let index = usize::from(outcome == "NO");
|
||||
let winner = row.get::<_, Option<String>>("winner")?;
|
||||
let status = match winner.as_deref() {
|
||||
None => "OPEN",
|
||||
Some("VOID") => "RESOLVED_PARTIAL",
|
||||
Some(w) if w == outcome => "RESOLVED_WIN",
|
||||
Some(_) => "RESOLVED_LOSS",
|
||||
};
|
||||
let view = market(row)?;
|
||||
let labels = [
|
||||
row.get::<_, String>("yes_label")?,
|
||||
row.get::<_, String>("no_label")?,
|
||||
];
|
||||
let price = view["outcomePrices"]
|
||||
.as_str()
|
||||
.and_then(|s| serde_json::from_str::<[String; 2]>(s).ok())
|
||||
.and_then(|a| a[index].parse::<serde_json::Number>().ok());
|
||||
let event_id = row
|
||||
.get::<_, Option<i64>>("leg_event_id")?
|
||||
.map(|id| id.to_string())
|
||||
.unwrap_or_default();
|
||||
let event_slug = row
|
||||
.get::<_, Option<String>>("leg_event_slug")?
|
||||
.unwrap_or_default();
|
||||
let event_title = row
|
||||
.get::<_, Option<String>>("leg_event_title")?
|
||||
.unwrap_or_default();
|
||||
let category = row
|
||||
.get::<_, Option<String>>("leg_category")?
|
||||
.unwrap_or_default();
|
||||
let title = view["groupItemTitle"]
|
||||
.as_str()
|
||||
.or_else(|| view["question"].as_str())
|
||||
.unwrap_or("");
|
||||
result.push(json!({
|
||||
"leg_index":result.len(),"leg_position_id":assets::id(&condition,&outcome),"leg_condition_id":condition,
|
||||
"leg_outcome_index":index,"leg_outcome_label":labels[index],"leg_status":status,
|
||||
"leg_resolved_at":iso(db,row.get("leg_at")?)?,"leg_current_price":price,
|
||||
"market":{
|
||||
"market_id":view["id"],"slug":view["slug"],"title":title,
|
||||
"question":view["question"],"group_item_title":view["groupItemTitle"].as_str().unwrap_or(""),
|
||||
"outcome":labels[index],"outcomes":labels,"image_url":"","icon_url":"","category":category,
|
||||
"subcategory":"","tags":[],"end_date":"","line":null,"sports_market_type":"",
|
||||
"event":{"event_id":event_id,"event_slug":event_slug,"event_title":event_title,"event_image":""}
|
||||
}
|
||||
}));
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
impl Position {
|
||||
fn wire(
|
||||
&self,
|
||||
db: &Connection,
|
||||
wallet: &str,
|
||||
settlement: &Settlement,
|
||||
legs: &[Value],
|
||||
) -> Result<Value, MarketDataError> {
|
||||
let (avg, rounded, gross) = self.basis.basis();
|
||||
Ok(json!({
|
||||
"combo_condition_id":self.combo,"outcome_index":self.index,"outcome_label":if self.index==0 {"Yes"} else {"No"},
|
||||
"combo_position_id":crate::combo::position_id(&self.combo,side(self.index)),"proxy_wallet":wallet,
|
||||
"current_size":decimal(self.basis.held,UNIT),"entry_avg_price_usdc":decimal(avg,UNIT),
|
||||
"entry_cost_usdc":decimal(rounded,UNIT),"gross_entry_cost_usdc":decimal(gross,UNIT),
|
||||
"entry_fees_usdc":0,"realized_payout_usdc":decimal(self.basis.payout,UNIT),
|
||||
"status":self.status,"redeemable":self.redeemable,
|
||||
"first_entry_at":iso(db,Some(self.basis.first))?,"first_entry_at_micros":self.basis.first*1000,
|
||||
"legs_total":settlement.total,"legs_resolved":settlement.total-settlement.pending,
|
||||
"legs_pending":settlement.pending,"legs":legs,"resolved_at":iso(db,settlement.resolved)?,
|
||||
"updated_at":iso(db,Some(self.basis.updated))?,"updated_at_micros":self.basis.updated*1000
|
||||
}))
|
||||
}
|
||||
}
|
||||
@@ -1,462 +0,0 @@
|
||||
use super::{leg_details, load_positions, side, Position};
|
||||
use crate::{
|
||||
combo,
|
||||
inventory::{decimal, UNIT},
|
||||
portfolio::protocol::CONTRACTS,
|
||||
validation::{hex_id, identifier},
|
||||
Exchange, MarketDataError,
|
||||
};
|
||||
use data_encoding::BASE64URL_NOPAD;
|
||||
use hmac::{Hmac, Mac};
|
||||
use rusqlite::{params, Connection};
|
||||
use serde::{de::DeserializeOwned, Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
use sha2::Sha256;
|
||||
use std::collections::HashMap;
|
||||
|
||||
fn invalid(message: impl Into<String>) -> MarketDataError {
|
||||
MarketDataError::Invalid(message.into())
|
||||
}
|
||||
|
||||
fn wallet(user: Option<String>) -> Result<String, MarketDataError> {
|
||||
let user = user.ok_or_else(|| invalid("user is required"))?;
|
||||
identifier(&user).map_err(|_| invalid("invalid user wallet"))?;
|
||||
let lower = user.to_ascii_lowercase();
|
||||
if lower.starts_with("0x") {
|
||||
if CONTRACTS
|
||||
.iter()
|
||||
.any(|known| known.eq_ignore_ascii_case(&lower))
|
||||
|| !hex_id(&lower, 40)
|
||||
{
|
||||
return Err(invalid("invalid user wallet"));
|
||||
}
|
||||
Ok(lower)
|
||||
} else {
|
||||
Ok(user)
|
||||
}
|
||||
}
|
||||
|
||||
fn conditions(value: String) -> Result<Vec<String>, MarketDataError> {
|
||||
let mut ids = Vec::new();
|
||||
for id in value.split(',').map(|s| s.trim().to_ascii_lowercase()) {
|
||||
let supported = id
|
||||
.strip_prefix("combo:")
|
||||
.is_some_and(|id| id.len() == 64 && id.bytes().all(|b| b.is_ascii_hexdigit()))
|
||||
|| (id.starts_with("0x03") && hex_id(&id, 64));
|
||||
if !supported {
|
||||
return Err(invalid(format!("invalid condition: {id}")));
|
||||
}
|
||||
ids.push(id);
|
||||
}
|
||||
ids.sort_unstable();
|
||||
ids.dedup();
|
||||
if ids.len() > 20 {
|
||||
return Err(invalid("at most 20 conditions"));
|
||||
}
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
fn mac(db: &Connection, domain: &[u8]) -> 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).expect("HMAC accepts any key length");
|
||||
mac.update(domain);
|
||||
Ok(mac)
|
||||
}
|
||||
|
||||
fn encode<T: Serialize>(
|
||||
db: &Connection,
|
||||
domain: &[u8],
|
||||
page: &T,
|
||||
) -> Result<String, MarketDataError> {
|
||||
let mut data = serde_json::to_vec(page).map_err(|_| MarketDataError::Unavailable)?;
|
||||
let mut mac = mac(db, domain)?;
|
||||
mac.update(&data);
|
||||
data.extend_from_slice(&mac.finalize().into_bytes());
|
||||
Ok(BASE64URL_NOPAD.encode(&data))
|
||||
}
|
||||
|
||||
fn decode<T: DeserializeOwned>(
|
||||
db: &Connection,
|
||||
domain: &[u8],
|
||||
token: &str,
|
||||
) -> Result<T, MarketDataError> {
|
||||
let bad = || invalid("invalid combo cursor");
|
||||
if token.len() > 4096 {
|
||||
return Err(bad());
|
||||
}
|
||||
let data = BASE64URL_NOPAD
|
||||
.decode(token.as_bytes())
|
||||
.map_err(|_| bad())?;
|
||||
let split = data.len().checked_sub(32).ok_or_else(bad)?;
|
||||
let (body, tag) = data.split_at(split);
|
||||
let mut mac = mac(db, domain)?;
|
||||
mac.update(body);
|
||||
mac.verify_slice(tag).map_err(|_| bad())?;
|
||||
serde_json::from_slice(body).map_err(|_| bad())
|
||||
}
|
||||
|
||||
fn agree<T: PartialEq>(incoming: Option<T>, stored: &T) -> Result<(), MarketDataError> {
|
||||
if incoming.as_ref().is_some_and(|v| v != stored) {
|
||||
return Err(invalid("combo cursor filter mismatch"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn page_size(limit: Option<u32>) -> Result<u32, MarketDataError> {
|
||||
let size = limit.unwrap_or(100);
|
||||
if size > 1000 {
|
||||
return Err(invalid("invalid limit"));
|
||||
}
|
||||
Ok(size)
|
||||
}
|
||||
|
||||
fn envelope(data: Vec<Value>, limit: u32, offset: usize, cursor: Option<String>) -> Value {
|
||||
json!({"data":data,"pagination":{"limit":limit,"offset":offset,"has_more":cursor.is_some(),"next_cursor":cursor}})
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ComboActivityQuery {
|
||||
user: Option<String>,
|
||||
#[serde(alias = "condition_id", alias = "conditionId")]
|
||||
condition: Option<String>,
|
||||
cursor: Option<String>,
|
||||
limit: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct ActivityPage {
|
||||
user: String,
|
||||
conditions: Vec<String>,
|
||||
before: i64,
|
||||
limit: u32,
|
||||
offset: usize,
|
||||
}
|
||||
|
||||
const ACTIVITY_DOMAIN: &[u8] = b"eventbook:/v2/activity/combos:v1\0";
|
||||
const POSITIONS_DOMAIN: &[u8] = b"eventbook:/v2/positions/combos:v1\0";
|
||||
|
||||
impl ComboActivityQuery {
|
||||
fn read(self, db: &Connection) -> Result<Value, MarketDataError> {
|
||||
let user = wallet(self.user)?;
|
||||
let conditions = self.condition.map(conditions).transpose()?;
|
||||
let mut page: ActivityPage = if let Some(token) = self.cursor {
|
||||
let page: ActivityPage = decode(db, ACTIVITY_DOMAIN, &token)?;
|
||||
agree(Some(user), &page.user)?;
|
||||
agree(conditions, &page.conditions)?;
|
||||
page
|
||||
} else {
|
||||
ActivityPage {
|
||||
user,
|
||||
conditions: conditions.unwrap_or_default(),
|
||||
before: i64::MAX,
|
||||
limit: page_size(self.limit)?,
|
||||
offset: 0,
|
||||
}
|
||||
};
|
||||
let offset = page.offset;
|
||||
let mut stmt = db.prepare_cached(
|
||||
"SELECT seq,combo,account,kind,outcome,cash_delta_micros,at_ms
|
||||
FROM combo_movements
|
||||
WHERE (account=?1 OR (?1 LIKE '0x%' AND account COLLATE NOCASE=?1)) AND seq<?2
|
||||
AND (?3='[]' OR combo IN (SELECT value FROM json_each(?3)))
|
||||
ORDER BY seq DESC LIMIT ?4",
|
||||
)?;
|
||||
let mut rows = stmt.query(params![
|
||||
page.user,
|
||||
page.before,
|
||||
json!(page.conditions).to_string(),
|
||||
page.limit + 1
|
||||
])?;
|
||||
let mut entries = Vec::new();
|
||||
let mut cache = HashMap::new();
|
||||
let mut more = false;
|
||||
while let Some(row) = rows.next()? {
|
||||
if entries.len() >= page.limit as usize {
|
||||
more = page.limit > 0;
|
||||
break;
|
||||
}
|
||||
let seq: i64 = row.get(0)?;
|
||||
let combo: String = row.get(1)?;
|
||||
let operation: String = row.get(3)?;
|
||||
let outcome: Option<String> = row.get(4)?;
|
||||
let cash = i128::from(row.get::<_, i64>(5)?);
|
||||
if !cache.contains_key(&combo) {
|
||||
cache.insert(combo.clone(), leg_details(db, &combo)?);
|
||||
}
|
||||
entries.push(json!({
|
||||
"id":format!("combo-movement:{seq}"),"type":operation,
|
||||
"proxy_wallet":row.get::<_,String>(2)?,"combo_condition_id":combo,
|
||||
"combo_position_id":outcome.as_ref().map(|o|combo::position_id(&combo,side(u8::from(o=="NO")))).unwrap_or_default(),
|
||||
"amount_usdc":(operation!="REDEEM").then(||decimal(cash.abs(),UNIT)),
|
||||
"payout_usdc":(operation=="REDEEM").then(||decimal(cash,UNIT)),
|
||||
"timestamp":row.get::<_,i64>(6)?/1000,"block_number":null,"transaction_hash":"",
|
||||
"legs":&cache[&combo]
|
||||
}));
|
||||
page.before = seq;
|
||||
}
|
||||
page.offset += entries.len();
|
||||
let next = more
|
||||
.then(|| encode(db, ACTIVITY_DOMAIN, &page))
|
||||
.transpose()?;
|
||||
Ok(envelope(entries, page.limit, offset, next))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ComboPositionsQuery {
|
||||
user: Option<String>,
|
||||
#[serde(alias = "condition_id", alias = "conditionId")]
|
||||
condition: Option<String>,
|
||||
status: Option<String>,
|
||||
cursor: Option<String>,
|
||||
limit: Option<u32>,
|
||||
#[serde(alias = "sortBy")]
|
||||
sort_by: Option<String>,
|
||||
#[serde(alias = "sortDirection")]
|
||||
sort_direction: Option<String>,
|
||||
#[serde(alias = "updatedAfter")]
|
||||
updated_after: Option<i64>,
|
||||
#[serde(alias = "updatedBefore")]
|
||||
updated_before: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Serialize, Deserialize, PartialEq)]
|
||||
enum Sort {
|
||||
FirstEntry,
|
||||
EntryCost,
|
||||
Updated,
|
||||
}
|
||||
|
||||
impl Sort {
|
||||
fn parse(sort: String) -> Result<Self, MarketDataError> {
|
||||
match sort.to_ascii_uppercase().as_str() {
|
||||
"FIRST_ENTRY" => Ok(Self::FirstEntry),
|
||||
"ENTRY_COST" | "CURRENT_VALUE" => Ok(Self::EntryCost),
|
||||
"UPDATED" => Ok(Self::Updated),
|
||||
_ => Err(invalid("invalid combo position sort")),
|
||||
}
|
||||
}
|
||||
|
||||
fn score(self, p: &Position) -> i128 {
|
||||
match self {
|
||||
Self::FirstEntry => i128::from(p.basis.first),
|
||||
Self::EntryCost => p.basis.basis().2,
|
||||
Self::Updated => i128::from(p.basis.updated),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn statuses(value: String) -> Result<Vec<String>, MarketDataError> {
|
||||
let mut statuses = value
|
||||
.split(',')
|
||||
.map(|s| s.trim().to_ascii_uppercase())
|
||||
.collect::<Vec<_>>();
|
||||
statuses.sort_unstable();
|
||||
statuses.dedup();
|
||||
if statuses.iter().any(|s| {
|
||||
!matches!(
|
||||
s.as_str(),
|
||||
"OPEN"
|
||||
| "REDEEMABLE"
|
||||
| "PARTIAL"
|
||||
| "RESOLVED_WIN"
|
||||
| "RESOLVED_LOSS"
|
||||
| "RESOLVED_PARTIAL"
|
||||
)
|
||||
}) || (statuses.len() > 1 && statuses.iter().any(|s| s == "REDEEMABLE"))
|
||||
{
|
||||
return Err(invalid("invalid combo position status"));
|
||||
}
|
||||
Ok(statuses)
|
||||
}
|
||||
|
||||
type PositionAnchor = (i128, String, u8);
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct PositionPage {
|
||||
user: String,
|
||||
conditions: Vec<String>,
|
||||
statuses: Vec<String>,
|
||||
sort: Sort,
|
||||
descending: bool,
|
||||
after: Option<i64>,
|
||||
before: Option<i64>,
|
||||
ceiling: Option<i64>,
|
||||
limit: u32,
|
||||
offset: usize,
|
||||
anchor: Option<PositionAnchor>,
|
||||
}
|
||||
|
||||
impl PositionPage {
|
||||
fn keyset(&self) -> bool {
|
||||
matches!(
|
||||
(self.sort, self.descending),
|
||||
(Sort::FirstEntry, true) | (Sort::Updated, false)
|
||||
)
|
||||
}
|
||||
|
||||
fn keep(&self, p: &Position) -> bool {
|
||||
let time = p.basis.updated / 1000;
|
||||
if self.after.is_some_and(|min| time < min)
|
||||
|| self.before.is_some_and(|max| time > max)
|
||||
|| self
|
||||
.ceiling
|
||||
.is_some_and(|ceiling| p.basis.updated > ceiling)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if self.statuses.is_empty() {
|
||||
return self.ceiling.is_some() || p.basis.held > 0;
|
||||
}
|
||||
if self.statuses.len() == 1 && self.statuses[0] == "OPEN" {
|
||||
return p.basis.held > 0;
|
||||
}
|
||||
self.statuses.iter().any(|status| {
|
||||
status == p.status
|
||||
&& (p.basis.held > 0 || (p.basis.redeemed > 0 && p.status.starts_with("RESOLVED_")))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl ComboPositionsQuery {
|
||||
fn page(self, db: &Connection) -> Result<PositionPage, MarketDataError> {
|
||||
let user = wallet(self.user)?;
|
||||
let conditions = self.condition.map(conditions).transpose()?;
|
||||
let statuses = self.status.map(statuses).transpose()?;
|
||||
let sort = self.sort_by.map(Sort::parse).transpose()?;
|
||||
let descending = self
|
||||
.sort_direction
|
||||
.map(|s| match s.to_ascii_uppercase().as_str() {
|
||||
"ASC" => Ok(false),
|
||||
"DESC" => Ok(true),
|
||||
_ => Err(invalid("invalid sort direction")),
|
||||
})
|
||||
.transpose()?;
|
||||
let (after, before) = (self.updated_after, self.updated_before);
|
||||
if let Some(token) = self.cursor {
|
||||
let page: PositionPage = decode(db, POSITIONS_DOMAIN, &token)?;
|
||||
agree(Some(user), &page.user)?;
|
||||
agree(conditions, &page.conditions)?;
|
||||
agree(statuses, &page.statuses)?;
|
||||
agree(sort, &page.sort)?;
|
||||
agree(descending, &page.descending)?;
|
||||
agree(after.map(Some), &page.after)?;
|
||||
agree(before.map(Some), &page.before)?;
|
||||
return Ok(page);
|
||||
}
|
||||
if after.is_some_and(|v| v < 0)
|
||||
|| before.is_some_and(|v| v < 0)
|
||||
|| after.zip(before).is_some_and(|(a, b)| a > b)
|
||||
{
|
||||
return Err(invalid("invalid combo update window"));
|
||||
}
|
||||
let ceiling = if after.is_some() || before.is_some() {
|
||||
Some(db.query_row(
|
||||
"SELECT CAST((unixepoch('subsec')-90)*1000 AS INTEGER)",
|
||||
[],
|
||||
|r| r.get(0),
|
||||
)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let statuses = statuses.unwrap_or_default();
|
||||
let sort = sort.unwrap_or(if statuses.len() == 1 && statuses[0] == "REDEEMABLE" {
|
||||
Sort::EntryCost
|
||||
} else {
|
||||
Sort::FirstEntry
|
||||
});
|
||||
Ok(PositionPage {
|
||||
user,
|
||||
conditions: conditions.unwrap_or_default(),
|
||||
statuses,
|
||||
sort,
|
||||
descending: descending.unwrap_or(true),
|
||||
after,
|
||||
before,
|
||||
ceiling,
|
||||
limit: page_size(self.limit)?,
|
||||
offset: 0,
|
||||
anchor: None,
|
||||
})
|
||||
}
|
||||
|
||||
fn read(self, db: &Connection) -> Result<Value, MarketDataError> {
|
||||
let mut page = self.page(db)?;
|
||||
if page.limit == 0 {
|
||||
return Ok(envelope(Vec::new(), 0, 0, None));
|
||||
}
|
||||
let (rows, settlements) =
|
||||
load_positions(db, &page.user, &json!(page.conditions).to_string())?;
|
||||
let mut ranked = rows
|
||||
.into_iter()
|
||||
.filter(|p| page.keep(p))
|
||||
.map(|p| ((page.sort.score(&p), p.combo.clone(), p.index), p))
|
||||
.collect::<Vec<_>>();
|
||||
ranked.sort_unstable_by(|a, b| {
|
||||
if page.descending {
|
||||
b.0.cmp(&a.0)
|
||||
} else {
|
||||
a.0.cmp(&b.0)
|
||||
}
|
||||
});
|
||||
let start = if page.keyset() {
|
||||
page.anchor.as_ref().map_or(0, |anchor| {
|
||||
ranked.partition_point(|(key, _)| {
|
||||
if page.descending {
|
||||
key >= anchor
|
||||
} else {
|
||||
key <= anchor
|
||||
}
|
||||
})
|
||||
})
|
||||
} else {
|
||||
page.offset
|
||||
};
|
||||
let mut data = Vec::new();
|
||||
let mut cache = HashMap::new();
|
||||
let mut end = None;
|
||||
for (key, p) in ranked.iter().skip(start).take(page.limit as usize) {
|
||||
if !cache.contains_key(&p.combo) {
|
||||
cache.insert(p.combo.clone(), leg_details(db, &p.combo)?);
|
||||
}
|
||||
data.push(p.wire(db, &page.user, &settlements[&p.combo], &cache[&p.combo])?);
|
||||
end = Some(key.clone());
|
||||
}
|
||||
let offset = page.offset;
|
||||
page.offset += data.len();
|
||||
page.anchor = if page.keyset() { end } else { None };
|
||||
let more = start + data.len() < ranked.len();
|
||||
let next = more
|
||||
.then(|| encode(db, POSITIONS_DOMAIN, &page))
|
||||
.transpose()?;
|
||||
Ok(envelope(data, page.limit, offset, next))
|
||||
}
|
||||
}
|
||||
|
||||
impl Exchange {
|
||||
pub fn public_combo_activity(
|
||||
&self,
|
||||
query: ComboActivityQuery,
|
||||
) -> Result<Value, MarketDataError> {
|
||||
let tx = self.db.unchecked_transaction()?;
|
||||
let data = query.read(&tx)?;
|
||||
tx.commit()?;
|
||||
Ok(data)
|
||||
}
|
||||
|
||||
pub fn public_combo_positions(
|
||||
&self,
|
||||
query: ComboPositionsQuery,
|
||||
) -> Result<Value, MarketDataError> {
|
||||
let tx = self.db.unchecked_transaction()?;
|
||||
let data = query.read(&tx)?;
|
||||
tx.commit()?;
|
||||
Ok(data)
|
||||
}
|
||||
}
|
||||
@@ -1,135 +0,0 @@
|
||||
use super::{basis_entries, side};
|
||||
use crate::{
|
||||
combo::{position_id, Factor},
|
||||
inventory::{decimal, UNIT},
|
||||
MarketDataError,
|
||||
};
|
||||
use rusqlite::{params, Connection};
|
||||
use serde_json::{json, Value};
|
||||
use std::collections::{btree_map::Entry, BTreeMap};
|
||||
|
||||
struct AtCut {
|
||||
factor: Option<Factor>,
|
||||
effective_at: Option<i64>,
|
||||
marks: [Option<i64>; 2],
|
||||
}
|
||||
|
||||
impl AtCut {
|
||||
fn read(db: &Connection, combo: &str, cut: i64) -> Result<Self, MarketDataError> {
|
||||
let mut stmt = db.prepare_cached(include_str!("snapshot_legs.sql"))?;
|
||||
let mut rows = stmt.query(params![combo, cut])?;
|
||||
let mut payouts = Vec::new();
|
||||
let mut zero_at = None::<i64>;
|
||||
let mut last = None::<i64>;
|
||||
while let Some(row) = rows.next()? {
|
||||
let payout = row.get::<_, Option<i64>>(1)?;
|
||||
if let Some(at) = row.get::<_, Option<i64>>(0)? {
|
||||
last = Some(last.map_or(at, |previous| previous.max(at)));
|
||||
if payout == Some(0) {
|
||||
zero_at = Some(zero_at.map_or(at, |previous| previous.min(at)));
|
||||
}
|
||||
}
|
||||
payouts.push(payout);
|
||||
}
|
||||
if payouts.is_empty() {
|
||||
return Err(MarketDataError::Unavailable);
|
||||
}
|
||||
let factor = Factor::resolved(&payouts);
|
||||
let mut marks = [None, None];
|
||||
if factor.is_none() {
|
||||
let mut stmt = db.prepare_cached(include_str!("snapshot_prices.sql"))?;
|
||||
let mut rows = stmt.query(params![combo, cut])?;
|
||||
while let Some(row) = rows.next()? {
|
||||
marks[usize::from(row.get::<_, String>(0)? == "NO")] = Some(row.get(1)?);
|
||||
}
|
||||
}
|
||||
Ok(Self {
|
||||
effective_at: factor.as_ref().and(zero_at.or(last)),
|
||||
factor,
|
||||
marks,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct Row {
|
||||
combo: String,
|
||||
index: u8,
|
||||
size: i128,
|
||||
avg: i128,
|
||||
price: i128,
|
||||
pub(crate) cost: i128,
|
||||
pub(crate) value: i128,
|
||||
pub(crate) bucket: usize,
|
||||
}
|
||||
|
||||
impl Row {
|
||||
pub(crate) fn wire(self) -> Value {
|
||||
let source = ["basis", "mark", "settlement"][self.bucket];
|
||||
json!({
|
||||
"asset":position_id(&self.combo,side(self.index)),"condition_id":self.combo,
|
||||
"module":3,"outcome":if self.index==0 {"Yes"} else {"No"},
|
||||
"title":null,"slug":null,"event_slug":null,
|
||||
"size":decimal(self.size,UNIT),"price":decimal(self.price,UNIT),
|
||||
"avg_price":decimal(self.avg,UNIT),"cost_basis":decimal(self.cost,UNIT),
|
||||
"value":decimal(self.value,UNIT),"price_source":source
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn rows(db: &Connection, user: &str, cut: i64) -> Result<Vec<Row>, MarketDataError> {
|
||||
let mut values = Vec::new();
|
||||
let mut quotes = BTreeMap::new();
|
||||
for ((combo, index), basis) in basis_entries(db, user, "[]", Some(cut))? {
|
||||
if basis.held <= i128::from(UNIT / 10) {
|
||||
continue;
|
||||
}
|
||||
let at = match quotes.entry(combo.clone()) {
|
||||
Entry::Occupied(v) => v.into_mut(),
|
||||
Entry::Vacant(v) => v.insert(AtCut::read(db, &combo, cut)?),
|
||||
};
|
||||
let side = side(index);
|
||||
let chosen = if let (Some(factor), Some(resolved_at)) = (&at.factor, at.effective_at) {
|
||||
if factor.status(side) == "RESOLVED_LOSS" {
|
||||
let selected = json!([combo]).to_string();
|
||||
basis_entries(db, user, &selected, Some(resolved_at))?
|
||||
.get(&(combo.clone(), index))
|
||||
.copied()
|
||||
.unwrap_or_default()
|
||||
} else {
|
||||
basis
|
||||
}
|
||||
} else {
|
||||
basis
|
||||
};
|
||||
let avg = if chosen.held == 0 {
|
||||
0
|
||||
} else {
|
||||
chosen.basis().0
|
||||
};
|
||||
let cost = chosen.principal;
|
||||
let (price, value, bucket) = if let Some(factor) = &at.factor {
|
||||
let quantity = i64::try_from(basis.held).map_err(|_| MarketDataError::Unavailable)?;
|
||||
(
|
||||
i128::from(factor.payout(side, UNIT)),
|
||||
i128::from(factor.payout(side, quantity)),
|
||||
2,
|
||||
)
|
||||
} else if let Some(mark) = at.marks[usize::from(index)] {
|
||||
let mark = i128::from(mark.clamp(0, UNIT));
|
||||
(mark, mark * basis.held / i128::from(UNIT), 1)
|
||||
} else {
|
||||
(avg, cost, 0)
|
||||
};
|
||||
values.push(Row {
|
||||
combo,
|
||||
index,
|
||||
size: basis.held,
|
||||
avg,
|
||||
price,
|
||||
cost,
|
||||
value,
|
||||
bucket,
|
||||
});
|
||||
}
|
||||
Ok(values)
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
SELECT s.at_ms,
|
||||
CASE s.winner WHEN 'VOID' THEN 500000 WHEN l.outcome THEN 1000000
|
||||
WHEN 'YES' THEN 0 WHEN 'NO' THEN 0 END AS payout
|
||||
FROM combo_legs l
|
||||
LEFT JOIN price_settlements s ON s.market=l.market AND s.at_ms<?2
|
||||
WHERE l.combo=?1
|
||||
ORDER BY l.market
|
||||
@@ -1,17 +0,0 @@
|
||||
WITH fills AS (
|
||||
SELECT r.outcome, t.flow, q.price_micros, t.executed_at, journal.seq
|
||||
FROM combo_rfqs r JOIN combo_rfq_trades t ON t.rfq=r.id
|
||||
JOIN combo_rfq_quotes q ON q.id=t.quote
|
||||
JOIN combo_portfolio_order journal ON journal.request_id=t.request_id
|
||||
WHERE r.combo=?1 AND t.executed_at<?2
|
||||
), prices AS (
|
||||
SELECT outcome,price_micros,executed_at,seq FROM fills
|
||||
UNION ALL
|
||||
SELECT CASE outcome WHEN 'YES' THEN 'NO' ELSE 'YES' END,1000000-price_micros,executed_at,seq
|
||||
FROM fills WHERE flow IN ('MINT','MERGE')
|
||||
), ranked AS (
|
||||
SELECT outcome,price_micros,
|
||||
ROW_NUMBER() OVER (PARTITION BY outcome ORDER BY executed_at DESC,seq DESC) AS latest
|
||||
FROM prices
|
||||
)
|
||||
SELECT outcome,price_micros FROM ranked WHERE latest=1
|
||||
@@ -1,10 +0,0 @@
|
||||
WITH owned AS (
|
||||
SELECT combo,outcome,shares_micros AS qty FROM combo_balances
|
||||
WHERE account=?1 OR (?1 LIKE '0x%' AND account COLLATE NOCASE=?1)
|
||||
UNION ALL
|
||||
SELECT r.combo,h.outcome,h.shares_micros FROM combo_rfq_holds h JOIN combo_rfqs r ON r.id=h.rfq
|
||||
WHERE h.outcome IS NOT NULL AND (h.account=?1 OR (?1 LIKE '0x%' AND h.account COLLATE NOCASE=?1))
|
||||
)
|
||||
SELECT combo,outcome,SUM(qty) FROM owned
|
||||
WHERE (?2='[]' OR combo IN (SELECT value FROM json_each(?2)))
|
||||
GROUP BY combo,outcome
|
||||
@@ -1,29 +0,0 @@
|
||||
WITH outcomes(outcome) AS (VALUES ('YES'),('NO')), moves AS (
|
||||
SELECT m.request_id,m.combo,o.outcome,m.at_ms,
|
||||
CASE m.kind WHEN 'SPLIT' THEN 'BUY' WHEN 'MERGE' THEN 'SELL' ELSE 'REDEEM' END AS op,
|
||||
m.shares_micros,
|
||||
CASE WHEN m.kind='SPLIT' AND o.outcome='YES' THEN m.shares_micros/2
|
||||
WHEN m.kind='SPLIT' THEN m.shares_micros-m.shares_micros/2
|
||||
ELSE m.cash_delta_micros END AS cash
|
||||
FROM combo_movements m JOIN outcomes o ON m.outcome IS NULL OR m.outcome=o.outcome
|
||||
WHERE m.account=?1 OR (?1 LIKE '0x%' AND m.account COLLATE NOCASE=?1)
|
||||
UNION ALL
|
||||
SELECT t.request_id,r.combo,r.outcome,t.executed_at,r.direction,q.shares_micros,q.cash_micros
|
||||
FROM combo_rfqs r JOIN combo_rfq_trades t ON t.rfq=r.id JOIN combo_rfq_quotes q ON q.id=t.quote
|
||||
WHERE r.requester=?1 OR (?1 LIKE '0x%' AND r.requester COLLATE NOCASE=?1)
|
||||
UNION ALL
|
||||
SELECT t.request_id,r.combo,
|
||||
CASE WHEN t.flow='TRANSFER' THEN r.outcome WHEN r.outcome='YES' THEN 'NO' ELSE 'YES' END,
|
||||
t.executed_at,
|
||||
CASE WHEN t.flow='MINT' THEN 'BUY' WHEN t.flow='MERGE' THEN 'SELL'
|
||||
WHEN r.direction='BUY' THEN 'SELL' ELSE 'BUY' END,
|
||||
q.shares_micros,
|
||||
CASE WHEN t.flow='TRANSFER' THEN q.cash_micros ELSE q.shares_micros-q.cash_micros END
|
||||
FROM combo_rfq_quotes q JOIN combo_rfq_trades t ON t.quote=q.id JOIN combo_rfqs r ON r.id=t.rfq
|
||||
WHERE q.maker=?1 OR (?1 LIKE '0x%' AND q.maker COLLATE NOCASE=?1)
|
||||
)
|
||||
SELECT m.combo,m.outcome,m.at_ms,m.op,m.shares_micros,m.cash
|
||||
FROM moves m JOIN combo_portfolio_order journal ON journal.request_id=m.request_id
|
||||
WHERE (?2='[]' OR m.combo IN (SELECT value FROM json_each(?2)))
|
||||
AND (?3 IS NULL OR m.at_ms<?3)
|
||||
ORDER BY journal.seq,m.outcome
|
||||
@@ -1,21 +0,0 @@
|
||||
BEGIN IMMEDIATE;
|
||||
CREATE TABLE IF NOT EXISTS combo_portfolio_order (
|
||||
seq INTEGER PRIMARY KEY,
|
||||
request_id TEXT NOT NULL UNIQUE REFERENCES requests(id)
|
||||
);
|
||||
-- Older databases have the command receipt order even when both sources share a clock tick.
|
||||
INSERT OR IGNORE INTO combo_portfolio_order(request_id)
|
||||
SELECT r.id FROM requests r
|
||||
WHERE EXISTS(SELECT 1 FROM combo_movements m WHERE m.request_id=r.id)
|
||||
OR EXISTS(SELECT 1 FROM combo_rfq_trades t WHERE t.request_id=r.id)
|
||||
ORDER BY r.rowid;
|
||||
CREATE TRIGGER IF NOT EXISTS record_combo_portfolio_order AFTER INSERT ON requests
|
||||
WHEN EXISTS(SELECT 1 FROM combo_movements m WHERE m.request_id=NEW.id)
|
||||
OR EXISTS(SELECT 1 FROM combo_rfq_trades t WHERE t.request_id=NEW.id)
|
||||
BEGIN
|
||||
INSERT INTO combo_portfolio_order(request_id) VALUES(NEW.id);
|
||||
END;
|
||||
CREATE INDEX IF NOT EXISTS combo_movements_wallet_seq ON combo_movements(account COLLATE NOCASE,seq);
|
||||
CREATE INDEX IF NOT EXISTS combo_rfq_requester_wallet ON combo_rfqs(requester COLLATE NOCASE);
|
||||
CREATE INDEX IF NOT EXISTS combo_rfq_maker_wallet ON combo_rfq_quotes(maker COLLATE NOCASE);
|
||||
COMMIT;
|
||||
@@ -1,565 +0,0 @@
|
||||
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
|
||||
}))
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
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))
|
||||
@@ -1,65 +0,0 @@
|
||||
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;
|
||||
@@ -1,34 +0,0 @@
|
||||
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,35 +36,6 @@ 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.prepare_cached(concat!(
|
||||
let due: bool = tx.query_row(
|
||||
"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) OR EXISTS(",
|
||||
include_str!("combo_rfq_due.sql"), ")",
|
||||
))?.query_row([], |row| row.get(0))?;
|
||||
OR EXISTS(SELECT 1 FROM quote_pending)",
|
||||
[], |row| row.get(0),
|
||||
)?;
|
||||
if !due {
|
||||
return Ok(tx);
|
||||
}
|
||||
@@ -49,10 +49,8 @@ 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)?;
|
||||
crate::position_balance_history::flush(&write)?;
|
||||
write.commit()?;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,17 +32,16 @@ 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, rfq_reserved): (i64, i64, i64, i64) = db.query_row(
|
||||
let (cash, remainder, reserved): (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'),
|
||||
(SELECT COALESCE(SUM(cash_micros),0) FROM combo_rfq_holds WHERE account=a.id)
|
||||
WHERE account=a.id AND side='buy' AND status='live')
|
||||
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.get(3)?)),
|
||||
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
|
||||
)?;
|
||||
let available = i128::from(cash) * 10000 + i128::from(remainder);
|
||||
let reserved = i128::from(reserved) + i128::from(rfq_reserved);
|
||||
let reserved = i128::from(reserved);
|
||||
Ok(
|
||||
json!({"account":account, "available_micros":available, "reserved_micros":reserved,
|
||||
"total_cash_micros":available+reserved}),
|
||||
|
||||
@@ -4,9 +4,6 @@ mod activity;
|
||||
mod assets;
|
||||
mod augmented;
|
||||
mod catalog;
|
||||
mod combo;
|
||||
mod combo_portfolio;
|
||||
mod combo_rfq;
|
||||
mod depth_feed;
|
||||
mod estimate;
|
||||
mod expiry;
|
||||
@@ -37,7 +34,6 @@ mod minimum_size;
|
||||
mod neg_risk;
|
||||
mod open_interest;
|
||||
mod portfolio;
|
||||
mod position_balance_history;
|
||||
mod prices_history;
|
||||
mod public_trades;
|
||||
mod quotes;
|
||||
@@ -53,13 +49,11 @@ use serde_json::{json, Map, Value};
|
||||
use std::{path::Path, time::Duration};
|
||||
|
||||
pub use assets::parse_id as parse_asset_id;
|
||||
pub use combo_portfolio::{ComboActivityQuery, ComboPositionsQuery};
|
||||
pub use depth_feed::MarketPage;
|
||||
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;
|
||||
@@ -133,27 +127,6 @@ 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 combo_portfolio_ready: bool = db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='trigger' AND name='record_combo_portfolio_order')",
|
||||
[], |r| r.get(0),
|
||||
)?;
|
||||
if !combo_portfolio_ready {
|
||||
db.execute_batch(include_str!("combo_portfolio_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),
|
||||
@@ -162,14 +135,6 @@ 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 {
|
||||
@@ -261,9 +226,6 @@ impl Exchange {
|
||||
| "market_amounts"
|
||||
| "tick_history"
|
||||
| "catalog"
|
||||
| "combo"
|
||||
| "combo_rfq"
|
||||
| "combo_rfq_open"
|
||||
| "events"
|
||||
| "history"
|
||||
| "prices_history"
|
||||
@@ -277,7 +239,6 @@ impl Exchange {
|
||||
| "book"
|
||||
| "open_orders"
|
||||
| "positions"
|
||||
| "position_balances_at"
|
||||
| "holders"
|
||||
| "balance"
|
||||
| "portfolio_value"
|
||||
@@ -382,7 +343,6 @@ 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);
|
||||
|
||||
@@ -114,20 +114,6 @@ 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,
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
pub(crate) mod http;
|
||||
pub(super) mod protocol;
|
||||
pub(crate) mod snapshot;
|
||||
mod protocol;
|
||||
|
||||
use crate::{
|
||||
inventory::{decimal, UNIT},
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
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;
|
||||
@@ -1,6 +1,6 @@
|
||||
// Polygon deployments listed at https://docs.polymarket.com/resources/contracts.
|
||||
// For upgradeable contracts, use the public proxy address.
|
||||
pub(crate) const CONTRACTS: &[&str] = &[
|
||||
pub(super) const CONTRACTS: &[&str] = &[
|
||||
"0xE111180000d2663C0091e4f400237545B87B996B", // CTF Exchange
|
||||
"0xe2222d279d744050d28e00520010520000310F59", // Neg Risk CTF Exchange
|
||||
"0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296", // Neg Risk Adapter (CTF negative-risk approvals)
|
||||
|
||||
@@ -1,293 +0,0 @@
|
||||
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
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
for row in crate::combo_portfolio::snapshot::rows(&tx, &cursor.wallet, point)? {
|
||||
let i = positions;
|
||||
positions += 1;
|
||||
let in_page = i >= cursor.offset && i - cursor.offset < cursor.limit;
|
||||
if first {
|
||||
totals[row.bucket] += row.value;
|
||||
basis_total += row.cost;
|
||||
}
|
||||
if in_page {
|
||||
data.push(row.wire());
|
||||
}
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
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
|
||||
@@ -1,31 +0,0 @@
|
||||
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
|
||||
@@ -1,73 +0,0 @@
|
||||
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}))
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
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;
|
||||
@@ -1,62 +0,0 @@
|
||||
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;
|
||||
@@ -1,104 +0,0 @@
|
||||
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);
|
||||
}
|
||||
@@ -1,112 +0,0 @@
|
||||
use exchange::Exchange;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
fn positions(db: &Exchange, query: Value) -> Value {
|
||||
db.public_combo_positions(serde_json::from_value(query).unwrap())
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn activity(db: &Exchange, query: Value) -> Value {
|
||||
db.public_combo_activity(serde_json::from_value(query).unwrap())
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn combo_portfolio_replays_rfq_cost_by_side() {
|
||||
let mut db = Exchange::open(":memory:").unwrap();
|
||||
for line in include_str!("../../../docs/examples/combo-rfq.jsonl").lines() {
|
||||
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);
|
||||
}
|
||||
db.execute(cmd).unwrap();
|
||||
}
|
||||
let taker = positions(&db, json!({"user":"taker"}));
|
||||
assert_eq!(taker["data"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(taker["data"][0]["outcome_index"], 0);
|
||||
assert_eq!(taker["data"][0]["current_size"], json!(2.5));
|
||||
assert_eq!(taker["data"][0]["gross_entry_cost_usdc"], json!(0.875));
|
||||
assert_eq!(taker["data"][0]["legs"][1]["leg_outcome_index"], 1);
|
||||
assert_eq!(taker["data"][0]["status"], "OPEN");
|
||||
let maker = positions(&db, json!({"user":"maker"}));
|
||||
assert_eq!(maker["data"][0]["outcome_index"], 1);
|
||||
assert_eq!(maker["data"][0]["current_size"], json!(2.5));
|
||||
assert_eq!(maker["data"][0]["gross_entry_cost_usdc"], json!(1.625));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn combo_portfolio_keeps_redemption_history_and_scope() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("combo-public.sqlite");
|
||||
let mut db = Exchange::open(&path).unwrap();
|
||||
let cmds = include_str!("../../../docs/examples/combo-ledger.jsonl")
|
||||
.lines()
|
||||
.map(|line| serde_json::from_str::<Value>(line).unwrap())
|
||||
.collect::<Vec<_>>();
|
||||
for cmd in &cmds[..10] {
|
||||
db.execute(cmd.clone()).unwrap();
|
||||
}
|
||||
let first = positions(&db, json!({"user":"alice","status":"REDEEMABLE","limit":1}));
|
||||
assert_eq!(first["data"][0]["status"], "REDEEMABLE");
|
||||
assert!(first["data"][0]["redeemable"].as_bool().unwrap());
|
||||
assert_eq!(first["data"][0]["legs_resolved"], 2);
|
||||
let cursor = first["pagination"]["next_cursor"].as_str().unwrap();
|
||||
drop(db);
|
||||
|
||||
let mut db = Exchange::open(&path).unwrap();
|
||||
let second = positions(&db, json!({"user":"alice","cursor":cursor,"limit":999}));
|
||||
assert_eq!(second["pagination"]["limit"], 1);
|
||||
assert_ne!(
|
||||
first["data"][0]["outcome_index"],
|
||||
second["data"][0]["outcome_index"]
|
||||
);
|
||||
assert!(db
|
||||
.public_combo_positions(
|
||||
serde_json::from_value(json!({
|
||||
"user":"alice","cursor":cursor,"status":"OPEN"
|
||||
}))
|
||||
.unwrap()
|
||||
)
|
||||
.is_err());
|
||||
assert!(db
|
||||
.public_combo_positions(
|
||||
serde_json::from_value(json!({
|
||||
"user":"other","cursor":cursor
|
||||
}))
|
||||
.unwrap()
|
||||
)
|
||||
.is_err());
|
||||
assert!(db
|
||||
.public_combo_activity(
|
||||
serde_json::from_value(json!({
|
||||
"user":"alice","cursor":cursor
|
||||
}))
|
||||
.unwrap()
|
||||
)
|
||||
.is_err());
|
||||
for cmd in &cmds[10..12] {
|
||||
db.execute(cmd.clone()).unwrap();
|
||||
}
|
||||
assert_eq!(positions(&db, json!({"user":"alice"}))["data"], json!([]));
|
||||
let mut rows = positions(&db, json!({"user":"alice","status":"RESOLVED_PARTIAL"}))["data"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.clone();
|
||||
rows.sort_by_key(|r| r["outcome_index"].as_u64().unwrap());
|
||||
assert_eq!(rows[0]["realized_payout_usdc"], json!(0.25));
|
||||
assert_eq!(rows[1]["realized_payout_usdc"], json!(0.75));
|
||||
assert_eq!(rows[0]["gross_entry_cost_usdc"], json!(0.500001));
|
||||
assert_eq!(rows[1]["gross_entry_cost_usdc"], json!(0.500001));
|
||||
|
||||
let first = activity(&db, json!({"user":"alice","limit":1}));
|
||||
assert_eq!(first["data"][0]["type"], "REDEEM");
|
||||
assert_eq!(first["data"][0]["payout_usdc"], json!(0.75));
|
||||
let second = activity(
|
||||
&db,
|
||||
json!({"user":"alice","cursor":first["pagination"]["next_cursor"]}),
|
||||
);
|
||||
assert_eq!(second["data"][0]["payout_usdc"], json!(0.25));
|
||||
assert!(second["data"][0]["block_number"].is_null());
|
||||
}
|
||||
@@ -1,147 +0,0 @@
|
||||
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
|
||||
);
|
||||
}
|
||||
@@ -1,138 +0,0 @@
|
||||
use exchange::Exchange;
|
||||
use rusqlite::Connection;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
const BUYER: &str = "0x0000000000000000000000000000000000000011";
|
||||
const MAKER: &str = "0x0000000000000000000000000000000000000022";
|
||||
const DAY: i64 = 1_699_920_000_000;
|
||||
const CUT: i64 = DAY + 86_400_000;
|
||||
|
||||
fn date(db: &Connection, at: i64) -> String {
|
||||
db.query_row("SELECT date(?/1000,'unixepoch')", [at], |r| r.get(0))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn snapshot(db: &Exchange, query: Value) -> Value {
|
||||
db.public_position_snapshot(serde_json::from_value(query).unwrap())
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn combo_snapshot_joins_binary_rows_and_prices_without_cut_lookahead() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("combo-snapshot.sqlite");
|
||||
let mut exchange = Exchange::open(&path).unwrap();
|
||||
let mut combo = String::new();
|
||||
for line in include_str!("../../../docs/examples/combo-rfq.jsonl")
|
||||
.lines()
|
||||
.take(10)
|
||||
{
|
||||
let mut cmd: Value = serde_json::from_str(line).unwrap();
|
||||
for field in ["account", "requester", "maker"] {
|
||||
match cmd[field].as_str() {
|
||||
Some("taker") => cmd[field] = json!(BUYER),
|
||||
Some("maker") => cmd[field] = json!(MAKER),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if cmd["op"] == "request_combo_quote" {
|
||||
combo = cmd["combo"].as_str().unwrap().to_owned();
|
||||
cmd["last_look_ms"] = json!(300000);
|
||||
}
|
||||
exchange.execute(cmd).unwrap();
|
||||
}
|
||||
for cmd in [
|
||||
json!({"op":"list","id":"daily-single","market":"daily-single","rules":"ordinary balance"}),
|
||||
json!({"op":"split","id":"single-split","account":BUYER,"market":"daily-single","qty":1}),
|
||||
json!({"op":"close","id":"close-leg-a","market":"combo-a"}),
|
||||
json!({"op":"finalize","id":"final-leg-a","market":"combo-a","winner":"NO"}),
|
||||
json!({"op":"redeem_combo","id":"burn-loser","combo":combo,"account":BUYER,"qty":2,"outcome":"YES"}),
|
||||
] {
|
||||
exchange.execute(cmd).unwrap();
|
||||
}
|
||||
let sql = Connection::open(&path).unwrap();
|
||||
sql.execute(
|
||||
"UPDATE position_balance_history_start SET at_ms=?",
|
||||
[DAY - 1],
|
||||
)
|
||||
.unwrap();
|
||||
sql.execute("UPDATE position_balance_history SET at_ms=?", [DAY + 1000])
|
||||
.unwrap();
|
||||
sql.execute("UPDATE wallet_movements SET at_ms=?", [DAY + 1000])
|
||||
.unwrap();
|
||||
sql.execute("UPDATE combo_rfq_trades SET executed_at=?", [DAY + 1000])
|
||||
.unwrap();
|
||||
sql.execute(
|
||||
"UPDATE price_settlements SET at_ms=? WHERE market='combo-a'",
|
||||
[CUT],
|
||||
)
|
||||
.unwrap();
|
||||
sql.execute("UPDATE combo_movements SET at_ms=?", [CUT + 1000])
|
||||
.unwrap();
|
||||
|
||||
let d = date(&sql, DAY);
|
||||
let first = snapshot(&exchange, json!({"user":BUYER,"date":d,"limit":2}));
|
||||
assert_eq!(first["summary"]["positions"], 3);
|
||||
assert_eq!(first["summary"]["cost_basis"], json!(2.4));
|
||||
assert_eq!(first["summary"]["value_by_source"]["basis"], 1);
|
||||
assert_eq!(first["summary"]["value_by_source"]["mark"], json!(1.4));
|
||||
assert_eq!(first["data"][0]["module"], 0);
|
||||
assert_eq!(first["data"][1]["module"], 0);
|
||||
let last = snapshot(
|
||||
&exchange,
|
||||
json!({"user":BUYER,"cursor":first["pagination"]["next_cursor"]}),
|
||||
);
|
||||
assert_eq!(last["data"][0]["module"], 3);
|
||||
assert_eq!(last["data"][0]["price_source"], "mark");
|
||||
assert_eq!(last["data"][0]["price"], json!(0.35));
|
||||
assert!(last["data"][0]["title"].is_null());
|
||||
assert!(!last["pagination"]["has_more"].as_bool().unwrap());
|
||||
|
||||
let maker = snapshot(&exchange, json!({"user":MAKER,"date":d}));
|
||||
assert_eq!(maker["data"][0]["outcome"], "No");
|
||||
assert_eq!(maker["data"][0]["price"], json!(0.65));
|
||||
assert_eq!(maker["data"][0]["value"], json!(2.6));
|
||||
|
||||
let following = date(&sql, CUT);
|
||||
let after = snapshot(&exchange, json!({"user":BUYER,"date":following}));
|
||||
let combo = &after["data"][2];
|
||||
assert_eq!(combo["module"], 3);
|
||||
assert_eq!(combo["size"], 2);
|
||||
assert_eq!(combo["price_source"], "settlement");
|
||||
assert_eq!(combo["value"], 0);
|
||||
assert_eq!(combo["cost_basis"], json!(1.4));
|
||||
let winning = snapshot(&exchange, json!({"user":MAKER,"date":following}));
|
||||
assert_eq!(winning["data"][0]["price"], 1);
|
||||
assert_eq!(winning["data"][0]["value"], 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn daily_combo_uses_basis_when_no_market_price_exists() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("combo-basis.sqlite");
|
||||
let mut exchange = Exchange::open(&path).unwrap();
|
||||
for line in include_str!("../../../docs/examples/combo-ledger.jsonl")
|
||||
.lines()
|
||||
.take(6)
|
||||
{
|
||||
let mut cmd: Value = serde_json::from_str(line).unwrap();
|
||||
if cmd["account"] == "alice" {
|
||||
cmd["account"] = json!(BUYER);
|
||||
}
|
||||
exchange.execute(cmd).unwrap();
|
||||
}
|
||||
let sql = Connection::open(&path).unwrap();
|
||||
sql.execute(
|
||||
"UPDATE position_balance_history_start SET at_ms=?",
|
||||
[DAY - 1],
|
||||
)
|
||||
.unwrap();
|
||||
sql.execute("UPDATE combo_movements SET at_ms=?", [DAY + 1000])
|
||||
.unwrap();
|
||||
let page = snapshot(&exchange, json!({"user":BUYER,"date":date(&sql,DAY)}));
|
||||
assert_eq!(page["summary"]["positions"], 2);
|
||||
assert_eq!(page["summary"]["value_by_source"]["basis"], json!(1.000002));
|
||||
assert_eq!(page["data"][0]["price_source"], "basis");
|
||||
assert_eq!(page["data"][0]["cost_basis"], json!(0.500001));
|
||||
assert_eq!(page["data"][0]["value"], json!(0.500001));
|
||||
}
|
||||
@@ -4178,182 +4178,3 @@ 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,6 +8,11 @@ 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
|
||||
@@ -123,3 +128,55 @@ 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)
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"chain_id": 137,
|
||||
"block_number": "0x5df5831",
|
||||
"block_hash": "0xf36806915eb4a8aa5ecb85d411a3259c9a65b1f1af65049e30e5098a32f6b45c",
|
||||
"condition_id": "0xdf04a0495b0a16dbce386acdc16d9aed19784db9888be53d150354b83b7c18b1",
|
||||
"contract": "0x4D97DCd97eC945f40cF65F87097ACe5EA0476045",
|
||||
"sources": [
|
||||
"https://polygon.drpc.org",
|
||||
"https://polygon-bor-rpc.publicnode.com"
|
||||
],
|
||||
"outcome_slots": "0x0000000000000000000000000000000000000000000000000000000000000002",
|
||||
"denominator": "0x0000000000000000000000000000000000000000000000000000000000000001",
|
||||
"numerators": [
|
||||
"0x0000000000000000000000000000000000000000000000000000000000000000",
|
||||
"0x0000000000000000000000000000000000000000000000000000000000000001"
|
||||
],
|
||||
"observed_at_ms": 1796490278240
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
[
|
||||
{
|
||||
"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
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,221 @@
|
||||
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,6 +1,9 @@
|
||||
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};
|
||||
@@ -33,7 +36,45 @@ fn observe_book(client: &Client, url: reqwest::Url, token: &str) -> Result<()> {
|
||||
fn main() -> Result<()> {
|
||||
let args: Vec<_> = std::env::args().skip(1).collect();
|
||||
let usage =
|
||||
"usage: venue-probe [--compare-prices | --inspect-book TOKEN | --replay-book TOKEN FILE | --replay-market FILE]";
|
||||
"usage: venue-probe [--compare-prices | --inspect-book TOKEN | --replay-book TOKEN FILE | --replay-market FILE | --inspect-resolution CONDITION [EXPECTED] | --replay-resolution FILE [EXPECTED] | --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(());
|
||||
}
|
||||
}
|
||||
|
||||
if let [mode, file] = args.as_slice() {
|
||||
if mode == "--replay-market" {
|
||||
let raw = serde_json::from_reader(std::fs::File::open(file)?)?;
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
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()?)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,274 @@
|
||||
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(())
|
||||
}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
{"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"}
|
||||
@@ -1,16 +0,0 @@
|
||||
{"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"}
|
||||
@@ -393,14 +393,6 @@ fidelity 以分钟为单位;省略或不大于零时按 1 分钟处理。相
|
||||
|
||||
例如,使用 [足球样例](examples/football.jsonl) 上架的全场 2:1 和半场 1:0 是同一场比赛的两个独立市场。各发一条公告后,用 `op: catalog` 按 `cup-a-b` 取得 `event.event_id`。查询 `GET /market-clarifications?event_id=<该编号>&ascending=true` 可以同时读到两条。再传半场盘的 `market_id` 就只返回半场盘的公告。`event_id` 和 `market_id` 使用本库各自独立的数字编号。重启保留编号,旧库按原有事件键排序补号。跨筛选条件取交集的行为已用本地样例验证,尚待同一批生产公告逐项对照。[官方筛选参数](https://docs.polymarket.com/api-reference/markets/list-market-clarifications)
|
||||
|
||||
### 组合持仓与活动 Data API
|
||||
|
||||
官方组合持仓按钱包返回每个组合结果的份额、成本、兑付额和各腿状态。默认返回仍持有的余额。组合活动按链上顺序翻页,主要返回拆分、合并和兑付等生命周期记录。两个端点的本次生产访问返回 403,字段及筛选依据公开规范。[组合持仓](https://docs.polymarket.com/api-reference/wallet/list-combo-positions) · [组合活动](https://docs.polymarket.com/api-reference/feeds/list-combo-activity)
|
||||
|
||||
本地持仓按共同写入序号重放两侧 RFQ 和钱包操作。拆分采用本地各半成本,最小单位余数给 NO。出售、合并和兑付均按减少份额移除加权成本,完全兑付后保留已兑付部分的成本及总回款。本地无成交手续费。组合各腿引用公开市场目录,持仓数量与当前可用及预留份额核对。分页游标绑定钱包、筛选和排序。默认首次入场倒序和更新时间正序使用键集续页,其他组合使用游标中的偏移量。带更新时间的查询固定 90 秒稳定截止。
|
||||
|
||||
活动端点用本地写入序号替代链上区块和日志顺序。成对拆分、合并各占一条记录,缺少单侧资产标识时为空。区块号为 null,无交易哈希。`RESOLVED_PARTIAL` 同时用于表现本地 VOID 的腿。生产合并账户钱包、缺失行情的表征、历史行保留口径和链上编号尚待对照。
|
||||
|
||||
### Gamma 事件与盘口详情
|
||||
|
||||
公开目录中,市场 559651 和事件 30828 使用同一 slug。市场的 outcomes 和 clobTokenIds 在外层 JSON 中都是字符串,各自解码一次得到两个按位置对应的值。生产目录的市场对象带 events 数组。官方事件详情把各子盘放在 markets 数组。此次生产列表读取成功,两个 slug 详情端点的线上回执尚未取得。[生产目录样例](https://gamma-api.polymarket.com/markets?limit=1) · [官方事件详情](https://docs.polymarket.com/api-reference/events/get-event-by-slug) · [官方市场详情](https://docs.polymarket.com/api-reference/markets/get-market-by-slug)
|
||||
@@ -425,11 +417,13 @@ 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 链上兑付核对
|
||||
|
||||
官方日终快照在次日 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)
|
||||
从已封盘的 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)
|
||||
|
||||
本地组合与单盘共用分页及汇总,并按本地稳定顺序追加组合。组合使用模块 3,`title`、`slug`、`event_slug` 为 null。组合余额与成本均从日终切点之前的账本流水重放。任一腿兑付为零可提前确定组合兑付,其余情况等待所有腿。零兑付侧保留终局之前的成本,即使之后已部分烧毁。未结算时只采用切点之前该侧的真实组合成交价。拆分或合并成交有两侧报价,直接转让只为成交的一侧记录价格。缺价回退到成本。结算价值按实际份额使用完整兑付精度,显示的每份价格保留到微美元。本次生产快照请求返回 403。生产行情来源和成本样例仍待获取。
|
||||
### PositionManager V2 链上兑付核对
|
||||
|
||||
V2 市场以两项 Position ID 共享的高 31 字节表示条件,首字节标记模块。探针用该模块编号查询 PositionManager 注册表,再从模块读取按目录顺序排列的兑付权重。生产 Binary 样本在两个 Polygon 节点的最终确认区块 `0x5df5912` 均返回 `[1000000, 0]`,与 Gamma 第一结果获胜一致。两个权重的分母固定为 100 万,空数组表示合约当前没有可读取的结果。NegRisk 的二元约束有离线用例,仍缺少生产目录关联样本。组合盘兑付、独立链上状态证明和同步入账仍待覆盖。[探针时序与重放](../crates/venue-probe/README.md#polygon-positionmanager-v2-裁决核对) · [双节点记录](../crates/venue-probe/fixtures/live-position-resolutions.json) · [官方 V2 模块文档](https://github.com/Polymarket/polymarket-v2-external/blob/main/docs/modules.md)
|
||||
|
||||
### Data API 账户持仓价值
|
||||
|
||||
@@ -437,7 +431,7 @@ fidelity 以分钟为单位;省略或不大于零时按 1 分钟处理。相
|
||||
|
||||
本地可以重放 [估值样例](examples/valuation.jsonl)。按样例依次查询 Alice,可见首次成交后 NO 缺价;买一和卖一收窄后所有持仓合计 8.87;裁决 YES 胜后为 8;赎回后为 0。持仓含挂卖预留份额。另一个回归使用两个各持有 0.000030 对份额且最终平分兑付的市场,总额 0.000060 舍入为 0.0001,单独查询任一市场则为 0。估值汇总、份额精度和多条件筛选可通过 public_wallet_value_rounds_after_summing_and_scopes_each_condition 复核。
|
||||
|
||||
当前本地价值端点仅聚合单盘持仓。组合成本已能从组合持仓与日终快照读取,仍待接入该端点。无价时 HTTP 返回可重试的 503,这是本地明确的处理方式,官方公开规范没有给出此种输入的专门示例。协议地址校验采用公布的 Polygon 部署清单,尚未取得生产 API 内部地址集合或舍入中点的线上样本。本轮生产估值接口连接超时。[官方部署地址](https://docs.polymarket.com/resources/contracts)
|
||||
模拟器目前没有可持有的组合合约,因此已有账户的聚合覆盖单盘持仓;带组合的钱包仍需单独对照。无价时 HTTP 返回可重试的 503,这是本地明确的处理方式,官方公开规范没有给出此种输入的专门示例。协议地址校验采用公布的 Polygon 部署清单,尚未取得生产 API 内部地址集合或舍入中点的线上样本。本轮生产估值接口连接超时。[官方部署地址](https://docs.polymarket.com/resources/contracts)
|
||||
|
||||
### Data API 未平仓量与归档
|
||||
|
||||
@@ -469,22 +463,6 @@ 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