Skip to main content

af_iperps/
errors.rs

1// Copyright (c) Aftermath Technologies, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4#![expect(non_upper_case_globals, reason = "Copied from Move")]
5
6macro_rules! move_aborts {
7    (module $_:ident::$module:ident {$(
8        $(#[$meta:meta])*
9        const $Error:ident: u64 = $num:literal;
10    )*}) => {
11        $(
12            $(#[$meta])*
13            pub const $Error: u64 = $num;
14        )*
15        #[derive(
16            Debug,
17            PartialEq,
18            Eq,
19            Hash,
20            num_enum::IntoPrimitive,
21            num_enum::TryFromPrimitive,
22            strum::Display,
23            strum::EnumIs,
24            strum::EnumMessage,
25            strum::IntoStaticStr,
26        )]
27        #[repr(u64)]
28        pub enum MoveAbort {$(
29            $(#[$meta])*
30            $Error = $num,
31        )*}
32    };
33}
34
35move_aborts! {
36module perpetuals::errors {
37    // ClearingHouse ---------------------------------------------------------------
38
39    /// Cannot deposit/withdraw zero coins to/from the account's collateral.
40    const DepositOrWithdrawAmountZero: u64 = 0;
41    /// Size to place is 0. Raised also when there is no open position and
42    /// an order with `reduce_only` is passed.
43    const SizeOrPositionZero: u64 = 1;
44    /// Index price returned from oracle is 0 or invalid value
45    const BadIndexPrice: u64 = 2;
46    /// Price is either 0 or greater than 0x8000_0000_0000_0000
47    const InvalidPrice: u64 = 3;
48    /// Order value in USD is too low
49    const OrderUsdValueTooLow: u64 = 4;
50    /// Passed a vector of invalid order ids to perform force cancellation
51    /// during liquidation
52    const InvalidForceCancelIds: u64 = 5;
53    /// Liquidate must be the first operation of the session, if performed.
54    const LiquidateNotFirstOperation: u64 = 6;
55    /// Passed a vector of invalid order ids to cancel
56    const InvalidCancelOrderIds: u64 = 7;
57    /// Ticket has already passed `expire_timestamp` and can only be cancelled
58    const StopOrderTicketExpired: u64 = 8;
59    /// Index price is not at correct value to satisfy stop order conditions
60    const StopOrderConditionsViolated: u64 = 9;
61    /// Index price is not at correct value to satisfy stop order conditions
62    const WrongOrderDetails: u64 = 10;
63    /// Invalid base price feed storage for the clearing house
64    const InvalidBasePriceFeedStorage: u64 = 11;
65    /// Same liquidator and liqee account ids
66    const SelfLiquidation: u64 = 12;
67    /// User trying to access the account used the wrong account cap
68    const InvalidAccountCap: u64 = 13;
69    /// Raised when passing an integrator taker fee that is greater than
70    /// the `max_integrator_taker_fee` set by the user in its account
71    const InvalidIntegratorTakerFee: u64 = 14;
72    /// Raised when trying to call a function with the wrong package's version
73    const WrongVersion: u64 = 16;
74    /// Raised when trying to have a session composed by only `start_session` and `end_session`
75    const EmptySession: u64 = 17;
76    /// Market already registered in the registry
77    const MarketAlreadyRegistered: u64 = 18;
78    /// Collateral is not registered in the registry
79    const CollateralIsNotRegistered: u64 = 19;
80    /// Market is not registered in the registry
81    const MarketIsNotRegistered: u64 = 20;
82    /// Invalid collateral price feed storage for the clearing house
83    const InvalidCollateralPriceFeedStorage: u64 = 21;
84    /// Fees accrued are negative
85    const NegativeFeesAccrued: u64 = 22;
86    /// Passed a timestamp older than current Clock's one
87    const InvalidExpirationTimestamp: u64 = 23;
88    /// Stop order gas cost provided is not enough
89    const NotEnoughGasForStopOrder: u64 = 24;
90    /// Invalid account trying to perform an action on a StopOrderTicket
91    const InvalidAccountForStopOrder: u64 = 26;
92    /// Invalid executor trying to execute the StopOrderTicket
93    const InvalidExecutorForStopOrder: u64 = 27;
94    /// Raised when the market's max open interest is surpassed as a result of
95    /// the session's actions
96    const MaxOpenInterestSurpassed: u64 = 28;
97    /// Raised when a position's would get a base amount higher than the
98    /// allowed percentage of open interest
99    const MaxOpenInterestPositionPercentSurpassed: u64 = 29;
100    /// Raised processing a session that requires a collateral allocation,
101    /// but not enough collateral is available in the account
102    const NotEnoughCollateralToAllocateForSession: u64 = 30;
103    /// Raised processing a session that requires a collateral allocation
104    /// and a wrong account is being used to fund it
105    const WrongAccountIdForAllocation: u64 = 31;
106    /// Raised when trying to create an integrator vault for an address
107    /// that already has one
108    const IntegratorVaultAlreadyExists: u64 = 32;
109    /// Raised when trying to access an integrator vault that does not exist
110    const IntegratorVaultDoesNotExist: u64 = 33;
111    /// Raised when trying to place an order passing a `size` that is not a multiple
112    /// of market's lot size
113    const SizeNotMultipleOfLotSize: u64 = 34;
114    /// Raised when trying to place an order passing a `price` that is not a multiple
115    /// of market's tick size
116    const PriceNotMultipleOfTickSize: u64 = 35;
117    /// Raised when adl counterparties vec lengths differ
118    const ADLCounterpartiesMismatch: u64 = 36;
119    /// Raised when adl counterparty cannot reduce its assigned portion of base
120    const ADLCounterpartyInsufficient: u64 = 37;
121    /// Raised when adl does not fully close the bad debt position
122    const ADLBadDebtPositionNotClosed: u64 = 38;
123    /// Raised when weights for adl do not sum to fixed point 1
124    const ADLWeightsDoNotSumToOne: u64 = 39;
125    /// Open interest is 0 when trying to socialize bad debt
126    const NoOpenInterestToSocializeBadDebt: u64 = 40;
127    /// Bad debt amount is greater than max allowed threshold
128    const BadDebtAboveThreshold: u64 = 41;
129
130    // Market ---------------------------------------------------------------
131
132    /// While creating ordered map with invalid parameters,
133    /// or changing them improperly for an existent map.
134    const InvalidMarketParameters: u64 = 1000;
135    /// Tried to call `update_funding` before enough time has passed since the
136    /// last update.
137    const UpdatingFundingTooEarly: u64 = 1001;
138    /// Margin ratio update proposal already exists for market
139    const ProposalAlreadyExists: u64 = 1002;
140    /// Margin ratio update proposal cannot be commited too early
141    const PrematureProposal: u64 = 1003;
142    /// Margin ratio update proposal delay is outside the valid range
143    const InvalidProposalDelay: u64 = 1004;
144    /// Margin ratio update proposal does not exist for market
145    const ProposalDoesNotExist: u64 = 1005;
146    /// Exchange has no available fees to withdraw
147    const NoFeesAccrued: u64 = 1006;
148    /// Tried to withdraw more insurance funds than the allowed amount
149    const InsufficientInsuranceSurplus: u64 = 1007;
150    /// Cannot create a market for which a price feed does not exist
151    const NoPriceFeedForMarket: u64 = 1008;
152    /// Cannot delete a proposal that already matured. It can only be committed.
153    const ProposalAlreadyMatured: u64 = 1009;
154    /// Raised when an operation is performed while the market is paused
155    const MarketIsPaused: u64 = 1010;
156    /// Raised when trying to call `close_position_at_settlement_prices` while
157    /// the market is not paused
158    const MarketIsNotPaused: u64 = 1011;
159    /// Raised when trying to call `close_position_at_settlement_prices` while
160    /// before `close_market` has been called by admin
161    const MarketIsNotClosed: u64 = 1012;
162    /// Raised when Admin tries to resume a closed market
163    const MarketIsClosed: u64 = 1013;
164
165    // Position  ---------------------------------------------------------------
166
167    /// Tried placing a new pending order when the position already has the maximum
168    /// allowed number of pending orders.
169    const MaxPendingOrdersExceeded: u64 = 2000;
170    /// Used for checking both liqee and liqor positions during liquidation
171    const PositionBelowIMR: u64 = 2001;
172    /// When leaving liqee's position with a margin ratio above tolerance,
173    /// meaning that liqor has overbought position
174    const PositionAboveTolerance: u64 = 2002;
175    /// An operation brought an account below initial margin requirements.
176    const InitialMarginRequirementViolated: u64 = 2003;
177    /// Position is above MMR, so can't be liquidated.
178    const PositionAboveMMR: u64 = 2004;
179    /// Cannot realize bad debt via means other than calling 'liquidate'.
180    const PositionBadDebt: u64 = 2005;
181    /// Cannot withdraw more than the account's free collateral.
182    const InsufficientFreeCollateral: u64 = 2006;
183    /// Cannot have more than 1 position in a market.
184    const PositionAlreadyExists: u64 = 2007;
185    /// Cannot compute deallocate amount for a target MR < IMR.
186    const DeallocateTargetMrTooLow: u64 = 2008;
187    /// Raised when trying to set a position's IMR lower than market's IMR or higher than 1
188    const InvalidPositionIMR: u64 = 2009;
189    /// Invalid stop order type
190    const InvalidStopOrderType: u64 = 2010;
191    /// Invalid position' status for placing a SLTP order
192    const InvalidPositionForSLTP: u64 = 2011;
193
194    // Orderbook & OrderedMap -------------------------------------------------------
195
196    /// While creating ordered map with wrong parameters.
197    const InvalidMapParameters: u64 = 3000;
198    /// While searching for a key, but it doesn't exist.
199    const KeyNotExist: u64 = 3001;
200    /// While inserting already existing key.
201    const KeyAlreadyExists: u64 = 3002;
202    /// When attempting to destroy a non-empty map
203    const DestroyNotEmpty: u64 = 3003;
204    /// Invalid user tries to modify an order
205    const InvalidUserForOrder: u64 = 3004;
206    /// Orderbook flag requirements violated
207    const FlagRequirementsViolated: u64 = 3005;
208    /// Minimum size matched not reached
209    const NotEnoughLiquidity: u64 = 3006;
210    /// When trying to change a map configuration, but the map has
211    /// length less than 4
212    const MapTooSmall: u64 = 3007;
213
214    // Account ---------------------------------------------------------------
215
216    /// When trying to create another `AccountCap<ASSISTANT>` for an `Account` that already
217    /// has `constants::MAX_ASSISTANTS_PER_ACCOUNT` active assistants.
218    const TooManyAssistantsPerAccount: u64 = 4000;
219}
220}
221
222#[cfg(test)]
223mod tests {
224    use super::MoveAbort;
225
226    #[test]
227    fn variant_to_code() {
228        assert_eq!(MoveAbort::MaxPendingOrdersExceeded as u64, 2000);
229        assert_eq!(MoveAbort::MapTooSmall as u64, 3007);
230        assert_eq!(Ok(MoveAbort::MaxPendingOrdersExceeded), 2000_u64.try_into());
231        assert_eq!(Ok(MoveAbort::MapTooSmall), 3007_u64.try_into());
232    }
233}