Compare commits

..

1 Commits

Author SHA1 Message Date
codex-bot 39656fffd2 Serve Gamma public directory search and opt-in public profiles 2026-12-05 22:17:34 +08:00
12 changed files with 552 additions and 75 deletions
+17 -3
View File
@@ -8,6 +8,7 @@
```mermaid
flowchart LR
market_http["src/market_http.rs"] -.->|执行公开目录搜索| api
main["src/main.rs"] -->|把标准输入输出交给 serve| stream["src/stream.rs"]
main -.->|打开数据库| api["exchange crate"]
stream -.->|执行命令| api
@@ -338,7 +339,22 @@ sequenceDiagram
H-->>C: 200 data 数组,未找到返回空数组
```
### 查询持仓价值
### Gamma 搜索
重放[搜索样例](../../docs/examples/gamma-search.jsonl)后,`GET /public-search?q=North+Cup&limit_per_type=1&page=1&search_profiles=true` 返回第一场比赛及公开资料。把页码改为 2 可取下一场比赛。以「前十分钟」为关键词,会从盘口问题找到父事件。加 `optimized=true` 获取精简响应。
```mermaid
sequenceDiagram
actor C as 客户端
participant H as market_http.rs
participant E as Exchange
C->>H: GET /public-search,传关键词和页码
H->>E: 解码参数并查询公开目录
E-->>H: 当页事件和盘口,按需附上公开资料
H-->>C: JSON 搜索结果
```
## 查询持仓价值
`GET /v2/value?user=alice&condition=e` 返回该账户在市场 e 的持仓价值,单位为模拟美元。使用已登记的本地账户名或 20 字节钱包地址。省略 condition 查询所有已持有市场。无持仓的钱包返回零,仅有现金的账户也返回零。
@@ -425,5 +441,3 @@ sequenceDiagram
E-->>H: true
H-->>C: 200,neg_risk 为真
```
批量盘口 POST /books 的响应使用 asset_id 对应请求。重复资产只返回一份,单批最多 500 个不同标识。
+95 -46
View File
@@ -3,7 +3,7 @@ use exchange::{Exchange, HistoryError};
use percent_encoding::percent_decode_str;
use serde::Deserialize;
use serde_json::{json, Value};
use std::{collections::HashSet, io::Read, net::TcpListener, sync::Mutex, thread};
use std::{io::Read, net::TcpListener, sync::Mutex, thread};
use tiny_http::{Header, Method, Request, Response, Server};
const MAX_BOOKS: usize = 500;
@@ -18,15 +18,20 @@ struct BookParam {
_side: Option<exchange::PriceSide>,
}
#[derive(Deserialize)]
struct BatchBookParam {
token_id: Option<String>,
side: Option<String>,
}
type Reply = std::result::Result<Value, (u16, &'static str)>;
fn book_response(engine: &Mutex<Exchange>, tokens: Vec<String>, 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,
if single {
"Invalid token id"
} else {
"Invalid payload"
},
));
}
let tokens = params.into_iter().map(|p| p.token_id).collect::<Vec<_>>();
let mut books = engine
.lock()
.map_err(|_| (500, "error getting the orderbook"))?
@@ -320,6 +325,29 @@ fn clarifications(engine: &Mutex<Exchange>, query: &str) -> Reply {
fn respond(mut req: Request, engine: &Mutex<Exchange>) -> std::io::Result<()> {
let (path, params) = req.url().split_once('?').unwrap_or((req.url(), ""));
if path == "/public-search" {
if req.method() != &Method::Get {
return send(req, 405, json!({"error":"Method not allowed"}), Some("GET"));
}
let result = serde_urlencoded::from_str::<Vec<(String, String)>>(params)
.map_err(|_| exchange::MarketDataError::Invalid("Invalid search query".into()))
.and_then(|fields| {
engine
.lock()
.map_err(|_| exchange::MarketDataError::Unavailable)?
.gamma_search(&fields)
});
let (status, body) = match result {
Ok(value) => (200, value),
Err(exchange::MarketDataError::Invalid(error)) => {
(422, json!({"type":"validation error","error":error}))
}
Err(exchange::MarketDataError::Unavailable) => {
(500, json!({"error":"Search unavailable"}))
}
};
return send(req, status, body, None);
}
let mut allow = None;
if req.method() == &Method::Get
&& matches!(
@@ -434,36 +462,10 @@ fn respond(mut req: Request, engine: &Mutex<Exchange>) -> std::io::Result<()> {
(&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| {
if p.token_id.trim().is_empty() {
return Err((400, "Invalid token id"));
}
book_response(engine, vec![p.token_id], true)
}),
(&Method::Post, "/books") => batch_params::<BatchBookParam>(&mut req).and_then(|rows| {
let mut seen = HashSet::new();
let mut tokens = Vec::new();
for row in &rows {
let Some(token) = row.token_id.as_deref().filter(|id| !id.trim().is_empty()) else {
continue;
};
if let Some(side) = row.side.as_deref() {
if !side.is_empty()
&& !side.eq_ignore_ascii_case("BUY")
&& !side.eq_ignore_ascii_case("SELL")
{
continue;
}
}
if seen.insert(token) {
if seen.len() > MAX_BOOKS {
return Err((400, "Payload exceeds the limit"));
}
tokens.push(token.to_owned());
}
}
book_response(engine, tokens, false)
}),
.and_then(|p| query(engine, vec![p], true)),
(&Method::Post, "/books") => {
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, vec![p.token_id], true)),
@@ -607,6 +609,48 @@ mod tests {
#[test]
fn socket_serves_single_and_batch_books_and_rejects_invalid_requests() {
let mut db = Exchange::open(":memory:").unwrap();
for line in include_str!("../../../docs/examples/gamma-search.jsonl").lines() {
db.execute(serde_json::from_str(line).unwrap()).unwrap();
}
let search_fields = |raw| serde_urlencoded::from_str::<Vec<(String, String)>>(raw).unwrap();
let search_first = db
.gamma_search(&search_fields(
"q=North+Cup&limit_per_type=1&search_profiles=true",
))
.unwrap();
assert_eq!(search_first["events"][0]["slug"], "north-cup");
assert_eq!(
search_first["events"][0]["markets"][0]["conditionId"],
"north-cup-goals"
);
assert_eq!(search_first["profiles"][0]["name"], "North Cup analyst");
assert_eq!(
search_first["pagination"],
json!({"hasMore":true,"totalResults":2})
);
let second_search = db
.gamma_search(&search_fields(
"q=North+Cup&limit_per_type=1&page=2&optimized=true",
))
.unwrap();
assert_eq!(second_search["events"][0]["slug"], "north-cup-archive");
assert_eq!(second_search["hasMore"], false);
assert!(second_search.get("pagination").is_none());
assert!(second_search["events"][0]["markets"][0]
.get("conditionId")
.is_none());
let visible_profile = db
.gamma_search(&search_fields("q=Pitch+observer&search_profiles=true"))
.unwrap();
assert!(visible_profile["profiles"][0].get("name").is_none());
assert_eq!(
visible_profile["profiles"][0]["displayUsernamePublic"],
false
);
let by_market_text = db
.gamma_search(&search_fields("q=%E5%89%8D%E5%8D%81%E5%88%86%E9%92%9F"))
.unwrap();
assert_eq!(by_market_text["events"][0]["slug"], "north-cup");
let market = "map 2:胜者";
db.execute(
json!({"op":"list","id":"list","market":market,"rules":"simulated","tick_size":"0.01"}),
@@ -713,6 +757,14 @@ mod tests {
assert_eq!(quoted["outcomePrices"], r#"["0.4","0.6"]"#);
let empty_trades = json!({"data":[],"pagination":{"limit":100,"offset":0,"has_more":false,"next_cursor":null}});
let cases = [
("GET","/public-search?q=North+Cup&limit_per_type=1&search_profiles=true",String::new(),200,Some(search_first)),
("GET","/public-search?q=North+Cup&limit_per_type=1&page=2&optimized=true",String::new(),200,Some(second_search)),
("GET","/public-search?q=Pitch+observer&search_profiles=true",String::new(),200,Some(visible_profile)),
("GET","/public-search?q=Undisclosed+analyst&search_profiles=true",String::new(),200,Some(json!({"pagination":{"hasMore":false,"totalResults":0}}))),
("GET","/public-search?q=%E5%89%8D%E5%8D%81%E5%88%86%E9%92%9F",String::new(),200,Some(by_market_text)),
("GET","/public-search",String::new(),422,Some(json!({"type":"validation error","error":"query argument \"q\": empty"}))),
("GET","/public-search?q=north&page=101",String::new(),422,None),
("POST","/public-search",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}))),
@@ -851,7 +903,7 @@ mod tests {
"/books",
mixed.to_string(),
200,
Some(json!([expected_no, expected_yes])),
Some(json!([expected_no, expected_yes, expected_no])),
),
(
"GET",
@@ -862,11 +914,8 @@ mod tests {
),
("GET", "/book", String::new(), 400, None),
("POST", "/books", "[]".into(), 200, Some(json!([]))),
("POST", "/books", json!(max_batch).to_string(), 200, Some(json!([expected_yes]))),
("POST", "/books", json!(too_many).to_string(), 200, Some(json!([expected_yes]))),
("POST", "/books", json!((0..=MAX_BOOKS).map(|i| json!({"token_id": i.to_string()})).collect::<Vec<_>>()).to_string(), 400, Some(json!({"error":"Payload exceeds the limit"}))),
("POST", "/books", json!([{"token_id":""},{"side":"BUY"},{"token_id":yes,"side":"invalid"},{"token_id":no,"side":"sell"}]).to_string(), 200, Some(json!([expected_no]))),
("POST", "/books", json!([{"token_id":123}]).to_string(), 400, Some(json!({"error":"Invalid payload"}))),
("POST", "/books", json!(max_batch).to_string(), 200, None),
("POST", "/books", json!(too_many).to_string(), 400, None),
(
"POST",
"/books",
@@ -878,8 +927,8 @@ mod tests {
"POST",
"/books",
r#"[{"token_id":"7","side":"INVALID"}]"#.into(),
200,
Some(json!([])),
400,
None,
),
("GET", "/v2/prices-history?tokenId=eb%3AYES%3Amap+2%3A%E8%83%9C%E8%80%85&interval=1h&bucketSeconds=60", String::new(), 200,
Some(json!({"data":[],"pagination":{"has_more":false,"next_cursor":null,"offset":0,"limit":10000}}))),
+19
View File
@@ -25,6 +25,10 @@ flowchart LR
publicsql -->|预定窗口内的成交及订单| schema
publictrades -->|标识结果资产| assets
publictrades -->|校验事件及盘口选择| valid
api -->|查询公开目录| gamma_search["src/gamma_search.rs"]
market -->|登记公开资料| gamma_search
gamma_search --> search_sql["src/gamma_search_events.sql"]
gamma_search --> profile_schema["src/gamma_search_profiles.sql"]
queries -->|市场持有人榜单| holders["src/holders.rs"]
holders -->|按余额及结果分页| holderrows["src/holders.sql"]
holderrows -->|读取含挂单预留的持仓| markschema
@@ -1237,6 +1241,21 @@ sequenceDiagram
一个本地事件有可见盘口且所有可见盘口均已封盘时,目录将事件标为 closed。空事件和仍有开放子盘的事件保持开放。
### Gamma 公开搜索
```mermaid
sequenceDiagram
actor C as 客户端
participant E as Exchange
participant S as gamma_search.rs
participant D as SQLite
C->>E: GET /public-search,传关键词、状态与页码
E->>S: 校验参数并打开统一读快照
S->>D: 匹配赛事标题和盘口问题,统计并排序
S->>D: 展开当页盘口及按需读取标签或公开资料
S-->>C: 返回匹配事件和分页,或精简响应
```
### 从账本查询公开成交
```mermaid
+2
View File
@@ -3,6 +3,8 @@ use serde::Deserialize;
#[derive(Deserialize)]
#[serde(tag = "op", rename_all = "lowercase", deny_unknown_fields)]
pub(crate) enum Command {
#[serde(rename = "upsert_public_profile")]
UpsertPublicProfile(crate::gamma_search::SearchProfile),
Fund {
account: String,
cents: Option<i64>,
+346
View File
@@ -0,0 +1,346 @@
use crate::{
gamma_directory::{header, market},
validation::{hex_id, identifier},
Exchange, MarketDataError,
};
use anyhow::{ensure, Result};
use rusqlite::{params, Connection, Transaction};
use serde::Deserialize;
use serde_json::{json, Value};
use std::collections::HashMap;
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct SearchProfile {
wallet: String,
name: Option<String>,
pseudonym: Option<String>,
bio: Option<String>,
profile_image: Option<String>,
display_username_public: bool,
}
impl SearchProfile {
pub(crate) fn save(self, tx: &Transaction) -> Result<Value> {
let wallet = self.wallet.to_ascii_lowercase();
ensure!(hex_id(&wallet, 40), "invalid profile wallet");
for public_label in [&self.name, &self.pseudonym].into_iter().flatten() {
identifier(public_label)?;
}
tx.execute(
"INSERT INTO gamma_search_profiles(wallet,name,pseudonym,bio,profile_image,display_username_public)
VALUES(?,?,?,?,?,?)
ON CONFLICT(wallet) DO UPDATE SET name=excluded.name,pseudonym=excluded.pseudonym,
bio=excluded.bio,profile_image=excluded.profile_image,
display_username_public=excluded.display_username_public",
params![wallet,self.name,self.pseudonym,self.bio,self.profile_image,self.display_username_public],
)?;
Ok(json!({"proxyWallet":wallet}))
}
}
#[derive(Default)]
struct Search {
phrase: String,
tags: Vec<String>,
excluded_tags: Vec<i64>,
recurrence: Option<String>,
closed: Option<bool>,
sort_volume: bool,
ascending: bool,
limit: Option<i64>,
page: i64,
profiles: bool,
search_tags: bool,
optimized: bool,
}
fn invalid(message: impl Into<String>) -> MarketDataError {
MarketDataError::Invalid(message.into())
}
fn field_error(key: &str) -> MarketDataError {
invalid(format!("\"{key}\" has a wrong value"))
}
impl Search {
fn parse(fields: &[(String, String)]) -> Result<Self, MarketDataError> {
let mut q = Self::default();
for (key, value) in fields {
let boolean = || {
value
.to_ascii_lowercase()
.parse::<bool>()
.map_err(|_| field_error(key))
};
let integer = || value.parse::<i64>().map_err(|_| field_error(key));
match key.as_str() {
"q" => q.phrase = value.clone(),
"events_status" => {
q.closed = match value.as_str() {
"active" => Some(false),
"resolved" => Some(true),
_ => None,
}
}
"events_tag" => q.tags.push(value.to_ascii_lowercase()),
"exclude_tag_id" => q.excluded_tags.push(integer()?),
"recurrence" => q.recurrence = Some(value.clone()),
"sort" => q.sort_volume = value == "volume",
"ascending" => q.ascending = boolean()?,
"search_tags" => q.search_tags = boolean()?,
"search_profiles" => q.profiles = boolean()?,
"page" => q.page = integer()?,
"limit_per_type" => q.limit = Some(integer()?),
"optimized" => q.optimized = boolean()?,
"cache" => {
boolean()?;
}
"keep_closed_markets" => {
integer()?;
}
_ => {}
}
}
if q.phrase.is_empty() {
return Err(invalid("query argument \"q\": empty"));
}
if q.page > 100 {
return Err(invalid(
"query argument \"page\": must be less than or equal to 100",
));
}
Ok(q)
}
fn limit(&self) -> i64 {
match self.limit {
None => 5,
Some(n) if n <= 0 => 50,
Some(n) => n.min(50),
}
}
fn terms(&self) -> Vec<String> {
self.phrase
.split_whitespace()
.map(str::to_ascii_lowercase)
.collect()
}
}
fn source(
db: &Connection,
object: &str,
sql: &'static str,
empty: &'static str,
) -> rusqlite::Result<&'static str> {
let ready: bool = db.query_row(
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE name=?)",
[object],
|r| r.get(0),
)?;
Ok(if ready { sql } else { empty })
}
fn event_matches(db: &Connection, q: &Search) -> rusqlite::Result<(Vec<String>, i64)> {
// Optional directory modules contribute data as soon as their migrations exist.
let tags = source(
db,
"directory_tags",
"SELECT id,slug FROM directory_tags",
"SELECT NULL AS id,NULL AS slug WHERE 0",
)?;
let tagged_events = source(
db,
"event_tags",
"SELECT tag,event FROM event_tags",
"SELECT NULL AS tag,NULL AS event WHERE 0",
)?;
let recurrences = source(
db,
"series_events",
"SELECT a.event,s.recurrence FROM series_events a JOIN directory_series s ON s.id=a.series",
"SELECT NULL AS event,NULL AS recurrence WHERE 0",
)?;
let base = include_str!("gamma_search_events.sql")
.replace("{directory}", include_str!("gamma_events.sql"))
.replace("{tags}", tags)
.replace("{tagged_events}", tagged_events)
.replace("{recurrences}", recurrences);
let filters = json!({"phrase":q.phrase.trim().to_ascii_lowercase(),"terms":q.terms(),"closed":q.closed.map(i64::from),
"tags":q.tags,"excluded_tags":q.excluded_tags,"recurrence":q.recurrence}).to_string();
let total: i64 = db
.prepare_cached(&format!("{base} SELECT COUNT(*) FROM matching"))?
.query_row([&filters], |r| r.get(0))?;
let order = if q.sort_volume {
let dir = if q.ascending { "ASC" } else { "DESC" };
format!(
"COALESCE((SELECT SUM(t.price*CAST(t.quantity AS REAL))
FROM listed_markets l JOIN wallet_trade_legs t ON t.market=l.market
JOIN execution_context c ON c.execution=t.execution AND c.taker_order=t.order_seq
WHERE l.event=m.id),0) {dir}, m.event_id DESC"
)
} else {
"m.score ASC,m.event_id DESC".into()
};
let mut stmt = db.prepare_cached(&format!(
"{base} SELECT m.id FROM matching m ORDER BY {order} LIMIT ?2 OFFSET ?3"
))?;
let ids = stmt
.query_map(
params![filters, q.limit(), (q.page.max(1) - 1) * q.limit()],
|r| r.get(0),
)?
.collect::<rusqlite::Result<_>>()?;
Ok((ids, total))
}
fn event_rows(db: &Connection, ids: &[String], optimized: bool) -> rusqlite::Result<Vec<Value>> {
if ids.is_empty() {
return Ok(Vec::new());
}
let keys = json!(ids).to_string();
let mut headers = db.prepare_cached(concat!(
include_str!("gamma_events.sql"),
" WHERE e.id IN (SELECT value FROM json_each(?))",
))?;
let mut events = headers
.query_map([&keys], header)?
.collect::<rusqlite::Result<HashMap<_, _>>>()?;
let mut markets = db.prepare_cached(concat!(
include_str!("gamma_market.sql"),
" AND COALESCE(s.event,t.event) IN (SELECT value FROM json_each(?)) AND COALESCE(v.archived,0)=0
ORDER BY COALESCE(t.group_order,0),w.market",
))?;
let mut children = HashMap::<String, Vec<Value>>::new();
let mut rows = markets.query([keys])?;
while let Some(row) = rows.next()? {
let mut value = market(row)?;
if optimized {
if let Some(object) = value.as_object_mut() {
object.retain(|k, _| {
matches!(
k.as_str(),
"active"
| "archived"
| "bestAsk"
| "closed"
| "groupItemTitle"
| "lastTradePrice"
| "outcomePrices"
| "outcomes"
| "question"
| "slug"
)
});
}
}
children.entry(row.get("parent")?).or_default().push(value);
}
Ok(ids
.iter()
.filter_map(|id| {
events.remove(id).map(|mut event| {
if optimized {
if let Some(object) = event.as_object_mut() {
object.retain(|k, _| {
matches!(k.as_str(), "id" | "slug" | "title" | "closed" | "active")
});
}
}
event["markets"] = Value::Array(children.remove(id).unwrap_or_default());
event
})
})
.collect())
}
fn profile_rows(db: &Connection, q: &Search) -> rusqlite::Result<Vec<Value>> {
let mut stmt = db.prepare_cached(
"WITH visible AS (
SELECT id,wallet,CASE WHEN display_username_public THEN name END AS public_name,
pseudonym,bio,profile_image,display_username_public
FROM gamma_search_profiles
)
SELECT wallet,public_name,pseudonym,bio,profile_image,display_username_public
FROM visible
WHERE NOT EXISTS(SELECT 1 FROM json_each(?1)
WHERE instr(lower(wallet||' '||COALESCE(public_name,'')||' '||COALESCE(pseudonym,'')),value)=0)
ORDER BY CASE WHEN lower(wallet)=?2 OR lower(public_name)=?2 OR lower(pseudonym)=?2 THEN 0 ELSE 1 END,id
LIMIT ?3 OFFSET ?4",
)?;
let rows = stmt.query_map(params![json!(q.terms()).to_string(),q.phrase.trim().to_ascii_lowercase(),
q.limit(),(q.page.max(1)-1)*q.limit()], |r| {
let mut profile = json!({"proxyWallet":r.get::<_,String>(0)?,"displayUsernamePublic":r.get::<_,bool>(5)?});
for (column,key) in [(1,"name"),(2,"pseudonym"),(3,"bio"),(4,"profileImage")] {
if let Some(value) = r.get::<_,Option<String>>(column)? { profile[key]=json!(value); }
}
Ok(profile)
})?;
rows.collect()
}
fn tag_rows(db: &Connection, q: &Search) -> rusqlite::Result<Vec<Value>> {
let tags = source(
db,
"directory_tags",
"SELECT id,slug,label FROM directory_tags",
"SELECT NULL AS id,NULL AS slug,NULL AS label WHERE 0",
)?;
let assigned = source(
db,
"event_tags",
"SELECT tag,event FROM event_tags",
"SELECT NULL AS tag,NULL AS event WHERE 0",
)?;
let sql = format!(
"WITH tags AS ({tags}), assigned AS ({assigned})
SELECT CAST(t.id AS TEXT),t.slug,t.label,(SELECT count(*) FROM assigned a WHERE a.tag=t.id)
FROM tags t WHERE NOT EXISTS(SELECT 1 FROM json_each(?1)
WHERE instr(lower(t.slug||' '||t.label),value)=0)
ORDER BY CASE WHEN lower(t.slug)=?2 OR lower(t.label)=?2 THEN 0 ELSE 1 END,t.id
LIMIT ?3 OFFSET ?4"
);
let mut stmt = db.prepare_cached(&sql)?;
let rows = stmt.query_map(params![json!(q.terms()).to_string(),q.phrase.trim().to_ascii_lowercase(),
q.limit(),(q.page.max(1)-1)*q.limit()], |r| Ok(json!({
"id":r.get::<_,String>(0)?,"slug":r.get::<_,String>(1)?,"label":r.get::<_,String>(2)?,
"event_count":r.get::<_,i64>(3)?
})))?;
rows.collect()
}
impl Exchange {
pub fn gamma_search(&self, fields: &[(String, String)]) -> Result<Value, MarketDataError> {
let q = Search::parse(fields)?;
let tx = self.db.unchecked_transaction()?;
let (ids, total) = event_matches(&tx, &q)?;
let events = event_rows(&tx, &ids, q.optimized)?;
let profiles = if q.profiles {
profile_rows(&tx, &q)?
} else {
Vec::new()
};
let tags = if q.search_tags {
tag_rows(&tx, &q)?
} else {
Vec::new()
};
let has_more = q.page.max(1) * q.limit() < total;
let value = if q.optimized {
json!({"events":(!events.is_empty()).then_some(events),"hasMore":has_more,
"profiles":(!profiles.is_empty()).then_some(profiles),"tags":(!tags.is_empty()).then_some(tags)})
} else {
let mut response = json!({"pagination":{"hasMore":has_more,"totalResults":total}});
for (key, rows) in [("events", events), ("profiles", profiles), ("tags", tags)] {
if !rows.is_empty() {
response[key] = Value::Array(rows);
}
}
response
};
tx.commit()?;
Ok(value)
}
}
@@ -0,0 +1,39 @@
-- Bound search values are literal substrings. The directory views supply membership.
WITH
directory AS NOT MATERIALIZED ({directory}),
tags AS NOT MATERIALIZED ({tags}),
tagged_events AS NOT MATERIALIZED ({tagged_events}),
recurrences AS NOT MATERIALIZED ({recurrences}),
terms AS (SELECT value FROM json_each(?1,'$.terms')),
matching AS (
SELECT e.id,e.event_id,e.title,
CASE
WHEN lower(e.slug)=json_extract(?1,'$.phrase') OR lower(e.title)=json_extract(?1,'$.phrase') THEN 0
WHEN NOT EXISTS(SELECT 1 FROM terms WHERE instr(lower(e.title||' '||e.slug),value)=0) THEN 1
ELSE 2
END AS score
FROM directory e
WHERE (json_extract(?1,'$.closed') IS NULL OR e.closed=json_extract(?1,'$.closed'))
AND (json_extract(?1,'$.recurrence') IS NULL OR EXISTS(
SELECT 1 FROM recurrences r WHERE r.event=e.id AND r.recurrence=json_extract(?1,'$.recurrence')
))
AND (json_array_length(?1,'$.tags')=0 OR EXISTS(
SELECT 1 FROM tagged_events a JOIN tags t ON t.id=a.tag WHERE a.event=e.id
AND lower(t.slug) IN (SELECT value FROM json_each(?1,'$.tags'))
))
AND NOT EXISTS(
SELECT 1 FROM tagged_events a WHERE a.event=e.id
AND a.tag IN (SELECT value FROM json_each(?1,'$.excluded_tags'))
)
AND (
NOT EXISTS(SELECT 1 FROM terms WHERE instr(lower(e.title||' '||e.slug),value)=0) OR EXISTS(
SELECT 1 FROM listed_markets l JOIN market_wire_metadata w ON w.market=l.market
LEFT JOIN market_visibility v ON v.market=l.market
LEFT JOIN augmented_outcomes a ON a.market=l.market
WHERE l.event=e.id AND COALESCE(a.role,'')<>'placeholder'
AND COALESCE(v.archived,0)=0 AND NOT EXISTS(
SELECT 1 FROM terms WHERE instr(lower(w.question||' '||w.slug),value)=0
)
)
)
)
@@ -0,0 +1,11 @@
BEGIN IMMEDIATE;
CREATE TABLE IF NOT EXISTS gamma_search_profiles (
id INTEGER PRIMARY KEY,
wallet TEXT NOT NULL UNIQUE,
name TEXT,
pseudonym TEXT,
bio TEXT,
profile_image TEXT,
display_username_public INTEGER NOT NULL CHECK(display_username_public IN (0,1))
);
COMMIT;
+9
View File
@@ -22,6 +22,7 @@ mod cancellation;
mod clarifications;
mod clob_market;
mod command;
mod gamma_search;
mod inventory;
mod kickoff;
mod last_trades;
@@ -33,6 +34,7 @@ mod market_stream;
mod minimum_size;
mod neg_risk;
mod open_interest;
mod portfolio;
mod prices_history;
mod public_trades;
@@ -84,6 +86,13 @@ impl Exchange {
db.busy_timeout(Duration::from_secs(10))?;
db.execute_batch("PRAGMA foreign_keys=ON")?;
db.execute_batch(include_str!("schema.sql"))?;
let search_profiles_ready: bool = db.query_row(
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='table' AND name='gamma_search_profiles')",
[], |r| r.get(0),
)?;
if !search_profiles_ready {
db.execute_batch(include_str!("gamma_search_profiles.sql"))?;
}
let submissions_ready: bool = db.query_row(
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='table' AND name='order_submissions')",
[], |r| r.get(0),
+1
View File
@@ -16,6 +16,7 @@ pub(crate) fn apply(
request_id: &str,
) -> Result<Value> {
match command {
Command::UpsertPublicProfile(profile) => profile.save(tx),
Command::Fund {
account,
cents,
+7
View File
@@ -0,0 +1,7 @@
{"op":"event","id":"search-a","event":"north-cup","slug":"north-cup","title":"North Cup","category":"sports"}
{"op":"event","id":"search-b","event":"north-cup-archive","slug":"north-cup-archive","title":"North Cup Archive","category":"sports"}
{"op":"list","id":"search-market-a","market":"north-cup-goals","rules":"以正式比赛结束记录为准。","listing":{"event":"north-cup","question":"前十分钟会进球吗?","yes_label":"会","no_label":"不会","source":"比赛记录","resolver":"操作员","rules_version":1}}
{"op":"list","id":"search-market-b","market":"archived-north-cup-score","rules":"最终比分由赛事报告确认。","listing":{"event":"north-cup-archive","question":"最终比分是 2:1 吗?","yes_label":"是","no_label":"否","source":"赛事报告","resolver":"操作员","rules_version":1}}
{"op":"close","id":"search-close","market":"archived-north-cup-score"}
{"op":"upsert_public_profile","id":"search-profile-public","wallet":"0x0000000000000000000000000000000000000011","name":"North Cup analyst","display_username_public":true}
{"op":"upsert_public_profile","id":"search-profile-hidden","wallet":"0x0000000000000000000000000000000000000022","name":"Undisclosed analyst","pseudonym":"Pitch observer","display_username_public":false}
-22
View File
@@ -1,22 +0,0 @@
{
"selection": {
"repeat": {"method":"POST","url":"https://clob.polymarket.com/books","payload":[{"token_id":"23677896678650147625251750117853328843601853501710889530409633595389256242910"},{"token_id":"77367448845023382525249480243608609306658725883285195065573683809293972009019"},{"token_id":"35090254409399344650860070211816464534198960801264823587796928404808383727584"},{"token_id":"23677896678650147625251750117853328843601853501710889530409633595389256242910"}],"status":200,"date":"Fri, 04 Dec 2026 20:34:33 GMT","body":[{"asset_id":"35090254409399344650860070211816464534198960801264823587796928404808383727584","market":"0xa5f8a44504de30fa36fff2406b2b27b3d15476ed50448e4fc3ead4861d8a5e3e","timestamp":"1796416471487","hash":"8ac1310a449516053a001c0a4fdbf8febcf4fb69"},{"asset_id":"23677896678650147625251750117853328843601853501710889530409633595389256242910","market":"0xf17ad24eb4ad57926495b114149c765b9b95bc286eadc91cbbfa901ceb10d0b8","timestamp":"1796416466081","hash":"c9c08e49a8ec41370c28230a4c623d378472b7f5"},{"asset_id":"77367448845023382525249480243608609306658725883285195065573683809293972009019","market":"0xf17ad24eb4ad57926495b114149c765b9b95bc286eadc91cbbfa901ceb10d0b8","timestamp":"1796416466081","hash":"6fe42b07ad22ca0a864268708eb956c93064d10c"}]},
"forward": {"method":"POST","url":"https://clob.polymarket.com/books","payload":[{"token_id":"35090254409399344650860070211816464534198960801264823587796928404808383727584"},{"token_id":"77367448845023382525249480243608609306658725883285195065573683809293972009019"},{"token_id":"23677896678650147625251750117853328843601853501710889530409633595389256242910"}],"status":200,"date":"Fri, 04 Dec 2026 20:34:33 GMT","body":[{"asset_id":"23677896678650147625251750117853328843601853501710889530409633595389256242910","market":"0xf17ad24eb4ad57926495b114149c765b9b95bc286eadc91cbbfa901ceb10d0b8","timestamp":"1796416466081","hash":"c9c08e49a8ec41370c28230a4c623d378472b7f5"},{"asset_id":"35090254409399344650860070211816464534198960801264823587796928404808383727584","market":"0xa5f8a44504de30fa36fff2406b2b27b3d15476ed50448e4fc3ead4861d8a5e3e","timestamp":"1796416471487","hash":"8ac1310a449516053a001c0a4fdbf8febcf4fb69"},{"asset_id":"77367448845023382525249480243608609306658725883285195065573683809293972009019","market":"0xf17ad24eb4ad57926495b114149c765b9b95bc286eadc91cbbfa901ceb10d0b8","timestamp":"1796416466081","hash":"6fe42b07ad22ca0a864268708eb956c93064d10c"}]},
"reverse": {"method":"POST","url":"https://clob.polymarket.com/books","payload":[{"token_id":"23677896678650147625251750117853328843601853501710889530409633595389256242910"},{"token_id":"77367448845023382525249480243608609306658725883285195065573683809293972009019"},{"token_id":"35090254409399344650860070211816464534198960801264823587796928404808383727584"}],"status":200,"date":"Fri, 04 Dec 2026 20:34:33 GMT","body":[{"asset_id":"77367448845023382525249480243608609306658725883285195065573683809293972009019","market":"0xf17ad24eb4ad57926495b114149c765b9b95bc286eadc91cbbfa901ceb10d0b8","timestamp":"1796416466081","hash":"6fe42b07ad22ca0a864268708eb956c93064d10c"},{"asset_id":"35090254409399344650860070211816464534198960801264823587796928404808383727584","market":"0xa5f8a44504de30fa36fff2406b2b27b3d15476ed50448e4fc3ead4861d8a5e3e","timestamp":"1796416471487","hash":"8ac1310a449516053a001c0a4fdbf8febcf4fb69"},{"asset_id":"23677896678650147625251750117853328843601853501710889530409633595389256242910","market":"0xf17ad24eb4ad57926495b114149c765b9b95bc286eadc91cbbfa901ceb10d0b8","timestamp":"1796416466081","hash":"c9c08e49a8ec41370c28230a4c623d378472b7f5"}]},
"mixed": {"method":"POST","url":"https://clob.polymarket.com/books","payload":[{"token_id":"123"},{"token_id":"77367448845023382525249480243608609306658725883285195065573683809293972009019"},{"token_id":"not-an-asset"},{"token_id":"35090254409399344650860070211816464534198960801264823587796928404808383727584"},{"token_id":"77367448845023382525249480243608609306658725883285195065573683809293972009019"}],"status":200,"date":"Fri, 04 Dec 2026 20:34:33 GMT","body":[{"asset_id":"77367448845023382525249480243608609306658725883285195065573683809293972009019","market":"0xf17ad24eb4ad57926495b114149c765b9b95bc286eadc91cbbfa901ceb10d0b8","timestamp":"1796416466081","hash":"6fe42b07ad22ca0a864268708eb956c93064d10c"},{"asset_id":"35090254409399344650860070211816464534198960801264823587796928404808383727584","market":"0xa5f8a44504de30fa36fff2406b2b27b3d15476ed50448e4fc3ead4861d8a5e3e","timestamp":"1796416471487","hash":"8ac1310a449516053a001c0a4fdbf8febcf4fb69"}]},
"empty": {"method":"POST","url":"https://clob.polymarket.com/books","payload":[],"status":200,"date":"Fri, 04 Dec 2026 20:34:33 GMT","body":[]},
"all_missing": {"method":"POST","url":"https://clob.polymarket.com/books","payload":[{"token_id":"123"}],"status":200,"date":"Fri, 04 Dec 2026 20:34:33 GMT","body":[]},
"side_field": {"method":"POST","url":"https://clob.polymarket.com/books","payload":[{"token_id":"77367448845023382525249480243608609306658725883285195065573683809293972009019","side":"NO_SUCH_SIDE"},{"token_id":"35090254409399344650860070211816464534198960801264823587796928404808383727584"}],"status":200,"date":"Fri, 04 Dec 2026 20:34:33 GMT","body":[{"asset_id":"35090254409399344650860070211816464534198960801264823587796928404808383727584","market":"0xa5f8a44504de30fa36fff2406b2b27b3d15476ed50448e4fc3ead4861d8a5e3e","timestamp":"1796416471487","hash":"8ac1310a449516053a001c0a4fdbf8febcf4fb69"}]}
},
"fields": {
"valid_sides": {"method":"POST","url":"https://clob.polymarket.com/books","payload":[{"token_id":"35090254409399344650860070211816464534198960801264823587796928404808383727584","side":"BUY"},{"token_id":"77367448845023382525249480243608609306658725883285195065573683809293972009019","side":"SELL"}],"status":200,"date":"Fri, 04 Dec 2026 20:34:51 GMT","body":["35090254409399344650860070211816464534198960801264823587796928404808383727584","77367448845023382525249480243608609306658725883285195065573683809293972009019"]},
"blank_side": {"method":"POST","url":"https://clob.polymarket.com/books","payload":[{"token_id":"35090254409399344650860070211816464534198960801264823587796928404808383727584","side":""},{"token_id":"77367448845023382525249480243608609306658725883285195065573683809293972009019","side":null}],"status":200,"date":"Fri, 04 Dec 2026 20:34:51 GMT","body":["35090254409399344650860070211816464534198960801264823587796928404808383727584","77367448845023382525249480243608609306658725883285195065573683809293972009019"]},
"lower": {"method":"POST","url":"https://clob.polymarket.com/books","payload":[{"token_id":"35090254409399344650860070211816464534198960801264823587796928404808383727584","side":"buy"},{"token_id":"77367448845023382525249480243608609306658725883285195065573683809293972009019","side":"sell"}],"status":200,"date":"Fri, 04 Dec 2026 20:34:51 GMT","body":["35090254409399344650860070211816464534198960801264823587796928404808383727584","77367448845023382525249480243608609306658725883285195065573683809293972009019"]},
"missing_id": {"method":"POST","url":"https://clob.polymarket.com/books","payload":[{"side":"BUY"},{"token_id":"77367448845023382525249480243608609306658725883285195065573683809293972009019"}],"status":200,"date":"Fri, 04 Dec 2026 20:34:51 GMT","body":["77367448845023382525249480243608609306658725883285195065573683809293972009019"]},
"blank_id": {"method":"POST","url":"https://clob.polymarket.com/books","payload":[{"token_id":""},{"token_id":"77367448845023382525249480243608609306658725883285195065573683809293972009019"}],"status":200,"date":"Fri, 04 Dec 2026 20:34:51 GMT","body":["77367448845023382525249480243608609306658725883285195065573683809293972009019"]},
"number_id": {"method":"POST","url":"https://clob.polymarket.com/books","payload":[{"token_id":123},{"token_id":"77367448845023382525249480243608609306658725883285195065573683809293972009019"}],"status":400,"date":"Fri, 04 Dec 2026 20:34:51 GMT","body":{"error":"Invalid payload"}},
"empty_obj": {"method":"POST","url":"https://clob.polymarket.com/books","payload":{},"status":400,"date":"Fri, 04 Dec 2026 20:34:51 GMT","body":{"error":"Invalid payload"}},
"limit_500": {"method":"POST","url":"https://clob.polymarket.com/books","payload":{"repeat":500,"item":{"token_id":"35090254409399344650860070211816464534198960801264823587796928404808383727584"}},"status":200,"date":"Fri, 04 Dec 2026 20:34:51 GMT","body":["35090254409399344650860070211816464534198960801264823587796928404808383727584"]},
"limit_501": {"method":"POST","url":"https://clob.polymarket.com/books","payload":{"repeat":501,"item":{"token_id":"35090254409399344650860070211816464534198960801264823587796928404808383727584"}},"status":200,"date":"Fri, 04 Dec 2026 20:34:52 GMT","body":["35090254409399344650860070211816464534198960801264823587796928404808383727584"]}
}
}
+6 -4
View File
@@ -405,6 +405,12 @@ fidelity 以分钟为单位;省略或不大于零时按 1 分钟处理。相
在本地主题样例中只关闭 nvda-300 时,/markets 的结果仍有 nvda-200,/events 中的主题事件仍开放,事件详情中两个门槛盘都可见。关闭第二个门槛盘后,/events?closed=true 才返回这个事件。本地市场上架后默认 active 为 true,封盘仅更新交易状态。运营方可以通过 set_market_visibility 单独修改市场的 active 和 archived。事件仍使用原有的发布状态。封盘的事件聚合规则、默认每页 20 条和默认按数字 ID 降序都是本地约定。支持按 id、slug、市场 question 或事件 title 排序,逗号分隔多个字段;相同排序值用数字 ID 确定先后。每页使用独立读快照,分页之间如有上架或关闭,offset 可能移动。标签、链上标识、按交易量排序及官方游标分页仍待实现。
### Gamma 公开搜索
生产 `/public-search?q=nvidia` 和大写查询返回同样的前五条事件;盘口嵌在事件的 markets 数组。省略或清空 q 返回 422,未匹配时普通结果只保留 pagination。页码从 1 起算,0 和负值按第一页处理,超过 100 返回 422。省略 `limit_per_type` 的样本返回 5 条,0、负值和超过 50 的样本返回 50 条。`events_status=active` 和 `resolved` 分别缩小结果集,`closed` 在样本中按默认搜索处理。优化响应在顶层给出 hasMore,盘口和事件字段更少。启用资料和标签搜索时可单独返回匹配结果。[Gamma 搜索规范](https://docs.polymarket.com/api-reference/search/search-markets-events-and-profiles)
本地[样例](examples/gamma-search.jsonl)按赛事标题及盘口问题和 slug 查找,可用 `events_status`、本地成交额排序和分页。标签与系列表可用时,搜索支持对应的标签过滤、标签结果和 recurrence。显式登记的资料可供搜索,隐藏的用户名既不参与匹配也不返回。匹配采用本地字面子串和确定性排序。生产相关性算法、索引延迟、缓存及少见字段仍待核验。当前公开搜索的盘口随本地父事件返回,独立盘口仍可直接用市场目录查询。
### 公开成交的 Data API 入口
`GET /v2/trades` 读取本地成交账本,返回钱包视角的 BUY/SELL、份额数、按该结果计算的每份价格、成交秒数、结果标签和所属市场。对照 [赛事样例](examples/football.jsonl) 与 [成交样例](examples/volume.jsonl),Bob 的 NO 买单与 Alice 的 YES 买单在同一次互补撮合中成交。Bob 买入 3 份的每份价格为 0.40,Alice 买入的每份为 0.60。直接转让时买卖双方使用同一个成交价。默认只展示吃单方。对无已知吃单方的本地开盘集合竞价,taker_only=false 可查两侧的账本记录。
@@ -471,7 +477,3 @@ SDK 使用 `GET /neg-risk?token_id=…`,也可以从已缓存的 CLOB 市场
### 已裁决市场的公开盘口
对电竞、乒乓球和 SOL 涨跌盘的六个已裁决结果单查 /book,全部返回 404。批量 /books 和 /prices 忽略已裁决资产,混合批次保留可用资产。中点和价差多数同样返回 404,但一个 V2 市场的两侧分别仍能读到价差 1 或中点 0.5。Eventbook 对已裁决结果统一省略四种公开行情,保留内部快照供交易状态和回放。封盘待裁决阶段、外场淘汰时延和例外是否由服务缓存触发仍待验证。[生产响应](examples/public-resolved-books.json)
### 批量盘口的资产对应关系
生产 /books 批量返回每个可用资产至多一份盘口。响应顺序在重排请求时变化,客户端按 asset_id 对应结果。本地返回有效资产首次出现的顺序。重复项只占一个资产名额,最多 500 个不同标识。空标识、缺标识、无盘口和无效方向的项会被跳过。数字类型的标识使请求返回 400。BUY、SELL 的大小写及空方向不影响取到完整盘口。[生产样本](examples/public-batch-books.json) · [官方批量盘口接口](https://docs.polymarket.com/api-reference/market-data/get-order-books-request-body)