Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 5bbe185257 | |||
| f32b817c0a |
@@ -9,6 +9,8 @@
|
||||
```mermaid
|
||||
flowchart LR
|
||||
main["src/main.rs"] -->|把标准输入输出交给 serve| stream["src/stream.rs"]
|
||||
main -->|启动公开行情 HTTP| market_http["src/market_http.rs"]
|
||||
market_http -.->|查询 Gamma 标签及目录| api
|
||||
main -.->|打开数据库| api["exchange crate"]
|
||||
stream -.->|执行命令| api
|
||||
```
|
||||
@@ -425,3 +427,26 @@ sequenceDiagram
|
||||
E-->>H: true
|
||||
H-->>C: 200,neg_risk 为真
|
||||
```
|
||||
|
||||
|
||||
## Gamma 标签
|
||||
|
||||
按顺序重放 [NVIDIA 主题](../../docs/examples/topic.jsonl)和[标签样例](../../docs/examples/gamma-tags.jsonl)。使用 `GET /tags` 发现标签,使用 `GET /tags/101` 或 `GET /tags/slug/technology` 查询同一标签。事件和市场的数字 ID 分别来自 `GET /events?slug=nvda-closing-price-2027` 与 `GET /markets?slug=nvda-200`,可以拼入 `/events/{id}/tags` 或 `/markets/{id}/tags`。
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
actor C as 目录客户端
|
||||
participant H as market_http.rs
|
||||
participant E as Exchange
|
||||
C->>H: GET /tags/slug/price-thresholds
|
||||
H->>E: 按 slug 读取标签
|
||||
E-->>C: id 为字符串 102
|
||||
C->>H: GET /markets?tag_id=102&include_tag=true
|
||||
H->>E: 在分页前筛选已关联的市场
|
||||
E-->>H: nvda-200 和对应标签数组
|
||||
H-->>C: 盘口列表
|
||||
C->>H: GET /tags/slug/technology/related-tags/tags?omit_empty=true
|
||||
H->>E: 查 Technology 的直接相关标签及其开放赛事
|
||||
E-->>H: Price thresholds
|
||||
H-->>C: 相关标签详情数组
|
||||
```
|
||||
|
||||
+168
-11
@@ -255,7 +255,7 @@ fn market_lookup(engine: &Mutex<Exchange>, prefix: &str, raw: &str) -> Reply {
|
||||
|
||||
fn directory_route(path: &str) -> Option<(&str, bool, &str)> {
|
||||
let (resource, tail) = path.strip_prefix('/')?.split_once('/')?;
|
||||
if !matches!(resource, "markets" | "events") {
|
||||
if !matches!(resource, "markets" | "events" | "tags") {
|
||||
return None;
|
||||
}
|
||||
let (by_slug, raw) = match tail.strip_prefix("slug/") {
|
||||
@@ -265,27 +265,103 @@ fn directory_route(path: &str) -> Option<(&str, bool, &str)> {
|
||||
(!raw.is_empty() && !raw.contains('/')).then_some((resource, by_slug, raw))
|
||||
}
|
||||
|
||||
enum TagRoute<'a> {
|
||||
Related((bool, &'a str, bool)),
|
||||
Resource((exchange::DirectoryResource, &'a str)),
|
||||
}
|
||||
|
||||
fn related_tags_route(path: &str) -> Option<(bool, &str, bool)> {
|
||||
let (path, expanded) = path
|
||||
.strip_suffix("/tags")
|
||||
.map_or((path, false), |p| (p, true));
|
||||
let (resource, by_slug, raw) = directory_route(path.strip_suffix("/related-tags")?)?;
|
||||
(resource == "tags").then_some((by_slug, raw, expanded))
|
||||
}
|
||||
|
||||
fn related_tags(engine: &Mutex<Exchange>, route: (bool, &str, bool), params: &str) -> Reply {
|
||||
let (by_slug, raw, expanded) = route;
|
||||
let slug;
|
||||
let key = if by_slug {
|
||||
slug = percent_decode_str(raw)
|
||||
.decode_utf8()
|
||||
.map_err(|_| (400, "Invalid directory key"))?;
|
||||
exchange::DirectoryKey::Slug(&slug)
|
||||
} else {
|
||||
exchange::DirectoryKey::Id(directory_id(raw)?)
|
||||
};
|
||||
let query = serde_urlencoded::from_str::<exchange::RelatedTagsQuery>(params)
|
||||
.map_err(|_| (422, "Invalid related tag query"))?;
|
||||
engine
|
||||
.lock()
|
||||
.map_err(|_| (500, "Directory unavailable"))?
|
||||
.gamma_related_tags(key, expanded, query)
|
||||
.map(Value::Array)
|
||||
.map_err(|_| (500, "Directory unavailable"))
|
||||
}
|
||||
|
||||
fn resource_tags_route(path: &str) -> Option<(exchange::DirectoryResource, &str)> {
|
||||
let (resource, id) = path
|
||||
.strip_prefix('/')?
|
||||
.strip_suffix("/tags")?
|
||||
.split_once('/')?;
|
||||
if id.is_empty() || id.contains('/') {
|
||||
return None;
|
||||
}
|
||||
let resource = match resource {
|
||||
"events" => exchange::DirectoryResource::Events,
|
||||
"markets" => exchange::DirectoryResource::Markets,
|
||||
_ => return None,
|
||||
};
|
||||
Some((resource, id))
|
||||
}
|
||||
|
||||
fn resource_tags(
|
||||
engine: &Mutex<Exchange>,
|
||||
route: (exchange::DirectoryResource, &str),
|
||||
query: &str,
|
||||
) -> Reply {
|
||||
if !query.is_empty() {
|
||||
return Err((400, "Unsupported directory query"));
|
||||
}
|
||||
let (resource, raw) = route;
|
||||
let id = directory_id(raw)?;
|
||||
engine
|
||||
.lock()
|
||||
.map_err(|_| (500, "Directory unavailable"))?
|
||||
.gamma_resource_tags(resource, id)
|
||||
.map_err(|_| (500, "Directory unavailable"))?
|
||||
.ok_or((404, "Not found"))
|
||||
}
|
||||
|
||||
fn directory_id(raw: &str) -> std::result::Result<i64, (u16, &'static str)> {
|
||||
let value = percent_decode_str(raw)
|
||||
.decode_utf8()
|
||||
.map_err(|_| (400, "Invalid directory key"))?;
|
||||
value
|
||||
.parse::<i64>()
|
||||
.ok()
|
||||
.filter(|id| *id > 0 && value.bytes().all(|b| b.is_ascii_digit()))
|
||||
.ok_or((400, "Invalid directory id"))
|
||||
}
|
||||
|
||||
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 slug;
|
||||
let key = if by_slug {
|
||||
exchange::DirectoryKey::Slug(&value)
|
||||
slug = percent_decode_str(raw)
|
||||
.decode_utf8()
|
||||
.map_err(|_| (400, "Invalid directory key"))?;
|
||||
exchange::DirectoryKey::Slug(&slug)
|
||||
} 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)
|
||||
exchange::DirectoryKey::Id(directory_id(raw)?)
|
||||
};
|
||||
let exchange = engine.lock().map_err(|_| (500, "Directory unavailable"))?;
|
||||
let found = match resource {
|
||||
"markets" => exchange.gamma_market(key),
|
||||
"tags" => exchange.gamma_tag(key),
|
||||
_ => exchange.gamma_event(key),
|
||||
};
|
||||
found
|
||||
@@ -358,7 +434,43 @@ fn respond(mut req: Request, engine: &Mutex<Exchange>) -> std::io::Result<()> {
|
||||
};
|
||||
return send(req, status, body, None);
|
||||
}
|
||||
let tags_lookup = related_tags_route(path)
|
||||
.map(TagRoute::Related)
|
||||
.or_else(|| resource_tags_route(path).map(TagRoute::Resource));
|
||||
if let Some(lookup) = tags_lookup {
|
||||
if req.method() != &Method::Get {
|
||||
return send(req, 405, json!({"error":"Method not allowed"}), Some("GET"));
|
||||
}
|
||||
let reply = match lookup {
|
||||
TagRoute::Related(route) => related_tags(engine, route, params),
|
||||
TagRoute::Resource(route) => resource_tags(engine, route, params),
|
||||
};
|
||||
let (status, body) = match reply {
|
||||
Ok(value) => (200, value),
|
||||
Err((status, msg)) => (status, json!({"error":msg})),
|
||||
};
|
||||
return send(req, status, body, None);
|
||||
}
|
||||
let reply = match (req.method(), path) {
|
||||
(&Method::Get, "/tags") => {
|
||||
let query = serde_urlencoded::from_str::<exchange::TagsQuery>(params);
|
||||
match query {
|
||||
Ok(query) => engine
|
||||
.lock()
|
||||
.map_err(|_| (500, "Directory unavailable"))
|
||||
.and_then(|e| {
|
||||
e.gamma_tags(query)
|
||||
.map(Value::Array)
|
||||
.map_err(|err| match err {
|
||||
exchange::MarketDataError::Invalid(_) => (422, "Invalid tag query"),
|
||||
exchange::MarketDataError::Unavailable => {
|
||||
(500, "Directory unavailable")
|
||||
}
|
||||
})
|
||||
}),
|
||||
Err(_) => Err((422, "Invalid tag query")),
|
||||
}
|
||||
}
|
||||
(&Method::Get, _) if is_setting => token_setting(name, engine, params, segment),
|
||||
(_, _) if is_setting => {
|
||||
allow = Some("GET");
|
||||
@@ -471,6 +583,7 @@ fn respond(mut req: Request, engine: &Mutex<Exchange>) -> std::io::Result<()> {
|
||||
| "/markets"
|
||||
| "/events"
|
||||
| "/market-clarifications"
|
||||
| "/tags"
|
||||
| "/v2/oi"
|
||||
| "/v2/value"
|
||||
| "/v2/trades"
|
||||
@@ -656,6 +769,13 @@ mod tests {
|
||||
{
|
||||
db.execute(serde_json::from_str(command).unwrap()).unwrap();
|
||||
}
|
||||
for line in include_str!("../../../docs/examples/gamma-tags.jsonl").lines() {
|
||||
db.execute(serde_json::from_str(line).unwrap()).unwrap();
|
||||
}
|
||||
assert!(db
|
||||
.execute(json!({"op":"set_tags","id":"invalid-tag-replacement",
|
||||
"kind":"event","target":"nvda-2027","tag_ids":[101,999]}))
|
||||
.is_err());
|
||||
let topic = db
|
||||
.gamma_event(exchange::DirectoryKey::Slug("nvda-closing-price-2027"))
|
||||
.unwrap()
|
||||
@@ -690,6 +810,20 @@ mod tests {
|
||||
assert_eq!(quoted["bestBid"], json!(0.39));
|
||||
assert_eq!(quoted["bestAsk"], json!(0.41));
|
||||
assert_eq!(quoted["outcomePrices"], r#"["0.4","0.6"]"#);
|
||||
assert!(db
|
||||
.execute(json!({"op":"set_related_tags","id":"invalid-tag-links",
|
||||
"tag_id":101,"links":[{"id":9001,"related_tag_id":999,"rank":1}]}))
|
||||
.is_err());
|
||||
let links = json!([{"id":"9001","tagID":101,"relatedTagID":103,"rank":1},
|
||||
{"id":"9002","tagID":101,"relatedTagID":102,"rank":2}]);
|
||||
let event_tags_path = format!("{event_path}/tags");
|
||||
let market_tags_path = format!("{market_path}/tags");
|
||||
let event_tags = topic["tags"].clone();
|
||||
assert_eq!(event_tags[0]["id"], "101");
|
||||
assert_eq!(event_tags[1]["id"], "102");
|
||||
let market_tags = json!([event_tags[1].clone()]);
|
||||
let mut tagged_market = info.clone();
|
||||
tagged_market["tags"] = market_tags.clone();
|
||||
let empty_trades = json!({"data":[],"pagination":{"limit":100,"offset":0,"has_more":false,"next_cursor":null}});
|
||||
let cases = [
|
||||
("GET","/v2/oi?conditionId=s,s",String::new(),200,Some(json!({"data":[{"condition_id":"s","value":0}]}))),
|
||||
@@ -715,6 +849,29 @@ mod tests {
|
||||
("GET","/markets?condition_ids=nvda-200&clob_token_ids=eb%3ANO%3Anvda-200&closed=Any",String::new(),200,Some(json!([info]))),
|
||||
("GET","/markets?active=true&closed=false&slug=map%2B2%2F1",String::new(),200,Some(json!([separate]))),
|
||||
("GET","/markets?condition_ids=s&clob_token_ids=unknown&closed=any",String::new(),200,Some(json!([]))),
|
||||
("GET","/tags?order=id&ascending=true&limit=1&offset=1",String::new(),200,Some(market_tags.clone())),
|
||||
("GET","/tags?is_carousel=false",String::new(),200,Some(market_tags.clone())),
|
||||
("GET","/tags/101",String::new(),200,Some(event_tags[0].clone())),
|
||||
("GET","/tags/slug/price-thresholds",String::new(),200,Some(event_tags[1].clone())),
|
||||
("GET","/tags/101/related-tags",String::new(),200,Some(links.clone())),
|
||||
("GET","/tags/slug/technology/related-tags?omit_empty=true",String::new(),200,Some(json!([links[1].clone()]))),
|
||||
("GET","/tags/101/related-tags?omit_empty=true&status=closed",String::new(),200,Some(json!([links[0].clone()]))),
|
||||
("GET","/tags/101/related-tags?omit_empty=true&status=all",String::new(),200,Some(links)),
|
||||
("GET","/tags/slug/technology/related-tags/tags?omit_empty=true",String::new(),200,Some(market_tags.clone())),
|
||||
("GET","/tags/999/related-tags",String::new(),200,Some(json!([]))),
|
||||
("GET","/tags/101/related-tags?omit_empty=invalid",String::new(),422,None),
|
||||
("GET","/markets?tag_id=101&related_tags=true&include_tag=true",String::new(),200,Some(json!([tagged_market.clone()]))),
|
||||
("GET","/events?tag_id=101&related_tags=true&closed=false",String::new(),200,Some(json!([topic.clone()]))),
|
||||
("GET","/events?tag_id=101&related_tags=false&closed=true",String::new(),200,Some(json!([]))),
|
||||
("GET","/events?tag_id=101&related_tags=true&tag_slug=technology&closed=true",String::new(),200,Some(json!([]))),
|
||||
("GET","/tags/999",String::new(),404,None),
|
||||
("GET",event_tags_path.as_str(),String::new(),200,Some(event_tags.clone())),
|
||||
("GET",market_tags_path.as_str(),String::new(),200,Some(market_tags)),
|
||||
("GET","/markets/999999/tags",String::new(),404,None),
|
||||
("GET","/events?tag_id=101&tag_slug=price-thresholds",String::new(),200,Some(json!([topic.clone()]))),
|
||||
("GET","/events?tag_id=101&exclude_tag_id=102",String::new(),200,Some(json!([]))),
|
||||
("GET","/markets?tag_id=102&include_tag=true",String::new(),200,Some(json!([tagged_market]))),
|
||||
("GET","/markets?tag_id=101",String::new(),200,Some(json!([]))),
|
||||
("GET","/markets?closed=any",String::new(),422,None),
|
||||
("GET","/events?closed=open",String::new(),422,None),
|
||||
("GET","/markets?limit=0",String::new(),200,Some(json!([]))),
|
||||
|
||||
@@ -9,6 +9,15 @@
|
||||
```mermaid
|
||||
flowchart LR
|
||||
test["tests/market.rs"] -->|通过公开 API 驱动市场| api["src/lib.rs"]
|
||||
api -->|初始化标签表| tags_sql["src/gamma_tags.sql"]
|
||||
market -->|保存标签及其归属| tags["src/gamma_tags.rs"]
|
||||
tags --> tags_sql
|
||||
tags --> tag_links_sql["src/gamma_tag_links.sql"]
|
||||
lists -->|扩展指定标签的直接关系| tags
|
||||
directory["src/gamma_directory.rs"] -->|读取赛事标签| event_sql["src/gamma_events.sql"]
|
||||
lists["src/gamma_list.rs"] --> directory
|
||||
lists --> tags
|
||||
event_sql --> tags_sql
|
||||
api -->|解析结果资产 ID| assets["src/assets.rs"]
|
||||
queries -->|解析单笔和批量报价| marks
|
||||
marks -->|拆解每个 token_id| assets
|
||||
@@ -1434,3 +1443,21 @@ sequenceDiagram
|
||||
E-->>C: 返回本次两侧销毁量和实付金额
|
||||
end
|
||||
```
|
||||
|
||||
|
||||
## Gamma 标签和目录筛选
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
actor O as 操作员
|
||||
participant E as Exchange
|
||||
participant T as gamma_tags.rs
|
||||
participant D as SQLite
|
||||
actor C as 公开客户端
|
||||
O->>E: 登记标签、设置归属及相关标签关系
|
||||
E->>T: 校验目标与标签编号
|
||||
T->>D: 按事务保存标签、归属或带排名的有向关系
|
||||
C->>E: 查询标签、归属或按标签筛选目录
|
||||
E->>D: 查询关联,按需扩展数字标签的直接关系,再筛选和分页
|
||||
E-->>C: 标签对象、市场或赛事列表
|
||||
```
|
||||
|
||||
@@ -9,6 +9,19 @@ pub(crate) enum Command {
|
||||
micros: Option<i64>,
|
||||
},
|
||||
Event(crate::catalog::Event),
|
||||
#[serde(rename = "upsert_tag")]
|
||||
UpsertTag(crate::gamma_tags::Tag),
|
||||
#[serde(rename = "set_tags")]
|
||||
SetTags {
|
||||
kind: crate::gamma_tags::TagTarget,
|
||||
target: String,
|
||||
tag_ids: Vec<i64>,
|
||||
},
|
||||
#[serde(rename = "set_related_tags")]
|
||||
SetRelatedTags {
|
||||
tag_id: i64,
|
||||
links: Vec<crate::gamma_tags::TagLink>,
|
||||
},
|
||||
#[serde(rename = "reschedule_sports")]
|
||||
RescheduleSports {
|
||||
event: String,
|
||||
|
||||
@@ -18,7 +18,8 @@ pub(super) fn header(row: &Row<'_>) -> rusqlite::Result<(String, Value)> {
|
||||
let event = json!({
|
||||
"id":row.get::<_,i64>("event_id")?.to_string(),"slug":row.get::<_,String>("slug")?,
|
||||
"title":row.get::<_,String>("title")?,"category":row.get::<_,String>("category")?,
|
||||
"active":true,"closed":row.get::<_,bool>("closed")?
|
||||
"active":true,"closed":row.get::<_,bool>("closed")?,
|
||||
"tags":crate::gamma_tags::parse_wire(row.get("tags")?)?
|
||||
});
|
||||
Ok((key, event))
|
||||
}
|
||||
|
||||
@@ -5,5 +5,6 @@ SELECT e.id,e.event_id,e.slug,e.title,e.category,
|
||||
WHERE m.id IN (SELECT market FROM sports_markets WHERE event=e.id
|
||||
UNION ALL SELECT market FROM topic_markets WHERE event=e.id)
|
||||
AND COALESCE(a.role,'')<>'placeholder'
|
||||
),0) AS closed
|
||||
),0) AS closed,
|
||||
COALESCE((SELECT tags FROM event_tag_arrays a WHERE a.event=e.id),'[]') AS tags
|
||||
FROM numbered_events e
|
||||
|
||||
@@ -19,6 +19,11 @@ struct Filters {
|
||||
slugs: Vec<String>,
|
||||
conditions: Vec<String>,
|
||||
tokens: Vec<String>,
|
||||
tag_id: Option<i64>,
|
||||
tag_slug: Option<String>,
|
||||
excluded_tags: Vec<i64>,
|
||||
include_tag: bool,
|
||||
related_tags: bool,
|
||||
closed: Option<bool>,
|
||||
active: Option<bool>,
|
||||
order: String,
|
||||
@@ -70,6 +75,25 @@ impl Filters {
|
||||
.ok_or_else(|| invalid(key))?,
|
||||
),
|
||||
"slug" if !value.trim().is_empty() => f.slugs.push(value.clone()),
|
||||
"tag_id" | "exclude_tag_id" if key == "tag_id" || !markets => {
|
||||
let id = value
|
||||
.parse::<i64>()
|
||||
.ok()
|
||||
.filter(|id| *id > 0)
|
||||
.ok_or_else(|| invalid(key))?;
|
||||
if key == "tag_id" {
|
||||
f.tag_id = Some(id);
|
||||
} else {
|
||||
f.excluded_tags.push(id);
|
||||
}
|
||||
}
|
||||
"tag_slug" if !markets && !value.trim().is_empty() => {
|
||||
f.tag_slug = Some(value.clone());
|
||||
}
|
||||
"related_tags" => f.related_tags = value.parse().map_err(|_| invalid(key))?,
|
||||
"include_tag" if markets => {
|
||||
f.include_tag = value.parse().map_err(|_| invalid(key))?
|
||||
}
|
||||
"condition_ids" if markets && !value.trim().is_empty() => {
|
||||
f.conditions.push(value.clone())
|
||||
}
|
||||
@@ -130,11 +154,19 @@ 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 (?8 IS NULL OR COALESCE(v.active,1)=?8)
|
||||
AND (?9 IS NULL OR EXISTS(SELECT 1 FROM market_tags a WHERE a.market=w.market
|
||||
AND a.tag IN (SELECT value FROM json_each(?9))))";
|
||||
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)";
|
||||
AND (?3 IS NULL OR e.closed=?3)
|
||||
AND (?6 IS NULL OR EXISTS(SELECT 1 FROM event_tags a WHERE a.event=e.id
|
||||
AND a.tag IN (SELECT value FROM json_each(?6))))
|
||||
AND (?7 IS NULL OR EXISTS(SELECT 1 FROM event_tags a JOIN directory_tags t ON t.id=a.tag
|
||||
WHERE a.event=e.id AND t.slug=?7))
|
||||
AND NOT EXISTS(SELECT 1 FROM event_tags a WHERE a.event=e.id
|
||||
AND a.tag IN (SELECT value FROM json_each(?8)))";
|
||||
|
||||
fn markets(db: &Connection, f: &Filters, order: &str) -> rusqlite::Result<Vec<Value>> {
|
||||
// A supplied set containing only foreign tokens must match nothing.
|
||||
@@ -161,7 +193,8 @@ fn markets(db: &Connection, f: &Filters, order: &str) -> rusqlite::Result<Vec<Va
|
||||
f.closed,
|
||||
f.limit,
|
||||
f.offset,
|
||||
f.active
|
||||
f.active,
|
||||
crate::gamma_tags::tag_scope(db, f.tag_id, f.related_tags)?
|
||||
],
|
||||
|r| Ok((market(r)?, r.get::<_, Option<String>>("parent")?)),
|
||||
)?
|
||||
@@ -175,9 +208,30 @@ fn markets(db: &Connection, f: &Filters, order: &str) -> rusqlite::Result<Vec<Va
|
||||
let events = headers
|
||||
.query_map([json!(parents).to_string()], header)?
|
||||
.collect::<rusqlite::Result<HashMap<_, _>>>()?;
|
||||
let mut tags = HashMap::<String, Value>::new();
|
||||
if f.include_tag {
|
||||
let keys: Vec<_> = rows
|
||||
.iter()
|
||||
.filter_map(|(row, _)| row["conditionId"].as_str())
|
||||
.collect();
|
||||
let mut stmt = db.prepare_cached(
|
||||
"SELECT market,tags FROM market_tag_arrays WHERE market IN (SELECT value FROM json_each(?))",
|
||||
)?;
|
||||
tags = stmt
|
||||
.query_map([json!(keys).to_string()], |r| {
|
||||
Ok((r.get(0)?, crate::gamma_tags::parse_wire(r.get(1)?)?))
|
||||
})?
|
||||
.collect::<rusqlite::Result<_>>()?;
|
||||
}
|
||||
Ok(rows
|
||||
.into_iter()
|
||||
.map(|(mut row, parent)| {
|
||||
if f.include_tag {
|
||||
let assigned = row["conditionId"]
|
||||
.as_str()
|
||||
.and_then(|market| tags.remove(market));
|
||||
row["tags"] = assigned.unwrap_or_else(|| json!([]));
|
||||
}
|
||||
row["events"] = json!(parent
|
||||
.and_then(|key| events.get(&key))
|
||||
.into_iter()
|
||||
@@ -200,7 +254,10 @@ fn events(db: &Connection, f: &Filters, order: &str) -> rusqlite::Result<Vec<Val
|
||||
json!(f.slugs).to_string(),
|
||||
f.closed,
|
||||
f.limit,
|
||||
f.offset
|
||||
f.offset,
|
||||
crate::gamma_tags::tag_scope(db, f.tag_id, f.related_tags)?,
|
||||
f.tag_slug,
|
||||
json!(f.excluded_tags).to_string()
|
||||
],
|
||||
header,
|
||||
)?
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
BEGIN IMMEDIATE;
|
||||
CREATE TABLE IF NOT EXISTS directory_tag_links (
|
||||
id INTEGER PRIMARY KEY CHECK(id>0),
|
||||
tag INTEGER NOT NULL REFERENCES directory_tags(id),
|
||||
related_tag INTEGER NOT NULL REFERENCES directory_tags(id),
|
||||
rank INTEGER NOT NULL CHECK(rank>=0),
|
||||
UNIQUE(tag,related_tag),
|
||||
CHECK(tag<>related_tag)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS event_tags_by_tag ON event_tags(tag,event);
|
||||
COMMIT;
|
||||
@@ -0,0 +1,268 @@
|
||||
use crate::{validation::identifier, DirectoryKey, DirectoryResource, Exchange, MarketDataError};
|
||||
use anyhow::{ensure, Result};
|
||||
use rusqlite::{params, Connection, OptionalExtension, ToSql, Transaction};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
use std::collections::HashSet;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct Tag {
|
||||
tag_id: i64,
|
||||
slug: String,
|
||||
label: String,
|
||||
force_show: Option<bool>,
|
||||
force_hide: Option<bool>,
|
||||
is_carousel: Option<bool>,
|
||||
}
|
||||
|
||||
impl Tag {
|
||||
pub(crate) fn save(self, tx: &Transaction) -> Result<Value> {
|
||||
ensure!(self.tag_id > 0, "invalid tag id");
|
||||
identifier(&self.slug)?;
|
||||
identifier(&self.label)?;
|
||||
tx.execute(
|
||||
"INSERT INTO directory_tags VALUES(?1,?2,?3,?4,?5,?6,
|
||||
strftime('%Y-%m-%dT%H:%M:%fZ','now'),strftime('%Y-%m-%dT%H:%M:%fZ','now'))
|
||||
ON CONFLICT(id) DO UPDATE SET slug=excluded.slug,label=excluded.label,
|
||||
force_show=excluded.force_show,force_hide=excluded.force_hide,
|
||||
is_carousel=excluded.is_carousel,updated_at=excluded.updated_at",
|
||||
params![
|
||||
self.tag_id,
|
||||
self.slug,
|
||||
self.label,
|
||||
self.force_show,
|
||||
self.force_hide,
|
||||
self.is_carousel
|
||||
],
|
||||
)?;
|
||||
Ok(json!({"tag_id":self.tag_id.to_string()}))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub(crate) enum TagTarget {
|
||||
Event,
|
||||
Market,
|
||||
}
|
||||
|
||||
pub(crate) fn assign(
|
||||
tx: &Transaction,
|
||||
kind: TagTarget,
|
||||
target: &str,
|
||||
tags: Vec<i64>,
|
||||
) -> Result<Value> {
|
||||
identifier(target)?;
|
||||
ensure!(
|
||||
tags.iter().all(|id| *id > 0) && tags.iter().collect::<HashSet<_>>().len() == tags.len(),
|
||||
"tag ids must be positive and unique"
|
||||
);
|
||||
let (exists, remove, insert) = match kind {
|
||||
TagTarget::Event => (
|
||||
"SELECT EXISTS(SELECT 1 FROM event_directory_ids WHERE event=?)",
|
||||
"DELETE FROM event_tags WHERE event=?",
|
||||
"INSERT INTO event_tags VALUES(?1,?2,?3)",
|
||||
),
|
||||
TagTarget::Market => (
|
||||
"SELECT EXISTS(SELECT 1 FROM markets WHERE id=?)",
|
||||
"DELETE FROM market_tags WHERE market=?",
|
||||
"INSERT INTO market_tags VALUES(?1,?2,?3)",
|
||||
),
|
||||
};
|
||||
ensure!(
|
||||
tx.query_row(exists, [target], |r| r.get::<_, bool>(0))?,
|
||||
"tag target not found"
|
||||
);
|
||||
tx.execute(remove, [target])?;
|
||||
let mut stmt = tx.prepare_cached(insert)?;
|
||||
for (position, tag) in tags.iter().enumerate() {
|
||||
stmt.execute(params![target, tag, position as i64])?;
|
||||
}
|
||||
Ok(json!({"target":target,"tag_ids":tags}))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct TagLink {
|
||||
id: i64,
|
||||
related_tag_id: i64,
|
||||
rank: i64,
|
||||
}
|
||||
|
||||
pub(crate) fn set_links(tx: &Transaction, tag: i64, links: &[TagLink]) -> Result<Value> {
|
||||
let exists: bool = tx.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM directory_tags WHERE id=?)",
|
||||
[tag],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
ensure!(exists, "tag not found");
|
||||
tx.execute("DELETE FROM directory_tag_links WHERE tag=?", [tag])?;
|
||||
let mut stmt = tx.prepare_cached(
|
||||
"INSERT INTO directory_tag_links(id,tag,related_tag,rank) VALUES(?,?,?,?)",
|
||||
)?;
|
||||
for link in links {
|
||||
stmt.execute(params![link.id, tag, link.related_tag_id, link.rank])?;
|
||||
}
|
||||
Ok(json!({"tag_id":tag.to_string(),"links":links.len()}))
|
||||
}
|
||||
|
||||
pub(super) fn tag_scope(
|
||||
db: &Connection,
|
||||
tag: Option<i64>,
|
||||
related: bool,
|
||||
) -> rusqlite::Result<Option<String>> {
|
||||
let Some(tag) = tag else { return Ok(None) };
|
||||
if !related {
|
||||
return Ok(Some(json!([tag]).to_string()));
|
||||
}
|
||||
db.prepare_cached(
|
||||
"SELECT json_group_array(id) FROM (
|
||||
SELECT ?1 AS id UNION ALL SELECT related_tag FROM directory_tag_links WHERE tag=?1
|
||||
)",
|
||||
)?
|
||||
.query_row([tag], |r| r.get(0))
|
||||
.map(Some)
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct RelatedTagsQuery {
|
||||
omit_empty: Option<bool>,
|
||||
status: Option<String>,
|
||||
}
|
||||
|
||||
pub(super) fn parse_wire(raw: String) -> rusqlite::Result<Value> {
|
||||
serde_json::from_str(&raw).map_err(|err| {
|
||||
rusqlite::Error::FromSqlConversionFailure(0, rusqlite::types::Type::Text, Box::new(err))
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct TagsQuery {
|
||||
limit: Option<i64>,
|
||||
offset: Option<i64>,
|
||||
ascending: Option<bool>,
|
||||
order: Option<String>,
|
||||
is_carousel: Option<bool>,
|
||||
}
|
||||
|
||||
fn invalid() -> MarketDataError {
|
||||
MarketDataError::Invalid("Invalid tag query".into())
|
||||
}
|
||||
|
||||
impl Exchange {
|
||||
pub fn gamma_tags(&self, q: TagsQuery) -> Result<Vec<Value>, MarketDataError> {
|
||||
let limit = q.limit.unwrap_or(0);
|
||||
let offset = q.offset.unwrap_or(0);
|
||||
if limit < 0 || offset < 0 {
|
||||
return Err(invalid());
|
||||
}
|
||||
let direction = if q.ascending == Some(true) {
|
||||
"ASC"
|
||||
} else {
|
||||
"DESC"
|
||||
};
|
||||
let mut cols = Vec::new();
|
||||
for field in q.order.as_deref().unwrap_or("updatedAt").split(',') {
|
||||
cols.push(match field.trim() {
|
||||
"id" => "id",
|
||||
"slug" => "slug",
|
||||
"label" => "label",
|
||||
"createdAt" => "created_at",
|
||||
"updatedAt" => "updated_at",
|
||||
_ => return Err(invalid()),
|
||||
});
|
||||
}
|
||||
if !cols.contains(&"id") {
|
||||
cols.push("id");
|
||||
}
|
||||
let order = cols
|
||||
.iter()
|
||||
.map(|col| format!("{col} {direction}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
let sql = format!(
|
||||
"SELECT wire FROM directory_tag_wire WHERE (?1 IS NULL OR is_carousel=?1)
|
||||
ORDER BY {order} LIMIT ?2 OFFSET ?3"
|
||||
);
|
||||
let mut stmt = self.db.prepare_cached(&sql)?;
|
||||
let limit = if limit == 0 { 50 } else { limit };
|
||||
let rows = stmt.query_map(params![q.is_carousel, limit, offset], |r| {
|
||||
parse_wire(r.get(0)?)
|
||||
})?;
|
||||
Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
|
||||
}
|
||||
|
||||
pub fn gamma_tag(&self, key: DirectoryKey<'_>) -> Result<Option<Value>, MarketDataError> {
|
||||
let (sql, arg): (_, &dyn ToSql) = match &key {
|
||||
DirectoryKey::Id(id) => ("SELECT wire FROM directory_tag_wire WHERE id=?", id),
|
||||
DirectoryKey::Slug(slug) => ("SELECT wire FROM directory_tag_wire WHERE slug=?", slug),
|
||||
};
|
||||
Ok(self
|
||||
.db
|
||||
.prepare_cached(sql)?
|
||||
.query_row([arg], |r| parse_wire(r.get(0)?))
|
||||
.optional()?)
|
||||
}
|
||||
|
||||
pub fn gamma_related_tags(
|
||||
&self,
|
||||
key: DirectoryKey<'_>,
|
||||
expanded: bool,
|
||||
query: RelatedTagsQuery,
|
||||
) -> Result<Vec<Value>, MarketDataError> {
|
||||
let (field, arg): (_, &dyn ToSql) = match &key {
|
||||
DirectoryKey::Id(id) => ("id", id),
|
||||
DirectoryKey::Slug(slug) => ("slug", slug),
|
||||
};
|
||||
let status = match query.status.as_deref() {
|
||||
Some("closed") => Some(true),
|
||||
Some("all") => None,
|
||||
_ => Some(false),
|
||||
};
|
||||
let body = if expanded {
|
||||
"t.wire"
|
||||
} else {
|
||||
"json_object('id',CAST(l.id AS TEXT),'tagID',l.tag,'relatedTagID',l.related_tag,'rank',l.rank)"
|
||||
};
|
||||
let sql = format!(
|
||||
"WITH event_states AS NOT MATERIALIZED ({})
|
||||
SELECT {body} FROM directory_tag_links l
|
||||
JOIN directory_tag_wire t ON t.id=l.related_tag
|
||||
WHERE l.tag=(SELECT id FROM directory_tags WHERE {field}=?1)
|
||||
AND (NOT ?2 OR EXISTS(
|
||||
SELECT 1 FROM event_tags a JOIN event_states e ON e.id=a.event
|
||||
WHERE a.tag=l.related_tag AND (?3 IS NULL OR e.closed=?3)
|
||||
))
|
||||
ORDER BY l.rank,l.id",
|
||||
include_str!("gamma_events.sql"),
|
||||
);
|
||||
let mut stmt = self.db.prepare_cached(&sql)?;
|
||||
let rows = stmt.query_map(
|
||||
params![arg, query.omit_empty.unwrap_or(false), status],
|
||||
|r| parse_wire(r.get(0)?),
|
||||
)?;
|
||||
Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
|
||||
}
|
||||
|
||||
pub fn gamma_resource_tags(
|
||||
&self,
|
||||
resource: DirectoryResource,
|
||||
id: i64,
|
||||
) -> Result<Option<Value>, MarketDataError> {
|
||||
let sql = match resource {
|
||||
DirectoryResource::Events => "SELECT COALESCE(a.tags,'[]')
|
||||
FROM event_directory_ids e LEFT JOIN event_tag_arrays a ON a.event=e.event WHERE e.id=?",
|
||||
DirectoryResource::Markets => "SELECT COALESCE(a.tags,'[]')
|
||||
FROM market_directory_ids m LEFT JOIN augmented_outcomes o ON o.market=m.market
|
||||
LEFT JOIN market_tag_arrays a ON a.market=m.market
|
||||
WHERE m.id=? AND COALESCE(o.role,'')<>'placeholder'",
|
||||
};
|
||||
Ok(self
|
||||
.db
|
||||
.prepare_cached(sql)?
|
||||
.query_row([id], |r| parse_wire(r.get(0)?))
|
||||
.optional()?)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
BEGIN IMMEDIATE;
|
||||
CREATE TABLE IF NOT EXISTS directory_tags (
|
||||
id INTEGER PRIMARY KEY CHECK(id>0),
|
||||
slug TEXT NOT NULL UNIQUE,
|
||||
label TEXT NOT NULL,
|
||||
force_show INTEGER,
|
||||
force_hide INTEGER,
|
||||
is_carousel INTEGER,
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS event_tags (
|
||||
event TEXT NOT NULL REFERENCES event_directory_ids(event),
|
||||
tag INTEGER NOT NULL REFERENCES directory_tags(id),
|
||||
position INTEGER NOT NULL,
|
||||
PRIMARY KEY(event,tag)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS market_tags (
|
||||
market TEXT NOT NULL REFERENCES markets(id),
|
||||
tag INTEGER NOT NULL REFERENCES directory_tags(id),
|
||||
position INTEGER NOT NULL,
|
||||
PRIMARY KEY(market,tag)
|
||||
);
|
||||
CREATE VIEW IF NOT EXISTS directory_tag_wire AS
|
||||
SELECT id,slug,label,is_carousel,created_at,updated_at,
|
||||
json_patch(
|
||||
json_object('id',CAST(id AS TEXT),'slug',slug,'label',label,
|
||||
'createdAt',created_at,'updatedAt',updated_at),
|
||||
json_object('forceShow',json(CASE force_show WHEN 0 THEN 'false' WHEN 1 THEN 'true' END),
|
||||
'forceHide',json(CASE force_hide WHEN 0 THEN 'false' WHEN 1 THEN 'true' END),
|
||||
'isCarousel',json(CASE is_carousel WHEN 0 THEN 'false' WHEN 1 THEN 'true' END))
|
||||
) AS wire
|
||||
FROM directory_tags;
|
||||
CREATE VIEW IF NOT EXISTS event_tag_arrays AS
|
||||
SELECT event, json_group_array(json(wire)) AS tags
|
||||
FROM (SELECT a.event,t.wire FROM event_tags a JOIN directory_tag_wire t ON t.id=a.tag
|
||||
ORDER BY a.event,a.position)
|
||||
GROUP BY event;
|
||||
CREATE VIEW IF NOT EXISTS market_tag_arrays AS
|
||||
SELECT market, json_group_array(json(wire)) AS tags
|
||||
FROM (SELECT a.market,t.wire FROM market_tags a JOIN directory_tag_wire t ON t.id=a.tag
|
||||
ORDER BY a.market,a.position)
|
||||
GROUP BY market;
|
||||
COMMIT;
|
||||
@@ -10,6 +10,7 @@ mod expiry;
|
||||
mod fees;
|
||||
mod gamma_directory;
|
||||
mod gamma_list;
|
||||
mod gamma_tags;
|
||||
mod heartbeat;
|
||||
mod holders;
|
||||
mod twap;
|
||||
@@ -52,6 +53,7 @@ pub use assets::parse_id as parse_asset_id;
|
||||
pub use depth_feed::MarketPage;
|
||||
pub use gamma_directory::DirectoryKey;
|
||||
pub use gamma_list::DirectoryResource;
|
||||
pub use gamma_tags::{RelatedTagsQuery, TagsQuery};
|
||||
pub use open_interest::InterestQuery;
|
||||
pub use portfolio::http::ValueQuery;
|
||||
pub use prices_history::http::HistoryQuery;
|
||||
@@ -98,6 +100,20 @@ impl Exchange {
|
||||
if !directory_ready {
|
||||
db.execute_batch(include_str!("event_directory_schema.sql"))?;
|
||||
}
|
||||
let tags_ready: bool = db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='view' AND name='directory_tag_wire')",
|
||||
[], |r| r.get(0),
|
||||
)?;
|
||||
if !tags_ready {
|
||||
db.execute_batch(include_str!("gamma_tags.sql"))?;
|
||||
}
|
||||
let tag_links_ready: bool = db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='table' AND name='directory_tag_links')",
|
||||
[], |r| r.get(0),
|
||||
)?;
|
||||
if !tag_links_ready {
|
||||
db.execute_batch(include_str!("gamma_tag_links.sql"))?;
|
||||
}
|
||||
let kickoff_ready: bool = db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='table' AND name='sports_kickoffs')",
|
||||
[], |r| r.get(0),
|
||||
|
||||
@@ -58,6 +58,15 @@ pub(crate) fn apply(
|
||||
}
|
||||
Command::TickSizeChange(change) => change.apply(tx, request_id),
|
||||
Command::Event(event) => event.save(tx),
|
||||
Command::UpsertTag(tag) => tag.save(tx),
|
||||
Command::SetTags {
|
||||
kind,
|
||||
target,
|
||||
tag_ids,
|
||||
} => crate::gamma_tags::assign(tx, kind, &target, tag_ids),
|
||||
Command::SetRelatedTags { tag_id, links } => {
|
||||
crate::gamma_tags::set_links(tx, tag_id, &links)
|
||||
}
|
||||
Command::RescheduleSports {
|
||||
event,
|
||||
previous_ms,
|
||||
|
||||
@@ -8,11 +8,6 @@ cargo run --locked -p venue-probe
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
main -->|核对 CTF 权重| ctf["src/ctf_resolution.rs"]
|
||||
main -->|核对 V2 模块权重| position["src/position_resolution.rs"]
|
||||
position -->|解析目录及结果 ID| catalog
|
||||
position -->|读取最终确认区块| rpc["src/polygon_rpc.rs"]
|
||||
ctf -->|读取最终确认区块| rpc
|
||||
main["src/main.rs"] -->|依次调用两个只读探针| impls["src/probes.rs"]
|
||||
main -->|重放 Gamma 市场| catalog["src/catalog.rs"]
|
||||
impls -->|识别持仓协议及两套 ID| catalog
|
||||
@@ -128,55 +123,3 @@ sequenceDiagram
|
||||
2026-12-03 06:55 UTC 采集的[同侧报价快照](fixtures/live-side-prices.json)按请求保存前后盘口、报价、时间、方法及响应。双侧盘口最优价为 0.039 和 0.04。缺买盘的结果返回 BUY 字符串 0,缺卖盘的结果返回 SELL 字符串 1。批量 POST 返回相同字符串。文档列出的逗号分隔 GET 在这次生产取样返回 400。三个资产的前后盘口哈希各自一致。[官方单价接口](https://docs.polymarket.com/api-reference/market-data/get-market-price)
|
||||
|
||||
[电竞盘双空样本](fixtures/live-empty-prices.json)保留前后盘口和两次价格请求。两个深度数组均为空,公开 BUY 返回 "0",SELL 返回 "1"。探针把该结果计为已验证的空盘报价,实际可成交数量仍为零。
|
||||
|
||||
## Polygon CTF 裁决核对
|
||||
|
||||
`venue-probe --inspect-resolution CONDITION [EXPECTED]` 读取 Polygon 主网 CTF 的二元条件。默认使用 PublicNode,可通过 `EVENTBOOK_POLYGON_RPC_URL` 更换 HTTPS RPC。将输出保存为 JSON 后,`venue-probe --replay-resolution FILE [EXPECTED]` 可离线核对原始 ABI 字。`EXPECTED` 可用 `first`、`second`、`split`、`weighted`、`unresolved` 或 `unprepared`。前两个值指目录结果顺序,使用者应按已核实的结果映射指定预期。给出预期且不一致时,命令保留报告并以非零状态退出。
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
actor C as 调用者
|
||||
participant P as venue-probe
|
||||
participant N as Polygon RPC
|
||||
alt 现场读取
|
||||
C->>P: inspect-resolution CONDITION
|
||||
P->>N: 核对主网链 ID 及已最终确认区块
|
||||
P->>N: 在该区块读取结果数、分母和各侧权重
|
||||
P->>N: 复核区块哈希
|
||||
else 离线重放
|
||||
C->>P: replay-resolution FILE
|
||||
end
|
||||
P-->>C: 返回原始 ABI 字、十进制权重和对照结果
|
||||
```
|
||||
|
||||
[实测记录](fixtures/live-ctf-resolution.json)保存了两个独立节点一致返回的区块和权重。该市场的 Gamma 目录结果顺序为 Over、Under,链上分子为 0、1,分母为 1。探针只读取 CTF 的合约状态。结果由所选 RPC 提供,仅覆盖 CTF 二元条件。PositionManager 的读取路径见下节。链上状态证明仍待接入。[Gamma 封盘样本](../../docs/examples/public-closed-chart-history.json) · [Polymarket 合约清单](https://docs.polymarket.com/resources/contracts) · [Conditional Tokens 合约](https://github.com/gnosis/conditional-tokens-contracts/blob/master/contracts/ConditionalTokens.sol)
|
||||
|
||||
## Polygon PositionManager V2 裁决核对
|
||||
|
||||
`venue-probe --inspect-position-resolution MARKET_JSON [EXPECTED]` 读取一条原始 Gamma V2 市场。Gamma 可能将 31 字节条件以尾部补零的 32 字节形式返回。通过两个 Position ID 核对条件和结果顺序后,按条件首字节从 PositionManager 查找 Binary 或 NegRisk 模块,并从该模块读取兑付权重。与 CTF 命令共用 Polygon RPC 配置。两次调用都绑定到同一最终确认区块,并在返回结果前复核区块哈希。[模块注册表](https://github.com/Polymarket/polymarket-v2-external/blob/main/docs/position-manager.md) · [Position ID 编码](https://github.com/Polymarket/polymarket-v2-external/blob/main/docs/position-ids.md) · [模块源码说明](https://github.com/Polymarket/polymarket-v2-external/blob/main/docs/modules.md)
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
actor U as 调用者
|
||||
participant P as venue-probe
|
||||
participant R as Polygon RPC
|
||||
participant M as PositionManager
|
||||
participant S as Binary 或 NegRisk 模块
|
||||
U->>P: inspect-position-resolution MARKET_JSON
|
||||
P->>P: 从两个 Position ID 核对条件与结果顺序
|
||||
P->>R: eth_chainId 与 finalized 区块
|
||||
R-->>P: 137、区块号和哈希
|
||||
P->>R: 在指定区块调用 moduleById
|
||||
R->>M: moduleById(module_id)
|
||||
M-->>R: 已注册的模块代理
|
||||
R-->>P: 模块代理地址
|
||||
P->>R: 在同一区块调用 getResult
|
||||
R->>S: getResult(condition_id)
|
||||
S-->>R: 空数组或两个权重
|
||||
R-->>P: 原始 ABI 字
|
||||
P->>R: 复核同一区块哈希
|
||||
R-->>P: 区块号和哈希
|
||||
P-->>U: 目录结果、合约、区块、原始 ABI 和兑付状态
|
||||
```
|
||||
|
||||
`venue-probe --replay-position-resolution crates/venue-probe/fixtures/live-position-resolutions.json first` 可重放生产 Binary 样本。两个 Polygon 节点在区块 `0x5df5912` 返回同一模块地址与兑付权重 `[1000000, 0]`,对应目录第一结果获胜。空权重数组报告为 `unresolved`。已兑付状态按数组值报告为 `first`、`second`、`split` 或 `weighted`。提供预期时,任何结果不符都会在输出报告后返回非零状态。NegRisk 的权重约束有离线回归用例,生产目录与链上结果的对应仍待验证。组合盘使用独立模块,预言机证明和本地账本入账也仍待覆盖。[双节点原始样本](fixtures/live-position-resolutions.json) · [合约部署地址](https://docs.polymarket.com/resources/contracts)
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
{
|
||||
"chain_id": 137,
|
||||
"block_number": "0x5df5831",
|
||||
"block_hash": "0xf36806915eb4a8aa5ecb85d411a3259c9a65b1f1af65049e30e5098a32f6b45c",
|
||||
"condition_id": "0xdf04a0495b0a16dbce386acdc16d9aed19784db9888be53d150354b83b7c18b1",
|
||||
"contract": "0x4D97DCd97eC945f40cF65F87097ACe5EA0476045",
|
||||
"sources": [
|
||||
"https://polygon.drpc.org",
|
||||
"https://polygon-bor-rpc.publicnode.com"
|
||||
],
|
||||
"outcome_slots": "0x0000000000000000000000000000000000000000000000000000000000000002",
|
||||
"denominator": "0x0000000000000000000000000000000000000000000000000000000000000001",
|
||||
"numerators": [
|
||||
"0x0000000000000000000000000000000000000000000000000000000000000000",
|
||||
"0x0000000000000000000000000000000000000000000000000000000000000001"
|
||||
],
|
||||
"observed_at_ms": 1796490278240
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
[
|
||||
{
|
||||
"chain_id": 137,
|
||||
"block_number": "0x5df5912",
|
||||
"block_hash": "0x7bee6030d9cd7c98bc7f6ae18f89c5a5b8c3a912993f558658224cf0a98a4533",
|
||||
"market": {
|
||||
"id": "7543472",
|
||||
"slug": "setkameua-anat-illia-2026-12-03",
|
||||
"version": "v2",
|
||||
"conditionId": "0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000",
|
||||
"positionIds": [
|
||||
"759916398134244316868652908232832573045153963965173623897622651599218278400",
|
||||
"759916398134244316868652908232832573045153963965173623897622651599218278401"
|
||||
],
|
||||
"outcomePrices": "[\"1\", \"0\"]",
|
||||
"outcomes": "[\"Nikolenko Anatolii\", \"Fokin Illia\"]"
|
||||
},
|
||||
"registry": "0x0000000000000000000000001000008dd9001b968442c1000017eae6e0da00ba",
|
||||
"result": "0x0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000f42400000000000000000000000000000000000000000000000000000000000000000",
|
||||
"sources": [
|
||||
"https://polygon.drpc.org",
|
||||
"https://polygon-bor-rpc.publicnode.com"
|
||||
],
|
||||
"observed_at_ms": 1796490613542
|
||||
}
|
||||
]
|
||||
@@ -1,221 +0,0 @@
|
||||
use crate::polygon_rpc::{hex_data, quantity, word, FinalizedRpc, POLYGON_CHAIN_ID};
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use reqwest::blocking::Client;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
const CTF: &str = "0x4D97DCd97eC945f40cF65F87097ACe5EA0476045";
|
||||
// First four bytes of Keccak-256 of the public ABI signatures.
|
||||
const OUTCOME_SLOTS: &str = "d42dc0c2"; // getOutcomeSlotCount(bytes32)
|
||||
const PAYOUT_DENOMINATOR: &str = "dd34de67"; // payoutDenominator(bytes32)
|
||||
const PAYOUT_NUMERATOR: &str = "0504c814"; // payoutNumerators(bytes32,uint256)
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
struct Observation {
|
||||
chain_id: u64,
|
||||
block_number: String,
|
||||
block_hash: String,
|
||||
contract: String,
|
||||
condition_id: String,
|
||||
outcome_slots: String,
|
||||
denominator: String,
|
||||
numerators: Option<[String; 2]>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
observed_at_ms: Option<u64>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
sources: Vec<String>,
|
||||
}
|
||||
|
||||
fn add(a: [u8; 32], b: [u8; 32]) -> Result<[u8; 32]> {
|
||||
let mut result = [0; 32];
|
||||
let mut carry = 0;
|
||||
for i in (0..32).rev() {
|
||||
let sum = u16::from(a[i]) + u16::from(b[i]) + carry;
|
||||
result[i] = sum as u8;
|
||||
carry = sum >> 8;
|
||||
}
|
||||
ensure!(carry == 0, "CTF payout weights overflow uint256");
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
fn decimal(word: [u8; 32]) -> String {
|
||||
let mut digits = vec![0_u8];
|
||||
for byte in word {
|
||||
let mut carry = u16::from(byte);
|
||||
for digit in &mut digits {
|
||||
let n = u16::from(*digit) * 256 + carry;
|
||||
*digit = (n % 10) as u8;
|
||||
carry = n / 10;
|
||||
}
|
||||
while carry > 0 {
|
||||
digits.push((carry % 10) as u8);
|
||||
carry /= 10;
|
||||
}
|
||||
}
|
||||
digits
|
||||
.into_iter()
|
||||
.rev()
|
||||
.map(|digit| char::from(b'0' + digit))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn audit(obs: Observation, expected: Option<&str>) -> Result<Value> {
|
||||
ensure!(
|
||||
obs.chain_id == POLYGON_CHAIN_ID && obs.contract.eq_ignore_ascii_case(CTF),
|
||||
"observation is not from the configured Polygon CTF deployment"
|
||||
);
|
||||
let block = quantity(&obs.block_number)?;
|
||||
hex_data(&obs.block_hash, 32)?;
|
||||
hex_data(&obs.condition_id, 32)?;
|
||||
let n = word(&obs.outcome_slots)?;
|
||||
let d = word(&obs.denominator)?;
|
||||
let zero = [0; 32];
|
||||
let mut two = [0; 32];
|
||||
two[31] = 2;
|
||||
let (status, numerators) = match (n, obs.numerators.as_ref()) {
|
||||
(n, None) if n == zero && d == zero => ("unprepared", None),
|
||||
(n, Some(values)) if n == two => {
|
||||
let a = word(&values[0])?;
|
||||
let b = word(&values[1])?;
|
||||
ensure!(add(a, b)? == d, "CTF payout sum does not match denominator");
|
||||
let status = if d == zero {
|
||||
"unresolved"
|
||||
} else if a == zero {
|
||||
"second"
|
||||
} else if b == zero {
|
||||
"first"
|
||||
} else if a == b {
|
||||
"split"
|
||||
} else {
|
||||
"weighted"
|
||||
};
|
||||
(status, Some([decimal(a), decimal(b)]))
|
||||
}
|
||||
_ => anyhow::bail!("observation is not an unprepared or binary CTF condition"),
|
||||
};
|
||||
if let Some(expected) = expected {
|
||||
ensure!(
|
||||
matches!(
|
||||
expected,
|
||||
"unprepared" | "unresolved" | "first" | "second" | "split" | "weighted"
|
||||
),
|
||||
"invalid expected CTF payout status"
|
||||
);
|
||||
}
|
||||
Ok(
|
||||
json!({"observation":obs,"block":block,"status":status,"payout_denominator":decimal(d),
|
||||
"payout_numerators":numerators,"expected":expected,"matches":expected.map(|v|v==status)}),
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn inspect(client: &Client, condition: &str, expected: Option<&str>) -> Result<Value> {
|
||||
let cid = hex_data(condition, 32)?;
|
||||
let block = FinalizedRpc::connect(client)?;
|
||||
let slots = block.call(CTF, &format!("0x{OUTCOME_SLOTS}{cid}"))?;
|
||||
let slot_word = word(&slots)?;
|
||||
let mut two = [0; 32];
|
||||
two[31] = 2;
|
||||
ensure!(
|
||||
slot_word == [0; 32] || slot_word == two,
|
||||
"CTF condition has a nonbinary outcome count"
|
||||
);
|
||||
let denominator = block.call(CTF, &format!("0x{PAYOUT_DENOMINATOR}{cid}"))?;
|
||||
let numerators = if slot_word == two {
|
||||
Some([
|
||||
block.call(CTF, &format!("0x{PAYOUT_NUMERATOR}{cid}{:064x}", 0))?,
|
||||
block.call(CTF, &format!("0x{PAYOUT_NUMERATOR}{cid}{:064x}", 1))?,
|
||||
])
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let observed_at_ms = block.confirm()?;
|
||||
audit(
|
||||
Observation {
|
||||
chain_id: POLYGON_CHAIN_ID,
|
||||
block_number: block.number,
|
||||
block_hash: block.hash,
|
||||
contract: CTF.to_owned(),
|
||||
condition_id: condition.to_ascii_lowercase(),
|
||||
outcome_slots: slots,
|
||||
denominator,
|
||||
numerators,
|
||||
observed_at_ms: Some(observed_at_ms),
|
||||
sources: Vec::new(),
|
||||
},
|
||||
expected,
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn replay(file: &str, expected: Option<&str>) -> Result<Value> {
|
||||
let raw: Value = serde_json::from_reader(std::fs::File::open(file)?)?;
|
||||
let obs = serde_json::from_value(raw.get("observation").cloned().unwrap_or(raw))?;
|
||||
audit(obs, expected)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn fixture() -> Observation {
|
||||
serde_json::from_str(include_str!("../fixtures/live-ctf-resolution.json")).unwrap()
|
||||
}
|
||||
|
||||
fn abi(value: u64) -> String {
|
||||
format!("0x{value:064x}")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn captured_polymarket_ctf_paid_the_second_outcome() {
|
||||
let report = audit(fixture(), Some("second")).unwrap();
|
||||
assert_eq!(report["status"], "second");
|
||||
assert_eq!(report["payout_denominator"], "1");
|
||||
assert_eq!(report["payout_numerators"], json!(["0", "1"]));
|
||||
assert_eq!(report["matches"], true);
|
||||
assert_eq!(audit(fixture(), Some("first")).unwrap()["matches"], false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_split_and_invalid_payout_shapes_remain_distinct() {
|
||||
let mut obs = fixture();
|
||||
obs.outcome_slots = abi(0);
|
||||
obs.denominator = abi(0);
|
||||
obs.numerators = None;
|
||||
assert_eq!(audit(obs, None).unwrap()["status"], "unprepared");
|
||||
|
||||
let mut obs = fixture();
|
||||
obs.denominator = abi(0);
|
||||
obs.numerators = Some([abi(0), abi(0)]);
|
||||
assert_eq!(audit(obs, None).unwrap()["status"], "unresolved");
|
||||
|
||||
let mut obs = fixture();
|
||||
obs.denominator = abi(2);
|
||||
obs.numerators = Some([abi(1), abi(1)]);
|
||||
assert_eq!(audit(obs, Some("split")).unwrap()["status"], "split");
|
||||
|
||||
let mut obs = fixture();
|
||||
obs.denominator = abi(3);
|
||||
obs.numerators = Some([abi(1), abi(1)]);
|
||||
assert!(audit(obs, None).is_err());
|
||||
|
||||
let mut obs = fixture();
|
||||
obs.chain_id = 1;
|
||||
assert!(audit(obs, None).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uint256_payout_weights_do_not_round_or_wrap() {
|
||||
let max = format!("0x{}", "ff".repeat(32));
|
||||
let mut obs = fixture();
|
||||
obs.denominator = max.clone();
|
||||
obs.numerators = Some([max.clone(), abi(0)]);
|
||||
let report = audit(obs, None).unwrap();
|
||||
assert_eq!(
|
||||
report["payout_denominator"],
|
||||
"115792089237316195423570985008687907853269984665640564039457584007913129639935"
|
||||
);
|
||||
let mut obs = fixture();
|
||||
obs.denominator = abi(0);
|
||||
obs.numerators = Some([max, abi(1)]);
|
||||
assert!(audit(obs, None).is_err());
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,6 @@
|
||||
mod book_audit;
|
||||
mod books;
|
||||
mod catalog;
|
||||
mod ctf_resolution;
|
||||
mod polygon_rpc;
|
||||
mod position_resolution;
|
||||
mod price_check;
|
||||
mod probes;
|
||||
use anyhow::{ensure, Result};
|
||||
@@ -36,45 +33,7 @@ fn observe_book(client: &Client, url: reqwest::Url, token: &str) -> Result<()> {
|
||||
fn main() -> Result<()> {
|
||||
let args: Vec<_> = std::env::args().skip(1).collect();
|
||||
let usage =
|
||||
"usage: venue-probe [--compare-prices | --inspect-book TOKEN | --replay-book TOKEN FILE | --replay-market FILE | --inspect-resolution CONDITION [EXPECTED] | --replay-resolution FILE [EXPECTED] | --inspect-position-resolution MARKET_JSON [EXPECTED] | --replay-position-resolution FILE [EXPECTED]]";
|
||||
if let [mode, value, rest @ ..] = args.as_slice() {
|
||||
if matches!(
|
||||
mode.as_str(),
|
||||
"--inspect-resolution"
|
||||
| "--replay-resolution"
|
||||
| "--inspect-position-resolution"
|
||||
| "--replay-position-resolution"
|
||||
) {
|
||||
ensure!(rest.len() <= 1, usage);
|
||||
let expected = rest.first().map(String::as_str);
|
||||
let reports = match mode.as_str() {
|
||||
"--replay-resolution" => vec![ctf_resolution::replay(value, expected)?],
|
||||
"--replay-position-resolution" => position_resolution::replay(value, expected)?,
|
||||
_ => {
|
||||
let client = Client::builder()
|
||||
.connect_timeout(Duration::from_secs(5))
|
||||
.timeout(Duration::from_secs(10))
|
||||
.redirect(reqwest::redirect::Policy::none())
|
||||
.user_agent("eventbook-readonly-probe/0.1")
|
||||
.build()?;
|
||||
vec![if mode == "--inspect-resolution" {
|
||||
ctf_resolution::inspect(&client, value, expected)?
|
||||
} else {
|
||||
position_resolution::inspect(&client, value, expected)?
|
||||
}]
|
||||
}
|
||||
};
|
||||
for report in &reports {
|
||||
println!("{report}");
|
||||
}
|
||||
ensure!(
|
||||
reports.iter().all(|report| report["matches"] != false),
|
||||
"payout status differs from the expected result"
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
"usage: venue-probe [--compare-prices | --inspect-book TOKEN | --replay-book TOKEN FILE | --replay-market FILE]";
|
||||
if let [mode, file] = args.as_slice() {
|
||||
if mode == "--replay-market" {
|
||||
let raw = serde_json::from_reader(std::fs::File::open(file)?)?;
|
||||
|
||||
@@ -1,137 +0,0 @@
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use reqwest::{blocking::Client, Url};
|
||||
use serde_json::{json, Value};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
pub(crate) const POLYGON_CHAIN_ID: u64 = 137;
|
||||
const DEFAULT_RPC: &str = "https://polygon-bor-rpc.publicnode.com";
|
||||
|
||||
pub(crate) fn hex_data(raw: &str, bytes: usize) -> Result<&str> {
|
||||
let body = raw.strip_prefix("0x").context("invalid ABI hex prefix")?;
|
||||
ensure!(
|
||||
body.len() == 2 * bytes && body.bytes().all(|b| b.is_ascii_hexdigit()),
|
||||
"invalid ABI hex length or digit"
|
||||
);
|
||||
Ok(body)
|
||||
}
|
||||
|
||||
pub(crate) fn quantity(raw: &str) -> Result<u64> {
|
||||
let body = raw
|
||||
.strip_prefix("0x")
|
||||
.context("invalid RPC quantity prefix")?;
|
||||
ensure!(
|
||||
!body.is_empty()
|
||||
&& body.bytes().all(|b| b.is_ascii_hexdigit())
|
||||
&& (body.len() == 1 || !body.starts_with('0')),
|
||||
"invalid RPC quantity"
|
||||
);
|
||||
u64::from_str_radix(body, 16).context("invalid RPC quantity")
|
||||
}
|
||||
|
||||
pub(crate) fn word(raw: &str) -> Result<[u8; 32]> {
|
||||
let mut value = [0; 32];
|
||||
for (i, chunk) in hex_data(raw, 32)?.as_bytes().chunks_exact(2).enumerate() {
|
||||
value[i] = u8::from_str_radix(std::str::from_utf8(chunk)?, 16)?;
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn rpc(client: &Client, url: &Url, method: &str, params: Value) -> Result<Value> {
|
||||
let response: Value = client
|
||||
.post(url.clone())
|
||||
.json(&json!({
|
||||
"jsonrpc":"2.0","id":1,"method":method,"params":params
|
||||
}))
|
||||
.send()
|
||||
.map_err(reqwest::Error::without_url)?
|
||||
.error_for_status()
|
||||
.map_err(reqwest::Error::without_url)?
|
||||
.json()
|
||||
.map_err(reqwest::Error::without_url)?;
|
||||
ensure!(
|
||||
response["jsonrpc"] == "2.0" && response["id"] == 1,
|
||||
"invalid RPC envelope for {method}"
|
||||
);
|
||||
if let Some(error) = response.get("error") {
|
||||
anyhow::bail!("{method} RPC rejected the request (code {})", error["code"]);
|
||||
}
|
||||
response
|
||||
.get("result")
|
||||
.cloned()
|
||||
.with_context(|| format!("missing result for {method}"))
|
||||
}
|
||||
|
||||
pub(crate) struct FinalizedRpc<'a> {
|
||||
client: &'a Client,
|
||||
url: Url,
|
||||
pub number: String,
|
||||
pub hash: String,
|
||||
}
|
||||
|
||||
impl<'a> FinalizedRpc<'a> {
|
||||
pub(crate) fn connect(client: &'a Client) -> Result<Self> {
|
||||
let url = Url::parse(
|
||||
&std::env::var("EVENTBOOK_POLYGON_RPC_URL").unwrap_or_else(|_| DEFAULT_RPC.to_owned()),
|
||||
)
|
||||
.context("invalid Polygon RPC URL")?;
|
||||
ensure!(
|
||||
url.scheme() == "https" && url.username().is_empty() && url.password().is_none(),
|
||||
"Polygon RPC requires an HTTPS URL without embedded credentials"
|
||||
);
|
||||
let chain = rpc(client, &url, "eth_chainId", json!([]))?;
|
||||
let chain_id = quantity(chain.as_str().context("missing chain id")?)?;
|
||||
ensure!(chain_id == POLYGON_CHAIN_ID, "RPC is not Polygon mainnet");
|
||||
let anchor = rpc(
|
||||
client,
|
||||
&url,
|
||||
"eth_getBlockByNumber",
|
||||
json!(["finalized", false]),
|
||||
)?;
|
||||
let number = anchor["number"]
|
||||
.as_str()
|
||||
.context("RPC finalized block has no block number")?;
|
||||
quantity(number)?;
|
||||
let hash = anchor["hash"]
|
||||
.as_str()
|
||||
.context("RPC finalized block has no block hash")?;
|
||||
hex_data(hash, 32)?;
|
||||
Ok(Self {
|
||||
client,
|
||||
url,
|
||||
number: number.to_owned(),
|
||||
hash: hash.to_owned(),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn call(&self, contract: &str, data: &str) -> Result<String> {
|
||||
let value = rpc(
|
||||
self.client,
|
||||
&self.url,
|
||||
"eth_call",
|
||||
json!([{"to":contract,"data":data},self.number]),
|
||||
)?;
|
||||
value
|
||||
.as_str()
|
||||
.map(str::to_owned)
|
||||
.context("invalid eth_call ABI result")
|
||||
}
|
||||
|
||||
pub(crate) fn confirm(&self) -> Result<u64> {
|
||||
// Providers may lack EIP-1898 support. Read the finalized block number,
|
||||
// then verify its hash again before accepting any of the calls.
|
||||
let current = rpc(
|
||||
self.client,
|
||||
&self.url,
|
||||
"eth_getBlockByNumber",
|
||||
json!([self.number, false]),
|
||||
)?;
|
||||
ensure!(
|
||||
current["hash"] == self.hash && current["number"] == self.number,
|
||||
"RPC block changed during reads"
|
||||
);
|
||||
Ok(SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)?
|
||||
.as_millis()
|
||||
.try_into()?)
|
||||
}
|
||||
}
|
||||
@@ -1,274 +0,0 @@
|
||||
use crate::{
|
||||
catalog::Market,
|
||||
polygon_rpc::{hex_data, quantity, word, FinalizedRpc, POLYGON_CHAIN_ID},
|
||||
};
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use reqwest::blocking::Client;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
const POSITION_MANAGER: &str = "0x006F54F7f9A22e0000CC2AB60031000000ae9fEF";
|
||||
// moduleById(uint256), getResult(bytes31)
|
||||
const MODULE_BY_ID: &str = "4d51cdf1";
|
||||
const GET_RESULT: &str = "e4939c77";
|
||||
const DENOMINATOR: u64 = 1_000_000;
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
struct Observation {
|
||||
chain_id: u64,
|
||||
block_number: String,
|
||||
block_hash: String,
|
||||
market: Value,
|
||||
registry: String,
|
||||
result: String,
|
||||
observed_at_ms: u64,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
sources: Vec<String>,
|
||||
}
|
||||
|
||||
fn market_binding(raw: &Value) -> Result<(Market, u8, &'static str)> {
|
||||
ensure!(
|
||||
raw["version"] == "v2",
|
||||
"PositionManager probe requires a V2 Gamma market"
|
||||
);
|
||||
let market = Market::parse(raw)?;
|
||||
let cid = market.report["position_condition_id"]
|
||||
.as_str()
|
||||
.context("missing encoded condition")?;
|
||||
let hex = hex_data(cid, 31)?;
|
||||
let gamma_condition = market.report["condition_id"]
|
||||
.as_str()
|
||||
.context("missing Gamma condition ID")?;
|
||||
// Gamma can publish a bytes32 representation of the left-aligned bytes31.
|
||||
let gamma_condition = match gamma_condition.len() {
|
||||
64 => hex_data(gamma_condition, 31)?,
|
||||
66 => hex_data(gamma_condition, 32)?
|
||||
.strip_suffix("00")
|
||||
.context("invalid Gamma condition ID padding")?,
|
||||
_ => anyhow::bail!("invalid Gamma condition ID length"),
|
||||
};
|
||||
ensure!(
|
||||
gamma_condition.eq_ignore_ascii_case(hex),
|
||||
"Gamma condition ID disagrees with the Position IDs"
|
||||
);
|
||||
let (module, name) = match &hex[..2] {
|
||||
"01" => (1, "BinaryModule"),
|
||||
"02" => (2, "NegRiskModule"),
|
||||
_ => anyhow::bail!("PositionManager probe requires a Binary or NegRisk condition"),
|
||||
};
|
||||
Ok((market, module, name))
|
||||
}
|
||||
|
||||
fn module_address(registry: &str, module: u8) -> Result<String> {
|
||||
let raw = hex_data(registry, 32)?;
|
||||
ensure!(
|
||||
raw[..24].bytes().all(|digit| digit == b'0'),
|
||||
"invalid module registry address padding"
|
||||
);
|
||||
let address = format!("0x{}", &raw[24..]);
|
||||
let expected = match module {
|
||||
1 => "0x1000008dD9001B968442c1000017eaE6E0dA00Ba",
|
||||
2 => "0x200000900045e3B6259600682756002200028933",
|
||||
_ => anyhow::bail!("unsupported PositionManager module"),
|
||||
};
|
||||
ensure!(
|
||||
expected.eq_ignore_ascii_case(&address),
|
||||
"PositionManager registry differs from the published deployment"
|
||||
);
|
||||
Ok(address)
|
||||
}
|
||||
|
||||
fn uint(word_hex: &str) -> Result<u64> {
|
||||
let data = word(&format!("0x{word_hex}"))?;
|
||||
ensure!(
|
||||
data[..24].iter().all(|&byte| byte == 0),
|
||||
"unexpected ABI integer overflow"
|
||||
);
|
||||
Ok(u64::from_be_bytes(data[24..].try_into()?))
|
||||
}
|
||||
|
||||
fn result(raw: &str, module: u8) -> Result<Option<[u64; 2]>> {
|
||||
let bytes = match raw.len() {
|
||||
130 => 64,
|
||||
258 => 128,
|
||||
_ => anyhow::bail!("getResult must return an empty or two-element ABI array"),
|
||||
};
|
||||
let data = hex_data(raw, bytes)?;
|
||||
ensure!(uint(&data[..64])? == 32, "invalid getResult array offset");
|
||||
let length = uint(&data[64..128])?;
|
||||
if bytes == 64 {
|
||||
ensure!(length == 0, "invalid empty getResult array");
|
||||
return Ok(None);
|
||||
}
|
||||
ensure!(length == 2, "invalid getResult array length");
|
||||
let a = uint(&data[128..192])?;
|
||||
let b = uint(&data[192..256])?;
|
||||
ensure!(
|
||||
a.checked_add(b) == Some(DENOMINATOR),
|
||||
"invalid V2 payout denominator"
|
||||
);
|
||||
ensure!(module != 2 || a == 0 || b == 0, "nonbinary NegRisk payout");
|
||||
Ok(Some([a, b]))
|
||||
}
|
||||
|
||||
fn audit(obs: Observation, expected: Option<&str>) -> Result<Value> {
|
||||
ensure!(
|
||||
obs.chain_id == POLYGON_CHAIN_ID,
|
||||
"observation is not from Polygon mainnet"
|
||||
);
|
||||
let block = quantity(&obs.block_number)?;
|
||||
hex_data(&obs.block_hash, 32)?;
|
||||
let (market, module, name) = market_binding(&obs.market)?;
|
||||
let target = module_address(&obs.registry, module)?;
|
||||
let weights = result(&obs.result, module)?;
|
||||
let status = match weights {
|
||||
None => "unresolved",
|
||||
Some([0, _]) => "second",
|
||||
Some([_, 0]) => "first",
|
||||
Some([a, b]) if a == b => "split",
|
||||
Some(_) => "weighted",
|
||||
};
|
||||
if let Some(value) = expected {
|
||||
ensure!(
|
||||
matches!(
|
||||
value,
|
||||
"unresolved" | "first" | "second" | "split" | "weighted"
|
||||
),
|
||||
"invalid expected V2 payout status"
|
||||
);
|
||||
}
|
||||
Ok(
|
||||
json!({"observation":obs,"block":block,"position_manager":POSITION_MANAGER,"module":name,
|
||||
"module_id":module,"module_contract":target,
|
||||
"position_condition_id":market.report["position_condition_id"],
|
||||
"outcomes":market.report["outcomes"],"status":status,
|
||||
"payout_denominator":weights.map(|_|DENOMINATOR.to_string()),
|
||||
"payout_numerators":weights.map(|weights|weights.map(|v|v.to_string())),
|
||||
"expected":expected,"matches":expected.map(|v|v==status)}),
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn inspect(client: &Client, file: &str, expected: Option<&str>) -> Result<Value> {
|
||||
let market: Value = serde_json::from_reader(std::fs::File::open(file)?)?;
|
||||
let (binding, module, _) = market_binding(&market)?;
|
||||
let cid = hex_data(
|
||||
binding.report["position_condition_id"]
|
||||
.as_str()
|
||||
.context("missing condition")?,
|
||||
31,
|
||||
)?;
|
||||
let block = FinalizedRpc::connect(client)?;
|
||||
let registry = block.call(POSITION_MANAGER, &format!("0x{MODULE_BY_ID}{module:064x}"))?;
|
||||
let address = module_address(®istry, module)?;
|
||||
// Solidity bytes31 is left-aligned in its ABI word. The final byte is padding.
|
||||
let result = block.call(&address, &format!("0x{GET_RESULT}{cid}00"))?;
|
||||
let observed_at_ms = block.confirm()?;
|
||||
let market = Value::Object(
|
||||
[
|
||||
"id",
|
||||
"slug",
|
||||
"version",
|
||||
"conditionId",
|
||||
"positionIds",
|
||||
"outcomes",
|
||||
"outcomePrices",
|
||||
]
|
||||
.into_iter()
|
||||
.filter_map(|key| market.get(key).map(|value| (key.to_owned(), value.clone())))
|
||||
.collect(),
|
||||
);
|
||||
audit(
|
||||
Observation {
|
||||
chain_id: POLYGON_CHAIN_ID,
|
||||
block_number: block.number,
|
||||
block_hash: block.hash,
|
||||
market,
|
||||
registry,
|
||||
result,
|
||||
observed_at_ms,
|
||||
sources: Vec::new(),
|
||||
},
|
||||
expected,
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn replay(file: &str, expected: Option<&str>) -> Result<Vec<Value>> {
|
||||
let raw: Value = serde_json::from_reader(std::fs::File::open(file)?)?;
|
||||
let rows = match raw {
|
||||
Value::Array(rows) => rows,
|
||||
value => vec![value],
|
||||
};
|
||||
ensure!(!rows.is_empty(), "no V2 observations in file");
|
||||
rows.into_iter()
|
||||
.map(|row| {
|
||||
let obs = serde_json::from_value(row.get("observation").cloned().unwrap_or(row))?;
|
||||
audit(obs, expected)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn abi(values: &[u64]) -> String {
|
||||
let mut encoded = String::from("0x");
|
||||
for value in values {
|
||||
encoded.push_str(&format!("{value:064x}"));
|
||||
}
|
||||
encoded
|
||||
}
|
||||
|
||||
const LIVE: &str = include_str!("../fixtures/live-position-resolutions.json");
|
||||
|
||||
#[test]
|
||||
fn replay_binary_observation_preserves_gamma_outcome_order() -> Result<()> {
|
||||
let [obs]: [Observation; 1] = serde_json::from_str(LIVE)?;
|
||||
let report = audit(obs, Some("first"))?;
|
||||
assert_eq!(report["status"], "first");
|
||||
assert_eq!(report["matches"], true);
|
||||
assert_eq!(report["outcomes"][0]["label"], "Nikolenko Anatolii");
|
||||
assert_eq!(report["payout_numerators"], json!(["1000000", "0"]));
|
||||
assert_eq!(report["payout_denominator"], "1000000");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_mismatched_condition_and_unexpected_module_address() -> Result<()> {
|
||||
let [mut obs]: [Observation; 1] = serde_json::from_str(LIVE)?;
|
||||
assert!(module_address(&obs.registry, 2).is_err());
|
||||
let condition = obs.market["conditionId"].as_str().unwrap();
|
||||
let unpadded = condition.strip_suffix("00").unwrap().to_owned();
|
||||
let wrong_padding = format!("{unpadded}01");
|
||||
obs.market["conditionId"] = json!(unpadded);
|
||||
assert!(market_binding(&obs.market).is_ok());
|
||||
obs.market["conditionId"] = json!(wrong_padding);
|
||||
assert!(market_binding(&obs.market).is_err());
|
||||
obs.market["conditionId"] = json!(format!("0x02{}", "00".repeat(30)));
|
||||
assert!(market_binding(&obs.market).is_err());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_unresolved_and_resolved_weights_and_rejects_malformed_abi() -> Result<()> {
|
||||
assert_eq!(result(&abi(&[32, 0]), 1)?, None);
|
||||
assert_eq!(
|
||||
result(&abi(&[32, 2, 0, 1_000_000]), 2)?,
|
||||
Some([0, 1_000_000])
|
||||
);
|
||||
let fractional = abi(&[32, 2, 700_000, 300_000]);
|
||||
assert_eq!(result(&fractional, 1)?, Some([700_000, 300_000]));
|
||||
assert!(result(&fractional, 2).is_err());
|
||||
for bad in [
|
||||
abi(&[64, 0]),
|
||||
abi(&[32, 2]),
|
||||
abi(&[32, 1, 0, 1_000_000]),
|
||||
abi(&[32, 2, 0, 999_999]),
|
||||
abi(&[32, 2, 0, 1_000_000, 0]),
|
||||
format!("0x1{}", &fractional[3..]),
|
||||
] {
|
||||
assert!(result(&bad, 1).is_err());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
{"op":"upsert_tag","id":"tag-tech","tag_id":101,"label":"Technology","slug":"technology","force_show":true}
|
||||
{"op":"upsert_tag","id":"tag-threshold","tag_id":102,"label":"Price thresholds","slug":"price-thresholds","is_carousel":false}
|
||||
{"op":"set_tags","id":"tag-nvda","kind":"event","target":"nvda-2027","tag_ids":[101,102]}
|
||||
{"op":"set_tags","id":"tag-nvda-market","kind":"market","target":"nvda-200","tag_ids":[102]}
|
||||
{"op":"upsert_tag","id":"tag-archives","tag_id":103,"label":"Archived technology","slug":"archived-technology"}
|
||||
{"op":"upsert_tag","id":"tag-depth","tag_id":104,"label":"Semi-conductors","slug":"semi-conductors"}
|
||||
{"op":"event","id":"create-tag-archive","event":"tag-archive","slug":"tag-archive","title":"Archive fixture","category":"technology"}
|
||||
{"op":"list","id":"create-archived-tech","market":"archived-tech","rules":"Archive fixture.","listing":{"event":"tag-archive","question":"Archive fixture?","yes_label":"YES","no_label":"NO","source":"fixture","resolver":"operator","rules_version":1,"group_order":1}}
|
||||
{"op":"close","id":"close-archived-tech","market":"archived-tech"}
|
||||
{"op":"set_tags","id":"tag-archive-event","kind":"event","target":"tag-archive","tag_ids":[103]}
|
||||
{"op":"set_tags","id":"tag-depth-market","kind":"market","target":"nvda-300","tag_ids":[104]}
|
||||
{"op":"set_related_tags","id":"tag-technology-links","tag_id":101,"links":[{"id":9002,"related_tag_id":102,"rank":2},{"id":9001,"related_tag_id":103,"rank":1}]}
|
||||
{"op":"set_related_tags","id":"tag-threshold-links","tag_id":102,"links":[{"id":9003,"related_tag_id":104,"rank":1}]}
|
||||
@@ -417,14 +417,6 @@ fidelity 以分钟为单位;省略或不大于零时按 1 分钟处理。相
|
||||
|
||||
官方 OpenAPI 给出的 condition 和 event 查询按条件返回,question 查询以问题为单位。两种查询的更新时间分别是 UTC 时间和 Unix 秒数字符串。本地使用记录下来的提案、争议和兑付时间。早期数据库缺失的时间保留为空。本地未接入链上事件,交易哈希和日志序号保留空串,区块号、报告人及投票截止估计省略。new_version_q 采用 OpenAPI 对规则修订的定义,本地原始规则不可改。旧版官方子图在 QuestionInitialized 上直接置 true,这一点存在口径差异。提案到期后需按模拟系统的最终确认流程兑付。本次按规范、合约及子图核对,生产端点没有取得可重放的响应。[官方接口](https://docs.polymarket.com/api-reference/markets/get-resolution-state) · [OpenAPI](https://data-api.polymarket.com/v2/openapi.json) · [UMA 适配器](https://github.com/Polymarket/uma-ctf-adapter/blob/main/src/UmaCtfAdapter.sol) · [裁决子图](https://github.com/Polymarket/resolution-subgraph/blob/main/src/uma-ctf-adapter.ts)
|
||||
|
||||
### CTF 链上兑付核对
|
||||
|
||||
从已封盘的 CS2 市场目录读取 `conditionId` 和结果顺序,在两个 Polygon 节点用同一最终确认区块 `0x5df5831` 读取 CTF。结果数为 2,按目录顺序的兑付分子为 [0,1],分母为 1,对应 Under 胜出。实测 ABI 字可由 `venue-probe --replay-resolution` 离线核对,也可指定 `second` 作为预期。此次取样验证了该 CTF 条件,真实预言机证明及链上同步入账仍待覆盖。[生产目录记录](examples/public-closed-chart-history.json) · [双节点链上记录](../crates/venue-probe/fixtures/live-ctf-resolution.json)
|
||||
|
||||
### PositionManager V2 链上兑付核对
|
||||
|
||||
V2 市场以两项 Position ID 共享的高 31 字节表示条件,首字节标记模块。探针用该模块编号查询 PositionManager 注册表,再从模块读取按目录顺序排列的兑付权重。生产 Binary 样本在两个 Polygon 节点的最终确认区块 `0x5df5912` 均返回 `[1000000, 0]`,与 Gamma 第一结果获胜一致。两个权重的分母固定为 100 万,空数组表示合约当前没有可读取的结果。NegRisk 的二元约束有离线用例,仍缺少生产目录关联样本。组合盘兑付、独立链上状态证明和同步入账仍待覆盖。[探针时序与重放](../crates/venue-probe/README.md#polygon-positionmanager-v2-裁决核对) · [双节点记录](../crates/venue-probe/fixtures/live-position-resolutions.json) · [官方 V2 模块文档](https://github.com/Polymarket/polymarket-v2-external/blob/main/docs/modules.md)
|
||||
|
||||
### Data API 账户持仓价值
|
||||
|
||||
官方 `GET /v2/value` 要求传 user,可选最多 20 个不同 condition。结果是 data 对象,内含 proxy_wallet 和四位小数精度的美元金额。一个无持仓的钱包值为零。官方总额还包括未终结组合的成本基础,指定 condition 时仅统计选中的单盘。资金余额不计入持仓价值。[官方 OpenAPI](https://data-api.polymarket.com/v2/openapi.json)
|
||||
@@ -479,3 +471,15 @@ SDK 使用 `GET /neg-risk?token_id=…`,也可以从已缓存的 CLOB 市场
|
||||
### 已裁决市场的公开盘口
|
||||
|
||||
对电竞、乒乓球和 SOL 涨跌盘的六个已裁决结果单查 /book,全部返回 404。批量 /books 和 /prices 忽略已裁决资产,混合批次保留可用资产。中点和价差多数同样返回 404,但一个 V2 市场的两侧分别仍能读到价差 1 或中点 0.5。Eventbook 对已裁决结果统一省略四种公开行情,保留内部快照供交易状态和回放。封盘待裁决阶段、外场淘汰时延和例外是否由服务缓存触发仍待验证。[生产响应](examples/public-resolved-books.json)
|
||||
|
||||
|
||||
### Gamma 标签及目录导航
|
||||
|
||||
生产样本中,事件 30828 和子盘 559651 的标签专用端点均返回五个标签,分别是 103715、100265、101970、366、102458,两个端点的顺序不同。`GET /tags/slug/geopolitics` 返回字符串 ID `100265`。事件详情内带标签。市场详情默认省略标签,市场列表使用 `include_tag=true` 时可展开。不存在的事件或市场在专用标签端点返回 404,不存在的事件筛选标签返回空数组。生产 `/tags?limit=0` 的样本返回默认的 50 项。[事件标签](https://gamma-api.polymarket.com/events/30828/tags) · [市场标签](https://gamma-api.polymarket.com/markets/559651/tags) · [标签列表规范](https://docs.polymarket.com/api-reference/tags/list-tags)
|
||||
|
||||
本地分别为事件和市场登记标签及显示顺序。先重放[主题样例](examples/topic.jsonl),再重放[标签样例](examples/gamma-tags.jsonl)。`GET /events?tag_id=101&tag_slug=price-thresholds` 返回 NVIDIA 主题,追加 `exclude_tag_id=102` 后返回空数组。`GET /markets?tag_id=102&include_tag=true` 仅返回 nvda-200 和它的标签。错误的标签编号使关联写入整体回滚。模板标签、生产默认排序与父子标签写入规则仍待验证。
|
||||
|
||||
|
||||
生产 Sports 的 ID 和 slug 入口返回同一组关系,第一项指向 450,查询 450 的反向入口返回空数组。Geopolitics 有 19 个相关标签,默认的 `omit_empty=true` 保留 17 个,`status=closed` 或 `status=all` 均保留 19 个。生产事件 10083 能通过 `tag_id=100265&related_tags=true` 找到,追加 `tag_slug=geopolitics` 后无结果。生产盘口 677218 没有 Sports 标签 1,但有直接相关标签 100639,并能通过 `tag_id=1&related_tags=true` 找到。[关系查询](https://docs.polymarket.com/api-reference/tags/get-related-tags-relationships-by-tag-id) · [相关标签详情](https://docs.polymarket.com/api-reference/tags/get-tags-related-to-a-tag-id)
|
||||
|
||||
本地 `set_related_tags` 在一个事务内替换指定标签的全部出边。`/related-tags` 返回关系和排名,加 `/tags` 返回标签详情。按 ID 或 slug 查询均可。空关联或不存在的根标签返回空数组。开启 `omit_empty` 后,默认只保留与开放赛事有关联的标签,再按 `status` 可改查已关闭或所有赛事。数字标签扩展只走直接关系,slug 与排除规则继续精确匹配。样例中 Technology 指向 Price thresholds,后者指向 Semi-conductors。按 Technology 扩展查市场只返回 nvda-200。更深层的生产关系、空标签的生产索引延迟和 keyset 列表仍待核对。
|
||||
|
||||
Reference in New Issue
Block a user