Serve public wallet position lifecycle and settlement flags

This commit is contained in:
2026-12-05 04:44:37 +08:00
parent 31af9ad9cf
commit 629d5d2548
10 changed files with 453 additions and 1 deletions
+22
View File
@@ -1434,3 +1434,25 @@ sequenceDiagram
E-->>C: 返回本次两侧销毁量和实付金额
end
```
### 公开持仓生命周期
```mermaid
flowchart LR
cli["cli/market_http.rs"] --> positions["portfolio/positions.rs"]
positions --> sql["portfolio/positions.sql"]
positions --> mark["portfolio.rs 中的估值"]
```
```mermaid
sequenceDiagram
participant H as HTTP
participant P as public_positions
participant D as SQLite
H->>P: 钱包或市场、持仓状态和游标
P->>D: 清理到期任务并读取同一快照中的仓位与市场
D-->>P: 持仓、配对份额、裁决和目录
P->>P: 按排序键保留一页、签署下一页游标
P-->>H: data 和 pagination
```
+1
View File
@@ -54,6 +54,7 @@ pub use gamma_directory::DirectoryKey;
pub use gamma_list::DirectoryResource;
pub use open_interest::InterestQuery;
pub use portfolio::http::ValueQuery;
pub use portfolio::positions::PositionQuery;
pub use prices_history::http::HistoryQuery;
pub use prices_history::legacy::ClobHistoryQuery;
pub use public_trades::http::TradeQuery;
+1
View File
@@ -1,4 +1,5 @@
pub(crate) mod http;
pub(crate) mod positions;
mod protocol;
use crate::{
+288
View File
@@ -0,0 +1,288 @@
use crate::{
assets, expiry,
inventory::{decimal, UNIT},
validation::{condition_filter, hex_id, identifier},
Exchange, MarketDataError,
};
use data_encoding::BASE64URL_NOPAD;
use hmac::{Hmac, Mac};
use rusqlite::{params, Connection, TransactionBehavior};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use sha2::Sha256;
use std::collections::BTreeMap;
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PositionQuery {
user: Option<String>,
#[serde(alias = "condition_id", alias = "conditionId")]
condition: Option<String>,
status: Option<String>,
#[serde(alias = "sortBy")]
sort_by: Option<String>,
#[serde(alias = "sortDirection")]
sort_direction: Option<String>,
#[serde(alias = "includeArchived")]
include_archived: Option<bool>,
limit: Option<u32>,
cursor: Option<String>,
}
#[derive(Serialize, Deserialize, PartialEq, Eq)]
struct Selection {
user: Option<String>,
conditions: Option<String>,
status: String,
sort: String,
direction: String,
archived: bool,
}
#[derive(Serialize, Deserialize)]
struct Cursor {
selection: Selection,
limit: u32,
offset: u64,
last: Key,
}
// Negate only the numeric rank for descending order. Identity is a stable
// tie-breaker regardless of direction or changes elsewhere in the portfolio.
type Key = (bool, i64, String, String, String);
fn invalid(message: &str) -> MarketDataError {
MarketDataError::Invalid(message.to_owned())
}
impl Cursor {
fn mac(db: &Connection) -> Result<Hmac<Sha256>, MarketDataError> {
let secret: Vec<u8> = db.query_row(
"SELECT secret FROM trade_cursor_key WHERE singleton=1",
[],
|row| row.get(0),
)?;
let mut mac =
Hmac::<Sha256>::new_from_slice(&secret).map_err(|_| MarketDataError::Unavailable)?;
mac.update(b"eventbook:/v2/positions:v1\0");
Ok(mac)
}
fn decode(db: &Connection, encoded: &str) -> Result<Self, MarketDataError> {
let bad = || invalid("invalid position cursor");
if encoded.len() > 8192 {
return Err(bad());
}
let bytes = BASE64URL_NOPAD
.decode(encoded.as_bytes())
.map_err(|_| bad())?;
let split = bytes.len().checked_sub(32).ok_or_else(bad)?;
let (payload, signature) = bytes.split_at(split);
let mut mac = Self::mac(db)?;
mac.update(payload);
mac.verify_slice(signature).map_err(|_| bad())?;
serde_json::from_slice(payload).map_err(|_| bad())
}
fn encode(&self, db: &Connection) -> Result<String, MarketDataError> {
let mut bytes = serde_json::to_vec(self).map_err(|_| MarketDataError::Unavailable)?;
let mut mac = Self::mac(db)?;
mac.update(&bytes);
bytes.extend_from_slice(&mac.finalize().into_bytes());
Ok(BASE64URL_NOPAD.encode(&bytes))
}
}
impl Exchange {
pub fn public_positions(&self, query: PositionQuery) -> Result<Value, MarketDataError> {
let tx = expiry::transaction(&self.db, TransactionBehavior::Deferred)
.map_err(|_| MarketDataError::Unavailable)?;
let mut user = query.user;
let wallet = user.as_deref().is_some_and(|id| hex_id(id, 40));
if let Some(id) = &mut user {
if wallet {
id.make_ascii_lowercase();
if super::protocol::CONTRACTS
.iter()
.any(|c| c.eq_ignore_ascii_case(id))
{
return Err(invalid("protocol contract is not a user"));
}
} else {
identifier(id).map_err(|_| invalid("invalid user"))?;
if !tx.query_row(
"SELECT EXISTS(SELECT 1 FROM accounts WHERE id=?1)",
[&*id],
|r| r.get::<_, bool>(0),
)? {
return Err(invalid("invalid user"));
}
}
}
let conditions = condition_filter(query.condition.as_deref(), &tx)?;
if user.is_none() {
let count = conditions
.as_ref()
.map(|s| serde_json::from_str::<Vec<String>>(s))
.transpose()
.map_err(|_| MarketDataError::Unavailable)?
.map_or(0, |ids| ids.len());
if count != 1 {
return Err(invalid("expected a user or exactly one condition"));
}
}
let cursor = query
.cursor
.as_deref()
.map(|encoded| Cursor::decode(&tx, encoded))
.transpose()?;
let prior = cursor.as_ref().map(|p| &p.selection);
let mut status = query
.status
.or_else(|| prior.map(|s| s.status.clone()))
.unwrap_or_else(|| "OPEN".into());
if !matches!(
status.as_str(),
"OPEN" | "CLOSED" | "REDEEMABLE" | "REDEEMABLE_LOST" | "MERGEABLE"
) || (user.is_none() && status == "REDEEMABLE_LOST")
{
return Err(invalid("invalid position status"));
}
if user.is_none() && status == "MERGEABLE" {
status = "OPEN".into();
}
if status == "CLOSED" && query.include_archived.is_some() {
return Err(invalid("include_archived is unavailable for CLOSED"));
}
let sort = query
.sort_by
.or_else(|| prior.map(|s| s.sort.clone()))
.unwrap_or_else(|| {
if status == "MERGEABLE" {
"TOKENS".into()
} else {
"CURRENT_VALUE".into()
}
});
let direction = query
.sort_direction
.or_else(|| prior.map(|s| s.direction.clone()))
.unwrap_or_else(|| "DESC".into());
if !matches!(sort.as_str(), "CURRENT_VALUE" | "PRICE" | "TOKENS")
|| !matches!(direction.as_str(), "ASC" | "DESC")
{
return Err(invalid("invalid or unsupported position sort"));
}
let selection = Selection {
user,
conditions,
status,
sort,
direction,
archived: query
.include_archived
.or_else(|| prior.map(|s| s.archived))
.unwrap_or(false),
};
let limit = cursor
.as_ref()
.map_or(query.limit.unwrap_or(100), |p| p.limit);
if limit > 1000 || cursor.as_ref().is_some_and(|p| p.selection != selection) {
return Err(invalid("invalid position limit or cursor filters"));
}
let offset = cursor.as_ref().map_or(0, |p| p.offset);
let mut page = BTreeMap::new();
if limit != 0 {
let mut stmt = tx.prepare_cached(include_str!("positions.sql"))?;
let mut rows = stmt.query(params![
selection.user,
wallet,
selection.conditions,
selection.status,
selection.archived
])?;
while let Some(row) = rows.next()? {
let account: String = row.get(0)?;
let market: String = row.get(1)?;
let outcome: String = row.get(2)?;
let size: i64 = row.get(3)?;
let phase: String = row.get(4)?;
let payout: Option<i64> = row.get(5)?;
let mark = super::price(&tx, &market, &outcome, &phase, payout)
.map_err(|_| MarketDataError::Unavailable)?
.map(|(price, _)| price);
let value = super::holding_value(size, mark);
let rank = match selection.sort.as_str() {
"TOKENS" => size,
"PRICE" => mark.unwrap_or(0),
_ => value
.unwrap_or(0)
.try_into()
.map_err(|_| MarketDataError::Unavailable)?,
};
let rank = if selection.direction == "DESC" {
-rank
} else {
rank
};
let losing = selection.status == "REDEEMABLE" && payout == Some(0);
let key = (
losing,
rank,
account.clone(),
market.clone(),
outcome.clone(),
);
if cursor.as_ref().is_some_and(|p| key <= p.last) {
continue;
}
let yes = outcome == "YES";
let opposite = if yes { "NO" } else { "YES" };
let redeemable = size > 0 && phase == "resolved";
let status = if selection.status == "CLOSED" {
"CLOSED"
} else if redeemable {
"REDEEMABLE"
} else {
"OPEN"
};
page.insert(key, json!({
"proxy_wallet": account, "condition_id": market,
"token_id": assets::id(&market,&outcome), "opposite_token_id": assets::id(&market,opposite),
"current_size": decimal(size.into(),UNIT),
"current_price": mark.map(|p| decimal(p.into(),UNIT)),
"current_value": value.map(|v| decimal(v,UNIT)),
"status": status, "redeemable": redeemable, "mergeable": row.get::<_, bool>(7)?,
"archived": row.get::<_, bool>(6)?, "negative_risk": row.get::<_, bool>(12)?,
"title": row.get::<_, String>(8)?, "slug": row.get::<_, String>(9)?,
"outcome": row.get::<_, String>(if yes {10} else {11})?,
"opposite_outcome": row.get::<_, String>(if yes {11} else {10})?,
"outcome_index": if yes {0} else {1}
}));
if page.len() > limit as usize + 1 {
page.pop_last();
}
}
}
let has_more = page.len() > limit as usize;
let next = if has_more {
page.pop_last();
let token = Cursor {
selection,
limit,
offset: offset.saturating_add(u64::from(limit)),
last: page.last_key_value().expect("nonempty page").0.clone(),
}
.encode(&tx)?;
Some(token)
} else {
None
};
let data: Vec<_> = page.into_values().collect();
tx.commit()?;
Ok(
json!({"data":data,"pagination":{"limit":limit,"offset":offset,"has_more":has_more,"next_cursor":next}}),
)
}
}
@@ -0,0 +1,23 @@
WITH held AS (
SELECT p.*,p.available+p.reserved AS size,
COALESCE(v.active,1) AS active, COALESCE(v.archived,0) AS archived
FROM position_units p LEFT JOIN market_visibility v USING(market)
WHERE (?1 IS NULL OR CASE WHEN ?2 THEN p.account COLLATE NOCASE=?1 ELSE p.account=?1 END)
AND (?3 IS NULL OR p.market IN (SELECT value FROM json_each(?3)))
)
SELECT p.account,p.market,p.outcome,p.size,p.phase,p.payout_per_share,p.archived,
p.phase<>'resolved' AND p.size>=100000 AND COALESCE(other.size,0)>=100000 AS mergeable,
w.question,w.slug,w.yes_label,w.no_label,n.market IS NOT NULL AS negative_risk
FROM held p
JOIN market_wire_metadata w ON w.market=p.market
LEFT JOIN held other ON other.account=p.account AND other.market=p.market AND other.outcome<>p.outcome
LEFT JOIN neg_risk_members n ON n.market=p.market
WHERE CASE ?4
WHEN 'CLOSED' THEN p.size<100000
ELSE p.active AND (?5 OR NOT p.archived) AND p.size>=100000 AND CASE ?4
WHEN 'OPEN' THEN 1
WHEN 'REDEEMABLE' THEN p.phase='resolved'
WHEN 'REDEEMABLE_LOST' THEN p.phase='resolved' AND p.payout_per_share=0
WHEN 'MERGEABLE' THEN mergeable
END
END
+66
View File
@@ -4176,3 +4176,69 @@ fn order_submission_terms_survive_fills_cancel_retries_and_legacy_upgrade() {
assert_eq!(e.execute(cmd.clone()).unwrap()["orders"][0], expected);
}
}
#[test]
fn public_positions_walk_a_mergeable_pair_and_held_settlement() {
let dir = tempdir().unwrap();
let path = dir.path().join("positions.db");
let mut e = Exchange::open(&path).unwrap();
setup(&mut e);
let read =
|engine: &Exchange, query| engine.public_positions(serde_json::from_value(query).unwrap());
for cmd in [
json!({"op":"list","id":"dust-list","market":"dust","rules":"dust"}),
json!({"op":"split","id":"dust-split","market":"dust","account":"bob","qty_micros":8800}),
json!({"op":"close","id":"dust-close","market":"dust"}),
json!({"op":"finalize","id":"dust-win","market":"dust","winner":"YES"}),
] {
e.execute(cmd).unwrap();
}
assert_eq!(
read(&e, json!({"user":"bob","condition":"dust"})).unwrap()["data"],
json!([])
);
let dust = read(
&e,
json!({"user":"bob","condition":"dust","status":"CLOSED"}),
)
.unwrap();
let winning_dust = dust["data"]
.as_array()
.unwrap()
.iter()
.find(|row| row["token_id"] == "eb:YES:dust")
.unwrap();
assert_eq!(winning_dust["current_size"], 0.0088);
assert_eq!(winning_dust["redeemable"], true);
let first = read(&e, json!({"user":"alice","status":"MERGEABLE","limit":1})).unwrap();
assert_eq!(first["data"][0]["mergeable"], true);
let cursor = first["pagination"]["next_cursor"].as_str().unwrap();
assert!(read(&e, json!({"user":"bob","cursor":cursor})).is_err());
assert!(read(&e, json!({"user":"alice","status":"OPEN","cursor":cursor})).is_err());
drop(e);
let mut e = Exchange::open(path).unwrap();
let next = read(&e, json!({"user":"alice","cursor":cursor,"limit":5})).unwrap();
assert_eq!(next["pagination"]["limit"], 1);
assert_eq!(next["pagination"]["offset"], 1);
assert_eq!(next["pagination"]["has_more"], false);
assert_ne!(next["data"][0]["token_id"], first["data"][0]["token_id"]);
e.execute(json!({"op":"close","id":"close","market":"e"}))
.unwrap();
e.execute(json!({"op":"finalize","id":"win","market":"e","winner":"YES"}))
.unwrap();
let held = read(&e, json!({"user":"alice","condition":"e","status":"OPEN"})).unwrap();
assert_eq!(held["data"][0]["status"], "REDEEMABLE");
assert_eq!(held["data"][0]["current_value"], 10);
assert_eq!(held["data"][0]["mergeable"], false);
let lost = read(&e, json!({"user":"alice","status":"REDEEMABLE_LOST"})).unwrap();
assert_eq!(lost["data"].as_array().unwrap().len(), 1);
assert_eq!(lost["data"][0]["token_id"], "eb:NO:e");
e.execute(json!({"op":"redeem","id":"claim","market":"e","account":"alice"}))
.unwrap();
assert_eq!(
read(&e, json!({"user":"alice"})).unwrap()["data"],
json!([])
);
let closed = read(&e, json!({"user":"alice","status":"CLOSED"})).unwrap();
assert_eq!(closed["data"].as_array().unwrap().len(), 2);
}