af_iperps/lib.rs
1#![cfg_attr(all(doc, not(doctest)), feature(doc_auto_cfg))]
2
3//! Move types for Aftermath's `Perpetuals` package
4
5use af_move_type::otw::Otw;
6use af_sui_pkg_sdk::sui_pkg_sdk;
7use af_sui_types::{hex_address_bytes, ObjectId};
8use af_utilities::types::ifixed::IFixed;
9use sui_framework_sdk::balance::Balance;
10use sui_framework_sdk::object::{ID, UID};
11
12pub mod errors;
13pub mod event_ext;
14pub mod event_instance;
15#[cfg(feature = "graphql")]
16pub mod graphql;
17pub mod math;
18pub mod order_helpers;
19pub mod order_id;
20#[cfg(feature = "slo")]
21pub mod slo;
22
23// Convenient aliases since these types will never exist onchain with a type argument other than an
24// OTW.
25pub type Account = account::Account<Otw>;
26pub type AccountTypeTag = account::AccountTypeTag<Otw>;
27pub type ClearingHouse = clearing_house::ClearingHouse<Otw>;
28pub type ClearingHouseTypeTag = clearing_house::ClearingHouseTypeTag<Otw>;
29pub type SubAccount = subaccount::SubAccount<Otw>;
30pub type SubAccountTypeTag = subaccount::SubAccountTypeTag<Otw>;
31pub type Vault = clearing_house::Vault<Otw>;
32pub type VaultTypeTag = clearing_house::VaultTypeTag<Otw>;
33
34/// Package IDs of the perpetuals contract versions published on testnet, in order of its versions.
35pub const TESTNET_PACKAGE_VERSIONS: &[ObjectId] = &[ObjectId::new(hex_address_bytes(
36 b"0x9725155a70cf2d2241b8cc2fa8376809689312cabb4acaa5ca5ba47eaf4d611f",
37))];
38
39sui_pkg_sdk!(perpetuals {
40 module account {
41 /// The Account object saves the collateral available to be used in clearing houses.
42 struct Account<!phantom T> has key, store {
43 id: UID,
44 /// Numerical value associated to the account
45 account_id: u64,
46 /// Balance available to be allocated to markets.
47 collateral: Balance<T>,
48 }
49
50 /// Object that allows to place one order on behalf of the user, used to
51 /// offer stop limit or market orders. A stop order is an order that is placed
52 /// only if the index price respects certain conditions, like being above or
53 /// below a certain price.
54 ///
55 /// Only the `Account` owner can mint this object and can decide who is
56 /// going to be the recipient of the ticket. This allows users to run their
57 /// own stop orders bots eventually, but it's mainly used to allow 3rd parties
58 /// to offer such a service (the user is required to trust such 3rd party).
59 /// The object is intended to be sent to a multisig wallet owned by
60 /// both the 3rd party and the user. The object is not transferable, stopping
61 /// the 3rd party from transferring it away, and can be destroyed in any moment
62 /// only by the user. The user needs to trust the 3rd party for liveness of the
63 /// service offered.
64 ///
65 /// The order details are encrypted offchain and the result is stored in the ticket.
66 /// The user needs to share such details with the 3rd party only.
67 struct StopOrderTicket<!phantom T> has key {
68 id: UID,
69 /// Save user address. This allow only the user to cancel the ticket eventually.
70 user_address: address,
71 /// Timestamp after which the order cannot be placed anymore
72 expire_timestamp: u64,
73 /// Vector containing the blake2b hash obtained by the offchain
74 /// application of blake2b on the following parameters:
75 /// - clearing_house_id: ID
76 /// - account_id: u64
77 /// - is_limit_order: `true` if limit order, `false` if market order
78 /// - stop_index_price: u256
79 /// - ge_stop_index_price: `true` means the order can be placed when
80 /// oracle index price is >= than chosen `stop_index_price`
81 /// - side: bool
82 /// - size: u64
83 /// - price: u64 (can be set at random value if `is_limit_order` is false)
84 /// - order_type: u64 (can be set at random value if `is_limit_order` is false)
85 /// - salt: vector<u8>
86 encrypted_details: vector<u8>
87 }
88 }
89
90 module admin {
91 /// Capability object required to perform admin functions.
92 ///
93 /// Minted once when the module is published and transfered to its creator.
94 struct AdminCapability has key, store {
95 id: UID
96 }
97 }
98
99 module clearing_house {
100 /// The central object that owns the market state.
101 ///
102 /// Dynamic fields:
103 /// - [`position::Position`]
104 /// - [`Vault`]
105 ///
106 /// Dynamic objects:
107 /// - [`orderbook::Orderbook`]
108 struct ClearingHouse<!phantom T> has key {
109 id: UID,
110 version: u64,
111 market_params: market::MarketParams,
112 market_state: market::MarketState
113 }
114
115 /// Stores all deposits from traders for collateral T.
116 /// Stores the funds reserved for covering bad debt from untimely
117 /// liquidations.
118 ///
119 /// The Clearing House keeps track of who owns each share of the vault.
120 struct Vault<!phantom T> has store {
121 collateral_balance: Balance<T>,
122 insurance_fund_balance: Balance<T>,
123 scaling_factor: IFixed
124 }
125
126 /// Stores the proposed parameters for updating margin ratios
127 struct MarginRatioProposal has store {
128 /// Target timestamp at which to apply the proposed updates
129 maturity: u64,
130 /// Proposed IMR
131 margin_ratio_initial: IFixed,
132 /// Proposed MMR
133 margin_ratio_maintenance: IFixed,
134 }
135
136 /// Stores the proposed parameters for a position's custom fees
137 struct PositionFeesProposal has store {
138 /// Proposed IMR
139 maker_fee: IFixed,
140 /// Proposed MMR
141 taker_fee: IFixed,
142 }
143
144 /// Used by clearing house to check margin when placing an order
145 struct SessionHotPotato<!phantom T> {
146 clearing_house: ClearingHouse<T>,
147 account_id: u64,
148 timestamp_ms: u64,
149 collateral_price: IFixed,
150 index_price: IFixed,
151 book_price: IFixed,
152 margin_before: IFixed,
153 min_margin_before: IFixed,
154 fills: vector<orderbook::FillReceipt>,
155 post: orderbook::PostReceipt,
156 liquidation_receipt: move_stdlib_sdk::option::Option<LiquidationReceipt>
157 }
158
159 struct LiquidationReceipt has drop, store {
160 liqee_account_id: u64,
161 size_to_liquidate: u64,
162 base_ask_cancel: u64,
163 base_bid_cancel: u64,
164 pending_orders: u64
165 }
166
167 struct SessionSummary has drop {
168 base_filled_ask: IFixed,
169 base_filled_bid: IFixed,
170 quote_filled_ask: IFixed,
171 quote_filled_bid: IFixed,
172 base_posted_ask: IFixed,
173 base_posted_bid: IFixed,
174 /// This would be the `mark_price` used in the eventuality the session contains a liquidation.
175 /// Set at 0 in case there is no liquidation in the session.
176 mark_price: IFixed,
177 bad_debt: IFixed
178 }
179 }
180
181 module subaccount {
182 /// The SubAccount object represents an `Account` object with limited access to
183 /// protocol's features. Being a shared object, it can only be used by the address
184 /// specified in the `user` field.
185 struct SubAccount<!phantom T> has key, store {
186 id: UID,
187 /// Address able to make calls using this `SubAccount`
188 user: address,
189 /// Numerical value associated to the parent account
190 account_id: u64,
191 /// Balance available to be allocated to markets.
192 collateral: Balance<T>,
193 }
194
195 }
196
197 module events {
198 struct CreatedAccount<!phantom T> has copy, drop {
199 user: address,
200 account_id: u64
201 }
202
203 struct DepositedCollateral<!phantom T> has copy, drop {
204 account_id: u64,
205 collateral: u64,
206 account_collateral_after: u64
207 }
208
209 struct AllocatedCollateral has copy, drop {
210 ch_id: ID,
211 account_id: u64,
212 collateral: u64,
213 account_collateral_after: u64,
214 position_collateral_after: IFixed,
215 vault_balance_after: u64
216 }
217
218 struct WithdrewCollateral<!phantom T> has copy, drop {
219 account_id: u64,
220 collateral: u64,
221 account_collateral_after: u64
222 }
223
224 struct DeallocatedCollateral has copy, drop {
225 ch_id: ID,
226 account_id: u64,
227 collateral: u64,
228 account_collateral_after: u64,
229 position_collateral_after: IFixed,
230 vault_balance_after: u64
231 }
232
233 struct CreatedOrderbook has copy, drop {
234 branch_min: u64,
235 branches_merge_max: u64,
236 branch_max: u64,
237 leaf_min: u64,
238 leaves_merge_max: u64,
239 leaf_max: u64
240 }
241
242 struct CreatedClearingHouse has copy, drop {
243 ch_id: ID,
244 collateral: String,
245 coin_decimals: u64,
246 margin_ratio_initial: IFixed,
247 margin_ratio_maintenance: IFixed,
248 base_oracle_id: ID,
249 collateral_oracle_id: ID,
250 funding_frequency_ms: u64,
251 funding_period_ms: u64,
252 premium_twap_frequency_ms: u64,
253 premium_twap_period_ms: u64,
254 spread_twap_frequency_ms: u64,
255 spread_twap_period_ms: u64,
256 maker_fee: IFixed,
257 taker_fee: IFixed,
258 liquidation_fee: IFixed,
259 force_cancel_fee: IFixed,
260 insurance_fund_fee: IFixed,
261 lot_size: u64,
262 tick_size: u64,
263 }
264
265 struct RegisteredMarketInfo<!phantom T> has copy, drop {
266 ch_id: ID,
267 base_pfs_id: ID,
268 collateral_pfs_id: ID,
269 lot_size: u64,
270 tick_size: u64,
271 scaling_factor: IFixed
272 }
273
274 struct RemovedRegisteredMarketInfo<!phantom T> has copy, drop {
275 ch_id: ID,
276 }
277
278 struct RegisteredCollateralInfo<!phantom T> has copy, drop {
279 ch_id: ID,
280 collateral_pfs_id: ID,
281 scaling_factor: IFixed
282 }
283
284 struct UpdatedClearingHouseVersion has copy, drop {
285 ch_id: ID,
286 version: u64
287 }
288
289 struct UpdatedPremiumTwap has copy, drop {
290 ch_id: ID,
291 book_price: IFixed,
292 index_price: IFixed,
293 premium_twap: IFixed,
294 premium_twap_last_upd_ms: u64,
295 }
296
297 struct UpdatedSpreadTwap has copy, drop {
298 ch_id: ID,
299 book_price: IFixed,
300 index_price: IFixed,
301 spread_twap: IFixed,
302 spread_twap_last_upd_ms: u64,
303 }
304
305 struct UpdatedFunding has copy, drop {
306 ch_id: ID,
307 cum_funding_rate_long: IFixed,
308 cum_funding_rate_short: IFixed,
309 funding_last_upd_ms: u64,
310 }
311
312 struct SettledFunding has copy, drop {
313 ch_id: ID,
314 account_id: u64,
315 collateral_change_usd: IFixed,
316 collateral_after: IFixed,
317 mkt_funding_rate_long: IFixed,
318 mkt_funding_rate_short: IFixed
319 }
320
321 struct FilledMakerOrder has copy, drop {
322 ch_id: ID,
323 maker_account_id: u64,
324 maker_collateral: IFixed,
325 collateral_change_usd: IFixed,
326 order_id: u128,
327 maker_size: u64,
328 maker_final_size: u64,
329 maker_base_amount: IFixed,
330 maker_quote_amount: IFixed,
331 maker_pending_asks_quantity: IFixed,
332 maker_pending_bids_quantity: IFixed,
333 }
334
335 struct FilledTakerOrder has copy, drop {
336 ch_id: ID,
337 taker_account_id: u64,
338 taker_collateral: IFixed,
339 collateral_change_usd: IFixed,
340 base_asset_delta_ask: IFixed,
341 quote_asset_delta_ask: IFixed,
342 base_asset_delta_bid: IFixed,
343 quote_asset_delta_bid: IFixed,
344 taker_base_amount: IFixed,
345 taker_quote_amount: IFixed,
346 liquidated_volume: IFixed,
347 }
348
349 struct OrderbookPostReceipt has copy, drop {
350 ch_id: ID,
351 account_id: u64,
352 order_id: u128,
353 order_size: u64,
354 }
355
356 struct PostedOrder has copy, drop {
357 ch_id: ID,
358 account_id: u64,
359 posted_base_ask: u64,
360 posted_base_bid: u64,
361 pending_asks: IFixed,
362 pending_bids: IFixed,
363 pending_orders: u64,
364 }
365
366 struct CanceledOrder has copy, drop {
367 ch_id: ID,
368 account_id: u64,
369 size: u64,
370 order_id: u128,
371 }
372
373 struct CanceledOrders has copy, drop {
374 ch_id: ID,
375 account_id: u64,
376 asks_quantity: IFixed,
377 bids_quantity: IFixed,
378 pending_orders: u64,
379 }
380
381 struct LiquidatedPosition has copy, drop {
382 ch_id: ID,
383 liqee_account_id: u64,
384 liqor_account_id: u64,
385 is_liqee_long: bool,
386 size_liquidated: u64,
387 mark_price: IFixed,
388 liqee_collateral_change_usd: IFixed,
389 liqee_collateral: IFixed,
390 liqee_base_amount: IFixed,
391 liqee_quote_amount: IFixed,
392 bad_debt: IFixed
393 }
394
395 struct UpdatedCumFundings has copy, drop {
396 ch_id: ID,
397 cum_funding_rate_long: IFixed,
398 cum_funding_rate_short: IFixed,
399 }
400
401 struct CreatedPosition has copy, drop {
402 ch_id: ID,
403 account_id: u64,
404 mkt_funding_rate_long: IFixed,
405 mkt_funding_rate_short: IFixed,
406 }
407
408 struct CreatedStopOrderTicket has copy, drop {
409 account_id: u64,
410 recipient: address,
411 encrypted_details: vector<u8>
412 }
413
414 struct DeletedStopOrderTicket has copy, drop {
415 id: ID,
416 user_address: address,
417 processed: bool
418 }
419
420 struct CreatedMarginRatiosProposal has copy, drop {
421 ch_id: ID,
422 margin_ratio_initial: IFixed,
423 margin_ratio_maintenance: IFixed,
424 }
425
426 struct UpdatedMarginRatios has copy, drop {
427 ch_id: ID,
428 margin_ratio_initial: IFixed,
429 margin_ratio_maintenance: IFixed,
430 }
431
432 struct DeletedMarginRatiosProposal has copy, drop {
433 ch_id: ID,
434 margin_ratio_initial: IFixed,
435 margin_ratio_maintenance: IFixed,
436 }
437
438 struct CreatedPositionFeesProposal has copy, drop {
439 ch_id: ID,
440 account_id: u64,
441 maker_fee: IFixed,
442 taker_fee: IFixed,
443 }
444
445 struct DeletedPositionFeesProposal has copy, drop {
446 ch_id: ID,
447 account_id: u64,
448 maker_fee: IFixed,
449 taker_fee: IFixed,
450 }
451
452 struct AcceptedPositionFeesProposal has copy, drop {
453 ch_id: ID,
454 account_id: u64,
455 maker_fee: IFixed,
456 taker_fee: IFixed,
457 }
458
459 struct RejectedPositionFeesProposal has copy, drop {
460 ch_id: ID,
461 account_id: u64,
462 maker_fee: IFixed,
463 taker_fee: IFixed,
464 }
465
466 struct ResettedPositionFees has copy, drop {
467 ch_id: ID,
468 account_id: u64,
469 }
470
471 struct UpdatedFees has copy, drop {
472 ch_id: ID,
473 maker_fee: IFixed,
474 taker_fee: IFixed,
475 liquidation_fee: IFixed,
476 force_cancel_fee: IFixed,
477 insurance_fund_fee: IFixed,
478 }
479
480 struct UpdatedFundingParameters has copy, drop {
481 ch_id: ID,
482 funding_frequency_ms: u64,
483 funding_period_ms: u64,
484 premium_twap_frequency_ms: u64,
485 premium_twap_period_ms: u64,
486 }
487
488 struct UpdatedSpreadTwapParameters has copy, drop {
489 ch_id: ID,
490 spread_twap_frequency_ms: u64,
491 spread_twap_period_ms: u64
492 }
493
494 struct UpdatedMinOrderUsdValue has copy, drop {
495 ch_id: ID,
496 min_order_usd_value: IFixed,
497 }
498
499 struct UpdatedLiquidationTolerance has copy, drop {
500 ch_id: ID,
501 liquidation_tolerance: u64,
502 }
503
504 struct UpdatedBaseOracleTolerance has copy, drop {
505 ch_id: ID,
506 oracle_tolerance: u64,
507 }
508
509 struct UpdatedCollateralOracleTolerance has copy, drop {
510 ch_id: ID,
511 oracle_tolerance: u64,
512 }
513
514 struct UpdatedMaxPendingOrders has copy, drop {
515 ch_id: ID,
516 max_pending_orders: u64
517 }
518
519 struct DonatedToInsuranceFund has copy, drop {
520 sender: address,
521 ch_id: ID,
522 new_balance: u64,
523 }
524
525 struct WithdrewFees has copy, drop {
526 sender: address,
527 ch_id: ID,
528 amount: u64,
529 vault_balance_after: u64,
530 }
531
532 struct WithdrewInsuranceFund has copy, drop {
533 sender: address,
534 ch_id: ID,
535 amount: u64,
536 insurance_fund_balance_after: u64,
537 }
538
539 struct UpdatedOpenInterestAndFeesAccrued has copy, drop {
540 ch_id: ID,
541 open_interest: IFixed,
542 fees_accrued: IFixed
543 }
544
545 struct CreatedSubAccount has copy, drop {
546 subaccount_id: ID,
547 user: address,
548 account_id: u64
549 }
550
551 struct SetSubAccountUser has copy, drop {
552 subaccount_id: ID,
553 user: address,
554 account_id: u64
555 }
556
557 struct DeletedSubAccount has copy, drop {
558 subaccount_id: ID,
559 account_id: u64
560 }
561
562 struct DepositedCollateralSubAccount has copy, drop {
563 subaccount_id: ID,
564 account_id: u64,
565 collateral: u64,
566 subaccount_collateral_after: u64
567 }
568
569 struct WithdrewCollateralSubAccount has copy, drop {
570 subaccount_id: ID,
571 account_id: u64,
572 collateral: u64,
573 subaccount_collateral_after: u64
574 }
575
576 struct AllocatedCollateralSubAccount has copy, drop {
577 ch_id: ID,
578 subaccount_id: ID,
579 account_id: u64,
580 collateral: u64,
581 subaccount_collateral_after: u64,
582 position_collateral_after: IFixed,
583 vault_balance_after: u64
584 }
585
586 struct DeallocatedCollateralSubAccount has copy, drop {
587 ch_id: ID,
588 subaccount_id: ID,
589 account_id: u64,
590 collateral: u64,
591 subaccount_collateral_after: u64,
592 position_collateral_after: IFixed,
593 vault_balance_after: u64
594 }
595 }
596
597 module keys {
598 /// Key type for accessing a `MarketInfo` saved in registry.
599 struct RegistryMarketInfo has copy, drop, store {
600 ch_id: ID
601 }
602
603 /// Key type for accessing a `CollateralInfo` saved in registry.
604 struct RegistryCollateralInfo<!phantom T> has copy, drop, store {}
605
606 /// Key type for accessing market params in clearing house.
607 struct Orderbook has copy, drop, store {}
608
609 /// Key type for accessing vault in clearing house.
610 struct MarketVault has copy, drop, store {}
611
612 /// Key type for accessing trader position in clearing house.
613 struct Position has copy, drop, store {
614 account_id: u64,
615 }
616
617 /// Key type for accessing market margin parameters change proposal in clearing house.
618 struct MarginRatioProposal has copy, drop, store {}
619
620 /// Key type for accessing custom fees parameters change proposal for an account
621 struct PositionFeesProposal has copy, drop, store {
622 account_id: u64
623 }
624
625 /// Key type for accessing asks map in the orderbook
626 struct AsksMap has copy, drop, store {}
627
628 /// Key type for accessing asks map in the orderbook
629 struct BidsMap has copy, drop, store {}
630 }
631
632 module market {
633 /// Static attributes of a perpetuals market.
634 struct MarketParams has copy, drop, store {
635 /// Minimum margin ratio for opening a new position.
636 margin_ratio_initial: IFixed,
637 /// Margin ratio below which full liquidations can occur.
638 margin_ratio_maintenance: IFixed,
639 /// Identifier of the base asset's price feed storage.
640 base_pfs_id: ID,
641 /// Identifier of the collateral asset's price feed storage.
642 collateral_pfs_id: ID,
643 /// The time span between each funding rate update.
644 funding_frequency_ms: u64,
645 /// Period of time over which funding (the difference between book and
646 /// index prices) gets paid.
647 ///
648 /// Setting the funding period too long may cause the perpetual to start
649 /// trading at a very dislocated price to the index because there's less
650 /// of an incentive for basis arbitrageurs to push the prices back in
651 /// line since they would have to carry the basis risk for a longer
652 /// period of time.
653 ///
654 /// Setting the funding period too short may cause nobody to trade the
655 /// perpetual because there's too punitive of a price to pay in the case
656 /// the funding rate flips sign.
657 funding_period_ms: u64,
658 /// The time span between each funding TWAP (both index price and orderbook price) update.
659 premium_twap_frequency_ms: u64,
660 /// The reference time span used for weighting the TWAP (both index price and orderbook price)
661 /// updates for funding rates estimation
662 premium_twap_period_ms: u64,
663 /// The time span between each spread TWAP updates (used for liquidations).
664 spread_twap_frequency_ms: u64,
665 /// The reference time span used for weighting the TWAP updates for spread.
666 spread_twap_period_ms: u64,
667 /// Proportion of volume charged as fees from makers upon processing
668 /// fill events.
669 maker_fee: IFixed,
670 /// Proportion of volume charged as fees from takers after processing
671 /// fill events.
672 taker_fee: IFixed,
673 /// Proportion of volume charged as fees from liquidatees
674 liquidation_fee: IFixed,
675 /// Proportion of volume charged as fees from liquidatees after forced cancelling
676 /// of pending orders during liquidation.
677 force_cancel_fee: IFixed,
678 /// Proportion of volume charged as fees from liquidatees to deposit into insurance fund
679 insurance_fund_fee: IFixed,
680 /// Minimum USD value an order is required to be worth to be placed
681 min_order_usd_value: IFixed,
682 /// Number of base units exchanged per lot
683 lot_size: u64,
684 /// Number of quote units exchanged per tick
685 tick_size: u64,
686 /// Number of lots in a position that a liquidator may buy in excess of what would be
687 /// strictly required to bring the liqee's account back to IMR.
688 liquidation_tolerance: u64,
689 /// Maximum number of pending orders that a position can have.
690 max_pending_orders: u64,
691 /// Timestamp tolerance for base oracle price
692 base_oracle_tolerance: u64,
693 /// Timestamp tolerance for collateral oracle price
694 collateral_oracle_tolerance: u64
695 }
696
697 /// The state of a perpetuals market.
698 struct MarketState has store {
699 /// The latest cumulative funding premium in this market for longs. Must be updated
700 /// periodically.
701 cum_funding_rate_long: IFixed,
702 /// The latest cumulative funding premium in this market for shorts. Must be updated
703 /// periodically.
704 cum_funding_rate_short: IFixed,
705 /// The timestamp (millisec) of the latest cumulative funding premium update
706 /// (both longs and shorts).
707 funding_last_upd_ms: u64,
708 /// The last calculated funding premium TWAP (used for funding settlement).
709 premium_twap: IFixed,
710 /// The timestamp (millisec) of the last update of `premium_twap`.
711 premium_twap_last_upd_ms: u64,
712 /// The last calculated spread TWAP (used for liquidations).
713 /// Spread is (book - index).
714 spread_twap: IFixed,
715 /// The timestamp (millisec) of `spread_twap` last update.
716 spread_twap_last_upd_ms: u64,
717 /// Open interest (in base tokens) as a fixed-point number. Counts the
718 /// total size of contracts as the sum of all long positions.
719 open_interest: IFixed,
720 /// Total amount of fees accrued by this market (in T's units)
721 /// Only admin can withdraw these fees.
722 fees_accrued: IFixed,
723 }
724 }
725
726 module orderbook {
727 /// An order on the orderbook
728 struct Order has copy, drop, store {
729 /// User's account id
730 account_id: u64,
731 /// Amount of lots to be filled
732 size: u64
733 }
734
735 /// The orderbook doesn't know the types of tokens traded, it assumes a correct
736 /// management by the clearing house
737 struct Orderbook has key, store {
738 id: UID,
739 /// Number of limit orders placed on book, monotonically increases
740 counter: u64,
741 }
742
743 // -----------------------------------------------------------------------------
744 // Result Structures
745 // -----------------------------------------------------------------------------
746
747 struct FillReceipt has drop, store {
748 account_id: u64,
749 order_id: u128,
750 size: u64,
751 final_size: u64,
752 }
753
754 struct PostReceipt has drop, store {
755 base_ask: u64,
756 base_bid: u64,
757 pending_orders: u64
758 }
759
760 /// Order info data structure that is returned by `inspect_orders` function.
761 struct OrderInfo has copy, drop, store {
762 price: u64,
763 size: u64,
764 }
765 }
766
767 module ordered_map {
768 /// Ordered map with `u128` type as a key and `V` type as a value.
769 struct Map<!phantom V: copy + drop + store> has key, store {
770 /// Object UID for adding dynamic fields that are used as pointers to nodes.
771 id: UID,
772 /// Number of key-value pairs in the map.
773 size: u64,
774 /// Counter for creating another node as a dynamic field.
775 counter: u64,
776 /// Pointer to the root node, which is a branch or a leaf.
777 root: u64,
778 /// Pointer to first leaf.
779 first: u64,
780 /// Minimal number of kids in a non-root branch;
781 /// must satisfy 2 <= branch_min <= branch_max / 2.
782 branch_min: u64,
783 /// Maximal number of kids in a branch, which is merge of two branches;
784 /// must satisfy 2 * branch_min <= branches_merge_max <= branch_max.
785 branches_merge_max: u64,
786 /// Maximal number of kids in a branch.
787 branch_max: u64,
788 /// Minimal number of elements in a non-root leaf;
789 /// must satisfy 2 <= leaf_min <= (leaf_max + 1) / 2.
790 leaf_min: u64,
791 /// Maximal number of elements in a leaf, which is merge of two leaves;
792 /// must satisfy 2 * leaf_min - 1 <= leaves_merge_max <= leaf_max.
793 leaves_merge_max: u64,
794 /// Maximal number of elements in a leaf.
795 leaf_max: u64,
796 }
797
798 /// Branch node with kids and ordered separating keys.
799 struct Branch has drop, store {
800 /// Separating keys for kids sorted in ascending order.
801 keys: vector<u128>,
802 /// Kids of the node.
803 kids: vector<u64>,
804 }
805
806 /// Key-value pair.
807 struct Pair<V: copy + drop + store> has copy, drop, store {
808 key: u128,
809 val: V,
810 }
811
812 /// Leaf node with ordered key-value pairs.
813 struct Leaf<V: copy + drop + store> has drop, store {
814 /// Keys sorted in ascending order together with values.
815 keys_vals: vector<Pair<V>>,
816 /// Pointer to next leaf.
817 next: u64,
818 }
819 }
820
821 module position {
822 /// Stores information about an open position
823 struct Position has store {
824 /// Amount of allocated tokens (e.g., USD stables) backing this account's position.
825 collateral: IFixed,
826 /// The perpetual contract size, controlling the amount of exposure to
827 /// the underlying asset. Positive implies long position and negative,
828 /// short. Represented as a signed fixed-point number.
829 base_asset_amount: IFixed,
830 /// The entry value for this position, including leverage. Represented
831 /// as a signed fixed-point number.
832 quote_asset_notional_amount: IFixed,
833 /// Last long cumulative funding rate used to update this position. The
834 /// market's latest long cumulative funding rate minus this gives the funding
835 /// rate this position must pay. This rate multiplied by this position's
836 /// value (base asset amount * market price) gives the total funding
837 /// owed, which is deducted from the trader account's margin. This debt
838 /// is accounted for in margin ratio calculations, which may lead to
839 /// liquidation. Represented as a signed fixed-point number.
840 cum_funding_rate_long: IFixed,
841 /// Last short cumulative funding rate used to update this position. The
842 /// market's latest short cumulative funding rate minus this gives the funding
843 /// rate this position must pay. This rate multiplied by this position's
844 /// value (base asset amount * market price) gives the total funding
845 /// owed, which is deducted from the trader account's margin. This debt
846 /// is accounted for in margin ratio calculations, which may lead to
847 /// liquidation. Represented as a signed fixed-point number.
848 cum_funding_rate_short: IFixed,
849 /// Base asset amount resting in ask orders in the orderbook.
850 /// Represented as a signed fixed-point number.
851 asks_quantity: IFixed,
852 /// Base asset amount resting in bid orders in the orderbook.
853 /// Represented as a signed fixed-point number.
854 bids_quantity: IFixed,
855 /// Number of pending orders in this position.
856 pending_orders: u64,
857 /// Custom maker fee for this position, set at default value of 100%
858 maker_fee: IFixed,
859 /// Custom taker fee for this position, set at default value of 100%
860 taker_fee: IFixed,
861 }
862 }
863
864 module registry {
865 /// Registry object that maintains:
866 /// - A mapping between a clearing house id and `MarketInfo`
867 /// - A mapping between a collateral type `T` and `CollateralInfo`
868 /// It also maintains the global counter for account creation.
869 /// Minted and shared when the module is published.
870 struct Registry has key {
871 id: UID,
872 next_account_id: u64
873 }
874
875 /// Struct containing all the immutable info about a registered market
876 struct MarketInfo<!phantom T> has store {
877 base_pfs_id: ID,
878 collateral_pfs_id: ID,
879 lot_size: u64,
880 tick_size: u64,
881 scaling_factor: IFixed
882 }
883
884 /// Struct containing all the immutable info about the collateral
885 /// used in one or more markets
886 struct CollateralInfo<!phantom T> has store {
887 collateral_pfs_id: ID,
888 scaling_factor: IFixed
889 }
890 }
891});
892
893impl<T: af_move_type::MoveType> clearing_house::ClearingHouse<T> {
894 /// The ID of the package that governs this clearing house's logic.
895 ///
896 /// This may be different than the package defining the clearing house's type because a package
897 /// upgrade + `interface::upgrade_clearing_house_version` call can change
898 /// [`ClearingHouse::version`] so that the upgraded package is the one that is allowed to make
899 /// changes to it.
900 ///
901 /// Attempting to make a PTB Move call that mutates this clearing house but is not defined in
902 /// this package version will fail.
903 pub const fn governing_package_testnet(&self) -> ObjectId {
904 // NOTE: we published the most recent testnet contracts starting with `VERSION = 1`
905 TESTNET_PACKAGE_VERSIONS[self.version as usize - 1]
906 }
907}