63 lines
2.4 KiB
Rust
63 lines
2.4 KiB
Rust
//! Shared wire checks and financial projections for the trusted native hosts.
|
|
//! Host identities, envelopes and transaction boundaries remain in each adapter.
|
|
use crate::financial::{
|
|
contract::{Counter, Id},
|
|
matching::{ManagedOrder, OrderStatus},
|
|
risk::RiskAccount,
|
|
};
|
|
use napi::{Error, Result};
|
|
use serde::{de::DeserializeOwned, Serialize};
|
|
use serde_json::{json, Value};
|
|
|
|
fn error(error: impl std::fmt::Display) -> Error {
|
|
Error::from_reason(error.to_string())
|
|
}
|
|
|
|
// Some internal replay types accept unknown fields, and serde defaults missing
|
|
// Option fields to None. Comparing recursive keys keeps explicit nulls required
|
|
// at the wire boundary without changing those internal financial types.
|
|
fn keys_match(input: &Value, typed: &Value) -> bool {
|
|
match (input, typed) {
|
|
(Value::Object(a), Value::Object(b)) => {
|
|
a.len() == b.len()
|
|
&& a.iter()
|
|
.all(|(k, v)| b.get(k).is_some_and(|other| keys_match(v, other)))
|
|
}
|
|
(Value::Array(a), Value::Array(b)) => {
|
|
a.len() == b.len() && a.iter().zip(b).all(|(a, b)| keys_match(a, b))
|
|
}
|
|
_ => true,
|
|
}
|
|
}
|
|
|
|
pub(super) fn parse<T: DeserializeOwned + Serialize>(
|
|
input: &str,
|
|
field_error: &'static str,
|
|
) -> Result<T> {
|
|
let raw: Value = serde_json::from_str(input).map_err(error)?;
|
|
let typed: T = serde_json::from_str(input).map_err(error)?;
|
|
if !keys_match(&raw, &serde_json::to_value(&typed).map_err(error)?) {
|
|
return Err(error(field_error));
|
|
}
|
|
Ok(typed)
|
|
}
|
|
|
|
// Revision is explicit: paper journals project intermediate effects at the
|
|
// pre-transaction admission revision; final/replay views use the current one.
|
|
// A lookup supports both the live matching account and paper reconstruction
|
|
// without cloning an account or changing reservation-derived order ordering.
|
|
pub(super) fn financial_view<'a>(
|
|
risk: &RiskAccount,
|
|
revision: Counter,
|
|
order: impl Fn(&Id) -> Option<&'a ManagedOrder>,
|
|
) -> Result<Value> {
|
|
Ok(json!({
|
|
"admissionRevision": revision,
|
|
"portfolio": risk.ledger().economic_snapshot(),
|
|
"equity": risk.ledger().equity().map_err(error)?,
|
|
"availableCash": risk.available_cash(),
|
|
"orders": risk.reservations().filter_map(|r| order(&r.order.order_id)).filter(|o| o.status == OrderStatus::Open).collect::<Vec<_>>(),
|
|
"reservations": risk.reservations().collect::<Vec<_>>(),
|
|
"risk": risk.state(),
|
|
}))
|
|
}
|