use crate::deploy::error::BadDeploy;
use crate::utils::sign::{Map, Value};
pub const MAX_LEVERAGE: u32 = 50;
pub const MAX_TIERS: usize = 3;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MarginTier {
pub lower_bound: u64,
pub max_leverage: u32,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MarginTable {
description: String,
tiers: Vec<MarginTier>,
}
impl MarginTable {
pub fn new(description: impl Into<String>, tiers: Vec<MarginTier>) -> Result<Self, BadDeploy> {
let in_range = tiers.iter().all(|tier| (1..=MAX_LEVERAGE).contains(&tier.max_leverage));
let ordered = tiers
.windows(2)
.all(|two| two[0].lower_bound < two[1].lower_bound && two[0].max_leverage > two[1].max_leverage);
if tiers.is_empty() || tiers.len() > MAX_TIERS || !in_range || !ordered {
return Err(BadDeploy::MarginTiers);
}
Ok(MarginTable { description: description.into(), tiers })
}
#[must_use]
pub fn description(&self) -> &str {
&self.description
}
#[must_use]
pub fn tiers(&self) -> &[MarginTier] {
&self.tiers
}
#[must_use]
pub fn wire(&self) -> Map {
let tiers = self
.tiers
.iter()
.map(|tier| Map::new().put("lowerBound", tier.lower_bound).put("maxLeverage", tier.max_leverage));
Map::new().put("description", self.description.clone()).put("marginTiers", Value::array(tiers))
}
}