59 lines
2.1 KiB
Rust
59 lines
2.1 KiB
Rust
use super::{marked_holdings, protocol::CONTRACTS};
|
|
use crate::{
|
|
expiry,
|
|
inventory::decimal,
|
|
validation::{condition_filter, hex_id},
|
|
Exchange, MarketDataError,
|
|
};
|
|
use rusqlite::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 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 = condition_filter(query.condition.as_deref(), &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)}}))
|
|
}
|
|
}
|