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)]
39#[non_exhaustive]
40pub enum PerpDeploy {
41 RegisterAsset2 {
46 max_gas: Option<u64>,
49 asset: NewAsset,
51 margin_mode: MarginMode,
53 dex: DexName,
55 schema: Option<DexSchema>,
57 },
58 RegisterAsset {
61 max_gas: Option<u64>,
64 asset: NewAsset,
66 only_isolated: bool,
68 dex: DexName,
70 schema: Option<DexSchema>,
72 },
73 SetOracle {
76 dex: DexName,
78 oracle_pxs: ByCoin<Dec>,
80 mark_pxs: Vec<ByCoin<Dec>>,
82 external_perp_pxs: ByCoin<Dec>,
84 },
85 SetFundingMultipliers(ByCoin<Dec>),
87 SetFundingInterestRates(ByCoin<Dec>),
89 SetFundingClamps(ByCoin<Dec>),
91 HaltTrading {
93 coin: String,
95 is_halted: bool,
97 },
98 InsertMarginTable {
100 dex: DexName,
102 margin_table: MarginTable,
104 },
105 SetMarginTableIds(ByCoin<u32>),
107 SetFeeRecipient {
109 dex: DexName,
111 fee_recipient: Address,
113 },
114 SetOpenInterestCaps(ByCoin<Option<u64>>),
119 SetSubDeployers {
121 dex: DexName,
123 sub_deployers: Vec<SubDeployer>,
125 },
126 SetMarginModes(ByCoin<MarginMode>),
128 SetDeployerFees(ByCoin<DeployerFee>),
130 SetPerpAnnotation {
132 coin: String,
134 annotation: Annotation,
136 },
137 DisableDex(DexName),
139}
140
141fn by_coin<K: Into<String>, T>(pairs: impl IntoIterator<Item = (K, T)>) -> Result<ByCoin<T>, BadDeploy> {
143 let mut coins = ByCoin::new();
144 for (coin, value) in pairs {
145 match coins.entry(coin.into()) {
146 Entry::Occupied(taken) => return Err(BadDeploy::Twice(taken.key().clone())),
147 Entry::Vacant(slot) => {
148 slot.insert(value);
149 }
150 }
151 }
152 Ok(coins)
153}
154
155fn within(
157 what: &'static str,
158 value: Dec,
159 (least, least_text): (Dec, &'static str),
160 (most, most_text): (Dec, &'static str),
161) -> Result<Dec, BadDeploy> {
162 if value < least || value > most {
163 return Err(BadDeploy::OutOfRange { what, least: least_text, most: most_text, value: value.to_wire() });
164 }
165 Ok(value)
166}
167
168fn checked<T: Copy>(coins: &ByCoin<T>, check: impl Fn(T) -> Result<(), BadDeploy>) -> Result<(), BadDeploy> {
170 coins.values().try_for_each(|value| check(*value))
171}
172
173fn not_negative(what: &'static str, value: Dec) -> Result<(), BadDeploy> {
174 if value.is_negative() {
175 return Err(BadDeploy::OutOfRange { what, least: "0", most: "any", value: value.to_wire() });
176 }
177 Ok(())
178}
179
180fn tuples<T>(coins: &ByCoin<T>, value: impl Fn(&T) -> Value) -> Value {
182 Value::array(coins.iter().map(|(coin, one)| Value::Array(vec![coin.clone().into(), value(one)])))
183}
184
185fn decimals(coins: &ByCoin<Dec>) -> Value {
186 tuples(coins, |value| value.to_wire().into())
187}
188
189const ZERO: (Dec, &str) = (Dec::ZERO, "0");
190const TEN: (Dec, &str) = (Dec::lit::<0>(10), "10");
191const RATE: Dec = Dec::lit::<2>(1);
192
193impl PerpDeploy {
194 pub fn register_asset2(
196 dex: DexName,
197 max_gas: Option<u64>,
198 asset: NewAsset,
199 margin_mode: MarginMode,
200 schema: Option<DexSchema>,
201 ) -> Result<Self, BadDeploy> {
202 not_negative("oraclePx", asset.oracle_px)?;
203 Ok(PerpDeploy::RegisterAsset2 { max_gas, asset, margin_mode, dex, schema })
204 }
205
206 pub fn register_asset(
208 dex: DexName,
209 max_gas: Option<u64>,
210 asset: NewAsset,
211 only_isolated: bool,
212 schema: Option<DexSchema>,
213 ) -> Result<Self, BadDeploy> {
214 not_negative("oraclePx", asset.oracle_px)?;
215 Ok(PerpDeploy::RegisterAsset { max_gas, asset, only_isolated, dex, schema })
216 }
217
218 pub fn set_oracle<K: Into<String>>(
220 dex: DexName,
221 oracle_pxs: impl IntoIterator<Item = (K, Dec)>,
222 mark_pxs: Vec<Vec<(K, Dec)>>,
223 external_perp_pxs: impl IntoIterator<Item = (K, Dec)>,
224 ) -> Result<Self, BadDeploy> {
225 if mark_pxs.len() > 2 {
226 return Err(BadDeploy::MarkPxs(mark_pxs.len()));
227 }
228 let oracle_pxs = by_coin(oracle_pxs)?;
229 let mark_pxs = mark_pxs.into_iter().map(by_coin).collect::<Result<Vec<_>, _>>()?;
230 let external_perp_pxs = by_coin(external_perp_pxs)?;
231 checked(&oracle_pxs, |px| not_negative("an oracle price", px))?;
232 mark_pxs.iter().try_for_each(|marks| checked(marks, |px| not_negative("a mark price", px)))?;
233 checked(&external_perp_pxs, |px| not_negative("an external perp price", px))?;
234 Ok(PerpDeploy::SetOracle { dex, oracle_pxs, mark_pxs, external_perp_pxs })
235 }
236
237 pub fn set_funding_multipliers<K: Into<String>>(
239 multipliers: impl IntoIterator<Item = (K, Dec)>,
240 ) -> Result<Self, BadDeploy> {
241 let multipliers = by_coin(multipliers)?;
242 checked(&multipliers, |value| within("a funding multiplier", value, ZERO, TEN).map(drop))?;
243 Ok(PerpDeploy::SetFundingMultipliers(multipliers))
244 }
245
246 pub fn set_funding_interest_rates<K: Into<String>>(
248 rates: impl IntoIterator<Item = (K, Dec)>,
249 ) -> Result<Self, BadDeploy> {
250 let rates = by_coin(rates)?;
251 checked(&rates, |value| {
252 within("a funding interest rate", value, (RATE.negate(), "-0.01"), (RATE, "0.01")).map(drop)
253 })?;
254 Ok(PerpDeploy::SetFundingInterestRates(rates))
255 }
256
257 pub fn set_funding_clamps<K: Into<String>>(clamps: impl IntoIterator<Item = (K, Dec)>) -> Result<Self, BadDeploy> {
259 let clamps = by_coin(clamps)?;
260 checked(&clamps, |value| within("a funding clamp", value, ZERO, (RATE, "0.01")).map(drop))?;
261 Ok(PerpDeploy::SetFundingClamps(clamps))
262 }
263
264 pub fn set_margin_table_ids<K: Into<String>>(ids: impl IntoIterator<Item = (K, u32)>) -> Result<Self, BadDeploy> {
266 let ids = by_coin(ids)?;
267 if let Some((coin, _)) = ids.iter().find(|(_, id)| **id == 0) {
268 return Err(BadDeploy::MarginTableZero(coin.clone()));
269 }
270 Ok(PerpDeploy::SetMarginTableIds(ids))
271 }
272
273 pub fn set_open_interest_caps<K: Into<String>>(
276 caps: impl IntoIterator<Item = (K, Option<u64>)>,
277 ) -> Result<Self, BadDeploy> {
278 Ok(PerpDeploy::SetOpenInterestCaps(by_coin(caps)?))
279 }
280
281 pub fn set_sub_deployers(dex: DexName, sub_deployers: Vec<SubDeployer>) -> Result<Self, BadDeploy> {
283 if sub_deployers.is_empty() {
284 return Err(BadDeploy::NoGrants);
285 }
286 Ok(PerpDeploy::SetSubDeployers { dex, sub_deployers })
287 }
288
289 pub fn set_margin_modes<K: Into<String>>(
291 modes: impl IntoIterator<Item = (K, MarginMode)>,
292 ) -> Result<Self, BadDeploy> {
293 Ok(PerpDeploy::SetMarginModes(by_coin(modes)?))
294 }
295
296 pub fn set_deployer_fees<K: Into<String>>(
299 fees: impl IntoIterator<Item = (K, DeployerFee)>,
300 ) -> Result<Self, BadDeploy> {
301 let fees = by_coin(fees)?;
302 checked(&fees, |fee| {
303 if fee.growth_mode {
304 if fee.scale >= TEN.0 {
305 return Err(BadDeploy::OutOfRange {
306 what: "a growth mode fee scale",
307 least: "0",
308 most: "just under 10",
309 value: fee.scale.to_wire(),
310 });
311 }
312 not_negative("a growth mode fee scale", fee.scale)
313 } else {
314 within("a fee scale", fee.scale, ZERO, (Dec::lit::<0>(3), "3")).map(drop)
315 }
316 })?;
317 Ok(PerpDeploy::SetDeployerFees(fees))
318 }
319
320 #[must_use]
322 pub const fn kind(&self) -> PerpKind {
323 match self {
324 PerpDeploy::RegisterAsset2 { .. } => PerpKind::RegisterAsset2,
325 PerpDeploy::RegisterAsset { .. } => PerpKind::RegisterAsset,
326 PerpDeploy::SetOracle { .. } => PerpKind::SetOracle,
327 PerpDeploy::SetFundingMultipliers(_) => PerpKind::SetFundingMultipliers,
328 PerpDeploy::SetFundingInterestRates(_) => PerpKind::SetFundingInterestRates,
329 PerpDeploy::SetFundingClamps(_) => PerpKind::SetFundingClamps,
330 PerpDeploy::HaltTrading { .. } => PerpKind::HaltTrading,
331 PerpDeploy::InsertMarginTable { .. } => PerpKind::InsertMarginTable,
332 PerpDeploy::SetMarginTableIds(_) => PerpKind::SetMarginTableIds,
333 PerpDeploy::SetFeeRecipient { .. } => PerpKind::SetFeeRecipient,
334 PerpDeploy::SetOpenInterestCaps(_) => PerpKind::SetOpenInterestCaps,
335 PerpDeploy::SetSubDeployers { .. } => PerpKind::SetSubDeployers,
336 PerpDeploy::SetMarginModes(_) => PerpKind::SetMarginModes,
337 PerpDeploy::SetDeployerFees(_) => PerpKind::SetDeployerFees,
338 PerpDeploy::SetPerpAnnotation { .. } => PerpKind::SetPerpAnnotation,
339 PerpDeploy::DisableDex(_) => PerpKind::DisableDex,
340 }
341 }
342
343 #[must_use]
346 pub fn body(&self) -> Value {
347 let gas = |max_gas: &Option<u64>| max_gas.map_or(Value::Nil, Value::from);
348 let schema = |schema: &Option<DexSchema>| schema.as_ref().map_or(Value::Nil, |one| one.wire().into());
349 match self {
350 PerpDeploy::RegisterAsset2 { max_gas, asset, margin_mode, dex, schema: new } => Map::new()
351 .put("maxGas", gas(max_gas))
352 .put("assetRequest", asset.wire().put("marginMode", margin_mode.wire()))
353 .put("dex", dex.as_str().to_owned())
354 .put("schema", schema(new))
355 .into(),
356 PerpDeploy::RegisterAsset { max_gas, asset, only_isolated, dex, schema: new } => Map::new()
357 .put("maxGas", gas(max_gas))
358 .put("assetRequest", asset.wire().put("onlyIsolated", *only_isolated))
359 .put("dex", dex.as_str().to_owned())
360 .put("schema", schema(new))
361 .into(),
362 PerpDeploy::SetOracle { dex, oracle_pxs, mark_pxs, external_perp_pxs } => Map::new()
363 .put("dex", dex.as_str().to_owned())
364 .put("oraclePxs", decimals(oracle_pxs))
365 .put("markPxs", Value::array(mark_pxs.iter().map(decimals)))
366 .put("externalPerpPxs", decimals(external_perp_pxs))
367 .into(),
368 PerpDeploy::SetFundingMultipliers(values)
369 | PerpDeploy::SetFundingInterestRates(values)
370 | PerpDeploy::SetFundingClamps(values) => decimals(values),
371 PerpDeploy::HaltTrading { coin, is_halted } => {
372 Map::new().put("coin", coin.clone()).put("isHalted", *is_halted).into()
373 }
374 PerpDeploy::InsertMarginTable { dex, margin_table } => {
375 Map::new().put("dex", dex.as_str().to_owned()).put("marginTable", margin_table.wire()).into()
376 }
377 PerpDeploy::SetMarginTableIds(ids) => tuples(ids, |id| (*id).into()),
378 PerpDeploy::SetFeeRecipient { dex, fee_recipient } => {
379 Map::new().put("dex", dex.as_str().to_owned()).put("feeRecipient", fee_recipient.to_hex()).into()
380 }
381 PerpDeploy::SetOpenInterestCaps(caps) => tuples(caps, |cap| cap.map_or(Value::Nil, Value::from)),
382 PerpDeploy::SetSubDeployers { dex, sub_deployers } => Map::new()
383 .put("dex", dex.as_str().to_owned())
384 .put("subDeployers", Value::array(sub_deployers.iter().map(SubDeployer::wire)))
385 .into(),
386 PerpDeploy::SetMarginModes(modes) => tuples(modes, |mode| mode.wire().into()),
387 PerpDeploy::SetDeployerFees(fees) => tuples(fees, |fee| {
388 Map::new().put("scale", fee.scale.to_wire()).put("growthMode", fee.growth_mode).into()
389 }),
390 PerpDeploy::SetPerpAnnotation { coin, annotation } => {
391 annotation.wire_after(Map::new().put("coin", coin.clone())).into()
392 }
393 PerpDeploy::DisableDex(dex) => dex.as_str().to_owned().into(),
394 }
395 }
396}
397
398impl L1Action for PerpDeploy {
399 fn action(&self) -> Map {
400 Map::new().put("type", "perpDeploy").put(self.kind().wire(), self.body())
401 }
402}
403
404#[cfg(test)]
405#[path = "tests/perp.rs"]
406mod tests;