Serve condition-scoped portfolio valuations from marked holdings

This commit is contained in:
2026-12-03 12:31:58 +08:00
parent 5696e3dae2
commit e26ba27a24
13 changed files with 302 additions and 16 deletions
+30
View File
@@ -1276,3 +1276,33 @@ sequenceDiagram
C->>E: public_resolutions(condition)
E-->>C: resolved,每份 YES 和 NO 各兑付 500000 微单位
```
### 账户持仓估值
公开估值在同一份账本快照中读取可用份额、挂卖锁定份额、盘口和裁决。若所选市场有非零持仓缺少估值依据,客户端可以重试;JSONL 的 portfolio_value 另提供已定价的小计和缺价数量。
```mermaid
flowchart LR
L["lib.rs · Exchange"] --> H["portfolio/http.rs · 钱包、条件、四位小数"]
H --> P["portfolio/protocol.rs · 协议合约地址"]
H --> V["portfolio.rs · 汇总份额价值"]
V --> S["portfolio/value.sql · 按账户及市场取持仓"]
V --> Q["quotes.rs · 盘口或成交价"]
```
```mermaid
sequenceDiagram
participant C as 客户端
participant H as Exchange
participant D as SQLite
C->>H: public_portfolio_value(user, condition)
H->>D: 处理到期委托,读取账户持仓快照
loop 每个有份额的结果
H->>D: 读取裁决兑付率或该资产的估值依据
end
alt 所有选中持仓均可定价
H-->>C: 全部相加,最后舍入到四位小数
else 仍有持仓缺价
H-->>C: 当前无法给出完整估值
end
```
+1
View File
@@ -52,6 +52,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 portfolio::http::ValueQuery;
pub use prices_history::http::HistoryQuery;
pub use prices_history::legacy::ClobHistoryQuery;
pub use public_trades::http::TradeQuery;
+18 -7
View File
@@ -1,3 +1,6 @@
pub(crate) mod http;
mod protocol;
use crate::{
inventory::{decimal, UNIT},
validation::identifier,
@@ -122,13 +125,15 @@ pub(crate) fn holding_value(size: i64, mark: Option<i64>) -> Option<i128> {
mark.map(|p| i128::from(p) * i128::from(size) / i128::from(UNIT))
}
pub(crate) fn value(db: &Connection, account: &str) -> Result<Value> {
identifier(account)?;
let mut stmt = db.prepare(
"SELECT market,outcome,available+reserved AS size,phase,payout_per_share
FROM position_units WHERE account=? AND available+reserved>0",
)?;
let mut rows = stmt.query([account])?;
/// Total in units of (micro-share × micro-dollar per share), before final rounding.
fn marked_holdings(
db: &Connection,
account: &str,
conditions: Option<&str>,
wallet_address: bool,
) -> Result<(i128, u64)> {
let mut stmt = db.prepare_cached(include_str!("portfolio/value.sql"))?;
let mut rows = stmt.query(params![account, conditions, wallet_address])?;
let mut priced = 0i128;
let mut missing = 0u64;
while let Some(row) = rows.next()? {
@@ -146,6 +151,12 @@ pub(crate) fn value(db: &Connection, account: &str) -> Result<Value> {
None => missing += 1,
}
}
Ok((priced, missing))
}
pub(crate) fn value(db: &Connection, account: &str) -> Result<Value> {
identifier(account)?;
let (priced, missing) = marked_holdings(db, account, None, false)?;
let priced = priced / i128::from(UNIT);
Ok(
json!({"account":account,"value_micros":(missing==0).then_some(priced),
+88
View File
@@ -0,0 +1,88 @@
use super::{marked_holdings, protocol::CONTRACTS};
use crate::{
expiry,
inventory::decimal,
validation::{hex_id, IdSelector},
Exchange, MarketDataError,
};
use rusqlite::{Connection, TransactionBehavior};
use serde::Deserialize;
use serde_json::{json, Value};
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ValueQuery {
user: String,
#[serde(alias = "condition_id", alias = "conditionId")]
condition: Option<String>,
}
impl ValueQuery {
fn conditions(&self, db: &Connection) -> Result<Option<String>, MarketDataError> {
let Some(raw) = &self.condition else {
return Ok(None);
};
let selector = IdSelector::Many(
raw.split(',')
.map(str::trim)
.map(|id| {
if hex_id(id, 64) {
id.to_ascii_lowercase()
} else {
id.to_owned()
}
})
.collect(),
);
let ids = selector
.ids()
.map_err(|e| MarketDataError::Invalid(e.to_string()))?;
let mut exists = db.prepare_cached("SELECT EXISTS(SELECT 1 FROM markets WHERE id=?)")?;
for id in &ids {
if !hex_id(id, 64) && !exists.query_row([id], |r| r.get::<_, bool>(0))? {
return Err(MarketDataError::Invalid("invalid condition".into()));
}
}
Ok(Some(json!(ids).to_string()))
}
}
impl Exchange {
pub fn public_portfolio_value(&self, query: ValueQuery) -> Result<Value, MarketDataError> {
let tx = expiry::transaction(&self.db, TransactionBehavior::Deferred)
.map_err(|_| MarketDataError::Unavailable)?;
let user = &query.user;
let wallet = hex_id(user, 40);
if wallet {
if CONTRACTS.iter().any(|c| c.eq_ignore_ascii_case(user)) {
return Err(MarketDataError::Invalid(
"protocol contract is not a user".into(),
));
}
} else if user.trim().is_empty()
|| !tx.query_row(
"SELECT EXISTS(SELECT 1 FROM accounts WHERE id=?)",
[user],
|r| r.get::<_, bool>(0),
)?
{
return Err(MarketDataError::Invalid("invalid user".into()));
}
let conditions = query.conditions(&tx)?;
let (priced, missing) = marked_holdings(&tx, user, conditions.as_deref(), wallet)
.map_err(|_| MarketDataError::Unavailable)?;
if missing != 0 {
return Err(MarketDataError::Unavailable);
}
// Four decimal places per dollar. Round once, after summing every holding.
const QUANTUM: i128 = 100_000_000;
let rounded = priced / QUANTUM + i128::from(priced % QUANTUM >= QUANTUM / 2);
let proxy_wallet = if wallet {
user.to_ascii_lowercase()
} else {
user.clone()
};
tx.commit()?;
Ok(json!({"data":{"proxy_wallet":proxy_wallet,"value":decimal(rounded,10_000)}}))
}
}
+33
View File
@@ -0,0 +1,33 @@
// Polygon deployments listed at https://docs.polymarket.com/resources/contracts.
// For upgradeable contracts, use the public proxy address.
pub(super) const CONTRACTS: &[&str] = &[
"0xE111180000d2663C0091e4f400237545B87B996B", // CTF Exchange
"0xe2222d279d744050d28e00520010520000310F59", // Neg Risk CTF Exchange
"0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296", // Neg Risk Adapter (CTF negative-risk approvals)
"0x4D97DCd97eC945f40cF65F87097ACe5EA0476045", // Conditional Tokens (CTF)
"0x006F54F7f9A22e0000CC2AB60031000000ae9fEF", // PositionManager Poly v2
"0x12121212006e4CD160D18e3f00711DA5c3372600", // Router Poly v2
"0x1000008dD9001B968442c1000017eaE6E0dA00Ba", // BinaryModule Poly v2
"0x200000900045e3B6259600682756002200028933", // NegRiskModule Poly v2
"0x30000034706C7d8e12009DAB006Be20000c031A8", // CombinatorialModule Poly v2
"0xe3333700cA9d93003F00f0F71f8515005F6c00Aa", // ExchangeV3 Poly v2
"0xa1200000d0002264C9a1698e001292D00E1b00af", // AutoRedeemer Poly v2
"0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB", // pUSD — CollateralToken Poly v2
"0x93070a847efEf7F70739046A929D47a521F5B8ee", // CollateralOnramp Poly v2
"0x2957922Eb93258b93368531d39fAcCA3B4dC5854", // CollateralOfframp Poly v2
"0xebC2459Ec962869ca4c0bd1E06368272732BCb08", // PermissionedRamp Poly v2
"0xAdA100Db00Ca00073811820692005400218FcE1f", // CtfCollateralAdapter
"0xadA2005600Dec949baf300f4C6120000bDB6eAab", // NegRiskCtfCollateralAdapter
"0xCe84E053301A82937F90ee2C2c1889cAb1db25dE", // pUSD CollateralToken implementation
"0x00000000000Fb5C9ADea0298D729A0CB3823Cc07", // Deposit Wallet Factory
"0x7A18EDfe055488A3128f01F563e5B479D92ffc3a", // Deposit Wallet Beacon
"0xaacfeea03eb1561c4e67d661e40682bd20e3541b", // Gnosis Safe Factory
"0xaB45c5A4B0c941a2F231C04C3f49182e1A254052", // Polymarket Proxy Factory
"0x6A9D222616C90FcA5754cd1333cFD9b7fb6a4F74", // UMA Adapter
"0xCB1822859cEF82Cd2Eb4E6276C7916e692995130", // UMA Optimistic Oracle
"0x0A0a0A0A8B00C51b7D810501b03F230028C04a87", // OracleAggregator Poly v2
"0x000012e0009c84078c4924fba808A41b9f67527f", // OOReporterModule Poly v2
"0xc12EC12E0000326890Ca5560dEf5EB5C22b16814", // ChainlinkReporterModule Poly v2
"0x8Ef9D6d668798b1f363b305D916F30739d2b0419", // EOAReporterModule Poly v2
"0x157Ce2d672854c848c9b79C49a8Cc6cc89176a49", // UmaCtfAdapter v3.1.0
];
+11
View File
@@ -0,0 +1,11 @@
WITH owners(id) AS (
SELECT ?1 WHERE NOT ?3
UNION ALL
SELECT id FROM accounts WHERE ?3 AND id=?1 COLLATE NOCASE
)
SELECT market,outcome,available+reserved AS size,phase,payout_per_share
FROM position_units
WHERE account IN (SELECT id FROM owners) AND available+reserved>0
AND (?2 IS NULL OR
CASE WHEN length(market)=66 AND market GLOB '0x*' AND substr(market,3) NOT GLOB '*[^0-9a-fA-F]*'
THEN lower(market) ELSE market END IN (SELECT value FROM json_each(?2)))
+1 -4
View File
@@ -49,10 +49,7 @@ impl Policy {
}
fn question_key(raw: &str) -> Result<String> {
ensure!(
raw.len() == 66 && raw.starts_with("0x") && raw[2..].bytes().all(|b| b.is_ascii_hexdigit()),
"invalid question_id"
);
ensure!(crate::validation::hex_id(raw, 64), "invalid question_id");
Ok(raw.to_ascii_lowercase())
}
+1
View File
@@ -1,6 +1,7 @@
CREATE TABLE IF NOT EXISTS accounts (
id TEXT PRIMARY KEY, cash INTEGER NOT NULL CHECK(cash >= 0)
);
CREATE INDEX IF NOT EXISTS accounts_by_wallet ON accounts(id COLLATE NOCASE);
CREATE TABLE IF NOT EXISTS markets (
id TEXT PRIMARY KEY, rules TEXT NOT NULL, phase TEXT NOT NULL,
collateral INTEGER NOT NULL DEFAULT 0 CHECK(collateral >= 0), winner TEXT
+5 -3
View File
@@ -7,6 +7,10 @@ pub(crate) fn identifier(id: &str) -> Result<()> {
);
Ok(())
}
pub(crate) fn hex_id(id: &str, digits: usize) -> bool {
id.len() == 2 + digits && id.starts_with("0x") && id[2..].bytes().all(|b| b.is_ascii_hexdigit())
}
pub(crate) fn amount(n: i64) -> Result<()> {
ensure!((1..=1_000_000_000).contains(&n), "invalid amount");
Ok(())
@@ -61,9 +65,7 @@ pub(crate) fn directory_selector(
ensure!(n > 0, "invalid event_id");
keys.push(n.to_string());
} else {
if id.starts_with("0x")
&& !(id.len() == 66 && id[2..].bytes().all(|b| b.is_ascii_hexdigit()))
{
if id.starts_with("0x") && !hex_id(id, 64) {
// Locally listed condition IDs may legitimately use a short 0x prefix.
let listed: bool = db.query_row(
"SELECT EXISTS(SELECT 1 FROM markets WHERE id=?1)",
+60 -1
View File
@@ -1759,7 +1759,19 @@ fn valuation_counts_reserved_shares_and_distinguishes_unpriced_from_zero() {
let cmd: Value = serde_json::from_str(line).unwrap();
let response = e.execute(cmd.clone()).unwrap();
match cmd["op"].as_str().unwrap() {
"portfolio_value" => snapshots.push(response),
"portfolio_value" => {
let query =
serde_json::from_value(json!({"user":"alice","condition":"e,e"})).unwrap();
let wire = e.public_portfolio_value(query);
match response["value_micros"].as_i64() {
Some(micros) => assert_eq!(
wire.unwrap()["data"]["value"].as_f64(),
Some(micros as f64 / 1_000_000.0)
),
None => assert!(matches!(wire, Err(exchange::MarketDataError::Unavailable))),
}
snapshots.push(response);
}
"positions" => {
let yes = response["positions"]
.as_array()
@@ -3556,3 +3568,50 @@ fn resolution_feed_tracks_a_reset_and_final_split_after_reopening() {
);
assert!(final_market[0].get("resolved_block").is_none());
}
#[test]
fn public_wallet_value_rounds_after_summing_and_scopes_each_condition() {
let dir = tempdir().unwrap();
let path = dir.path().join("wallet-value.sqlite");
let wallet = format!("0x{}", "aB".repeat(20));
let condition = format!("0x{}", "AB".repeat(32));
let mut db = Exchange::open(&path).unwrap();
db.execute(json!({"op":"fund","id":"fund","account":wallet,"cents":100}))
.unwrap();
for market in [&condition[..], "final"] {
db.execute(json!({"op":"list","id":format!("list-{market}"),"market":market,"rules":"official result"})).unwrap();
db.execute(json!({"op":"split","id":format!("split-{market}"),"account":wallet,"market":market,"qty_micros":30})).unwrap();
db.execute(json!({"op":"close","id":format!("close-{market}"),"market":market}))
.unwrap();
db.execute(
json!({"op":"finalize","id":format!("final-{market}"),"market":market,"winner":"VOID"}),
)
.unwrap();
}
drop(db);
let db = Exchange::open(path).unwrap();
let value = |query: Value| db.public_portfolio_value(serde_json::from_value(query).unwrap());
let user = wallet.to_ascii_lowercase();
assert_eq!(
value(json!({"user":user})).unwrap(),
json!({"data":{"proxy_wallet":user,"value":0.0001}})
);
assert_eq!(
value(json!({"user":wallet,"conditionId":condition.to_ascii_lowercase()})).unwrap()["data"]
["value"],
0
);
assert_eq!(
value(json!({"user":user,"condition":format!("final,{condition},final")})).unwrap()["data"]
["value"],
json!(0.0001)
);
let too_many = (0..21)
.map(|n| format!("0x{n:064x}"))
.collect::<Vec<_>>()
.join(",");
assert!(matches!(
value(json!({"user":user,"condition":too_many})),
Err(exchange::MarketDataError::Invalid(_))
));
}