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