Expose event and market directory details with consistent outcome prices

This commit is contained in:
2026-12-03 11:54:06 +08:00
parent 9cbcc03681
commit 6f620089b6
9 changed files with 361 additions and 12 deletions
+25
View File
@@ -242,3 +242,28 @@ sequenceDiagram
```
event_id 取自本地 events 或 catalog 查询,market_id 取自 assets 查询。两个参数均可重复,同类 ID 取并集,同时指定事件与市场时取交集。独立市场的公告也能通过 market_id 查询。默认按公告 ID 降序,每页 20 条;支持 order=id、ascending、offset 和 0 到 100 的 limit。当前查询对其他筛选参数返回 400。
### 从事件页进入订单簿
```mermaid
flowchart LR
H["market_http.rs"] --> G["exchange/gamma_directory.rs"]
H --> B["exchange/book_snapshot.rs"]
```
```mermaid
sequenceDiagram
participant C as 客户端
participant H as market-http
participant E as Exchange
C->>H: GET /events/slug/nvda-closing-price-2027
H->>E: gamma_event
E-->>C: markets 数组,每项含该门槛的目录 ID
C->>H: GET /markets/{id}
H->>E: gamma_market
E-->>C: outcomes 与 clobTokenIds,均为 JSON 数组编码的字符串
C->>H: GET /book?token_id=选中的资产
H-->>C: 该结果的买卖盘
```
加载 [主题事件样例](../../docs/examples/topic.jsonl) 后即可按上图读取。事件与市场均支持按数字 ID 和按 slug 查询,缺失资源返回 404。路径段按 UTF-8 百分号编码,路径中的加号表示加号。当前详情入口支持无查询参数的 GET。
+97 -1
View File
@@ -251,6 +251,46 @@ fn market_lookup(engine: &Mutex<Exchange>, prefix: &str, raw: &str) -> Reply {
.ok_or((if is_token { 404 } else { 400 }, "market not found"))
}
fn directory_route(path: &str) -> Option<(&str, bool, &str)> {
let (resource, tail) = path.strip_prefix('/')?.split_once('/')?;
if !matches!(resource, "markets" | "events") {
return None;
}
let (by_slug, raw) = match tail.strip_prefix("slug/") {
Some(slug) => (true, slug),
None => (false, tail),
};
(!raw.is_empty() && !raw.contains('/')).then_some((resource, by_slug, raw))
}
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"));
}
let value = percent_decode_str(raw)
.decode_utf8()
.map_err(|_| (400, "Invalid directory key"))?;
let key = if by_slug {
exchange::DirectoryKey::Slug(&value)
} else {
let id = value
.parse::<i64>()
.ok()
.filter(|id| *id > 0 && value.bytes().all(|b| b.is_ascii_digit()))
.ok_or((400, "Invalid directory id"))?;
exchange::DirectoryKey::Id(id)
};
let exchange = engine.lock().map_err(|_| (500, "Directory unavailable"))?;
let found = match resource {
"markets" => exchange.gamma_market(key),
_ => exchange.gamma_event(key),
};
found
.map_err(|_| (500, "Directory unavailable"))?
.ok_or((404, "Not found"))
}
fn clarifications(engine: &Mutex<Exchange>, query: &str) -> Reply {
let invalid = (400, "Invalid clarification query");
let fields: Vec<(String, String)> = serde_urlencoded::from_str(query).map_err(|_| invalid)?;
@@ -425,7 +465,14 @@ fn respond(mut req: Request, engine: &Mutex<Exchange>) -> std::io::Result<()> {
allow = Some("POST");
Err((405, "Method not allowed"))
}
_ => Err((404, "Not found")),
_ => match directory_route(path) {
Some(route) if req.method() == &Method::Get => directory_lookup(engine, route, params),
Some(_) => {
allow = Some("GET");
Err((405, "Method not allowed"))
}
None => Err((404, "Not found")),
},
};
let (status, body) = match reply {
Ok(v) => (200, v),
@@ -550,7 +597,56 @@ mod tests {
let note_query = format!(
"/market-clarifications?market_id=9999&market_id={note_id}&order=id&ascending=true"
);
for command in include_str!("../../../docs/examples/topic.jsonl")
.lines()
.take(3)
{
db.execute(serde_json::from_str(command).unwrap()).unwrap();
}
let topic = db
.gamma_event(exchange::DirectoryKey::Slug("nvda-closing-price-2027"))
.unwrap()
.unwrap();
let event_path = format!("/events/{}", topic["id"].as_str().unwrap());
let first_child = &topic["markets"][0];
assert_eq!(first_child["conditionId"], "nvda-200");
assert_eq!(topic["markets"].as_array().unwrap().len(), 2);
let info = db
.gamma_market(exchange::DirectoryKey::Slug("nvda-200"))
.unwrap()
.unwrap();
let market_path = format!("/markets/{}", info["id"].as_str().unwrap());
assert_eq!(info["events"][0]["id"], topic["id"]);
assert_eq!(
serde_json::from_str::<[String; 2]>(info["clobTokenIds"].as_str().unwrap()).unwrap()[0],
"eb:YES:nvda-200"
);
assert_eq!(
serde_json::from_str::<[String; 2]>(info["outcomes"].as_str().unwrap()).unwrap()[1],
"未超过"
);
let separate = db
.gamma_market(exchange::DirectoryKey::Slug("map+2/1"))
.unwrap()
.unwrap();
assert_eq!(separate["events"], json!([]));
let quoted = db
.gamma_market(exchange::DirectoryKey::Slug("s"))
.unwrap()
.unwrap();
assert_eq!(quoted["bestBid"], json!(0.39));
assert_eq!(quoted["bestAsk"], json!(0.41));
assert_eq!(quoted["outcomePrices"], r#"["0.4","0.6"]"#);
let cases = [
("GET",event_path.as_str(),String::new(),200,Some(topic.clone())),
("GET","/events/slug/nvda-closing-price-2027",String::new(),200,Some(topic)),
("GET",market_path.as_str(),String::new(),200,Some(info.clone())),
("GET","/markets/slug/nvda-200",String::new(),200,Some(info)),
("GET","/markets/slug/map+2%2F1",String::new(),200,Some(separate)),
("GET","/events/0",String::new(),400,None),
("GET","/markets/slug/missing",String::new(),404,None),
("GET","/events/999999",String::new(),404,None),
("POST","/events/slug/test","{}".into(),405,None),
("GET","/market-clarifications?event_id=1&event_id=2",String::new(),200,Some(json!([]))),
("GET","/market-clarifications?event_id=0",String::new(),400,None),
("GET",note_query.as_str(),String::new(),200,Some(note)),