Compare commits

...

1 Commits

Author SHA1 Message Date
codex-bot 953a3521fc Match CLOB order defaults and delayed live receipts 2026-12-05 23:28:22 +08:00
5 changed files with 174 additions and 15 deletions
+8
View File
@@ -173,6 +173,8 @@ CTF 市场可在任一结果资产映射中填写 `condition_id`(32 字节十
`POST /orders` 接受最多 15 笔签名订单组成的 JSON 数组。对整个数组的原始请求体验签,再逐项验订单签名。本地按输入顺序受理,结果数组与输入对齐,单项失败时其余有效订单继续提交。[官方批量接口](https://docs.polymarket.com/api-reference/trade/post-multiple-orders)
单笔和批量订单省略 `orderType` 时按 GTC 处理。同一签名订单显式传 GTC 时沿用同一回执。同步延迟期间若对手撤单,受理后实际进入盘口的订单返回 `live`,金额采用原限价条款。
```mermaid
flowchart LR
main["main.rs"] --> http["account_http.rs"]
@@ -223,6 +225,7 @@ sequenceDiagram
H-->>C: HTTP 401
else 提交签名订单
H->>V: 提交订单、API key 与已认证的签名者地址
V->>V: 省略 orderType 时使用 GTC
V->>V: 按 tokenId 查找资产、EIP-712 域并核对钱包绑定
alt 合约钱包
V->>R: eth_call isValidSignature(hash, signature)
@@ -234,6 +237,11 @@ sequenceDiagram
V->>E: 以订单哈希为幂等键提交本地订单与已验签 maker
E-->>V: 返回挂单、即时成交或 delayed 回执
V-->>H: 返回订单状态、资产数量和即时成交 ID
opt 等待同步延迟回执
H->>V: 按订单哈希读取最终结果
V->>E: 读取首次提交成交,若实际挂单则读取原限价数量
V-->>H: 返回 live 或 matched 等最终状态
end
else 验证失败
V-->>H: 返回订单拒绝
end
+149 -15
View File
@@ -387,20 +387,32 @@ fn placement_response(
.as_i64()
.context("missing signed order number")?;
let fills = engine.submission_fills(order)?;
let (status, making, taking) = if fills.trade_ids.is_empty() {
match signed_amounts {
Some((making, taking)) if receipt["status"] == "live" => ("live", making, taking),
_ => ("unmatched", String::new(), String::new()),
}
} else {
let cash = fills.cash_micros.to_string();
let shares = fills.shares_micros.to_string();
let wire_amounts = |cash: i128, shares: i128| {
if selling {
("matched", shares, cash)
(shares.to_string(), cash.to_string())
} else {
("matched", cash, shares)
(cash.to_string(), shares.to_string())
}
};
let (status, (making, taking)) = if !fills.trade_ids.is_empty() {
(
"matched",
wire_amounts(fills.cash_micros, fills.shares_micros),
)
} else if receipt["status"] == "live" {
let amounts = match signed_amounts {
Some(amounts) => amounts,
None => {
// A synchronous order may stop crossing before release and rest
// instead. The accepted order retains the exact limit amounts.
let (cash, shares) = engine.submission_amounts(order)?;
wire_amounts(cash, shares)
}
};
("live", amounts)
} else {
("unmatched", (String::new(), String::new()))
};
let trade_ids: Vec<_> = fills
.trade_ids
.into_iter()
@@ -437,13 +449,35 @@ pub(crate) fn rejected_order() -> Value {
struct Request {
owner: String,
order: Order,
order_type: String,
#[serde(default)]
order_type: OrderType,
#[serde(default)]
post_only: bool,
#[serde(default)]
defer_exec: bool,
}
#[derive(Clone, Copy, Default, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
enum OrderType {
#[default]
Gtc,
Gtd,
Fak,
Fok,
}
impl OrderType {
fn as_str(self) -> &'static str {
match self {
Self::Gtc => "GTC",
Self::Gtd => "GTD",
Self::Fak => "FAK",
Self::Fok => "FOK",
}
}
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct Order {
@@ -561,10 +595,6 @@ impl Request {
ensure!(maker > 0 && taker > 0, "invalid signed amounts");
let expiry: i64 = self.order.expiration.parse()?;
let tif = self.order_type.as_str();
ensure!(
matches!(tif, "GTC" | "GTD" | "FAK" | "FOK"),
"unsupported order type"
);
ensure!(
if tif == "GTD" {
expiry > 0
@@ -773,6 +803,110 @@ mod tests {
serde_json::from_str(include_str!("../../../docs/examples/signed-ctf-order.json")).unwrap()
}
#[test]
fn omitted_order_type_is_gtc_in_single_and_mixed_batch_requests() {
let vector = sample();
let wallet = vector["wallet"].as_str().unwrap();
let orders =
Orders::new(serde_json::from_value(vector["order_config"].clone()).unwrap()).unwrap();
let explicit = &vector["request"];
let mut omitted = explicit.clone();
omitted.as_object_mut().unwrap().remove("orderType");
let mut invalid = omitted.clone();
invalid["orderType"] = Value::Null;
let mut engine = Exchange::open(":memory:").unwrap();
for cmd in [
json!({"op":"fund","id":"fund","account":"alice","cents":500}),
json!({"op":"list","id":"list","market":"demo","rules":"test","tick_size":"0.01"}),
json!({"op":"open","id":"open","market":"demo"}),
] {
engine.execute(cmd).unwrap();
}
let first = orders
.submit(
&mut engine,
"alice",
"alice-key",
wallet,
omitted.to_string().as_bytes(),
)
.unwrap();
assert_eq!(first["status"], "live");
assert_eq!(first["orderID"], vector["expected_order_hash"]);
let batch = json!([explicit, invalid, omitted]);
let reply = orders
.submit_batch(
&mut engine,
"alice",
"alice-key",
wallet,
batch.to_string().as_bytes(),
)
.unwrap();
assert_eq!(reply[0], first);
assert_eq!(reply[1], rejected_order());
assert_eq!(reply[2], first);
assert_eq!(
engine.execute(json!({"op":"state"})).unwrap()["orders"]
.as_array()
.unwrap()
.len(),
1
);
}
#[test]
fn synchronous_order_reports_live_if_liquidity_leaves_before_release() {
let vector = sample();
let wallet = vector["wallet"].as_str().unwrap();
let orders =
Orders::new(serde_json::from_value(vector["order_config"].clone()).unwrap()).unwrap();
let mut engine = Exchange::open(":memory:").unwrap();
for cmd in [
json!({"op":"fund","id":"alice","account":"alice","cents":500}),
json!({"op":"fund","id":"bob","account":"bob","cents":500}),
json!({"op":"list","id":"list","market":"demo","rules":"test","tick_size":"0.01"}),
json!({"op":"split","id":"split","account":"bob","market":"demo","qty":3}),
json!({"op":"open","id":"open","market":"demo"}),
json!({"op":"set_taker_delay","id":"delay","market":"demo","itode":true}),
] {
engine.execute(cmd).unwrap();
}
let ask = engine
.execute(json!({"op":"order","id":"ask","account":"bob",
"market":"demo","outcome":"YES","side":"sell","qty":3,"price":55}))
.unwrap();
let payload = vector["request"].to_string();
let queued = orders
.submit(
&mut engine,
"alice",
"alice-key",
wallet,
payload.as_bytes(),
)
.unwrap();
assert_eq!(queued["local_receipt"]["wait_for_result"], true);
engine
.execute(json!({"op":"cancel","id":"cancel","account":"bob","order":ask["order"]}))
.unwrap();
use std::time::{SystemTime, UNIX_EPOCH};
let ready = queued["local_receipt"]["ready_at_ms"].as_u64().unwrap();
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_millis() as u64;
thread::sleep(Duration::from_millis(ready.saturating_sub(now) + 1));
engine.maintain_delayed_orders().unwrap();
let hash = vector["expected_order_hash"].as_str().unwrap();
let reply = synchronous_reply(&engine, "alice", hash).unwrap().unwrap();
assert_eq!(reply["status"], "live");
assert_eq!(reply["makingAmount"], "1800000");
assert_eq!(reply["takingAmount"], "3000000");
assert_eq!(reply["tradeIDs"], json!([]));
}
fn position_sample() -> Value {
serde_json::from_str(include_str!(
"../../../docs/examples/signed-protocol-v2-orders.json"
+3
View File
@@ -256,6 +256,9 @@ sequenceDiagram
D->>D: 同事务记录受影响账户的事件
opt 已验签订单
E->>D: 保存订单哈希和 maker 钱包
opt 同步延迟后挂单
E->>D: 读取原始订单价格与数量,生成挂单回执金额
end
end
alt 事务提交
opt 客户端需要建立或刷新账户状态
+12
View File
@@ -77,6 +77,18 @@ pub(crate) fn lookup(db: &Connection, account: &str, raw: &str) -> Result<Option
}
impl Exchange {
/// Return the original cash and share amounts for an accepted limit order.
pub fn submission_amounts(&self, order: i64) -> Result<(i128, i128)> {
let mut stmt = self
.db
.prepare_cached("SELECT price,quantity FROM orders WHERE seq=?")?;
Ok(stmt.query_row([order], |row| {
let price = i128::from(row.get::<_, i64>(0)?);
let lots = i128::from(row.get::<_, i64>(1)?);
Ok((price * lots, lots * i128::from(crate::lots::MICROS)))
})?)
}
/// 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(
+2
View File
@@ -340,6 +340,8 @@ Protocol V2 的 position ID 继续通过订单 `tokenId` 字段传输。资产
`itode` 市场使用同一持久化队列,短时等待固定为 150 毫秒。CLOB 的 `/clob-markets/{condition_id}` 在启用时发布 `itode: true`。HTTP 等待时释放 Exchange 互斥锁,按原订单哈希查询最终执行结果。批量响应只等待同步短时窗口并保留原顺序。重启、重试或更改市场延迟设置时,以订单首次入队的响应模式为准。生产抖动和批量尾延迟仍待实测。[官方撮合窗口](https://docs.polymarket.com/concepts/order-lifecycle)
单笔和批量接口都将省略的 `orderType` 视为 GTC。用同一签名分别提交省略字段和显式 GTC 的请求,两者关联同一个订单哈希。同步延迟期间对手撤单时,回放样例中的买单以每份 0.60 挂 3 份,返回 `live`、`makingAmount=1800000` 和 `takingAmount=3000000`。这是本地重新撮合后进入盘口的回执行为,生产环境这一竞态仍待实测。[官方单笔接口](https://docs.polymarket.com/api-reference/trade/post-a-new-order) · [官方批量接口](https://docs.polymarket.com/api-reference/trade/post-multiple-orders) · [签名样例](examples/signed-ctf-order.json)
## 市场 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)