Serve condition-scoped portfolio valuations from marked holdings
This commit is contained in:
@@ -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)",
|
||||
|
||||
Reference in New Issue
Block a user