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