89 lines
3.0 KiB
Rust
89 lines
3.0 KiB
Rust
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)}}))
|
|
}
|
|
}
|