Serve condition-scoped portfolio valuations from marked holdings
This commit is contained in:
@@ -333,3 +333,27 @@ sequenceDiagram
|
||||
E-->>H: 每个可见市场一行
|
||||
H-->>C: 200 data 数组,未找到返回空数组
|
||||
```
|
||||
|
||||
### 查询持仓价值
|
||||
|
||||
`GET /v2/value?user=alice&condition=e` 返回该账户在市场 e 的持仓价值,单位为模拟美元。使用已登记的本地账户名或 20 字节钱包地址。省略 condition 查询所有已持有市场。无持仓的钱包返回零,仅有现金的账户也返回零。
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
H["market_http.rs · GET /v2/value"] --> V["exchange/portfolio/http.rs"]
|
||||
V --> A["exchange/portfolio.rs"] --> S["exchange/portfolio/value.sql"]
|
||||
```
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as 客户端
|
||||
participant H as market_http.rs
|
||||
participant E as Exchange
|
||||
C->>H: GET /v2/value?user=alice&condition=e
|
||||
H->>E: 读取 e 的所有结果资产价值
|
||||
alt 持仓均可估值
|
||||
H-->>C: 200,data 含 proxy_wallet 和 value
|
||||
else 非零持仓缺价
|
||||
H-->>C: 503,Retry-After 提示重试
|
||||
end
|
||||
```
|
||||
|
||||
@@ -327,7 +327,7 @@ 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/prices-history" | "/v2/trades" | "/v2/resolutions" | "/v2/value"
|
||||
)
|
||||
{
|
||||
let (status, body) = data_page(path, params, engine);
|
||||
@@ -485,6 +485,7 @@ fn respond(mut req: Request, engine: &Mutex<Exchange>) -> std::io::Result<()> {
|
||||
| "/markets"
|
||||
| "/events"
|
||||
| "/market-clarifications"
|
||||
| "/v2/value"
|
||||
| "/v2/trades"
|
||||
| "/v2/resolutions"
|
||||
| "/v2/prices-history",
|
||||
@@ -525,6 +526,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/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),
|
||||
_ => read_page(params, engine, Exchange::public_price_history),
|
||||
@@ -535,6 +537,10 @@ fn data_page(path: &str, params: &str, engine: &Mutex<Exchange>) -> (u16, Value)
|
||||
400,
|
||||
json!({"code":"invalid_request","error":message,"retryable":false}),
|
||||
),
|
||||
Err(HistoryError::Unavailable) if path == "/v2/value" => (
|
||||
503,
|
||||
json!({"code":"unavailable","error":"portfolio valuation unavailable","retryable":true}),
|
||||
),
|
||||
Err(HistoryError::Unavailable) if path == "/v2/resolutions" => (
|
||||
500,
|
||||
json!({"code":"internal","error":"resolution state unavailable","retryable":true}),
|
||||
@@ -554,6 +560,9 @@ fn send(req: Request, status: u16, body: Value, allow: Option<&str>) -> std::io:
|
||||
let mut response = Response::from_data(body.to_string().into_bytes())
|
||||
.with_status_code(status)
|
||||
.with_header(Header::from_bytes("Content-Type", "application/json").unwrap());
|
||||
if status == 503 {
|
||||
response = response.with_header(Header::from_bytes("Retry-After", "1").unwrap());
|
||||
}
|
||||
if let Some(method) = allow {
|
||||
response.add_header(Header::from_bytes("Allow", method).unwrap());
|
||||
}
|
||||
@@ -616,6 +625,9 @@ mod tests {
|
||||
let lookup_info = json!({"gst":null,"nr":false,"rfqe":false,"ibce":false,"oas":0,"mos":0.01,"mts":0.0025,
|
||||
"t":[{"o":"YES","t":"eb:YES:map+2/1"},{"o":"NO","t":"eb:NO:map+2/1"}]});
|
||||
for command in [
|
||||
json!({"op":"fund","id":"v-fund","account":"unpriced-owner","cents":100}),
|
||||
json!({"op":"list","id":"v-list","market":"unpriced","rules":"valuation fixture"}),
|
||||
json!({"op":"split","id":"v-split","account":"unpriced-owner","market":"unpriced","qty":1}),
|
||||
json!({"op":"list","id":"s-list","market":"s","rules":"spread fixture"}),
|
||||
json!({"op":"open","id":"s-open","market":"s"}),
|
||||
json!({"op":"fund","id":"s-f1","account":"a","cents":100}),
|
||||
@@ -686,6 +698,12 @@ 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","/v2/value?user=0x0000000000000000000000000000000000000001",String::new(),200,Some(json!({"data":{"proxy_wallet":"0x0000000000000000000000000000000000000001","value":0}}))),
|
||||
("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),
|
||||
("GET","/v2/value?user=0x4d97dcd97ec945f40cf65f87097ace5ea0476045",String::new(),400,None),
|
||||
("POST","/v2/value",String::new(),405,None),
|
||||
("GET","/v2/trades?user=unknown&conditionId=unknown&takerOnly=false",String::new(),200,Some(empty_trades)),
|
||||
("GET","/v2/trades?offset=2",String::new(),400,None),
|
||||
("GET","/v2/trades?cursor=invalid",String::new(),400,None),
|
||||
@@ -850,6 +868,9 @@ mod tests {
|
||||
assert!(headers
|
||||
.to_ascii_lowercase()
|
||||
.contains("content-type: application/json"));
|
||||
if status == 503 {
|
||||
assert!(headers.to_ascii_lowercase().contains("retry-after: 1"));
|
||||
}
|
||||
let actual: Value = serde_json::from_str(body).unwrap();
|
||||
if let Some(expected) = expected {
|
||||
assert_eq!(actual, expected);
|
||||
|
||||
@@ -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
|
||||
```
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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)}}))
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
];
|
||||
@@ -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)))
|
||||
@@ -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,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
|
||||
|
||||
@@ -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)",
|
||||
|
||||
@@ -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(_))
|
||||
));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user