Serve public wallet position lifecycle and settlement flags
This commit is contained in:
@@ -423,3 +423,5 @@ sequenceDiagram
|
||||
E-->>H: true
|
||||
H-->>C: 200,neg_risk 为真
|
||||
```
|
||||
|
||||
GET /v2/positions 查询钱包或单一市场的当前持仓、待赎回份额、互补仓位及已退出记录。用 pagination.next_cursor 续读时沿用原钱包或市场与筛选条件。
|
||||
|
||||
@@ -329,7 +329,12 @@ fn respond(mut req: Request, engine: &Mutex<Exchange>) -> std::io::Result<()> {
|
||||
if req.method() == &Method::Get
|
||||
&& matches!(
|
||||
path,
|
||||
"/v2/prices-history" | "/v2/trades" | "/v2/resolutions" | "/v2/value" | "/v2/oi"
|
||||
"/v2/prices-history"
|
||||
| "/v2/trades"
|
||||
| "/v2/resolutions"
|
||||
| "/v2/value"
|
||||
| "/v2/oi"
|
||||
| "/v2/positions"
|
||||
)
|
||||
{
|
||||
let (status, body) = data_page(path, params, engine);
|
||||
@@ -473,6 +478,7 @@ fn respond(mut req: Request, engine: &Mutex<Exchange>) -> std::io::Result<()> {
|
||||
| "/market-clarifications"
|
||||
| "/v2/oi"
|
||||
| "/v2/value"
|
||||
| "/v2/positions"
|
||||
| "/v2/trades"
|
||||
| "/v2/resolutions"
|
||||
| "/v2/prices-history",
|
||||
@@ -514,6 +520,7 @@ fn read_page<Q: serde::de::DeserializeOwned>(
|
||||
fn data_page(path: &str, params: &str, engine: &Mutex<Exchange>) -> (u16, Value) {
|
||||
let page = match path {
|
||||
"/v2/oi" => read_page(params, engine, Exchange::public_open_interest),
|
||||
"/v2/positions" => read_page(params, engine, Exchange::public_positions),
|
||||
"/v2/value" => read_page(params, engine, Exchange::public_portfolio_value),
|
||||
"/v2/trades" => read_page(params, engine, Exchange::public_trade_feed),
|
||||
"/v2/resolutions" => read_page(params, engine, Exchange::public_resolutions),
|
||||
@@ -529,6 +536,10 @@ fn data_page(path: &str, params: &str, engine: &Mutex<Exchange>) -> (u16, Value)
|
||||
503,
|
||||
json!({"code":"unavailable","error":"open interest unavailable","retryable":true}),
|
||||
),
|
||||
Err(HistoryError::Unavailable) if path == "/v2/positions" => (
|
||||
503,
|
||||
json!({"code":"unavailable","error":"positions unavailable","retryable":true}),
|
||||
),
|
||||
Err(HistoryError::Unavailable) if path == "/v2/value" => (
|
||||
503,
|
||||
json!({"code":"unavailable","error":"portfolio valuation unavailable","retryable":true}),
|
||||
@@ -695,6 +706,10 @@ mod tests {
|
||||
("GET","/v2/oi",String::new(),503,None),
|
||||
("POST","/v2/oi",String::new(),405,None),
|
||||
("GET","/v2/value?user=0x0000000000000000000000000000000000000001",String::new(),200,Some(json!({"data":{"proxy_wallet":"0x0000000000000000000000000000000000000001","value":0}}))),
|
||||
("GET","/v2/positions?user=0x0000000000000000000000000000000000000001",String::new(),200,Some(json!({"data":[],"pagination":{"limit":100,"offset":0,"has_more":false,"next_cursor":null}}))),
|
||||
("GET","/v2/positions",String::new(),400,None),
|
||||
("GET","/v2/positions?user=unpriced-owner&cursor=invalid",String::new(),400,None),
|
||||
("POST","/v2/positions",String::new(),405,None),
|
||||
("GET","/v2/value",String::new(),400,None),
|
||||
("GET","/v2/value?user=unpriced-owner",String::new(),503,None),
|
||||
("GET","/v2/value?user=a&condition=",String::new(),400,None),
|
||||
|
||||
@@ -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
|
||||
```
|
||||
|
||||
@@ -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,4 +1,5 @@
|
||||
pub(crate) mod http;
|
||||
pub(crate) mod positions;
|
||||
mod protocol;
|
||||
|
||||
use crate::{
|
||||
|
||||
@@ -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
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user