Compare commits
8 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b58c45c8f7 | |||
| a1435909ac | |||
| 3730b41e00 | |||
| 6dcc88b4f0 | |||
| 2e95c5a631 | |||
| 07d15e573e | |||
| 1cc667542b | |||
| d0fc875f88 |
Generated
+41
-190
@@ -2,6 +2,12 @@
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "adler2"
|
||||
version = "2.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
|
||||
|
||||
[[package]]
|
||||
name = "ahash"
|
||||
version = "0.8.15"
|
||||
@@ -33,12 +39,6 @@ version = "1.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
|
||||
|
||||
[[package]]
|
||||
name = "base16ct"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf"
|
||||
|
||||
[[package]]
|
||||
name = "base64"
|
||||
version = "0.22.1"
|
||||
@@ -51,12 +51,6 @@ version = "0.23.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
|
||||
|
||||
[[package]]
|
||||
name = "base64ct"
|
||||
version = "1.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.13.2"
|
||||
@@ -128,28 +122,16 @@ name = "cli"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"data-encoding",
|
||||
"exchange",
|
||||
"hmac",
|
||||
"k256",
|
||||
"flate2",
|
||||
"percent-encoding",
|
||||
"reqwest",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"serde_urlencoded",
|
||||
"sha2",
|
||||
"sha3",
|
||||
"subtle",
|
||||
"tiny_http",
|
||||
"tungstenite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "const-oid"
|
||||
version = "0.9.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8"
|
||||
|
||||
[[package]]
|
||||
name = "cpufeatures"
|
||||
version = "0.2.17"
|
||||
@@ -169,15 +151,12 @@ dependencies = [
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crypto-bigint"
|
||||
version = "0.5.5"
|
||||
name = "crc32fast"
|
||||
version = "1.5.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76"
|
||||
checksum = "fd9ae8fcb3ea71b0b26338b4ffb13006bb175de8fd07921089a906ce7e5e6945"
|
||||
dependencies = [
|
||||
"generic-array",
|
||||
"rand_core 0.6.4",
|
||||
"subtle",
|
||||
"zeroize",
|
||||
"cfg-if",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -196,16 +175,6 @@ version = "2.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2a2330da5de22e8a3cb63252ce2abb30116bf5265e89c0e01bc17015ce30a476"
|
||||
|
||||
[[package]]
|
||||
name = "der"
|
||||
version = "0.7.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"
|
||||
dependencies = [
|
||||
"const-oid",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "digest"
|
||||
version = "0.10.7"
|
||||
@@ -213,7 +182,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
|
||||
dependencies = [
|
||||
"block-buffer",
|
||||
"const-oid",
|
||||
"crypto-common",
|
||||
"subtle",
|
||||
]
|
||||
@@ -229,39 +197,6 @@ dependencies = [
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ecdsa"
|
||||
version = "0.16.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca"
|
||||
dependencies = [
|
||||
"der",
|
||||
"digest",
|
||||
"elliptic-curve",
|
||||
"rfc6979",
|
||||
"signature",
|
||||
"spki",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "elliptic-curve"
|
||||
version = "0.13.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47"
|
||||
dependencies = [
|
||||
"base16ct",
|
||||
"crypto-bigint",
|
||||
"digest",
|
||||
"ff",
|
||||
"generic-array",
|
||||
"group",
|
||||
"pkcs8",
|
||||
"rand_core 0.6.4",
|
||||
"sec1",
|
||||
"subtle",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "errno"
|
||||
version = "0.3.15"
|
||||
@@ -306,22 +241,23 @@ version = "2.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
|
||||
|
||||
[[package]]
|
||||
name = "ff"
|
||||
version = "0.13.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393"
|
||||
dependencies = [
|
||||
"rand_core 0.6.4",
|
||||
"subtle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "find-msvc-tools"
|
||||
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"
|
||||
@@ -388,7 +324,6 @@ checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
|
||||
dependencies = [
|
||||
"typenum",
|
||||
"version_check",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -430,17 +365,6 @@ dependencies = [
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "group"
|
||||
version = "0.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63"
|
||||
dependencies = [
|
||||
"ff",
|
||||
"rand_core 0.6.4",
|
||||
"subtle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.14.5"
|
||||
@@ -699,28 +623,6 @@ dependencies = [
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "k256"
|
||||
version = "0.13.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f6e3919bbaa2945715f0bb6d3934a173d1e9a59ac23767fbaaef277265a7411b"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"ecdsa",
|
||||
"elliptic-curve",
|
||||
"once_cell",
|
||||
"sha2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "keccak"
|
||||
version = "0.1.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cb26cec98cce3a3d96cbb7bced3c4b16e3d13f27ec56dbd62cbc8f39cfb9d653"
|
||||
dependencies = [
|
||||
"cpufeatures 0.2.17",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.191"
|
||||
@@ -772,6 +674,16 @@ version = "2.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
||||
|
||||
[[package]]
|
||||
name = "miniz_oxide"
|
||||
version = "0.9.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c"
|
||||
dependencies = [
|
||||
"adler2",
|
||||
"simd-adler32",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "mio"
|
||||
version = "1.2.5"
|
||||
@@ -801,16 +713,6 @@ version = "0.2.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752"
|
||||
|
||||
[[package]]
|
||||
name = "pkcs8"
|
||||
version = "0.10.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7"
|
||||
dependencies = [
|
||||
"der",
|
||||
"spki",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pkg-config"
|
||||
version = "0.3.34"
|
||||
@@ -952,15 +854,6 @@ dependencies = [
|
||||
"rand_core 0.9.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_core"
|
||||
version = "0.6.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
|
||||
dependencies = [
|
||||
"getrandom 0.2.17",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_core"
|
||||
version = "0.9.5"
|
||||
@@ -1025,16 +918,6 @@ dependencies = [
|
||||
"webpki-roots",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rfc6979"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2"
|
||||
dependencies = [
|
||||
"hmac",
|
||||
"subtle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ring"
|
||||
version = "0.17.14"
|
||||
@@ -1129,20 +1012,6 @@ version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
|
||||
|
||||
[[package]]
|
||||
name = "sec1"
|
||||
version = "0.7.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc"
|
||||
dependencies = [
|
||||
"base16ct",
|
||||
"der",
|
||||
"generic-array",
|
||||
"pkcs8",
|
||||
"subtle",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde"
|
||||
version = "1.0.229"
|
||||
@@ -1220,16 +1089,6 @@ dependencies = [
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sha3"
|
||||
version = "0.10.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "77fd7028345d415a4034cf8777cd4f8ab1851274233b45f84e3d955502d93874"
|
||||
dependencies = [
|
||||
"digest",
|
||||
"keccak",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "shlex"
|
||||
version = "2.0.1"
|
||||
@@ -1237,14 +1096,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
|
||||
|
||||
[[package]]
|
||||
name = "signature"
|
||||
version = "2.2.0"
|
||||
name = "simd-adler32"
|
||||
version = "0.3.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de"
|
||||
dependencies = [
|
||||
"digest",
|
||||
"rand_core 0.6.4",
|
||||
]
|
||||
checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
|
||||
|
||||
[[package]]
|
||||
name = "slab"
|
||||
@@ -1268,16 +1123,6 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "spki"
|
||||
version = "0.7.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d"
|
||||
dependencies = [
|
||||
"base64ct",
|
||||
"der",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "stable_deref_trait"
|
||||
version = "1.2.1"
|
||||
@@ -1890,6 +1735,12 @@ dependencies = [
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zlib-rs"
|
||||
version = "0.6.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "aa76918995d776d9dd34d371030be228d021137449771493d56e29f77e4148ac"
|
||||
|
||||
[[package]]
|
||||
name = "zmij"
|
||||
version = "1.0.23"
|
||||
|
||||
@@ -5,17 +5,11 @@ version.workspace = true
|
||||
|
||||
[dependencies]
|
||||
exchange = { path = "../exchange" }
|
||||
serde_json = { workspace = true, features = ["raw_value"] }
|
||||
serde_json.workspace = true
|
||||
anyhow.workspace = true
|
||||
serde.workspace = true
|
||||
tungstenite = "0.28"
|
||||
tiny_http = "0.12"
|
||||
serde_urlencoded = "0.7"
|
||||
percent-encoding = "2"
|
||||
sha2 = "0.10"
|
||||
subtle = "2"
|
||||
hmac = "0.12"
|
||||
data-encoding = "2"
|
||||
k256 = { version = "0.13", default-features = false, features = ["ecdsa", "std"] }
|
||||
sha3 = "0.10"
|
||||
reqwest = { version = "0.12", default-features = false, features = ["blocking", "rustls-tls", "json"] }
|
||||
flate2 = "1"
|
||||
|
||||
+76
-208
@@ -43,15 +43,13 @@ sequenceDiagram
|
||||
|
||||
## 市场 WebSocket
|
||||
|
||||
已有可执行文件可用 `cli DATABASE --market-ws 127.0.0.1:9001 [ORDER_CONFIG_JSON]` 启动行情监听,客户端连接 `ws://127.0.0.1:9001/ws/market`。同一数据库可以由另一条 JSON 行命令会话写入。监听模式只接收市场订阅与心跳。提供与公开 HTTP 相同的配置文件后,订阅和退订可使用目录返回的资产 ID,盘口、增量、成交、步长和市场状态事件也使用配置中的条件和资产 ID。同一快照的 HTTP 与 WebSocket 响应共用盘口哈希。每个连接独立维护订阅,所有连接共享一个 Exchange。当前服务提供明文 WebSocket,接入 TLS 需要相应的服务入口。
|
||||
已有可执行文件可用 `cli DATABASE --market-ws 127.0.0.1:9001` 启动行情监听,客户端连接 `ws://127.0.0.1:9001/ws/market`。同一数据库可以由另一条 JSON 行命令会话写入。监听模式只接收市场订阅与心跳。每个连接独立维护订阅,所有连接共享一个 Exchange。当前服务提供明文 WebSocket,接入 TLS 需要相应的服务入口。
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
main["main.rs"] --> ws["market_ws.rs"]
|
||||
main --> stdin["stream.rs"]
|
||||
ws --> ids["wire_ids.rs"]
|
||||
ws --> subs["subscriptions.rs"]
|
||||
subs --> ids
|
||||
subs --> api["exchange::Exchange / MarketPage"]
|
||||
stdin --> api
|
||||
```
|
||||
@@ -63,16 +61,13 @@ sequenceDiagram
|
||||
participant S as 连接订阅
|
||||
participant E as Exchange
|
||||
C->>W: Upgrade /ws/market
|
||||
C->>S: type=market,订阅 YES 的公开资产 ID
|
||||
S->>S: 将订阅资产 ID 映射为本地资产 ID
|
||||
C->>S: type=market,订阅 YES
|
||||
S->>E: 同一快照内读取 YES 盘口和批次号
|
||||
S-->>W: 返回本地盘口快照
|
||||
W-->>C: 返回映射后的初始 book 数组和盘口哈希,可用 initial_dump=false 省略
|
||||
S-->>C: 初始 book 数组,可用 initial_dump=false 省略
|
||||
C->>S: operation=subscribe,增加 NO
|
||||
S-->>C: 新增 NO 的 book 数组
|
||||
S->>E: 从该市场的已读批次号读取后续变化
|
||||
S-->>W: 过滤出已订阅且晚于其起点的变化
|
||||
W-->>C: price_change,发布映射后的条件 ID 和资产 ID
|
||||
S-->>C: price_change,只含已订阅且晚于其起点的资产
|
||||
opt 成交或价格步长变化
|
||||
S-->>C: 按同一游标发送 last_trade_price 或 tick_size_change
|
||||
end
|
||||
@@ -87,178 +82,14 @@ sequenceDiagram
|
||||
|
||||
[订阅报文样例](../../docs/examples/market-ws.txt)逐行发送为文本帧。客户端可每 10 秒发送一次 `PING`。本地按 100 毫秒间隔检查新批次,单页最多 64 个批次,每个进程最多接纳 128 个同时连接的会话。这些是本地实现参数。慢连接的网络写入在释放 Exchange 锁后进行。
|
||||
|
||||
## 账户 WebSocket
|
||||
|
||||
用 `cli DATABASE --user-ws 127.0.0.1:9003 CREDENTIALS_JSON` 启动账户监听器。它绑定回环地址,客户端连接 `ws://127.0.0.1:9003/ws/user`。凭证文件是 JSON 数组,每项包含 `api_key`、`account` 和 `digest`。`account` 对应模拟器账户。`digest` 是随机 `secret` 的 UTF-8 字节、一个零字节、随机 `passphrase` 的 UTF-8 字节依次拼接后的 SHA-256 十六进制值。Unix 下凭证文件可用 `0600` 权限。服务启动时加载映射,修改映射后重启监听器。
|
||||
|
||||
可在 WebSocket 凭证路径后追加与账户 HTTP 相同的 `ORDER_CONFIG_JSON`。订阅、退订和快照可以使用配置的条件 ID。已映射的订单、账户快照和两侧成交按官方格式返回条件和资产 ID。WebSocket 读取映射时无需连接验签 RPC。
|
||||
|
||||
用 `cli DATABASE --user-ws 127.0.0.1:9003 --account-credentials CREDENTIALS_JSON` 可让 WebSocket 与账户 HTTP 使用同一份凭证配置和同一个数据库。订阅的 `auth` 对象填写 `apiKey`、`secret` 和 `passphrase`,接受 HTTP 签发的凭证。服务在处理订阅命令和读取事件前检查签发状态。已撤销的密钥会关闭对应连接。[官方用户频道](https://docs.polymarket.com/api-reference/wss/user)
|
||||
|
||||
客户端首帧发送 `{"type":"user","auth":{"apiKey":"<本地 API key>","secret":"<本地 secret>","passphrase":"<本地 passphrase>"},"markets":["demo"]}`。省略 `markets` 订阅该账户所有市场。可随时用 `operation: subscribe` 或 `operation: unsubscribe` 更新市场。文本 `PING` 返回 `PONG`。
|
||||
|
||||
首次连接后可以发送 `{"operation":"snapshot","market":"demo"}`,用返回的 `snapshot` 帧替换账户挂单和近期成交,再应用序号大于快照 `cursor` 的事件。若已有对应订阅范围的游标,可在首帧提供整数 `after` 直接从断点续读。后来加入的市场从订阅时的事件边界开始推送,可为该市场单独请求快照。
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
main["main.rs"] --> ws["market_ws.rs"]
|
||||
ws --> user["user_ws.rs"]
|
||||
user --> exchange["exchange::Exchange"]
|
||||
```
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as 客户端
|
||||
participant W as market_ws.rs
|
||||
participant U as user_ws.rs
|
||||
participant E as Exchange
|
||||
C->>W: Upgrade /ws/user
|
||||
C->>W: type=user,auth 和可选 markets、after
|
||||
W->>U: 校验凭证并绑定账户
|
||||
opt 客户端刷新账户状态
|
||||
C->>U: operation=snapshot
|
||||
U->>E: 同一快照查询挂单、近期成交和游标
|
||||
U-->>C: snapshot
|
||||
end
|
||||
loop 连接存续
|
||||
U->>E: 续读该账户已提交事件
|
||||
U-->>C: 推送订阅范围内的订单和成交帧
|
||||
end
|
||||
```
|
||||
|
||||
## 账户 HTTP
|
||||
|
||||
用 `cli DATABASE --account-http 127.0.0.1:9004 CREDENTIALS_JSON [ORDER_CONFIG_JSON]` 启动私有账户服务。凭证文件是 JSON 数组,每条记录包含 `api_key`、`account`、`address`、`secret` 和 `passphrase`。`address` 是绑定到本地账户的交易地址,`secret` 是至少 32 个随机字节的 Base64URL 字符串。Unix 下凭证文件可用 `0600` 权限。HTTP 凭证文件需要签名用的密钥材料,和账户 WebSocket 的摘要文件分别配置。
|
||||
|
||||
需要 SDK 自行签发密钥时,在已有凭证中设置可选的 `wallet_auth_chain_id`,并使用隔离的模拟链 ID。启用的钱包可以带 `POLY_ADDRESS`、`POLY_TIMESTAMP`、`POLY_NONCE` 和 EIP‑712 `POLY_SIGNATURE` 请求 `POST /auth/api-key`。同一钱包与 nonce 签发一次。之后可用 `GET /auth/derive-api-key` 和新的钱包签名取回同一凭证。返回 `apiKey`、`secret` 和 `passphrase`,可直接签名 L2 HTTP 请求。原来配置的凭证仍可用于 L2 请求。本地签发凭证与签发者密钥材料绑定,修改签发者密钥或账户映射会使旧签发凭证失效。样例中的时间戳用于离线核对,实际发请求时须使用新时间戳重新签名。[官方 L1 说明](https://github.com/Polymarket/agent-skills/blob/main/authentication.md) · [离线签名样例](../../docs/examples/clob-wallet-auth.json)
|
||||
|
||||
`GET /auth/api-keys` 使用 L2 HMAC,返回当前账户仍有效的已签发密钥 ID。用待撤销密钥签名 `DELETE /auth/api-key`,成功返回空对象。撤销会持久化,原 nonce 无法再创建或派生该密钥。直接配置在凭证文件中的密钥通过修改配置并重启管理。[官方 Rust SDK](https://github.com/Polymarket/rs-clob-client-v2/blob/main/src/clob/client.rs)
|
||||
|
||||
`GET /data/orders`、`GET /data/order/{id}` 和 `GET /data/trades` 接受 `POLY_API_KEY`、`POLY_ADDRESS`、`POLY_TIMESTAMP`、`POLY_PASSPHRASE`、`POLY_SIGNATURE`。按官方 SDK 将时间戳、请求方法 `GET` 和 URL 路径拼接,再用 Base64URL 解码后的 `secret` 计算 HMAC-SHA256。`POLY_SIGNATURE` 使用 Base64URL 编码。服务器接受与当前时间相差至多 30 秒的请求。成交 ID 和未签名订单 ID 使用本地数字标识。列表按 `next_cursor` 续读,`LTE=` 表示末页。[Polymarket SDK 签名实现](https://github.com/Polymarket/py-clob-client-v2/blob/main/py_clob_client_v2/signing/hmac.py)
|
||||
|
||||
`/data/orders?id=…` 返回仍然活跃的订单或最近一小时内进入终态的订单。准确查询旧订单使用 `/data/order/{id}`。`/data/trades` 与 `/ws/user` 的成交帧都带 `maker_orders`,其中的结果资产、方向、份额和价格来自挂单方的成交腿。HTTP 会附上已登记的挂单方钱包地址。
|
||||
|
||||
使用同一组认证头查询 `GET /balance-allowance?asset_type=COLLATERAL`,或用 `asset_type=CONDITIONAL&token_id=123` 查询指定结果份额。条件资产接受签名订单配置中的数值 token ID,也接受本地 `eb:YES:demo` 形式。余额用百万分之一美元或份额的整数字符串表示,包含仍挂单的预留。对配置中的模拟交易合约,`allowances` 返回模拟无限授权。没有匹配配置时返回空对象。本地直接查询账本,`GET /balance-allowance/update` 验证同一组参数并返回 JSON `null`。签名只覆盖路径,请求参数与官方 SDK 一样放在查询字符串。[官方 SDK 用例](https://github.com/Polymarket/py-clob-client-v2/blob/main/examples/account/get_balance_allowance.py)
|
||||
|
||||
撤单使用同一组认证头。签名消息依次拼接时间戳、`DELETE`、路径和原始请求体字节。响应为 `canceled`(字符串订单 ID 数组)和 `not_canceled`(订单 ID 到取消失败原因的映射)。[官方撤单说明](https://docs.polymarket.com/trading/manage-orders#cancel-orders)
|
||||
|
||||
| 路径 | 请求体 |
|
||||
|---|---|
|
||||
| `/order` | `{"orderID":"1"}` |
|
||||
| `/orders` | `["1","2"]`,最多 3,000 项 |
|
||||
| `/cancel-market-orders` | `{"market":"demo"}` 或 `{"asset_id":"eb:YES:demo"}`,两者也可并用 |
|
||||
| `/cancel-all` | 空请求体 |
|
||||
|
||||
在签名时效内重复发送同一请求会返回原回执。要撤销之后新挂出的订单,使用新的签名时间戳。
|
||||
|
||||
`POST /v1/heartbeats` 用同一套请求头认证,签名覆盖 `POST`、路径及 `{"heartbeat_id":""}` 的原始字节。成功返回新的 `heartbeat_id`。用该 ID 继续发送,推荐间隔 5 秒。ID 不匹配返回 HTTP 400 和当前有效 ID,原截止点保持不变。保护范围由凭证绑定,只覆盖该 API key 的订单。通过可信 CLI 测试时,下单的 `key_id` 应填写该凭证的 `api_key`。HTTP 服务运行期间每 250 毫秒检查到期会话,即使客户端没有请求。 [官方订单心跳](https://docs.polymarket.com/trading/manage-orders#order-heartbeats)
|
||||
|
||||
提供可选的 `ORDER_CONFIG_JSON` 后启用 `POST /order`。配置含 `chain_id` 和 `tokens`,每个映射包含十进制 `token_id`、本地 `asset_id` 和 EIP‑712 `verifying_contract`。[签名样例](../../docs/examples/signed-ctf-order.json) 给出了隔离的本地签名域、合成钱包和请求。使用样例的 `order_config` 对象保存配置文件,使用 `request` 对象构造请求体。HTTP 请求仍需由本地 API 凭证对原始请求体计算 HMAC。订单的 `signer` 必须匹配该凭证的地址。直签订单的 `maker` 与 `signer` 相同。
|
||||
|
||||
本地入口支持 CTF Exchange v2 钱包签名的 GTC、GTD、FOK 和 FAK,以及 GTC/GTD 的 post-only。`orderID` 为签名订单哈希,用于查询、撤单和事件对账。原有通过 CLI 下的未签名单继续使用数字标识。相同签名订单通过账本请求回执幂等恢复。成交和抵押保存在本地模拟账本。[官方下单接口](https://docs.polymarket.com/api-reference/trade/post-a-new-order)
|
||||
|
||||
资产映射的 `domain_version` 默认是字符串 `"2"`,对应 CTF Exchange v2。Protocol V2 的仓位订单用 `"3"`,并把十进制 position ID 填入配置的 `token_id` 和订单的 `tokenId`。服务从本地资产映射取得 EIP‑712 版本和交易合约。同一个本地市场配置的两个 V3 仓位须对应同一条件和合约,结果索引须匹配 YES 与 NO。[Protocol V2 签名样例](../../docs/examples/signed-protocol-v2-orders.json) · [官方合约签名域](https://github.com/Polymarket/polymarket-v2-external/blob/main/src/exchange/Exchange.sol#L1218-L1224)
|
||||
|
||||
CTF 市场可在任一结果资产映射中填写 `condition_id`(32 字节十六进制)。Protocol V2 由仓位 ID 去掉结果字节后得到条件 ID。账户 HTTP 的查询过滤和按市场撤单接受已配置的条件 ID,资产参数支持十进制和十六进制。订单、成交及 `maker_orders` 返回已映射的十进制资产 ID。内部继续用 Eventbook 市场和资产 ID 记账。未设置映射的市场及资产继续用本地标识。[官方成交接口](https://docs.polymarket.com/api-reference/trade/get-trades)
|
||||
|
||||
资产映射可选配 `proxy_factory` 和 `safe_factory`,各自包含工厂 `address` 和含构造参数的 `init_code_hash`。为当前签名域配置可信部署参数后,`POLY_PROXY`(1)和 `POLY_GNOSIS_SAFE`(2)的 `maker` 必须等于用本地配置和签名者通过 CREATE2 推导出的钱包。Proxy 将 20 字节地址作为 salt 哈希的输入,Safe 使用 ABI 编码后的 32 字节地址。未配置对应工厂时拒绝该类型。样例使用隔离的签名域和公开的工厂参数,含可提交的 Proxy、Safe 请求,以及签名有效但 maker 错误的请求。[代理钱包样例](../../docs/examples/signed-ctf-wallet-orders.json) · [官方地址推导](https://github.com/Polymarket/builder-relayer-client/blob/main/src/builder/derive.ts)
|
||||
|
||||
合约钱包订单使用 `POLY_1271`(3)。在本地 HTTP 凭证记录中把 `contract_wallet` 绑定到已部署钱包,并在订单配置中提供可信的 `erc1271_rpc_url`。启动时检查 RPC 的 `eth_chainId`。订单的 `maker` 和 `signer` 均须是该合约地址。HTTP HMAC 仍使用凭证的 `address`。网关在账本加锁前,对配置的链执行只读 `eth_call`,由合约用 ERC‑1271 检查订单哈希和原始签名,包括官方 SDK 封装的 Deposit Wallet 签名。[合约钱包样例](../../docs/examples/signed-ctf-contract-wallet.json) · [ERC‑1271 标准](https://eips.ethereum.org/EIPS/eip-1271)
|
||||
|
||||
下单回执返回整数字符串字段 `makingAmount` 和 `takingAmount`,单位是百万分之一美元或份额,以买卖方向决定顺序。首次提交时只有挂单,返回签名条款和 `live`。发生即时成交时,返回实际成交本金、份额、`tradeIDs` 和 `matched`。部分成交后仍在盘口的剩余量可从订单查询读取。相同请求的重试只返回首次提交产生的成交。模拟成交没有链上交易哈希。[官方下单回执](https://docs.polymarket.com/trading/place-orders#check-the-response)
|
||||
|
||||
启用了秒级撮合延迟的市场中,可立即成交的签名订单先收到 `delayed`。按订单哈希可查询等待或拒绝状态,等待期间的撤单响应会说明该订单仍在延迟窗口。订单到期后进入平常的撮合流程,所得成交仍通过账户频道和成交查询发送。账户 HTTP 服务每 250 毫秒检查到期订单,重启后继续处理数据库里已受理的订单。[官方订单生命周期](https://docs.polymarket.com/concepts/order-lifecycle)
|
||||
|
||||
若市场详情显示 `itode: true`,可立即成交的订单进入 150 毫秒等待。HTTP 在账本锁外等待,并在重新校验后返回最终回执。批量回执保持输入顺序,只等待其中的 `itode` 订单。若服务暂时读不到执行结果,返回 HTTP 503;客户端可重送相同签名订单查询原处理结果。[官方订单生命周期](https://docs.polymarket.com/concepts/order-lifecycle)
|
||||
|
||||
`POST /orders` 接受最多 15 笔签名订单组成的 JSON 数组。对整个数组的原始请求体验签,再逐项验订单签名。本地按输入顺序受理,结果数组与输入对齐,单项失败时其余有效订单继续提交。[官方批量接口](https://docs.polymarket.com/api-reference/trade/post-multiple-orders)
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
main["main.rs"] --> http["account_http.rs"]
|
||||
http --> creds["credential_file.rs"]
|
||||
http --> l1["account_http/l1.rs"]
|
||||
l1 --> eth["ethereum.rs"]
|
||||
order --> eth
|
||||
http --> wire["wire_ids.rs"]
|
||||
ws --> wire
|
||||
http --> order["signed_order.rs"]
|
||||
http --> refs["order_refs.rs"]
|
||||
ws --> refs
|
||||
order --> api
|
||||
order --> rpc["signed_order/erc1271.rs"]
|
||||
http --> api["exchange::Exchange"]
|
||||
ws["user_ws.rs"] --> creds
|
||||
```
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as SDK
|
||||
participant A as account_http/l1.rs
|
||||
participant E as Exchange
|
||||
C->>A: POST /auth/api-key 或 GET /auth/derive-api-key
|
||||
A->>A: 校验本地钱包登记、链 ID、时间和 EIP-712 签名
|
||||
alt 创建
|
||||
A->>E: 首次登记签发者、nonce 和 API key ID
|
||||
else 派生
|
||||
A->>E: 查询已签发的同一 nonce
|
||||
end
|
||||
E-->>A: 登记结果或已签发 ID
|
||||
A-->>C: 返回可签名 L2 HTTP 请求的凭证
|
||||
C->>A: GET /auth/api-keys 或 DELETE /auth/api-key,使用 L2 签名
|
||||
A->>E: 查询当前账户或撤销当前密钥
|
||||
A-->>C: 返回有效密钥 ID 或确认撤销
|
||||
```
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as 客户端
|
||||
participant H as account_http.rs
|
||||
participant V as signed_order.rs
|
||||
participant R as 钱包 RPC
|
||||
participant E as Exchange
|
||||
C->>H: 带签名的订单、查询、撤单或心跳
|
||||
H->>H: 验证请求并绑定本地账户
|
||||
alt 凭证无效
|
||||
H-->>C: HTTP 401
|
||||
else 提交签名订单
|
||||
H->>V: 提交订单、API key 与已认证的签名者地址
|
||||
V->>V: 按 tokenId 查找资产、EIP-712 域并核对钱包绑定
|
||||
alt 合约钱包
|
||||
V->>R: eth_call isValidSignature(hash, signature)
|
||||
R-->>V: ERC-1271 魔术值或失败
|
||||
else EOA、Proxy 或 Safe
|
||||
V->>V: 恢复 EIP-712 签名者
|
||||
end
|
||||
alt 验证通过
|
||||
V->>E: 以订单哈希为幂等键提交本地订单与已验签 maker
|
||||
E-->>V: 返回挂单、即时成交或 delayed 回执
|
||||
V-->>H: 返回订单状态、资产数量和即时成交 ID
|
||||
else 验证失败
|
||||
V-->>H: 返回订单拒绝
|
||||
end
|
||||
H-->>C: 返回单笔或批量结果
|
||||
else 查询余额或刷新
|
||||
H->>E: 读取绑定账户的抵押余额或指定结果份额
|
||||
E-->>H: 同一快照内的可用量加挂单预留
|
||||
H-->>C: 返回余额和模拟授权,或确认刷新
|
||||
else 订单与成交查询、撤单或心跳
|
||||
H->>E: 解析市场与资产 ID,按绑定账户执行请求
|
||||
E-->>H: 返回操作结果
|
||||
H-->>C: 返回响应
|
||||
end
|
||||
```
|
||||
|
||||
## 盘口 HTTP
|
||||
|
||||
`cli DATABASE --market-http 127.0.0.1:9002 [ORDER_CONFIG_JSON]` 启动公开盘口读取服务。可与写入会话和 WebSocket 服务共用数据库文件。提供与账户 HTTP 相同的配置文件时,客户端可用公开资产 ID 查询盘口、报价、交易参数及历史价格,并可用公开条件 ID 查询 CLOB 市场参数。Gamma 列表和详情返回配置中的条件 ID 和 CTF 代币 ID。Position Exchange 市场配齐两个资产后返回 `positionIds`。加载映射无需 RPC。[HTTP 请求样例](../../docs/examples/clob-http.http)
|
||||
`cli DATABASE --market-http 127.0.0.1:9002` 启动公开盘口读取服务。可与写入会话和 WebSocket 服务共用数据库文件。[HTTP 请求样例](../../docs/examples/clob-http.http)
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
main["main.rs"] --> http["market_http.rs"]
|
||||
http --> ids["wire_ids.rs"]
|
||||
http --> api["exchange::Exchange::public_books"]
|
||||
http --> hash["exchange::relabel_book_snapshot"]
|
||||
```
|
||||
|
||||
```mermaid
|
||||
@@ -267,10 +98,8 @@ sequenceDiagram
|
||||
participant H as market_http
|
||||
participant E as Exchange
|
||||
C->>H: GET /book?token_id=... 或 POST /books
|
||||
H->>H: 将请求中的资产 ID 映射为本地资产 ID
|
||||
H->>E: 读取本地资产盘口
|
||||
H->>E: 提交本次请求的资产 ID
|
||||
E-->>H: 一个数据库快照中的盘口列表
|
||||
H->>H: 写入已配置的公开 ID 并重新计算哈希
|
||||
H-->>C: 单盘 JSON 对象或批量 JSON 数组
|
||||
```
|
||||
|
||||
@@ -418,6 +247,40 @@ sequenceDiagram
|
||||
|
||||
event_id 取自本地 events 或 catalog 查询,market_id 取自 assets 查询。两个参数均可重复,同类 ID 取并集,同时指定事件与市场时取交集。独立市场的公告也能通过 market_id 查询。默认按公告 ID 降序,每页 20 条;支持 order=id、ascending、offset 和 0 到 100 的 limit。当前查询对其他筛选参数返回 400。
|
||||
|
||||
### 组合账本
|
||||
|
||||
重放[组合样例](../../docs/examples/combo-ledger.jsonl),或自选两个已上架市场的结果,向 `prepare_combo` 提交 `legs`。取回的 `combo` ID 可用于 `split_combo`、`merge_combo`、`redeem_combo` 和只读的 `combo`。拆分和合并的数量表示成对的 YES 和 NO 份额,兑付需要指定一侧。数量可使用整数份额 `qty` 或微份 `qty_micros`。只读查询加 `account` 可查看该账户的两侧份额。
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
actor U as 操作员
|
||||
participant S as stream.rs
|
||||
participant E as Exchange
|
||||
U->>S: prepare_combo,提交腿的市场与选择
|
||||
S->>E: 执行组合定义命令
|
||||
E-->>U: 组合 ID、腿和可兑奖状态
|
||||
U->>S: split_combo,再查询 combo
|
||||
S->>E: 冻结模拟现金,生成 YES 和 NO
|
||||
E-->>U: 账户两侧的微份额及当前兑付状态
|
||||
```
|
||||
|
||||
### 组合询价
|
||||
|
||||
重放[组合询价样例](../../docs/examples/combo-rfq.jsonl)。样例先用双方现金生成互补的组合份额,再用已有份额合并并卖出。报价方通过 `combo_rfq_open` 发现尚未结束的询价。请求方用 `combo_rfq` 查看报价,再接受指定报价。报价与接受命令使用各自的请求 ID,账户余额查询会列出已受理询价的现金预留。
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
actor T as 请求方
|
||||
participant J as JSONL 命令入口
|
||||
actor M as 报价方
|
||||
T->>J: request_combo_quote
|
||||
M->>J: combo_rfq_open 与 quote_combo
|
||||
T->>J: accept_combo_quote,指定报价 ID
|
||||
J-->>T: 确认期限与预留状态
|
||||
M->>J: respond_combo_quote,提交最后确认
|
||||
T->>J: combo_rfq,读取成交或失败状态
|
||||
```
|
||||
|
||||
### 从事件页进入订单簿
|
||||
|
||||
```mermaid
|
||||
@@ -445,14 +308,11 @@ sequenceDiagram
|
||||
|
||||
### 浏览目录
|
||||
|
||||
`GET /markets` 和 `GET /events` 返回数组。支持 limit、offset、ascending、order、active、closed,以及可重复的 id 和 slug。市场列表也支持重复的 `condition_ids`、`clob_token_ids` 和 `position_ids`。同类标识取并集,提供多类标识时取交集,每类最多 100 个值。未知资产不返回市场。查询字符串中的加号需要编码成 %2B。
|
||||
|
||||
已迁移的市场可以在 `ORDER_CONFIG_JSON` 中通过 `migrated_markets` 登记。每项包含本地 `market`、`ctf_condition_id`、两个 `ctf_token_ids` 和两个 `position_ids`,两个数组均按 YES、NO 排列。原有 `tokens` 必须完整配置实际交易使用的一组资产。目录的 `conditionId` 使用 CTF 条件,查询也接受仓位推导的结构条件。迁移盘以 `version=v1` 返回两组资产,原生仓位盘以 `version=v2` 返回 `positionIds`。仅登记为目录资产的另一组 ID 可用于查市场,签名下单仍由 `tokens` 决定。
|
||||
`GET /markets` 和 `GET /events` 返回数组。支持 limit、offset、ascending、order、active、closed,以及可重复的 id 和 slug。市场列表也支持重复的 condition_ids 和 clob_token_ids。同类标识取并集,提供多类标识时取交集。查询字符串中的加号需要编码成 %2B。
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
H["market_http.rs · GET /markets 与 /events"] --> W["wire_ids.rs · 目录资产"]
|
||||
H --> P["exchange/gamma_list.rs"] --> D["exchange/gamma_directory.rs"]
|
||||
H["market_http.rs · GET /markets 与 /events"] --> P["exchange/gamma_list.rs"] --> D["exchange/gamma_directory.rs"]
|
||||
```
|
||||
|
||||
```mermaid
|
||||
@@ -464,14 +324,13 @@ sequenceDiagram
|
||||
H->>E: gamma_list(Events),保留重复参数
|
||||
E-->>C: 一个事件及其可见子盘
|
||||
C->>H: GET /markets?slug=nvda-300&closed=any
|
||||
H->>H: 按各自的资产类型转换筛选值
|
||||
H->>E: gamma_list(Markets),在分页前应用筛选
|
||||
H->>E: gamma_list(Markets),按 slug 查询开放或已关闭的盘口
|
||||
E-->>C: 匹配市场数组
|
||||
```
|
||||
|
||||
### 查询公开成交
|
||||
|
||||
`GET /v2/trades?user=bob&limit=1` 按成交时间倒序返回 Bob 作为吃单方的成交。查询双方时加 `taker_only=false`。下一页传回 `pagination.next_cursor` 并重送筛选条件。condition 支持已配置的公开条件 ID 和本地市场 ID,event_id 接受 Gamma 目录里的数字事件 ID。条件列表以逗号分隔。提供 `ORDER_CONFIG_JSON` 时,成交响应的 `condition_id` 和 `token_id` 使用同一份配置中的公开标识。
|
||||
`GET /v2/trades?user=bob&limit=1` 按成交时间倒序返回 Bob 作为吃单方的成交。查询双方时加 `taker_only=false`。下一页传回 `pagination.next_cursor` 并重送筛选条件。condition 支持本地市场 ID,event_id 接受 Gamma 目录里的数字事件 ID。条件列表以逗号分隔。钱包、市场和资产字段使用本地账户和目录标识。
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
@@ -484,18 +343,34 @@ sequenceDiagram
|
||||
participant H as market-http
|
||||
participant E as Exchange
|
||||
C->>H: GET /v2/trades,user=bob,limit=1
|
||||
H->>H: 逐项将公开条件 ID 映射为本地市场
|
||||
H->>E: 查询该账户的成交
|
||||
H->>E: 解析参数并查询该账户的成交
|
||||
E-->>H: 一条成交和下一页签名游标
|
||||
H-->>C: data 含公开条件和资产 ID,原样返回 pagination
|
||||
H-->>C: data、pagination
|
||||
C->>H: 重送 user 和 cursor
|
||||
H->>E: 验证签名,从上一笔订单之后继续
|
||||
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 查询。多个条件或多个事件用逗号分隔,每次选择一种查询方式。已配置的公开条件 ID 可用于筛选,并出现在按条件或事件查询返回的 `condition_id` 中。
|
||||
`GET /v2/resolutions?condition=m` 读取单盘状态,`?event_id=1` 读取事件的各个盘口。已登记问题标识的乐观裁决市场也支持 question_id 查询。多个条件或多个事件用逗号分隔,每次选择一种查询方式。
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
@@ -514,9 +389,19 @@ 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 可使用已配置的公开条件 ID,省略时查询所有已持有市场。无持仓的钱包返回零,仅有现金的账户也返回零。
|
||||
`GET /v2/value?user=alice&condition=e` 返回该账户在市场 e 的持仓价值,单位为模拟美元。使用已登记的本地账户名或 20 字节钱包地址。省略 condition 查询所有已持有市场。无持仓的钱包返回零,仅有现金的账户也返回零。
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
@@ -540,7 +425,7 @@ sequenceDiagram
|
||||
|
||||
### 查询未平仓量
|
||||
|
||||
`GET /v2/oi` 返回单行 GLOBAL。指定 `GET /v2/oi?condition=cup` 可查 cup 的金额,空盘返回 0,归档市场从数组中省略。筛选支持已配置的公开条件 ID、逗号分隔及 condition_id、conditionId 两个别名。按市场查询时,响应返回已映射的 `condition_id`。已有份额却无法估值时,本地返回可重试的 503。
|
||||
`GET /v2/oi` 返回单行 GLOBAL。指定 `GET /v2/oi?condition=cup` 可查 cup 的金额,空盘返回 0,归档市场从数组中省略。筛选支持逗号分隔及 condition_id、conditionId 两个别名。已有份额却无法估值时,本地返回可重试的 503。
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
@@ -601,20 +486,3 @@ sequenceDiagram
|
||||
E-->>H: true
|
||||
H-->>C: 200,neg_risk 为真
|
||||
```
|
||||
|
||||
## 做市返佣 HTTP
|
||||
|
||||
公开市场服务的 `POST /v1/maker-tier/tiers` 接收最多 100 个地址并返回 UTC 档位快照。`GET /rebates/current` 接收 `date` 和 `maker_address`,返回已发放明细,空结果为 JSON null。
|
||||
|
||||
JSONL 和账户 HTTP 的维护循环都执行日结。同一 SQLite 数据库可同时服务二者,按日期去重。JSONL `activity` 可通过 `types=["MAKER_REBATE"]` 查询指定账户的返佣流水。
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as 客户端
|
||||
participant H as market_http.rs
|
||||
participant E as Exchange
|
||||
C->>H: 查询 maker 档位或指定日期返佣
|
||||
H->>E: 验证地址与日期后读取模拟账本
|
||||
E-->>H: 档位快照或返佣明细
|
||||
H-->>C: 返回结果并映射公开条件 ID
|
||||
```
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,334 +0,0 @@
|
||||
use super::{header, Credentials, Principal, Reply};
|
||||
use crate::ethereum::{
|
||||
address_word, fixed_hex, keccak, recover_address, typed_digest, u64_word, uint_word, Address,
|
||||
Word,
|
||||
};
|
||||
use anyhow::Result;
|
||||
use data_encoding::{BASE64URL, HEXLOWER};
|
||||
use exchange::Exchange;
|
||||
use hmac::{Hmac, Mac};
|
||||
use serde_json::json;
|
||||
use sha2::{Digest, Sha256};
|
||||
use tiny_http::Header;
|
||||
|
||||
const UNAUTHORIZED: (u16, &str) = (401, "Invalid L1 Request headers");
|
||||
const UNAVAILABLE: (u16, &str) = (503, "API keys unavailable");
|
||||
|
||||
pub(super) const CREATE: &str = "/auth/api-key";
|
||||
pub(super) const DERIVE: &str = "/auth/derive-api-key";
|
||||
pub(super) const LIST: &str = "/auth/api-keys";
|
||||
|
||||
pub(super) fn list(exchange: &Exchange, registry: &Credentials, account: &str) -> Reply {
|
||||
let mut ids = Vec::new();
|
||||
for (id, root) in ®istry.by_key {
|
||||
if root.account != account {
|
||||
continue;
|
||||
}
|
||||
if let Some(chain) = root.wallet_auth_chain_id {
|
||||
let keys = exchange.active_api_keys(id).map_err(|_| UNAVAILABLE)?;
|
||||
ids.extend(keys.into_iter().filter_map(|(key, nonce)| {
|
||||
(Issued::new(root, id, nonce, chain).id == key).then_some(key)
|
||||
}));
|
||||
}
|
||||
}
|
||||
ids.sort_unstable();
|
||||
ids.dedup();
|
||||
Ok(json!({"apiKeys":ids}))
|
||||
}
|
||||
|
||||
pub(super) fn revoke(exchange: &Exchange, key: &str, issued: bool) -> Reply {
|
||||
if !issued {
|
||||
return Err((400, "configured API key cannot be deleted through HTTP"));
|
||||
}
|
||||
if !exchange
|
||||
.revoke_issued_api_key(key)
|
||||
.map_err(|_| UNAVAILABLE)?
|
||||
{
|
||||
return Err((401, "Unauthorized"));
|
||||
}
|
||||
Ok(json!({}))
|
||||
}
|
||||
|
||||
pub(super) fn credentials(
|
||||
exchange: &Exchange,
|
||||
registry: &Credentials,
|
||||
headers: &[Header],
|
||||
now: u64,
|
||||
create: bool,
|
||||
) -> Reply {
|
||||
let address = header(headers, "POLY_ADDRESS").ok_or(UNAUTHORIZED)?;
|
||||
let timestamp = header(headers, "POLY_TIMESTAMP").ok_or(UNAUTHORIZED)?;
|
||||
let signature = header(headers, "POLY_SIGNATURE").ok_or(UNAUTHORIZED)?;
|
||||
let seconds = timestamp.parse::<u64>().map_err(|_| UNAUTHORIZED)?;
|
||||
if timestamp != seconds.to_string() || now.abs_diff(seconds) > 30 {
|
||||
return Err(UNAUTHORIZED);
|
||||
}
|
||||
let wallet = fixed_hex::<20>(address).map_err(|_| UNAUTHORIZED)?;
|
||||
let (issuer, principal) = registry
|
||||
.wallet_auth
|
||||
.get(&wallet)
|
||||
.and_then(|issuer| Some((issuer, registry.by_key.get(issuer)?)))
|
||||
.ok_or(UNAUTHORIZED)?;
|
||||
let chain = principal.wallet_auth_chain_id.ok_or(UNAUTHORIZED)?;
|
||||
let mut nonce_headers = headers.iter().filter(|h| h.field.equiv("POLY_NONCE"));
|
||||
let nonce = nonce_headers.next().map_or("0", |h| h.value.as_str());
|
||||
if nonce_headers.next().is_some() {
|
||||
return Err(UNAUTHORIZED);
|
||||
}
|
||||
let nonce = uint_word(nonce).map_err(|_| UNAUTHORIZED)?;
|
||||
let signer = recover_address(auth_digest(chain, wallet, timestamp, nonce), signature)
|
||||
.map_err(|_| UNAUTHORIZED)?;
|
||||
if signer != wallet {
|
||||
return Err(UNAUTHORIZED);
|
||||
}
|
||||
let issued = Issued::new(principal, issuer, nonce, chain);
|
||||
if create {
|
||||
if registry.by_key.contains_key(&issued.id) {
|
||||
return Err(UNAVAILABLE);
|
||||
}
|
||||
if !exchange
|
||||
.issue_api_key(issuer, &nonce, &issued.id)
|
||||
.map_err(|_| UNAVAILABLE)?
|
||||
{
|
||||
return Err((400, "Could not create api key"));
|
||||
}
|
||||
} else if exchange
|
||||
.issued_api_key_id(issuer, &nonce)
|
||||
.map_err(|_| UNAVAILABLE)?
|
||||
.as_deref()
|
||||
!= Some(issued.id.as_str())
|
||||
{
|
||||
return Err((404, "Could not derive api key"));
|
||||
}
|
||||
Ok(
|
||||
json!({"apiKey":issued.id,"secret":BASE64URL.encode(&issued.secret),"passphrase":issued.passphrase}),
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn principal(
|
||||
exchange: &Exchange,
|
||||
registry: &Credentials,
|
||||
key: &str,
|
||||
) -> Result<Option<Principal>> {
|
||||
let Some((issuer, nonce)) = exchange.issued_api_key_scope(key)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let Some(root) = registry.by_key.get(&issuer) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let Some(chain) = root.wallet_auth_chain_id else {
|
||||
return Ok(None);
|
||||
};
|
||||
let issued = Issued::new(root, &issuer, nonce, chain);
|
||||
if issued.id != key {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(Some(Principal {
|
||||
account: root.account.clone(),
|
||||
address: root.address.clone(),
|
||||
contract_wallet: root.contract_wallet.clone(),
|
||||
wallet_auth_chain_id: None,
|
||||
secret: issued.secret.to_vec(),
|
||||
passphrase: Sha256::digest(issued.passphrase.as_bytes()).into(),
|
||||
}))
|
||||
}
|
||||
|
||||
fn auth_digest(chain: u64, wallet: Address, timestamp: &str, nonce: Word) -> Word {
|
||||
let domain = keccak(
|
||||
[
|
||||
keccak("EIP712Domain(string name,string version,uint256 chainId)"),
|
||||
keccak("ClobAuthDomain"),
|
||||
keccak("1"),
|
||||
u64_word(chain),
|
||||
]
|
||||
.concat(),
|
||||
);
|
||||
let body = keccak(
|
||||
[
|
||||
keccak("ClobAuth(address address,string timestamp,uint256 nonce,string message)"),
|
||||
address_word(wallet),
|
||||
keccak(timestamp),
|
||||
nonce,
|
||||
keccak("This message attests that I control the given wallet"),
|
||||
]
|
||||
.concat(),
|
||||
);
|
||||
typed_digest(domain, body)
|
||||
}
|
||||
|
||||
struct Issued {
|
||||
id: String,
|
||||
secret: Word,
|
||||
passphrase: String,
|
||||
}
|
||||
|
||||
impl Issued {
|
||||
fn new(root: &Principal, issuer: &str, nonce: Word, chain: u64) -> Self {
|
||||
let scope = json!([
|
||||
issuer,
|
||||
root.address,
|
||||
root.account,
|
||||
root.contract_wallet,
|
||||
chain
|
||||
])
|
||||
.to_string();
|
||||
let derive = |purpose: &[u8]| -> Word {
|
||||
let mut mac = Hmac::<Sha256>::new_from_slice(&root.secret)
|
||||
.expect("HMAC-SHA256 accepts any key size");
|
||||
mac.update(b"eventbook-wallet-api-key-v1\0");
|
||||
mac.update(purpose);
|
||||
mac.update(&nonce);
|
||||
mac.update(scope.as_bytes());
|
||||
mac.finalize().into_bytes().into()
|
||||
};
|
||||
let mut id = derive(b"id");
|
||||
id[6] = (id[6] & 0x0f) | 0x40;
|
||||
id[8] = (id[8] & 0x3f) | 0x80;
|
||||
let id = HEXLOWER.encode(&id[..16]);
|
||||
let id = format!(
|
||||
"{}-{}-{}-{}-{}",
|
||||
&id[..8],
|
||||
&id[8..12],
|
||||
&id[12..16],
|
||||
&id[16..20],
|
||||
&id[20..]
|
||||
);
|
||||
Self {
|
||||
id,
|
||||
secret: derive(b"secret"),
|
||||
passphrase: BASE64URL.encode(&derive(b"passphrase")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::account_http::Record;
|
||||
use serde_json::Value;
|
||||
use tiny_http::Method;
|
||||
|
||||
#[test]
|
||||
fn issued_key_authenticates_http_and_websocket_until_revoked() {
|
||||
let sample: Value = serde_json::from_str(include_str!(
|
||||
"../../../../docs/examples/clob-wallet-auth.json"
|
||||
))
|
||||
.unwrap();
|
||||
let headers: Vec<_> = sample["headers"]
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|(name, value)| {
|
||||
Header::from_bytes(name.as_str(), value.as_str().unwrap()).unwrap()
|
||||
})
|
||||
.collect();
|
||||
let value = |name: &str| sample["headers"][name].as_str().unwrap();
|
||||
let chain = sample["chain_id"].as_u64().unwrap();
|
||||
let now = sample["timestamp"].as_u64().unwrap();
|
||||
let wallet = fixed_hex(value("POLY_ADDRESS")).unwrap();
|
||||
let nonce = uint_word(value("POLY_NONCE")).unwrap();
|
||||
assert_eq!(
|
||||
format!(
|
||||
"0x{}",
|
||||
HEXLOWER.encode(&auth_digest(chain, wallet, value("POLY_TIMESTAMP"), nonce))
|
||||
),
|
||||
sample["expected_digest"].as_str().unwrap()
|
||||
);
|
||||
|
||||
let registry = |chain| {
|
||||
Credentials::from_records(vec![Record {
|
||||
api_key: "seed-key".into(),
|
||||
account: "alice".into(),
|
||||
address: value("POLY_ADDRESS").into(),
|
||||
contract_wallet: None,
|
||||
wallet_auth_chain_id: Some(chain),
|
||||
secret: BASE64URL.encode(&[0x12; 32]),
|
||||
passphrase: "test-root-passphrase".into(),
|
||||
}])
|
||||
.unwrap()
|
||||
};
|
||||
let exchange = Exchange::open(":memory:").unwrap();
|
||||
let creds = registry(chain);
|
||||
assert_eq!(
|
||||
credentials(&exchange, ®istry(chain + 1), &headers, now, true),
|
||||
Err(UNAUTHORIZED)
|
||||
);
|
||||
assert_eq!(
|
||||
credentials(&exchange, &creds, &headers, now + 31, true),
|
||||
Err(UNAUTHORIZED)
|
||||
);
|
||||
assert_eq!(
|
||||
credentials(&exchange, &creds, &headers, now, false)
|
||||
.unwrap_err()
|
||||
.0,
|
||||
404
|
||||
);
|
||||
let response = credentials(&exchange, &creds, &headers, now, true).unwrap();
|
||||
assert_eq!(
|
||||
credentials(&exchange, &creds, &headers, now, true)
|
||||
.unwrap_err()
|
||||
.0,
|
||||
400
|
||||
);
|
||||
assert_eq!(
|
||||
credentials(&exchange, &creds, &headers, now, false).unwrap(),
|
||||
response
|
||||
);
|
||||
assert_ne!(response["secret"], BASE64URL.encode(&[0x12; 32]));
|
||||
let id = response["apiKey"].as_str().unwrap();
|
||||
let issued = principal(&exchange, &creds, id).unwrap().unwrap();
|
||||
assert!(principal(&exchange, ®istry(chain + 1), id)
|
||||
.unwrap()
|
||||
.is_none());
|
||||
let secret = BASE64URL
|
||||
.decode(response["secret"].as_str().unwrap().as_bytes())
|
||||
.unwrap();
|
||||
let mut mac = Hmac::<Sha256>::new_from_slice(&secret).unwrap();
|
||||
mac.update(format!("{now}GET/data/orders").as_bytes());
|
||||
let signature = BASE64URL.encode(&mac.finalize().into_bytes());
|
||||
let hmac_headers = [
|
||||
("POLY_API_KEY", id),
|
||||
("POLY_ADDRESS", value("POLY_ADDRESS")),
|
||||
("POLY_PASSPHRASE", response["passphrase"].as_str().unwrap()),
|
||||
("POLY_TIMESTAMP", value("POLY_TIMESTAMP")),
|
||||
("POLY_SIGNATURE", &signature),
|
||||
]
|
||||
.map(|(name, value)| Header::from_bytes(name, value).unwrap());
|
||||
let (_, owner, _) = creds
|
||||
.verify(
|
||||
&hmac_headers,
|
||||
&Method::Get,
|
||||
"/data/orders",
|
||||
b"",
|
||||
now,
|
||||
Some(&issued),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(owner.account, "alice");
|
||||
assert_eq!(
|
||||
list(&exchange, &creds, "alice").unwrap(),
|
||||
json!({"apiKeys":[id]})
|
||||
);
|
||||
assert_eq!(
|
||||
list(&exchange, &creds, "bob").unwrap(),
|
||||
json!({"apiKeys":[]})
|
||||
);
|
||||
assert!(revoke(&exchange, "seed-key", false).is_err());
|
||||
|
||||
let auth = json!({"type":"user","auth":response}).to_string();
|
||||
let ws_creds = crate::user_ws::Credentials::from_account(registry(chain));
|
||||
let session = crate::user_ws::Session::start(&exchange, &ws_creds, &auth).unwrap();
|
||||
assert!(session.active(&exchange).unwrap());
|
||||
|
||||
revoke(&exchange, id, true).unwrap();
|
||||
assert!(!session.active(&exchange).unwrap());
|
||||
assert!(crate::user_ws::Session::start(&exchange, &ws_creds, &auth).is_err());
|
||||
assert!(principal(&exchange, &creds, id).unwrap().is_none());
|
||||
assert_eq!(
|
||||
list(&exchange, &creds, "alice").unwrap(),
|
||||
json!({"apiKeys":[]})
|
||||
);
|
||||
assert!(credentials(&exchange, &creds, &headers, now, false).is_err());
|
||||
assert!(credentials(&exchange, &creds, &headers, now, true).is_err());
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use serde::de::DeserializeOwned;
|
||||
use std::{fs::File, io::Read, path::Path};
|
||||
|
||||
pub(crate) fn read<T: DeserializeOwned>(path: &Path) -> Result<T> {
|
||||
let file = File::open(path).context("open account credentials")?;
|
||||
let meta = file.metadata()?;
|
||||
ensure!(
|
||||
meta.is_file() && meta.len() <= 1_048_576,
|
||||
"invalid credentials file"
|
||||
);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
ensure!(
|
||||
meta.permissions().mode() & 0o077 == 0,
|
||||
"credentials file must be private"
|
||||
);
|
||||
}
|
||||
let mut bytes = Vec::new();
|
||||
file.take(1_048_577).read_to_end(&mut bytes)?;
|
||||
ensure!(bytes.len() <= 1_048_576, "invalid credentials file");
|
||||
serde_json::from_slice(&bytes).map_err(|_| anyhow::anyhow!("invalid credentials file"))
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use data_encoding::HEXLOWER_PERMISSIVE;
|
||||
use k256::ecdsa::{RecoveryId, Signature, VerifyingKey};
|
||||
use sha3::{Digest, Keccak256};
|
||||
|
||||
pub(crate) type Word = [u8; 32];
|
||||
pub(crate) type Address = [u8; 20];
|
||||
|
||||
pub(crate) fn keccak(data: impl AsRef<[u8]>) -> Word {
|
||||
Keccak256::digest(data).into()
|
||||
}
|
||||
|
||||
pub(crate) fn fixed_hex<const N: usize>(text: &str) -> Result<[u8; N]> {
|
||||
let raw = text
|
||||
.strip_prefix("0x")
|
||||
.context("invalid hexadecimal value")?;
|
||||
ensure!(raw.len() == N * 2, "invalid hexadecimal width");
|
||||
HEXLOWER_PERMISSIVE
|
||||
.decode(raw.as_bytes())?
|
||||
.try_into()
|
||||
.map_err(|_| anyhow::anyhow!("invalid hexadecimal width"))
|
||||
}
|
||||
|
||||
pub(crate) fn address_word(address: Address) -> Word {
|
||||
let mut out = [0; 32];
|
||||
out[12..].copy_from_slice(&address);
|
||||
out
|
||||
}
|
||||
|
||||
pub(crate) fn u64_word(value: u64) -> Word {
|
||||
let mut out = [0; 32];
|
||||
out[24..].copy_from_slice(&value.to_be_bytes());
|
||||
out
|
||||
}
|
||||
|
||||
pub(crate) fn uint_word(text: &str) -> Result<Word> {
|
||||
ensure!(
|
||||
!text.is_empty() && text.len() <= 78 && text.bytes().all(|b| b.is_ascii_digit()),
|
||||
"invalid uint256"
|
||||
);
|
||||
let mut out = [0u8; 32];
|
||||
for digit in text.bytes() {
|
||||
let mut carry = u16::from(digit - b'0');
|
||||
for byte in out.iter_mut().rev() {
|
||||
carry += u16::from(*byte) * 10;
|
||||
*byte = carry as u8;
|
||||
carry >>= 8;
|
||||
}
|
||||
ensure!(carry == 0, "uint256 overflow");
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
pub(crate) fn typed_digest(domain: Word, body: Word) -> Word {
|
||||
let mut message = [0u8; 66];
|
||||
message[..2].copy_from_slice(&[0x19, 0x01]);
|
||||
message[2..34].copy_from_slice(&domain);
|
||||
message[34..].copy_from_slice(&body);
|
||||
keccak(message)
|
||||
}
|
||||
|
||||
pub(crate) fn recover_address(digest: Word, signature: &str) -> Result<Address> {
|
||||
let bytes = fixed_hex::<65>(signature)?;
|
||||
let signature = Signature::from_slice(&bytes[..64]).context("invalid signature")?;
|
||||
ensure!(signature.normalize_s().is_none(), "noncanonical signature");
|
||||
let id = match bytes[64] {
|
||||
0 | 1 => bytes[64],
|
||||
27 | 28 => bytes[64] - 27,
|
||||
_ => anyhow::bail!("invalid recovery ID"),
|
||||
};
|
||||
let recovery = RecoveryId::from_byte(id).context("invalid recovery ID")?;
|
||||
let key = VerifyingKey::recover_from_prehash(&digest, &signature, recovery)
|
||||
.context("invalid signature")?;
|
||||
let public = key.to_encoded_point(false);
|
||||
let mut address = [0; 20];
|
||||
address.copy_from_slice(&keccak(&public.as_bytes()[1..])[12..]);
|
||||
Ok(address)
|
||||
}
|
||||
+7
-77
@@ -1,104 +1,34 @@
|
||||
mod account_http;
|
||||
mod credential_file;
|
||||
mod ethereum;
|
||||
mod market_http;
|
||||
mod market_ws;
|
||||
mod order_refs;
|
||||
mod signed_order;
|
||||
mod snapshot_http;
|
||||
mod stream;
|
||||
mod subscriptions;
|
||||
mod user_ws;
|
||||
mod wire_ids;
|
||||
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use exchange::Exchange;
|
||||
use std::{
|
||||
env, io,
|
||||
net::{SocketAddr, TcpListener},
|
||||
path::Path,
|
||||
};
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let mut args = env::args_os().skip(1);
|
||||
let usage = "usage: cli DATABASE [--market-ws HOST:PORT [ORDER_CONFIG_JSON] | --market-http HOST:PORT [ORDER_CONFIG_JSON] | --user-ws LOOPBACK:PORT [--account-credentials] CREDENTIALS_JSON [ORDER_CONFIG_JSON] | --account-http LOOPBACK:PORT CREDENTIALS_JSON [ORDER_CONFIG_JSON]]";
|
||||
let usage = "usage: cli DATABASE [--market-ws HOST:PORT | --market-http HOST:PORT]";
|
||||
let path = args.next().context(usage)?;
|
||||
if let Some(mode) = args.next() {
|
||||
ensure!(
|
||||
mode == "--market-ws"
|
||||
|| mode == "--market-http"
|
||||
|| mode == "--user-ws"
|
||||
|| mode == "--account-http",
|
||||
usage
|
||||
);
|
||||
ensure!(mode == "--market-ws" || mode == "--market-http", usage);
|
||||
let addr: SocketAddr = args
|
||||
.next()
|
||||
.and_then(|s| s.into_string().ok())
|
||||
.context(usage)?
|
||||
.parse()?;
|
||||
let credentials = if mode == "--user-ws" || mode == "--account-http" {
|
||||
ensure!(
|
||||
addr.ip().is_loopback(),
|
||||
"private account services require a loopback listener"
|
||||
);
|
||||
Some(args.next().context(usage)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let ws_account_credentials = mode == "--user-ws"
|
||||
&& credentials
|
||||
.as_ref()
|
||||
.is_some_and(|value| value == "--account-credentials");
|
||||
let credentials = if ws_account_credentials {
|
||||
Some(args.next().context(usage)?)
|
||||
} else {
|
||||
credentials
|
||||
};
|
||||
let order_config = args.next();
|
||||
ensure!(args.next().is_none(), usage);
|
||||
let engine = Exchange::open(path)?;
|
||||
let listener = TcpListener::bind(addr)?;
|
||||
return match mode.to_str() {
|
||||
Some("--market-http" | "--market-ws") => {
|
||||
let ids = order_config
|
||||
.as_deref()
|
||||
.map(Path::new)
|
||||
.map(signed_order::Orders::load_identifiers)
|
||||
.transpose()?
|
||||
.unwrap_or_default();
|
||||
if mode == "--market-http" {
|
||||
market_http::serve(engine, listener, ids)
|
||||
} else {
|
||||
market_ws::serve(engine, listener, None, ids)
|
||||
}
|
||||
}
|
||||
Some("--account-http") => account_http::serve(
|
||||
engine,
|
||||
listener,
|
||||
Path::new(&credentials.context(usage)?),
|
||||
order_config.as_deref().map(Path::new),
|
||||
),
|
||||
_ => {
|
||||
let credentials = credentials
|
||||
.as_deref()
|
||||
.map(Path::new)
|
||||
.map(|path| {
|
||||
if ws_account_credentials {
|
||||
account_http::Credentials::load(path)
|
||||
.map(user_ws::Credentials::from_account)
|
||||
} else {
|
||||
user_ws::Credentials::load(path)
|
||||
}
|
||||
})
|
||||
.transpose()?;
|
||||
let credentials = match (credentials, order_config.as_deref()) {
|
||||
(Some(credentials), Some(path)) => {
|
||||
let identifiers = signed_order::Orders::load_identifiers(Path::new(path))?;
|
||||
Some(credentials.with_identifiers(identifiers))
|
||||
}
|
||||
(credentials, _) => credentials,
|
||||
};
|
||||
market_ws::serve(engine, listener, credentials, wire_ids::WireIds::default())
|
||||
}
|
||||
return if mode == "--market-http" {
|
||||
market_http::serve(engine, listener)
|
||||
} else {
|
||||
market_ws::serve(engine, listener)
|
||||
};
|
||||
}
|
||||
let mut exchange = Exchange::open(path)?;
|
||||
|
||||
+90
-498
@@ -1,6 +1,6 @@
|
||||
use crate::wire_ids::WireIds;
|
||||
use crate::snapshot_http;
|
||||
use anyhow::Result;
|
||||
use exchange::{ConditionList, Exchange, HistoryError};
|
||||
use exchange::{Exchange, HistoryError};
|
||||
use percent_encoding::percent_decode_str;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
@@ -21,7 +21,7 @@ struct BookParam {
|
||||
|
||||
type Reply = std::result::Result<Value, (u16, &'static str)>;
|
||||
|
||||
fn query(engine: &Mutex<Exchange>, ids: &WireIds, params: Vec<BookParam>, single: bool) -> Reply {
|
||||
fn query(engine: &Mutex<Exchange>, params: Vec<BookParam>, single: bool) -> Reply {
|
||||
if params.len() > MAX_BOOKS || params.iter().any(|p| p.token_id.trim().is_empty()) {
|
||||
return Err((
|
||||
400,
|
||||
@@ -32,19 +32,12 @@ fn query(engine: &Mutex<Exchange>, ids: &WireIds, params: Vec<BookParam>, single
|
||||
},
|
||||
));
|
||||
}
|
||||
let tokens = local_tokens(ids, params.into_iter().map(|p| p.token_id));
|
||||
let books = engine
|
||||
let tokens = params.into_iter().map(|p| p.token_id).collect::<Vec<_>>();
|
||||
let mut books = engine
|
||||
.lock()
|
||||
.map_err(|_| (500, "error getting the orderbook"))?
|
||||
.public_books(&tokens)
|
||||
.map_err(|_| (500, "error getting the orderbook"))?;
|
||||
let mut books = books
|
||||
.into_iter()
|
||||
.map(|book| {
|
||||
ids.book(book)
|
||||
.map_err(|_| (500, "error getting the orderbook"))
|
||||
})
|
||||
.collect::<std::result::Result<Vec<_>, _>>()?;
|
||||
if single {
|
||||
books.pop().ok_or((404, MISSING))
|
||||
} else {
|
||||
@@ -52,38 +45,6 @@ fn query(engine: &Mutex<Exchange>, ids: &WireIds, params: Vec<BookParam>, single
|
||||
}
|
||||
}
|
||||
|
||||
fn local_tokens(ids: &WireIds, tokens: impl IntoIterator<Item = String>) -> Vec<String> {
|
||||
tokens
|
||||
.into_iter()
|
||||
.map(|token| ids.local_asset(&token).to_owned())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn map_id_field(row: &mut Value, field: &str, map: impl FnOnce(&str) -> String) {
|
||||
if let Some(slot) = row.get_mut(field) {
|
||||
if let Some(id) = slot.as_str() {
|
||||
*slot = Value::String(map(id));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn map_query_asset<Q: serde::de::DeserializeOwned>(
|
||||
params: &str,
|
||||
ids: &WireIds,
|
||||
asset_fields: &[&str],
|
||||
) -> Result<Q, HistoryError> {
|
||||
let invalid = |_| HistoryError::Invalid("invalid query parameters".into());
|
||||
let mut fields: Vec<(String, String)> = serde_urlencoded::from_str(params).map_err(invalid)?;
|
||||
for (key, value) in &mut fields {
|
||||
if asset_fields.contains(&key.as_str()) {
|
||||
*value = ids.local_asset(value).to_owned();
|
||||
}
|
||||
}
|
||||
let encoded = serde_urlencoded::to_string(fields)
|
||||
.map_err(|_| HistoryError::Invalid("invalid query parameters".into()))?;
|
||||
serde_urlencoded::from_str(&encoded).map_err(invalid)
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum QuoteField {
|
||||
Spread,
|
||||
@@ -92,7 +53,6 @@ enum QuoteField {
|
||||
|
||||
fn quote_response(
|
||||
engine: &Mutex<Exchange>,
|
||||
ids: &WireIds,
|
||||
tokens: Vec<String>,
|
||||
field: QuoteField,
|
||||
single: bool,
|
||||
@@ -102,7 +62,6 @@ fn quote_response(
|
||||
QuoteField::Midpoint => (500, "error getting the midpoint"),
|
||||
};
|
||||
let exchange = engine.lock().map_err(|_| internal_error)?;
|
||||
let tokens = local_tokens(ids, tokens);
|
||||
let rows = match field {
|
||||
QuoteField::Spread => exchange.spreads(&tokens),
|
||||
QuoteField::Midpoint => exchange.midpoints(&tokens),
|
||||
@@ -121,7 +80,7 @@ fn quote_response(
|
||||
}
|
||||
let result = rows
|
||||
.into_iter()
|
||||
.filter_map(|(id, value)| value.map(|s| (ids.wire_asset(&id).to_owned(), Value::String(s))))
|
||||
.filter_map(|(id, value)| value.map(|s| (id, Value::String(s))))
|
||||
.collect();
|
||||
Ok(Value::Object(result))
|
||||
}
|
||||
@@ -146,12 +105,7 @@ impl WirePrice {
|
||||
}
|
||||
}
|
||||
|
||||
fn book_prices(
|
||||
engine: &Mutex<Exchange>,
|
||||
ids: &WireIds,
|
||||
rows: Vec<WirePrice>,
|
||||
single: bool,
|
||||
) -> Reply {
|
||||
fn book_prices(engine: &Mutex<Exchange>, rows: Vec<WirePrice>, single: bool) -> Reply {
|
||||
if rows.is_empty() || rows.len() > MAX_BOOKS {
|
||||
return Err((400, "Invalid payload"));
|
||||
}
|
||||
@@ -161,7 +115,6 @@ fn book_prices(
|
||||
if !single && row.side.is_none() {
|
||||
row.side = Some("SELL".into());
|
||||
}
|
||||
row.token_id = ids.local_asset(&row.token_id).to_owned();
|
||||
row.into_request()
|
||||
})
|
||||
.collect::<std::result::Result<Vec<_>, _>>()?;
|
||||
@@ -189,19 +142,12 @@ fn book_prices(
|
||||
.ok_or((500, "Internal server error"))?;
|
||||
return Ok(json!({"price":price}));
|
||||
}
|
||||
let Value::Object(rows) = value else {
|
||||
return Err((500, "Internal server error"));
|
||||
};
|
||||
Ok(Value::Object(
|
||||
rows.into_iter()
|
||||
.map(|(asset, row)| (ids.wire_asset(&asset).to_owned(), row))
|
||||
.collect(),
|
||||
))
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn read_json<T: serde::de::DeserializeOwned>(
|
||||
fn batch_params<T: serde::de::DeserializeOwned>(
|
||||
req: &mut Request,
|
||||
) -> std::result::Result<T, (u16, &'static str)> {
|
||||
) -> std::result::Result<Vec<T>, (u16, &'static str)> {
|
||||
if req.body_length().is_some_and(|n| n as u64 > MAX_BODY) {
|
||||
return Err((413, "Request body too large"));
|
||||
}
|
||||
@@ -216,13 +162,7 @@ fn read_json<T: serde::de::DeserializeOwned>(
|
||||
serde_json::from_slice(&data).map_err(|_| (400, "Invalid payload"))
|
||||
}
|
||||
|
||||
fn last_prices(
|
||||
engine: &Mutex<Exchange>,
|
||||
ids: &WireIds,
|
||||
tokens: Vec<String>,
|
||||
single: bool,
|
||||
) -> Reply {
|
||||
let tokens = local_tokens(ids, tokens);
|
||||
fn last_prices(engine: &Mutex<Exchange>, tokens: Vec<String>, single: bool) -> Reply {
|
||||
let mut rows = engine
|
||||
.lock()
|
||||
.map_err(|_| (500, "Internal server error"))?
|
||||
@@ -238,9 +178,6 @@ fn last_prices(
|
||||
None => json!({"price":"0.5","side":""}),
|
||||
})
|
||||
} else {
|
||||
for row in &mut rows {
|
||||
map_id_field(row, "token_id", |id| ids.wire_asset(id).to_owned());
|
||||
}
|
||||
Ok(Value::Array(rows))
|
||||
}
|
||||
}
|
||||
@@ -253,7 +190,6 @@ struct TokenQuery {
|
||||
fn token_setting(
|
||||
name: &str,
|
||||
engine: &Mutex<Exchange>,
|
||||
ids: &WireIds,
|
||||
params: &str,
|
||||
segment: Option<&str>,
|
||||
) -> Reply {
|
||||
@@ -266,7 +202,6 @@ fn token_setting(
|
||||
.into(),
|
||||
};
|
||||
let exchange = engine.lock().map_err(|_| (500, "Internal server error"))?;
|
||||
let token = ids.local_asset(&token);
|
||||
let unavailable = |e| match e {
|
||||
exchange::MarketDataError::Invalid(_) => invalid,
|
||||
exchange::MarketDataError::Unavailable => (500, "Internal server error"),
|
||||
@@ -274,21 +209,21 @@ fn token_setting(
|
||||
match name {
|
||||
"neg-risk" => {
|
||||
let flag = exchange
|
||||
.token_neg_risk(token)
|
||||
.token_neg_risk(&token)
|
||||
.map_err(unavailable)?
|
||||
.ok_or((404, "market not found"))?;
|
||||
Ok(json!({"neg_risk":flag}))
|
||||
}
|
||||
"fee-rate" => {
|
||||
let fee = exchange
|
||||
.base_fee_bps(token)
|
||||
.base_fee_bps(&token)
|
||||
.map_err(unavailable)?
|
||||
.ok_or((404, "fee rate not found for market"))?;
|
||||
Ok(json!({"base_fee":fee}))
|
||||
}
|
||||
_ => {
|
||||
let tick = exchange
|
||||
.minimum_tick_size(token)
|
||||
.minimum_tick_size(&token)
|
||||
.map_err(unavailable)?
|
||||
.ok_or((404, "market not found"))?;
|
||||
Ok(json!({"minimum_tick_size":tick}))
|
||||
@@ -296,7 +231,7 @@ fn token_setting(
|
||||
}
|
||||
}
|
||||
|
||||
fn market_lookup(engine: &Mutex<Exchange>, ids: &WireIds, prefix: &str, raw: &str) -> Reply {
|
||||
fn market_lookup(engine: &Mutex<Exchange>, prefix: &str, raw: &str) -> Reply {
|
||||
let is_token = prefix == "markets-by-token";
|
||||
let invalid = if is_token {
|
||||
"Invalid token id"
|
||||
@@ -308,36 +243,15 @@ fn market_lookup(engine: &Mutex<Exchange>, ids: &WireIds, prefix: &str, raw: &st
|
||||
.map_err(|_| (400, invalid))?;
|
||||
let exchange = engine.lock().map_err(|_| (500, "Internal server error"))?;
|
||||
let info = if is_token {
|
||||
exchange.market_by_token(ids.local_asset(&id))
|
||||
exchange.market_by_token(&id)
|
||||
} else {
|
||||
exchange.clob_market_info(ids.local_market(&id))
|
||||
exchange.clob_market_info(&id)
|
||||
};
|
||||
let mut info = info
|
||||
.map_err(|e| match e {
|
||||
exchange::MarketDataError::Invalid(_) => (400, invalid),
|
||||
exchange::MarketDataError::Unavailable => (500, "Internal server error"),
|
||||
})?
|
||||
.ok_or((if is_token { 404 } else { 400 }, "market not found"))?;
|
||||
if is_token {
|
||||
map_id_field(&mut info, "condition_id", |market| {
|
||||
ids.wire_market(market).to_owned()
|
||||
});
|
||||
for field in ["primary_token_id", "secondary_token_id"] {
|
||||
map_id_field(&mut info, field, |asset| ids.wire_asset(asset).to_owned());
|
||||
}
|
||||
} else {
|
||||
let local = ids.local_market(&id);
|
||||
let condition = ids.wire_market(local);
|
||||
if condition != local {
|
||||
info["c"] = json!(condition);
|
||||
}
|
||||
if let Some(tokens) = info["t"].as_array_mut() {
|
||||
for token in tokens {
|
||||
map_id_field(token, "t", |asset| ids.wire_asset(asset).to_owned());
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(info)
|
||||
info.map_err(|e| match e {
|
||||
exchange::MarketDataError::Invalid(_) => (400, invalid),
|
||||
exchange::MarketDataError::Unavailable => (500, "Internal server error"),
|
||||
})?
|
||||
.ok_or((if is_token { 404 } else { 400 }, "market not found"))
|
||||
}
|
||||
|
||||
fn directory_route(path: &str) -> Option<(&str, bool, &str)> {
|
||||
@@ -352,12 +266,7 @@ fn directory_route(path: &str) -> Option<(&str, bool, &str)> {
|
||||
(!raw.is_empty() && !raw.contains('/')).then_some((resource, by_slug, raw))
|
||||
}
|
||||
|
||||
fn directory_lookup(
|
||||
engine: &Mutex<Exchange>,
|
||||
ids: &WireIds,
|
||||
route: (&str, bool, &str),
|
||||
params: &str,
|
||||
) -> Reply {
|
||||
fn directory_lookup(engine: &Mutex<Exchange>, route: (&str, bool, &str), params: &str) -> Reply {
|
||||
let (resource, by_slug, raw) = route;
|
||||
if !params.is_empty() {
|
||||
return Err((400, "Unsupported directory query"));
|
||||
@@ -383,54 +292,6 @@ fn directory_lookup(
|
||||
found
|
||||
.map_err(|_| (500, "Directory unavailable"))?
|
||||
.ok_or((404, "Not found"))
|
||||
.map(|mut row| {
|
||||
write_directory(&mut row, ids);
|
||||
row
|
||||
})
|
||||
}
|
||||
|
||||
fn write_directory(row: &mut Value, ids: &WireIds) {
|
||||
if let Some(market) = row["conditionId"].as_str() {
|
||||
let position = ids.is_position_market(market);
|
||||
let assets = row["clobTokenIds"]
|
||||
.as_str()
|
||||
.and_then(|raw| serde_json::from_str::<Vec<String>>(raw).ok());
|
||||
if let Some(migrated) = ids.migrated_assets(market) {
|
||||
row["version"] = json!("v1");
|
||||
row["clobTokenIds"] = json!(json!(migrated.ctf).to_string());
|
||||
row["positionIds"] = json!(migrated.positions);
|
||||
} else if let Some(assets) = assets {
|
||||
let mapped: Vec<_> = assets.iter().map(|asset| ids.wire_asset(asset)).collect();
|
||||
if position {
|
||||
row["version"] = json!("v2");
|
||||
if assets
|
||||
.iter()
|
||||
.zip(&mapped)
|
||||
.all(|(local, wire)| local.as_str() != *wire)
|
||||
{
|
||||
row["positionIds"] = json!(mapped);
|
||||
}
|
||||
row["clobTokenIds"] = Value::Null;
|
||||
} else if assets
|
||||
.iter()
|
||||
.zip(&mapped)
|
||||
.any(|(local, wire)| local.as_str() != *wire)
|
||||
{
|
||||
row["version"] = json!("v1");
|
||||
row["clobTokenIds"] = json!(json!(mapped).to_string());
|
||||
}
|
||||
}
|
||||
map_id_field(row, "conditionId", |market| {
|
||||
ids.wire_market(market).to_owned()
|
||||
});
|
||||
}
|
||||
for key in ["markets", "events"] {
|
||||
if let Some(children) = row.get_mut(key).and_then(Value::as_array_mut) {
|
||||
for child in children {
|
||||
write_directory(child, ids);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn clarifications(engine: &Mutex<Exchange>, query: &str) -> Reply {
|
||||
@@ -463,61 +324,29 @@ fn clarifications(engine: &Mutex<Exchange>, query: &str) -> Reply {
|
||||
Ok(Value::Array(rows))
|
||||
}
|
||||
|
||||
fn rebate_error(err: exchange::MarketDataError) -> (u16, &'static str) {
|
||||
match err {
|
||||
exchange::MarketDataError::Invalid(_) => (400, "Invalid maker rebate request"),
|
||||
exchange::MarketDataError::Unavailable => (503, "Maker rebates unavailable"),
|
||||
}
|
||||
}
|
||||
|
||||
fn maker_tiers(req: &mut Request, engine: &Mutex<Exchange>) -> Reply {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Batch {
|
||||
addresses: Vec<String>,
|
||||
}
|
||||
let batch: Batch = read_json(req)?;
|
||||
engine
|
||||
.lock()
|
||||
.map_err(|_| (503, "Maker rebates unavailable"))?
|
||||
.maker_tiers(batch.addresses)
|
||||
.map_err(rebate_error)
|
||||
}
|
||||
|
||||
fn maker_rebates(engine: &Mutex<Exchange>, ids: &WireIds, params: &str) -> Reply {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Query {
|
||||
date: String,
|
||||
maker_address: String,
|
||||
}
|
||||
let query: Query =
|
||||
serde_urlencoded::from_str(params).map_err(|_| (400, "Invalid maker rebate request"))?;
|
||||
let mut data = engine
|
||||
.lock()
|
||||
.map_err(|_| (503, "Maker rebates unavailable"))?
|
||||
.maker_rebates(&query.date, &query.maker_address)
|
||||
.map_err(rebate_error)?;
|
||||
if let Some(rows) = data.as_array_mut() {
|
||||
for row in rows {
|
||||
map_id_field(row, "condition_id", |market| {
|
||||
ids.wire_market(market).to_owned()
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(data)
|
||||
}
|
||||
|
||||
fn respond(mut req: Request, engine: &Mutex<Exchange>, ids: &WireIds) -> std::io::Result<()> {
|
||||
fn respond(
|
||||
mut req: Request,
|
||||
engine: &Mutex<Exchange>,
|
||||
snapshots: &snapshot_http::Starts,
|
||||
) -> std::io::Result<()> {
|
||||
let (path, params) = req.url().split_once('?').unwrap_or((req.url(), ""));
|
||||
let mut allow = None;
|
||||
if path == "/v2/positions/snapshot" {
|
||||
return snapshot_http::respond(req, engine, snapshots);
|
||||
}
|
||||
if req.method() == &Method::Get
|
||||
&& matches!(
|
||||
path,
|
||||
"/v2/prices-history" | "/v2/trades" | "/v2/resolutions" | "/v2/value" | "/v2/oi"
|
||||
"/v2/prices-history"
|
||||
| "/v2/trades"
|
||||
| "/v2/resolutions"
|
||||
| "/v2/value"
|
||||
| "/v2/oi"
|
||||
| "/v2/positions/combos"
|
||||
| "/v2/activity/combos"
|
||||
)
|
||||
{
|
||||
let (status, body) = data_page(path, params, engine, ids);
|
||||
let (status, body) = data_page(path, params, engine);
|
||||
return send(req, status, body, None);
|
||||
}
|
||||
let route = path.strip_prefix('/').unwrap_or(path);
|
||||
@@ -537,27 +366,14 @@ fn respond(mut req: Request, engine: &Mutex<Exchange>, ids: &WireIds) -> std::io
|
||||
if req.method() != &Method::Get {
|
||||
return send(req, 405, json!({"error":"Method not allowed"}), Some("GET"));
|
||||
}
|
||||
let (status, body) = match market_lookup(engine, ids, prefix, id) {
|
||||
let (status, body) = match market_lookup(engine, prefix, id) {
|
||||
Ok(value) => (200, value),
|
||||
Err((status, msg)) => (status, json!({"error":msg})),
|
||||
};
|
||||
return send(req, status, body, None);
|
||||
}
|
||||
let reply = match (req.method(), path) {
|
||||
(&Method::Post, "/v1/maker-tier/tiers") if params.is_empty() => {
|
||||
maker_tiers(&mut req, engine)
|
||||
}
|
||||
(&Method::Post, "/v1/maker-tier/tiers") => Err((400, "Invalid maker rebate request")),
|
||||
(&Method::Get, "/rebates/current") => maker_rebates(engine, ids, params),
|
||||
(_, "/v1/maker-tier/tiers" | "/rebates/current") => {
|
||||
allow = Some(if path == "/rebates/current" {
|
||||
"GET"
|
||||
} else {
|
||||
"POST"
|
||||
});
|
||||
Err((405, "Method not allowed"))
|
||||
}
|
||||
(&Method::Get, _) if is_setting => token_setting(name, engine, ids, params, segment),
|
||||
(&Method::Get, _) if is_setting => token_setting(name, engine, params, segment),
|
||||
(_, _) if is_setting => {
|
||||
allow = Some("GET");
|
||||
Err((405, "Method not allowed"))
|
||||
@@ -570,31 +386,14 @@ fn respond(mut req: Request, engine: &Mutex<Exchange>, ids: &WireIds) -> std::io
|
||||
};
|
||||
let result = serde_urlencoded::from_str::<Vec<(String, String)>>(params)
|
||||
.map_err(|_| exchange::MarketDataError::Invalid("Invalid directory query".into()))
|
||||
.and_then(|mut fields| {
|
||||
for (key, value) in &mut fields {
|
||||
match key.as_str() {
|
||||
"condition_ids" => *value = ids.local_market(value).to_owned(),
|
||||
"clob_token_ids" | "position_ids" if !value.trim().is_empty() => {
|
||||
*value = ids
|
||||
.directory_asset(value, key == "position_ids")
|
||||
.unwrap_or("unmapped-asset")
|
||||
.to_owned();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
.and_then(|fields| {
|
||||
engine
|
||||
.lock()
|
||||
.map_err(|_| exchange::MarketDataError::Unavailable)?
|
||||
.gamma_list(resource, &fields)
|
||||
});
|
||||
match result {
|
||||
Ok(mut page) => {
|
||||
for row in &mut page {
|
||||
write_directory(row, ids);
|
||||
}
|
||||
Ok(Value::Array(page))
|
||||
}
|
||||
Ok(page) => Ok(Value::Array(page)),
|
||||
Err(exchange::MarketDataError::Invalid(message)) => {
|
||||
return send(req, 422, json!({"error":message}), None)
|
||||
}
|
||||
@@ -603,7 +402,8 @@ fn respond(mut req: Request, engine: &Mutex<Exchange>, ids: &WireIds) -> std::io
|
||||
}
|
||||
(&Method::Get, "/market-clarifications") => clarifications(engine, params),
|
||||
(&Method::Get, "/prices-history") => {
|
||||
let result = map_query_asset::<exchange::ClobHistoryQuery>(params, ids, &["market"])
|
||||
let result = serde_urlencoded::from_str::<exchange::ClobHistoryQuery>(params)
|
||||
.map_err(|_| HistoryError::Invalid("invalid query parameters".into()))
|
||||
.and_then(|query| {
|
||||
engine
|
||||
.lock()
|
||||
@@ -620,9 +420,10 @@ fn respond(mut req: Request, engine: &Mutex<Exchange>, ids: &WireIds) -> std::io
|
||||
}
|
||||
(&Method::Get, "/price") => serde_urlencoded::from_str::<WirePrice>(params)
|
||||
.map_err(|_| (400, "Invalid token id"))
|
||||
.and_then(|p| book_prices(engine, ids, vec![p], true)),
|
||||
(&Method::Post, "/prices") => read_json::<Vec<WirePrice>>(&mut req)
|
||||
.and_then(|rows| book_prices(engine, ids, rows, false)),
|
||||
.and_then(|p| book_prices(engine, vec![p], true)),
|
||||
(&Method::Post, "/prices") => {
|
||||
batch_params::<WirePrice>(&mut req).and_then(|rows| book_prices(engine, rows, false))
|
||||
}
|
||||
(&Method::Get, "/prices") => Err((400, "Invalid payload")),
|
||||
(&Method::Get, "/spread" | "/midpoint") => {
|
||||
let field = if path == "/spread" {
|
||||
@@ -632,7 +433,7 @@ fn respond(mut req: Request, engine: &Mutex<Exchange>, ids: &WireIds) -> std::io
|
||||
};
|
||||
serde_urlencoded::from_str::<BookParam>(params)
|
||||
.map_err(|_| (400, "Invalid token id"))
|
||||
.and_then(|p| quote_response(engine, ids, vec![p.token_id], field, true))
|
||||
.and_then(|p| quote_response(engine, vec![p.token_id], field, true))
|
||||
}
|
||||
(&Method::Post, "/spreads" | "/midpoints") => {
|
||||
let field = if path == "/spreads" {
|
||||
@@ -640,10 +441,9 @@ fn respond(mut req: Request, engine: &Mutex<Exchange>, ids: &WireIds) -> std::io
|
||||
} else {
|
||||
QuoteField::Midpoint
|
||||
};
|
||||
read_json::<Vec<BookParam>>(&mut req).and_then(|p| {
|
||||
batch_params::<BookParam>(&mut req).and_then(|p| {
|
||||
quote_response(
|
||||
engine,
|
||||
ids,
|
||||
p.into_iter().map(|b| b.token_id).collect(),
|
||||
field,
|
||||
false,
|
||||
@@ -653,19 +453,18 @@ fn respond(mut req: Request, engine: &Mutex<Exchange>, ids: &WireIds) -> std::io
|
||||
(&Method::Get, "/midpoints") => Err((400, "Invalid payload")),
|
||||
(&Method::Get, "/book") => serde_urlencoded::from_str::<BookParam>(params)
|
||||
.map_err(|_| (400, "Invalid token id"))
|
||||
.and_then(|p| query(engine, ids, vec![p], true)),
|
||||
.and_then(|p| query(engine, vec![p], true)),
|
||||
(&Method::Post, "/books") => {
|
||||
read_json::<Vec<BookParam>>(&mut req).and_then(|p| query(engine, ids, p, false))
|
||||
batch_params::<BookParam>(&mut req).and_then(|p| query(engine, p, false))
|
||||
}
|
||||
(&Method::Get, "/last-trade-price") => serde_urlencoded::from_str::<BookParam>(params)
|
||||
.map_err(|_| (400, "Invalid token id"))
|
||||
.and_then(|p| last_prices(engine, ids, vec![p.token_id], true)),
|
||||
.and_then(|p| last_prices(engine, vec![p.token_id], true)),
|
||||
(&Method::Get, "/last-trades-prices") => Err((400, "Invalid payload")),
|
||||
(&Method::Post, "/last-trades-prices") => {
|
||||
read_json::<Vec<BookParam>>(&mut req).and_then(|p| {
|
||||
batch_params::<BookParam>(&mut req).and_then(|p| {
|
||||
last_prices(
|
||||
engine,
|
||||
ids,
|
||||
p.into_iter().map(|item| item.token_id).collect(),
|
||||
false,
|
||||
)
|
||||
@@ -690,6 +489,8 @@ fn respond(mut req: Request, engine: &Mutex<Exchange>, ids: &WireIds) -> std::io
|
||||
| "/v2/value"
|
||||
| "/v2/trades"
|
||||
| "/v2/resolutions"
|
||||
| "/v2/positions/combos"
|
||||
| "/v2/activity/combos"
|
||||
| "/v2/prices-history",
|
||||
) => {
|
||||
allow = Some("GET");
|
||||
@@ -700,9 +501,7 @@ fn respond(mut req: Request, engine: &Mutex<Exchange>, ids: &WireIds) -> std::io
|
||||
Err((405, "Method not allowed"))
|
||||
}
|
||||
_ => match directory_route(path) {
|
||||
Some(route) if req.method() == &Method::Get => {
|
||||
directory_lookup(engine, ids, route, params)
|
||||
}
|
||||
Some(route) if req.method() == &Method::Get => directory_lookup(engine, route, params),
|
||||
Some(_) => {
|
||||
allow = Some("GET");
|
||||
Err((405, "Method not allowed"))
|
||||
@@ -717,77 +516,29 @@ fn respond(mut req: Request, engine: &Mutex<Exchange>, ids: &WireIds) -> std::io
|
||||
send(req, status, body, allow)
|
||||
}
|
||||
|
||||
fn read_condition_page<Q: serde::de::DeserializeOwned>(
|
||||
fn read_page<Q: serde::de::DeserializeOwned>(
|
||||
params: &str,
|
||||
engine: &Mutex<Exchange>,
|
||||
ids: &WireIds,
|
||||
condition: fn(&mut Q) -> &mut Option<ConditionList>,
|
||||
read: fn(&Exchange, Q) -> Result<Value, HistoryError>,
|
||||
) -> Result<(Value, bool), HistoryError> {
|
||||
let mut query = serde_urlencoded::from_str(params)
|
||||
) -> Result<Value, HistoryError> {
|
||||
let query = serde_urlencoded::from_str(params)
|
||||
.map_err(|_| HistoryError::Invalid("invalid query parameters".into()))?;
|
||||
let selector = condition(&mut query);
|
||||
let has_condition = selector.is_some();
|
||||
if let Some(selector) = selector {
|
||||
selector.resolve(|wire| ids.market_for_condition(wire).map(str::to_owned));
|
||||
}
|
||||
let exchange = engine.lock().map_err(|_| HistoryError::Unavailable)?;
|
||||
Ok((read(&exchange, query)?, has_condition))
|
||||
read(&exchange, query)
|
||||
}
|
||||
|
||||
fn data_page(path: &str, params: &str, engine: &Mutex<Exchange>, ids: &WireIds) -> (u16, Value) {
|
||||
fn data_page(path: &str, params: &str, engine: &Mutex<Exchange>) -> (u16, Value) {
|
||||
let page = match path {
|
||||
"/v2/oi" => read_condition_page(
|
||||
params,
|
||||
engine,
|
||||
ids,
|
||||
|q| &mut q.condition,
|
||||
Exchange::public_open_interest,
|
||||
),
|
||||
"/v2/value" => read_condition_page(
|
||||
params,
|
||||
engine,
|
||||
ids,
|
||||
|q| &mut q.condition,
|
||||
Exchange::public_portfolio_value,
|
||||
),
|
||||
"/v2/trades" => read_condition_page(
|
||||
params,
|
||||
engine,
|
||||
ids,
|
||||
|q| &mut q.condition,
|
||||
Exchange::public_trade_feed,
|
||||
),
|
||||
"/v2/resolutions" => read_condition_page(
|
||||
params,
|
||||
engine,
|
||||
ids,
|
||||
|q| &mut q.condition,
|
||||
Exchange::public_resolutions,
|
||||
),
|
||||
_ => map_query_asset(params, ids, &["tokenId", "token_id"]).and_then(|query| {
|
||||
engine
|
||||
.lock()
|
||||
.map_err(|_| HistoryError::Unavailable)?
|
||||
.public_price_history(query)
|
||||
.map(|page| (page, false))
|
||||
}),
|
||||
"/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),
|
||||
};
|
||||
match page {
|
||||
Ok((mut page, has_condition)) => {
|
||||
// The unfiltered interest row is a global aggregate.
|
||||
match (path, has_condition, page.get_mut("data")) {
|
||||
("/v2/oi", false, _) => {}
|
||||
(_, _, Some(Value::Array(rows))) => {
|
||||
for row in rows {
|
||||
map_id_field(row, "condition_id", |id| ids.wire_market(id).to_owned());
|
||||
map_id_field(row, "token_id", |id| ids.wire_asset(id).to_owned());
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
(200, page)
|
||||
}
|
||||
Ok(data) => (200, data),
|
||||
Err(HistoryError::Invalid(message)) => (
|
||||
400,
|
||||
json!({"code":"invalid_request","error":message,"retryable":false}),
|
||||
@@ -804,6 +555,14 @@ fn data_page(path: &str, params: &str, engine: &Mutex<Exchange>, ids: &WireIds)
|
||||
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}),
|
||||
@@ -828,14 +587,15 @@ fn send(req: Request, status: u16, body: Value, allow: Option<&str>) -> std::io:
|
||||
req.respond(response)
|
||||
}
|
||||
|
||||
pub(crate) fn serve(engine: Exchange, listener: TcpListener, ids: WireIds) -> Result<()> {
|
||||
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, &ids) {
|
||||
if let Err(err) = respond(req, &engine, &snapshots) {
|
||||
eprintln!("market HTTP response: {err}");
|
||||
}
|
||||
}
|
||||
@@ -850,110 +610,6 @@ mod tests {
|
||||
use super::*;
|
||||
use std::{io::Write, net::TcpStream, time::Duration};
|
||||
|
||||
#[test]
|
||||
fn analytics_filters_accept_directory_ids_and_return_the_same_public_ids() {
|
||||
let mut db = Exchange::open(":memory:").unwrap();
|
||||
for line in include_str!("../../../docs/examples/market-stream-trades.jsonl").lines() {
|
||||
db.execute(serde_json::from_str(&line.replace("demo", "mapped,market")).unwrap())
|
||||
.unwrap();
|
||||
}
|
||||
for command in [
|
||||
json!({"op":"close","id":"close","market":"mapped,market"}),
|
||||
json!({"op":"finalize","id":"final","market":"mapped,market","winner":"YES"}),
|
||||
json!({"op":"list","id":"global-list","market":"GLOBAL","rules":"global fixture"}),
|
||||
] {
|
||||
db.execute(command).unwrap();
|
||||
}
|
||||
let condition = format!("0x{}", "ab".repeat(32));
|
||||
let upper = format!("0x{}", "AB".repeat(32));
|
||||
let global = format!("0x{}", "ef".repeat(32));
|
||||
let absent = format!("0x{}", "cd".repeat(32));
|
||||
let mut ids = WireIds::default();
|
||||
ids.bind_market("mapped,market", [0xab; 32]).unwrap();
|
||||
ids.bind_market("GLOBAL", [0xef; 32]).unwrap();
|
||||
ids.bind_asset(
|
||||
"eb:YES:mapped,market",
|
||||
crate::wire_ids::token_word("1001").unwrap(),
|
||||
"1001",
|
||||
)
|
||||
.unwrap();
|
||||
let engine = Mutex::new(db);
|
||||
let page = |path: &str, query: &str| {
|
||||
let (status, body) = data_page(path, query, &engine, &ids);
|
||||
assert_eq!(status, 200, "{path}: {body}");
|
||||
body
|
||||
};
|
||||
|
||||
let oi = page(
|
||||
"/v2/oi",
|
||||
&format!("conditionId={upper}%2C{absent}%2C{condition}"),
|
||||
);
|
||||
assert_eq!(oi, json!({"data":[{"condition_id":condition,"value":5}]}));
|
||||
assert_eq!(page("/v2/oi", "")["data"][0]["condition_id"], "GLOBAL");
|
||||
assert_eq!(
|
||||
page("/v2/oi", &format!("condition={global}"))["data"][0]["condition_id"],
|
||||
global
|
||||
);
|
||||
assert_eq!(
|
||||
page("/v2/value", &format!("user=taker&condition_id={condition}")),
|
||||
json!({"data":{"proxy_wallet":"taker","value":3}})
|
||||
);
|
||||
let resolution = page(
|
||||
"/v2/resolutions",
|
||||
&format!("condition={condition},{absent}"),
|
||||
);
|
||||
assert_eq!(resolution["data"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(resolution["data"][0]["condition_id"], condition);
|
||||
assert_eq!(resolution["data"][0]["payouts"], json!([1_000_000, 0]));
|
||||
|
||||
let top = page(
|
||||
"/v2/trades",
|
||||
&format!("user=taker&condition={condition}&limit=1"),
|
||||
);
|
||||
let cursor = top["pagination"]["next_cursor"].as_str().unwrap();
|
||||
let next = page(
|
||||
"/v2/trades",
|
||||
&format!("user=taker&conditionId={upper}&cursor={cursor}"),
|
||||
);
|
||||
for page in [top, next] {
|
||||
assert_eq!(page["data"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(page["data"][0]["condition_id"], condition);
|
||||
assert_eq!(page["data"][0]["token_id"], "1001");
|
||||
}
|
||||
|
||||
let (status, body) = data_page(
|
||||
"/v2/oi",
|
||||
&format!("condition={condition},invalid-id"),
|
||||
&engine,
|
||||
&ids,
|
||||
);
|
||||
assert_eq!(status, 400);
|
||||
assert_eq!(body["error"], "invalid condition: invalid-id");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn position_exchange_directory_keeps_token_families_distinct() {
|
||||
let mut ids = WireIds::default();
|
||||
ids.mark_position_market("position");
|
||||
ids.bind_market("position", [0x22; 32]).unwrap();
|
||||
for (asset, token) in [("eb:YES:position", "256"), ("eb:NO:position", "257")] {
|
||||
ids.bind_asset(asset, crate::wire_ids::token_word(token).unwrap(), token)
|
||||
.unwrap();
|
||||
}
|
||||
let mut event = json!({"id":"5","markets":[{"id":"9","conditionId":"position",
|
||||
"clobTokenIds":r#"["eb:YES:position","eb:NO:position"]"#}]});
|
||||
write_directory(&mut event, &ids);
|
||||
assert_eq!(event["id"], "5");
|
||||
assert_eq!(event["markets"][0]["id"], "9");
|
||||
assert_eq!(
|
||||
event["markets"][0]["conditionId"],
|
||||
format!("0x{}", "22".repeat(32))
|
||||
);
|
||||
assert_eq!(event["markets"][0]["positionIds"], json!(["256", "257"]));
|
||||
assert!(event["markets"][0]["clobTokenIds"].is_null());
|
||||
assert_eq!(event["markets"][0]["version"], "v2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn socket_serves_single_and_batch_books_and_rejects_invalid_requests() {
|
||||
let mut db = Exchange::open(":memory:").unwrap();
|
||||
@@ -1062,78 +718,12 @@ mod tests {
|
||||
assert_eq!(quoted["bestAsk"], json!(0.41));
|
||||
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}});
|
||||
db.execute(json!({"op":"list","id":"mapped-list","market":"mapped","rules":"ID fixture"}))
|
||||
.unwrap();
|
||||
let mut ids = WireIds::default();
|
||||
ids.bind_market("mapped", [0x11; 32]).unwrap();
|
||||
for (asset, token) in [("eb:YES:mapped", "1001"), ("eb:NO:mapped", "1002")] {
|
||||
ids.bind_asset(asset, crate::wire_ids::token_word(token).unwrap(), token)
|
||||
.unwrap();
|
||||
}
|
||||
let condition = format!("0x{}", "11".repeat(32));
|
||||
let mapped_directory = db
|
||||
.gamma_market(exchange::DirectoryKey::Slug("mapped"))
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let mut mapped_directory = mapped_directory;
|
||||
mapped_directory["conditionId"] = json!(condition);
|
||||
mapped_directory["version"] = json!("v1");
|
||||
mapped_directory["clobTokenIds"] = json!(r#"["1001","1002"]"#);
|
||||
let mapped_query = format!("/markets?condition_ids={condition}&clob_token_ids=1002");
|
||||
let mapped_clob = format!("/clob-markets/{condition}");
|
||||
let local_mapped_book = db
|
||||
.execute(json!({"op":"clob_book","token_id":"eb:YES:mapped"}))
|
||||
.unwrap();
|
||||
let local_hash = local_mapped_book["hash"].clone();
|
||||
let mapped_book =
|
||||
exchange::relabel_book_snapshot(local_mapped_book, Some(&condition), Some("1001"))
|
||||
.unwrap();
|
||||
assert_ne!(mapped_book["hash"], local_hash);
|
||||
let mut mapped_clob_info = db.clob_market_info("mapped").unwrap().unwrap();
|
||||
mapped_clob_info["c"] = json!(condition);
|
||||
mapped_clob_info["t"][0]["t"] = json!("1001");
|
||||
mapped_clob_info["t"][1]["t"] = json!("1002");
|
||||
for (asset, token) in [("eb:YES:hybrid", "2001"), ("eb:NO:hybrid", "2002")] {
|
||||
ids.bind_asset(asset, crate::wire_ids::token_word(token).unwrap(), token)
|
||||
.unwrap();
|
||||
}
|
||||
db.execute(json!({"op":"list","id":"hybrid-list","market":"hybrid","rules":"ID fixture"}))
|
||||
.unwrap();
|
||||
db.execute(json!({"op":"close","id":"hybrid-close","market":"hybrid"}))
|
||||
.unwrap();
|
||||
ids.bind_migrated_market(
|
||||
"hybrid",
|
||||
[0x33; 32],
|
||||
&["2001".into(), "2002".into()],
|
||||
&["512".into(), "513".into()],
|
||||
)
|
||||
.unwrap();
|
||||
let mut hybrid = db
|
||||
.gamma_market(exchange::DirectoryKey::Slug("hybrid"))
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
hybrid["conditionId"] = json!(format!("0x{}", "33".repeat(32)));
|
||||
hybrid["clobTokenIds"] = json!(r#"["2001","2002"]"#);
|
||||
hybrid["positionIds"] = json!(["512", "513"]);
|
||||
hybrid["version"] = json!("v1");
|
||||
let cases = [
|
||||
("GET","/markets?position_ids=9999&position_ids=0513&closed=any",String::new(),200,Some(json!([hybrid.clone()]))),
|
||||
("GET","/markets?clob_token_ids=2002&position_ids=512&closed=true",String::new(),200,Some(json!([hybrid.clone()]))),
|
||||
("GET","/markets/slug/hybrid",String::new(),200,Some(hybrid)),
|
||||
("GET","/markets?clob_token_ids=1002&position_ids=512&closed=any",String::new(),200,Some(json!([]))),
|
||||
("GET","/markets?position_ids=2002&closed=any",String::new(),200,Some(json!([]))),
|
||||
("GET","/markets?clob_token_ids=512&closed=any",String::new(),200,Some(json!([]))),
|
||||
("GET","/markets?position_ids=513",String::new(),200,Some(json!([]))),
|
||||
("GET","/markets?position_ids=&closed=any",String::new(),422,None),
|
||||
("GET","/book?token_id=0x3e9",String::new(),200,Some(mapped_book.clone())),
|
||||
("POST","/books",r#"[{"token_id":"1001"}]"#.into(),200,Some(json!([mapped_book]))),
|
||||
("GET",mapped_query.as_str(),String::new(),200,Some(json!([mapped_directory.clone()]))),
|
||||
("GET","/markets/slug/mapped",String::new(),200,Some(mapped_directory)),
|
||||
("GET","/markets-by-token/1002",String::new(),200,Some(json!({"condition_id":condition,"primary_token_id":"1001","secondary_token_id":"1002"}))),
|
||||
("GET",mapped_clob.as_str(),String::new(),200,Some(mapped_clob_info)),
|
||||
("GET","/prices-history?market=1001&interval=1h",String::new(),200,Some(json!({"history":[]}))),
|
||||
("GET","/v2/prices-history?tokenId=1001&interval=1h&bucketSeconds=60",String::new(),200,None),
|
||||
("GET","/tick-size/1001",String::new(),200,Some(json!({"minimum_tick_size":0.01}))),
|
||||
("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}))),
|
||||
@@ -1303,6 +893,8 @@ mod tests {
|
||||
Some(json!({"data":[],"pagination":{"has_more":false,"next_cursor":null,"offset":0,"limit":10000}}))),
|
||||
("GET","/v2/prices-history?token_id=7&interval=1h",String::new(),400,None),
|
||||
("POST","/v2/prices-history",String::new(),405,None),
|
||||
("GET","/v2/positions/snapshot",String::new(),406,None),
|
||||
("POST","/v2/positions/snapshot",String::new(),405,None),
|
||||
("GET", "/books", String::new(), 405, None),
|
||||
("POST", "/order", "{}".into(), 404, None),
|
||||
];
|
||||
@@ -1314,7 +906,7 @@ mod tests {
|
||||
.recv_timeout(Duration::from_secs(5))
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
respond(req, &db, &ids).unwrap();
|
||||
respond(req, &db, &snapshot_http::Starts::default()).unwrap();
|
||||
}
|
||||
});
|
||||
for (method, path, body, status, expected) in cases {
|
||||
|
||||
+28
-200
@@ -1,7 +1,6 @@
|
||||
use crate::{subscriptions::Session, user_ws, wire_ids::WireIds};
|
||||
use crate::subscriptions::Session;
|
||||
use anyhow::{Context, Result};
|
||||
use exchange::Exchange;
|
||||
use serde_json::Value;
|
||||
use std::{
|
||||
io::ErrorKind,
|
||||
net::{TcpListener, TcpStream},
|
||||
@@ -18,15 +17,8 @@ use tungstenite::{
|
||||
|
||||
const POLL: Duration = Duration::from_millis(100);
|
||||
|
||||
pub(crate) fn serve(
|
||||
engine: Exchange,
|
||||
listener: TcpListener,
|
||||
credentials: Option<user_ws::Credentials>,
|
||||
ids: WireIds,
|
||||
) -> Result<()> {
|
||||
pub(crate) fn serve(engine: Exchange, listener: TcpListener) -> Result<()> {
|
||||
let engine = Arc::new(Mutex::new(engine));
|
||||
let credentials = credentials.map(Arc::new);
|
||||
let ids = Arc::new(ids);
|
||||
for stream in listener.incoming() {
|
||||
let stream = stream?;
|
||||
// Each accepted session owns exactly one engine reference and one OS thread.
|
||||
@@ -34,13 +26,11 @@ pub(crate) fn serve(
|
||||
continue;
|
||||
}
|
||||
let engine = Arc::clone(&engine);
|
||||
let credentials = credentials.clone();
|
||||
let ids = Arc::clone(&ids);
|
||||
thread::Builder::new()
|
||||
.name("market-ws".into())
|
||||
.spawn(move || {
|
||||
if let Err(err) = connection(stream, &engine, credentials.as_deref(), &ids) {
|
||||
eprintln!("WebSocket: {err}");
|
||||
if let Err(err) = connection(stream, &engine) {
|
||||
eprintln!("market WebSocket: {err}");
|
||||
}
|
||||
})?;
|
||||
}
|
||||
@@ -52,47 +42,16 @@ fn send(socket: &mut WebSocket<TcpStream>, frame: serde_json::Value) -> Result<(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn public_frame(ids: &WireIds, mut frame: Value) -> Result<Value> {
|
||||
if frame["event_type"] == "book" {
|
||||
return ids.book(frame);
|
||||
}
|
||||
ids.write_record(&mut frame);
|
||||
if let Some(changes) = frame.get_mut("price_changes").and_then(Value::as_array_mut) {
|
||||
for change in changes {
|
||||
ids.write_record(change);
|
||||
}
|
||||
}
|
||||
if let Some(assets) = frame.get_mut("assets_ids").and_then(Value::as_array_mut) {
|
||||
for asset in assets {
|
||||
ids.write_asset(asset);
|
||||
}
|
||||
}
|
||||
if let Some(winner) = frame.get_mut("winning_asset_id") {
|
||||
ids.write_asset(winner);
|
||||
}
|
||||
Ok(frame)
|
||||
}
|
||||
|
||||
pub(crate) fn connection(
|
||||
stream: TcpStream,
|
||||
engine: &Mutex<Exchange>,
|
||||
credentials: Option<&user_ws::Credentials>,
|
||||
ids: &WireIds,
|
||||
) -> Result<()> {
|
||||
pub(crate) fn connection(stream: TcpStream, engine: &Mutex<Exchange>) -> Result<()> {
|
||||
stream.set_read_timeout(Some(Duration::from_secs(5)))?;
|
||||
stream.set_write_timeout(Some(Duration::from_secs(5)))?;
|
||||
let config = WebSocketConfig::default()
|
||||
.max_message_size(Some(65536))
|
||||
.max_frame_size(Some(65536));
|
||||
let path = if credentials.is_some() {
|
||||
"/ws/user"
|
||||
} else {
|
||||
"/ws/market"
|
||||
};
|
||||
let mut socket = accept_hdr_with_config(
|
||||
stream,
|
||||
|req: &Request, resp: Response| {
|
||||
if req.uri().path() == path {
|
||||
if req.uri().path() == "/ws/market" {
|
||||
Ok(resp)
|
||||
} else {
|
||||
let mut err = ErrorResponse::new(Some("unknown WebSocket path".into()));
|
||||
@@ -102,111 +61,45 @@ pub(crate) fn connection(
|
||||
},
|
||||
Some(config),
|
||||
)
|
||||
.map_err(|_| anyhow::anyhow!("WebSocket handshake failed"))?;
|
||||
.map_err(|e| anyhow::anyhow!("market WebSocket handshake: {e}"))?;
|
||||
socket.get_mut().set_read_timeout(Some(POLL))?;
|
||||
let mut session = Session::default();
|
||||
let mut user: Option<user_ws::Session> = None;
|
||||
let auth_deadline = Instant::now() + Duration::from_secs(5);
|
||||
let mut next = Instant::now();
|
||||
loop {
|
||||
if credentials.is_some() && user.is_none() && Instant::now() >= auth_deadline {
|
||||
socket.close(None)?;
|
||||
break;
|
||||
}
|
||||
match (socket.read(), credentials) {
|
||||
(Ok(Message::Text(s)), _) if s.as_str() == "PING" => {
|
||||
socket.send(Message::text("PONG"))?
|
||||
}
|
||||
(Ok(Message::Text(s)), Some(credentials)) => {
|
||||
if let Some(user) = user.as_mut() {
|
||||
let reply = {
|
||||
let mut engine = engine
|
||||
.lock()
|
||||
.map_err(|_| anyhow::anyhow!("exchange unavailable"))?;
|
||||
if !user.active(&engine)? {
|
||||
drop(engine);
|
||||
socket.close(None)?;
|
||||
break;
|
||||
}
|
||||
user.control(&mut engine, s.as_str())
|
||||
};
|
||||
match reply {
|
||||
Ok(Some(frame)) => send(&mut socket, frame)?,
|
||||
Ok(None) => {}
|
||||
Err(_) => socket.send(Message::text("INVALID OPERATION"))?,
|
||||
}
|
||||
} else {
|
||||
let init = {
|
||||
let engine = engine
|
||||
.lock()
|
||||
.map_err(|_| anyhow::anyhow!("exchange unavailable"))?;
|
||||
user_ws::Session::start(&engine, credentials, s.as_str())
|
||||
};
|
||||
match init {
|
||||
Ok(initialized) => user = Some(initialized),
|
||||
Err(_) => {
|
||||
socket.send(Message::text("INVALID SUBSCRIPTION"))?;
|
||||
socket.close(None)?;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
(Ok(Message::Text(s)), None) => {
|
||||
match socket.read() {
|
||||
Ok(Message::Text(s)) if s.as_str() == "PING" => socket.send(Message::text("PONG"))?,
|
||||
Ok(Message::Text(s)) => {
|
||||
let reply = {
|
||||
let mut engine = engine
|
||||
.lock()
|
||||
.map_err(|_| anyhow::anyhow!("exchange unavailable"))?;
|
||||
session.control(&mut engine, ids, s.as_str())
|
||||
session.control(&mut engine, s.as_str())
|
||||
};
|
||||
match reply {
|
||||
Ok(snapshots) if !snapshots.is_empty() => {
|
||||
let frames = snapshots
|
||||
.into_iter()
|
||||
.map(|frame| ids.book(frame))
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
send(&mut socket, Value::Array(frames))?;
|
||||
}
|
||||
Ok(snapshots) if !snapshots.is_empty() => send(&mut socket, snapshots.into())?,
|
||||
Ok(_) => {}
|
||||
Err(_) => socket.send(Message::text("INVALID OPERATION"))?,
|
||||
}
|
||||
}
|
||||
(Ok(Message::Close(_)), _) => {
|
||||
Ok(Message::Close(_)) => {
|
||||
let _ = socket.flush();
|
||||
break;
|
||||
}
|
||||
(Ok(Message::Ping(_)), _) => socket.flush()?,
|
||||
(Ok(_), _) => {}
|
||||
(Err(Error::Io(err)), _)
|
||||
Ok(Message::Ping(_)) => socket.flush()?,
|
||||
Ok(_) => {}
|
||||
Err(Error::Io(err))
|
||||
if matches!(err.kind(), ErrorKind::TimedOut | ErrorKind::WouldBlock) => {}
|
||||
(Err(Error::ConnectionClosed | Error::AlreadyClosed), _) => break,
|
||||
(Err(err), _) => return Err(err).context("read WebSocket"),
|
||||
Err(Error::ConnectionClosed | Error::AlreadyClosed) => break,
|
||||
Err(err) => return Err(err).context("read market WebSocket"),
|
||||
}
|
||||
if Instant::now() >= next {
|
||||
let frames = if credentials.is_some() && user.is_none() {
|
||||
Vec::new()
|
||||
} else {
|
||||
let frames = {
|
||||
let mut engine = engine
|
||||
.lock()
|
||||
.map_err(|_| anyhow::anyhow!("exchange unavailable"))?;
|
||||
match user.as_mut() {
|
||||
Some(user) => {
|
||||
if !user.active(&engine)? {
|
||||
drop(engine);
|
||||
socket.close(None)?;
|
||||
break;
|
||||
}
|
||||
user.poll(&mut engine)?
|
||||
}
|
||||
None => session.poll(&mut engine)?,
|
||||
}
|
||||
session.poll(&mut engine)?
|
||||
};
|
||||
for frame in frames {
|
||||
let frame = if credentials.is_none() {
|
||||
public_frame(ids, frame)?
|
||||
} else {
|
||||
frame
|
||||
};
|
||||
send(&mut socket, frame)?;
|
||||
}
|
||||
next = Instant::now() + POLL;
|
||||
@@ -218,52 +111,10 @@ pub(crate) fn connection(
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn mapped_ids() -> WireIds {
|
||||
let mut ids = WireIds::default();
|
||||
ids.bind_market("demo", [0x11; 32]).unwrap();
|
||||
for (local, token) in [("eb:YES:demo", "1001"), ("eb:NO:demo", "1002")] {
|
||||
ids.bind_asset(local, crate::wire_ids::token_word(token).unwrap(), token)
|
||||
.unwrap();
|
||||
}
|
||||
ids
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lifecycle_frames_map_both_outcomes_and_only_a_nonnull_winner() {
|
||||
let ids = mapped_ids();
|
||||
for (event_type, winner) in [
|
||||
("new_market", None),
|
||||
("market_resolved", Some(json!("eb:NO:demo"))),
|
||||
("market_resolved", Some(Value::Null)),
|
||||
] {
|
||||
let mut frame = json!({"event_type":event_type,"id":"7","market":"demo",
|
||||
"assets_ids":["eb:YES:demo","eb:NO:demo"]});
|
||||
if let Some(winner) = winner.as_ref() {
|
||||
frame["winning_asset_id"] = winner.clone();
|
||||
}
|
||||
let projected = public_frame(&ids, frame).unwrap();
|
||||
assert_eq!(projected["market"], format!("0x{}", "11".repeat(32)));
|
||||
assert_eq!(projected["id"], "7");
|
||||
assert_eq!(projected["assets_ids"], json!(["1001", "1002"]));
|
||||
match winner {
|
||||
Some(Value::String(_)) => assert_eq!(projected["winning_asset_id"], "1002"),
|
||||
Some(Value::Null) => {
|
||||
assert_eq!(projected.get("winning_asset_id"), Some(&Value::Null))
|
||||
}
|
||||
_ => assert!(projected.get("winning_asset_id").is_none()),
|
||||
}
|
||||
}
|
||||
}
|
||||
use serde_json::{json, Value};
|
||||
|
||||
#[test]
|
||||
fn market_socket_sends_snapshots_deltas_and_application_pongs() {
|
||||
verify_market_socket(false);
|
||||
verify_market_socket(true);
|
||||
}
|
||||
|
||||
fn verify_market_socket(mapped: bool) {
|
||||
let mut engine = Exchange::open(":memory:").unwrap();
|
||||
for cmd in [
|
||||
json!({"op":"list","id":"list","market":"demo","rules":"r","tick_size":"0.01"}),
|
||||
@@ -272,47 +123,27 @@ mod tests {
|
||||
] {
|
||||
engine.execute(cmd).unwrap();
|
||||
}
|
||||
let ids = if mapped {
|
||||
mapped_ids()
|
||||
} else {
|
||||
WireIds::default()
|
||||
};
|
||||
let asset = ids.wire_asset("eb:NO:demo").to_owned();
|
||||
let market = ids.wire_market("demo").to_owned();
|
||||
let local = engine
|
||||
.execute(json!({"op":"clob_book","token_id":"eb:NO:demo"}))
|
||||
.unwrap();
|
||||
let http_book = ids.book(local).unwrap();
|
||||
let engine = Arc::new(Mutex::new(engine));
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let db = Arc::clone(&engine);
|
||||
let worker =
|
||||
thread::spawn(move || connection(listener.accept().unwrap().0, &db, None, &ids));
|
||||
let worker = thread::spawn(move || connection(listener.accept().unwrap().0, &db));
|
||||
let tcp = TcpStream::connect(addr).unwrap();
|
||||
tcp.set_read_timeout(Some(Duration::from_secs(3))).unwrap();
|
||||
let (mut client, _) = tungstenite::client(format!("ws://{addr}/ws/market"), tcp).unwrap();
|
||||
let mut controls: Vec<_> = include_str!("../../../docs/examples/market-ws.txt")
|
||||
let controls: Vec<&str> = include_str!("../../../docs/examples/market-ws.txt")
|
||||
.lines()
|
||||
.map(str::to_owned)
|
||||
.collect();
|
||||
if mapped {
|
||||
controls[0] = controls[0].replace("eb:YES:demo", "0x3e9");
|
||||
controls[1] = controls[1].replace("eb:NO:demo", "1002");
|
||||
controls[2] = controls[2].replace("eb:YES:demo", "1001");
|
||||
}
|
||||
client.send(Message::text(controls[0].as_str())).unwrap();
|
||||
client.send(Message::text(controls[0])).unwrap();
|
||||
client.send(Message::text("PING")).unwrap();
|
||||
assert_eq!(client.read().unwrap().into_text().unwrap(), "PONG"); // initial_dump=false
|
||||
client.send(Message::text(controls[1].as_str())).unwrap();
|
||||
client.send(Message::text(controls[1])).unwrap();
|
||||
let frames: Value =
|
||||
serde_json::from_str(client.read().unwrap().to_text().unwrap()).unwrap();
|
||||
assert_eq!(frames.as_array().unwrap().len(), 1);
|
||||
assert_eq!(frames[0]["asset_id"], asset);
|
||||
assert_eq!(frames[0]["market"], market);
|
||||
assert_eq!(frames[0]["hash"], http_book["hash"]);
|
||||
assert_eq!(frames[0]["asset_id"], "eb:NO:demo");
|
||||
assert_eq!(frames[0]["event_type"], "book");
|
||||
client.send(Message::text(controls[2].as_str())).unwrap();
|
||||
client.send(Message::text(controls[2])).unwrap();
|
||||
client.send(Message::text("PING")).unwrap();
|
||||
assert_eq!(client.read().unwrap().into_text().unwrap(), "PONG"); // unsubscribe processed
|
||||
engine.lock().unwrap().execute(json!({"op":"order","id":"bid","account":"maker","asset_id":"eb:YES:demo","side":"buy","price":30,"qty":1})).unwrap();
|
||||
@@ -320,13 +151,10 @@ mod tests {
|
||||
assert_eq!(delta["event_type"], "price_change");
|
||||
assert!(delta["timestamp"].as_str().unwrap().parse::<i64>().is_ok());
|
||||
assert_eq!(delta["price_changes"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(delta["market"], market);
|
||||
assert_eq!(delta["price_changes"][0]["asset_id"], asset);
|
||||
assert_eq!(delta["price_changes"][0]["asset_id"], "eb:NO:demo");
|
||||
assert_eq!(delta["price_changes"][0]["price"], "0.7");
|
||||
let quote: Value = serde_json::from_str(client.read().unwrap().to_text().unwrap()).unwrap();
|
||||
assert_eq!(quote["event_type"], "best_bid_ask");
|
||||
assert_eq!(quote["market"], market);
|
||||
assert_eq!(quote["asset_id"], asset);
|
||||
assert_eq!(quote["best_ask"], "0.7");
|
||||
assert!(quote["best_bid"].is_null());
|
||||
client.close(None).unwrap();
|
||||
|
||||
@@ -1,32 +0,0 @@
|
||||
use anyhow::Result;
|
||||
use exchange::Exchange;
|
||||
use serde_json::{json, Value};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
pub(crate) type Hashes = BTreeMap<i64, String>;
|
||||
|
||||
pub(crate) fn seq(value: &Value) -> Option<i64> {
|
||||
value.as_i64().or_else(|| value.as_str()?.parse().ok())
|
||||
}
|
||||
|
||||
pub(crate) fn wire(value: &Value, hashes: &Hashes) -> Value {
|
||||
match seq(value) {
|
||||
Some(seq) => hashes
|
||||
.get(&seq)
|
||||
.map_or_else(|| json!(seq.to_string()), |hash| json!(hash)),
|
||||
None => value.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn lookup(engine: &Exchange, rows: &[Value], fields: &[&str]) -> Result<Hashes> {
|
||||
let ids = rows
|
||||
.iter()
|
||||
.flat_map(|row| {
|
||||
fields
|
||||
.iter()
|
||||
.filter_map(|key| seq(&row[*key]))
|
||||
.chain(seq(&row["maker_leg"]["order_id"]))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
engine.order_hashes(&ids)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,107 +0,0 @@
|
||||
use super::{u64_word, Address, Word};
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use data_encoding::{HEXLOWER, HEXLOWER_PERMISSIVE};
|
||||
use reqwest::{blocking::Client, redirect::Policy, Url};
|
||||
use serde_json::{json, Value};
|
||||
use std::{io::Read, time::Duration};
|
||||
|
||||
const MAGIC: [u8; 4] = [0x16, 0x26, 0xba, 0x7e];
|
||||
const MAX_RESPONSE: u64 = 16 * 1024;
|
||||
|
||||
pub(super) struct Verifier {
|
||||
client: Client,
|
||||
url: Url,
|
||||
}
|
||||
|
||||
impl Verifier {
|
||||
pub(super) fn new(url: &str, chain_id: u64) -> Result<Self> {
|
||||
let url = Url::parse(url).context("invalid ERC-1271 RPC URL")?;
|
||||
ensure!(
|
||||
matches!(url.scheme(), "http" | "https") && url.host_str().is_some(),
|
||||
"invalid ERC-1271 RPC URL"
|
||||
);
|
||||
let client = Client::builder()
|
||||
.redirect(Policy::none())
|
||||
.timeout(Duration::from_secs(3))
|
||||
.build()?;
|
||||
let verifier = Self { client, url };
|
||||
let result = verifier.rpc("eth_chainId", json!([]))?;
|
||||
let actual = result
|
||||
.as_str()
|
||||
.and_then(|value| value.strip_prefix("0x"))
|
||||
.and_then(|value| u64::from_str_radix(value, 16).ok());
|
||||
ensure!(actual == Some(chain_id), "ERC-1271 RPC chain mismatch");
|
||||
Ok(verifier)
|
||||
}
|
||||
|
||||
pub(super) fn verify(
|
||||
&self,
|
||||
exchange: Address,
|
||||
wallet: Address,
|
||||
digest: Word,
|
||||
signature: &str,
|
||||
) -> Result<()> {
|
||||
let signature = signature
|
||||
.strip_prefix("0x")
|
||||
.context("invalid contract signature")?;
|
||||
ensure!(
|
||||
!signature.is_empty() && signature.len() <= 8192,
|
||||
"invalid contract signature length"
|
||||
);
|
||||
let signature = HEXLOWER_PERMISSIVE.decode(signature.as_bytes())?;
|
||||
let calldata = encode_call(digest, &signature);
|
||||
let result = self.rpc(
|
||||
"eth_call",
|
||||
json!([{
|
||||
"from": format!("0x{}", HEXLOWER.encode(&exchange)),
|
||||
"to": format!("0x{}", HEXLOWER.encode(&wallet)),
|
||||
"data": format!("0x{}", HEXLOWER.encode(&calldata)),
|
||||
}, "latest"]),
|
||||
)?;
|
||||
let mut expected = [0; 32];
|
||||
expected[..4].copy_from_slice(&MAGIC);
|
||||
let raw = result.as_str().and_then(|value| value.strip_prefix("0x"));
|
||||
ensure!(
|
||||
raw.is_some_and(|value| value.eq_ignore_ascii_case(&HEXLOWER.encode(&expected))),
|
||||
"contract rejected order signature"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn rpc(&self, method: &str, params: Value) -> Result<Value> {
|
||||
let response = self
|
||||
.client
|
||||
.post(self.url.clone())
|
||||
.json(&json!({"jsonrpc":"2.0","id":1,"method":method,"params":params}))
|
||||
.send()
|
||||
.and_then(|response| response.error_for_status())
|
||||
.map_err(reqwest::Error::without_url)
|
||||
.context("ERC-1271 RPC unavailable")?;
|
||||
let mut buf = Vec::new();
|
||||
response.take(MAX_RESPONSE + 1).read_to_end(&mut buf)?;
|
||||
ensure!(
|
||||
buf.len() as u64 <= MAX_RESPONSE,
|
||||
"oversized ERC-1271 RPC response"
|
||||
);
|
||||
let mut response: Value = serde_json::from_slice(&buf)?;
|
||||
ensure!(
|
||||
response["jsonrpc"] == "2.0" && response["id"] == 1 && response.get("error").is_none(),
|
||||
"invalid ERC-1271 RPC response"
|
||||
);
|
||||
response
|
||||
.as_object_mut()
|
||||
.and_then(|obj| obj.remove("result"))
|
||||
.context("missing ERC-1271 RPC result")
|
||||
}
|
||||
}
|
||||
|
||||
fn encode_call(digest: Word, signature: &[u8]) -> Vec<u8> {
|
||||
let mut data = Vec::new();
|
||||
data.extend_from_slice(&MAGIC);
|
||||
data.extend_from_slice(&digest);
|
||||
data.extend_from_slice(&u64_word(64));
|
||||
data.extend_from_slice(&u64_word(signature.len() as u64));
|
||||
data.extend_from_slice(signature);
|
||||
data.resize(4 + 96 + signature.len().next_multiple_of(32), 0);
|
||||
data
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
use exchange::{Exchange, MarketDataError, SnapshotQuery};
|
||||
use flate2::{write::GzEncoder, Compression};
|
||||
use serde_json::{json, Value};
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
io::{self, Write},
|
||||
net::IpAddr,
|
||||
sync::Mutex,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use tiny_http::{Header, Method, Request, Response};
|
||||
|
||||
const WINDOW: Duration = Duration::from_secs(30);
|
||||
pub(crate) type Starts = Mutex<HashMap<IpAddr, Instant>>;
|
||||
|
||||
fn accepts_gzip(req: &Request) -> bool {
|
||||
req.headers()
|
||||
.iter()
|
||||
.filter(|h| h.field.equiv("Accept-Encoding"))
|
||||
.any(|h| {
|
||||
h.value.as_str().split(',').any(|coding| {
|
||||
let mut parts = coding.split(';').map(str::trim);
|
||||
parts
|
||||
.next()
|
||||
.is_some_and(|name| name.eq_ignore_ascii_case("gzip"))
|
||||
&& parts.all(|part| {
|
||||
let Some((name, value)) = part.split_once('=') else {
|
||||
return false;
|
||||
};
|
||||
name.trim().eq_ignore_ascii_case("q")
|
||||
&& value
|
||||
.trim()
|
||||
.parse::<f32>()
|
||||
.is_ok_and(|q| q > 0.0 && q <= 1.0)
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn error(
|
||||
req: Request,
|
||||
status: u16,
|
||||
code: &str,
|
||||
message: &str,
|
||||
header: Option<Header>,
|
||||
) -> io::Result<()> {
|
||||
let body = json!({"code":code,"error":message,"retryable":matches!(status,429|503)});
|
||||
let mut response = Response::from_data(body.to_string().into_bytes())
|
||||
.with_status_code(status)
|
||||
.with_header(Header::from_bytes("Content-Type", "application/json").unwrap())
|
||||
.with_header(Header::from_bytes("Vary", "Accept-Encoding").unwrap());
|
||||
if let Some(header) = header {
|
||||
response.add_header(header);
|
||||
}
|
||||
req.respond(response)
|
||||
}
|
||||
|
||||
pub(crate) fn respond(req: Request, engine: &Mutex<Exchange>, starts: &Starts) -> io::Result<()> {
|
||||
if req.method() != &Method::Get {
|
||||
return error(
|
||||
req,
|
||||
405,
|
||||
"method_not_allowed",
|
||||
"Method not allowed",
|
||||
Header::from_bytes("Allow", "GET").ok(),
|
||||
);
|
||||
}
|
||||
if !accepts_gzip(&req) {
|
||||
return error(
|
||||
req,
|
||||
406,
|
||||
"not_acceptable",
|
||||
"Accept-Encoding: gzip is required",
|
||||
None,
|
||||
);
|
||||
}
|
||||
let params = req.url().split_once('?').map_or("", |(_, params)| params);
|
||||
let query: SnapshotQuery = match serde_urlencoded::from_str(params) {
|
||||
Ok(query) => query,
|
||||
Err(_) => {
|
||||
return error(
|
||||
req,
|
||||
400,
|
||||
"invalid_request",
|
||||
"invalid query parameters",
|
||||
None,
|
||||
)
|
||||
}
|
||||
};
|
||||
let ip = if query.is_first_page() {
|
||||
req.remote_addr().map(|addr| addr.ip())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut walks = starts
|
||||
.lock()
|
||||
.map_err(|_| io::Error::other("snapshot rate limit unavailable"))?;
|
||||
let now = Instant::now();
|
||||
if let Some(ip) = ip {
|
||||
walks.retain(|_, at| now.duration_since(*at) < WINDOW);
|
||||
if let Some(at) = walks.get(&ip) {
|
||||
let wait = WINDOW
|
||||
.saturating_sub(now.duration_since(*at))
|
||||
.as_millis()
|
||||
.div_ceil(1000);
|
||||
drop(walks);
|
||||
return error(
|
||||
req,
|
||||
429,
|
||||
"rate_limited",
|
||||
"snapshot first-page rate limit",
|
||||
Header::from_bytes("Retry-After", wait.to_string()).ok(),
|
||||
);
|
||||
}
|
||||
}
|
||||
let result = engine
|
||||
.lock()
|
||||
.map_err(|_| MarketDataError::Unavailable)
|
||||
.and_then(|engine| engine.public_position_snapshot(query));
|
||||
if let (Some(ip), Ok(_)) = (ip, &result) {
|
||||
walks.insert(ip, Instant::now());
|
||||
}
|
||||
drop(walks);
|
||||
match result {
|
||||
Ok(data) => gzip(req, &data),
|
||||
Err(MarketDataError::Invalid(message)) => {
|
||||
error(req, 400, "invalid_request", &message, None)
|
||||
}
|
||||
Err(MarketDataError::Unavailable) => error(
|
||||
req,
|
||||
503,
|
||||
"unavailable",
|
||||
"snapshot unavailable",
|
||||
Header::from_bytes("Retry-After", "1").ok(),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
fn gzip(req: Request, data: &Value) -> io::Result<()> {
|
||||
let mut gzip = GzEncoder::new(Vec::new(), Compression::default());
|
||||
gzip.write_all(data.to_string().as_bytes())?;
|
||||
let response = Response::from_data(gzip.finish()?)
|
||||
.with_header(Header::from_bytes("Content-Type", "application/json").unwrap())
|
||||
.with_header(Header::from_bytes("Content-Encoding", "gzip").unwrap())
|
||||
.with_header(Header::from_bytes("Cache-Control", "public, max-age=86400").unwrap())
|
||||
.with_header(Header::from_bytes("Vary", "Accept-Encoding").unwrap());
|
||||
req.respond(response)
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
use crate::wire_ids::WireIds;
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use exchange::{parse_asset_id, Exchange, MarketPage};
|
||||
use serde::Deserialize;
|
||||
@@ -37,12 +36,7 @@ pub(crate) struct Session {
|
||||
}
|
||||
|
||||
impl Session {
|
||||
pub fn control(
|
||||
&mut self,
|
||||
engine: &mut Exchange,
|
||||
ids: &WireIds,
|
||||
text: &str,
|
||||
) -> Result<Vec<Value>> {
|
||||
pub fn control(&mut self, engine: &mut Exchange, text: &str) -> Result<Vec<Value>> {
|
||||
let c: Control = serde_json::from_str(text)?;
|
||||
let opening = !self.opened;
|
||||
let subscribe = match (opening, c.channel.as_deref(), c.operation.as_deref()) {
|
||||
@@ -53,12 +47,8 @@ impl Session {
|
||||
ensure!(!c.assets_ids.is_empty(), "assets_ids required");
|
||||
let mut groups = BTreeMap::<String, BTreeSet<String>>::new();
|
||||
for token in c.assets_ids {
|
||||
let token = ids.local_asset(&token);
|
||||
let (_, market) = parse_asset_id(token)?;
|
||||
groups
|
||||
.entry(market.into())
|
||||
.or_default()
|
||||
.insert(token.to_owned());
|
||||
let (_, market) = parse_asset_id(&token)?;
|
||||
groups.entry(market.into()).or_default().insert(token);
|
||||
}
|
||||
// Validate all assets before replacing a live subscription.
|
||||
let mut next = self.clone();
|
||||
@@ -238,23 +228,12 @@ mod tests {
|
||||
}
|
||||
let mut session = Session::default();
|
||||
let opening = r#"{"type":"market","assets_ids":["eb:YES:demo"]}"#;
|
||||
assert_eq!(
|
||||
session
|
||||
.control(&mut db, &WireIds::default(), opening)
|
||||
.unwrap()
|
||||
.len(),
|
||||
1
|
||||
);
|
||||
assert_eq!(session.control(&mut db, opening).unwrap().len(), 1);
|
||||
db.execute(json!({"op":"order","id":"a","account":"maker","asset_id":"eb:YES:demo","side":"buy","price":20,"qty":1})).unwrap();
|
||||
let subscribe = r#"{"operation":"subscribe","assets_ids":["eb:NO:demo"]}"#;
|
||||
let snap = session
|
||||
.control(&mut db, &WireIds::default(), subscribe)
|
||||
.unwrap();
|
||||
let snap = session.control(&mut db, subscribe).unwrap();
|
||||
assert_eq!(snap[0]["asks"][0]["price"], "0.8");
|
||||
assert!(session
|
||||
.control(&mut db, &WireIds::default(), subscribe)
|
||||
.unwrap()
|
||||
.is_empty());
|
||||
assert!(session.control(&mut db, subscribe).unwrap().is_empty());
|
||||
let frames = session.poll(&mut db).unwrap();
|
||||
assert_eq!(frames.len(), 1);
|
||||
assert_eq!(frames[0]["price_changes"].as_array().unwrap().len(), 1);
|
||||
@@ -268,17 +247,12 @@ mod tests {
|
||||
.unwrap();
|
||||
let mut session = Session::default();
|
||||
session
|
||||
.control(
|
||||
&mut db,
|
||||
&WireIds::default(),
|
||||
r#"{"type":"market","assets_ids":["eb:YES:demo"]}"#,
|
||||
)
|
||||
.control(&mut db, r#"{"type":"market","assets_ids":["eb:YES:demo"]}"#)
|
||||
.unwrap();
|
||||
db.execute(json!({"op":"tick_size_change","id":"t","asset_id":"eb:YES:demo","new_tick_size":"0.001","timestamp":"1"})).unwrap();
|
||||
let snap = session
|
||||
.control(
|
||||
&mut db,
|
||||
&WireIds::default(),
|
||||
r#"{"operation":"subscribe","assets_ids":["eb:NO:demo"]}"#,
|
||||
)
|
||||
.unwrap();
|
||||
@@ -298,7 +272,7 @@ mod tests {
|
||||
let mut enabled = Session::default();
|
||||
let mut standard = Session::default();
|
||||
for (s, custom) in [(&mut enabled, true), (&mut standard, false)] {
|
||||
s.control(&mut db, &WireIds::default(),&json!({"type":"market","assets_ids":["eb:YES:lobby"],"custom_feature_enabled":custom}).to_string()).unwrap();
|
||||
s.control(&mut db,&json!({"type":"market","assets_ids":["eb:YES:lobby"],"custom_feature_enabled":custom}).to_string()).unwrap();
|
||||
assert!(s.poll(&mut db).unwrap().is_empty());
|
||||
}
|
||||
db.execute(inputs.next().unwrap()).unwrap();
|
||||
@@ -315,7 +289,6 @@ mod tests {
|
||||
for s in [&mut enabled, &mut standard] {
|
||||
s.control(
|
||||
&mut db,
|
||||
&WireIds::default(),
|
||||
r#"{"operation":"subscribe","assets_ids":["eb:YES:match-1","eb:NO:match-1"]}"#,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
@@ -1,429 +0,0 @@
|
||||
use crate::{account_http, order_refs, wire_ids::WireIds};
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use exchange::Exchange;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::{collections::BTreeMap, path::Path, sync::Arc};
|
||||
use subtle::ConstantTimeEq;
|
||||
|
||||
const MAX_MARKETS: usize = 256;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct CredentialRecord {
|
||||
api_key: String,
|
||||
account: String,
|
||||
digest: String,
|
||||
}
|
||||
|
||||
enum Source {
|
||||
Digest(BTreeMap<String, (String, [u8; 32])>),
|
||||
Account(account_http::Credentials),
|
||||
}
|
||||
|
||||
pub(crate) struct Credentials {
|
||||
source: Source,
|
||||
ids: Arc<WireIds>,
|
||||
}
|
||||
|
||||
impl Credentials {
|
||||
pub(crate) fn from_account(credentials: account_http::Credentials) -> Self {
|
||||
Self {
|
||||
source: Source::Account(credentials),
|
||||
ids: Arc::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn with_identifiers(mut self, ids: WireIds) -> Self {
|
||||
self.ids = Arc::new(ids);
|
||||
self
|
||||
}
|
||||
|
||||
pub(crate) fn load(path: &Path) -> Result<Self> {
|
||||
Self::from_records(crate::credential_file::read(path)?)
|
||||
}
|
||||
|
||||
fn from_records(rows: Vec<CredentialRecord>) -> Result<Self> {
|
||||
let mut records = BTreeMap::new();
|
||||
for row in rows {
|
||||
ensure!(
|
||||
!row.api_key.trim().is_empty()
|
||||
&& !row.account.trim().is_empty()
|
||||
&& row.account.trim().chars().count() <= 256,
|
||||
"invalid credential account or key"
|
||||
);
|
||||
ensure!(
|
||||
row.digest.len() == 64 && row.digest.bytes().all(|b| b.is_ascii_hexdigit()),
|
||||
"invalid credential digest"
|
||||
);
|
||||
let mut digest = [0; 32];
|
||||
for (i, byte) in digest.iter_mut().enumerate() {
|
||||
*byte = u8::from_str_radix(&row.digest[i * 2..i * 2 + 2], 16)?;
|
||||
}
|
||||
ensure!(
|
||||
records.insert(row.api_key, (row.account, digest)).is_none(),
|
||||
"duplicate API key"
|
||||
);
|
||||
}
|
||||
ensure!(!records.is_empty(), "no user WebSocket credentials");
|
||||
Ok(Self {
|
||||
source: Source::Digest(records),
|
||||
ids: Arc::default(),
|
||||
})
|
||||
}
|
||||
|
||||
fn account(&self, engine: &Exchange, auth: &Auth) -> Result<Option<(String, bool)>> {
|
||||
match &self.source {
|
||||
Source::Digest(records) => {
|
||||
let authenticated = records.get(&auth.api_key).and_then(|(account, expected)| {
|
||||
let actual = digest(&auth.secret, &auth.passphrase)?;
|
||||
bool::from(actual.ct_eq(expected)).then(|| (account.clone(), false))
|
||||
});
|
||||
Ok(authenticated)
|
||||
}
|
||||
Source::Account(credentials) => {
|
||||
credentials.websocket_account(engine, &auth.api_key, &auth.secret, &auth.passphrase)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn digest(secret: &str, passphrase: &str) -> Option<[u8; 32]> {
|
||||
if [secret, passphrase]
|
||||
.iter()
|
||||
.any(|value| value.is_empty() || value.contains('\0'))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let mut hasher = Sha256::new();
|
||||
hasher.update(secret.as_bytes());
|
||||
hasher.update([0]);
|
||||
hasher.update(passphrase.as_bytes());
|
||||
Some(hasher.finalize().into())
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Auth {
|
||||
#[serde(rename = "apiKey")]
|
||||
api_key: String,
|
||||
secret: String,
|
||||
passphrase: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Init {
|
||||
#[serde(rename = "type")]
|
||||
channel: String,
|
||||
auth: Auth,
|
||||
#[serde(default)]
|
||||
markets: Vec<String>,
|
||||
after: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(tag = "operation", rename_all = "snake_case", deny_unknown_fields)]
|
||||
enum Control {
|
||||
Subscribe {
|
||||
markets: Vec<String>,
|
||||
},
|
||||
Unsubscribe {
|
||||
markets: Vec<String>,
|
||||
},
|
||||
Snapshot {
|
||||
market: Option<String>,
|
||||
trade_limit: Option<u32>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Page {
|
||||
cursor: i64,
|
||||
events: Vec<Value>,
|
||||
}
|
||||
|
||||
pub(crate) struct Session {
|
||||
account: String,
|
||||
api_key: String,
|
||||
issued: bool,
|
||||
cursor: i64,
|
||||
all: bool,
|
||||
markets: BTreeMap<String, Option<i64>>,
|
||||
ids: Arc<WireIds>,
|
||||
}
|
||||
|
||||
fn validate_markets(markets: &[String]) -> Result<()> {
|
||||
ensure!(markets.len() <= MAX_MARKETS, "too many market filters");
|
||||
ensure!(
|
||||
markets
|
||||
.iter()
|
||||
.all(|id| !id.trim().is_empty() && id.trim().chars().count() <= 256),
|
||||
"invalid market filter"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl Session {
|
||||
pub(crate) fn start(engine: &Exchange, credentials: &Credentials, frame: &str) -> Result<Self> {
|
||||
let init: Init = serde_json::from_str(frame)?;
|
||||
ensure!(init.channel == "user", "invalid user subscription");
|
||||
let (account, issued) = credentials
|
||||
.account(engine, &init.auth)?
|
||||
.context("invalid credentials")?;
|
||||
validate_markets(&init.markets)?;
|
||||
let current = engine.account_event_cursor()?;
|
||||
let cursor = init.after.unwrap_or(current);
|
||||
ensure!((0..=current).contains(&cursor), "invalid user event cursor");
|
||||
Ok(Self {
|
||||
account,
|
||||
api_key: init.auth.api_key,
|
||||
issued,
|
||||
cursor,
|
||||
all: init.markets.is_empty(),
|
||||
markets: init
|
||||
.markets
|
||||
.into_iter()
|
||||
.map(|id| (credentials.ids.local_market(&id).to_owned(), Some(cursor)))
|
||||
.collect(),
|
||||
ids: Arc::clone(&credentials.ids),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn active(&self, engine: &Exchange) -> Result<bool> {
|
||||
if self.issued {
|
||||
engine.is_issued_api_key_active(&self.api_key)
|
||||
} else {
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn control(&mut self, engine: &mut Exchange, frame: &str) -> Result<Option<Value>> {
|
||||
let (subscribe, markets) = match serde_json::from_str(frame)? {
|
||||
Control::Snapshot {
|
||||
market,
|
||||
trade_limit,
|
||||
} => {
|
||||
let market = market.as_deref().map(|id| self.ids.local_market(id));
|
||||
let mut snapshot = engine.execute(json!({"op":"account_snapshot","account":self.account,"market":market,"trade_limit":trade_limit}))?;
|
||||
for kind in ["orders", "trades"] {
|
||||
if let Some(rows) = snapshot[kind].as_array_mut() {
|
||||
let hashes = order_refs::lookup(engine, rows, &["order", "taker_order"])?;
|
||||
for row in rows {
|
||||
row["order_id"] = order_refs::wire(&row["order"], &hashes);
|
||||
if kind == "trades" {
|
||||
row["taker_order_id"] =
|
||||
order_refs::wire(&row["taker_order"], &hashes);
|
||||
}
|
||||
self.ids.write_record(row);
|
||||
}
|
||||
}
|
||||
}
|
||||
snapshot["event_type"] = json!("snapshot");
|
||||
return Ok(Some(snapshot));
|
||||
}
|
||||
Control::Subscribe { markets } => (true, markets),
|
||||
Control::Unsubscribe { markets } => (false, markets),
|
||||
};
|
||||
validate_markets(&markets)?;
|
||||
let now = engine.account_event_cursor()?;
|
||||
let mut selection = self.markets.clone();
|
||||
for market in markets {
|
||||
let market = self.ids.local_market(&market).to_owned();
|
||||
let active = selection.get(&market).map_or(self.all, Option::is_some);
|
||||
if subscribe == active {
|
||||
continue;
|
||||
}
|
||||
if !subscribe && !self.all {
|
||||
selection.remove(&market);
|
||||
} else {
|
||||
selection.insert(market, subscribe.then_some(now));
|
||||
}
|
||||
}
|
||||
ensure!(selection.len() <= MAX_MARKETS, "too many market filters");
|
||||
self.markets = selection;
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
pub(crate) fn poll(&mut self, engine: &mut Exchange) -> Result<Vec<Value>> {
|
||||
let page: Page = serde_json::from_value(engine.execute(
|
||||
json!({"op":"account_events","account":self.account,"after":self.cursor,"limit":128,"include_maker":true}),
|
||||
)?)?;
|
||||
let hashes = order_refs::lookup(engine, &page.events, &["order_id", "taker_order_id"])?;
|
||||
self.cursor = page.cursor;
|
||||
Ok(page
|
||||
.events
|
||||
.into_iter()
|
||||
.filter_map(|mut frame| {
|
||||
let id = frame["market"].as_str()?;
|
||||
let seq = frame["seq"].as_i64()?;
|
||||
if !self
|
||||
.markets
|
||||
.get(id)
|
||||
.map_or(self.all, |start| start.is_some_and(|n| seq > n))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
frame["owner"] = json!(self.api_key);
|
||||
frame["order_id"] = order_refs::wire(&frame["order_id"], &hashes);
|
||||
if frame["event_type"] == "order" {
|
||||
frame["id"] = frame["order_id"].clone();
|
||||
frame["order_owner"] = json!(self.api_key);
|
||||
match frame["status"].as_str() {
|
||||
Some("FILLED") => frame["status"] = json!("MATCHED"),
|
||||
Some("CANCELLED" | "EXPIRED") => frame["status"] = json!("CANCELED"),
|
||||
_ => {}
|
||||
}
|
||||
} else if let Some(leg) = frame.as_object_mut()?.remove("maker_leg") {
|
||||
frame["taker_order_id"] = order_refs::wire(&frame["taker_order_id"], &hashes);
|
||||
let mut maker_orders = Vec::new();
|
||||
if let Value::Object(mut maker) = leg {
|
||||
maker.remove("account");
|
||||
let id = order_refs::wire(&maker["order_id"], &hashes);
|
||||
maker.insert("order_id".into(), id);
|
||||
maker_orders.push(maker);
|
||||
}
|
||||
frame["maker_orders"] = json!(maker_orders);
|
||||
}
|
||||
self.ids.write_execution(&mut frame);
|
||||
Some(frame)
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::market_ws::connection;
|
||||
use std::{
|
||||
net::{TcpListener, TcpStream},
|
||||
sync::{Arc, Mutex},
|
||||
thread,
|
||||
time::Duration,
|
||||
};
|
||||
use tungstenite::Message;
|
||||
|
||||
#[test]
|
||||
fn user_socket_authenticates_and_filters_live_events() {
|
||||
let mut db = Exchange::open(":memory:").unwrap();
|
||||
for account in ["alice", "bob"] {
|
||||
db.execute(
|
||||
json!({"op":"fund","id":format!("fund-{account}"),"account":account,"cents":1000}),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
for market in ["demo", "other"] {
|
||||
db.execute(json!({"op":"list","id":format!("list-{market}"),"market":market,"rules":"simulated"})).unwrap();
|
||||
db.execute(json!({"op":"open","id":format!("open-{market}"),"market":market}))
|
||||
.unwrap();
|
||||
}
|
||||
let digest = digest("only-a-test-secret", "test-passphrase").unwrap();
|
||||
let condition = format!("0x{}", "ab".repeat(32));
|
||||
let mut ids = WireIds::default();
|
||||
ids.bind_market("demo", [0xab; 32]).unwrap();
|
||||
ids.bind_asset(
|
||||
"eb:YES:demo",
|
||||
crate::ethereum::uint_word("123").unwrap(),
|
||||
"123",
|
||||
)
|
||||
.unwrap();
|
||||
let credentials = Credentials::from_records(vec![CredentialRecord {
|
||||
account: "alice".into(),
|
||||
api_key: "alice-test-key".into(),
|
||||
digest: digest
|
||||
.iter()
|
||||
.map(|b| format!("{b:02x}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(""),
|
||||
}])
|
||||
.unwrap()
|
||||
.with_identifiers(ids);
|
||||
let mut init = json!({"type":"user","markets":[condition],"after":0,
|
||||
"auth":{"apiKey":"alice-test-key","secret":"wrong","passphrase":"test-passphrase"}});
|
||||
assert!(Session::start(&db, &credentials, &init.to_string()).is_err());
|
||||
init["auth"]["secret"] = json!("only-a-test-secret");
|
||||
assert!(Session::start(&db, &credentials, &init.to_string()).is_ok());
|
||||
|
||||
let db = Arc::new(Mutex::new(db));
|
||||
let server_db = Arc::clone(&db);
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let worker = thread::spawn(move || {
|
||||
connection(
|
||||
listener.accept().unwrap().0,
|
||||
&server_db,
|
||||
Some(&credentials),
|
||||
&WireIds::default(),
|
||||
)
|
||||
});
|
||||
let tcp = TcpStream::connect(addr).unwrap();
|
||||
tcp.set_read_timeout(Some(Duration::from_secs(4))).unwrap();
|
||||
let (mut client, _) = tungstenite::client(format!("ws://{addr}/ws/user"), tcp).unwrap();
|
||||
client.send(Message::text(init.to_string())).unwrap();
|
||||
client
|
||||
.send(Message::text(r#"{"operation":"snapshot","account":"bob"}"#))
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
client.read().unwrap().into_text().unwrap(),
|
||||
"INVALID OPERATION"
|
||||
);
|
||||
client
|
||||
.send(Message::text(
|
||||
json!({"operation":"snapshot","market":condition}).to_string(),
|
||||
))
|
||||
.unwrap();
|
||||
let snapshot: Value =
|
||||
serde_json::from_str(client.read().unwrap().to_text().unwrap()).unwrap();
|
||||
assert_eq!(snapshot["event_type"], "snapshot");
|
||||
assert_eq!(snapshot["orders"], json!([]));
|
||||
client.send(Message::text("PING")).unwrap();
|
||||
assert_eq!(client.read().unwrap().into_text().unwrap(), "PONG");
|
||||
|
||||
for (id, account, market) in [
|
||||
("hidden-bob", "bob", "demo"),
|
||||
("hidden-market", "alice", "other"),
|
||||
] {
|
||||
db.lock().unwrap().execute(json!({"op":"order","id":id,"account":account,"market":market,"outcome":"YES","side":"buy","price":20,"qty":1})).unwrap();
|
||||
}
|
||||
let order_hash = format!("0x{}", "33".repeat(32));
|
||||
let maker = "0x51b7c68a71dccbc0b7fa4400934a293d8f4d3ba8";
|
||||
db.lock()
|
||||
.unwrap()
|
||||
.execute_signed_order(
|
||||
json!({"op":"order","id":format!("clob-order:{order_hash}"),
|
||||
"account":"alice","market":"demo","outcome":"YES","side":"buy","price":20,"qty":1}),
|
||||
maker,
|
||||
)
|
||||
.unwrap();
|
||||
let frame: Value = serde_json::from_str(client.read().unwrap().to_text().unwrap()).unwrap();
|
||||
assert_eq!(frame["type"], "PLACEMENT");
|
||||
assert_eq!(frame["owner"], "alice-test-key");
|
||||
assert_eq!(frame["market"], condition);
|
||||
assert_eq!(frame["asset_id"], "123");
|
||||
assert_eq!(frame["id"], order_hash);
|
||||
assert_eq!(frame["maker_address"], maker);
|
||||
client
|
||||
.send(Message::text(
|
||||
json!({"operation":"unsubscribe","markets":[condition]}).to_string(),
|
||||
))
|
||||
.unwrap();
|
||||
client.send(Message::text("PING")).unwrap();
|
||||
assert_eq!(client.read().unwrap().into_text().unwrap(), "PONG");
|
||||
db.lock().unwrap().execute(json!({"op":"order","id":"while-unsubscribed","account":"alice","market":"demo","outcome":"YES","side":"buy","price":20,"qty":1})).unwrap();
|
||||
client
|
||||
.send(Message::text(
|
||||
r#"{"operation":"subscribe","markets":["demo"]}"#,
|
||||
))
|
||||
.unwrap();
|
||||
client.send(Message::text("PING")).unwrap();
|
||||
assert_eq!(client.read().unwrap().into_text().unwrap(), "PONG");
|
||||
db.lock().unwrap().execute(json!({"op":"order","id":"after-resubscribe","account":"alice","market":"demo","outcome":"YES","side":"buy","price":20,"qty":1})).unwrap();
|
||||
let resumed: Value =
|
||||
serde_json::from_str(client.read().unwrap().to_text().unwrap()).unwrap();
|
||||
assert_eq!(resumed["id"], "5");
|
||||
client.close(None).unwrap();
|
||||
worker.join().unwrap().unwrap();
|
||||
}
|
||||
}
|
||||
@@ -1,261 +0,0 @@
|
||||
use crate::ethereum::{fixed_hex, uint_word, Word};
|
||||
use anyhow::{ensure, Result};
|
||||
use data_encoding::HEXLOWER;
|
||||
use serde_json::Value;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
pub(crate) struct MigratedAssets {
|
||||
pub(crate) ctf: [String; 2],
|
||||
pub(crate) positions: [String; 2],
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct WireIds {
|
||||
assets_by_token: BTreeMap<Word, String>,
|
||||
tokens_by_asset: BTreeMap<String, String>,
|
||||
markets_by_condition: BTreeMap<Word, String>,
|
||||
conditions_by_market: BTreeMap<String, String>,
|
||||
position_markets: BTreeSet<String>,
|
||||
migrated_markets: BTreeMap<String, MigratedAssets>,
|
||||
alternate_assets_by_token: BTreeMap<Word, (String, bool)>,
|
||||
}
|
||||
|
||||
impl WireIds {
|
||||
pub(crate) fn bind_asset(&mut self, asset: &str, token: Word, decimal: &str) -> Result<()> {
|
||||
ensure!(
|
||||
!self.tokens_by_asset.contains_key(asset),
|
||||
"duplicate local order asset"
|
||||
);
|
||||
ensure!(
|
||||
!self.assets_by_token.contains_key(&token),
|
||||
"duplicate order token ID"
|
||||
);
|
||||
self.assets_by_token.insert(token, asset.to_owned());
|
||||
self.tokens_by_asset
|
||||
.insert(asset.to_owned(), decimal.trim_start_matches('0').to_owned());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn bind_market(&mut self, market: &str, condition: Word) -> Result<()> {
|
||||
ensure!(condition != [0; 32], "invalid market condition ID");
|
||||
let wire = format!("0x{}", HEXLOWER.encode(&condition));
|
||||
ensure!(
|
||||
self.conditions_by_market
|
||||
.get(market)
|
||||
.is_none_or(|stored| stored == &wire)
|
||||
&& self
|
||||
.markets_by_condition
|
||||
.get(&condition)
|
||||
.is_none_or(|stored| stored == market),
|
||||
"inconsistent condition ID mapping"
|
||||
);
|
||||
self.conditions_by_market.insert(market.to_owned(), wire);
|
||||
self.markets_by_condition
|
||||
.insert(condition, market.to_owned());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn bind_migrated_market(
|
||||
&mut self,
|
||||
market: &str,
|
||||
ctf_condition: Word,
|
||||
ctf: &[String; 2],
|
||||
positions: &[String; 2],
|
||||
) -> Result<()> {
|
||||
ensure!(
|
||||
!self.migrated_markets.contains_key(market),
|
||||
"duplicate migrated market"
|
||||
);
|
||||
let ctf_words = [uint_word(&ctf[0])?, uint_word(&ctf[1])?];
|
||||
let position_words = [uint_word(&positions[0])?, uint_word(&positions[1])?];
|
||||
let mut structural = position_words[1];
|
||||
ensure!(structural[31] == 1, "invalid NO position slot");
|
||||
structural[31] = 0;
|
||||
ensure!(
|
||||
structural == position_words[0] && structural != [0; 32] && structural != ctf_condition,
|
||||
"invalid structural condition for migrated market"
|
||||
);
|
||||
ensure!(
|
||||
ctf_condition != [0; 32]
|
||||
&& ctf_words[0] != [0; 32]
|
||||
&& ctf_words[1] != [0; 32]
|
||||
&& ctf_words[0] != ctf_words[1],
|
||||
"invalid CTF condition or token pair"
|
||||
);
|
||||
|
||||
let uses_positions = self.is_position_market(market);
|
||||
let (primary, alternate, primary_condition) = if uses_positions {
|
||||
(&position_words, &ctf_words, structural)
|
||||
} else {
|
||||
(&ctf_words, &position_words, ctf_condition)
|
||||
};
|
||||
for (index, label) in ["YES", "NO"].into_iter().enumerate() {
|
||||
let asset = format!("eb:{label}:{market}");
|
||||
ensure!(
|
||||
self.assets_by_token.get(&primary[index]) == Some(&asset),
|
||||
"migrated market must match both configured order assets"
|
||||
);
|
||||
ensure!(
|
||||
!self.assets_by_token.contains_key(&alternate[index])
|
||||
&& !self
|
||||
.alternate_assets_by_token
|
||||
.contains_key(&alternate[index]),
|
||||
"duplicate migrated market token ID"
|
||||
);
|
||||
}
|
||||
let alternate_condition = if uses_positions {
|
||||
ctf_condition
|
||||
} else {
|
||||
structural
|
||||
};
|
||||
ensure!(
|
||||
self.markets_by_condition
|
||||
.get(&alternate_condition)
|
||||
.is_none_or(|stored| stored == market),
|
||||
"inconsistent migrated condition ID mapping"
|
||||
);
|
||||
self.bind_market(market, primary_condition)?;
|
||||
self.markets_by_condition
|
||||
.insert(alternate_condition, market.to_owned());
|
||||
self.conditions_by_market.insert(
|
||||
market.to_owned(),
|
||||
format!("0x{}", HEXLOWER.encode(&ctf_condition)),
|
||||
);
|
||||
for (token, label) in alternate.iter().zip(["YES", "NO"]) {
|
||||
self.alternate_assets_by_token
|
||||
.insert(*token, (format!("eb:{label}:{market}"), !uses_positions));
|
||||
}
|
||||
self.migrated_markets.insert(
|
||||
market.to_owned(),
|
||||
MigratedAssets {
|
||||
ctf: ctf
|
||||
.each_ref()
|
||||
.map(|id| id.trim_start_matches('0').to_owned()),
|
||||
positions: positions
|
||||
.each_ref()
|
||||
.map(|id| id.trim_start_matches('0').to_owned()),
|
||||
},
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn migrated_assets(&self, market: &str) -> Option<&MigratedAssets> {
|
||||
self.migrated_markets.get(market)
|
||||
}
|
||||
|
||||
pub(crate) fn directory_asset<'a>(&'a self, raw: &'a str, positions: bool) -> Option<&'a str> {
|
||||
if let Ok(word) = token_word(raw) {
|
||||
if let Some((asset, is_position)) = self.alternate_assets_by_token.get(&word) {
|
||||
return (*is_position == positions).then_some(asset.as_str());
|
||||
}
|
||||
let asset = self.assets_by_token.get(&word)?;
|
||||
let (_, market) = exchange::parse_asset_id(asset).ok()?;
|
||||
return (self.is_position_market(market) == positions).then_some(asset.as_str());
|
||||
}
|
||||
if !positions {
|
||||
let (_, market) = exchange::parse_asset_id(raw).ok()?;
|
||||
if !self.is_position_market(market) {
|
||||
return Some(raw);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub(crate) fn check_market_alias(&self, market: &str) -> Result<()> {
|
||||
ensure!(
|
||||
self.local_market(market) == market,
|
||||
"condition ID conflicts with a local market ID"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn asset_for_token(&self, token: &str) -> Option<&str> {
|
||||
self.assets_by_token
|
||||
.get(&token_word(token).ok()?)
|
||||
.map(String::as_str)
|
||||
}
|
||||
|
||||
pub(crate) fn market_for_condition(&self, condition: &str) -> Option<&str> {
|
||||
self.markets_by_condition
|
||||
.get(&fixed_hex::<32>(condition).ok()?)
|
||||
.map(String::as_str)
|
||||
}
|
||||
|
||||
pub(crate) fn local_market<'a>(&'a self, raw: &'a str) -> &'a str {
|
||||
self.market_for_condition(raw).unwrap_or(raw)
|
||||
}
|
||||
|
||||
pub(crate) fn local_asset<'a>(&'a self, raw: &'a str) -> &'a str {
|
||||
self.asset_for_token(raw).unwrap_or(raw)
|
||||
}
|
||||
|
||||
pub(crate) fn wire_market<'a>(&'a self, market: &'a str) -> &'a str {
|
||||
self.conditions_by_market
|
||||
.get(market)
|
||||
.map_or(market, String::as_str)
|
||||
}
|
||||
|
||||
pub(crate) fn wire_asset<'a>(&'a self, asset: &'a str) -> &'a str {
|
||||
self.tokens_by_asset
|
||||
.get(asset)
|
||||
.map_or(asset, String::as_str)
|
||||
}
|
||||
|
||||
pub(crate) fn mark_position_market(&mut self, market: &str) {
|
||||
self.position_markets.insert(market.to_owned());
|
||||
}
|
||||
|
||||
pub(crate) fn is_position_market(&self, market: &str) -> bool {
|
||||
self.position_markets.contains(market)
|
||||
}
|
||||
|
||||
pub(crate) fn book(&self, snapshot: Value) -> Result<Value> {
|
||||
let market = snapshot["market"]
|
||||
.as_str()
|
||||
.and_then(|id| self.conditions_by_market.get(id));
|
||||
let asset = snapshot["asset_id"]
|
||||
.as_str()
|
||||
.and_then(|id| self.tokens_by_asset.get(id));
|
||||
exchange::relabel_book_snapshot(
|
||||
snapshot,
|
||||
market.map(String::as_str),
|
||||
asset.map(String::as_str),
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn write_asset(&self, slot: &mut Value) {
|
||||
if let Some(asset) = slot.as_str().and_then(|id| self.tokens_by_asset.get(id)) {
|
||||
*slot = Value::String(asset.clone());
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn write_record(&self, row: &mut Value) {
|
||||
if let Some(market) = row["market"]
|
||||
.as_str()
|
||||
.and_then(|id| self.conditions_by_market.get(id))
|
||||
{
|
||||
row["market"] = Value::String(market.clone());
|
||||
}
|
||||
if let Some(asset) = row.get_mut("asset_id") {
|
||||
self.write_asset(asset);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn write_execution(&self, row: &mut Value) {
|
||||
self.write_record(row);
|
||||
if let Some(makers) = row.get_mut("maker_orders").and_then(Value::as_array_mut) {
|
||||
for maker in makers {
|
||||
self.write_record(maker);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn token_word(raw: &str) -> Result<Word> {
|
||||
if let Some(hex) = raw.strip_prefix("0x") {
|
||||
ensure!((1..=64).contains(&hex.len()), "invalid token ID width");
|
||||
fixed_hex(&format!("0x{hex:0>64}"))
|
||||
} else {
|
||||
uint_word(raw)
|
||||
}
|
||||
}
|
||||
+119
-105
@@ -9,9 +9,6 @@
|
||||
```mermaid
|
||||
flowchart LR
|
||||
test["tests/market.rs"] -->|通过公开 API 驱动市场| api["src/lib.rs"]
|
||||
api -->|查询和日结做市返佣| maker_rebates["src/maker_rebates.rs"]
|
||||
maker_rebates -->|只读取已收费的被动成交| maker_fills["src/maker_fee_fills.sql"]
|
||||
maker_rebates -->|定位最早待结日期| maker_due["src/maker_rebate_due.sql"]
|
||||
api -->|解析结果资产 ID| assets["src/assets.rs"]
|
||||
queries -->|解析单笔和批量报价| marks
|
||||
marks -->|拆解每个 token_id| assets
|
||||
@@ -32,6 +29,24 @@ 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
|
||||
@@ -43,17 +58,6 @@ flowchart LR
|
||||
api -->|解析写命令| cmd["src/command.rs"]
|
||||
api -->|事务内派发| market["src/market.rs"]
|
||||
api -->|解析只读查询| queries["src/catalog.rs"]
|
||||
queries -->|按账户续读订单和成交事件| accountfeed["src/account_events.rs"]
|
||||
accountfeed -->|重用活跃订单投影| acct
|
||||
accountfeed -->|重用近期成交投影| trades
|
||||
api -->|安装事件表和事务触发器| accountjournal["src/account_event_schema.sql"]
|
||||
api -->|安装签名订单索引| orderidschema["src/order_identity_schema.sql"]
|
||||
api -->|在订单序号与哈希之间查询| orderid["src/order_identity.rs"]
|
||||
orderid --> orderidschema
|
||||
accountfeed -->|有序读取已提交的事件| accountjournal
|
||||
accountjournal -->|订单、直接及互补成交| schema
|
||||
acct -->|按终态时间筛选精确订单| accountjournal
|
||||
accountfeed -->|查成交的挂单方腿| trades
|
||||
queries -->|查询各盘及赛事成交量| volume["src/volume.rs"]
|
||||
volume -->|按市场汇总普通及互补成交| volumesql["src/volume.sql"]
|
||||
volumesql -->|成交、时间及吃单方| schema
|
||||
@@ -85,18 +89,7 @@ flowchart LR
|
||||
book -->|精确扣费或退回含费余款| ledger
|
||||
queries -->|按账户或订单对账| trades["src/account_trades.rs"]
|
||||
trades -->|读取两类成交| legsql["src/account_trades.sql"]
|
||||
legsql -->|按执行号、时间或挂单方筛选| schema
|
||||
trades -->|读取交易双方的签名钱包| signedwallets["src/order_identity_schema.sql"]
|
||||
accountfeed -->|读取历史订单的签名钱包| signedwallets
|
||||
acct -->|读取订单的签名钱包| signedwallets
|
||||
api -->|持久化市场化订单,窗口结束后重新验证| delays["src/order_delay.rs"]
|
||||
delays -->|订单队列和市场延迟参数| schema
|
||||
api -->|与订单回执一起保存已验签钱包| signedwallets
|
||||
api -->|按吃单 ID 重读首次成交的金额、份额和序号| orderidentity["src/order_identity.rs"]
|
||||
orderidentity -->|查询成交上下文及两类成交| schema
|
||||
trades -->|返回结果资产| assets
|
||||
api -->|原子登记、查询和撤销钱包签发的 API key ID| accountkeys["src/account_keys.rs"]
|
||||
accountkeys -->|保存签发索引及撤销记录| schema
|
||||
queries -->|账户挂单与单笔状态| acct["src/account_orders.rs"]
|
||||
acct -->|原单类型、post-only、受理时间| terms["src/order_submission_schema.sql"]
|
||||
book -->|受理订单时保存指令| terms
|
||||
@@ -248,31 +241,48 @@ sequenceDiagram
|
||||
E-->>C: 已退出的份额移入 CLOSED,可领取金额归零
|
||||
```
|
||||
|
||||
## 按账户续读订单与成交
|
||||
## 历史持仓余额
|
||||
|
||||
`{"op":"position_balances_at","account":"alice","before_ms":1800000000000}` 查询指定毫秒之前最后确认的各结果份额。查询上限不包含 `before_ms`。数据库首次启用历史记录时,把已有可用份额与挂卖预留一起作为余额起点,返回 `history_start_ms`。更早或未来的查询会报错。
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
E["lib.rs 与 expiry.rs"] --> H["position_balance_history.rs"]
|
||||
H --> S["position_balance_history_schema.sql"]
|
||||
H --> F["position_balance_history_flush.sql"]
|
||||
F --> P["position_units"]
|
||||
```
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as 可信操作员 CLI
|
||||
participant C as JSONL 客户端
|
||||
participant E as Exchange
|
||||
participant D as SQLite
|
||||
E->>D: 写入委托、成交或撤单
|
||||
D->>D: 同事务记录受影响账户的事件
|
||||
opt 已验签订单
|
||||
E->>D: 保存订单哈希和 maker 钱包
|
||||
end
|
||||
alt 事务提交
|
||||
opt 客户端需要建立或刷新账户状态
|
||||
C->>E: account_snapshot
|
||||
E->>D: 在同一快照读取所有活跃订单、近期成交和事件游标
|
||||
E-->>C: 账户快照与续读起点
|
||||
end
|
||||
C->>E: account_events 按账户、市场和游标查询
|
||||
E->>D: 读取账户范围内序号大于游标的事件
|
||||
D-->>E: 顺序事件及下一页判断
|
||||
E-->>C: events、cursor、has_more
|
||||
else 事务回滚
|
||||
D->>D: 同时丢弃事件与对应订单变更
|
||||
end
|
||||
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 到期
|
||||
@@ -452,6 +462,51 @@ sequenceDiagram
|
||||
E-->>U: 提交后新增的赢家 YES 即可赎回
|
||||
```
|
||||
|
||||
## 组合份额与兑付
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
actor O as 操作员
|
||||
participant E as Exchange
|
||||
participant C as combo.rs
|
||||
participant D as SQLite
|
||||
O->>E: prepare_combo,提交各市场及选择结果
|
||||
E->>C: 规范化腿并生成组合 ID
|
||||
C->>D: 保存组合定义与腿
|
||||
O->>E: split_combo,抵押模拟现金
|
||||
E->>C: 铸出等量 YES 和 NO
|
||||
C->>D: 提交现金扣减、份额和流水
|
||||
O->>E: combo,查询可兑奖状态
|
||||
E->>C: 读取各腿实际裁决
|
||||
alt 任一腿兑付为零或全部腿已裁决
|
||||
O->>E: redeem_combo,指定一侧与数量
|
||||
C->>D: 扣减份额、释放抵押、写流水
|
||||
else 仍有悬而未决的腿
|
||||
E-->>O: 返回待裁决状态
|
||||
end
|
||||
```
|
||||
|
||||
## 组合 RFQ 的预留与成交
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
actor T as 请求方
|
||||
participant E as exchange / SQLite
|
||||
actor M as 报价方
|
||||
T->>E: request_combo_quote,选择方向、结果和数量
|
||||
M->>E: combo_rfq_open,再提交 quote_combo
|
||||
T->>E: accept_combo_quote
|
||||
E->>E: 原子预留双方现金或份额
|
||||
alt 报价方在期限内确认且腿仍可交易
|
||||
M->>E: respond_combo_quote,确认
|
||||
E->>E: 转让、拆分或合并,提交唯一成交
|
||||
E-->>T: FILLED
|
||||
else 拒绝、腿关闭或期限届满
|
||||
E->>E: 释放预留,保留终态
|
||||
E-->>T: FAILED 或 EXPIRED
|
||||
end
|
||||
```
|
||||
|
||||
## 开盘后出现新候选人
|
||||
|
||||
`command.rs` 和 `market.rs` 把增强型组合的定义、命名和裁决交给 `augmented.rs`。成员编号和转换沿用 `neg_risk.rs`;`schema.sql` 拦截未命名盘口的直接订单。`catalog.rs`、`assets.rs` 和 `portfolio.rs` 从同一条命名记录生成展示字段。
|
||||
@@ -705,38 +760,6 @@ sequenceDiagram
|
||||
Q-->>C: 按资产与方向返回价格,无对手报 null
|
||||
```
|
||||
|
||||
## 延迟撮合
|
||||
|
||||
操作员通过 `set_taker_delay` 配置市场延迟。提供 `seconds` 时采用体育市场的异步秒级窗口,Gamma 返回 `secondsDelay`。提供 `itode: true` 时采用 150 毫秒同步响应窗口,CLOB 市场详情返回 `itode: true`。能立即成交的已验签订单在窗口结束前进入持久化队列,期间没有盘口挂单或余额预留。到期时用最新行情和可用余额重新提交,价格、数量、费用与有效期继续由撮合链路验证。
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as CLOB 客户端
|
||||
participant A as 账户 HTTP
|
||||
participant E as Exchange
|
||||
participant D as SQLite
|
||||
C->>A: 提交签名订单
|
||||
A->>E: 验签后提交
|
||||
E->>D: 校验余额、盘口和市场
|
||||
alt 已配置延迟且订单可立即成交
|
||||
E->>D: 记录订单哈希、请求和释放时间
|
||||
alt 异步秒级窗口
|
||||
E-->>C: delayed
|
||||
A->>E: 到期检查
|
||||
E->>D: 重新校验并原子记录撮合结果
|
||||
else itode 短时等待
|
||||
E-->>A: 返回等待期限,释放账本锁
|
||||
A->>E: 150 毫秒到期后读取最终结果
|
||||
E->>D: 重新校验并原子记录撮合结果
|
||||
E-->>A: 最终下单回执
|
||||
A-->>C: 返回最终结果
|
||||
end
|
||||
else 普通订单
|
||||
E->>D: 正常提交挂单或成交
|
||||
E-->>C: 返回即时回执
|
||||
end
|
||||
```
|
||||
|
||||
## 现金余额与费用
|
||||
|
||||
```mermaid
|
||||
@@ -754,9 +777,6 @@ sequenceDiagram
|
||||
C->>E: balance 指定账户
|
||||
E->>D: 同一快照读取可用金额及有效买单的预留金额
|
||||
E-->>C: available_micros、reserved_micros、total_cash_micros
|
||||
C->>E: wallet_balance_micros 指定账户与可选资产
|
||||
E->>D: 读取可用余额与挂单预留,份额保留微单位零头
|
||||
E-->>C: 返回抵押或指定结果份额的总微单位
|
||||
```
|
||||
|
||||
## 上架步长与金额预览
|
||||
@@ -1318,8 +1338,7 @@ sequenceDiagram
|
||||
P->>D: 一次读取本页事件的全部可见子盘
|
||||
P-->>C: 按事件分组,保留子盘口顺序
|
||||
C->>P: 按结果资产或市场 ID 查盘口
|
||||
P->>D: 分别筛选 CTF 与仓位对应市场,取交集后分页
|
||||
P->>D: 查询本页父事件摘要
|
||||
P->>D: 查询匹配盘口的一页和本页父事件摘要
|
||||
P-->>C: 返回含规则、结果资产、价格和父事件的市场列表
|
||||
```
|
||||
|
||||
@@ -1380,6 +1399,24 @@ 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 另提供已定价的小计和缺价数量。
|
||||
@@ -1522,26 +1559,3 @@ sequenceDiagram
|
||||
E-->>C: 返回本次两侧销毁量和实付金额
|
||||
end
|
||||
```
|
||||
|
||||
|
||||
## 做市返佣
|
||||
|
||||
维护循环自动结算有收费成交的已结束 UTC 日期,重启后按日期补结,每轮最多处理一天。可信操作员仍可用 `settle_maker_rebates` 指定日期。每笔成交取被动单的已验证钱包,按该日开始时过去 30 天的加权成交量分档。钱包当日累计达到 1 pUSD 才入账。现金余额、发放记录和到账时间在同一事务中写入。
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant M as 维护循环
|
||||
participant E as Exchange
|
||||
participant D as SQLite
|
||||
M->>E: 查找最早待结 UTC 日
|
||||
E->>D: 取得写事务并重新检查候选日期
|
||||
opt 日期尚未日结
|
||||
E->>D: 读取收费成交、maker 与历史加权量
|
||||
E->>E: 按档位和 1 pUSD 门槛计算发放
|
||||
E->>D: 增加余额并记录返佣与到账时间
|
||||
end
|
||||
E->>D: 同事务推进后台日结进度
|
||||
E-->>M: 提交
|
||||
```
|
||||
|
||||
本地 `activity` 支持 `MAKER_REBATE`,按账户、收益日和市场汇总到账。在升级前已发放但缺少到账时间的记录仍可查询,`at_ms` 为 null。
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
BEGIN IMMEDIATE;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS account_events (
|
||||
seq INTEGER PRIMARY KEY,
|
||||
account TEXT NOT NULL REFERENCES accounts(id),
|
||||
market TEXT NOT NULL REFERENCES markets(id),
|
||||
order_seq INTEGER NOT NULL REFERENCES orders(seq),
|
||||
kind TEXT NOT NULL CHECK(kind IN ('PLACEMENT','UPDATE','CANCELLATION','TRADE')),
|
||||
at_ms INTEGER NOT NULL DEFAULT (CAST(unixepoch('subsec')*1000 AS INTEGER)),
|
||||
quantity INTEGER,
|
||||
remaining INTEGER,
|
||||
status TEXT,
|
||||
execution INTEGER
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS account_event_sequence ON account_events(account,seq);
|
||||
CREATE INDEX IF NOT EXISTS account_market_event_sequence ON account_events(account,market,seq);
|
||||
CREATE INDEX IF NOT EXISTS account_order_terminal_time ON account_events(order_seq,at_ms)
|
||||
WHERE status IN ('filled','cancelled','expired');
|
||||
|
||||
CREATE TRIGGER IF NOT EXISTS account_event_placed AFTER INSERT ON orders
|
||||
WHEN NEW.quantity>0 BEGIN
|
||||
INSERT INTO account_events(account,market,order_seq,kind,quantity,remaining,status)
|
||||
VALUES(NEW.account,NEW.market,NEW.seq,'PLACEMENT',NEW.quantity,NEW.remaining,NEW.status);
|
||||
END;
|
||||
|
||||
-- A budget buy starts at zero until available fills determine its share size.
|
||||
CREATE TRIGGER IF NOT EXISTS account_event_order_changed AFTER UPDATE OF quantity,remaining,status ON orders
|
||||
WHEN NEW.quantity>0 AND (OLD.quantity=0 OR NEW.remaining<>OLD.remaining OR NEW.status<>OLD.status) BEGIN
|
||||
INSERT INTO account_events(account,market,order_seq,kind,quantity,remaining,status)
|
||||
VALUES(NEW.account,NEW.market,NEW.seq,
|
||||
CASE WHEN OLD.quantity=0 THEN 'PLACEMENT'
|
||||
WHEN NEW.status IN ('cancelled','expired') AND NEW.status<>OLD.status THEN 'CANCELLATION'
|
||||
ELSE 'UPDATE' END,
|
||||
NEW.quantity,NEW.remaining,NEW.status);
|
||||
END;
|
||||
|
||||
-- Execution IDs are shared across the transfer and complementary-fill tables.
|
||||
CREATE TRIGGER IF NOT EXISTS account_event_trade AFTER INSERT ON execution_context BEGIN
|
||||
INSERT INTO account_events(account,market,order_seq,kind,quantity,execution)
|
||||
SELECT account,market,order_seq,'TRADE',quantity,NEW.execution
|
||||
FROM wallet_trade_legs WHERE execution=NEW.execution ORDER BY order_seq;
|
||||
END;
|
||||
|
||||
COMMIT;
|
||||
@@ -1,163 +0,0 @@
|
||||
use crate::{
|
||||
account_orders, account_trades, assets, inventory, lots, validation::identifier, Exchange,
|
||||
};
|
||||
use anyhow::{ensure, Result};
|
||||
use rusqlite::{params, Connection, Transaction};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
fn cursor(db: &Connection) -> rusqlite::Result<i64> {
|
||||
db.query_row(
|
||||
"SELECT COALESCE(MAX(seq),0) FROM account_events",
|
||||
[],
|
||||
|row| row.get(0),
|
||||
)
|
||||
}
|
||||
|
||||
impl Exchange {
|
||||
/// Current event sequence for starting a live subscription.
|
||||
pub fn account_event_cursor(&self) -> Result<i64> {
|
||||
Ok(cursor(&self.db)?)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct Snapshot {
|
||||
account: String,
|
||||
market: Option<String>,
|
||||
trade_limit: Option<u32>,
|
||||
}
|
||||
|
||||
impl Snapshot {
|
||||
pub(crate) fn read(self, db: &Transaction<'_>) -> Result<Value> {
|
||||
let trades = account_trades::Filter::recent(
|
||||
self.account.clone(),
|
||||
self.market.clone(),
|
||||
self.trade_limit,
|
||||
)
|
||||
.read(db)?;
|
||||
let orders = account_orders::all_open(db, self.account, self.market)?;
|
||||
// Take the high-water mark in the same read transaction as both projections.
|
||||
let cursor = cursor(db)?;
|
||||
Ok(
|
||||
json!({"orders":orders,"trades":trades["trades"],"trade_next_after":trades["next_after"],"cursor":cursor}),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct Request {
|
||||
account: String,
|
||||
market: Option<String>,
|
||||
#[serde(default)]
|
||||
after: i64,
|
||||
limit: Option<u32>,
|
||||
#[serde(default)]
|
||||
include_maker: bool,
|
||||
}
|
||||
|
||||
impl Request {
|
||||
pub(crate) fn read(self, db: &Connection) -> Result<Value> {
|
||||
identifier(&self.account)?;
|
||||
if let Some(market) = &self.market {
|
||||
identifier(market)?;
|
||||
}
|
||||
let limit = self.limit.unwrap_or(100);
|
||||
ensure!(
|
||||
self.after >= 0 && (1..=1000).contains(&limit),
|
||||
"invalid pagination"
|
||||
);
|
||||
let scope = if self.market.is_some() {
|
||||
"AND e.market=?4"
|
||||
} else {
|
||||
"AND ?4 IS NULL"
|
||||
};
|
||||
let sql = format!(
|
||||
"WITH page AS MATERIALIZED (
|
||||
SELECT * FROM account_events e WHERE e.account=?1 AND e.seq>?2 {scope}
|
||||
ORDER BY e.seq LIMIT ?3
|
||||
)
|
||||
SELECT e.seq,e.market,e.kind,e.at_ms,e.order_seq,e.quantity,e.remaining,e.status,
|
||||
e.execution,o.outcome,o.side,o.price,
|
||||
COALESCE(f.price, CASE WHEN p.no_order=o.seq THEN 10000-p.yes_price ELSE p.yes_price END),
|
||||
CASE WHEN c.taker_order IS NULL THEN 'AUCTION'
|
||||
WHEN c.taker_order=o.seq THEN 'TAKER' ELSE 'MAKER' END, p.kind,
|
||||
c.taker_order,s.order_type,s.created_at,d.expiration,w.maker_address,tw.maker_address
|
||||
FROM page e JOIN orders o ON o.seq=e.order_seq
|
||||
LEFT JOIN fills f ON f.seq=e.execution
|
||||
LEFT JOIN paired_fills p ON p.seq=e.execution
|
||||
LEFT JOIN execution_context c ON c.execution=e.execution
|
||||
LEFT JOIN order_submissions s ON s.order_seq=o.seq
|
||||
LEFT JOIN order_deadlines d ON d.seq=o.seq
|
||||
LEFT JOIN signed_order_wallets w ON w.order_seq=o.seq
|
||||
LEFT JOIN signed_order_wallets tw ON tw.order_seq=c.taker_order
|
||||
ORDER BY e.seq"
|
||||
);
|
||||
let mut stmt = db.prepare_cached(&sql)?;
|
||||
let mut rows = stmt.query(params![self.account, self.after, limit + 1, self.market])?;
|
||||
let mut events = Vec::new();
|
||||
let mut cursor = self.after;
|
||||
let mut has_more = false;
|
||||
while let Some(row) = rows.next()? {
|
||||
if events.len() == limit as usize {
|
||||
has_more = true;
|
||||
break;
|
||||
}
|
||||
cursor = row.get::<_, i64>(0)?;
|
||||
let market = row.get::<_, String>(1)?;
|
||||
let kind = row.get::<_, String>(2)?;
|
||||
let outcome = row.get::<_, String>(9)?;
|
||||
let at_ms = row.get::<_, i64>(3)?;
|
||||
let mut event = json!({
|
||||
"seq":cursor,"type":kind,"market":market,"asset_id":assets::id(&market,&outcome),
|
||||
"outcome":outcome,"side":row.get::<_,String>(10)?.to_ascii_uppercase(),
|
||||
"timestamp":(at_ms / 1000).to_string(),"at_ms":at_ms,"order_id":row.get::<_,i64>(4)?.to_string()
|
||||
});
|
||||
let quantity = row.get::<_, i64>(5)?;
|
||||
if kind == "TRADE" {
|
||||
let price = row.get::<_, i64>(12)?;
|
||||
event["event_type"] = json!("trade");
|
||||
let execution: i64 = row.get(8)?;
|
||||
event["id"] = json!(execution.to_string());
|
||||
if self.include_maker {
|
||||
event["maker_leg"] = json!(account_trades::maker_leg(db, execution)?);
|
||||
}
|
||||
event["status"] = json!("MATCHED_NOT_BROADCASTED");
|
||||
event["trader_side"] = json!(row.get::<_, String>(13)?);
|
||||
event["taker_order_id"] =
|
||||
json!(row.get::<_, Option<i64>>(15)?.map(|id| id.to_string()));
|
||||
event["maker_address"] = json!(row.get::<_, Option<String>>(20)?);
|
||||
event["price"] = json!(inventory::decimal(price.into(), 10_000).to_string());
|
||||
event["size"] = json!(lots::display(quantity).to_string());
|
||||
event["kind"] = json!(row
|
||||
.get::<_, Option<String>>(14)?
|
||||
.as_deref()
|
||||
.unwrap_or("transfer"));
|
||||
} else {
|
||||
let remaining = row.get::<_, i64>(6)?;
|
||||
let price = row.get::<_, i64>(11)?;
|
||||
let status = row.get::<_, String>(7)?;
|
||||
event["event_type"] = json!("order");
|
||||
event["maker_address"] = json!(row.get::<_, Option<String>>(19)?);
|
||||
event["id"] = event["order_id"].clone();
|
||||
event["status"] = json!(status.to_ascii_uppercase());
|
||||
event["price"] = json!(inventory::decimal(price.into(), 10_000).to_string());
|
||||
event["original_size"] = json!(lots::display(quantity).to_string());
|
||||
event["size_matched"] = json!(lots::display(quantity - remaining).to_string());
|
||||
event["open_size"] =
|
||||
json!(lots::display(if status == "live" { remaining } else { 0 }).to_string());
|
||||
event["order_type"] = json!(row.get::<_, Option<String>>(16)?);
|
||||
event["created_at"] = json!(row
|
||||
.get::<_, Option<i64>>(17)?
|
||||
.map(|seconds| seconds.to_string()));
|
||||
event["expiration"] = json!(row
|
||||
.get::<_, Option<i64>>(18)?
|
||||
.map(|seconds| seconds.to_string()));
|
||||
}
|
||||
events.push(event);
|
||||
}
|
||||
Ok(json!({"events":events,"cursor":cursor,"has_more":has_more}))
|
||||
}
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
use crate::{validation::identifier, Exchange};
|
||||
use anyhow::Result;
|
||||
use rusqlite::{params, OptionalExtension};
|
||||
|
||||
impl Exchange {
|
||||
/// Record the public identifier of a wallet-issued API key exactly once per nonce.
|
||||
pub fn issue_api_key(&self, issuer: &str, nonce: &[u8; 32], id: &str) -> Result<bool> {
|
||||
identifier(issuer)?;
|
||||
identifier(id)?;
|
||||
Ok(self.db.execute(
|
||||
"INSERT INTO issued_api_keys(issuer,nonce,id) VALUES(?1,?2,?3)
|
||||
ON CONFLICT(issuer,nonce) DO NOTHING",
|
||||
params![issuer, nonce.as_slice(), id],
|
||||
)? == 1)
|
||||
}
|
||||
|
||||
pub fn issued_api_key_id(&self, issuer: &str, nonce: &[u8; 32]) -> Result<Option<String>> {
|
||||
Ok(self
|
||||
.db
|
||||
.query_row(
|
||||
"SELECT k.id FROM issued_api_keys k WHERE k.issuer=?1 AND k.nonce=?2
|
||||
AND NOT EXISTS(SELECT 1 FROM revoked_api_keys r WHERE r.id=k.id)",
|
||||
params![issuer, nonce.as_slice()],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.optional()?)
|
||||
}
|
||||
|
||||
pub fn issued_api_key_scope(&self, id: &str) -> Result<Option<(String, [u8; 32])>> {
|
||||
let row: Option<(String, Vec<u8>)> = self
|
||||
.db
|
||||
.query_row(
|
||||
"SELECT k.issuer,k.nonce FROM issued_api_keys k WHERE k.id=?1
|
||||
AND NOT EXISTS(SELECT 1 FROM revoked_api_keys r WHERE r.id=k.id)",
|
||||
[id],
|
||||
|row| Ok((row.get(0)?, row.get(1)?)),
|
||||
)
|
||||
.optional()?;
|
||||
row.map(|(issuer, nonce)| {
|
||||
let nonce = nonce
|
||||
.try_into()
|
||||
.map_err(|_| anyhow::anyhow!("invalid issued API key nonce"))?;
|
||||
Ok((issuer, nonce))
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
|
||||
pub fn active_api_keys(&self, issuer: &str) -> Result<Vec<(String, [u8; 32])>> {
|
||||
let mut stmt = self.db.prepare_cached(
|
||||
"SELECT k.id,k.nonce FROM issued_api_keys k WHERE k.issuer=?1
|
||||
AND NOT EXISTS(SELECT 1 FROM revoked_api_keys r WHERE r.id=k.id) ORDER BY k.id",
|
||||
)?;
|
||||
let rows = stmt.query_map([issuer], |row| {
|
||||
Ok((row.get::<_, String>(0)?, row.get::<_, Vec<u8>>(1)?))
|
||||
})?;
|
||||
rows.map(|row| {
|
||||
let (id, nonce) = row?;
|
||||
let nonce = nonce
|
||||
.try_into()
|
||||
.map_err(|_| anyhow::anyhow!("invalid issued API key nonce"))?;
|
||||
Ok((id, nonce))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn is_issued_api_key_active(&self, id: &str) -> Result<bool> {
|
||||
Ok(self.db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM issued_api_keys k WHERE k.id=?1
|
||||
AND NOT EXISTS(SELECT 1 FROM revoked_api_keys r WHERE r.id=k.id))",
|
||||
[id],
|
||||
|row| row.get(0),
|
||||
)?)
|
||||
}
|
||||
|
||||
/// Keep the original issuance row so an old nonce cannot reactivate the key.
|
||||
pub fn revoke_issued_api_key(&self, id: &str) -> Result<bool> {
|
||||
Ok(self.db.execute(
|
||||
"INSERT INTO revoked_api_keys(id) SELECT id FROM issued_api_keys WHERE id=?1
|
||||
ON CONFLICT(id) DO NOTHING",
|
||||
[id],
|
||||
)? == 1)
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,6 @@ pub(crate) struct Filter {
|
||||
#[serde(default)]
|
||||
after: i64,
|
||||
limit: Option<u32>,
|
||||
terminal_max_age_ms: Option<i64>,
|
||||
}
|
||||
|
||||
impl Filter {
|
||||
@@ -30,22 +29,12 @@ impl Filter {
|
||||
if let Some(order) = self.order {
|
||||
ensure!(order > 0, "invalid order");
|
||||
}
|
||||
if let Some(age) = self.terminal_max_age_ms {
|
||||
ensure!(
|
||||
self.order.is_some() && age >= 0,
|
||||
"invalid terminal order window"
|
||||
);
|
||||
}
|
||||
let limit = self.limit.unwrap_or(100);
|
||||
ensure!(
|
||||
self.after >= 0 && (1..=1000).contains(&limit),
|
||||
"invalid pagination"
|
||||
);
|
||||
let (orders, next_after) = self.scan(db, Some(limit))?;
|
||||
Ok(json!({"orders":orders,"next_after":next_after}))
|
||||
}
|
||||
|
||||
fn scan(self, db: &Connection, limit: Option<u32>) -> Result<(Vec<Value>, Option<i64>)> {
|
||||
// Use the live-account index for pages and the primary key for an exact lookup.
|
||||
let scope = if self.order.is_some() {
|
||||
"seq=?6"
|
||||
@@ -57,17 +46,11 @@ impl Filter {
|
||||
(SELECT expiration FROM order_deadlines d WHERE d.seq=orders.seq),
|
||||
b.amount_cents,COALESCE((SELECT micros FROM budget_spend_micros WHERE order_seq=orders.seq),b.spent_cents*10000),
|
||||
(SELECT COALESCE(SUM(fee_micros),0) FROM execution_fees WHERE taker_order=orders.seq),
|
||||
(SELECT key_id FROM order_keys WHERE order_seq=orders.seq),s.order_type,s.post_only,s.created_at,w.maker_address
|
||||
(SELECT key_id FROM order_keys WHERE order_seq=orders.seq),s.order_type,s.post_only,s.created_at
|
||||
FROM orders LEFT JOIN budget_buys b ON b.order_seq=orders.seq
|
||||
LEFT JOIN order_submissions s ON s.order_seq=orders.seq
|
||||
LEFT JOIN signed_order_wallets w ON w.order_seq=orders.seq
|
||||
WHERE account=?1 AND (?2 IS NULL OR market=?2) AND (?3 IS NULL OR outcome=?3)
|
||||
AND seq>?4 AND {scope}
|
||||
AND (?7 IS NULL OR status='live' OR EXISTS (
|
||||
SELECT 1 FROM account_events e WHERE e.order_seq=orders.seq
|
||||
AND e.status IN ('filled','cancelled','expired')
|
||||
AND e.at_ms>=CAST(unixepoch('subsec')*1000 AS INTEGER)-?7
|
||||
)) ORDER BY seq LIMIT ?5"
|
||||
AND seq>?4 AND {scope} ORDER BY seq LIMIT ?5"
|
||||
);
|
||||
let mut stmt = db.prepare(&sql)?;
|
||||
let mut rows = stmt.query(params![
|
||||
@@ -75,15 +58,14 @@ impl Filter {
|
||||
self.market,
|
||||
self.outcome,
|
||||
self.after,
|
||||
limit.map_or(-1, |limit| i64::from(limit) + 1),
|
||||
self.order,
|
||||
self.terminal_max_age_ms
|
||||
limit + 1,
|
||||
self.order
|
||||
])?;
|
||||
let mut orders = Vec::new();
|
||||
let mut last_id = None;
|
||||
let mut next_after = None;
|
||||
while let Some(row) = rows.next()? {
|
||||
if limit.is_some_and(|limit| orders.len() == limit as usize) {
|
||||
if orders.len() == limit as usize {
|
||||
next_after = last_id;
|
||||
break;
|
||||
}
|
||||
@@ -101,29 +83,10 @@ impl Filter {
|
||||
"status":status,"expiration":row.get::<_,Option<i64>>(8)?,
|
||||
"order_type":row.get::<_,Option<String>>(13)?,"post_only":row.get::<_,Option<bool>>(14)?,
|
||||
"created_at":row.get::<_,Option<i64>>(15)?,
|
||||
"maker_address":row.get::<_,Option<String>>(16)?,
|
||||
"amount_cents":row.get::<_,Option<i64>>(9)?,"spent_cents":row.get::<_,Option<i64>>(10)?.map(|v|crate::inventory::decimal(v.into(),10000)),"fee_micros":row.get::<_,i64>(11)?,"key_id":row.get::<_,Option<String>>(12)?}),
|
||||
);
|
||||
last_id = Some(id);
|
||||
}
|
||||
Ok((orders, next_after))
|
||||
Ok(json!({"orders":orders,"next_after":next_after}))
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn all_open(
|
||||
db: &Connection,
|
||||
account: String,
|
||||
market: Option<String>,
|
||||
) -> Result<Vec<Value>> {
|
||||
let filter = Filter {
|
||||
account,
|
||||
market,
|
||||
outcome: None,
|
||||
order: None,
|
||||
after: 0,
|
||||
limit: None,
|
||||
terminal_max_age_ms: None,
|
||||
};
|
||||
let (orders, _) = filter.scan(db, None)?;
|
||||
Ok(orders)
|
||||
}
|
||||
|
||||
@@ -1,29 +1,9 @@
|
||||
use crate::{assets, validation::identifier};
|
||||
use anyhow::{ensure, Result};
|
||||
use rusqlite::{params, Connection, OptionalExtension};
|
||||
use rusqlite::{params, Connection};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
pub(crate) fn maker_leg(db: &Connection, execution: i64) -> Result<Option<Value>> {
|
||||
let mut stmt = db.prepare_cached(
|
||||
"SELECT l.order_seq,l.account,l.market,l.outcome,l.side,l.price,l.quantity,w.maker_address
|
||||
FROM wallet_trade_legs l JOIN execution_context c ON c.execution=l.execution
|
||||
LEFT JOIN signed_order_wallets w ON w.order_seq=l.order_seq
|
||||
WHERE l.execution=?1 AND l.order_seq<>c.taker_order",
|
||||
)?;
|
||||
Ok(stmt.query_row([execution], |row| {
|
||||
let market: String = row.get(2)?;
|
||||
let outcome: String = row.get(3)?;
|
||||
Ok(json!({
|
||||
"account":row.get::<_,String>(1)?,"order_id":row.get::<_,i64>(0)?.to_string(),
|
||||
"matched_amount":crate::lots::display(row.get(6)?).to_string(),
|
||||
"price":crate::inventory::decimal(i128::from(row.get::<_,i64>(5)?),10_000).to_string(),
|
||||
"asset_id":assets::id(&market,&outcome),"outcome":outcome,
|
||||
"side":row.get::<_,String>(4)?.to_ascii_uppercase(),"maker_address":row.get::<_,Option<String>>(7)?
|
||||
}))
|
||||
}).optional()?)
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct Filter {
|
||||
@@ -31,35 +11,11 @@ pub(crate) struct Filter {
|
||||
market: Option<String>,
|
||||
outcome: Option<String>,
|
||||
order: Option<i64>,
|
||||
execution: Option<i64>,
|
||||
before_s: Option<i64>,
|
||||
after_s: Option<i64>,
|
||||
maker: Option<String>,
|
||||
maker_address: Option<String>,
|
||||
#[serde(default)]
|
||||
include_maker: bool,
|
||||
after: Option<(i64, i64)>,
|
||||
limit: Option<u32>,
|
||||
}
|
||||
|
||||
impl Filter {
|
||||
pub(crate) fn recent(account: String, market: Option<String>, limit: Option<u32>) -> Self {
|
||||
Self {
|
||||
account,
|
||||
market,
|
||||
outcome: None,
|
||||
order: None,
|
||||
execution: None,
|
||||
before_s: None,
|
||||
after_s: None,
|
||||
maker: None,
|
||||
maker_address: None,
|
||||
include_maker: false,
|
||||
after: None,
|
||||
limit,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn read(self, db: &Connection) -> Result<Value> {
|
||||
identifier(&self.account)?;
|
||||
if let Some(market) = &self.market {
|
||||
@@ -74,25 +30,12 @@ impl Filter {
|
||||
if let Some(order) = self.order {
|
||||
ensure!(order > 0, "invalid order");
|
||||
}
|
||||
ensure!(self.execution.is_none_or(|id| id > 0), "invalid execution");
|
||||
ensure!(
|
||||
self.before_s.is_none_or(|n| n >= 0) && self.after_s.is_none_or(|n| n >= 0),
|
||||
"invalid trade time filter"
|
||||
);
|
||||
if let Some(maker) = &self.maker {
|
||||
identifier(maker)?;
|
||||
}
|
||||
let limit = self.limit.unwrap_or(100);
|
||||
let (execution, order) = self.after.unwrap_or((i64::MAX, i64::MAX));
|
||||
ensure!(
|
||||
(1..=1000).contains(&limit) && execution > 0 && order > 0,
|
||||
"invalid pagination"
|
||||
);
|
||||
let maker_address = self
|
||||
.maker_address
|
||||
.as_deref()
|
||||
.map(crate::order_identity::normalize_maker)
|
||||
.transpose()?;
|
||||
let mut stmt = db.prepare(include_str!("account_trades.sql"))?;
|
||||
let mut rows = stmt.query(params![
|
||||
self.account,
|
||||
@@ -101,12 +44,7 @@ impl Filter {
|
||||
self.order,
|
||||
execution,
|
||||
order,
|
||||
limit + 1,
|
||||
self.execution,
|
||||
self.before_s,
|
||||
self.after_s,
|
||||
self.maker,
|
||||
maker_address
|
||||
limit + 1
|
||||
])?;
|
||||
let mut trades = Vec::new();
|
||||
let mut last = None;
|
||||
@@ -122,17 +60,13 @@ impl Filter {
|
||||
let outcome: String = r.get(3)?;
|
||||
let price: i64 = r.get(6)?;
|
||||
let size: i64 = r.get(7)?;
|
||||
let mut trade = json!({"execution":execution,"order":order,"market":market,"outcome":outcome,
|
||||
trades.push(
|
||||
json!({"execution":execution,"order":order,"market":market,"outcome":outcome,
|
||||
"asset_id":assets::id(&market,&outcome),"side":r.get::<_,String>(4)?,
|
||||
"kind":r.get::<_,String>(5)?,"price_micros":price*100,"size":crate::lots::display(size),
|
||||
"gross_cents":crate::inventory::decimal(i128::from(price)*i128::from(size),10000),"fee_micros":r.get::<_,i64>(10)?,"at_ms":r.get::<_,Option<i64>>(8)?,
|
||||
"role":r.get::<_,Option<String>>(9)?,"taker_order":r.get::<_,Option<i64>>(11)?});
|
||||
if self.include_maker {
|
||||
trade["maker_leg"] = json!(maker_leg(db, execution)?);
|
||||
trade["taker_address"] = json!(r.get::<_, Option<String>>(12)?);
|
||||
trade["taker_account"] = json!(r.get::<_, Option<String>>(13)?);
|
||||
}
|
||||
trades.push(trade);
|
||||
"role":r.get::<_,Option<String>>(9)?}),
|
||||
);
|
||||
last = Some((execution, order));
|
||||
}
|
||||
Ok(json!({"trades":trades,"next_after":next_after}))
|
||||
|
||||
@@ -1,19 +1,8 @@
|
||||
SELECT l.execution,l.order_seq,l.market,l.outcome,l.side,l.kind,l.price,l.quantity,l.at_ms,
|
||||
CASE WHEN c.execution IS NULL THEN NULL WHEN c.taker_order IS NULL THEN 'auction'
|
||||
WHEN c.taker_order=l.order_seq THEN 'taker' ELSE 'maker' END,
|
||||
COALESCE((SELECT fee_micros FROM execution_fees WHERE execution=l.execution AND taker_order=l.order_seq),0),
|
||||
c.taker_order,tw.maker_address,t.account
|
||||
COALESCE((SELECT fee_micros FROM execution_fees WHERE execution=l.execution AND taker_order=l.order_seq),0)
|
||||
FROM wallet_trade_legs l LEFT JOIN execution_context c ON c.execution=l.execution
|
||||
LEFT JOIN signed_order_wallets tw ON tw.order_seq=c.taker_order
|
||||
LEFT JOIN orders t ON t.seq=c.taker_order
|
||||
WHERE l.account=?1 AND (?2 IS NULL OR l.market=?2) AND (?3 IS NULL OR l.outcome=?3)
|
||||
AND (?4 IS NULL OR l.order_seq=?4) AND (l.execution,l.order_seq)<(?5,?6)
|
||||
AND (?8 IS NULL OR l.execution=?8)
|
||||
AND (?9 IS NULL OR l.at_ms/1000<?9) AND (?10 IS NULL OR l.at_ms/1000>?10)
|
||||
AND ((?11 IS NULL AND ?12 IS NULL) OR EXISTS (
|
||||
SELECT 1 FROM wallet_trade_legs other
|
||||
LEFT JOIN signed_order_wallets w ON w.order_seq=other.order_seq
|
||||
WHERE other.execution=l.execution AND other.order_seq<>c.taker_order
|
||||
AND ((?12 IS NULL AND other.account=?11) OR w.maker_address=?12
|
||||
OR (w.maker_address IS NULL AND other.account=?11))))
|
||||
ORDER BY l.execution DESC,l.order_seq DESC LIMIT ?7
|
||||
|
||||
@@ -13,8 +13,6 @@ enum Kind {
|
||||
Conversion,
|
||||
Redeem,
|
||||
Deposit,
|
||||
#[serde(rename = "MAKER_REBATE")]
|
||||
MakerRebate,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
@@ -124,9 +122,6 @@ impl Filter {
|
||||
"shares":shares,"cash_delta_cents":cash_cents,"fee_micros":fee,"net_cash_delta_micros":gross-i128::from(fee),
|
||||
"side":r.get::<_,Option<String>>(12)?,"price_micros":r.get::<_,Option<i64>>(13)?.map(|p|p*100),
|
||||
"request_id":r.get::<_,Option<String>>(10)?,"execution":(source==1).then_some(seq),"order":(source==1).then_some(leg)});
|
||||
if let Some(date) = r.get::<_, Option<String>>(18)? {
|
||||
item["rebate_date"] = json!(date);
|
||||
}
|
||||
if let Some(raw) = r.get::<_, Option<String>>(17)? {
|
||||
item["amounts_micros"] = serde_json::from_str(&raw)?;
|
||||
}
|
||||
|
||||
@@ -5,24 +5,15 @@ WITH activity(source,seq,leg,at_ms,kind,market,group_id,shares,cash_delta,reques
|
||||
SELECT 1,execution,order_seq,at_ms,'TRADE',market,NULL,quantity,
|
||||
quantity*price*CASE side WHEN 'buy' THEN -1 ELSE 1 END,NULL,outcome,side,price
|
||||
FROM wallet_trade_legs WHERE account=?1
|
||||
UNION ALL
|
||||
SELECT 2,unixepoch(p.date),m.id,t.paid_at_ms,'MAKER_REBATE',p.market,NULL,NULL,
|
||||
SUM(p.micros),NULL,NULL,NULL,NULL
|
||||
FROM maker_rebate_payouts p
|
||||
JOIN market_directory_ids m ON m.market=p.market
|
||||
LEFT JOIN maker_rebate_payment_times t ON t.date=p.date
|
||||
WHERE p.account=?1 AND (?2 IS NULL OR p.market=?2)
|
||||
GROUP BY p.date,p.market,m.id,t.paid_at_ms
|
||||
)
|
||||
SELECT COALESCE(at_ms,-1) AS ts,source,seq,leg,at_ms,kind,market,group_id,shares,cash_delta,request_id,outcome,side,price,
|
||||
COALESCE((SELECT fee_micros FROM execution_fees WHERE source=1 AND execution=seq AND taker_order=leg),0),
|
||||
CASE WHEN source IN (1,2) THEN cash_delta WHEN kind='DEPOSIT' THEN (SELECT json_extract(response,'$.funded_micros')
|
||||
CASE WHEN source=1 THEN cash_delta WHEN kind='DEPOSIT' THEN (SELECT json_extract(response,'$.funded_micros')
|
||||
FROM requests WHERE id=activity.request_id) ELSE
|
||||
(SELECT cash_micros FROM precise_movements WHERE request_id=activity.request_id AND account=?1) END,
|
||||
CASE WHEN source=1 THEN shares*10000 ELSE (SELECT shares_micros FROM precise_movements WHERE request_id=activity.request_id AND account=?1) END,
|
||||
CASE WHEN kind='REDEEM' THEN (SELECT json_extract(response,'$.amounts_micros')
|
||||
FROM requests WHERE id=activity.request_id) END,
|
||||
CASE WHEN source=2 THEN date(seq,'unixepoch') END
|
||||
FROM requests WHERE id=activity.request_id) END
|
||||
FROM activity
|
||||
WHERE (?2 IS NULL OR market=?2)
|
||||
AND (?3 IS NULL OR kind IN (SELECT value FROM json_each(?3)))
|
||||
|
||||
@@ -63,12 +63,7 @@ fn record_submission(
|
||||
crate::heartbeat::record_key(tx, seq, key)
|
||||
}
|
||||
|
||||
pub(crate) fn submit(
|
||||
tx: &Transaction,
|
||||
books: &Books,
|
||||
order: NewOrder,
|
||||
admitted_before_delay: bool,
|
||||
) -> Result<ShareExecution> {
|
||||
pub(crate) fn submit(tx: &Transaction, books: &Books, order: NewOrder) -> Result<ShareExecution> {
|
||||
let NewOrder {
|
||||
market,
|
||||
account,
|
||||
@@ -115,17 +110,10 @@ pub(crate) fn submit(
|
||||
let expiration =
|
||||
expiration.ok_or_else(|| anyhow::anyhow!("GTD requires expiration"))?;
|
||||
let now: i64 = tx.query_row("SELECT unixepoch()", [], |r| r.get(0))?;
|
||||
if admitted_before_delay {
|
||||
ensure!(
|
||||
expiration > now + 60,
|
||||
"GTD order expired during taker delay"
|
||||
);
|
||||
} else {
|
||||
ensure!(
|
||||
expiration >= now + 180,
|
||||
"GTD expiration must be at least 180 seconds ahead"
|
||||
);
|
||||
}
|
||||
ensure!(
|
||||
expiration >= now + 180,
|
||||
"GTD expiration must be at least 180 seconds ahead"
|
||||
);
|
||||
Some(expiration)
|
||||
}
|
||||
_ => {
|
||||
|
||||
@@ -43,29 +43,6 @@ impl Snapshot {
|
||||
}
|
||||
}
|
||||
|
||||
/// Serialize a public book with the supplied IDs and hash that exact snapshot.
|
||||
pub fn relabel_book_snapshot(
|
||||
mut value: Value,
|
||||
market: Option<&str>,
|
||||
asset: Option<&str>,
|
||||
) -> Result<Value> {
|
||||
if market.is_none() && asset.is_none() {
|
||||
return Ok(value);
|
||||
}
|
||||
let mut snapshot = Snapshot::deserialize(&value)?;
|
||||
if let Some(market) = market {
|
||||
snapshot.market = market.to_owned();
|
||||
}
|
||||
if let Some(asset) = asset {
|
||||
snapshot.asset_id = asset.to_owned();
|
||||
}
|
||||
snapshot.set_hash()?;
|
||||
value["market"] = json!(snapshot.market);
|
||||
value["asset_id"] = json!(snapshot.asset_id);
|
||||
value["hash"] = json!(snapshot.hash);
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn build(tx: &Transaction, books: &Books, token: &str) -> Result<Snapshot> {
|
||||
let (outcome, market) = assets::parse_id(token)?;
|
||||
find(tx, books, token, outcome, market, false)?
|
||||
@@ -201,17 +178,5 @@ mod tests {
|
||||
.unwrap();
|
||||
sample.set_hash().unwrap();
|
||||
assert_eq!(sample.hash, "0458ea5755c9f73d64a14636fa5c36ed460ec394");
|
||||
let condition = format!("0x{}", "11".repeat(32));
|
||||
let mut frame = serde_json::to_value(sample).unwrap();
|
||||
frame["event_type"] = json!("book");
|
||||
let wire = relabel_book_snapshot(frame, Some(&condition), Some("1001")).unwrap();
|
||||
assert_eq!(wire["event_type"], "book");
|
||||
assert_eq!(wire["market"], condition);
|
||||
assert_eq!(wire["asset_id"], "1001");
|
||||
assert_eq!(wire["hash"], "50a0eefae2ed89e3b7b4d28645d7d87c94a004cd");
|
||||
assert_eq!(
|
||||
relabel_book_snapshot(wire.clone(), None, None).unwrap(),
|
||||
wire
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,44 +1,10 @@
|
||||
use crate::{
|
||||
book::{release, CancelReason},
|
||||
order_identity,
|
||||
validation::identifier,
|
||||
};
|
||||
use anyhow::{ensure, Result};
|
||||
use rusqlite::{params, Transaction};
|
||||
use serde_json::{json, Map, Value};
|
||||
use std::collections::HashSet;
|
||||
|
||||
pub(crate) fn by_ref(tx: &Transaction, account: &str, orders: &[String]) -> Result<Value> {
|
||||
identifier(account)?;
|
||||
ensure!(
|
||||
(1..=3000).contains(&orders.len()),
|
||||
"cancel_orders requires 1 to 3000 order IDs"
|
||||
);
|
||||
let mut resolved = HashSet::new();
|
||||
let mut canceled = Vec::new();
|
||||
let mut not_canceled = Map::new();
|
||||
for raw in orders {
|
||||
let id = order_identity::normalize_order_ref(raw)?;
|
||||
let Some((seq, status)) = order_identity::lookup(tx, account, &id)? else {
|
||||
let reason = crate::order_delay::status(tx, account, &id)?.map_or_else(
|
||||
|| "order not found".to_owned(),
|
||||
|status| format!("order is {status}"),
|
||||
);
|
||||
not_canceled.insert(id, json!(reason));
|
||||
continue;
|
||||
};
|
||||
if !resolved.insert(seq) {
|
||||
continue;
|
||||
}
|
||||
if status == "live" {
|
||||
release(tx, seq, account, CancelReason::Cancelled)?;
|
||||
canceled.push(seq);
|
||||
} else {
|
||||
not_canceled.insert(id, json!(format!("order is {status}")));
|
||||
}
|
||||
}
|
||||
Ok(json!({"canceled":canceled,"not_canceled":not_canceled}))
|
||||
}
|
||||
|
||||
pub(crate) fn by_id(tx: &Transaction, account: &str, orders: &[i64]) -> Result<Value> {
|
||||
identifier(account)?;
|
||||
@@ -103,10 +69,5 @@ pub(crate) fn in_scope(
|
||||
for order in &canceled {
|
||||
release(tx, *order, account, CancelReason::Cancelled)?;
|
||||
}
|
||||
let not_canceled: Map<String, Value> =
|
||||
crate::order_delay::pending_in_scope(tx, account, market, outcome)?
|
||||
.into_iter()
|
||||
.map(|id| (id, json!("order is delayed")))
|
||||
.collect();
|
||||
Ok(json!({"canceled":canceled,"not_canceled":not_canceled}))
|
||||
Ok(json!({"canceled":canceled,"not_canceled":{}}))
|
||||
}
|
||||
|
||||
@@ -261,6 +261,10 @@ pub(crate) enum Query {
|
||||
market: String,
|
||||
},
|
||||
Positions(crate::portfolio::Filter),
|
||||
PositionBalancesAt {
|
||||
account: String,
|
||||
before_ms: i64,
|
||||
},
|
||||
OpenInterest(crate::open_interest::Request),
|
||||
Holders(crate::holders::Request),
|
||||
Balance {
|
||||
@@ -271,8 +275,6 @@ pub(crate) enum Query {
|
||||
},
|
||||
Activity(crate::activity::Filter),
|
||||
OpenOrders(crate::account_orders::Filter),
|
||||
AccountEvents(crate::account_events::Request),
|
||||
AccountSnapshot(crate::account_events::Snapshot),
|
||||
Trades(crate::account_trades::Filter),
|
||||
PublicTrades(crate::public_trades::Request),
|
||||
BookFeed(crate::depth_feed::Request),
|
||||
@@ -296,6 +298,17 @@ pub(crate) enum Query {
|
||||
event: Option<String>,
|
||||
slug: Option<String>,
|
||||
},
|
||||
ComboRfq {
|
||||
rfq: String,
|
||||
account: String,
|
||||
},
|
||||
ComboRfqOpen {
|
||||
limit: Option<u32>,
|
||||
},
|
||||
Combo {
|
||||
combo: String,
|
||||
account: Option<String>,
|
||||
},
|
||||
History {
|
||||
market: String,
|
||||
outcome: String,
|
||||
@@ -315,6 +328,9 @@ impl Query {
|
||||
.response(),
|
||||
)
|
||||
}
|
||||
Self::ComboRfq { rfq, account } => crate::combo_rfq::read(db, &rfq, &account),
|
||||
Self::ComboRfqOpen { limit } => crate::combo_rfq::open_requests(db, limit),
|
||||
Self::Combo { combo, account } => crate::combo::read(db, &combo, account.as_deref()),
|
||||
Self::Price(request) => request.single(db),
|
||||
Self::Prices { requests } => crate::quotes::prices(db, &requests),
|
||||
Self::QuoteHistory(request) => request.read(db),
|
||||
@@ -331,10 +347,11 @@ 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::AccountEvents(request) => request.read(db),
|
||||
Self::AccountSnapshot(request) => request.read(db),
|
||||
Self::OpenOrders(filter) => filter.read(db),
|
||||
Self::BookFeed(request) => request.read(db, books),
|
||||
Self::ClobBook { token_id } => crate::book_snapshot::read(db, books, &token_id),
|
||||
|
||||
@@ -39,9 +39,6 @@ impl Exchange {
|
||||
"mts":tick.number(),"mos":inventory::decimal(minimum.into(),inventory::UNIT),
|
||||
"nr":neg_risk,"rfqe":false,"ibce":false,"oas":0});
|
||||
info["mbf"] = json!(r.get::<_, i64>(7)?);
|
||||
if r.get::<_, i64>(9)? == crate::order_delay::SYNCHRONOUS_DELAY_MS {
|
||||
info["itode"] = json!(true);
|
||||
}
|
||||
if let Some(base) = r.get::<_, Option<i64>>(8)? {
|
||||
info["tbf"] = json!(base);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
SELECT w.yes_label, w.no_label, tick.step_micros, minimum.microshares,
|
||||
COALESCE(fee.rate_ppm, 0), member.market IS NOT NULL,
|
||||
strftime('%Y-%m-%dT%H:%M:%fZ', event.scheduled_at_ms / 1000.0, 'unixepoch'), fee.maker_bps, fee.taker_bps,
|
||||
COALESCE(delay.delay_ms,0)
|
||||
strftime('%Y-%m-%dT%H:%M:%fZ', event.scheduled_at_ms / 1000.0, 'unixepoch'), fee.maker_bps, fee.taker_bps
|
||||
FROM market_wire_metadata w
|
||||
LEFT JOIN market_tick_sizes tick ON tick.market=w.market
|
||||
LEFT JOIN market_minimum_sizes minimum ON minimum.market=w.market
|
||||
@@ -9,5 +8,4 @@ JOIN market_fee_terms fee ON fee.market=w.market
|
||||
LEFT JOIN neg_risk_members member ON member.market=w.market
|
||||
LEFT JOIN sports_markets sport ON sport.market=w.market
|
||||
LEFT JOIN events event ON event.id=sport.event
|
||||
LEFT JOIN market_order_delays delay ON delay.market=w.market
|
||||
WHERE w.market=?1
|
||||
|
||||
@@ -0,0 +1,357 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,301 @@
|
||||
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
|
||||
}))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,462 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
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)
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
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
|
||||
@@ -0,0 +1,17 @@
|
||||
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
|
||||
@@ -0,0 +1,10 @@
|
||||
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
|
||||
@@ -0,0 +1,29 @@
|
||||
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
|
||||
@@ -0,0 +1,21 @@
|
||||
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;
|
||||
@@ -0,0 +1,565 @@
|
||||
use crate::{
|
||||
combo::{self, Side},
|
||||
inventory::UNIT,
|
||||
ledger,
|
||||
validation::identifier,
|
||||
};
|
||||
use anyhow::{ensure, Result};
|
||||
use rusqlite::{params, Connection, OptionalExtension, Row, Transaction};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
const REQUESTER: &str = "AWAITING_REQUESTER_ACCEPTANCE";
|
||||
const MAKER: &str = "AWAITING_MAKER_CONFIRMATION";
|
||||
const MAX_MICROS: i64 = 1_000_000_000 * UNIT;
|
||||
const DB_NOW: &str = "SELECT CAST(unixepoch('subsec')*1000 AS INTEGER)";
|
||||
|
||||
#[derive(Clone, Copy, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "UPPERCASE")]
|
||||
enum Direction {
|
||||
Buy,
|
||||
Sell,
|
||||
}
|
||||
|
||||
impl Direction {
|
||||
fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Buy => "BUY",
|
||||
Self::Sell => "SELL",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
enum Source {
|
||||
Collateral,
|
||||
Inventory,
|
||||
}
|
||||
|
||||
impl Source {
|
||||
fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Collateral => "collateral",
|
||||
Self::Inventory => "inventory",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct Request {
|
||||
combo: String,
|
||||
requester: String,
|
||||
direction: Direction,
|
||||
side: Side,
|
||||
shares_micros: Option<i64>,
|
||||
notional_micros: Option<i64>,
|
||||
submission_window_ms: Option<i64>,
|
||||
acceptance_window_ms: Option<i64>,
|
||||
last_look_ms: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct Quote {
|
||||
rfq: String,
|
||||
maker: String,
|
||||
price_micros: i64,
|
||||
shares_micros: i64,
|
||||
source: Source,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct Accept {
|
||||
rfq: String,
|
||||
requester: String,
|
||||
quote: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct Respond {
|
||||
rfq: String,
|
||||
quote: String,
|
||||
maker: String,
|
||||
confirm: bool,
|
||||
}
|
||||
|
||||
struct Rfq {
|
||||
combo: String,
|
||||
requester: String,
|
||||
direction: Direction,
|
||||
side: Side,
|
||||
size_unit: String,
|
||||
requested: i64,
|
||||
submission_deadline: i64,
|
||||
expires_at: i64,
|
||||
last_look_ms: i64,
|
||||
status: String,
|
||||
selected_quote: Option<String>,
|
||||
confirm_by: Option<i64>,
|
||||
failure: Option<String>,
|
||||
}
|
||||
|
||||
struct QuoteRow {
|
||||
id: String,
|
||||
maker: String,
|
||||
price: i64,
|
||||
shares: i64,
|
||||
cash: i64,
|
||||
source: Source,
|
||||
canceled: bool,
|
||||
}
|
||||
|
||||
fn now(db: &Connection) -> rusqlite::Result<i64> {
|
||||
db.query_row(DB_NOW, [], |r| r.get(0))
|
||||
}
|
||||
|
||||
fn window(value: Option<i64>, default: i64) -> Result<i64> {
|
||||
let ms = value.unwrap_or(default);
|
||||
ensure!((1..=300_000).contains(&ms), "invalid RFQ window");
|
||||
Ok(ms)
|
||||
}
|
||||
|
||||
fn tradable(db: &Connection, combo: &str) -> rusqlite::Result<bool> {
|
||||
db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM combo_rfq_tradable WHERE id=?)",
|
||||
[combo],
|
||||
|r| r.get(0),
|
||||
)
|
||||
}
|
||||
|
||||
fn stored_side(side: &str) -> Side {
|
||||
if side == "YES" {
|
||||
Side::Yes
|
||||
} else {
|
||||
Side::No
|
||||
}
|
||||
}
|
||||
|
||||
fn request(db: &Connection, id: &str) -> rusqlite::Result<Rfq> {
|
||||
db.query_row(
|
||||
"SELECT combo,requester,direction,outcome,size_unit,requested_micros,submission_deadline,
|
||||
expires_at,last_look_ms,status,selected_quote,confirm_by,failure
|
||||
FROM combo_rfqs WHERE id=?",
|
||||
[id],
|
||||
|r| {
|
||||
Ok(Rfq {
|
||||
combo: r.get(0)?,
|
||||
requester: r.get(1)?,
|
||||
direction: if r.get::<_, String>(2)? == "BUY" {
|
||||
Direction::Buy
|
||||
} else {
|
||||
Direction::Sell
|
||||
},
|
||||
side: stored_side(&r.get::<_, String>(3)?),
|
||||
size_unit: r.get(4)?,
|
||||
requested: r.get(5)?,
|
||||
submission_deadline: r.get(6)?,
|
||||
expires_at: r.get(7)?,
|
||||
last_look_ms: r.get(8)?,
|
||||
status: r.get(9)?,
|
||||
selected_quote: r.get(10)?,
|
||||
confirm_by: r.get(11)?,
|
||||
failure: r.get(12)?,
|
||||
})
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
const QUOTE_COLUMNS: &str =
|
||||
"SELECT id,maker,price_micros,shares_micros,cash_micros,source,canceled FROM combo_rfq_quotes";
|
||||
|
||||
fn quote_row(r: &Row<'_>) -> rusqlite::Result<QuoteRow> {
|
||||
Ok(QuoteRow {
|
||||
id: r.get(0)?,
|
||||
maker: r.get(1)?,
|
||||
price: r.get(2)?,
|
||||
shares: r.get(3)?,
|
||||
cash: r.get(4)?,
|
||||
source: if r.get::<_, String>(5)? == "collateral" {
|
||||
Source::Collateral
|
||||
} else {
|
||||
Source::Inventory
|
||||
},
|
||||
canceled: r.get(6)?,
|
||||
})
|
||||
}
|
||||
|
||||
fn quote(db: &Connection, rfq: &str, id: &str) -> rusqlite::Result<QuoteRow> {
|
||||
db.prepare_cached(&format!("{QUOTE_COLUMNS} WHERE rfq=? AND id=?"))?
|
||||
.query_row(params![rfq, id], quote_row)
|
||||
}
|
||||
|
||||
impl Request {
|
||||
pub(crate) fn apply(self, tx: &Transaction, id: &str) -> Result<Value> {
|
||||
identifier(&self.requester)?;
|
||||
ensure!(
|
||||
tradable(tx, &self.combo)?,
|
||||
"unknown combo or unavailable leg"
|
||||
);
|
||||
let (unit, size) = match (self.shares_micros, self.notional_micros, self.direction) {
|
||||
(Some(q), None, _) => ("shares", q),
|
||||
(None, Some(q), Direction::Buy) => ("notional", q),
|
||||
_ => anyhow::bail!("provide one share size or a BUY notional budget"),
|
||||
};
|
||||
ensure!((1..=MAX_MICROS).contains(&size), "invalid RFQ size");
|
||||
let submitted = now(tx)?;
|
||||
let submission_deadline = submitted + window(self.submission_window_ms, 10_000)?;
|
||||
let expires_at = submission_deadline + window(self.acceptance_window_ms, 20_000)?;
|
||||
let last_look_ms = window(self.last_look_ms, 5_000)?;
|
||||
tx.execute(
|
||||
"INSERT INTO combo_rfqs(id,combo,requester,direction,outcome,size_unit,requested_micros,
|
||||
submission_deadline,expires_at,last_look_ms,status)
|
||||
VALUES(?,?,?,?,?,?,?,?,?,?,'AWAITING_REQUESTER_ACCEPTANCE')",
|
||||
params![id,self.combo,self.requester,self.direction.name(),self.side.name(),unit,size,
|
||||
submission_deadline,expires_at,last_look_ms],
|
||||
)?;
|
||||
read(tx, id, &self.requester)
|
||||
}
|
||||
}
|
||||
|
||||
impl Quote {
|
||||
pub(crate) fn apply(self, tx: &Transaction, id: &str) -> Result<Value> {
|
||||
identifier(&self.maker)?;
|
||||
let rfq = request(tx, &self.rfq)?;
|
||||
ensure!(
|
||||
rfq.status == REQUESTER && now(tx)? < rfq.submission_deadline,
|
||||
"submission window closed"
|
||||
);
|
||||
ensure!(self.maker != rfq.requester, "no self RFQ quotes");
|
||||
ensure!(tradable(tx, &rfq.combo)?, "unavailable combo leg");
|
||||
ensure!(
|
||||
(1..UNIT).contains(&self.price_micros)
|
||||
&& (1..=MAX_MICROS).contains(&self.shares_micros),
|
||||
"invalid quote amounts"
|
||||
);
|
||||
let cash = (i128::from(self.price_micros) * i128::from(self.shares_micros)
|
||||
/ i128::from(UNIT)) as i64;
|
||||
ensure!(
|
||||
cash > 0
|
||||
&& if rfq.size_unit == "notional" {
|
||||
cash <= rfq.requested
|
||||
} else {
|
||||
self.shares_micros <= rfq.requested
|
||||
},
|
||||
"quote exceeds requested size or rounds to zero"
|
||||
);
|
||||
let candidate = QuoteRow {
|
||||
id: id.into(),
|
||||
maker: self.maker,
|
||||
price: self.price_micros,
|
||||
shares: self.shares_micros,
|
||||
cash,
|
||||
source: self.source,
|
||||
canceled: false,
|
||||
};
|
||||
let maker_funding = funding(&rfq, &candidate).1;
|
||||
maker_funding.check(tx, &rfq.combo, &candidate.maker)?;
|
||||
tx.execute(
|
||||
"INSERT INTO combo_rfq_quotes(id,rfq,maker,price_micros,shares_micros,cash_micros,source,seq)
|
||||
SELECT ?1,?2,?3,?4,?5,?6,?7,COALESCE(MAX(seq),0)+1 FROM combo_rfq_quotes WHERE rfq=?2",
|
||||
params![id,self.rfq,candidate.maker,candidate.price,candidate.shares,cash,candidate.source.name()],
|
||||
)?;
|
||||
Ok(
|
||||
json!({"rfq_id":self.rfq,"quote_id":id,"price_micros":candidate.price,
|
||||
"shares_micros":candidate.shares,"cash_micros":cash}),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
enum Funding {
|
||||
Cash(i64),
|
||||
Shares(Side, i64),
|
||||
}
|
||||
|
||||
impl Funding {
|
||||
fn check(&self, tx: &Transaction, combo: &str, account: &str) -> Result<()> {
|
||||
match *self {
|
||||
Self::Cash(amount) => {
|
||||
let (cents, remainder) = tx.query_row(
|
||||
"SELECT a.cash,COALESCE(r.micros,0) FROM accounts a
|
||||
LEFT JOIN cash_remainders r ON r.account=a.id WHERE a.id=?",
|
||||
[account],
|
||||
|r| Ok((r.get::<_, i64>(0)?, r.get::<_, i64>(1)?)),
|
||||
)?;
|
||||
ensure!(
|
||||
i128::from(cents) * 10000 + i128::from(remainder) >= i128::from(amount),
|
||||
"insufficient RFQ cash"
|
||||
);
|
||||
}
|
||||
Self::Shares(side, amount) => {
|
||||
ensure!(
|
||||
combo::balance(tx, combo, account, side)? >= amount,
|
||||
"insufficient RFQ shares"
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn reserve(self, tx: &Transaction, id: &str, combo: &str, account: &str) -> Result<()> {
|
||||
match self {
|
||||
Self::Cash(amount) => {
|
||||
ledger::cash_micros(tx, account, -amount)?;
|
||||
tx.execute(
|
||||
"INSERT INTO combo_rfq_holds(rfq,account,cash_micros) VALUES(?,?,?)",
|
||||
params![id, account, amount],
|
||||
)?;
|
||||
}
|
||||
Self::Shares(side, amount) => {
|
||||
combo::change_balance(tx, combo, account, side, -amount)?;
|
||||
tx.execute("INSERT INTO combo_rfq_holds(rfq,account,outcome,shares_micros) VALUES(?,?,?,?)",
|
||||
params![id,account,side.name(),amount])?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn funding(rfq: &Rfq, q: &QuoteRow) -> (Funding, Funding) {
|
||||
use Funding::{Cash, Shares};
|
||||
match (rfq.direction, q.source) {
|
||||
(Direction::Buy, Source::Collateral) => (Cash(q.cash), Cash(q.shares - q.cash)),
|
||||
(Direction::Buy, Source::Inventory) => (Cash(q.cash), Shares(rfq.side, q.shares)),
|
||||
(Direction::Sell, Source::Collateral) => (Shares(rfq.side, q.shares), Cash(q.cash)),
|
||||
(Direction::Sell, Source::Inventory) => (
|
||||
Shares(rfq.side, q.shares),
|
||||
Shares(rfq.side.opposite(), q.shares),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
impl Accept {
|
||||
pub(crate) fn apply(self, tx: &Transaction) -> Result<Value> {
|
||||
let rfq = request(tx, &self.rfq)?;
|
||||
ensure!(self.requester == rfq.requester, "RFQ requester mismatch");
|
||||
let now = now(tx)?;
|
||||
ensure!(
|
||||
rfq.status == REQUESTER && now < rfq.expires_at,
|
||||
"RFQ acceptance window closed"
|
||||
);
|
||||
ensure!(tradable(tx, &rfq.combo)?, "unavailable combo leg");
|
||||
let quote = quote(tx, &self.rfq, &self.quote)?;
|
||||
ensure!(!quote.canceled, "quote unavailable");
|
||||
let (requester, maker) = funding(&rfq, "e);
|
||||
requester.reserve(tx, &self.rfq, &rfq.combo, &rfq.requester)?;
|
||||
maker.reserve(tx, &self.rfq, &rfq.combo, "e.maker)?;
|
||||
tx.execute("UPDATE combo_rfqs SET status='AWAITING_MAKER_CONFIRMATION',selected_quote=?,confirm_by=? WHERE id=?",
|
||||
params![self.quote,now+rfq.last_look_ms,self.rfq])?;
|
||||
read(tx, &self.rfq, &self.requester)
|
||||
}
|
||||
}
|
||||
|
||||
fn refund(tx: &Transaction, id: &str, combo: &str) -> Result<()> {
|
||||
let mut stmt = tx.prepare_cached(
|
||||
"SELECT account,outcome,shares_micros,cash_micros FROM combo_rfq_holds WHERE rfq=?",
|
||||
)?;
|
||||
let mut rows = stmt.query([id])?;
|
||||
while let Some(r) = rows.next()? {
|
||||
let account = r.get::<_, String>(0)?;
|
||||
if let Some(side) = r.get::<_, Option<String>>(1)? {
|
||||
combo::change_balance(tx, combo, &account, stored_side(&side), r.get(2)?)?;
|
||||
} else {
|
||||
ledger::cash_micros(tx, &account, r.get(3)?)?;
|
||||
}
|
||||
}
|
||||
tx.execute("DELETE FROM combo_rfq_holds WHERE rfq=?", [id])?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl Respond {
|
||||
pub(crate) fn apply(self, tx: &Transaction, request_id: &str) -> Result<Value> {
|
||||
let rfq = request(tx, &self.rfq)?;
|
||||
let quote = quote(tx, &self.rfq, &self.quote)?;
|
||||
ensure!(quote.maker == self.maker, "RFQ maker mismatch");
|
||||
let clock = now(tx)?;
|
||||
ensure!(
|
||||
rfq.status == MAKER
|
||||
&& rfq.selected_quote.as_deref() == Some(self.quote.as_str())
|
||||
&& rfq.confirm_by.is_some_and(|by| clock < by),
|
||||
"last-look window closed"
|
||||
);
|
||||
if !self.confirm || !tradable(tx, &rfq.combo)? {
|
||||
let reason = if self.confirm {
|
||||
"LEG_UNAVAILABLE"
|
||||
} else {
|
||||
"MAKER_DECLINED"
|
||||
};
|
||||
refund(tx, &self.rfq, &rfq.combo)?;
|
||||
tx.execute(
|
||||
"UPDATE combo_rfqs SET status='FAILED',failure=? WHERE id=?",
|
||||
params![reason, self.rfq],
|
||||
)?;
|
||||
return read(tx, &self.rfq, &self.maker);
|
||||
}
|
||||
let changed = tx.execute("DELETE FROM combo_rfq_holds WHERE rfq=?", [&self.rfq])?;
|
||||
ensure!(changed == 2, "RFQ funding missing");
|
||||
let flow = settle(tx, &rfq, "e)?;
|
||||
tx.execute(
|
||||
"INSERT INTO combo_rfq_trades(rfq,quote,request_id,flow,executed_at) VALUES(?,?,?,?,?)",
|
||||
params![self.rfq, self.quote, request_id, flow, clock],
|
||||
)?;
|
||||
tx.execute(
|
||||
"UPDATE combo_rfqs SET status='FILLED' WHERE id=?",
|
||||
[&self.rfq],
|
||||
)?;
|
||||
read(tx, &self.rfq, &self.maker)
|
||||
}
|
||||
}
|
||||
|
||||
fn settle(tx: &Transaction, r: &Rfq, q: &QuoteRow) -> Result<&'static str> {
|
||||
match (r.direction, q.source) {
|
||||
(Direction::Buy, Source::Collateral) => {
|
||||
combo::change_balance(tx, &r.combo, &r.requester, r.side, q.shares)?;
|
||||
combo::change_balance(tx, &r.combo, &q.maker, r.side.opposite(), q.shares)?;
|
||||
combo::change_backing(tx, &r.combo, q.shares)?;
|
||||
Ok("MINT")
|
||||
}
|
||||
(Direction::Sell, Source::Inventory) => {
|
||||
combo::change_backing(tx, &r.combo, -q.shares)?;
|
||||
ledger::cash_micros(tx, &r.requester, q.cash)?;
|
||||
ledger::cash_micros(tx, &q.maker, q.shares - q.cash)?;
|
||||
Ok("MERGE")
|
||||
}
|
||||
(direction, _) => {
|
||||
let (buyer, seller) = match direction {
|
||||
Direction::Buy => (&r.requester, &q.maker),
|
||||
Direction::Sell => (&q.maker, &r.requester),
|
||||
};
|
||||
combo::change_balance(tx, &r.combo, buyer, r.side, q.shares)?;
|
||||
ledger::cash_micros(tx, seller, q.cash)?;
|
||||
Ok("TRANSFER")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn cancel_quote(
|
||||
tx: &Transaction,
|
||||
id: &str,
|
||||
quote_id: &str,
|
||||
maker: &str,
|
||||
) -> Result<Value> {
|
||||
let q = quote(tx, id, quote_id)?;
|
||||
ensure!(
|
||||
!q.canceled && q.maker == maker && request(tx, id)?.status == REQUESTER,
|
||||
"quote cannot be canceled"
|
||||
);
|
||||
tx.execute(
|
||||
"UPDATE combo_rfq_quotes SET canceled=1 WHERE id=?",
|
||||
[quote_id],
|
||||
)?;
|
||||
Ok(json!({"rfq_id":id,"quote_id":quote_id,"canceled":true}))
|
||||
}
|
||||
|
||||
pub(crate) fn cancel_request(tx: &Transaction, id: &str, owner: &str) -> Result<Value> {
|
||||
let r = request(tx, id)?;
|
||||
ensure!(
|
||||
r.requester == owner && r.status == REQUESTER,
|
||||
"RFQ cannot be canceled"
|
||||
);
|
||||
tx.execute("UPDATE combo_rfqs SET status='CANCELED' WHERE id=?", [id])?;
|
||||
read(tx, id, owner)
|
||||
}
|
||||
|
||||
pub(crate) fn expire(tx: &Transaction) -> Result<()> {
|
||||
let due = {
|
||||
let mut stmt = tx.prepare_cached(include_str!("combo_rfq_due.sql"))?;
|
||||
let rows = stmt.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?;
|
||||
rows.collect::<rusqlite::Result<Vec<_>>>()?
|
||||
};
|
||||
for (id, combo) in due {
|
||||
refund(tx, &id, &combo)?;
|
||||
tx.execute(
|
||||
"UPDATE combo_rfqs SET status='EXPIRED',failure='DEADLINE_ELAPSED' WHERE id=?",
|
||||
[id],
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn open_requests(db: &Connection, limit: Option<u32>) -> Result<Value> {
|
||||
let limit = limit.unwrap_or(50);
|
||||
ensure!((1..=100).contains(&limit), "invalid RFQ listing limit");
|
||||
let mut stmt=db.prepare_cached(
|
||||
"SELECT r.id,r.combo,r.direction,r.outcome,r.size_unit,r.requested_micros,r.submission_deadline,
|
||||
c.canonical_legs
|
||||
FROM combo_rfqs r JOIN combo_rfq_tradable c ON c.id=r.combo
|
||||
WHERE r.status='AWAITING_REQUESTER_ACCEPTANCE'
|
||||
AND r.submission_deadline>CAST(unixepoch('subsec')*1000 AS INTEGER)
|
||||
ORDER BY r.submission_deadline,r.id LIMIT ?",
|
||||
)?;
|
||||
let mut result = Vec::new();
|
||||
let mut rows = stmt.query([limit])?;
|
||||
while let Some(r) = rows.next()? {
|
||||
let legs: Value = serde_json::from_str(&r.get::<_, String>(7)?)?;
|
||||
result.push(json!({
|
||||
"rfq_id":r.get::<_,String>(0)?,"combo":r.get::<_,String>(1)?,
|
||||
"direction":r.get::<_,String>(2)?,"side":r.get::<_,String>(3)?,
|
||||
"requested_size":{"unit":r.get::<_,String>(4)?,"value_micros":r.get::<_,i64>(5)?},
|
||||
"submission_deadline":r.get::<_,i64>(6)?,"legs":legs
|
||||
}));
|
||||
}
|
||||
Ok(json!({"rfqs":result}))
|
||||
}
|
||||
|
||||
pub(crate) fn read(db: &Connection, id: &str, viewer: &str) -> Result<Value> {
|
||||
let r = request(db, id)?;
|
||||
let owner = r.requester == viewer;
|
||||
let quoted: bool = db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM combo_rfq_quotes WHERE rfq=? AND maker=?)",
|
||||
params![id, viewer],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
ensure!(owner || quoted, "RFQ not visible to account");
|
||||
let ranks = if matches!(r.direction, Direction::Buy) {
|
||||
"ASC"
|
||||
} else {
|
||||
"DESC"
|
||||
};
|
||||
let mut stmt = db.prepare_cached(&format!(
|
||||
"{QUOTE_COLUMNS} WHERE rfq=?1 AND (?2 OR maker=?3) AND canceled=0
|
||||
ORDER BY price_micros {ranks},shares_micros DESC,seq"
|
||||
))?;
|
||||
let quotes = stmt
|
||||
.query_map(params![id, owner, viewer], quote_row)?
|
||||
.map(|q| {
|
||||
q.map(|q| {
|
||||
json!({"quote_id":q.id,"maker":q.maker,"price_micros":q.price,
|
||||
"shares_micros":q.shares,"cash_micros":q.cash,"source":q.source})
|
||||
})
|
||||
})
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
let selected = r.selected_quote.filter(|id| {
|
||||
owner
|
||||
|| quotes
|
||||
.iter()
|
||||
.any(|q| q["quote_id"].as_str() == Some(id.as_str()))
|
||||
});
|
||||
let fill = if selected.is_some() && r.status == "FILLED" {
|
||||
db.query_row(
|
||||
"SELECT t.executed_at,t.flow,q.price_micros,q.shares_micros,q.cash_micros
|
||||
FROM combo_rfq_trades t JOIN combo_rfq_quotes q ON q.id=t.quote WHERE t.rfq=?",
|
||||
[id],
|
||||
|r| {
|
||||
Ok(
|
||||
json!({"executed_at":r.get::<_,i64>(0)?,"flow":r.get::<_,String>(1)?,
|
||||
"price_micros":r.get::<_,i64>(2)?,"shares_micros":r.get::<_,i64>(3)?,
|
||||
"cash_micros":r.get::<_,i64>(4)?}),
|
||||
)
|
||||
},
|
||||
)
|
||||
.optional()?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok(json!({
|
||||
"rfq_id":id,"combo":r.combo,"direction":r.direction,"side":r.side,"status":r.status,
|
||||
"requested_size":{"unit":r.size_unit,"value_micros":r.requested},
|
||||
"submission_deadline":r.submission_deadline,"expires_at":r.expires_at,"quotes":quotes,
|
||||
"confirm_by":r.confirm_by.filter(|_|selected.is_some()),"selected_quote":selected,
|
||||
"failure":r.failure,"fill":fill
|
||||
}))
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
SELECT id,combo FROM combo_rfqs
|
||||
WHERE (status='AWAITING_REQUESTER_ACCEPTANCE' AND expires_at<=CAST(unixepoch('subsec')*1000 AS INTEGER))
|
||||
OR (status='AWAITING_MAKER_CONFIRMATION' AND confirm_by<=CAST(unixepoch('subsec')*1000 AS INTEGER))
|
||||
@@ -0,0 +1,65 @@
|
||||
BEGIN IMMEDIATE;
|
||||
CREATE TABLE IF NOT EXISTS combo_rfqs (
|
||||
id TEXT PRIMARY KEY REFERENCES requests(id) DEFERRABLE INITIALLY DEFERRED,
|
||||
combo TEXT NOT NULL REFERENCES combo_conditions(id),
|
||||
requester TEXT NOT NULL REFERENCES accounts(id),
|
||||
direction TEXT NOT NULL CHECK(direction IN ('BUY','SELL')),
|
||||
outcome TEXT NOT NULL CHECK(outcome IN ('YES','NO')),
|
||||
size_unit TEXT NOT NULL CHECK(size_unit IN ('shares','notional')),
|
||||
requested_micros INTEGER NOT NULL CHECK(requested_micros>0),
|
||||
submission_deadline INTEGER NOT NULL,
|
||||
expires_at INTEGER NOT NULL,
|
||||
last_look_ms INTEGER NOT NULL,
|
||||
status TEXT NOT NULL CHECK(status IN (
|
||||
'AWAITING_REQUESTER_ACCEPTANCE','AWAITING_MAKER_CONFIRMATION','FILLED','FAILED','EXPIRED','CANCELED'
|
||||
)),
|
||||
selected_quote TEXT,
|
||||
confirm_by INTEGER,
|
||||
failure TEXT,
|
||||
FOREIGN KEY(id,selected_quote) REFERENCES combo_rfq_quotes(rfq,id)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS combo_rfq_open_deadline ON combo_rfqs(expires_at)
|
||||
WHERE status='AWAITING_REQUESTER_ACCEPTANCE';
|
||||
CREATE INDEX IF NOT EXISTS combo_rfq_last_look ON combo_rfqs(confirm_by)
|
||||
WHERE status='AWAITING_MAKER_CONFIRMATION';
|
||||
CREATE TABLE IF NOT EXISTS combo_rfq_quotes (
|
||||
id TEXT PRIMARY KEY REFERENCES requests(id) DEFERRABLE INITIALLY DEFERRED,
|
||||
rfq TEXT NOT NULL REFERENCES combo_rfqs(id),
|
||||
maker TEXT NOT NULL REFERENCES accounts(id),
|
||||
price_micros INTEGER NOT NULL CHECK(price_micros BETWEEN 1 AND 999999),
|
||||
shares_micros INTEGER NOT NULL CHECK(shares_micros>0),
|
||||
cash_micros INTEGER NOT NULL CHECK(cash_micros>0),
|
||||
source TEXT NOT NULL CHECK(source IN ('collateral','inventory')),
|
||||
canceled INTEGER NOT NULL DEFAULT 0 CHECK(canceled IN (0,1)),
|
||||
seq INTEGER NOT NULL,
|
||||
UNIQUE(rfq,id),
|
||||
UNIQUE(rfq,seq)
|
||||
);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS combo_rfq_live_maker_quote ON combo_rfq_quotes(rfq,maker)
|
||||
WHERE canceled=0;
|
||||
CREATE TABLE IF NOT EXISTS combo_rfq_holds (
|
||||
rfq TEXT NOT NULL REFERENCES combo_rfqs(id),
|
||||
account TEXT NOT NULL REFERENCES accounts(id),
|
||||
outcome TEXT CHECK(outcome IN ('YES','NO')),
|
||||
shares_micros INTEGER NOT NULL DEFAULT 0 CHECK(shares_micros>=0),
|
||||
cash_micros INTEGER NOT NULL DEFAULT 0 CHECK(cash_micros>=0),
|
||||
PRIMARY KEY(rfq,account),
|
||||
CHECK((outcome IS NULL AND shares_micros=0 AND cash_micros>0)
|
||||
OR (outcome IS NOT NULL AND shares_micros>0 AND cash_micros=0))
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS combo_rfq_holds_account ON combo_rfq_holds(account);
|
||||
CREATE INDEX IF NOT EXISTS combo_rfq_by_condition ON combo_rfqs(combo);
|
||||
CREATE TABLE IF NOT EXISTS combo_rfq_trades (
|
||||
rfq TEXT PRIMARY KEY REFERENCES combo_rfqs(id),
|
||||
quote TEXT NOT NULL REFERENCES combo_rfq_quotes(id),
|
||||
request_id TEXT NOT NULL UNIQUE REFERENCES requests(id) DEFERRABLE INITIALLY DEFERRED,
|
||||
flow TEXT NOT NULL CHECK(flow IN ('TRANSFER','MINT','MERGE')),
|
||||
executed_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE VIEW IF NOT EXISTS combo_rfq_tradable AS
|
||||
SELECT c.id,c.canonical_legs FROM combo_conditions c
|
||||
WHERE NOT EXISTS(SELECT 1 FROM combo_legs l JOIN markets m ON m.id=l.market
|
||||
LEFT JOIN market_visibility v ON v.market=m.id
|
||||
WHERE l.combo=c.id AND (m.phase NOT IN ('preopen','continuous')
|
||||
OR COALESCE(v.active,1)=0 OR COALESCE(v.archived,0)=1));
|
||||
COMMIT;
|
||||
@@ -0,0 +1,34 @@
|
||||
BEGIN IMMEDIATE;
|
||||
CREATE TABLE IF NOT EXISTS combo_conditions (
|
||||
id TEXT PRIMARY KEY,
|
||||
canonical_legs TEXT NOT NULL UNIQUE,
|
||||
collateral_micros INTEGER NOT NULL DEFAULT 0 CHECK(collateral_micros>=0),
|
||||
rounding_dust_micros INTEGER NOT NULL DEFAULT 0 CHECK(rounding_dust_micros>=0)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS combo_legs (
|
||||
combo TEXT NOT NULL REFERENCES combo_conditions(id),
|
||||
market TEXT NOT NULL REFERENCES markets(id),
|
||||
outcome TEXT NOT NULL CHECK(outcome IN ('YES','NO')),
|
||||
PRIMARY KEY(combo,market)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS combo_balances (
|
||||
combo TEXT NOT NULL REFERENCES combo_conditions(id),
|
||||
account TEXT NOT NULL REFERENCES accounts(id),
|
||||
outcome TEXT NOT NULL CHECK(outcome IN ('YES','NO')),
|
||||
shares_micros INTEGER NOT NULL CHECK(shares_micros>0),
|
||||
PRIMARY KEY(combo,account,outcome)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS combo_movements (
|
||||
seq INTEGER PRIMARY KEY,
|
||||
request_id TEXT NOT NULL UNIQUE REFERENCES requests(id) DEFERRABLE INITIALLY DEFERRED,
|
||||
combo TEXT NOT NULL REFERENCES combo_conditions(id),
|
||||
account TEXT NOT NULL REFERENCES accounts(id),
|
||||
kind TEXT NOT NULL CHECK(kind IN ('SPLIT','MERGE','REDEEM')),
|
||||
outcome TEXT CHECK(outcome IN ('YES','NO')),
|
||||
shares_micros INTEGER NOT NULL CHECK(shares_micros>0),
|
||||
cash_delta_micros INTEGER NOT NULL,
|
||||
at_ms INTEGER NOT NULL DEFAULT(CAST(unixepoch('subsec')*1000 AS INTEGER)),
|
||||
CHECK((kind='REDEEM')=(outcome IS NOT NULL))
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS combo_movements_by_account ON combo_movements(account,at_ms,seq);
|
||||
COMMIT;
|
||||
@@ -3,10 +3,6 @@ use serde::Deserialize;
|
||||
#[derive(Deserialize)]
|
||||
#[serde(tag = "op", rename_all = "lowercase", deny_unknown_fields)]
|
||||
pub(crate) enum Command {
|
||||
#[serde(rename = "settle_maker_rebates")]
|
||||
SettleMakerRebates {
|
||||
date: String,
|
||||
},
|
||||
Fund {
|
||||
account: String,
|
||||
cents: Option<i64>,
|
||||
@@ -27,12 +23,6 @@ pub(crate) enum Command {
|
||||
},
|
||||
#[serde(rename = "tick_size_change")]
|
||||
TickSizeChange(crate::tick_changes::Change),
|
||||
#[serde(rename = "set_taker_delay")]
|
||||
SetTakerDelay {
|
||||
market: String,
|
||||
seconds: Option<u32>,
|
||||
itode: Option<bool>,
|
||||
},
|
||||
List {
|
||||
market: String,
|
||||
slug: Option<String>,
|
||||
@@ -46,6 +36,35 @@ pub(crate) enum Command {
|
||||
listing: Option<crate::catalog::Listing>,
|
||||
resolution: Option<crate::resolution::Policy>,
|
||||
},
|
||||
#[serde(rename = "prepare_combo")]
|
||||
PrepareCombo {
|
||||
legs: Vec<crate::combo::Leg>,
|
||||
},
|
||||
#[serde(rename = "split_combo")]
|
||||
SplitCombo(crate::combo::Amount),
|
||||
#[serde(rename = "merge_combo")]
|
||||
MergeCombo(crate::combo::Amount),
|
||||
#[serde(rename = "redeem_combo")]
|
||||
RedeemCombo(crate::combo::Redemption),
|
||||
#[serde(rename = "request_combo_quote")]
|
||||
RequestComboQuote(crate::combo_rfq::Request),
|
||||
#[serde(rename = "quote_combo")]
|
||||
QuoteCombo(crate::combo_rfq::Quote),
|
||||
#[serde(rename = "accept_combo_quote")]
|
||||
AcceptComboQuote(crate::combo_rfq::Accept),
|
||||
#[serde(rename = "respond_combo_quote")]
|
||||
RespondComboQuote(crate::combo_rfq::Respond),
|
||||
#[serde(rename = "cancel_combo_quote")]
|
||||
CancelComboQuote {
|
||||
rfq: String,
|
||||
quote: String,
|
||||
maker: String,
|
||||
},
|
||||
#[serde(rename = "cancel_combo_rfq")]
|
||||
CancelComboRfq {
|
||||
rfq: String,
|
||||
requester: String,
|
||||
},
|
||||
#[serde(rename = "define_neg_risk")]
|
||||
DefineNegRisk {
|
||||
group: String,
|
||||
@@ -140,11 +159,6 @@ pub(crate) enum Command {
|
||||
account: String,
|
||||
orders: Vec<i64>,
|
||||
},
|
||||
#[serde(rename = "cancel_order_refs")]
|
||||
CancelOrderRefs {
|
||||
account: String,
|
||||
orders: Vec<String>,
|
||||
},
|
||||
#[serde(rename = "cancel_market_orders")]
|
||||
CancelMarketOrders {
|
||||
account: String,
|
||||
|
||||
@@ -10,14 +10,14 @@ pub(crate) fn transaction(
|
||||
) -> Result<Transaction<'_>> {
|
||||
loop {
|
||||
let tx = Transaction::new_unchecked(db, behavior)?;
|
||||
let due: bool = tx.query_row(
|
||||
let due: bool = tx.prepare_cached(concat!(
|
||||
"SELECT EXISTS(SELECT 1 FROM order_deadlines WHERE pending=1 AND expiration<=unixepoch()+60)
|
||||
OR EXISTS(SELECT 1 FROM twap_markets WHERE pending_close=1 AND end_at<=unixepoch())
|
||||
OR EXISTS(SELECT 1 FROM order_heartbeats WHERE deadline_ms<=CAST(unixepoch('subsec')*1000 AS INTEGER))
|
||||
OR EXISTS(SELECT 1 FROM sports_kickoffs WHERE cleared_at_ms IS NULL AND due_ms<=CAST(unixepoch('subsec')*1000 AS INTEGER))
|
||||
OR EXISTS(SELECT 1 FROM quote_pending)",
|
||||
[], |row| row.get(0),
|
||||
)?;
|
||||
OR EXISTS(SELECT 1 FROM quote_pending) OR EXISTS(",
|
||||
include_str!("combo_rfq_due.sql"), ")",
|
||||
))?.query_row([], |row| row.get(0))?;
|
||||
if !due {
|
||||
return Ok(tx);
|
||||
}
|
||||
@@ -49,8 +49,10 @@ 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()?;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -75,7 +75,7 @@ pub(super) fn market(row: &Row<'_>) -> rusqlite::Result<Value> {
|
||||
"outcomes":json!([row.get::<_,String>("yes_label")?,row.get::<_,String>("no_label")?]).to_string(),
|
||||
"clobTokenIds":json!([assets::id(&key,"YES"),assets::id(&key,"NO")]).to_string(),
|
||||
"active":row.get::<_,bool>("active")?,"archived":row.get::<_,bool>("archived")?,"enableOrderBook":true,"acceptingOrders":accepts,"closed":!accepts,
|
||||
"secondsDelay":row.get::<_,i64>("seconds_delay")?,"orderPriceMinTickSize":tick.number(),"orderMinSize":inventory::decimal(size.into(),inventory::UNIT),
|
||||
"orderPriceMinTickSize":tick.number(),"orderMinSize":inventory::decimal(size.into(),inventory::UNIT),
|
||||
"groupItemTitle":row.get::<_,Option<String>>("group_title")?,
|
||||
"bestBid":bid.map(dollars),"bestAsk":ask.map(dollars),"lastTradePrice":last.map(dollars),"outcomePrices":prices,
|
||||
"makerBaseFee":row.get::<_,i64>("maker_bps")?,"takerBaseFee":row.get::<_,Option<i64>>("taker_bps")?,
|
||||
|
||||
@@ -19,7 +19,6 @@ struct Filters {
|
||||
slugs: Vec<String>,
|
||||
conditions: Vec<String>,
|
||||
tokens: Vec<String>,
|
||||
positions: Vec<String>,
|
||||
closed: Option<bool>,
|
||||
active: Option<bool>,
|
||||
order: String,
|
||||
@@ -77,9 +76,6 @@ impl Filters {
|
||||
"clob_token_ids" if markets && !value.trim().is_empty() => {
|
||||
f.tokens.push(value.clone())
|
||||
}
|
||||
"position_ids" if markets && !value.trim().is_empty() => {
|
||||
f.positions.push(value.clone())
|
||||
}
|
||||
_ => return Err(invalid(key)),
|
||||
}
|
||||
}
|
||||
@@ -88,7 +84,6 @@ impl Filters {
|
||||
f.slugs.len(),
|
||||
f.conditions.len(),
|
||||
f.tokens.len(),
|
||||
f.positions.len(),
|
||||
];
|
||||
if markets && sizes.iter().any(|n| *n > 100) {
|
||||
return Err(invalid("at most 100 values per identifier filter"));
|
||||
@@ -135,25 +130,22 @@ const MARKET_FILTER: &str = "
|
||||
AND (?3='[]' OR w.market IN (SELECT value FROM json_each(?3)))
|
||||
AND (?4 IS NULL OR w.market IN (SELECT value FROM json_each(?4)))
|
||||
AND (?5 IS NULL OR (m.phase NOT IN ('preopen','continuous'))=?5)
|
||||
AND (?8 IS NULL OR COALESCE(v.active,1)=?8)
|
||||
AND (?9 IS NULL OR w.market IN (SELECT value FROM json_each(?9)))";
|
||||
AND (?8 IS NULL OR COALESCE(v.active,1)=?8)";
|
||||
const EVENT_FILTER: &str = "
|
||||
WHERE (?1='[]' OR e.event_id IN (SELECT value FROM json_each(?1)))
|
||||
AND (?2='[]' OR e.slug IN (SELECT value FROM json_each(?2)))
|
||||
AND (?3 IS NULL OR e.closed=?3)";
|
||||
|
||||
// An unknown asset matches nothing. An omitted family does not filter the list.
|
||||
fn asset_markets(tokens: &[String]) -> Option<String> {
|
||||
(!tokens.is_empty()).then(|| {
|
||||
let keys: Vec<_> = tokens
|
||||
fn markets(db: &Connection, f: &Filters, order: &str) -> rusqlite::Result<Vec<Value>> {
|
||||
// A supplied set containing only foreign tokens must match nothing.
|
||||
let token_markets = (!f.tokens.is_empty()).then(|| {
|
||||
let keys: Vec<_> = f
|
||||
.tokens
|
||||
.iter()
|
||||
.filter_map(|token| assets::parse_id(token).ok().map(|(_, market)| market))
|
||||
.collect();
|
||||
json!(keys).to_string()
|
||||
})
|
||||
}
|
||||
|
||||
fn markets(db: &Connection, f: &Filters, order: &str) -> rusqlite::Result<Vec<Value>> {
|
||||
});
|
||||
let sql = format!(
|
||||
"{}{MARKET_FILTER} ORDER BY {order} LIMIT ?6 OFFSET ?7",
|
||||
include_str!("gamma_market.sql")
|
||||
@@ -165,12 +157,11 @@ fn markets(db: &Connection, f: &Filters, order: &str) -> rusqlite::Result<Vec<Va
|
||||
json!(f.ids).to_string(),
|
||||
json!(f.slugs).to_string(),
|
||||
json!(f.conditions).to_string(),
|
||||
asset_markets(&f.tokens),
|
||||
token_markets,
|
||||
f.closed,
|
||||
f.limit,
|
||||
f.offset,
|
||||
f.active,
|
||||
asset_markets(&f.positions)
|
||||
f.active
|
||||
],
|
||||
|r| Ok((market(r)?, r.get::<_, Option<String>>("parent")?)),
|
||||
)?
|
||||
|
||||
@@ -3,11 +3,10 @@ SELECT w.market, w.id, w.slug, w.question, w.yes_label, w.no_label, m.rules, m.p
|
||||
COALESCE(s.source,t.source) AS source, COALESCE(s.event,t.event) AS parent,
|
||||
COALESCE(a.name,t.group_title) AS group_title,
|
||||
tick.step_micros, minimum.microshares, member.market IS NOT NULL AS neg_risk,
|
||||
COALESCE(fee.rate_ppm,0)>0 AS fees_enabled, fee.maker_bps, fee.taker_bps, COALESCE(v.active,1) AS active, COALESCE(v.archived,0) AS archived, COALESCE(delay.delay_ms/1000,0) AS seconds_delay
|
||||
COALESCE(fee.rate_ppm,0)>0 AS fees_enabled, fee.maker_bps, fee.taker_bps, COALESCE(v.active,1) AS active, COALESCE(v.archived,0) AS archived
|
||||
FROM market_wire_metadata w
|
||||
JOIN markets m ON m.id=w.market
|
||||
LEFT JOIN market_visibility v ON v.market=w.market
|
||||
LEFT JOIN market_order_delays delay ON delay.market=w.market
|
||||
LEFT JOIN sports_markets s ON s.market=w.market
|
||||
LEFT JOIN topic_markets t ON t.market=w.market
|
||||
LEFT JOIN augmented_outcomes a ON a.market=w.market
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use anyhow::{ensure, Result};
|
||||
use rusqlite::{params, Connection, OptionalExtension, Transaction};
|
||||
use rusqlite::{params, Connection, Transaction};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
pub(crate) fn cash(tx: &Transaction, account: &str, delta: i64) -> Result<()> {
|
||||
@@ -31,46 +31,24 @@ pub(crate) fn cash_micros(tx: &Transaction, account: &str, delta: i64) -> Result
|
||||
}
|
||||
|
||||
pub(crate) fn balance(db: &Connection, account: &str) -> Result<Value> {
|
||||
let (available, reserved) =
|
||||
cash_balance(db, account)?.ok_or(rusqlite::Error::QueryReturnedNoRows)?;
|
||||
crate::validation::identifier(account)?;
|
||||
let (cash, remainder, reserved, rfq_reserved): (i64, i64, i64, i64) = db.query_row(
|
||||
"SELECT a.cash,COALESCE(r.micros,0),
|
||||
(SELECT COALESCE(SUM(price*remaining),0) FROM orders
|
||||
WHERE account=a.id AND side='buy' AND status='live'),
|
||||
(SELECT COALESCE(SUM(cash_micros),0) FROM combo_rfq_holds WHERE account=a.id)
|
||||
FROM accounts a LEFT JOIN cash_remainders r ON r.account=a.id WHERE a.id=?",
|
||||
[account],
|
||||
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)),
|
||||
)?;
|
||||
let available = i128::from(cash) * 10000 + i128::from(remainder);
|
||||
let reserved = i128::from(reserved) + i128::from(rfq_reserved);
|
||||
Ok(
|
||||
json!({"account":account, "available_micros":available, "reserved_micros":reserved,
|
||||
"total_cash_micros":available+reserved}),
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn cash_balance(db: &Connection, account: &str) -> Result<Option<(i128, i128)>> {
|
||||
crate::validation::identifier(account)?;
|
||||
let value = 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')
|
||||
FROM accounts a LEFT JOIN cash_remainders r ON r.account=a.id WHERE a.id=?",
|
||||
[account],
|
||||
|r| {
|
||||
let cash = i128::from(r.get::<_, i64>(0)?);
|
||||
let remainder = i128::from(r.get::<_, i64>(1)?);
|
||||
let reserved = i128::from(r.get::<_, i64>(2)?);
|
||||
Ok((cash * 10000 + remainder, reserved))
|
||||
},
|
||||
)
|
||||
.optional()?;
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
pub(crate) fn total_position_micros(db: &Connection, account: &str, asset: &str) -> Result<i128> {
|
||||
crate::validation::identifier(account)?;
|
||||
let (outcome, market) = crate::assets::parse_id(asset)?;
|
||||
Ok(db.query_row(
|
||||
"SELECT COALESCE(u.available,0),COALESCE(u.reserved,0)
|
||||
FROM markets m LEFT JOIN position_units u
|
||||
ON u.market=m.id AND u.outcome=?2 AND u.account=?3 WHERE m.id=?1",
|
||||
params![market, outcome, account],
|
||||
|row| Ok(i128::from(row.get::<_, i64>(0)?) + i128::from(row.get::<_, i64>(1)?)),
|
||||
)?)
|
||||
}
|
||||
|
||||
pub(crate) fn position(
|
||||
tx: &Transaction,
|
||||
account: &str,
|
||||
|
||||
+48
-138
@@ -1,11 +1,12 @@
|
||||
mod account_events;
|
||||
mod account_keys;
|
||||
mod account_orders;
|
||||
mod account_trades;
|
||||
mod activity;
|
||||
mod assets;
|
||||
mod augmented;
|
||||
mod catalog;
|
||||
mod combo;
|
||||
mod combo_portfolio;
|
||||
mod combo_rfq;
|
||||
mod depth_feed;
|
||||
mod estimate;
|
||||
mod expiry;
|
||||
@@ -20,7 +21,6 @@ mod volume;
|
||||
use validation::identifier;
|
||||
mod book;
|
||||
mod book_snapshot;
|
||||
pub use book_snapshot::relabel_book_snapshot;
|
||||
mod cancellation;
|
||||
mod clarifications;
|
||||
mod clob_market;
|
||||
@@ -30,16 +30,14 @@ mod kickoff;
|
||||
mod last_trades;
|
||||
mod ledger;
|
||||
mod lots;
|
||||
mod maker_rebates;
|
||||
mod market;
|
||||
mod market_amounts;
|
||||
mod market_stream;
|
||||
mod minimum_size;
|
||||
mod neg_risk;
|
||||
mod open_interest;
|
||||
mod order_delay;
|
||||
mod order_identity;
|
||||
mod portfolio;
|
||||
mod position_balance_history;
|
||||
mod prices_history;
|
||||
mod public_trades;
|
||||
mod quotes;
|
||||
@@ -55,19 +53,18 @@ 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 order_delay::SynchronousPlacement;
|
||||
pub use order_identity::{normalize_order_ref, SubmissionFills};
|
||||
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;
|
||||
pub use quotes::{PriceQueryError, PriceRequest, PriceSide};
|
||||
pub use resolution::http::ResolutionQuery;
|
||||
pub use validation::ConditionList;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum MarketDataError {
|
||||
@@ -136,6 +133,27 @@ 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),
|
||||
@@ -144,20 +162,14 @@ impl Exchange {
|
||||
db.execute_batch(include_str!("valuation_schema.sql"))?;
|
||||
}
|
||||
lots::migrate(&mut db)?;
|
||||
let account_events_ready: bool = db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='index' AND name='account_order_terminal_time')",
|
||||
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 !account_events_ready {
|
||||
db.execute_batch(include_str!("account_event_schema.sql"))?;
|
||||
}
|
||||
let signed_orders_ready: bool = db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='table' AND name='signed_order_wallets')",
|
||||
[], |row| row.get(0),
|
||||
)?;
|
||||
if !signed_orders_ready {
|
||||
db.execute_batch(include_str!("order_identity_schema.sql"))?;
|
||||
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 {
|
||||
@@ -184,7 +196,6 @@ impl Exchange {
|
||||
|
||||
/// Run expiry and synchronize the resident book while the transport is idle.
|
||||
pub fn maintain(&mut self) -> Result<()> {
|
||||
self.maintain_maker_rebates()?;
|
||||
let tx = expiry::transaction(&self.db, TransactionBehavior::Deferred)?;
|
||||
let changes = self.books.changes(&tx)?;
|
||||
tx.commit()?;
|
||||
@@ -192,20 +203,6 @@ impl Exchange {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Check for timed-out API sessions without refreshing books while none are due.
|
||||
pub fn maintain_due_heartbeats(&mut self) -> Result<()> {
|
||||
let due: bool = self.db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM order_heartbeats
|
||||
WHERE deadline_ms<=CAST(unixepoch('subsec')*1000 AS INTEGER))",
|
||||
[],
|
||||
|row| row.get(0),
|
||||
)?;
|
||||
if due {
|
||||
self.maintain()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Time until the next pending GTD stops trading, measured on the database clock.
|
||||
pub fn next_gtd_expiry(&self) -> Result<Option<Duration>> {
|
||||
let (first, now): (Option<i64>, i64) = self.db.query_row(
|
||||
@@ -243,36 +240,7 @@ impl Exchange {
|
||||
Ok(page)
|
||||
}
|
||||
|
||||
/// Gross wallet balance in millionths, including quantities reserved by live orders.
|
||||
pub fn wallet_balance_micros(&self, account: &str, asset: Option<&str>) -> Result<i128> {
|
||||
let tx = expiry::transaction(&self.db, TransactionBehavior::Deferred)?;
|
||||
let amount = match asset {
|
||||
Some(asset) => ledger::total_position_micros(&tx, account, asset)?,
|
||||
None => ledger::cash_balance(&tx, account)?
|
||||
.map_or(0, |(available, reserved)| available + reserved),
|
||||
};
|
||||
tx.commit()?;
|
||||
Ok(amount)
|
||||
}
|
||||
|
||||
pub fn execute(&mut self, payload: Value) -> Result<Value> {
|
||||
self.execute_with_maker(payload, None)
|
||||
}
|
||||
|
||||
/// Submit an order with the maker already verified by the signing gateway.
|
||||
pub fn execute_signed_order(&mut self, payload: Value, maker: &str) -> Result<Value> {
|
||||
ensure!(
|
||||
matches!(payload["op"].as_str(), Some("order" | "market_buy"))
|
||||
&& payload["id"]
|
||||
.as_str()
|
||||
.is_some_and(order_identity::is_signed_request),
|
||||
"invalid signed order request"
|
||||
);
|
||||
let maker = order_identity::normalize_maker(maker)?;
|
||||
self.execute_with_maker(payload, Some(&maker))
|
||||
}
|
||||
|
||||
fn execute_with_maker(&mut self, mut payload: Value, maker: Option<&str>) -> Result<Value> {
|
||||
pub fn execute(&mut self, mut payload: Value) -> Result<Value> {
|
||||
if payload["op"].as_str() == Some("heartbeat") {
|
||||
payload
|
||||
.as_object_mut()
|
||||
@@ -293,6 +261,9 @@ impl Exchange {
|
||||
| "market_amounts"
|
||||
| "tick_history"
|
||||
| "catalog"
|
||||
| "combo"
|
||||
| "combo_rfq"
|
||||
| "combo_rfq_open"
|
||||
| "events"
|
||||
| "history"
|
||||
| "prices_history"
|
||||
@@ -305,9 +276,8 @@ impl Exchange {
|
||||
| "clob_book"
|
||||
| "book"
|
||||
| "open_orders"
|
||||
| "account_events"
|
||||
| "account_snapshot"
|
||||
| "positions"
|
||||
| "position_balances_at"
|
||||
| "holders"
|
||||
| "balance"
|
||||
| "portfolio_value"
|
||||
@@ -384,11 +354,6 @@ impl Exchange {
|
||||
let id = payload["id"].as_str().context("request id required")?;
|
||||
identifier(id)?;
|
||||
let tx = expiry::transaction(&self.db, TransactionBehavior::Immediate)?;
|
||||
if order_identity::is_signed_request(id) {
|
||||
if let Some(prior) = order_delay::replay(&tx, id, &payload, maker)? {
|
||||
return Ok(prior);
|
||||
}
|
||||
}
|
||||
let prior: Option<(String, String)> = tx
|
||||
.query_row(
|
||||
"SELECT payload,response FROM requests WHERE id=?",
|
||||
@@ -401,81 +366,26 @@ impl Exchange {
|
||||
serde_json::from_str::<Value>(&saved)? == payload,
|
||||
"request id reused with different content"
|
||||
);
|
||||
if let Some(maker) = maker {
|
||||
order_identity::record_maker(&tx, id, maker)?;
|
||||
tx.commit()?;
|
||||
}
|
||||
return Ok(serde_json::from_str(&reply)?);
|
||||
}
|
||||
let mut body = command_body(&tx, &payload)?;
|
||||
let delay = match (maker, body["market"].as_str(), body["outcome"].as_str()) {
|
||||
(Some(maker), Some(market), Some(outcome)) => {
|
||||
let milliseconds = order_delay::configured(&tx, market)?;
|
||||
(milliseconds > 0)
|
||||
.then(|| (maker, market.to_owned(), outcome.to_owned(), milliseconds))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
if delay.is_some() && body["tif"] == "FOK" {
|
||||
// The delay applies once the order crosses. Full-depth validation runs at release.
|
||||
body["tif"] = json!("FAK");
|
||||
}
|
||||
let mut body = payload.clone();
|
||||
body.as_object_mut()
|
||||
.context("expected object")?
|
||||
.remove("id");
|
||||
assets::resolve(&tx, &mut body)?;
|
||||
let command = serde_json::from_value(body)?;
|
||||
let external = self.books.changes(&tx)?;
|
||||
self.books.apply(external);
|
||||
if delay.is_some() {
|
||||
// Validate against the normal matching path without committing any preview fills.
|
||||
tx.execute_batch("SAVEPOINT delay_preview")?;
|
||||
}
|
||||
let result = market::apply(&tx, &self.books, command, id, false)?;
|
||||
if let Some((maker, market, outcome, milliseconds)) = delay {
|
||||
if result["filled"].as_f64().is_some_and(|qty| qty > 0.0) {
|
||||
tx.execute_batch("ROLLBACK TO delay_preview; RELEASE delay_preview")?;
|
||||
let accepted = order_delay::enqueue(
|
||||
&tx,
|
||||
id,
|
||||
&payload,
|
||||
maker,
|
||||
&market,
|
||||
&outcome,
|
||||
milliseconds,
|
||||
)?;
|
||||
tx.commit()?;
|
||||
return Ok(accepted);
|
||||
}
|
||||
tx.execute_batch("RELEASE delay_preview")?;
|
||||
}
|
||||
record_request_result(&tx, id, &payload, maker, &result)?;
|
||||
let result = market::apply(&tx, &self.books, command, id)?;
|
||||
tx.execute(
|
||||
"INSERT INTO requests VALUES(?,?,?)",
|
||||
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);
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
|
||||
fn command_body(tx: &rusqlite::Transaction<'_>, payload: &Value) -> Result<Value> {
|
||||
let mut body = payload.clone();
|
||||
body.as_object_mut()
|
||||
.context("expected object")?
|
||||
.remove("id");
|
||||
assets::resolve(tx, &mut body)?;
|
||||
Ok(body)
|
||||
}
|
||||
|
||||
fn record_request_result(
|
||||
tx: &rusqlite::Transaction<'_>,
|
||||
id: &str,
|
||||
payload: &Value,
|
||||
maker: Option<&str>,
|
||||
result: &Value,
|
||||
) -> Result<()> {
|
||||
tx.execute(
|
||||
"INSERT INTO requests VALUES(?,?,?)",
|
||||
params![id, payload.to_string(), result.to_string()],
|
||||
)?;
|
||||
if let Some(maker) = maker {
|
||||
order_identity::record_maker(tx, id, maker)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
-- Time is taken from the execution, and the wallet only from the passive leg.
|
||||
WITH fee_fills AS (
|
||||
SELECT e.execution,e.taker_order,t.at_ms,f.quantity,f.price,
|
||||
CASE e.taker_order WHEN f.bid THEN f.ask ELSE f.bid END AS maker_order,
|
||||
e.fee_micros
|
||||
FROM trade_prices t
|
||||
JOIN fills f ON f.seq=t.fill
|
||||
JOIN execution_fees e ON e.execution=f.seq AND e.taker_order IN (f.bid,f.ask)
|
||||
WHERE t.at_ms>=?1 AND t.at_ms<?2
|
||||
UNION ALL
|
||||
SELECT e.execution,e.taker_order,f.at_ms,f.quantity,f.yes_price,
|
||||
CASE e.taker_order WHEN f.yes_order THEN f.no_order ELSE f.yes_order END,
|
||||
e.fee_micros
|
||||
FROM paired_fills f
|
||||
JOIN execution_fees e ON e.execution=f.seq AND e.taker_order IN (f.yes_order,f.no_order)
|
||||
WHERE f.at_ms>=?1 AND f.at_ms<?2
|
||||
)
|
||||
SELECT w.maker_address,m.account,m.market,f.quantity,f.price,f.fee_micros
|
||||
FROM fee_fills f JOIN signed_order_wallets w ON w.order_seq=f.maker_order
|
||||
JOIN orders m ON m.seq=f.maker_order
|
||||
JOIN orders t ON t.seq=f.taker_order
|
||||
LEFT JOIN signed_order_wallets tw ON tw.order_seq=t.seq
|
||||
WHERE m.account<>t.account AND (tw.maker_address IS NULL OR tw.maker_address<>w.maker_address)
|
||||
AND (?3 IS NULL OR w.maker_address IN (SELECT value FROM json_each(?3)))
|
||||
@@ -1,18 +0,0 @@
|
||||
WITH bounds AS MATERIALIZED (
|
||||
SELECT COALESCE((SELECT next_ms FROM maker_rebate_progress WHERE singleton=1),0) AS lower_ms,
|
||||
?1 AS upper_ms
|
||||
),
|
||||
direct AS (
|
||||
SELECT t.at_ms
|
||||
FROM trade_prices t CROSS JOIN execution_fees f ON f.execution=t.fill
|
||||
WHERE t.at_ms>=(SELECT lower_ms FROM bounds) AND t.at_ms<(SELECT upper_ms FROM bounds)
|
||||
ORDER BY t.at_ms LIMIT 1
|
||||
),
|
||||
paired AS (
|
||||
SELECT p.at_ms
|
||||
FROM paired_fills p CROSS JOIN execution_fees f ON f.execution=p.seq
|
||||
WHERE p.at_ms>=(SELECT lower_ms FROM bounds) AND p.at_ms<(SELECT upper_ms FROM bounds)
|
||||
ORDER BY p.at_ms LIMIT 1
|
||||
)
|
||||
SELECT date(MIN(at_ms)/1000,'unixepoch')
|
||||
FROM (SELECT at_ms FROM direct UNION ALL SELECT at_ms FROM paired)
|
||||
@@ -1,319 +0,0 @@
|
||||
use crate::{
|
||||
inventory::{decimal, UNIT},
|
||||
ledger,
|
||||
order_identity::normalize_maker,
|
||||
tick_size::PAR,
|
||||
Exchange, MarketDataError,
|
||||
};
|
||||
use anyhow::{ensure, Result};
|
||||
use rusqlite::{params, Connection, OptionalExtension, Transaction, TransactionBehavior};
|
||||
use serde_json::{json, Value};
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
|
||||
const DAY_MS: i64 = 86_400_000;
|
||||
const PUSD: &str = "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB";
|
||||
|
||||
fn date_start(db: &Connection, date: &str) -> rusqlite::Result<Option<i64>> {
|
||||
db.query_row(
|
||||
"SELECT CASE WHEN length(?1)=10 AND date(?1,'+0 days')=?1
|
||||
THEN unixepoch(?1)*1000 END",
|
||||
[date],
|
||||
|row| row.get(0),
|
||||
)
|
||||
}
|
||||
|
||||
fn maker_address(raw: &str) -> Result<String, MarketDataError> {
|
||||
normalize_maker(&raw.to_ascii_lowercase())
|
||||
.ok()
|
||||
.filter(|address| address[2..].bytes().any(|digit| digit != b'0'))
|
||||
.ok_or_else(|| MarketDataError::Invalid("invalid maker address".into()))
|
||||
}
|
||||
|
||||
// Quantities are hundredths of a share and prices are in ten-thousandths.
|
||||
// Keep the full numerator until tier comparison and response serialization.
|
||||
const WEIGHT_PER_DOLLAR: i128 = 100 * PAR as i128 * PAR as i128;
|
||||
|
||||
fn tier(weight: i128) -> (u8, i64) {
|
||||
for (threshold, tier, bps) in [
|
||||
(10_000_000, 4, 1500),
|
||||
(4_000_000, 3, 1000),
|
||||
(1_000_000, 2, 700),
|
||||
(200_000, 1, 300),
|
||||
] {
|
||||
if weight >= threshold * WEIGHT_PER_DOLLAR {
|
||||
return (tier, bps);
|
||||
}
|
||||
}
|
||||
(0, 0)
|
||||
}
|
||||
|
||||
fn weights(
|
||||
db: &Connection,
|
||||
snapshot: i64,
|
||||
makers: &str,
|
||||
) -> rusqlite::Result<BTreeMap<String, i128>> {
|
||||
let mut stmt = db.prepare_cached(include_str!("maker_fee_fills.sql"))?;
|
||||
let mut rows = stmt.query(params![snapshot - 30 * DAY_MS, snapshot, makers])?;
|
||||
let mut weights = BTreeMap::new();
|
||||
while let Some(row) = rows.next()? {
|
||||
let quantity = i128::from(row.get::<_, i64>(3)?);
|
||||
let price = i128::from(row.get::<_, i64>(4)?);
|
||||
*weights.entry(row.get(0)?).or_default() += quantity * price * (i128::from(PAR) - price);
|
||||
}
|
||||
Ok(weights)
|
||||
}
|
||||
|
||||
pub(crate) fn settle(tx: &Transaction, date: &str) -> Result<Value> {
|
||||
let start = date_start(tx, date)?.ok_or_else(|| anyhow::anyhow!("invalid rebate UTC date"))?;
|
||||
let closed: bool = tx.query_row("SELECT ?1<date('now')", [date], |row| row.get(0))?;
|
||||
ensure!(closed, "rebate day is still open");
|
||||
if let Some(count) = tx
|
||||
.query_row(
|
||||
"SELECT payout_count FROM maker_rebate_days WHERE date=?1",
|
||||
[date],
|
||||
|row| row.get::<_, i64>(0),
|
||||
)
|
||||
.optional()?
|
||||
{
|
||||
return Ok(json!({"date":date,"payout_count":count}));
|
||||
}
|
||||
let mut fees = BTreeMap::<(String, String, String), i128>::new();
|
||||
let mut stmt = tx.prepare_cached(include_str!("maker_fee_fills.sql"))?;
|
||||
let mut fills = stmt.query(params![start, start + DAY_MS, Option::<String>::None])?;
|
||||
while let Some(row) = fills.next()? {
|
||||
let maker: String = row.get(0)?;
|
||||
*fees.entry((maker, row.get(1)?, row.get(2)?)).or_default() +=
|
||||
i128::from(row.get::<_, i64>(5)?);
|
||||
}
|
||||
let makers = fees.keys().map(|key| &key.0).collect::<HashSet<_>>();
|
||||
let tiers = weights(tx, start, &json!(makers).to_string())?;
|
||||
|
||||
let mut payouts = Vec::new();
|
||||
let mut totals = BTreeMap::<String, i128>::new();
|
||||
for ((maker, account, market), collected) in fees {
|
||||
let (_, bps) = tier(tiers.get(&maker).copied().unwrap_or_default());
|
||||
let micros = collected * i128::from(bps) / 10_000;
|
||||
if micros > 0 {
|
||||
*totals.entry(maker.clone()).or_default() += micros;
|
||||
payouts.push((maker, account, market, micros));
|
||||
}
|
||||
}
|
||||
payouts.retain(|(maker, _, _, _)| totals[maker] >= i128::from(UNIT));
|
||||
tx.execute(
|
||||
"INSERT INTO maker_rebate_days VALUES(?1,?2)",
|
||||
params![date, i64::try_from(payouts.len())?],
|
||||
)?;
|
||||
let mut insert =
|
||||
tx.prepare_cached("INSERT INTO maker_rebate_payouts VALUES(?1,?2,?3,?4,?5)")?;
|
||||
for (maker, account, market, micros) in &payouts {
|
||||
let micros = i64::try_from(*micros)?;
|
||||
ledger::cash_micros(tx, account, micros)?;
|
||||
insert.execute(params![date, maker, account, market, micros])?;
|
||||
}
|
||||
if !payouts.is_empty() {
|
||||
tx.execute(
|
||||
"INSERT INTO maker_rebate_payment_times
|
||||
VALUES(?1,CAST(unixepoch('subsec')*1000 AS INTEGER))",
|
||||
[date],
|
||||
)?;
|
||||
}
|
||||
Ok(json!({"date":date,"payout_count":payouts.len()}))
|
||||
}
|
||||
|
||||
fn due_date(db: &Connection, cutoff: i64) -> rusqlite::Result<Option<String>> {
|
||||
db.prepare_cached(include_str!("maker_rebate_due.sql"))?
|
||||
.query_row([cutoff], |row| row.get(0))
|
||||
}
|
||||
|
||||
fn maintain_at(db: &Connection, cutoff: i64) -> Result<()> {
|
||||
if due_date(db, cutoff)?.is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
let tx = Transaction::new_unchecked(db, TransactionBehavior::Immediate)?;
|
||||
// A JSONL process and an HTTP server can race for the same date.
|
||||
if let Some(date) = due_date(&tx, cutoff)? {
|
||||
settle(&tx, &date)?;
|
||||
tx.execute(
|
||||
"INSERT OR REPLACE INTO maker_rebate_progress VALUES(1,unixepoch(?1,'+1 day')*1000)",
|
||||
[&date],
|
||||
)?;
|
||||
}
|
||||
tx.commit()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl Exchange {
|
||||
pub fn maintain_maker_rebates(&self) -> Result<()> {
|
||||
let cutoff = self
|
||||
.db
|
||||
.query_row("SELECT unixepoch(date('now'))*1000", [], |row| row.get(0))?;
|
||||
maintain_at(&self.db, cutoff)
|
||||
}
|
||||
|
||||
pub fn maker_tiers(&self, addresses: Vec<String>) -> Result<Value, MarketDataError> {
|
||||
if !(1..=100).contains(&addresses.len()) {
|
||||
return Err(MarketDataError::Invalid(
|
||||
"expected 1 to 100 maker addresses".into(),
|
||||
));
|
||||
}
|
||||
let mut seen = HashSet::new();
|
||||
let addresses = addresses
|
||||
.iter()
|
||||
.map(|address| maker_address(address))
|
||||
.collect::<Result<Vec<_>, _>>()?
|
||||
.into_iter()
|
||||
.filter(|address| seen.insert(address.clone()))
|
||||
.collect::<Vec<_>>();
|
||||
let tx = self.db.unchecked_transaction()?;
|
||||
let (date, start): (String, i64) = tx.query_row(
|
||||
"SELECT date('now'),unixepoch(date('now'))*1000",
|
||||
[],
|
||||
|row| Ok((row.get(0)?, row.get(1)?)),
|
||||
)?;
|
||||
let weights = weights(&tx, start, &json!(addresses).to_string())?;
|
||||
tx.commit()?;
|
||||
let tiers = addresses
|
||||
.into_iter()
|
||||
.map(|address| {
|
||||
let weight = weights.get(&address).copied().unwrap_or_default();
|
||||
let (tier, bps) = tier(weight);
|
||||
let wv = decimal(weight / (WEIGHT_PER_DOLLAR / i128::from(UNIT)), UNIT);
|
||||
json!({"address":address,"snapshot_date":date,"tier":tier,"rebate_bps":bps,
|
||||
"wv_30d":wv,"own_wv_30d":wv})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
Ok(json!({"tiers":tiers}))
|
||||
}
|
||||
|
||||
pub fn maker_rebates(&self, date: &str, maker: &str) -> Result<Value, MarketDataError> {
|
||||
let maker = maker_address(maker)?;
|
||||
if date_start(&self.db, date)?.is_none() {
|
||||
return Err(MarketDataError::Invalid("invalid rebate UTC date".into()));
|
||||
}
|
||||
let mut stmt = self.db.prepare_cached(
|
||||
"SELECT market,SUM(micros) FROM maker_rebate_payouts
|
||||
WHERE date=?1 AND maker=?2 GROUP BY market ORDER BY market",
|
||||
)?;
|
||||
let mut rows = stmt.query(params![date, maker])?;
|
||||
let mut data = Vec::new();
|
||||
while let Some(row) = rows.next()? {
|
||||
let market: String = row.get(0)?;
|
||||
let micros: i64 = row.get(1)?;
|
||||
let amount = format!("{}.{:06}", micros / UNIT, micros % UNIT);
|
||||
data.push(
|
||||
json!({"date":date,"condition_id":market,"asset_address":PUSD,"maker_address":maker,
|
||||
"rebated_fees_usdc":amount}),
|
||||
);
|
||||
}
|
||||
Ok(if data.is_empty() {
|
||||
Value::Null
|
||||
} else {
|
||||
Value::Array(data)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const MAKER: &str = "0x00000000000000000000000000000000000000aa";
|
||||
|
||||
#[test]
|
||||
fn tier_boundaries_include_the_threshold() {
|
||||
for (threshold, before, after) in [
|
||||
(200_000, (0, 0), (1, 300)),
|
||||
(1_000_000, (1, 300), (2, 700)),
|
||||
(4_000_000, (2, 700), (3, 1000)),
|
||||
(10_000_000, (3, 1000), (4, 1500)),
|
||||
] {
|
||||
assert_eq!(tier(threshold * WEIGHT_PER_DOLLAR - 1), before);
|
||||
assert_eq!(tier(threshold * WEIGHT_PER_DOLLAR), after);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scheduled_rebates_catch_up_and_credit_confirmed_passive_wallet_once() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("maker.sqlite");
|
||||
let mut exchange = Exchange::open(&path).unwrap();
|
||||
exchange
|
||||
.db
|
||||
.execute_batch(
|
||||
"INSERT INTO accounts VALUES('maker',0),('taker',0);
|
||||
INSERT INTO markets(id,rules,phase) VALUES('cup','result','continuous');
|
||||
INSERT INTO orders VALUES
|
||||
(1,'taker','cup','YES','buy',5000,80000000,0,'filled'),
|
||||
(2,'maker','cup','YES','sell',5000,80000000,0,'filled');
|
||||
INSERT INTO signed_order_ids VALUES('fixture-1',2);
|
||||
INSERT INTO fills VALUES(1,1,2,5000,80000000),(2,1,2,5000,200000);
|
||||
INSERT INTO execution_context VALUES(1,1),(2,1);
|
||||
INSERT INTO execution_fees VALUES(1,1,10000000000),(2,1,50000000);",
|
||||
)
|
||||
.unwrap();
|
||||
exchange
|
||||
.db
|
||||
.execute("INSERT INTO signed_order_wallets VALUES(2,?1)", [MAKER])
|
||||
.unwrap();
|
||||
let day: String = exchange
|
||||
.db
|
||||
.query_row("SELECT date('now','-1 day')", [], |row| row.get(0))
|
||||
.unwrap();
|
||||
let start = date_start(&exchange.db, &day).unwrap().unwrap();
|
||||
exchange
|
||||
.db
|
||||
.execute_batch(&format!(
|
||||
"UPDATE trade_prices SET at_ms={start}-{DAY_MS} WHERE fill=1;
|
||||
UPDATE trade_prices SET at_ms={start} WHERE fill=2;"
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(exchange.maker_rebates(&day, MAKER).unwrap(), Value::Null);
|
||||
let tier = exchange
|
||||
.maker_tiers(vec![MAKER.into(), MAKER.to_ascii_uppercase()])
|
||||
.unwrap();
|
||||
assert_eq!(tier["tiers"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(tier["tiers"][0]["tier"], 1);
|
||||
|
||||
exchange.maintain_maker_rebates().unwrap();
|
||||
assert_eq!(exchange.maker_rebates(&day, MAKER).unwrap(), Value::Null);
|
||||
drop(exchange);
|
||||
|
||||
let mut exchange = Exchange::open(&path).unwrap();
|
||||
exchange.maintain_maker_rebates().unwrap();
|
||||
exchange.maintain_maker_rebates().unwrap();
|
||||
let receipt = exchange
|
||||
.execute(json!({"op":"settle_maker_rebates","id":"pay","date":day}))
|
||||
.unwrap();
|
||||
assert_eq!(receipt["payout_count"], 1);
|
||||
drop(exchange);
|
||||
let mut exchange = Exchange::open(path).unwrap();
|
||||
assert_eq!(
|
||||
exchange
|
||||
.execute(json!({"op":"settle_maker_rebates","id":"pay-retry","date":day}))
|
||||
.unwrap(),
|
||||
receipt
|
||||
);
|
||||
let actual = exchange.maker_rebates(&day, MAKER).unwrap();
|
||||
assert_eq!(actual[0]["rebated_fees_usdc"], "1.500000");
|
||||
assert_eq!(
|
||||
ledger::balance(&exchange.db, "maker").unwrap()["available_micros"],
|
||||
1_500_000
|
||||
);
|
||||
assert_eq!(
|
||||
ledger::balance(&exchange.db, "taker").unwrap()["available_micros"],
|
||||
0
|
||||
);
|
||||
let activity = exchange
|
||||
.execute(json!({"op":"activity","account":"maker","types":["MAKER_REBATE"]}))
|
||||
.unwrap();
|
||||
assert_eq!(activity["activity"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(activity["activity"][0]["net_cash_delta_micros"], 1_500_000);
|
||||
assert_eq!(activity["activity"][0]["rebate_date"], day);
|
||||
assert!(activity["activity"][0]["at_ms"].as_i64().unwrap() >= start + DAY_MS);
|
||||
let activity = exchange
|
||||
.execute(json!({"op":"activity","account":"taker","types":["MAKER_REBATE"]}))
|
||||
.unwrap();
|
||||
assert_eq!(activity["activity"], json!([]));
|
||||
assert!(exchange.maker_rebates("2024-02-30", MAKER).is_err());
|
||||
}
|
||||
}
|
||||
@@ -14,10 +14,8 @@ pub(crate) fn apply(
|
||||
books: &Books,
|
||||
command: Command,
|
||||
request_id: &str,
|
||||
admitted_before_delay: bool,
|
||||
) -> Result<Value> {
|
||||
match command {
|
||||
Command::SettleMakerRebates { date } => crate::maker_rebates::settle(tx, &date),
|
||||
Command::Fund {
|
||||
account,
|
||||
cents,
|
||||
@@ -59,11 +57,6 @@ pub(crate) fn apply(
|
||||
Ok(json!({"market":market,"active":active,"archived":archived}))
|
||||
}
|
||||
Command::TickSizeChange(change) => change.apply(tx, request_id),
|
||||
Command::SetTakerDelay {
|
||||
market,
|
||||
seconds,
|
||||
itode,
|
||||
} => crate::order_delay::configure(tx, &market, seconds, itode),
|
||||
Command::Event(event) => event.save(tx),
|
||||
Command::RescheduleSports {
|
||||
event,
|
||||
@@ -121,6 +114,20 @@ pub(crate) fn apply(
|
||||
)?;
|
||||
Ok(json!({"phase":"preopen"}))
|
||||
}
|
||||
Command::PrepareCombo { legs } => crate::combo::prepare(tx, legs),
|
||||
Command::SplitCombo(amount) => amount.apply(tx, request_id, true),
|
||||
Command::MergeCombo(amount) => amount.apply(tx, request_id, false),
|
||||
Command::RedeemCombo(redemption) => redemption.apply(tx, request_id),
|
||||
Command::RequestComboQuote(request) => request.apply(tx, request_id),
|
||||
Command::QuoteCombo(quote) => quote.apply(tx, request_id),
|
||||
Command::AcceptComboQuote(accept) => accept.apply(tx),
|
||||
Command::RespondComboQuote(response) => response.apply(tx, request_id),
|
||||
Command::CancelComboQuote { rfq, quote, maker } => {
|
||||
crate::combo_rfq::cancel_quote(tx, &rfq, "e, &maker)
|
||||
}
|
||||
Command::CancelComboRfq { rfq, requester } => {
|
||||
crate::combo_rfq::cancel_request(tx, &rfq, &requester)
|
||||
}
|
||||
Command::DefineNegRisk {
|
||||
group,
|
||||
event,
|
||||
@@ -211,7 +218,6 @@ pub(crate) fn apply(
|
||||
expiration,
|
||||
post_only,
|
||||
},
|
||||
admitted_before_delay,
|
||||
)
|
||||
.map(|result| result.receipt()),
|
||||
Command::MarketSell {
|
||||
@@ -262,7 +268,6 @@ pub(crate) fn apply(
|
||||
expiration: None,
|
||||
post_only: false,
|
||||
},
|
||||
false,
|
||||
)?;
|
||||
let mut receipt = result.receipt();
|
||||
if let Some(amounts) = amounts {
|
||||
@@ -308,9 +313,6 @@ pub(crate) fn apply(
|
||||
Command::CancelOrders { account, orders } => {
|
||||
crate::cancellation::by_id(tx, &account, &orders)
|
||||
}
|
||||
Command::CancelOrderRefs { account, orders } => {
|
||||
crate::cancellation::by_ref(tx, &account, &orders)
|
||||
}
|
||||
Command::CancelMarketOrders {
|
||||
account,
|
||||
market,
|
||||
|
||||
@@ -2,7 +2,7 @@ use crate::{
|
||||
expiry,
|
||||
inventory::decimal,
|
||||
portfolio,
|
||||
validation::{condition_filter, ConditionList, IdSelector},
|
||||
validation::{condition_filter, IdSelector},
|
||||
Exchange, MarketDataError,
|
||||
};
|
||||
use anyhow::Result;
|
||||
@@ -100,14 +100,14 @@ fn aggregate(
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct InterestQuery {
|
||||
#[serde(alias = "conditionId", alias = "condition_id")]
|
||||
pub condition: Option<ConditionList>,
|
||||
condition: Option<String>,
|
||||
}
|
||||
|
||||
impl Exchange {
|
||||
pub fn public_open_interest(&self, query: InterestQuery) -> Result<Value, MarketDataError> {
|
||||
let tx = expiry::transaction(&self.db, TransactionBehavior::Deferred)
|
||||
.map_err(|_| MarketDataError::Unavailable)?;
|
||||
let ids = condition_filter(query.condition.as_ref(), &tx)?;
|
||||
let ids = condition_filter(query.condition.as_deref(), &tx)?;
|
||||
let totals =
|
||||
aggregate(&tx, ids.as_deref(), true).map_err(|_| MarketDataError::Unavailable)?;
|
||||
let mut data = Vec::with_capacity(totals.len());
|
||||
|
||||
@@ -1,394 +0,0 @@
|
||||
use crate::{assets, depth_feed, expiry, market, validation::identifier, Exchange};
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use rusqlite::{params, Connection, OptionalExtension, Transaction, TransactionBehavior};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
pub(crate) const SYNCHRONOUS_DELAY_MS: i64 = 150;
|
||||
|
||||
pub enum SynchronousPlacement {
|
||||
Waiting,
|
||||
Rejected,
|
||||
Submitted { receipt: Value, selling: bool },
|
||||
}
|
||||
|
||||
pub(crate) fn configure(
|
||||
tx: &Transaction,
|
||||
market: &str,
|
||||
seconds: Option<u32>,
|
||||
itode: Option<bool>,
|
||||
) -> Result<Value> {
|
||||
identifier(market)?;
|
||||
let delay_ms = match (seconds, itode) {
|
||||
(Some(seconds), None) => i64::from(seconds) * 1000,
|
||||
(None, Some(true)) => SYNCHRONOUS_DELAY_MS,
|
||||
(None, Some(false)) => 0,
|
||||
_ => anyhow::bail!("provide either seconds or itode"),
|
||||
};
|
||||
tx.execute(
|
||||
"INSERT INTO market_order_delays(market,delay_ms) VALUES(?,?)
|
||||
ON CONFLICT(market) DO UPDATE SET delay_ms=excluded.delay_ms",
|
||||
params![market, delay_ms],
|
||||
)?;
|
||||
let mut result = json!({"market":market,"seconds_delay":delay_ms/1000});
|
||||
if let Some(itode) = itode {
|
||||
result["itode"] = json!(itode);
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
pub(crate) fn configured(db: &Connection, market: &str) -> Result<i64> {
|
||||
Ok(db
|
||||
.query_row(
|
||||
"SELECT delay_ms FROM market_order_delays WHERE market=?",
|
||||
[market],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.optional()?
|
||||
.unwrap_or_default())
|
||||
}
|
||||
|
||||
pub(crate) fn enqueue(
|
||||
tx: &Transaction,
|
||||
id: &str,
|
||||
payload: &Value,
|
||||
maker: &str,
|
||||
market: &str,
|
||||
outcome: &str,
|
||||
delay: i64,
|
||||
) -> Result<Value> {
|
||||
let ready = tx.query_row(
|
||||
"INSERT INTO delayed_orders(request_id, account, market, outcome, payload, maker, ready_at_ms)
|
||||
VALUES(?1, ?2, ?3, ?4, ?5, ?6, CAST(unixepoch('subsec')*1000 AS INTEGER)+?7)
|
||||
RETURNING ready_at_ms",
|
||||
params![id, payload["account"].as_str().context("missing account")?, market, outcome, payload.to_string(), maker, delay],
|
||||
|row| row.get(0),
|
||||
)?;
|
||||
let synchronous = delay == SYNCHRONOUS_DELAY_MS;
|
||||
if synchronous {
|
||||
tx.execute("INSERT INTO synchronous_delayed_orders VALUES(?)", [id])?;
|
||||
}
|
||||
Ok(receipt(ready, synchronous))
|
||||
}
|
||||
|
||||
fn receipt(ready: i64, synchronous: bool) -> Value {
|
||||
let mut response = json!({"status":"delayed","ready_at_ms":ready});
|
||||
if synchronous {
|
||||
response["wait_for_result"] = json!(true);
|
||||
}
|
||||
response
|
||||
}
|
||||
|
||||
pub(crate) fn replay(
|
||||
tx: &Transaction,
|
||||
id: &str,
|
||||
payload: &Value,
|
||||
maker: Option<&str>,
|
||||
) -> Result<Option<Value>> {
|
||||
let prior: Option<(String, String, i64, bool)> = tx
|
||||
.query_row(
|
||||
"SELECT d.payload,d.maker,d.ready_at_ms,s.request_id IS NOT NULL
|
||||
FROM delayed_orders d LEFT JOIN synchronous_delayed_orders s USING(request_id)
|
||||
WHERE d.request_id=?",
|
||||
[id],
|
||||
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)),
|
||||
)
|
||||
.optional()?;
|
||||
if let Some((saved, address, ready, synchronous)) = prior {
|
||||
ensure!(
|
||||
maker == Some(address.as_str()) && serde_json::from_str::<Value>(&saved)? == *payload,
|
||||
"request id reused with different content"
|
||||
);
|
||||
return Ok(Some(receipt(ready, synchronous)));
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
pub(crate) fn status(db: &Connection, account: &str, hash: &str) -> Result<Option<String>> {
|
||||
if !hash.starts_with("0x") {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(db.query_row(
|
||||
"SELECT status FROM delayed_orders WHERE request_id=? AND account=? AND status<>'submitted'",
|
||||
params![format!("clob-order:{hash}"),account], |row| row.get(0),
|
||||
).optional()?)
|
||||
}
|
||||
|
||||
pub(crate) fn pending_in_scope(
|
||||
db: &Connection,
|
||||
account: &str,
|
||||
market: Option<&str>,
|
||||
outcome: Option<&str>,
|
||||
) -> Result<Vec<String>> {
|
||||
let mut stmt = db.prepare_cached(
|
||||
"SELECT substr(request_id,12) FROM delayed_orders WHERE account=?1 AND status='delayed'
|
||||
AND (?2 IS NULL OR market=?2) AND (?3 IS NULL OR outcome=?3) ORDER BY seq",
|
||||
)?;
|
||||
let rows = stmt.query_map(params![account, market, outcome], |row| row.get(0))?;
|
||||
Ok(rows.collect::<rusqlite::Result<_>>()?)
|
||||
}
|
||||
|
||||
impl Exchange {
|
||||
pub fn synchronous_placement(&self, account: &str, hash: &str) -> Result<SynchronousPlacement> {
|
||||
let (status, receipt, selling): (String, Option<String>, bool) = self.db.query_row(
|
||||
"SELECT d.status,r.response,COALESCE(json_extract(d.payload,'$.side')='sell',0)
|
||||
FROM synchronous_delayed_orders s JOIN delayed_orders d USING(request_id)
|
||||
LEFT JOIN requests r ON r.id=d.request_id
|
||||
WHERE d.request_id=?1 AND d.account=?2",
|
||||
params![format!("clob-order:{hash}"), account],
|
||||
|row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
|
||||
)?;
|
||||
match status.as_str() {
|
||||
"delayed" => Ok(SynchronousPlacement::Waiting),
|
||||
"rejected" => Ok(SynchronousPlacement::Rejected),
|
||||
"submitted" => {
|
||||
let receipt =
|
||||
serde_json::from_str(&receipt.context("missing synchronized order receipt")?)?;
|
||||
Ok(SynchronousPlacement::Submitted { receipt, selling })
|
||||
}
|
||||
_ => anyhow::bail!("invalid synchronous placement state"),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn delayed_order(&self, account: &str, raw: &str) -> Result<Option<Value>> {
|
||||
let hash = crate::normalize_order_ref(raw)?;
|
||||
if !hash.starts_with("0x") {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(self.db.query_row(
|
||||
"SELECT status,ready_at_ms,market,outcome,maker FROM delayed_orders
|
||||
WHERE request_id=? AND account=? AND status<>'submitted'",
|
||||
params![format!("clob-order:{hash}"),account], |row| {
|
||||
let status: String = row.get(0)?;
|
||||
let market: String = row.get(2)?;
|
||||
let outcome: String = row.get(3)?;
|
||||
Ok(json!({"id":hash,"status":status.to_ascii_uppercase(),"ready_at_ms":row.get::<_,i64>(1)?,
|
||||
"market":market,"outcome":outcome,"asset_id":assets::id(&market,&outcome),
|
||||
"maker_address":row.get::<_,String>(4)?}))
|
||||
},
|
||||
).optional()?)
|
||||
}
|
||||
|
||||
/// Process the oldest due signed orders after applying ordinary market maintenance.
|
||||
pub fn maintain_delayed_orders(&mut self) -> Result<()> {
|
||||
let now = self.db.query_row(
|
||||
"SELECT CAST(unixepoch('subsec')*1000 AS INTEGER)",
|
||||
[],
|
||||
|row| row.get(0),
|
||||
)?;
|
||||
self.run_delayed_orders(now)
|
||||
}
|
||||
|
||||
fn run_delayed_orders(&mut self, now: i64) -> Result<()> {
|
||||
for _ in 0..32 {
|
||||
let due: bool = self.db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM delayed_orders WHERE status='delayed'
|
||||
AND ready_at_ms<=?1)",
|
||||
[now],
|
||||
|row| row.get(0),
|
||||
)?;
|
||||
if !due {
|
||||
break;
|
||||
}
|
||||
let tx = expiry::transaction(&self.db, TransactionBehavior::Immediate)?;
|
||||
let next: Option<(String, String, String)> = tx
|
||||
.query_row(
|
||||
"SELECT request_id,payload,maker FROM delayed_orders WHERE status='delayed'
|
||||
AND ready_at_ms<=?1 ORDER BY ready_at_ms,seq LIMIT 1",
|
||||
[now],
|
||||
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
|
||||
)
|
||||
.optional()?;
|
||||
let Some((id, payload, maker)) = next else {
|
||||
break;
|
||||
};
|
||||
let payload: Value = serde_json::from_str(&payload)?;
|
||||
let command = serde_json::from_value(super::command_body(&tx, &payload)?)?;
|
||||
let external = self.books.changes(&tx)?;
|
||||
self.books.apply(external);
|
||||
tx.execute_batch("SAVEPOINT delayed_execution")?;
|
||||
let applied = market::apply(&tx, &self.books, command, &id, true);
|
||||
let status = match applied {
|
||||
Ok(result) => {
|
||||
super::record_request_result(&tx, &id, &payload, Some(&maker), &result)?;
|
||||
"submitted"
|
||||
}
|
||||
Err(err) => {
|
||||
if err.downcast_ref::<rusqlite::Error>().is_some() {
|
||||
return Err(err);
|
||||
}
|
||||
tx.execute_batch("ROLLBACK TO delayed_execution")?;
|
||||
"rejected"
|
||||
}
|
||||
};
|
||||
tx.execute_batch("RELEASE delayed_execution")?;
|
||||
tx.execute(
|
||||
"UPDATE delayed_orders SET status=?1 WHERE request_id=?2",
|
||||
params![status, id],
|
||||
)?;
|
||||
depth_feed::flush(&tx)?;
|
||||
let changes = self.books.changes(&tx)?;
|
||||
tx.commit()?;
|
||||
self.books.apply(changes);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const MAKER: &str = "0x0000000000000000000000000000000000000042";
|
||||
|
||||
fn seed(db: &mut Exchange, cash: u64) {
|
||||
for cmd in [
|
||||
json!({"op":"fund","id":"cash","account":"alice","cents":cash}),
|
||||
json!({"op":"fund","id":"fund-bob","account":"bob","cents":500}),
|
||||
json!({"op":"list","id":"list","market":"game","rules":"test","tick_size":"0.01"}),
|
||||
json!({"op":"split","id":"split","account":"bob","market":"game","qty":2}),
|
||||
json!({"op":"open","id":"open","market":"game"}),
|
||||
json!({"op":"order","id":"ask","account":"bob","asset_id":"eb:YES:game","side":"sell","price":55,"qty":2}),
|
||||
json!({"op":"set_taker_delay","id":"delay","market":"game","seconds":1}),
|
||||
] {
|
||||
db.execute(cmd).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_order_is_not_in_the_book_and_executes_once_after_restart() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let path = directory.path().join("delay.db");
|
||||
let mut db = Exchange::open(&path).unwrap();
|
||||
seed(&mut db, 300);
|
||||
let hash = format!("0x{}", "aa".repeat(32));
|
||||
let order = json!({"op":"order","id":format!("clob-order:{hash}"),"account":"alice",
|
||||
"asset_id":"eb:YES:game","side":"buy","price":60,"qty":1});
|
||||
let queued = db.execute_signed_order(order.clone(), MAKER).unwrap();
|
||||
let due = queued["ready_at_ms"].as_i64().unwrap();
|
||||
assert_eq!(queued["status"], "delayed");
|
||||
assert_eq!(db.wallet_balance_micros("alice", None).unwrap(), 3_000_000);
|
||||
assert_eq!(
|
||||
db.execute(json!({"op":"open_orders","account":"alice"}))
|
||||
.unwrap()["orders"],
|
||||
json!([])
|
||||
);
|
||||
assert!(db.delayed_order("bob", &hash).unwrap().is_none());
|
||||
assert_eq!(
|
||||
db.delayed_order("alice", &hash).unwrap().unwrap()["status"],
|
||||
"DELAYED"
|
||||
);
|
||||
let cancel = db
|
||||
.execute(
|
||||
json!({"op":"cancel_order_refs","id":"cancel","account":"alice","orders":[hash]}),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(cancel["not_canceled"][&hash], "order is delayed");
|
||||
db.run_delayed_orders(due - 1).unwrap();
|
||||
assert!(db.resolve_order_ref("alice", &hash).unwrap().is_none());
|
||||
drop(db);
|
||||
|
||||
let mut db = Exchange::open(&path).unwrap();
|
||||
db.run_delayed_orders(due).unwrap();
|
||||
db.run_delayed_orders(due).unwrap();
|
||||
let seq = db.resolve_order_ref("alice", &hash).unwrap().unwrap();
|
||||
assert_eq!(db.submission_fills(seq).unwrap().cash_micros, 550_000);
|
||||
assert_eq!(
|
||||
db.wallet_balance_micros("alice", Some("eb:YES:game"))
|
||||
.unwrap(),
|
||||
1_000_000
|
||||
);
|
||||
assert!(db.delayed_order("alice", &hash).unwrap().is_none());
|
||||
assert_eq!(db.execute_signed_order(order, MAKER).unwrap(), queued);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crossing_order_rechecks_balance_and_resting_order_skips_delay() {
|
||||
let mut db = Exchange::open(":memory:").unwrap();
|
||||
seed(&mut db, 60);
|
||||
let hash = format!("0x{}", "bb".repeat(32));
|
||||
let buy = json!({"op":"order","id":format!("clob-order:{hash}"),"account":"alice",
|
||||
"asset_id":"eb:YES:game","side":"buy","price":60,"qty":1});
|
||||
let delayed = db.execute_signed_order(buy, MAKER).unwrap();
|
||||
let resting_hash = format!("0x{}", "cc".repeat(32));
|
||||
let resting = json!({"op":"order","id":format!("clob-order:{resting_hash}"),"account":"alice",
|
||||
"asset_id":"eb:YES:game","side":"buy","price":30,"qty":1});
|
||||
assert_eq!(
|
||||
db.execute_signed_order(resting, MAKER).unwrap()["status"],
|
||||
"live"
|
||||
);
|
||||
db.run_delayed_orders(delayed["ready_at_ms"].as_i64().unwrap())
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
db.delayed_order("alice", &hash).unwrap().unwrap()["status"],
|
||||
"REJECTED"
|
||||
);
|
||||
assert!(db.resolve_order_ref("alice", &hash).unwrap().is_none());
|
||||
assert_eq!(
|
||||
db.wallet_balance_micros("alice", Some("eb:YES:game"))
|
||||
.unwrap(),
|
||||
0
|
||||
);
|
||||
assert_eq!(
|
||||
db.execute(json!({"op":"state"})).unwrap()["fills"],
|
||||
json!([])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fok_checks_full_depth_after_the_delay() {
|
||||
let mut db = Exchange::open(":memory:").unwrap();
|
||||
seed(&mut db, 300);
|
||||
let hash = format!("0x{}", "dd".repeat(32));
|
||||
let buy = json!({"op":"order","id":format!("clob-order:{hash}"),"account":"alice",
|
||||
"asset_id":"eb:YES:game","side":"buy","price":60,"qty":3,"tif":"FOK"});
|
||||
let delayed = db.execute_signed_order(buy, MAKER).unwrap();
|
||||
assert_eq!(delayed["status"], "delayed");
|
||||
db.run_delayed_orders(delayed["ready_at_ms"].as_i64().unwrap())
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
db.delayed_order("alice", &hash).unwrap().unwrap()["status"],
|
||||
"REJECTED"
|
||||
);
|
||||
assert_eq!(
|
||||
db.execute(json!({"op":"state"})).unwrap()["fills"],
|
||||
json!([])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn synchronous_delay_survives_configuration_changes_and_returns_original_execution() {
|
||||
let mut db = Exchange::open(":memory:").unwrap();
|
||||
seed(&mut db, 300);
|
||||
db.execute(json!({"op":"set_taker_delay","id":"sync","market":"game","itode":true}))
|
||||
.unwrap();
|
||||
assert_eq!(db.clob_market_info("game").unwrap().unwrap()["itode"], true);
|
||||
let hash = format!("0x{}", "ee".repeat(32));
|
||||
let buy = json!({"op":"order","id":format!("clob-order:{hash}"),"account":"alice",
|
||||
"asset_id":"eb:YES:game","side":"buy","price":60,"qty":1});
|
||||
let pending = db.execute_signed_order(buy.clone(), MAKER).unwrap();
|
||||
assert_eq!(pending["wait_for_result"], true);
|
||||
assert!(matches!(
|
||||
db.synchronous_placement("alice", &hash).unwrap(),
|
||||
SynchronousPlacement::Waiting
|
||||
));
|
||||
assert!(db.synchronous_placement("bob", &hash).is_err());
|
||||
db.execute(json!({"op":"set_taker_delay","id":"clear-sync","market":"game","itode":false}))
|
||||
.unwrap();
|
||||
assert!(db
|
||||
.clob_market_info("game")
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.get("itode")
|
||||
.is_none());
|
||||
db.run_delayed_orders(pending["ready_at_ms"].as_i64().unwrap())
|
||||
.unwrap();
|
||||
let SynchronousPlacement::Submitted { receipt, selling } =
|
||||
db.synchronous_placement("alice", &hash).unwrap()
|
||||
else {
|
||||
panic!("expected successful placement")
|
||||
};
|
||||
assert!(!selling);
|
||||
assert_eq!(receipt["status"], "filled");
|
||||
assert_eq!(db.execute_signed_order(buy, MAKER).unwrap(), pending);
|
||||
}
|
||||
}
|
||||
@@ -1,123 +0,0 @@
|
||||
use crate::Exchange;
|
||||
use anyhow::{ensure, Result};
|
||||
use rusqlite::{params, Connection, OptionalExtension};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
pub struct SubmissionFills {
|
||||
pub cash_micros: i128,
|
||||
pub shares_micros: i128,
|
||||
pub trade_ids: Vec<i64>,
|
||||
}
|
||||
|
||||
pub(crate) fn is_signed_request(id: &str) -> bool {
|
||||
id.strip_prefix("clob-order:0x").is_some_and(|hash| {
|
||||
hash.len() == 64
|
||||
&& hash
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn normalize_maker(raw: &str) -> Result<String> {
|
||||
ensure!(
|
||||
raw.strip_prefix("0x")
|
||||
.is_some_and(|hex| hex.len() == 40 && hex.bytes().all(|b| b.is_ascii_hexdigit())),
|
||||
"invalid maker address"
|
||||
);
|
||||
Ok(raw.to_ascii_lowercase())
|
||||
}
|
||||
|
||||
pub(crate) fn record_maker(db: &Connection, request_id: &str, maker: &str) -> Result<()> {
|
||||
db.execute(
|
||||
"INSERT INTO signed_order_wallets(order_seq,maker_address)
|
||||
SELECT order_seq,?2 FROM signed_order_ids WHERE hash=substr(?1,12)
|
||||
ON CONFLICT(order_seq) DO NOTHING",
|
||||
params![request_id, maker],
|
||||
)?;
|
||||
let stored: Option<String> = db
|
||||
.query_row(
|
||||
"SELECT w.maker_address FROM signed_order_wallets w
|
||||
JOIN signed_order_ids i ON i.order_seq=w.order_seq WHERE i.hash=substr(?1,12)",
|
||||
[request_id],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.optional()?;
|
||||
ensure!(
|
||||
stored.as_deref().is_none_or(|address| address == maker),
|
||||
"signed order maker mismatch"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn normalize_order_ref(raw: &str) -> Result<String> {
|
||||
if let Some(hex) = raw.strip_prefix("0x") {
|
||||
ensure!(
|
||||
hex.len() == 64 && hex.bytes().all(|b| b.is_ascii_hexdigit()),
|
||||
"invalid order hash"
|
||||
);
|
||||
return Ok(raw.to_ascii_lowercase());
|
||||
}
|
||||
let id: i64 = raw.parse()?;
|
||||
ensure!(id > 0, "invalid order reference");
|
||||
Ok(id.to_string())
|
||||
}
|
||||
|
||||
pub(crate) fn lookup(db: &Connection, account: &str, raw: &str) -> Result<Option<(i64, String)>> {
|
||||
let id = normalize_order_ref(raw)?;
|
||||
let mut stmt = db.prepare_cached(
|
||||
"SELECT o.seq,o.status FROM orders o
|
||||
WHERE o.seq=COALESCE((SELECT order_seq FROM signed_order_ids WHERE hash=?1),?2)
|
||||
AND o.account=?3",
|
||||
)?;
|
||||
Ok(stmt
|
||||
.query_row(params![id, id.parse::<i64>().ok(), account], |row| {
|
||||
Ok((row.get(0)?, row.get(1)?))
|
||||
})
|
||||
.optional()?)
|
||||
}
|
||||
|
||||
impl Exchange {
|
||||
/// Only executions caused by the incoming order, excluding subsequent maker fills.
|
||||
pub fn submission_fills(&self, order: i64) -> Result<SubmissionFills> {
|
||||
let mut stmt = self.db.prepare_cached(
|
||||
"SELECT c.execution,
|
||||
COALESCE(f.price, CASE WHEN p.no_order=?1 THEN 10000-p.yes_price ELSE p.yes_price END),
|
||||
COALESCE(f.quantity,p.quantity)
|
||||
FROM execution_context c
|
||||
LEFT JOIN fills f ON f.seq=c.execution
|
||||
LEFT JOIN paired_fills p ON p.seq=c.execution
|
||||
WHERE c.taker_order=?1 ORDER BY c.execution",
|
||||
)?;
|
||||
let mut rows = stmt.query([order])?;
|
||||
let mut fills = SubmissionFills {
|
||||
cash_micros: 0,
|
||||
shares_micros: 0,
|
||||
trade_ids: Vec::new(),
|
||||
};
|
||||
while let Some(row) = rows.next()? {
|
||||
let price = i128::from(row.get::<_, i64>(1)?);
|
||||
let lots = i128::from(row.get::<_, i64>(2)?);
|
||||
fills.cash_micros += price * lots;
|
||||
fills.shares_micros += lots * i128::from(crate::lots::MICROS);
|
||||
fills.trade_ids.push(row.get(0)?);
|
||||
}
|
||||
Ok(fills)
|
||||
}
|
||||
|
||||
pub fn resolve_order_ref(&self, account: &str, raw: &str) -> Result<Option<i64>> {
|
||||
Ok(lookup(&self.db, account, raw)?.map(|(seq, _)| seq))
|
||||
}
|
||||
|
||||
pub fn order_hashes(&self, orders: &[i64]) -> Result<BTreeMap<i64, String>> {
|
||||
if orders.is_empty() {
|
||||
return Ok(BTreeMap::new());
|
||||
}
|
||||
let mut stmt = self.db.prepare_cached(
|
||||
"SELECT order_seq,hash FROM signed_order_ids WHERE order_seq IN (SELECT value FROM json_each(?))",
|
||||
)?;
|
||||
let rows = stmt.query_map([serde_json::to_string(orders)?], |r| {
|
||||
Ok((r.get(0)?, r.get(1)?))
|
||||
})?;
|
||||
Ok(rows.collect::<rusqlite::Result<_>>()?)
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
BEGIN IMMEDIATE;
|
||||
CREATE TABLE IF NOT EXISTS signed_order_ids (
|
||||
hash TEXT PRIMARY KEY,
|
||||
order_seq INTEGER NOT NULL UNIQUE REFERENCES orders(seq)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS signed_order_wallets (
|
||||
order_seq INTEGER PRIMARY KEY REFERENCES signed_order_ids(order_seq),
|
||||
maker_address TEXT NOT NULL
|
||||
);
|
||||
|
||||
INSERT INTO signed_order_ids(hash,order_seq)
|
||||
SELECT substr(r.id,12),o.seq FROM requests r
|
||||
JOIN orders o ON o.seq=json_extract(r.response,'$.order')
|
||||
WHERE r.id GLOB 'clob-order:0x*' AND length(r.id)=77 AND substr(r.id,14) NOT GLOB '*[^0-9a-f]*'
|
||||
AND json_extract(r.payload,'$.op') IN ('order','market_buy')
|
||||
AND json_type(r.response,'$.order')='integer'
|
||||
ON CONFLICT(hash) DO NOTHING;
|
||||
|
||||
CREATE TRIGGER IF NOT EXISTS bind_signed_order AFTER INSERT ON requests
|
||||
WHEN NEW.id GLOB 'clob-order:0x*' AND length(NEW.id)=77 AND substr(NEW.id,14) NOT GLOB '*[^0-9a-f]*'
|
||||
AND json_extract(NEW.payload,'$.op') IN ('order','market_buy')
|
||||
AND json_type(NEW.response,'$.order')='integer' BEGIN
|
||||
INSERT INTO signed_order_ids(hash,order_seq)
|
||||
VALUES(substr(NEW.id,12),json_extract(NEW.response,'$.order'));
|
||||
END;
|
||||
COMMIT;
|
||||
@@ -1,5 +1,6 @@
|
||||
pub(crate) mod http;
|
||||
mod protocol;
|
||||
pub(super) mod protocol;
|
||||
pub(crate) mod snapshot;
|
||||
|
||||
use crate::{
|
||||
inventory::{decimal, UNIT},
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
BEGIN IMMEDIATE;
|
||||
-- Trade executions and wallet movements have independent ID sequences.
|
||||
-- Record their shared write order so a sale and a split in the same
|
||||
-- millisecond can be replayed in the order in which they committed.
|
||||
CREATE TABLE IF NOT EXISTS position_economics_order (
|
||||
seq INTEGER PRIMARY KEY,
|
||||
source INTEGER NOT NULL,
|
||||
record INTEGER NOT NULL,
|
||||
UNIQUE(source,record)
|
||||
);
|
||||
CREATE TRIGGER IF NOT EXISTS cost_order_fill AFTER INSERT ON fills BEGIN
|
||||
INSERT INTO position_economics_order(source,record) VALUES(1,NEW.seq);
|
||||
END;
|
||||
CREATE TRIGGER IF NOT EXISTS cost_order_paired AFTER INSERT ON paired_fills BEGIN
|
||||
INSERT INTO position_economics_order(source,record) VALUES(1,NEW.seq);
|
||||
END;
|
||||
CREATE TRIGGER IF NOT EXISTS cost_order_wallet AFTER INSERT ON wallet_movements
|
||||
WHEN NEW.kind IN ('SPLIT','MERGE','REDEEM','CONVERSION') BEGIN
|
||||
INSERT INTO position_economics_order(source,record) VALUES(0,NEW.id);
|
||||
END;
|
||||
COMMIT;
|
||||
@@ -2,7 +2,7 @@ use super::{marked_holdings, protocol::CONTRACTS};
|
||||
use crate::{
|
||||
expiry,
|
||||
inventory::decimal,
|
||||
validation::{condition_filter, hex_id, ConditionList},
|
||||
validation::{condition_filter, hex_id},
|
||||
Exchange, MarketDataError,
|
||||
};
|
||||
use rusqlite::TransactionBehavior;
|
||||
@@ -14,7 +14,7 @@ use serde_json::{json, Value};
|
||||
pub struct ValueQuery {
|
||||
user: String,
|
||||
#[serde(alias = "condition_id", alias = "conditionId")]
|
||||
pub condition: Option<ConditionList>,
|
||||
condition: Option<String>,
|
||||
}
|
||||
|
||||
impl Exchange {
|
||||
@@ -38,7 +38,7 @@ impl Exchange {
|
||||
{
|
||||
return Err(MarketDataError::Invalid("invalid user".into()));
|
||||
}
|
||||
let conditions = condition_filter(query.condition.as_ref(), &tx)?;
|
||||
let conditions = condition_filter(query.condition.as_deref(), &tx)?;
|
||||
let (priced, missing) = marked_holdings(&tx, user, conditions.as_deref(), wallet)
|
||||
.map_err(|_| MarketDataError::Unavailable)?;
|
||||
if missing != 0 {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// Polygon deployments listed at https://docs.polymarket.com/resources/contracts.
|
||||
// For upgradeable contracts, use the public proxy address.
|
||||
pub(super) const CONTRACTS: &[&str] = &[
|
||||
pub(crate) const CONTRACTS: &[&str] = &[
|
||||
"0xE111180000d2663C0091e4f400237545B87B996B", // CTF Exchange
|
||||
"0xe2222d279d744050d28e00520010520000310F59", // Neg Risk CTF Exchange
|
||||
"0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296", // Neg Risk Adapter (CTF negative-risk approvals)
|
||||
|
||||
@@ -0,0 +1,293 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
WITH legs AS (
|
||||
SELECT 1 AS source,t.execution AS record,t.order_seq AS leg,t.at_ms,
|
||||
t.side AS operation,t.quantity*10000 AS shares,t.quantity*t.price AS cash
|
||||
FROM wallet_trade_legs t
|
||||
WHERE t.account COLLATE NOCASE=?1 AND t.market=?2 AND t.outcome=?3
|
||||
AND (t.at_ms IS NULL OR t.at_ms<?4)
|
||||
UNION ALL
|
||||
SELECT 0,w.id,0,w.at_ms,
|
||||
CASE WHEN w.kind='REDEEM' AND json_extract(r.response,'$.amounts_micros') IS NULL
|
||||
THEN 'FULL_REDEEM' ELSE w.kind END,
|
||||
CASE WHEN w.kind='REDEEM' THEN json_extract(r.response,
|
||||
CASE ?3 WHEN 'YES' THEN '$.amounts_micros[0]' ELSE '$.amounts_micros[1]' END)
|
||||
ELSE COALESCE(p.shares_micros,w.shares*1000000) END,
|
||||
COALESCE(p.cash_micros,w.cash_delta*10000)
|
||||
FROM wallet_movements w
|
||||
LEFT JOIN precise_movements p ON p.request_id=w.request_id AND p.account=w.account
|
||||
JOIN requests r ON r.id=w.request_id
|
||||
WHERE w.account COLLATE NOCASE=?1 AND w.market=?2 AND w.kind IN ('SPLIT','MERGE','REDEEM')
|
||||
AND (w.at_ms IS NULL OR w.at_ms<?4)
|
||||
UNION ALL
|
||||
SELECT 0,w.id,0,w.at_ms,'CONVERSION',NULL,0
|
||||
FROM wallet_movements w JOIN requests r ON r.id=w.request_id
|
||||
WHERE w.kind='CONVERSION' AND (w.at_ms IS NULL OR w.at_ms<?4) AND (
|
||||
(w.account COLLATE NOCASE=?1 AND ?2 IN (
|
||||
SELECT value FROM json_each(r.response, CASE ?3 WHEN 'YES' THEN '$.yes_markets' ELSE '$.no_markets' END)
|
||||
)) OR (?3='YES' AND json_extract(r.response,'$.conversion_fee.yes_micros_per_market')>0
|
||||
AND json_extract(r.response,'$.conversion_fee.vault') COLLATE NOCASE=?1
|
||||
AND ?2 IN (SELECT value FROM json_each(r.response,'$.yes_markets')))
|
||||
)
|
||||
), ordered AS (
|
||||
SELECT l.*,o.seq AS write_seq
|
||||
FROM legs l LEFT JOIN position_economics_order o ON o.source=l.source AND o.record=l.record
|
||||
)
|
||||
-- The pre-journal records lack a shared order within a millisecond.
|
||||
SELECT operation,shares,cash,
|
||||
at_ms IS NULL OR (write_seq IS NULL AND
|
||||
MIN(source) OVER legacy_tick<>MAX(source) OVER legacy_tick) AS ambiguous
|
||||
FROM ordered
|
||||
WINDOW legacy_tick AS (PARTITION BY write_seq IS NULL,at_ms)
|
||||
ORDER BY write_seq IS NOT NULL,CASE WHEN write_seq IS NULL THEN at_ms END,
|
||||
write_seq,source,record,leg
|
||||
@@ -0,0 +1,31 @@
|
||||
WITH holdings AS (
|
||||
SELECT account,market,outcome,shares_micros,
|
||||
ROW_NUMBER() OVER (PARTITION BY account,market,outcome ORDER BY at_ms DESC,seq DESC) AS n
|
||||
FROM position_balance_history
|
||||
WHERE account COLLATE NOCASE=?1 AND at_ms<?2
|
||||
), totals AS (
|
||||
SELECT market,outcome,SUM(shares_micros) AS size FROM holdings WHERE n=1
|
||||
GROUP BY market,outcome HAVING SUM(shares_micros)>100000
|
||||
)
|
||||
SELECT p.market,p.outcome,p.size,w.question,w.slug,
|
||||
CASE p.outcome WHEN 'YES' THEN w.yes_label ELSE w.no_label END,
|
||||
event.slug,settlement.at_ms,settlement.winner,q.at_ms,q.yes_bid,q.yes_ask,
|
||||
trade.at_ms,trade.price
|
||||
FROM totals p
|
||||
JOIN market_wire_metadata w ON w.market=p.market
|
||||
LEFT JOIN listed_markets l ON l.market=p.market
|
||||
LEFT JOIN numbered_events event ON event.id=l.event
|
||||
LEFT JOIN price_settlements settlement ON settlement.market=p.market AND settlement.at_ms<?2
|
||||
LEFT JOIN quote_events q ON q.seq=(
|
||||
SELECT seq FROM quote_events WHERE market=p.market AND at_ms<?2
|
||||
AND yes_bid IS NOT NULL AND yes_ask BETWEEN yes_bid AND yes_bid+1000
|
||||
ORDER BY at_ms DESC,seq DESC LIMIT 1
|
||||
)
|
||||
LEFT JOIN (
|
||||
SELECT market,outcome,at_ms,price_micros AS price,fill
|
||||
FROM outcome_trade_prices WHERE at_ms<?2
|
||||
) trade ON trade.market=p.market AND trade.outcome=p.outcome AND trade.fill=(
|
||||
SELECT fill FROM outcome_trade_prices WHERE market=p.market AND outcome=p.outcome AND at_ms<?2
|
||||
ORDER BY at_ms DESC,fill DESC LIMIT 1
|
||||
)
|
||||
ORDER BY p.market,p.outcome
|
||||
@@ -0,0 +1,73 @@
|
||||
use crate::{assets, inventory, validation::identifier};
|
||||
use anyhow::{ensure, Result};
|
||||
use rusqlite::{params, Connection, Transaction, TransactionBehavior};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
pub(crate) fn install(db: &mut Connection) -> Result<()> {
|
||||
let installed = |db: &Connection| {
|
||||
db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM sqlite_schema
|
||||
WHERE type='table' AND name='position_balance_history_start')",
|
||||
[],
|
||||
|row| row.get::<_, bool>(0),
|
||||
)
|
||||
};
|
||||
if !installed(db)? {
|
||||
let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
||||
if !installed(&tx)? {
|
||||
tx.execute_batch(include_str!("position_balance_history_schema.sql"))?;
|
||||
}
|
||||
tx.commit()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Record only end-of-transaction ownership changes. Sell reservations can change
|
||||
/// the ledger's available and reserved columns without changing ownership.
|
||||
pub(crate) fn flush(tx: &Transaction<'_>) -> Result<()> {
|
||||
let pending: bool = tx.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM position_balance_pending)",
|
||||
[],
|
||||
|row| row.get(0),
|
||||
)?;
|
||||
if pending {
|
||||
tx.execute_batch(include_str!("position_balance_history_flush.sql"))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn read(tx: &Transaction<'_>, account: &str, before_ms: i64) -> Result<Value> {
|
||||
identifier(account)?;
|
||||
let (start, now): (i64, i64) = tx.query_row(
|
||||
"SELECT at_ms,CAST(unixepoch('subsec')*1000 AS INTEGER)
|
||||
FROM position_balance_history_start WHERE singleton=1",
|
||||
[],
|
||||
|row| Ok((row.get(0)?, row.get(1)?)),
|
||||
)?;
|
||||
ensure!(
|
||||
before_ms > start && before_ms <= now,
|
||||
"before_ms must be after the history baseline ({start}) and no later than now ({now})"
|
||||
);
|
||||
let mut stmt = tx.prepare_cached(
|
||||
"WITH balances AS (
|
||||
SELECT market,outcome,shares_micros,
|
||||
ROW_NUMBER() OVER (PARTITION BY market,outcome ORDER BY at_ms DESC,seq DESC) AS n
|
||||
FROM position_balance_history WHERE account=?1 AND at_ms<?2
|
||||
)
|
||||
SELECT market,outcome,shares_micros FROM balances
|
||||
WHERE n=1 AND shares_micros>0 ORDER BY market,outcome",
|
||||
)?;
|
||||
let data = stmt
|
||||
.query_map(params![account, before_ms], |row| {
|
||||
let market: String = row.get(0)?;
|
||||
let outcome: String = row.get(1)?;
|
||||
let shares: i64 = row.get(2)?;
|
||||
Ok(json!({
|
||||
"asset_id":assets::id(&market,&outcome),
|
||||
"market":market,"outcome":outcome,"shares_micros":shares,
|
||||
"size":inventory::decimal(shares.into(),inventory::UNIT)
|
||||
}))
|
||||
})?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
Ok(json!({"account":account,"before_ms":before_ms,"history_start_ms":start,"data":data}))
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
WITH clock(at_ms) AS MATERIALIZED (
|
||||
SELECT MAX(CAST(unixepoch('subsec')*1000 AS INTEGER),s.at_ms,
|
||||
COALESCE((SELECT MAX(at_ms) FROM position_balance_history),s.at_ms))
|
||||
FROM position_balance_history_start s
|
||||
), affected AS (
|
||||
SELECT p.account,p.market,p.outcome,c.at_ms,
|
||||
COALESCE(v.available+v.reserved,0) AS shares_micros,
|
||||
COALESCE((SELECT h.shares_micros FROM position_balance_history h
|
||||
WHERE h.account=p.account AND h.market=p.market AND h.outcome=p.outcome
|
||||
ORDER BY h.at_ms DESC,h.seq DESC LIMIT 1),0) AS previous
|
||||
FROM position_balance_pending p
|
||||
CROSS JOIN clock c
|
||||
LEFT JOIN position_units v USING(account,market,outcome)
|
||||
)
|
||||
INSERT INTO position_balance_history(account,market,outcome,at_ms,shares_micros)
|
||||
SELECT account,market,outcome,at_ms,shares_micros
|
||||
FROM affected WHERE shares_micros<>previous;
|
||||
DELETE FROM position_balance_pending;
|
||||
@@ -0,0 +1,62 @@
|
||||
CREATE TABLE position_balance_history_start (
|
||||
singleton INTEGER PRIMARY KEY CHECK(singleton=1),
|
||||
at_ms INTEGER NOT NULL
|
||||
);
|
||||
INSERT INTO position_balance_history_start VALUES(1,CAST(unixepoch('subsec')*1000 AS INTEGER));
|
||||
|
||||
CREATE TABLE position_balance_history (
|
||||
seq INTEGER PRIMARY KEY,
|
||||
account TEXT NOT NULL, market TEXT NOT NULL, outcome TEXT NOT NULL,
|
||||
at_ms INTEGER NOT NULL, shares_micros INTEGER NOT NULL CHECK(shares_micros>=0)
|
||||
);
|
||||
CREATE INDEX position_balance_history_by_holding
|
||||
ON position_balance_history(account,market,outcome,at_ms DESC,seq DESC);
|
||||
CREATE INDEX position_balance_history_by_time ON position_balance_history(at_ms);
|
||||
INSERT INTO position_balance_history(account,market,outcome,at_ms,shares_micros)
|
||||
SELECT account,market,outcome,s.at_ms,available+reserved
|
||||
FROM position_units CROSS JOIN position_balance_history_start s
|
||||
WHERE available+reserved>0;
|
||||
|
||||
CREATE TABLE position_balance_pending (
|
||||
account TEXT NOT NULL, market TEXT NOT NULL, outcome TEXT NOT NULL,
|
||||
PRIMARY KEY(account,market,outcome)
|
||||
) WITHOUT ROWID;
|
||||
|
||||
CREATE TRIGGER position_history_quantity AFTER UPDATE OF quantity ON positions
|
||||
WHEN NEW.quantity<>OLD.quantity BEGIN
|
||||
INSERT INTO position_balance_pending VALUES(NEW.account,NEW.market,NEW.outcome)
|
||||
ON CONFLICT(account,market,outcome) DO NOTHING;
|
||||
END;
|
||||
CREATE TRIGGER position_history_new_quantity AFTER INSERT ON positions
|
||||
WHEN NEW.quantity>0 BEGIN
|
||||
INSERT INTO position_balance_pending VALUES(NEW.account,NEW.market,NEW.outcome)
|
||||
ON CONFLICT(account,market,outcome) DO NOTHING;
|
||||
END;
|
||||
CREATE TRIGGER position_history_removed_quantity AFTER DELETE ON positions
|
||||
WHEN OLD.quantity>0 BEGIN
|
||||
INSERT INTO position_balance_pending VALUES(OLD.account,OLD.market,OLD.outcome)
|
||||
ON CONFLICT(account,market,outcome) DO NOTHING;
|
||||
END;
|
||||
CREATE TRIGGER position_history_new_remainder AFTER INSERT ON position_remainders
|
||||
WHEN NEW.micros<>0 BEGIN
|
||||
INSERT INTO position_balance_pending VALUES(NEW.account,NEW.market,NEW.outcome)
|
||||
ON CONFLICT(account,market,outcome) DO NOTHING;
|
||||
END;
|
||||
CREATE TRIGGER position_history_remainder AFTER UPDATE OF micros ON position_remainders
|
||||
WHEN NEW.micros<>OLD.micros BEGIN
|
||||
INSERT INTO position_balance_pending VALUES(NEW.account,NEW.market,NEW.outcome)
|
||||
ON CONFLICT(account,market,outcome) DO NOTHING;
|
||||
END;
|
||||
CREATE TRIGGER position_history_removed_remainder AFTER DELETE ON position_remainders
|
||||
WHEN OLD.micros<>0 BEGIN
|
||||
INSERT INTO position_balance_pending VALUES(OLD.account,OLD.market,OLD.outcome)
|
||||
ON CONFLICT(account,market,outcome) DO NOTHING;
|
||||
END;
|
||||
-- A seller can lose ownership through an execution that only changes a reserved order.
|
||||
CREATE TRIGGER position_history_execution AFTER UPDATE OF remaining,status ON orders
|
||||
WHEN OLD.side='sell' AND OLD.status='live'
|
||||
AND (OLD.remaining<>NEW.remaining OR OLD.status<>NEW.status)
|
||||
BEGIN
|
||||
INSERT INTO position_balance_pending VALUES(OLD.account,OLD.market,OLD.outcome)
|
||||
ON CONFLICT(account,market,outcome) DO NOTHING;
|
||||
END;
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::{Anchor, Filters, Scan};
|
||||
use crate::{
|
||||
assets, inventory, lots,
|
||||
validation::{directory_selector, identifier, ConditionList},
|
||||
validation::{directory_selector, identifier},
|
||||
Exchange, MarketDataError,
|
||||
};
|
||||
use anyhow::{ensure, Context, Result};
|
||||
@@ -17,7 +17,7 @@ use sha2::Sha256;
|
||||
pub struct TradeQuery {
|
||||
user: Option<String>,
|
||||
#[serde(alias = "condition_id", alias = "conditionId")]
|
||||
pub condition: Option<ConditionList>,
|
||||
condition: Option<String>,
|
||||
#[serde(alias = "eventId")]
|
||||
event_id: Option<String>,
|
||||
side: Option<String>,
|
||||
@@ -99,15 +99,8 @@ impl TradeQuery {
|
||||
if let Some(user) = &self.user {
|
||||
identifier(user)?;
|
||||
}
|
||||
let market =
|
||||
directory_selector(db, self.condition.as_ref().map(ConditionList::keys), false)?;
|
||||
let event = directory_selector(
|
||||
db,
|
||||
self.event_id
|
||||
.as_deref()
|
||||
.map(|ids| ids.split(',').map(str::trim)),
|
||||
true,
|
||||
)?;
|
||||
let market = directory_selector(db, self.condition.as_deref(), false)?;
|
||||
let event = directory_selector(db, self.event_id.as_deref(), true)?;
|
||||
let scoped = self.user.is_some() || market.is_some() || event.is_some();
|
||||
let (now,default_start):(i64,i64)=db.query_row(
|
||||
"SELECT CAST(unixepoch('subsec')*1000 AS INTEGER),CASE WHEN ?1 THEN CAST(unixepoch('now','-3 years','subsec')*1000 AS INTEGER) ELSE unixepoch('now','start of month','-1 month')*1000 END",
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
use super::question_key;
|
||||
use crate::{
|
||||
validation::{directory_selector, ConditionList, IdSelector},
|
||||
Exchange, MarketDataError,
|
||||
};
|
||||
use crate::{validation::directory_selector, Exchange, MarketDataError};
|
||||
use anyhow::{ensure, Result};
|
||||
use rusqlite::{named_params, Connection, Row};
|
||||
use serde::Deserialize;
|
||||
@@ -14,7 +11,7 @@ pub struct ResolutionQuery {
|
||||
#[serde(alias = "questionId")]
|
||||
question_id: Option<String>,
|
||||
#[serde(alias = "condition_id", alias = "conditionId")]
|
||||
pub condition: Option<ConditionList>,
|
||||
condition: Option<String>,
|
||||
#[serde(alias = "eventId")]
|
||||
event_id: Option<String>,
|
||||
}
|
||||
@@ -88,26 +85,17 @@ impl ResolutionQuery {
|
||||
"supply exactly one of question_id, condition, event_id"
|
||||
);
|
||||
let question = self.question_id.as_deref().map(question_key).transpose()?;
|
||||
let ids = |selector: Option<IdSelector>| -> Result<Option<String>> {
|
||||
selector
|
||||
let ids = |raw: Option<&str>, numeric| -> Result<Option<String>> {
|
||||
directory_selector(db, raw, numeric)?
|
||||
.map(|s| Ok(serde_json::to_string(&s.ids()?)?))
|
||||
.transpose()
|
||||
};
|
||||
let conditions =
|
||||
directory_selector(db, self.condition.as_ref().map(ConditionList::keys), false)?;
|
||||
let events = directory_selector(
|
||||
db,
|
||||
self.event_id
|
||||
.as_deref()
|
||||
.map(|ids| ids.split(',').map(str::trim)),
|
||||
true,
|
||||
)?;
|
||||
let mut stmt = db.prepare(include_str!("state.sql"))?;
|
||||
let data = stmt
|
||||
.query_map(
|
||||
named_params! {
|
||||
":question": question, ":conditions": ids(conditions)?,
|
||||
":events": ids(events)?,
|
||||
":question": question, ":conditions": ids(self.condition.as_deref(),false)?,
|
||||
":events": ids(self.event_id.as_deref(),true)?,
|
||||
},
|
||||
|row| resolution(row, question.is_some()),
|
||||
)?
|
||||
|
||||
@@ -125,8 +125,6 @@ END;
|
||||
CREATE TABLE IF NOT EXISTS execution_context (
|
||||
execution INTEGER PRIMARY KEY, taker_order INTEGER REFERENCES orders(seq)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS executions_by_taker_order
|
||||
ON execution_context(taker_order,execution) WHERE taker_order IS NOT NULL;
|
||||
CREATE INDEX IF NOT EXISTS account_orders_history ON orders(account,seq);
|
||||
CREATE INDEX IF NOT EXISTS market_buy_orders ON orders(market,seq) WHERE side='buy';
|
||||
CREATE INDEX IF NOT EXISTS fills_by_bid ON fills(bid,seq);
|
||||
@@ -264,28 +262,6 @@ CREATE TABLE IF NOT EXISTS execution_fees (
|
||||
taker_order INTEGER NOT NULL REFERENCES orders(seq), fee_micros INTEGER NOT NULL CHECK(fee_micros>0)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS fees_by_order ON execution_fees(taker_order);
|
||||
CREATE TABLE IF NOT EXISTS maker_rebate_days (
|
||||
date TEXT PRIMARY KEY,
|
||||
payout_count INTEGER NOT NULL CHECK(payout_count>=0)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS maker_rebate_payouts (
|
||||
date TEXT NOT NULL REFERENCES maker_rebate_days(date),
|
||||
maker TEXT NOT NULL,
|
||||
account TEXT NOT NULL REFERENCES accounts(id),
|
||||
market TEXT NOT NULL REFERENCES markets(id),
|
||||
micros INTEGER NOT NULL CHECK(micros>0),
|
||||
PRIMARY KEY(date,maker,account,market)
|
||||
) WITHOUT ROWID;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS maker_rebate_activity_account ON maker_rebate_payouts(account,date,market);
|
||||
CREATE TABLE IF NOT EXISTS maker_rebate_payment_times (
|
||||
date TEXT PRIMARY KEY REFERENCES maker_rebate_days(date),
|
||||
paid_at_ms INTEGER NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS maker_rebate_progress (
|
||||
singleton INTEGER PRIMARY KEY CHECK(singleton=1),
|
||||
next_ms INTEGER NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS order_keys (
|
||||
order_seq INTEGER PRIMARY KEY REFERENCES orders(seq), key_id TEXT NOT NULL
|
||||
@@ -351,36 +327,3 @@ CREATE TABLE IF NOT EXISTS trade_cursor_key (
|
||||
);
|
||||
INSERT INTO trade_cursor_key(singleton,secret)
|
||||
SELECT 1,randomblob(32) WHERE NOT EXISTS(SELECT 1 FROM trade_cursor_key);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS issued_api_keys (
|
||||
issuer TEXT NOT NULL,
|
||||
nonce BLOB NOT NULL CHECK(length(nonce)=32),
|
||||
id TEXT NOT NULL UNIQUE,
|
||||
PRIMARY KEY(issuer,nonce)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS revoked_api_keys (
|
||||
id TEXT PRIMARY KEY REFERENCES issued_api_keys(id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS market_order_delays (
|
||||
market TEXT PRIMARY KEY REFERENCES markets(id),
|
||||
delay_ms INTEGER NOT NULL CHECK(delay_ms>=0)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS delayed_orders (
|
||||
seq INTEGER PRIMARY KEY,
|
||||
request_id TEXT NOT NULL UNIQUE,
|
||||
account TEXT NOT NULL,
|
||||
market TEXT NOT NULL REFERENCES markets(id),
|
||||
outcome TEXT NOT NULL,
|
||||
payload TEXT NOT NULL,
|
||||
maker TEXT NOT NULL,
|
||||
ready_at_ms INTEGER NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT 'delayed' CHECK(status IN ('delayed','submitted','rejected'))
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS delayed_orders_due ON delayed_orders(ready_at_ms,seq)
|
||||
WHERE status='delayed';
|
||||
CREATE INDEX IF NOT EXISTS delayed_orders_account ON delayed_orders(account,market,outcome,seq)
|
||||
WHERE status='delayed';
|
||||
CREATE TABLE IF NOT EXISTS synchronous_delayed_orders (
|
||||
request_id TEXT PRIMARY KEY REFERENCES delayed_orders(request_id)
|
||||
);
|
||||
|
||||
@@ -53,74 +53,47 @@ impl IdSelector {
|
||||
}
|
||||
}
|
||||
|
||||
/// A Data API condition selector, split before resolving any aliases.
|
||||
pub struct ConditionList(Vec<String>);
|
||||
|
||||
impl<'de> serde::Deserialize<'de> for ConditionList {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
||||
let csv = <String as serde::Deserialize>::deserialize(deserializer)?;
|
||||
Ok(Self(
|
||||
csv.split(',').map(|part| part.trim().to_owned()).collect(),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
impl ConditionList {
|
||||
pub fn resolve(&mut self, mut local_id: impl FnMut(&str) -> Option<String>) {
|
||||
for key in &mut self.0 {
|
||||
if let Some(resolved) = local_id(key) {
|
||||
*key = resolved;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn keys(&self) -> impl Iterator<Item = &str> {
|
||||
self.0.iter().map(String::as_str)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn directory_selector<'a>(
|
||||
pub(crate) fn directory_selector(
|
||||
db: &Connection,
|
||||
input: Option<impl Iterator<Item = &'a str>>,
|
||||
raw: Option<&str>,
|
||||
numeric: bool,
|
||||
) -> Result<Option<IdSelector>> {
|
||||
input
|
||||
.map(|input| {
|
||||
let mut keys = Vec::new();
|
||||
for id in input {
|
||||
identifier(id)?;
|
||||
if numeric {
|
||||
let n = id.parse::<i64>().context("invalid event_id")?;
|
||||
ensure!(n > 0, "invalid event_id");
|
||||
keys.push(n.to_string());
|
||||
} else {
|
||||
if id.starts_with("0x") && !hex_id(id, 64) {
|
||||
// Locally listed condition IDs may legitimately use a short 0x prefix.
|
||||
let listed: bool = db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM markets WHERE id=?1)",
|
||||
[id],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
ensure!(listed, "invalid condition: {id}");
|
||||
}
|
||||
keys.push(id.to_owned());
|
||||
raw.map(|raw| {
|
||||
let mut keys = Vec::new();
|
||||
for id in raw.split(',').map(str::trim) {
|
||||
identifier(id)?;
|
||||
if numeric {
|
||||
let n = id.parse::<i64>().context("invalid event_id")?;
|
||||
ensure!(n > 0, "invalid event_id");
|
||||
keys.push(n.to_string());
|
||||
} else {
|
||||
if id.starts_with("0x") && !hex_id(id, 64) {
|
||||
// Locally listed condition IDs may legitimately use a short 0x prefix.
|
||||
let listed: bool = db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM markets WHERE id=?1)",
|
||||
[id],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
ensure!(listed, "invalid condition: {id}");
|
||||
}
|
||||
keys.push(id.to_owned());
|
||||
}
|
||||
Ok(IdSelector::Many(keys))
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
Ok(IdSelector::Many(keys))
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
|
||||
pub(crate) fn condition_filter(
|
||||
conditions: Option<&ConditionList>,
|
||||
raw: Option<&str>,
|
||||
db: &Connection,
|
||||
) -> Result<Option<String>, MarketDataError> {
|
||||
let Some(conditions) = conditions else {
|
||||
let Some(raw) = raw else {
|
||||
return Ok(None);
|
||||
};
|
||||
let selector = IdSelector::Many(
|
||||
conditions
|
||||
.keys()
|
||||
raw.split(',')
|
||||
.map(str::trim)
|
||||
.map(|id| {
|
||||
if hex_id(id, 64) {
|
||||
id.to_ascii_lowercase()
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
use exchange::Exchange;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
#[test]
|
||||
fn combo_replays_canonical_definition_and_keeps_rounding_dust() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("combo.sqlite");
|
||||
let mut db = Exchange::open(&path).unwrap();
|
||||
let commands = include_str!("../../../docs/examples/combo-ledger.jsonl")
|
||||
.lines()
|
||||
.map(|line| serde_json::from_str::<Value>(line).unwrap())
|
||||
.collect::<Vec<_>>();
|
||||
for command in &commands[..3] {
|
||||
db.execute(command.clone()).unwrap();
|
||||
}
|
||||
let definition = db.execute(commands[3].clone()).unwrap();
|
||||
let combo = definition["combo"].as_str().unwrap();
|
||||
assert_eq!(commands[4]["combo"], combo);
|
||||
assert_eq!(definition["legs"][0]["market"], "combo-a");
|
||||
let same = db
|
||||
.execute(json!({
|
||||
"op":"prepare_combo","id":"reordered","legs":[{"market":"combo-a","outcome":"YES"},
|
||||
{"market":"combo-b","outcome":"NO"}]
|
||||
}))
|
||||
.unwrap();
|
||||
assert_eq!(same, definition);
|
||||
assert!(db
|
||||
.execute(json!({
|
||||
"op":"prepare_combo","id":"contradiction","legs":[{"market":"combo-a","outcome":"YES"},
|
||||
{"market":"combo-a","outcome":"NO"}]
|
||||
}))
|
||||
.is_err());
|
||||
let split = db.execute(commands[4].clone()).unwrap();
|
||||
let view = json!({"op":"combo","combo":combo,"account":"alice"});
|
||||
assert!(!db.execute(view.clone()).unwrap()["redeemable"]
|
||||
.as_bool()
|
||||
.unwrap());
|
||||
assert!(db.execute(commands[10].clone()).is_err());
|
||||
|
||||
drop(db);
|
||||
let mut db = Exchange::open(&path).unwrap();
|
||||
assert_eq!(db.execute(commands[4].clone()).unwrap(), split);
|
||||
assert_eq!(
|
||||
db.execute(view.clone()).unwrap()["balances_micros"],
|
||||
json!([1000003, 1000003])
|
||||
);
|
||||
for command in &commands[5..10] {
|
||||
db.execute(command.clone()).unwrap();
|
||||
}
|
||||
let settled = db.execute(view.clone()).unwrap();
|
||||
assert_eq!(settled["payout_micros_per_share"], json!([250000, 750000]));
|
||||
assert_eq!(
|
||||
db.execute(commands[10].clone()).unwrap()["paid_micros"],
|
||||
250000
|
||||
);
|
||||
assert_eq!(
|
||||
db.execute(commands[11].clone()).unwrap()["paid_micros"],
|
||||
750000
|
||||
);
|
||||
let final_state = db.execute(view).unwrap();
|
||||
assert_eq!(final_state["balances_micros"], json!([0, 0]));
|
||||
assert_eq!(final_state["collateral_micros"], 0);
|
||||
assert_eq!(final_state["rounding_dust_micros"], 1);
|
||||
assert_eq!(
|
||||
db.execute(json!({"op":"balance","account":"alice"}))
|
||||
.unwrap()["available_micros"],
|
||||
9999999
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_leg_allows_early_redemption_even_after_an_unresolved_leg() {
|
||||
let mut db = Exchange::open(":memory:").unwrap();
|
||||
for command in [
|
||||
json!({"op":"fund","id":"fund","account":"alice","cents":200}),
|
||||
json!({"op":"list","id":"a","market":"a-pending","rules":"pending"}),
|
||||
json!({"op":"list","id":"b","market":"b-loss","rules":"settle early"}),
|
||||
] {
|
||||
db.execute(command).unwrap();
|
||||
}
|
||||
let prepared = db
|
||||
.execute(json!({
|
||||
"op":"prepare_combo","id":"combo","legs":[{"market":"a-pending","outcome":"YES"},
|
||||
{"market":"b-loss","outcome":"NO"}]
|
||||
}))
|
||||
.unwrap();
|
||||
let combo = prepared["combo"].as_str().unwrap();
|
||||
for command in [
|
||||
json!({"op":"split_combo","id":"split","combo":combo,"account":"alice","qty":2}),
|
||||
json!({"op":"close","id":"close","market":"b-loss"}),
|
||||
json!({"op":"finalize","id":"final","market":"b-loss","winner":"YES"}),
|
||||
] {
|
||||
db.execute(command).unwrap();
|
||||
}
|
||||
let view = json!({"op":"combo","combo":combo,"account":"alice"});
|
||||
let settled = db.execute(view.clone()).unwrap();
|
||||
assert!(settled["legs"][0]["payout_micros_per_share"].is_null());
|
||||
assert_eq!(settled["payout_micros_per_share"], json!([0, 1000000]));
|
||||
let yes=db.execute(json!({"op":"redeem_combo","id":"yes","combo":combo,"account":"alice","qty":2,"outcome":"YES"})).unwrap();
|
||||
let no=db.execute(json!({"op":"redeem_combo","id":"no","combo":combo,"account":"alice","qty":2,"outcome":"NO"})).unwrap();
|
||||
assert_eq!(yes["paid_micros"], 0);
|
||||
assert_eq!(no["paid_micros"], 2000000);
|
||||
assert_eq!(db.execute(view).unwrap()["rounding_dust_micros"], 0);
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
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());
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
use exchange::Exchange;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
fn commands() -> Vec<Value> {
|
||||
include_str!("../../../docs/examples/combo-rfq.jsonl")
|
||||
.lines()
|
||||
.map(|line| {
|
||||
let mut cmd: Value = serde_json::from_str(line).unwrap();
|
||||
if cmd["op"] == "request_combo_quote" {
|
||||
cmd["submission_window_ms"] = json!(300000);
|
||||
cmd["acceptance_window_ms"] = json!(300000);
|
||||
cmd["last_look_ms"] = json!(300000);
|
||||
}
|
||||
cmd
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn combo_rfq_reserves_then_mints_merges_and_transfers() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("rfq.sqlite");
|
||||
let mut db = Exchange::open(&path).unwrap();
|
||||
let cmds = commands();
|
||||
for cmd in &cmds[..6] {
|
||||
db.execute(cmd.clone()).unwrap();
|
||||
}
|
||||
let combo = cmds[5]["combo"].as_str().unwrap();
|
||||
assert_eq!(
|
||||
db.execute(cmds[6].clone()).unwrap()["rfqs"][0]["rfq_id"],
|
||||
"rfq-buy"
|
||||
);
|
||||
db.execute(cmds[7].clone()).unwrap();
|
||||
assert_eq!(
|
||||
db.execute(cmds[8].clone()).unwrap()["status"],
|
||||
"AWAITING_MAKER_CONFIRMATION"
|
||||
);
|
||||
let cash = json!({"op":"balance","account":"taker"});
|
||||
let held = db.execute(cash.clone()).unwrap();
|
||||
assert_eq!(held["reserved_micros"], 1400000);
|
||||
assert_eq!(held["total_cash_micros"], 5000000);
|
||||
assert!(db
|
||||
.execute(
|
||||
json!({"op":"respond_combo_quote","id":"wrong-maker","rfq":"rfq-buy",
|
||||
"quote":"rfq-mint-quote","maker":"taker","confirm":true})
|
||||
)
|
||||
.is_err());
|
||||
drop(db);
|
||||
|
||||
let mut db = Exchange::open(&path).unwrap();
|
||||
let mint = db.execute(cmds[9].clone()).unwrap();
|
||||
assert_eq!(mint["fill"]["flow"], "MINT");
|
||||
assert_eq!(db.execute(cmds[9].clone()).unwrap(), mint);
|
||||
assert_eq!(db.execute(cash.clone()).unwrap()["reserved_micros"], 0);
|
||||
for cmd in &cmds[11..14] {
|
||||
db.execute(cmd.clone()).unwrap();
|
||||
}
|
||||
let held = db.execute(cmds[15].clone()).unwrap();
|
||||
assert_eq!(held["balances_micros"], json!([4000000, 0]));
|
||||
assert_eq!(held["available_micros"], json!([2500000, 0]));
|
||||
let merge = db.execute(cmds[14].clone()).unwrap();
|
||||
assert_eq!(merge["fill"]["flow"], "MERGE");
|
||||
assert_eq!(
|
||||
db.execute(cmds[15].clone()).unwrap()["collateral_micros"],
|
||||
2500000
|
||||
);
|
||||
assert_eq!(
|
||||
db.execute(cash.clone()).unwrap()["available_micros"],
|
||||
4200000
|
||||
);
|
||||
|
||||
for cmd in [
|
||||
json!({"op":"request_combo_quote","id":"transfer","combo":combo,"requester":"taker",
|
||||
"direction":"SELL","side":"YES","shares_micros":1000000}),
|
||||
json!({"op":"quote_combo","id":"transfer-quote","rfq":"transfer","maker":"maker",
|
||||
"source":"collateral","price_micros":500000,"shares_micros":1000000}),
|
||||
json!({"op":"accept_combo_quote","id":"transfer-accept","rfq":"transfer","requester":"taker","quote":"transfer-quote"}),
|
||||
] {
|
||||
db.execute(cmd).unwrap();
|
||||
}
|
||||
let transfer = db
|
||||
.execute(
|
||||
json!({"op":"respond_combo_quote","id":"transfer-fill","rfq":"transfer",
|
||||
"quote":"transfer-quote","maker":"maker","confirm":true}),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(transfer["fill"]["flow"], "TRANSFER");
|
||||
assert_eq!(db.execute(cash).unwrap()["available_micros"], 4700000);
|
||||
assert_eq!(
|
||||
db.execute(cmds[15].clone()).unwrap()["collateral_micros"],
|
||||
2500000
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn combo_rfq_recovers_locks_on_expiry_and_rejects_competing_acceptance() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("rfq-expiry.sqlite");
|
||||
let mut db = Exchange::open(&path).unwrap();
|
||||
let cmds = commands();
|
||||
for cmd in &cmds[..9] {
|
||||
db.execute(cmd.clone()).unwrap();
|
||||
}
|
||||
let combo = cmds[5]["combo"].as_str().unwrap();
|
||||
for cmd in [
|
||||
json!({"op":"request_combo_quote","id":"second","combo":combo,"requester":"taker",
|
||||
"direction":"BUY","side":"NO","notional_micros":4000000}),
|
||||
json!({"op":"quote_combo","id":"second-quote","rfq":"second","maker":"maker",
|
||||
"source":"collateral","price_micros":800000,"shares_micros":5000000}),
|
||||
] {
|
||||
db.execute(cmd).unwrap();
|
||||
}
|
||||
let accept = json!({"op":"accept_combo_quote","id":"second-accept","rfq":"second","requester":"taker","quote":"second-quote"});
|
||||
assert!(db.execute(accept.clone()).is_err());
|
||||
let status = json!({"op":"combo_rfq","rfq":"second","account":"taker"});
|
||||
assert_eq!(
|
||||
db.execute(status.clone()).unwrap()["status"],
|
||||
"AWAITING_REQUESTER_ACCEPTANCE"
|
||||
);
|
||||
let conn = rusqlite::Connection::open(&path).unwrap();
|
||||
conn.execute("UPDATE combo_rfqs SET confirm_by=0 WHERE id='rfq-buy'", [])
|
||||
.unwrap();
|
||||
drop(conn);
|
||||
drop(db);
|
||||
|
||||
let mut db = Exchange::open(&path).unwrap();
|
||||
assert_eq!(db.execute(cmds[10].clone()).unwrap()["status"], "EXPIRED");
|
||||
assert!(db.execute(cmds[9].clone()).is_err());
|
||||
db.execute(accept).unwrap();
|
||||
let decline = db
|
||||
.execute(json!({"op":"respond_combo_quote","id":"decline",
|
||||
"rfq":"second","maker":"maker","quote":"second-quote","confirm":false}))
|
||||
.unwrap();
|
||||
assert_eq!(decline["status"], "FAILED");
|
||||
assert_eq!(decline["failure"], "MAKER_DECLINED");
|
||||
for account in ["taker", "maker"] {
|
||||
let cash = db
|
||||
.execute(json!({"op":"balance","account":account}))
|
||||
.unwrap();
|
||||
assert_eq!(cash["available_micros"], 5000000);
|
||||
assert_eq!(cash["reserved_micros"], 0);
|
||||
}
|
||||
assert_eq!(
|
||||
db.execute(cmds[15].clone()).unwrap()["collateral_micros"],
|
||||
0
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
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));
|
||||
}
|
||||
+180
-160
@@ -22,161 +22,6 @@ fn state(e: &mut Exchange) -> Value {
|
||||
e.execute(json!({"op":"state"})).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn account_event_pages_resume_after_restart_and_preserve_fill_legs() {
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("account-events.sqlite");
|
||||
let mut e = Exchange::open(&path).unwrap();
|
||||
setup(&mut e);
|
||||
e.execute(json!({"op":"open","id":"ev-open","market":"e"}))
|
||||
.unwrap();
|
||||
let ask = e.execute(order("ev-ask", "alice", "sell", 60, 5)).unwrap();
|
||||
let first = e
|
||||
.execute(json!({"op":"account_events","account":"alice","market":"e","limit":1}))
|
||||
.unwrap();
|
||||
assert_eq!(first["events"][0]["type"], "PLACEMENT");
|
||||
assert_eq!(first["events"][0]["size_matched"], "0");
|
||||
let mut rejected = order("ev-rejected", "bob", "buy", 60, 6);
|
||||
rejected["tif"] = json!("FOK");
|
||||
assert!(e.execute(rejected).is_err());
|
||||
let buy = json!({"op":"market_buy","id":"ev-buy","account":"bob","market":"e","outcome":"YES","amount_cents":120});
|
||||
let receipt = e.execute(buy.clone()).unwrap();
|
||||
assert_eq!(receipt["filled"], 2);
|
||||
assert_eq!(e.execute(buy).unwrap(), receipt);
|
||||
e.execute(json!({"op":"cancel","id":"ev-cancel","account":"alice","order":ask["order"]}))
|
||||
.unwrap();
|
||||
let bid = order("ev-yes", "alice", "buy", 60, 1);
|
||||
let mut no = order("ev-no", "bob", "buy", 40, 1);
|
||||
no["outcome"] = json!("NO");
|
||||
e.execute(bid).unwrap();
|
||||
e.execute(no).unwrap();
|
||||
drop(e);
|
||||
|
||||
let mut e = Exchange::open(&path).unwrap();
|
||||
let second = e.execute(json!({"op":"account_events","account":"alice","market":"e","after":first["cursor"],"limit":2})).unwrap();
|
||||
assert_eq!(second["has_more"], true);
|
||||
assert_eq!(second["events"][0]["type"], "TRADE");
|
||||
assert_eq!(second["events"][0]["trader_side"], "MAKER");
|
||||
assert_eq!(second["events"][0]["size"], "2");
|
||||
assert_eq!(second["events"][1]["type"], "UPDATE");
|
||||
assert_eq!(second["events"][1]["size_matched"], "2");
|
||||
assert_eq!(second["events"][1]["open_size"], "3");
|
||||
let rest = e
|
||||
.execute(
|
||||
json!({"op":"account_events","account":"alice","market":"e","after":second["cursor"]}),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(rest["events"][0]["type"], "CANCELLATION");
|
||||
assert_eq!(rest["events"][0]["open_size"], "0");
|
||||
assert_eq!(rest["events"][2]["price"], "0.6");
|
||||
assert_eq!(rest["events"][2]["kind"], "mint");
|
||||
let bob = e
|
||||
.execute(json!({"op":"account_events","account":"bob","market":"e","include_maker":true}))
|
||||
.unwrap();
|
||||
let events = bob["events"].as_array().unwrap();
|
||||
assert_eq!(events.len(), 6);
|
||||
assert_eq!(events[0]["original_size"], "2");
|
||||
assert_eq!(events[0]["order_type"], "FAK");
|
||||
assert_eq!(events[4]["price"], "0.4");
|
||||
assert_eq!(events[4]["trader_side"], "TAKER");
|
||||
assert_eq!(events[4]["id"], rest["events"][2]["id"]);
|
||||
assert_eq!(events[4]["maker_leg"]["price"], "0.6");
|
||||
assert_eq!(events[4]["maker_leg"]["asset_id"], "eb:YES:e");
|
||||
assert_eq!(events[4]["maker_leg"]["matched_amount"], "1");
|
||||
let empty = e
|
||||
.execute(
|
||||
json!({"op":"account_events","account":"alice","market":"e","after":rest["cursor"]}),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
empty,
|
||||
json!({"events":[],"cursor":rest["cursor"],"has_more":false})
|
||||
);
|
||||
assert_eq!(
|
||||
e.execute(json!({"op":"account_events","account":"alice","market":"other"}))
|
||||
.unwrap()["events"],
|
||||
json!([])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn terminal_order_window_uses_transition_time_and_preserves_exact_lookup() {
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("terminal.sqlite");
|
||||
let mut e = Exchange::open(&path).unwrap();
|
||||
setup(&mut e);
|
||||
let receipt = e.execute(order("term", "alice", "sell", 60, 5)).unwrap();
|
||||
e.execute(json!({"op":"cancel","id":"term-cancel","account":"alice","order":receipt["order"]}))
|
||||
.unwrap();
|
||||
let exact = json!({"op":"open_orders","account":"alice","order":receipt["order"]});
|
||||
let mut recent = exact.clone();
|
||||
recent["terminal_max_age_ms"] = json!(3_600_000);
|
||||
let recent_order = e.execute(recent.clone()).unwrap();
|
||||
assert_eq!(recent_order["orders"][0]["status"], "cancelled");
|
||||
let db = rusqlite::Connection::open(&path).unwrap();
|
||||
db.execute(
|
||||
"UPDATE account_events SET at_ms=(unixepoch()-3601)*1000 WHERE kind='CANCELLATION'",
|
||||
[],
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(e.execute(recent).unwrap()["orders"], json!([]));
|
||||
assert_eq!(e.execute(exact).unwrap()["orders"], recent_order["orders"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn account_snapshot_bridges_recent_trades_and_live_updates() {
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("reconnect.sqlite");
|
||||
let mut writer = Exchange::open(&path).unwrap();
|
||||
setup(&mut writer);
|
||||
writer
|
||||
.execute(json!({"op":"open","id":"snap-open","market":"e"}))
|
||||
.unwrap();
|
||||
let ask = writer
|
||||
.execute(order("snap-ask", "alice", "sell", 60, 5))
|
||||
.unwrap();
|
||||
writer
|
||||
.execute(order("snap-buy-1", "bob", "buy", 60, 1))
|
||||
.unwrap();
|
||||
writer
|
||||
.execute(order("snap-buy-2", "bob", "buy", 60, 1))
|
||||
.unwrap();
|
||||
let mut reader = Exchange::open(&path).unwrap();
|
||||
let read = json!({"op":"account_snapshot","account":"alice","market":"e","trade_limit":1});
|
||||
let snapshot = reader.execute(read.clone()).unwrap();
|
||||
assert_eq!(snapshot["orders"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(snapshot["orders"][0]["size_matched"], 2);
|
||||
assert_eq!(snapshot["orders"][0]["open_size"], 3);
|
||||
assert_eq!(snapshot["trades"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(snapshot["trades"][0]["execution"], 2);
|
||||
let prior = reader.execute(json!({"op":"trades","account":"alice","market":"e","after":snapshot["trade_next_after"]})).unwrap();
|
||||
assert_eq!(prior["trades"][0]["execution"], 1);
|
||||
|
||||
writer
|
||||
.execute(order("snap-buy-3", "bob", "buy", 60, 1))
|
||||
.unwrap();
|
||||
writer
|
||||
.execute(json!({"op":"cancel","id":"snap-cancel","account":"alice","order":ask["order"]}))
|
||||
.unwrap();
|
||||
drop(reader);
|
||||
let mut reader = Exchange::open(&path).unwrap();
|
||||
let changes = reader.execute(json!({"op":"account_events","account":"alice","market":"e","after":snapshot["cursor"]})).unwrap();
|
||||
let events = changes["events"].as_array().unwrap();
|
||||
assert_eq!(events.len(), 3);
|
||||
assert_eq!(events[0]["id"], "3");
|
||||
assert_eq!(events[1]["size_matched"], "3");
|
||||
assert_eq!(events[2]["type"], "CANCELLATION");
|
||||
let refreshed = reader.execute(read).unwrap();
|
||||
assert_eq!(refreshed["orders"], json!([]));
|
||||
assert_eq!(refreshed["trades"][0]["execution"], 3);
|
||||
assert_eq!(refreshed["cursor"], changes["cursor"]);
|
||||
let bob = reader
|
||||
.execute(json!({"op":"account_snapshot","account":"bob","market":"e"}))
|
||||
.unwrap();
|
||||
assert_eq!(bob["orders"], json!([]));
|
||||
assert_eq!(bob["trades"][0]["side"], "buy");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auction_fifo_ioc_close_and_redeem() {
|
||||
let mut e = Exchange::open(":memory:").unwrap();
|
||||
@@ -2315,11 +2160,7 @@ fn heartbeat_rotates_and_recovers_only_orders_owned_by_the_expired_key() {
|
||||
[],
|
||||
)
|
||||
.unwrap();
|
||||
e.maintain_due_heartbeats().unwrap();
|
||||
let canceled: String = observer
|
||||
.query_row("SELECT status FROM orders WHERE seq=3", [], |r| r.get(0))
|
||||
.unwrap();
|
||||
assert_eq!(canceled, "cancelled");
|
||||
e.maintain().unwrap();
|
||||
let s = state(&mut e);
|
||||
assert_eq!(s["orders"][2]["status"], "cancelled");
|
||||
assert_eq!(s["orders"][3]["status"], "live");
|
||||
@@ -4337,3 +4178,182 @@ fn order_submission_terms_survive_fills_cancel_retries_and_legacy_upgrade() {
|
||||
assert_eq!(e.execute(cmd.clone()).unwrap()["orders"][0], expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn balance_history_uses_committed_ownership_and_an_exclusive_cut() {
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("historical-balances.db");
|
||||
let mut engine = Exchange::open(&path).unwrap();
|
||||
setup(&mut engine);
|
||||
engine
|
||||
.execute(json!({"op":"open","id":"open-history","market":"e"}))
|
||||
.unwrap();
|
||||
let db = rusqlite::Connection::open(&path).unwrap();
|
||||
db.execute("UPDATE position_balance_history_start SET at_ms=1000", [])
|
||||
.unwrap();
|
||||
db.execute("UPDATE position_balance_history SET at_ms=2000", [])
|
||||
.unwrap();
|
||||
let count = || {
|
||||
db.query_row("SELECT COUNT(*) FROM position_balance_history", [], |r| {
|
||||
r.get::<_, i64>(0)
|
||||
})
|
||||
.unwrap()
|
||||
};
|
||||
let initial = count();
|
||||
assert_eq!(
|
||||
engine
|
||||
.execute(json!({"op":"position_balances_at","account":"alice","before_ms":2000}))
|
||||
.unwrap()["data"],
|
||||
json!([])
|
||||
);
|
||||
assert!(engine
|
||||
.execute(json!({"op":"position_balances_at","account":"alice","before_ms":1000}))
|
||||
.is_err());
|
||||
|
||||
let ask = order("history-ask", "alice", "sell", 50, 4);
|
||||
engine.execute(ask).unwrap();
|
||||
assert_eq!(count(), initial, "reserving shares preserves ownership");
|
||||
let buy = order("history-buy", "bob", "buy", 50, 2);
|
||||
engine.execute(buy.clone()).unwrap();
|
||||
assert_eq!(count(), initial + 2);
|
||||
engine.execute(buy).unwrap();
|
||||
assert_eq!(
|
||||
count(),
|
||||
initial + 2,
|
||||
"idempotent replay produces no second movement"
|
||||
);
|
||||
db.execute(
|
||||
"UPDATE position_balance_history SET at_ms=3000 WHERE at_ms>2000",
|
||||
[],
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
drop(engine);
|
||||
let mut engine = Exchange::open(&path).unwrap();
|
||||
let balance = |engine: &mut Exchange, account: &str, before_ms| {
|
||||
engine
|
||||
.execute(json!({"op":"position_balances_at","account":account,"before_ms":before_ms}))
|
||||
.unwrap()["data"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|row| row["outcome"] == "YES")
|
||||
.map(|row| row["shares_micros"].as_i64().unwrap())
|
||||
};
|
||||
assert_eq!(balance(&mut engine, "alice", 3000), Some(10_000_000));
|
||||
assert_eq!(balance(&mut engine, "alice", 3001), Some(8_000_000));
|
||||
assert_eq!(balance(&mut engine, "bob", 3001), Some(2_000_000));
|
||||
|
||||
engine
|
||||
.execute(json!({"op":"close","id":"history-close","market":"e"}))
|
||||
.unwrap();
|
||||
engine
|
||||
.execute(json!({"op":"finalize","id":"history-final","market":"e","winner":"YES"}))
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
count(),
|
||||
initial + 2,
|
||||
"closing the book releases reservations, not ownership"
|
||||
);
|
||||
engine
|
||||
.execute(json!({"op":"redeem","id":"history-redeem","account":"alice","market":"e"}))
|
||||
.unwrap();
|
||||
assert_eq!(count(), initial + 4);
|
||||
db.execute(
|
||||
"UPDATE position_balance_history SET at_ms=4000 WHERE at_ms>3000",
|
||||
[],
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(balance(&mut engine, "alice", 4000), Some(8_000_000));
|
||||
assert_eq!(balance(&mut engine, "alice", 4001), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn daily_position_snapshot_uses_the_cut_and_binds_cursor_scope() {
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("daily-positions.db");
|
||||
let mut engine = Exchange::open(&path).unwrap();
|
||||
let maker = "0x0000000000000000000000000000000000000011";
|
||||
let wallet = "0x0000000000000000000000000000000000000022";
|
||||
for cmd in [
|
||||
json!({"op":"fund","id":"daily-maker","account":maker,"cents":3000}),
|
||||
json!({"op":"fund","id":"daily-wallet","account":wallet,"cents":3000}),
|
||||
json!({"op":"list","id":"daily-market","market":"e","rules":"snapshot fixture"}),
|
||||
json!({"op":"list","id":"daily-basis-market","market":"f","rules":"unpriced fixture"}),
|
||||
json!({"op":"list","id":"daily-dust-market","market":"dust","rules":"dust fixture"}),
|
||||
json!({"op":"split","id":"daily-shares","account":maker,"market":"e","qty":4}),
|
||||
json!({"op":"split","id":"daily-both","account":wallet,"market":"f","qty":1}),
|
||||
json!({"op":"merge","id":"daily-merge","account":wallet,"market":"f","qty_micros":250000}),
|
||||
json!({"op":"split","id":"daily-dust","account":wallet,"market":"dust","qty_micros":100000}),
|
||||
json!({"op":"open","id":"daily-open","market":"e"}),
|
||||
order("daily-ask", maker, "sell", 40, 2),
|
||||
order("daily-buy", wallet, "buy", 40, 2),
|
||||
json!({"op":"close","id":"daily-close","market":"e"}),
|
||||
json!({"op":"finalize","id":"daily-final","market":"e","winner":"NO"}),
|
||||
] {
|
||||
engine.execute(cmd).unwrap();
|
||||
}
|
||||
let conn = rusqlite::Connection::open(&path).unwrap();
|
||||
let day = 1_699_920_000_000_i64;
|
||||
let cutoff = day + 86_400_000;
|
||||
conn.execute(
|
||||
"UPDATE position_balance_history_start SET at_ms=?",
|
||||
[day - 1],
|
||||
)
|
||||
.unwrap();
|
||||
for table in [
|
||||
"position_balance_history",
|
||||
"wallet_movements",
|
||||
"quote_events",
|
||||
"trade_prices",
|
||||
] {
|
||||
conn.execute(&format!("UPDATE {table} SET at_ms=?"), [day + 1000])
|
||||
.unwrap();
|
||||
}
|
||||
conn.execute("UPDATE price_settlements SET at_ms=?", [cutoff])
|
||||
.unwrap();
|
||||
let date: String = conn
|
||||
.query_row("SELECT date(?1/1000,'unixepoch')", [day], |r| r.get(0))
|
||||
.unwrap();
|
||||
let read = |engine: &Exchange, query| {
|
||||
engine.public_position_snapshot(serde_json::from_value(query).unwrap())
|
||||
};
|
||||
let first = read(&engine, json!({"user":wallet,"date":date,"limit":1})).unwrap();
|
||||
assert_eq!(first["summary"]["positions"], 3);
|
||||
assert_eq!(first["summary"]["cost_basis"], 1.55);
|
||||
assert_eq!(first["data"][0]["price_source"], "mark");
|
||||
assert_eq!(first["data"][0]["value"], 0.8);
|
||||
assert_eq!(first["summary"]["value_by_source"]["basis"], 0.75);
|
||||
assert!(first["summary"]["closed_block"].is_null());
|
||||
let cursor = first["pagination"]["next_cursor"].as_str().unwrap();
|
||||
drop(engine);
|
||||
let engine = Exchange::open(&path).unwrap();
|
||||
let second = read(
|
||||
&engine,
|
||||
json!({"user_address":wallet,"cursor":cursor,"limit":999}),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(second["pagination"]["limit"], 1);
|
||||
assert_eq!(second["pagination"]["offset"], 1);
|
||||
assert_eq!(second["data"][0]["price_source"], "basis");
|
||||
assert_eq!(second["data"][0]["size"], 0.75);
|
||||
assert_eq!(second["data"][0]["cost_basis"], 0.375);
|
||||
assert_eq!(second["data"][0]["avg_price"], 0.5);
|
||||
assert!(second.get("summary").is_none());
|
||||
assert!(read(&engine, json!({"user":maker,"cursor":cursor})).is_err());
|
||||
assert!(read(
|
||||
&engine,
|
||||
json!({"user":wallet,"cursor":cursor,"date":"2023-11-17"})
|
||||
)
|
||||
.is_err());
|
||||
assert!(read(&engine, json!({"user":wallet,"date":"2099-01-01"})).is_err());
|
||||
assert!(read(&engine, json!({"user":wallet,"date":"2023-02-30"})).is_err());
|
||||
|
||||
let next_day: String = conn
|
||||
.query_row("SELECT date(?1/1000,'unixepoch')", [cutoff], |r| r.get(0))
|
||||
.unwrap();
|
||||
let settled = read(&engine, json!({"user":wallet,"date":next_day})).unwrap();
|
||||
assert_eq!(settled["data"][0]["price_source"], "settlement");
|
||||
assert_eq!(settled["data"][0]["price"], 0);
|
||||
assert_eq!(settled["data"][0]["cost_basis"], 0.8);
|
||||
}
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
{
|
||||
"chain_id": 31337,
|
||||
"timestamp": 1782753357,
|
||||
"expected_digest": "0x34180bd2a7d6586464f2bf8cafc8626619bde55f1242bed7c7626610134e463c",
|
||||
"headers": {
|
||||
"POLY_ADDRESS": "0x7E5F4552091A69125d5DfCb7b8C2659029395Bdf",
|
||||
"POLY_TIMESTAMP": "1782753357",
|
||||
"POLY_NONCE": "340282366920938463463374607431768211473",
|
||||
"POLY_SIGNATURE": "0x3ea76b08219d33cd7a0c0caffa26368363681e09e6fd90e1340459d3fb5a79eb5cb2e7a1d1a43e38cb340d1bcd3267f67ad33dca905b8d6959f069d6b4e222b51c"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
{"op":"fund","id":"combo-fund","account":"alice","micros":10000000}
|
||||
{"op":"list","id":"combo-list-a","market":"combo-a","rules":"按模拟赛果 A 裁决。"}
|
||||
{"op":"list","id":"combo-list-b","market":"combo-b","rules":"按模拟赛果 B 裁决。"}
|
||||
{"op":"prepare_combo","id":"combo-prepare","legs":[{"market":"combo-b","outcome":"NO"},{"market":"combo-a","outcome":"YES"}]}
|
||||
{"op":"split_combo","id":"combo-split","combo":"combo:1131b7195fad3ca3c7ae8ebe3739ac78a765c241aa74fccf91236b6caa08cb1e","account":"alice","qty_micros":1000003}
|
||||
{"op":"merge_combo","id":"combo-merge","combo":"combo:1131b7195fad3ca3c7ae8ebe3739ac78a765c241aa74fccf91236b6caa08cb1e","account":"alice","qty_micros":2}
|
||||
{"op":"close","id":"combo-close-a","market":"combo-a"}
|
||||
{"op":"finalize","id":"combo-final-a","market":"combo-a","winner":"VOID"}
|
||||
{"op":"close","id":"combo-close-b","market":"combo-b"}
|
||||
{"op":"finalize","id":"combo-final-b","market":"combo-b","winner":"VOID"}
|
||||
{"op":"redeem_combo","id":"combo-redeem-yes","combo":"combo:1131b7195fad3ca3c7ae8ebe3739ac78a765c241aa74fccf91236b6caa08cb1e","account":"alice","outcome":"YES","qty_micros":1000001}
|
||||
{"op":"redeem_combo","id":"combo-redeem-no","combo":"combo:1131b7195fad3ca3c7ae8ebe3739ac78a765c241aa74fccf91236b6caa08cb1e","account":"alice","outcome":"NO","qty_micros":1000001}
|
||||
{"op":"combo","combo":"combo:1131b7195fad3ca3c7ae8ebe3739ac78a765c241aa74fccf91236b6caa08cb1e","account":"alice"}
|
||||
@@ -0,0 +1,16 @@
|
||||
{"op":"fund","id":"rfq-taker-fund","account":"taker","micros":5000000}
|
||||
{"op":"fund","id":"rfq-maker-fund","account":"maker","micros":5000000}
|
||||
{"op":"list","id":"rfq-a","market":"combo-a","rules":"按模拟赛果 A 裁决。"}
|
||||
{"op":"list","id":"rfq-b","market":"combo-b","rules":"按模拟赛果 B 裁决。"}
|
||||
{"op":"prepare_combo","id":"rfq-combo","legs":[{"market":"combo-a","outcome":"YES"},{"market":"combo-b","outcome":"NO"}]}
|
||||
{"op":"request_combo_quote","id":"rfq-buy","combo":"combo:1131b7195fad3ca3c7ae8ebe3739ac78a765c241aa74fccf91236b6caa08cb1e","requester":"taker","direction":"BUY","side":"YES","shares_micros":4000000}
|
||||
{"op":"combo_rfq_open"}
|
||||
{"op":"quote_combo","id":"rfq-mint-quote","rfq":"rfq-buy","maker":"maker","source":"collateral","price_micros":350000,"shares_micros":4000000}
|
||||
{"op":"accept_combo_quote","id":"rfq-buy-accept","rfq":"rfq-buy","requester":"taker","quote":"rfq-mint-quote"}
|
||||
{"op":"respond_combo_quote","id":"rfq-buy-fill","rfq":"rfq-buy","quote":"rfq-mint-quote","maker":"maker","confirm":true}
|
||||
{"op":"combo_rfq","rfq":"rfq-buy","account":"taker"}
|
||||
{"op":"request_combo_quote","id":"rfq-sell","combo":"combo:1131b7195fad3ca3c7ae8ebe3739ac78a765c241aa74fccf91236b6caa08cb1e","requester":"taker","direction":"SELL","side":"YES","shares_micros":1500000}
|
||||
{"op":"quote_combo","id":"rfq-merge-quote","rfq":"rfq-sell","maker":"maker","source":"inventory","price_micros":400000,"shares_micros":1500000}
|
||||
{"op":"accept_combo_quote","id":"rfq-sell-accept","rfq":"rfq-sell","requester":"taker","quote":"rfq-merge-quote"}
|
||||
{"op":"respond_combo_quote","id":"rfq-sell-fill","rfq":"rfq-sell","quote":"rfq-merge-quote","maker":"maker","confirm":true}
|
||||
{"op":"combo","combo":"combo:1131b7195fad3ca3c7ae8ebe3739ac78a765c241aa74fccf91236b6caa08cb1e","account":"taker"}
|
||||
@@ -1,37 +0,0 @@
|
||||
{
|
||||
"order_config": {
|
||||
"chain_id": 31337,
|
||||
"tokens": [
|
||||
{
|
||||
"token_id": "123",
|
||||
"asset_id": "eb:YES:demo",
|
||||
"verifying_contract": "0x0000000000000000000000000000000000000001"
|
||||
}
|
||||
]
|
||||
},
|
||||
"wallet": "0x7E5F4552091A69125d5DfCb7b8C2659029395Bdf",
|
||||
"contract_wallet": "0x000000000000000000000000000000000000002a",
|
||||
"request": {
|
||||
"owner": "alice-key",
|
||||
"orderType": "GTC",
|
||||
"deferExec": false,
|
||||
"postOnly": false,
|
||||
"order": {
|
||||
"salt": 42,
|
||||
"maker": "0x000000000000000000000000000000000000002a",
|
||||
"signer": "0x000000000000000000000000000000000000002a",
|
||||
"tokenId": "123",
|
||||
"makerAmount": "1800000",
|
||||
"takerAmount": "3000000",
|
||||
"side": "BUY",
|
||||
"signatureType": 3,
|
||||
"timestamp": "1782753357000",
|
||||
"expiration": "0",
|
||||
"metadata": "0x0000000000000000000000000000000000000000000000000000000000000000",
|
||||
"builder": "0x0000000000000000000000000000000000000000000000000000000000000000",
|
||||
"signature": "0xea87cc090fb1b3d108485f3eeb2c6d52c3392fec447ebc20f33a33d9bf625c9469e548d0b204154f8772c55f5ed94fd73e928109e9bded8dfa75d2dfc77679aa1b1756eafcf5c0056c373a8b5413362c518d2287077ba82f8a8948f28a8be74007373e9f6ac05c33e81db514bb1a90128e0f30a1cb4fa4f6e4287dc916ce20d2424f726465722875696e743235362073616c742c61646472657373206d616b65722c61646472657373207369676e65722c75696e7432353620746f6b656e49642c75696e74323536206d616b6572416d6f756e742c75696e743235362074616b6572416d6f756e742c75696e743820736964652c75696e7438207369676e6174757265547970652c75696e743235362074696d657374616d702c62797465733332206d657461646174612c62797465733332206275696c6465722900ba"
|
||||
}
|
||||
},
|
||||
"expected_order_hash": "0xca938bb3e1df437413cc666238ef48e1d5d28e4510067e36abde79c17d6b5d91",
|
||||
"expected_calldata": "0x1626ba7eca938bb3e1df437413cc666238ef48e1d5d28e4510067e36abde79c17d6b5d910000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000013dea87cc090fb1b3d108485f3eeb2c6d52c3392fec447ebc20f33a33d9bf625c9469e548d0b204154f8772c55f5ed94fd73e928109e9bded8dfa75d2dfc77679aa1b1756eafcf5c0056c373a8b5413362c518d2287077ba82f8a8948f28a8be74007373e9f6ac05c33e81db514bb1a90128e0f30a1cb4fa4f6e4287dc916ce20d2424f726465722875696e743235362073616c742c61646472657373206d616b65722c61646472657373207369676e65722c75696e7432353620746f6b656e49642c75696e74323536206d616b6572416d6f756e742c75696e743235362074616b6572416d6f756e742c75696e743820736964652c75696e7438207369676e6174757265547970652c75696e743235362074696d657374616d702c62797465733332206d657461646174612c62797465733332206275696c6465722900ba000000"
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
{
|
||||
"order_config": {
|
||||
"chain_id": 31337,
|
||||
"tokens": [
|
||||
{
|
||||
"token_id": "123",
|
||||
"asset_id": "eb:YES:demo",
|
||||
"verifying_contract": "0x0000000000000000000000000000000000000001"
|
||||
}
|
||||
]
|
||||
},
|
||||
"wallet": "0x7E5F4552091A69125d5DfCb7b8C2659029395Bdf",
|
||||
"expected_order_hash": "0x975651fc57c878c1ddcc7216ce87c8a202a8e3cb4b780b41c1fc63419dae9ae1",
|
||||
"request": {
|
||||
"owner": "alice-key",
|
||||
"orderType": "GTC",
|
||||
"deferExec": false,
|
||||
"postOnly": false,
|
||||
"order": {
|
||||
"salt": 42,
|
||||
"maker": "0x7E5F4552091A69125d5DfCb7b8C2659029395Bdf",
|
||||
"signer": "0x7E5F4552091A69125d5DfCb7b8C2659029395Bdf",
|
||||
"tokenId": "123",
|
||||
"makerAmount": "1800000",
|
||||
"takerAmount": "3000000",
|
||||
"side": "BUY",
|
||||
"signatureType": 0,
|
||||
"timestamp": "1782753357000",
|
||||
"expiration": "0",
|
||||
"metadata": "0x0000000000000000000000000000000000000000000000000000000000000000",
|
||||
"builder": "0x0000000000000000000000000000000000000000000000000000000000000000",
|
||||
"signature": "0xf235844d3cb7ca2407155e1c8c70a3049249c7d75de7e7e07cfbff552b75849d1f2d51a786fe4a6571fa4a5dcb77d9ffb876696095ff30306daadc73ab7edc251c"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,90 +0,0 @@
|
||||
{
|
||||
"order_config": {
|
||||
"chain_id": 31337,
|
||||
"tokens": [
|
||||
{
|
||||
"token_id": "123",
|
||||
"asset_id": "eb:YES:demo",
|
||||
"verifying_contract": "0x0000000000000000000000000000000000000001",
|
||||
"proxy_factory": {
|
||||
"address": "0xaB45c5A4B0c941a2F231C04C3f49182e1A254052",
|
||||
"init_code_hash": "0xd21df8dc65880a8606f09fe0ce3df9b8869287ab0b058be05aa9e8af6330a00b"
|
||||
},
|
||||
"safe_factory": {
|
||||
"address": "0xaacFeEa03eb1561C4e67d661e40682Bd20E3541b",
|
||||
"init_code_hash": "0x2bce2127ff07fb632d16c8347c4ebf501f4841168bed00d9e6ef715ddb6fcecf"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"wallet": "0x7E5F4552091A69125d5DfCb7b8C2659029395Bdf",
|
||||
"proxy": {
|
||||
"expected_order_hash": "0x8c6015fdc562470cac36d03caa4c4654fedc4f6482689a601ac80e4804d9a6a4",
|
||||
"request": {
|
||||
"owner": "alice-key",
|
||||
"orderType": "GTC",
|
||||
"deferExec": false,
|
||||
"postOnly": false,
|
||||
"order": {
|
||||
"salt": 42,
|
||||
"maker": "0x909dEdA326ED2aE677F5F8c2527E32977c9838c3",
|
||||
"signer": "0x7E5F4552091A69125d5DfCb7b8C2659029395Bdf",
|
||||
"tokenId": "123",
|
||||
"makerAmount": "1800000",
|
||||
"takerAmount": "3000000",
|
||||
"side": "BUY",
|
||||
"signatureType": 1,
|
||||
"timestamp": "1782753357000",
|
||||
"expiration": "0",
|
||||
"metadata": "0x0000000000000000000000000000000000000000000000000000000000000000",
|
||||
"builder": "0x0000000000000000000000000000000000000000000000000000000000000000",
|
||||
"signature": "0xf3d50ecd9c385a390e7acde35aec7d37cc44b4d2b367a531e1a8e47edb7d90dd16378bfa85ed5c6d93d5a0cf65121f0afc9368e74b88fad26e9d4c569f47d7e41b"
|
||||
}
|
||||
}
|
||||
},
|
||||
"safe": {
|
||||
"expected_order_hash": "0x27911f0db1db7d91a4a734ddf05ac22bbdda79bc4276ea93f1949204aeeff5e2",
|
||||
"request": {
|
||||
"owner": "alice-key",
|
||||
"orderType": "GTC",
|
||||
"deferExec": false,
|
||||
"postOnly": false,
|
||||
"order": {
|
||||
"salt": 42,
|
||||
"maker": "0x51b7C68A71dCcBc0b7FA4400934a293D8f4d3Ba8",
|
||||
"signer": "0x7E5F4552091A69125d5DfCb7b8C2659029395Bdf",
|
||||
"tokenId": "123",
|
||||
"makerAmount": "1800000",
|
||||
"takerAmount": "3000000",
|
||||
"side": "BUY",
|
||||
"signatureType": 2,
|
||||
"timestamp": "1782753357000",
|
||||
"expiration": "0",
|
||||
"metadata": "0x0000000000000000000000000000000000000000000000000000000000000000",
|
||||
"builder": "0x0000000000000000000000000000000000000000000000000000000000000000",
|
||||
"signature": "0x38c390964c9cc48240fe8e662d0843f3f2386418113e616edb3744957dacaae24e1f3b1d01613c5d288ebd53eed352b7f98c4479c432280362c157d1cc497c2d1b"
|
||||
}
|
||||
}
|
||||
},
|
||||
"wrong_safe_maker": {
|
||||
"owner": "alice-key",
|
||||
"orderType": "GTC",
|
||||
"deferExec": false,
|
||||
"postOnly": false,
|
||||
"order": {
|
||||
"salt": 42,
|
||||
"maker": "0x909dEdA326ED2aE677F5F8c2527E32977c9838c3",
|
||||
"signer": "0x7E5F4552091A69125d5DfCb7b8C2659029395Bdf",
|
||||
"tokenId": "123",
|
||||
"makerAmount": "1800000",
|
||||
"takerAmount": "3000000",
|
||||
"side": "BUY",
|
||||
"signatureType": 2,
|
||||
"timestamp": "1782753357000",
|
||||
"expiration": "0",
|
||||
"metadata": "0x0000000000000000000000000000000000000000000000000000000000000000",
|
||||
"builder": "0x0000000000000000000000000000000000000000000000000000000000000000",
|
||||
"signature": "0xeb0028667f7dcd43affd34733f2a2bf6d057ac5a7c582c2e431ac4851e4644fc500d303c3e5fc5f1651500f7cdf845a0469b637ab856909b3683860ad3bda4811c"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,134 +0,0 @@
|
||||
{
|
||||
"order_config": {
|
||||
"chain_id": 31337,
|
||||
"tokens": [
|
||||
{
|
||||
"token_id": "519157306076040251959047890783335914888746534222846460205908638840941182976",
|
||||
"asset_id": "eb:YES:demo",
|
||||
"verifying_contract": "0xe3333700cA9d93003F00f0F71f8515005F6c00Aa",
|
||||
"proxy_factory": {
|
||||
"address": "0xaB45c5A4B0c941a2F231C04C3f49182e1A254052",
|
||||
"init_code_hash": "0xd21df8dc65880a8606f09fe0ce3df9b8869287ab0b058be05aa9e8af6330a00b"
|
||||
},
|
||||
"safe_factory": {
|
||||
"address": "0xaacFeEa03eb1561C4e67d661e40682Bd20E3541b",
|
||||
"init_code_hash": "0x2bce2127ff07fb632d16c8347c4ebf501f4841168bed00d9e6ef715ddb6fcecf"
|
||||
},
|
||||
"domain_version": "3"
|
||||
},
|
||||
{
|
||||
"token_id": "519157306076040251959047890783335914888746534222846460205908638840941182977",
|
||||
"asset_id": "eb:NO:demo",
|
||||
"verifying_contract": "0xe3333700cA9d93003F00f0F71f8515005F6c00Aa",
|
||||
"proxy_factory": {
|
||||
"address": "0xaB45c5A4B0c941a2F231C04C3f49182e1A254052",
|
||||
"init_code_hash": "0xd21df8dc65880a8606f09fe0ce3df9b8869287ab0b058be05aa9e8af6330a00b"
|
||||
},
|
||||
"safe_factory": {
|
||||
"address": "0xaacFeEa03eb1561C4e67d661e40682Bd20E3541b",
|
||||
"init_code_hash": "0x2bce2127ff07fb632d16c8347c4ebf501f4841168bed00d9e6ef715ddb6fcecf"
|
||||
},
|
||||
"domain_version": "3"
|
||||
}
|
||||
]
|
||||
},
|
||||
"wallet": "0x7E5F4552091A69125d5DfCb7b8C2659029395Bdf",
|
||||
"eoa": {
|
||||
"request": {
|
||||
"owner": "alice-key",
|
||||
"orderType": "GTC",
|
||||
"deferExec": false,
|
||||
"postOnly": false,
|
||||
"order": {
|
||||
"salt": 42,
|
||||
"maker": "0x7E5F4552091A69125d5DfCb7b8C2659029395Bdf",
|
||||
"signer": "0x7E5F4552091A69125d5DfCb7b8C2659029395Bdf",
|
||||
"tokenId": "519157306076040251959047890783335914888746534222846460205908638840941182976",
|
||||
"makerAmount": "1800000",
|
||||
"takerAmount": "3000000",
|
||||
"side": "BUY",
|
||||
"signatureType": 0,
|
||||
"timestamp": "1782753357000",
|
||||
"expiration": "0",
|
||||
"metadata": "0x0000000000000000000000000000000000000000000000000000000000000000",
|
||||
"builder": "0x0000000000000000000000000000000000000000000000000000000000000000",
|
||||
"signature": "0x1eb5611d539bcfa3d07959d87030bc88630c1d0007a0f20ad932d4882c18b1d612388a7176497e07e812cf51239096dc3d5ca5ae4c40c8f7bd1aad44ed0a12ff1c"
|
||||
}
|
||||
},
|
||||
"expected_order_hash": "0xc5f82b06d14a9c3a10b49cff32b10cd1b4d2841da6704acfed8dd1d77a53313f"
|
||||
},
|
||||
"proxy": {
|
||||
"request": {
|
||||
"owner": "alice-key",
|
||||
"orderType": "GTC",
|
||||
"deferExec": false,
|
||||
"postOnly": false,
|
||||
"order": {
|
||||
"salt": 42,
|
||||
"maker": "0x909dEdA326ED2aE677F5F8c2527E32977c9838c3",
|
||||
"signer": "0x7E5F4552091A69125d5DfCb7b8C2659029395Bdf",
|
||||
"tokenId": "519157306076040251959047890783335914888746534222846460205908638840941182976",
|
||||
"makerAmount": "1800000",
|
||||
"takerAmount": "3000000",
|
||||
"side": "BUY",
|
||||
"signatureType": 1,
|
||||
"timestamp": "1782753357000",
|
||||
"expiration": "0",
|
||||
"metadata": "0x0000000000000000000000000000000000000000000000000000000000000000",
|
||||
"builder": "0x0000000000000000000000000000000000000000000000000000000000000000",
|
||||
"signature": "0xd1f7dcab0bde1fa942ec067373f320a5e7b99863f70c2ac51144fa0d177a380033041c582d2bf5ffb9bfe875a6ca22cdb090dbbb94ea325027c055f6ce267f3d1b"
|
||||
}
|
||||
},
|
||||
"expected_order_hash": "0x85ad3f0c79f55f683d20229bf6551eb207141191c802cf53cb100ac9bbd2e315"
|
||||
},
|
||||
"safe": {
|
||||
"request": {
|
||||
"owner": "alice-key",
|
||||
"orderType": "GTC",
|
||||
"deferExec": false,
|
||||
"postOnly": false,
|
||||
"order": {
|
||||
"salt": 42,
|
||||
"maker": "0x51b7C68A71dCcBc0b7FA4400934a293D8f4d3Ba8",
|
||||
"signer": "0x7E5F4552091A69125d5DfCb7b8C2659029395Bdf",
|
||||
"tokenId": "519157306076040251959047890783335914888746534222846460205908638840941182976",
|
||||
"makerAmount": "1800000",
|
||||
"takerAmount": "3000000",
|
||||
"side": "BUY",
|
||||
"signatureType": 2,
|
||||
"timestamp": "1782753357000",
|
||||
"expiration": "0",
|
||||
"metadata": "0x0000000000000000000000000000000000000000000000000000000000000000",
|
||||
"builder": "0x0000000000000000000000000000000000000000000000000000000000000000",
|
||||
"signature": "0x8c0c34f45f80e3c57b53349cc518135d8f72a2dc17e29e40090e5c99bf32adc63910c93a6779e706dfd796d47065d46d6efdcfffc2291f09dfc8dd0741950a071c"
|
||||
}
|
||||
},
|
||||
"expected_order_hash": "0xeac01d94f7bca5c1027dd4a7629e57bf95ce907ec5bb392f093a3b9584391fc2"
|
||||
},
|
||||
"contract": {
|
||||
"request": {
|
||||
"owner": "alice-key",
|
||||
"orderType": "GTC",
|
||||
"deferExec": false,
|
||||
"postOnly": false,
|
||||
"order": {
|
||||
"salt": 42,
|
||||
"maker": "0x000000000000000000000000000000000000002a",
|
||||
"signer": "0x000000000000000000000000000000000000002a",
|
||||
"tokenId": "519157306076040251959047890783335914888746534222846460205908638840941182976",
|
||||
"makerAmount": "1800000",
|
||||
"takerAmount": "3000000",
|
||||
"side": "BUY",
|
||||
"signatureType": 3,
|
||||
"timestamp": "1782753357000",
|
||||
"expiration": "0",
|
||||
"metadata": "0x0000000000000000000000000000000000000000000000000000000000000000",
|
||||
"builder": "0x0000000000000000000000000000000000000000000000000000000000000000",
|
||||
"signature": "0x91c95e803508eb7d43926fc34e092ec56f5c7bf18854d3b7a57de595091dfc676cc8d96f18e6c589af73312170a492875a9edffb8b1d4d2bd471c4c9279ad1451bad0e218aebd06822dee2ff47c13400b5af901fd51ef3f1ed9a0f1b8093f2faf417b5c88c61a3ae835b0646973fcdc423fca87138d6c3a64150d8550137d2ae694f726465722875696e743235362073616c742c61646472657373206d616b65722c61646472657373207369676e65722c75696e7432353620746f6b656e49642c75696e74323536206d616b6572416d6f756e742c75696e743235362074616b6572416d6f756e742c75696e743820736964652c75696e7438207369676e6174757265547970652c75696e743235362074696d657374616d702c62797465733332206d657461646174612c62797465733332206275696c6465722900ba"
|
||||
}
|
||||
},
|
||||
"expected_order_hash": "0x8ea78d0711795cd17da4c998c03a5de33fce95ec515752c106b261276ede8786",
|
||||
"contract_wallet": "0x000000000000000000000000000000000000002a",
|
||||
"expected_calldata": "0x1626ba7e8ea78d0711795cd17da4c998c03a5de33fce95ec515752c106b261276ede87860000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000013d91c95e803508eb7d43926fc34e092ec56f5c7bf18854d3b7a57de595091dfc676cc8d96f18e6c589af73312170a492875a9edffb8b1d4d2bd471c4c9279ad1451bad0e218aebd06822dee2ff47c13400b5af901fd51ef3f1ed9a0f1b8093f2faf417b5c88c61a3ae835b0646973fcdc423fca87138d6c3a64150d8550137d2ae694f726465722875696e743235362073616c742c61646472657373206d616b65722c61646472657373207369676e65722c75696e7432353620746f6b656e49642c75696e74323536206d616b6572416d6f756e742c75696e743235362074616b6572416d6f756e742c75696e743820736964652c75696e7438207369676e6174757265547970652c75696e743235362074696d657374616d702c62797465733332206d657461646174612c62797465733332206275696c6465722900ba000000"
|
||||
}
|
||||
}
|
||||
+31
-47
@@ -207,8 +207,6 @@ FOK 要求整笔金额成交,无法用完预算时交易回滚。超过最高
|
||||
|
||||
停止续期并保持 CLI 打开,10 秒阈值过后,下一次 5 秒定时检查或下一条有效交易/查询会撤掉同一账户、同一 key 在各盘口的 live 余单,释放现金及份额预留。用 open_orders 核对结果。同账户的其他 key 和其他账户同名 key 的订单各自独立。过期注册被移除,新挂单需要新的成功心跳才能重新获得保护。旧订单及省略 key_id 的订单属于该账户的默认 key,给默认 key 发送心跳时省略 key_id。关闭整个本地进程后,到期清理由其他活跃实例或重启时完成。
|
||||
|
||||
私有 HTTP 的 `POST /v1/heartbeats` 使用验签绑定的账户与 API key。成功时只返回 `heartbeat_id`,不匹配则以 HTTP 400 返回 `error_msg` 及当前有效 ID。独立空闲检查每 250 毫秒查看数据库是否有超时的 key。撤单与余额、账户事件和盘口一起提交。官方描述为尽力撤单,本地写事务出错会回滚并在之后的维护周期重试。该周期及生产撤单延迟未实测。[官方心跳接口](https://docs.polymarket.com/api-reference/trade/send-heartbeat)
|
||||
|
||||
本地 key_id 是可信模拟命令中的所有权标识。官方依据已认证凭据判定所有权,在扫描时排队尽力撤单。本地在同一 SQLite 事务内移除注册、撤单并释放预留;独立嵌入 exchange 的宿主可调用 maintain 驱动空闲期检查。鉴权、生产队列延迟和失败时的逐单结果仍待实测。
|
||||
|
||||
## 最小下单量
|
||||
@@ -229,8 +227,6 @@ JSONL 下单面板的 `price` 接受 token_id 和方向,BUY 读取最低卖价
|
||||
|
||||
`balance` 返回账户可用现金、有效买单预留现金及二者之和,单位均为百万分之一模拟美元。拆分完整结果集所用的抵押和已买入的份额另由仓位账本记录。模拟 fund 可以用整数 micros 建立账户,也可以沿用 cents。入金回执和 activity 的 net_cash_delta_micros 可用于精确对账,原 funded 和 cash_delta_cents 字段保留整分部分。一个账户只接受首次 fund;相同请求可幂等重放。
|
||||
|
||||
私有 CLOB `GET /balance-allowance` 按 HMAC 凭证查询抵押币或指定结果。响应使用 SDK 的 `balance` 和 `allowances` 字段。显示余额包含挂单预留,撮合仍按可用余额限制下单。模拟额度按配置的签名域合约返回,`/balance-allowance/update` 读取同一账本快照。Polymarket 的更新入口刷新链上余额与授权缓存,链上授权额度和余额同步仍待接入。[官方 Rust SDK 返回结构](https://github.com/Polymarket/rs-clob-client-v2/blob/main/src/clob/types/response.rs) · [官方 Python SDK 请求样例](https://github.com/Polymarket/py-clob-client-v2/blob/main/examples/account/get_balance_allowance.py)
|
||||
|
||||
[现金与费用样例](examples/cash-balance.jsonl)中,买家以 512500 微单位开户,先挂 49 分买单,仍有 22500 微单位可用。撤单后以 50 分买入一份,费率 0.05,对应费用 12500 微单位,买方余额恰为零。若初始现金少一个微单位,交易整体回滚。
|
||||
|
||||
费用函数使用六位小数的价格计算本金两侧的价格因子。例如 5 份、单价 0.013、费率 0.05,按目前的逐笔五位小数舍入约定收取 3210 微单位。正常下单入口的价格和预算仍以分输入;该价格算例覆盖费用运算,细价格限价单的提交与交割仍待接入。官方 SDK 对限价单按市场步长和数量精度推导抵押金额。这里的 fund 和 balance 是本地模拟账本接口,外场的授权额度及链上钱包余额需要分别对照。[官方 SDK 的订单金额计算](https://github.com/Polymarket/py-clob-client-v2/blob/main/py_clob_client_v2/order_builder/builder.py) · [官方费用公式](https://docs.polymarket.com/trading/fees.md)
|
||||
@@ -304,42 +300,6 @@ order、market_sell 和卖出 estimate 可用 size_micros 输入数量,也可
|
||||
|
||||
[回放样例](examples/depth-feed.jsonl)先在 YES 买一 0.30 美元挂两份。随后同价增加一份互补流动性、成交两份、撤掉最后一份;客户端看到该档从 2 份依次变为 3、1、0 份。每个事务只发布净变化,重复命令、已回滚命令及同事务内进入后全部成交的临时挂单不会产生额外档位。本地数据库首次升级时从现有挂单建立起点;升级前的深度变化没有回放记录。请在升级所有写入进程后启用。这里验证从快照重建买卖档位,最近成交、步长变化需使用相应行情事件;公网 WebSocket 的传播顺序和延迟仍待独立对照。
|
||||
|
||||
## 账户委托及成交的续读
|
||||
|
||||
在可信 CLI 发送 `{"op":"account_events","account":"alice","market":"e","after":0,"limit":100}`。保存 `cursor`,下次用它作 `after`,沿用相同账户和市场范围。`has_more` 表示当前快照中仍有事件,空页保留传入的游标。事件与订单、成交共用写事务。拒单回滚事件,重复请求返回原回执。进程重启后可继续使用保存的游标。
|
||||
|
||||
Alice 挂卖 5 份后成交 2 份再撤单,会依次收到 `PLACEMENT`、`TRADE`、`UPDATE`、`CANCELLATION`。后两条累计成交量都为 2,可成交余量分别为 3 和 0。两笔互补买单成交时,账户各自收到自己的成交腿,共用执行 ID,价格分别为 0.60 和 0.40。本地集合竞价的成交角色为 `AUCTION`。交易已在本地账本完成,事件状态记作 `MATCHED_NOT_BROADCASTED`。订单与成交的 `timestamp` 使用 Unix 秒字符串,`at_ms` 和 `seq` 用于本地精确排序。[官方账户频道](https://docs.polymarket.com/api-reference/wss/user) · [交易状态及重连说明](https://docs.polymarket.com/trading/realtime-order-updates.md)
|
||||
|
||||
事件记录从数据库升级起开始。首次连接或丢失游标时,用 `{"op":"account_snapshot","account":"alice","market":"e","trade_limit":100}` 建立账户状态。响应在同一个数据库快照返回选定范围内全部活跃订单、近期成交和事件游标。近期成交默认 100 条,最多 1000 条;`trade_next_after` 可以传给 `trades` 查询更早的成交。客户端先替换本地挂单和成交视图,再把 `cursor` 传给 `account_events`。快照之后提交的成交和撤单从事件流读到,已有数据可包含升级前的挂单或成交。游标重放是本地扩展,Polymarket 文档要求重连后查询账户当前挂单与近期成交。对应回归用例为 `account_snapshot_bridges_recent_trades_and_live_updates` 和 `account_event_pages_resume_after_restart_and_preserve_fill_legs`。
|
||||
|
||||
本地 `/ws/user` 通过 `auth` 绑定账户,支持市场订阅更新及文本心跳。`PLACEMENT`、`UPDATE` 和 `CANCELLATION` 推送已提交的订单变更,`TRADE` 从账户视角返回本地成交腿和已知挂单方的执行信息。推送里已成交订单的状态为 `MATCHED`,撤销与到期为 `CANCELED`。本地 `snapshot` 控制帧及首帧的 `after` 是断线恢复扩展。WebSocket 可以使用本地摘要配置,或通过共享账户配置接受已签发的 API 凭证。细分会话范围仍待接入。成交推送保留本地执行 ID 和事件顺序,挂单方凭证标识及链上确认阶段仍待核验。回环用例为 `user_socket_authenticates_and_filters_live_events`。[官方账户频道](https://docs.polymarket.com/api-reference/wss/user)
|
||||
|
||||
L1 钱包认证支持 `POST /auth/api-key` 和 `GET /auth/derive-api-key`。已登记且显式启用的钱包按 `ClobAuth` 结构签名。签发由 SQLite 约束保证同一签发者与 nonce 只成功一次。派生检查同一记录,由本地凭证材料重算 L2 密钥,SQLite 中只保存签发索引。未签发的 nonce、错误链和过期签名都会失败。本地 HTTP 支持 EOA 钱包签发与派生,L2 入口可列出该账户的有效签发密钥或撤销当前签发密钥。撤销后原 nonce 保留,HTTP 及账户 WebSocket 查询撤销记录,WebSocket 在下次检查时关闭会话。合约钱包 L1 授权和生产撤销传播时序仍待核验。[官方 SDK 签名](https://github.com/Polymarket/py-clob-client-v2/blob/main/py_clob_client_v2/signing/eip712.py) · [签名样例](examples/clob-wallet-auth.json)
|
||||
|
||||
本地私有 HTTP 支持 `/data/orders`、`/data/order/{id}`、`/data/trades`。列表默认 100 条,客户端将 `next_cursor` 原样传回,`LTE=` 表示结束。签名按 SDK 计算,账户从凭证映射取得。用 Bob 的凭证查 Alice 的订单 ID,返回 404。对 `/data/orders?id=…`,活跃单仍可查,终态单仅在状态变更后的一小时内返回。缺少终态时间的旧单仍可从 `/data/order/{id}` 查到。窗口使用账本事件时间,未取得对应生产响应。[订单列表](https://docs.polymarket.com/api-reference/trade/get-user-orders) · [单笔订单](https://docs.polymarket.com/api-reference/trade/get-single-order-by-id)
|
||||
|
||||
成交可按执行 ID、市场、资产、时间及实际挂单方钱包地址查。成交时间过滤按秒比较,排除边界。HTTP 和 User Channel 都使用实际挂单方的成交腿生成 `maker_orders`。例如 Alice 挂 YES 0.60,Bob 买互补 NO 0.40,Bob 的成交主行是 NO 0.40,`maker_orders` 则是 Alice 的 YES 0.60。顶层成交地址取吃单订单的钱包,`maker_orders[].maker_address` 取相应挂单订单的钱包。HTTP 在缺少已验签钱包时从本地凭证取地址。集合竞价没有已知挂单方,不生成挂单方条目。分页游标使用本地记录位置。生产的凭证签发、地址代理关系和链上终态仍待验证。[成交列表](https://docs.polymarket.com/api-reference/trade/get-trades)
|
||||
|
||||
账户查询、按盘撤单和账户 WebSocket 可共用签名配置的 ID 映射。市场过滤接受条件 ID;资产过滤接受十进制和十六进制的 CTF token 或 V3 position ID。CTF 条件 ID 由配置提供,V3 由 position ID 低字节清零得到。HTTP 订单、成交、挂单方腿以及账户推送按映射返回正式格式的资产和市场 ID。公共行情和 Gamma 的同一映射仍待统一。[官方用户频道](https://docs.polymarket.com/api-reference/wss/user) · [官方 Rust SDK 成交结构](https://github.com/Polymarket/rs-clob-client-v2/blob/main/src/clob/types/response.rs)
|
||||
|
||||
私有 HTTP 撤单入口为 `DELETE /order`、`/orders`、`/cancel-market-orders` 和 `/cancel-all`。签名覆盖原始请求体。只释放绑定账户的挂单剩余预留,已成交数量保留,撤单事件与盘口变更一并提交。批量请求对重复订单号去重,其他账户的订单等同于找不到。局部失败写入 `not_canceled`。在同一签名的一次有效期内重试会返回原回执,避免旧的全撤请求影响后来下的订单,这是本地幂等约定。生产回执错误文本和撤单传播时延仍待实测。[官方撤单说明](https://docs.polymarket.com/trading/manage-orders#cancel-orders)
|
||||
|
||||
私有 `POST /order` 支持 CTF Exchange v2 和 Protocol V2 仓位订单的 EOA、Proxy、Safe 和 ERC‑1271 签名。EIP‑712 绑定双方地址、资产、数量、方向、签名类型、时间戳和扩展字段;有效期、订单类型及 post-only 由 HTTP HMAC 覆盖。先验签,再将配置中的数值资产 ID 映射到本地结果。签名摘要作为 `orderID`,同一签名重送沿用原回执。查询、撤单和账户推送都使用该哈希。旧版签名订单根据持久化回执补建索引,未签名的模拟订单沿用数字标识。样例中提交以 0.60 买入 3 份的 GTC,账户预留 1.80 模拟美元。样例的订单摘要和签名已用 Python `eth-account` 独立验证。[签名样例](examples/signed-ctf-order.json) · [官方签名结构](https://github.com/Polymarket/py-clob-client-v2/blob/main/py_clob_client_v2/order_utils/exchange_order_builder_v2.py)
|
||||
|
||||
Proxy 和 Safe 的验签同时检查 EIP‑712 签名者与 API 凭证绑定的钱包身份,以及用所配置工厂推导出的 maker。两个样例地址、订单摘要及签名用 Python `eth-account` 和 `eth-abi` 独立核对,另含一条使用正确签名者签名但 maker 不符合 Safe 推导规则的订单。本地账本继续用凭证账户记账。订单、回执及验签后的 maker 地址同事务保存,HTTP 查单、成交过滤和账户推送读取所关联订单的钱包。升级前的订单在收到相同的已验签请求后补记钱包,沿用原回执。[代理钱包样例](examples/signed-ctf-wallet-orders.json) · [官方验签规则](https://github.com/Polymarket/ctf-exchange-v2/blob/main/src/exchange/mixins/Signatures.sol)
|
||||
|
||||
ERC‑1271 订单的 maker 和 signer 同为本地凭证绑定的合约钱包。请求的 HMAC 使用凭证地址,签名者授权由钱包合约在所配置链上判断。RPC 使用交易合约地址作为调用方,并检查钱包返回的 ERC‑1271 魔术值。调用为只读模拟,账本仍在本地。合成样例根据 SDK 的嵌套签名格式生成,包含用于对照的订单哈希和 ABI 请求。已核对离线样例,另提供模拟 RPC 回归用例。生产钱包权限、链状态变化以及链上成交仍待实测。[SDK 签名格式](https://github.com/Polymarket/py-clob-client-v2/blob/main/py_clob_client_v2/order_utils/exchange_order_builder_v2.py) · [合成样例](examples/signed-ctf-contract-wallet.json)
|
||||
|
||||
Protocol V2 的 position ID 继续通过订单 `tokenId` 字段传输。资产映射指定 EIP‑712 版本 `"3"` 和 Exchange 合约,配置校验结果索引以及本地市场内成对仓位的条件和合约一致性。对官方 Polygon 部署执行只读 `domainSeparator()`,得到 `0x466c63910185bbd55e8679264200c4e0abdcbb0c6264eb3d41d13326022e095b`,与按 SDK 的域名、版本 `3`、链 ID `137` 和代理合约地址独立计算的结果一致。合成样例用隔离的链 ID,覆盖四种钱包类型。[官方 SDK 订单路由](https://github.com/Polymarket/py-clob-client-v2/blob/main/py_clob_client_v2/order_builder/builder.py) · [仓位 ID 规范](https://github.com/Polymarket/polymarket-v2-external/blob/main/docs/position-ids.md) · [签名样例](examples/signed-protocol-v2-orders.json)
|
||||
|
||||
限价单要求签名金额和本地盘口精度完全匹配。即时买单的保护价向下取整,卖单向上取整,两者仍须通过市场步长校验。市场买单沿用本地整分预算,份额限价单和即时卖单沿用 0.01 份的撮合单位。`POST /orders` 可一次提交 1 至 15 笔,按输入顺序逐项返回成功或失败。本地写事务逐项受理,生产接口并行处理。链上成交回执与 Protocol V2 的链上结算仍待接入。本轮未使用生产交易凭证。[官方批量接口](https://docs.polymarket.com/api-reference/trade/post-multiple-orders)
|
||||
|
||||
订单提交回执采用 SDK 的 `makingAmount`、`takingAmount` 和 `tradeIDs`。无即时成交时采用官方挂单示例的签名金额。有即时成交时,回执按买卖方向返回实际成交本金及份额的整数微单位,费用保存在本地回执中。两档合计成交时返回每笔执行 ID,与账户成交查询一致。部分成交的剩余挂单继续显示在订单查询中。重试从原订单的吃单执行重建回执,后来作为挂单方的成交和集合竞价不计入首次提交。生产环境的延迟匹配状态、金额计算细节与链上回执仍待实测。[官方下单说明](https://docs.polymarket.com/trading/place-orders#check-the-response) · [官方 Rust SDK 回执](https://github.com/Polymarket/rs-clob-client-v2/blob/main/src/clob/types/response.rs)
|
||||
|
||||
体育盘可配置异步秒级延迟,Gamma 返回 `secondsDelay`。本地只延迟已验签且提交时可立即成交的订单,期间不占用余额、盘口或成交记录,同哈希重送沿用 `delayed` 回执。到期由账户 HTTP 的维护循环处理,经数据库重启仍可续跑。撤单对等待中的订单返回不可撤销。到期按市场、余额、有效期和盘口重新校验。GTC 或 GTD 无即时成交时可进入盘口,FOK、FAK 和未通过检查的订单走原有执行规则。生产市场的启停条件、延迟传播及余额预留细节仍待实测。[官方订单生命周期](https://docs.polymarket.com/concepts/order-lifecycle) · [官方市场字段](https://docs.polymarket.com/api-reference/markets/get-market-by-id)
|
||||
|
||||
`itode` 市场使用同一持久化队列,短时等待固定为 150 毫秒。CLOB 的 `/clob-markets/{condition_id}` 在启用时发布 `itode: true`。HTTP 等待时释放 Exchange 互斥锁,按原订单哈希查询最终执行结果。批量响应只等待同步短时窗口并保留原顺序。重启、重试或更改市场延迟设置时,以订单首次入队的响应模式为准。生产抖动和批量尾延迟仍待实测。[官方撮合窗口](https://docs.polymarket.com/concepts/order-lifecycle)
|
||||
|
||||
## 市场 WebSocket 的订阅与推送
|
||||
|
||||
`/ws/market` 使用原始行情协议的毫秒时间戳字符串和顶层 `event_type`。首次 `type: market` 订阅默认收到一组 `book`;可用 `initial_dump: false` 跳过。动态 `subscribe` 总是为新资产发送快照,重复订阅同一资产保持原进度。退订只影响当前连接。两侧同时订阅时,变化可合并在同一条 `price_change` 内;已有订阅的积压变化和新订阅的快照使用各自起点。启用 `custom_feature_enabled` 后额外发送最优档发生变化的 `best_bid_ask`,同价档量变化只发 `price_change`。协议样例采用 Eventbook 资产 ID。[官方原始帧示例](https://docs.polymarket.com/market-data/realtime-data.md) · [可重放的客户端文本帧](examples/market-ws.txt)
|
||||
@@ -433,6 +393,14 @@ 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)
|
||||
@@ -457,13 +425,19 @@ 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)
|
||||
|
||||
### 日终快照的历史份额
|
||||
|
||||
官方日终快照在次日 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)
|
||||
|
||||
本地组合与单盘共用分页及汇总,并按本地稳定顺序追加组合。组合使用模块 3,`title`、`slug`、`event_slug` 为 null。组合余额与成本均从日终切点之前的账本流水重放。任一腿兑付为零可提前确定组合兑付,其余情况等待所有腿。零兑付侧保留终局之前的成本,即使之后已部分烧毁。未结算时只采用切点之前该侧的真实组合成交价。拆分或合并成交有两侧报价,直接转让只为成交的一侧记录价格。缺价回退到成本。结算价值按实际份额使用完整兑付精度,显示的每份价格保留到微美元。本次生产快照请求返回 403。生产行情来源和成本样例仍待获取。
|
||||
|
||||
### Data API 账户持仓价值
|
||||
|
||||
官方 `GET /v2/value` 要求传 user,可选最多 20 个不同 condition。结果是 data 对象,内含 proxy_wallet 和四位小数精度的美元金额。一个无持仓的钱包值为零。官方总额还包括未终结组合的成本基础,指定 condition 时仅统计选中的单盘。资金余额不计入持仓价值。[官方 OpenAPI](https://data-api.polymarket.com/v2/openapi.json)
|
||||
|
||||
本地可以重放 [估值样例](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 未平仓量与归档
|
||||
|
||||
@@ -495,6 +469,22 @@ SDK 使用 `GET /neg-risk?token_id=…`,也可以从已缓存的 CLOB 市场
|
||||
|
||||
在同一数据库先重放[费用样例](examples/neg-risk-fee.jsonl),再重放[裁决后转换样例](examples/neg-risk-after-verdict.jsonl)。甲先判 NO,新增转换把准备金增至 500002 微美元。「其他」判 YES 后,用户和金库分别领取 493752 和 6250 微美元;赢家抵押归零。乙也判 NO 后,用户交回剩余的甲 NO 和乙 NO,各 250001 微份。转换当场向「其他」补入 250001 微美元抵押,用户和金库可再领取 246876 和 3125。每次领取使用独立的请求 ID。另一种情形中,如果输入包含赢家自己的 NO,这些份额的兑付价值已经为零,现存赢家 YES 的抵押须全额保留。
|
||||
|
||||
### 组合定义、抵押与兑付
|
||||
|
||||
官方 CombinatorialModule 以规范腿集合标识组合。重复腿、同一条件的相反结果和非二元腿受到限制。组合 YES 的兑付乘各腿权重,NO 用其补数。若已有零兑付腿,未裁决的其他腿不会阻止兑付。合约保留 36 位累积精度,YES 用向下系数,NO 用向上系数的补数,每次实际兑付按抵押币最小单位向下取整。[组合合约](https://github.com/Polymarket/polymarket-v2-external/blob/main/src/modules/CombinatorialModule.sol) · [官方日终估值规则](https://docs.polymarket.com/api-reference/wallet/snapshot-a-wallets-positions-at-the-end-of-a-day)
|
||||
|
||||
本地接受 2 至 50 条已经上架的二元腿。按市场 ID 排序后生成独立的本地组合 ID,两侧份额使用其各自的本地标识。拆分、合并和兑付与抵押账本及请求回执同事务写入,不改动底层市场的份额。组合账本在最后一笔份额烧毁后登记无法兑付的尾差。重放[组合样例](examples/combo-ledger.jsonl),分别选择 A 的 YES 和 B 的 NO。拆分 1000003 微份后合并 2 微份。两条腿都作废时,YES 每份为 0.25,NO 每份为 0.75,实际分别兑付 250000 与 750000 微美元,最后记录 1 微美元尾差。
|
||||
|
||||
本轮公开组合候选目录返回 HTTP 403。生产 RFQ 资格、报价和成交,链上标识以及组合持仓对账仍待接入和验证。[公开候选目录规范](https://docs.polymarket.com/api-reference/combo-markets/get-combo-markets)
|
||||
|
||||
### 组合 RFQ 的状态、预留与成交
|
||||
|
||||
官方请求与报价模型区分 BUY/SELL、YES/NO,以及份额或名义金额。询价有报价提交期限,接受选定报价后,系统向报价方发带 `confirm_by` 的最后确认消息。确认后线上另有执行状态。本地可信 JSONL 实现这一流程,以数据库时钟约束期限。提交、接受和最后确认窗口默认分别为 10、20 和 5 秒,可由模拟请求显式设定。接受报价后立即复核并冻结双方资金或份额。报价可供请求方选择,同价时优先较大数量,再按提交顺序。选择和预留不走公开盘口。[官方报价网关](https://docs.polymarket.com/api-reference/wss/rfq) · [最后确认](https://docs.polymarket.com/api-reference/maker/confirm-or-decline-last-look) · [请求方 SDK](https://github.com/Polymarket/ts-sdk/blob/main/packages/bindings/src/combos/builder-rfq.ts)
|
||||
|
||||
报价的微美元本金是数量乘微美元价格后向下取整。本地份额询价可接受不超请求数量的单个报价,名义金额用于限制 BUY 的预算。按方向与报价资金来源,结算可转让已持有份额、用双方资金拆分、或用互补库存合并。重放[样例](examples/combo-rfq.jsonl),双方分别出资 1.40 和 2.60 生成四对份额。再合并 1.5 对后,报价方和请求方分别收回 0.90 和 0.60,组合抵押剩 2.50。相同确认请求重放原成交。拒绝和到期释放全部预留,重启后检查已到期请求。
|
||||
|
||||
当前交付采用本地单报价选中、无手续费和同步结算。外场签名、报价聚合、费率、线上限额、联网做市商的报价投递和链上异步执行还有待接入。
|
||||
|
||||
### 互斥适配器按量赎回
|
||||
|
||||
当前 SDK 的 `redeem_positions(condition_id)` 选择该市场的协议路径,领取持有人两侧的余额。另一个公开入口是 NegRiskAdapter 的 `redeemPositions(conditionId, amounts)`,先将调用人指定的 YES 和 NO 转入适配器,再执行底层兑付。即使兑付额为零,适配器仍发出带有输入数量和兑付额的事件。以下样例验证该适配器的数量语义;生产协议版本、批量交易及链上回执尚待比对。[官方持仓接口](https://docs.polymarket.com/trading/positions/manage) · [适配器源码](https://github.com/Polymarket/neg-risk-ctf-adapter/blob/main/src/NegRiskAdapter.sol#L191-L207)
|
||||
@@ -511,9 +501,3 @@ SDK 使用 `GET /neg-risk?token_id=…`,也可以从已缓存的 CLOB 市场
|
||||
### 已裁决市场的公开盘口
|
||||
|
||||
对电竞、乒乓球和 SOL 涨跌盘的六个已裁决结果单查 /book,全部返回 404。批量 /books 和 /prices 忽略已裁决资产,混合批次保留可用资产。中点和价差多数同样返回 404,但一个 V2 市场的两侧分别仍能读到价差 1 或中点 0.5。Eventbook 对已裁决结果统一省略四种公开行情,保留内部快照供交易状态和回放。封盘待裁决阶段、外场淘汰时延和例外是否由服务缓存触发仍待验证。[生产响应](examples/public-resolved-books.json)
|
||||
|
||||
### 做市返佣档位与日结
|
||||
|
||||
`POST /v1/maker-tier/tiers` 查询截至 UTC 日开始前 30 天的 maker 加权成交。权重为成交份额乘价格乘一减价格。仅使用实际记录的吃单费和已验证的钱包,排除无费用成交、集合竞价、同本地账户和同钱包对敲。模拟档位使用当前官方标准的 0%、3%、7%、10%、15%,以对应 UTC 日开始时的权重计算。[官方做市返佣公式和档位](https://docs.polymarket.com/programs/maker-rebates)
|
||||
|
||||
维护循环自动处理已结束且有收费成交的 UTC 日期。重启后按日期补结,每轮最多一天。可信操作员也可执行 `settle_maker_rebates`。日结按市场汇总实际吃单费乘档位比例。钱包当日累计达到 1 pUSD 才将返佣增加到模拟现金余额,并在同一事务写入日结与逐市场明细。`GET /rebates/current` 按指定钱包和日期返回已发放金额的十进制字符串,空结果为 null。JSONL 账户活动以 `MAKER_REBATE` 显示收益日期、到账时间和净金额。升级前的返佣记录若缺少到账时间则返回 null。活动档位覆盖、钱包组归集、链上发放和生产账本对账仍待接入或验证。[官方档位查询](https://docs.polymarket.com/api-reference/rebates/get-maker-tiers-for-addresses) · [官方返佣查询](https://docs.polymarket.com/api-reference/rebates/get-current-rebated-fees-for-a-maker)
|
||||
|
||||
Reference in New Issue
Block a user