1pub mod asset;
6pub mod margin;
7pub mod sub;
8
9pub use asset::{DexSchema, MarginMode, NewAsset};
10pub use margin::{MarginTable, MarginTier};
11pub use sub::{PerpKind, SubDeployer};
12
13use std::collections::{BTreeMap, btree_map::Entry};
14
15use crate::deploy::annotation::Annotation;
16use crate::deploy::error::BadDeploy;
17use crate::deploy::name::DexName;
18use crate::utils::sign::{L1Action, Map, Value};
19use crate::utils::{Address, Dec};
20
21pub type ByCoin<T> = BTreeMap<String, T>;
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub struct DeployerFee {
29 pub scale: Dec,
31 pub growth_mode: bool,
33}
34
35#[derive(Debug, Clone, PartialEq, Eq)]
39pub enum PerpDeploy {
40 RegisterAsset2 {
45 max_gas: Option<u64>,
48 asset: NewAsset,
50 margin_mode: MarginMode,
52 dex: DexName,
54 schema: Option<DexSchema>,
56 },
57 RegisterAsset {
60 max_gas: Option<u64>,
63 asset: NewAsset,
65 only_isolated: bool,
67 dex: DexName,
69 schema: Option<DexSchema>,
71 },
72 SetOracle {
75 dex: DexName,
77 oracle_pxs: ByCoin<Dec>,
79 mark_pxs: Vec<ByCoin<Dec>>,
81 external_perp_pxs: ByCoin<Dec>,
83 },
84 SetFundingMultipliers(ByCoin<Dec>),
86 SetFundingInterestRates(ByCoin<Dec>),
88 SetFundingClamps(ByCoin<Dec>),
90 HaltTrading {
92 coin: String,
94 is_halted: bool,
96 },
97 InsertMarginTable {
99 dex: DexName,
101 margin_table: MarginTable,
103 },
104 SetMarginTableIds(ByCoin<u32>),
106 SetFeeRecipient {
108 dex: DexName,
110 fee_recipient: Address,
112 },
113 SetOpenInterestCaps(ByCoin<Option<u64>>),
118 SetSubDeployers {
120 dex: DexName,
122 sub_deployers: Vec<SubDeployer>,
124 },
125 SetMarginModes(ByCoin<MarginMode>),
127 SetDeployerFees(ByCoin<DeployerFee>),
129 SetPerpAnnotation {
131 coin: String,
133 annotation: Annotation,
135 },
136 DisableDex(DexName),
138}
139
140fn by_coin<K: Into<String>, T>(pairs: impl IntoIterator<Item = (K, T)>) -> Result<ByCoin<T>, BadDeploy> {
142 let mut coins = ByCoin::new();
143 for (coin, value) in pairs {
144 match coins.entry(coin.into()) {
145 Entry::Occupied(taken) => return Err(BadDeploy::Twice(taken.key().clone())),
146 Entry::Vacant(slot) => {
147 slot.insert(value);
148 }
149 }
150 }
151 Ok(coins)
152}
153
154fn within(
156 what: &'static str,
157 value: Dec,
158 (least, least_text): (Dec, &'static str),
159 (most, most_text): (Dec, &'static str),
160) -> Result<Dec, BadDeploy> {
161 if value < least || value > most {
162 return Err(BadDeploy::OutOfRange { what, least: least_text, most: most_text, value: value.to_wire() });
163 }
164 Ok(value)
165}
166
167fn checked<T: Copy>(coins: &ByCoin<T>, check: impl Fn(T) -> Result<(), BadDeploy>) -> Result<(), BadDeploy> {
169 coins.values().try_for_each(|value| check(*value))
170}
171
172fn not_negative(what: &'static str, value: Dec) -> Result<(), BadDeploy> {
173 if value.is_negative() {
174 return Err(BadDeploy::OutOfRange { what, least: "0", most: "any", value: value.to_wire() });
175 }
176 Ok(())
177}
178
179fn tuples<T>(coins: &ByCoin<T>, value: impl Fn(&T) -> Value) -> Value {
181 Value::array(coins.iter().map(|(coin, one)| Value::Array(vec![coin.clone().into(), value(one)])))
182}
183
184fn decimals(coins: &ByCoin<Dec>) -> Value {
185 tuples(coins, |value| value.to_wire().into())
186}
187
188const ZERO: (Dec, &str) = (Dec::ZERO, "0");
189const TEN: (Dec, &str) = (Dec::lit::<0>(10), "10");
190const RATE: Dec = Dec::lit::<2>(1);
191
192impl PerpDeploy {
193 pub fn register_asset2(
195 dex: DexName,
196 max_gas: Option<u64>,
197 asset: NewAsset,
198 margin_mode: MarginMode,
199 schema: Option<DexSchema>,
200 ) -> Result<Self, BadDeploy> {
201 not_negative("oraclePx", asset.oracle_px)?;
202 Ok(PerpDeploy::RegisterAsset2 { max_gas, asset, margin_mode, dex, schema })
203 }
204
205 pub fn register_asset(
207 dex: DexName,
208 max_gas: Option<u64>,
209 asset: NewAsset,
210 only_isolated: bool,
211 schema: Option<DexSchema>,
212 ) -> Result<Self, BadDeploy> {
213 not_negative("oraclePx", asset.oracle_px)?;
214 Ok(PerpDeploy::RegisterAsset { max_gas, asset, only_isolated, dex, schema })
215 }
216
217 pub fn set_oracle<K: Into<String>>(
219 dex: DexName,
220 oracle_pxs: impl IntoIterator<Item = (K, Dec)>,
221 mark_pxs: Vec<Vec<(K, Dec)>>,
222 external_perp_pxs: impl IntoIterator<Item = (K, Dec)>,
223 ) -> Result<Self, BadDeploy> {
224 if mark_pxs.len() > 2 {
225 return Err(BadDeploy::MarkPxs(mark_pxs.len()));
226 }
227 let oracle_pxs = by_coin(oracle_pxs)?;
228 let mark_pxs = mark_pxs.into_iter().map(by_coin).collect::<Result<Vec<_>, _>>()?;
229 let external_perp_pxs = by_coin(external_perp_pxs)?;
230 checked(&oracle_pxs, |px| not_negative("an oracle price", px))?;
231 mark_pxs.iter().try_for_each(|marks| checked(marks, |px| not_negative("a mark price", px)))?;
232 checked(&external_perp_pxs, |px| not_negative("an external perp price", px))?;
233 Ok(PerpDeploy::SetOracle { dex, oracle_pxs, mark_pxs, external_perp_pxs })
234 }
235
236 pub fn set_funding_multipliers<K: Into<String>>(
238 multipliers: impl IntoIterator<Item = (K, Dec)>,
239 ) -> Result<Self, BadDeploy> {
240 let multipliers = by_coin(multipliers)?;
241 checked(&multipliers, |value| within("a funding multiplier", value, ZERO, TEN).map(drop))?;
242 Ok(PerpDeploy::SetFundingMultipliers(multipliers))
243 }
244
245 pub fn set_funding_interest_rates<K: Into<String>>(
247 rates: impl IntoIterator<Item = (K, Dec)>,
248 ) -> Result<Self, BadDeploy> {
249 let rates = by_coin(rates)?;
250 checked(&rates, |value| {
251 within("a funding interest rate", value, (RATE.negate(), "-0.01"), (RATE, "0.01")).map(drop)
252 })?;
253 Ok(PerpDeploy::SetFundingInterestRates(rates))
254 }
255
256 pub fn set_funding_clamps<K: Into<String>>(clamps: impl IntoIterator<Item = (K, Dec)>) -> Result<Self, BadDeploy> {
258 let clamps = by_coin(clamps)?;
259 checked(&clamps, |value| within("a funding clamp", value, ZERO, (RATE, "0.01")).map(drop))?;
260 Ok(PerpDeploy::SetFundingClamps(clamps))
261 }
262
263 pub fn set_margin_table_ids<K: Into<String>>(ids: impl IntoIterator<Item = (K, u32)>) -> Result<Self, BadDeploy> {
265 let ids = by_coin(ids)?;
266 if let Some((coin, _)) = ids.iter().find(|(_, id)| **id == 0) {
267 return Err(BadDeploy::MarginTableZero(coin.clone()));
268 }
269 Ok(PerpDeploy::SetMarginTableIds(ids))
270 }
271
272 pub fn set_open_interest_caps<K: Into<String>>(
275 caps: impl IntoIterator<Item = (K, Option<u64>)>,
276 ) -> Result<Self, BadDeploy> {
277 Ok(PerpDeploy::SetOpenInterestCaps(by_coin(caps)?))
278 }
279
280 pub fn set_sub_deployers(dex: DexName, sub_deployers: Vec<SubDeployer>) -> Result<Self, BadDeploy> {
282 if sub_deployers.is_empty() {
283 return Err(BadDeploy::NoGrants);
284 }
285 Ok(PerpDeploy::SetSubDeployers { dex, sub_deployers })
286 }
287
288 pub fn set_margin_modes<K: Into<String>>(
290 modes: impl IntoIterator<Item = (K, MarginMode)>,
291 ) -> Result<Self, BadDeploy> {
292 Ok(PerpDeploy::SetMarginModes(by_coin(modes)?))
293 }
294
295 pub fn set_deployer_fees<K: Into<String>>(
298 fees: impl IntoIterator<Item = (K, DeployerFee)>,
299 ) -> Result<Self, BadDeploy> {
300 let fees = by_coin(fees)?;
301 checked(&fees, |fee| {
302 if fee.growth_mode {
303 if fee.scale >= TEN.0 {
304 return Err(BadDeploy::OutOfRange {
305 what: "a growth mode fee scale",
306 least: "0",
307 most: "just under 10",
308 value: fee.scale.to_wire(),
309 });
310 }
311 not_negative("a growth mode fee scale", fee.scale)
312 } else {
313 within("a fee scale", fee.scale, ZERO, (Dec::lit::<0>(3), "3")).map(drop)
314 }
315 })?;
316 Ok(PerpDeploy::SetDeployerFees(fees))
317 }
318
319 #[must_use]
321 pub const fn kind(&self) -> PerpKind {
322 match self {
323 PerpDeploy::RegisterAsset2 { .. } => PerpKind::RegisterAsset2,
324 PerpDeploy::RegisterAsset { .. } => PerpKind::RegisterAsset,
325 PerpDeploy::SetOracle { .. } => PerpKind::SetOracle,
326 PerpDeploy::SetFundingMultipliers(_) => PerpKind::SetFundingMultipliers,
327 PerpDeploy::SetFundingInterestRates(_) => PerpKind::SetFundingInterestRates,
328 PerpDeploy::SetFundingClamps(_) => PerpKind::SetFundingClamps,
329 PerpDeploy::HaltTrading { .. } => PerpKind::HaltTrading,
330 PerpDeploy::InsertMarginTable { .. } => PerpKind::InsertMarginTable,
331 PerpDeploy::SetMarginTableIds(_) => PerpKind::SetMarginTableIds,
332 PerpDeploy::SetFeeRecipient { .. } => PerpKind::SetFeeRecipient,
333 PerpDeploy::SetOpenInterestCaps(_) => PerpKind::SetOpenInterestCaps,
334 PerpDeploy::SetSubDeployers { .. } => PerpKind::SetSubDeployers,
335 PerpDeploy::SetMarginModes(_) => PerpKind::SetMarginModes,
336 PerpDeploy::SetDeployerFees(_) => PerpKind::SetDeployerFees,
337 PerpDeploy::SetPerpAnnotation { .. } => PerpKind::SetPerpAnnotation,
338 PerpDeploy::DisableDex(_) => PerpKind::DisableDex,
339 }
340 }
341
342 #[must_use]
345 pub fn body(&self) -> Value {
346 let gas = |max_gas: &Option<u64>| max_gas.map_or(Value::Nil, Value::from);
347 let schema = |schema: &Option<DexSchema>| schema.as_ref().map_or(Value::Nil, |one| one.wire().into());
348 match self {
349 PerpDeploy::RegisterAsset2 { max_gas, asset, margin_mode, dex, schema: new } => Map::new()
350 .put("maxGas", gas(max_gas))
351 .put("assetRequest", asset.wire().put("marginMode", margin_mode.wire()))
352 .put("dex", dex.as_str().to_owned())
353 .put("schema", schema(new))
354 .into(),
355 PerpDeploy::RegisterAsset { max_gas, asset, only_isolated, dex, schema: new } => Map::new()
356 .put("maxGas", gas(max_gas))
357 .put("assetRequest", asset.wire().put("onlyIsolated", *only_isolated))
358 .put("dex", dex.as_str().to_owned())
359 .put("schema", schema(new))
360 .into(),
361 PerpDeploy::SetOracle { dex, oracle_pxs, mark_pxs, external_perp_pxs } => Map::new()
362 .put("dex", dex.as_str().to_owned())
363 .put("oraclePxs", decimals(oracle_pxs))
364 .put("markPxs", Value::array(mark_pxs.iter().map(decimals)))
365 .put("externalPerpPxs", decimals(external_perp_pxs))
366 .into(),
367 PerpDeploy::SetFundingMultipliers(values)
368 | PerpDeploy::SetFundingInterestRates(values)
369 | PerpDeploy::SetFundingClamps(values) => decimals(values),
370 PerpDeploy::HaltTrading { coin, is_halted } => {
371 Map::new().put("coin", coin.clone()).put("isHalted", *is_halted).into()
372 }
373 PerpDeploy::InsertMarginTable { dex, margin_table } => {
374 Map::new().put("dex", dex.as_str().to_owned()).put("marginTable", margin_table.wire()).into()
375 }
376 PerpDeploy::SetMarginTableIds(ids) => tuples(ids, |id| (*id).into()),
377 PerpDeploy::SetFeeRecipient { dex, fee_recipient } => {
378 Map::new().put("dex", dex.as_str().to_owned()).put("feeRecipient", fee_recipient.to_hex()).into()
379 }
380 PerpDeploy::SetOpenInterestCaps(caps) => tuples(caps, |cap| cap.map_or(Value::Nil, Value::from)),
381 PerpDeploy::SetSubDeployers { dex, sub_deployers } => Map::new()
382 .put("dex", dex.as_str().to_owned())
383 .put("subDeployers", Value::array(sub_deployers.iter().map(SubDeployer::wire)))
384 .into(),
385 PerpDeploy::SetMarginModes(modes) => tuples(modes, |mode| mode.wire().into()),
386 PerpDeploy::SetDeployerFees(fees) => tuples(fees, |fee| {
387 Map::new().put("scale", fee.scale.to_wire()).put("growthMode", fee.growth_mode).into()
388 }),
389 PerpDeploy::SetPerpAnnotation { coin, annotation } => {
390 annotation.wire_after(Map::new().put("coin", coin.clone())).into()
391 }
392 PerpDeploy::DisableDex(dex) => dex.as_str().to_owned().into(),
393 }
394 }
395}
396
397impl L1Action for PerpDeploy {
398 fn action(&self) -> Map {
399 Map::new().put("type", "perpDeploy").put(self.kind().wire(), self.body())
400 }
401}
402
403#[cfg(test)]
404#[path = "tests/perp.rs"]
405mod tests;