gmsol-store 0.10.0

GMX-Solana is an extension of GMX on the Solana blockchain.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
//! ## Market
//! A [`Market`](crate::states::Market) in GMX-Solana is defined by three tokens:
//!
//! - **Index Token**: The underlying asset that serves as the trading instrument. The price movements
//!   of this token determine the profit or loss of positions. It does not need to be a real token.
//! - **Long Token**: The token used to:
//!   - Collateralize long and short positions
//!   - Pay profits to long position holders
//! - **Short Token**: The token used to:
//!   - Collateralize long and short positions
//!   - Pay profits to short position holders
//!
//! Long token and short token can be the same token, in which case the market
//! is called a *single-token market*.
//!
//! Liquidity Providers (LPs) can provide liquidity to the market by depositing pool tokens (long token
//! and short token) in exchange for market tokens. These market tokens represent the LP's proportional
//! share of the market's liquidity pool. The deposited tokens are held in shared token accounts called
//! *Market Vaults*, with deposited amounts for this market tracked in the market state. LPs can later
//! redeem their market tokens back for the underlying collateral tokens through withdrawal instructions.
//!
//! Traders can open long or short positions using either token as collateral. When opening a position,
//! the trader deposits collateral tokens and specifies the desired leverage. The position's profit or
//! loss is determined by price movements of the index token. The loss is incurred in the collateral
//! token used to open the position while the profit is realized in the long token and short token
//! respectively.

use std::str::FromStr;

use anchor_lang::{prelude::*, Bump};
use anchor_spl::token::Mint;
use borsh::{BorshDeserialize, BorshSerialize};
use config::MarketConfigFlag;
use gmsol_model::{
    num::Unsigned, price::Prices, Balance, BaseMarket, BaseMarketExt, ClockKind, Delta, PoolKind,
};
use gmsol_utils::{
    market::{MarketError, MarketFlag, MAX_MARKET_FLAGS},
    pubkey::{optional_address, DEFAULT_PUBKEY},
    token_config::TokenMapAccess,
};
use pool::cancel_amounts;
use revertible::RevertibleBuffer;
use virtual_inventory::VirtualInventory;

use crate::{
    constants::MARKET_DECIMALS,
    utils::fixed_str::{bytes_to_fixed_str, fixed_str_to_bytes},
    CoreError, ModelError,
};

use super::{Factor, InitSpace, Oracle, Seed};

use self::{
    config::{MarketConfig, MarketConfigBuffer, MarketConfigKey},
    pool::{Pool, Pools},
};

pub use gmsol_utils::market::{HasMarketMeta, MarketMeta};
pub use model::AsLiquidityMarket;

/// Market Utils.
pub mod utils;

/// Clock ops.
pub mod clock;

/// Market Config.
pub mod config;

/// Revertible Market Operations.
pub mod revertible;

/// Pool.
pub mod pool;

/// Market Status.
pub mod status;

/// Virtual Inventory.
pub mod virtual_inventory;

mod model;

const MAX_NAME_LEN: usize = 64;

/// Market.
#[account(zero_copy)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Market {
    version: u8,
    /// Bump Seed.
    pub(crate) bump: u8,
    flags: MarketFlagContainer,
    padding: [u8; 5],
    closed_state_updated_at: i64,
    #[cfg_attr(feature = "serde", serde(with = "serde_bytes"))]
    name: [u8; MAX_NAME_LEN],
    pub(crate) meta: MarketMeta,
    /// Store.
    pub store: Pubkey,
    config: MarketConfig,
    indexer: Indexer,
    state: State,
    buffer: RevertibleBuffer,
    virtual_inventory_for_swaps: Pubkey,
    virtual_inventory_for_positions: Pubkey,
    #[cfg_attr(feature = "serde", serde(with = "serde_bytes"))]
    reserved: [u8; 192],
}

#[zero_copy]
#[cfg_attr(feature = "debug", derive(derive_more::Debug))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
struct State {
    pools: Pools,
    clocks: Clocks,
    other: OtherState,
    #[cfg_attr(feature = "debug", debug(skip))]
    #[cfg_attr(feature = "serde", serde(with = "serde_bytes"))]
    reserved: [u8; 1024],
}

impl Bump for Market {
    fn seed(&self) -> u8 {
        self.bump
    }
}

impl Seed for Market {
    const SEED: &'static [u8] = b"market";
}

impl InitSpace for Market {
    const INIT_SPACE: usize = std::mem::size_of::<Self>();
}

impl Default for Market {
    fn default() -> Self {
        use bytemuck::Zeroable;
        Self::zeroed()
    }
}

impl AsRef<Market> for Market {
    fn as_ref(&self) -> &Market {
        self
    }
}

impl Market {
    /// Find PDA for [`Market`] account.
    pub fn find_market_address(
        store: &Pubkey,
        token: &Pubkey,
        store_program_id: &Pubkey,
    ) -> (Pubkey, u8) {
        Pubkey::find_program_address(
            &[Self::SEED, store.as_ref(), token.as_ref()],
            store_program_id,
        )
    }

    /// Initialize the market.
    #[allow(clippy::too_many_arguments)]
    pub fn init(
        &mut self,
        bump: u8,
        store: Pubkey,
        name: &str,
        market_token_mint: Pubkey,
        index_token_mint: Pubkey,
        long_token_mint: Pubkey,
        short_token_mint: Pubkey,
        is_enabled: bool,
    ) -> Result<()> {
        self.bump = bump;
        self.store = store;
        self.name = fixed_str_to_bytes(name)?;
        self.set_enabled(is_enabled);
        self.meta.market_token_mint = market_token_mint;
        self.meta.index_token_mint = index_token_mint;
        self.meta.long_token_mint = long_token_mint;
        self.meta.short_token_mint = short_token_mint;
        let is_pure = self.meta.long_token_mint == self.meta.short_token_mint;
        self.set_flag(MarketFlag::Pure, is_pure);
        self.state.pools.init(is_pure);
        self.state.clocks.init_to_current()?;
        self.config.init();

        // Initialize buffer.
        self.buffer.init();
        Ok(())
    }

    /// Get meta.
    pub fn meta(&self) -> &MarketMeta {
        &self.meta
    }

    /// Get validated meta.
    pub fn validated_meta(&self, store: &Pubkey) -> Result<&MarketMeta> {
        self.validated_meta_with_options(store, false)
    }

    /// Get validated meta with options.
    pub(crate) fn validated_meta_with_options(
        &self,
        store: &Pubkey,
        allow_closed: bool,
    ) -> Result<&MarketMeta> {
        self.validate_with_options(store, allow_closed)?;
        Ok(self.meta())
    }

    /// Get name.
    pub fn name(&self) -> Result<&str> {
        bytes_to_fixed_str(&self.name)
    }

    /// Description.
    pub fn description(&self) -> Result<String> {
        let name = self.name()?;
        Ok(format!(
            "Market {{ name = {name}, token = {}}}",
            self.meta.market_token_mint
        ))
    }

    /// Get flag.
    pub fn flag(&self, flag: MarketFlag) -> bool {
        self.flags.get_flag(flag)
    }

    /// Set flag.
    ///
    /// Return the previous value.
    pub fn set_flag(&mut self, flag: MarketFlag, value: bool) -> bool {
        self.flags.set_flag(flag, value)
    }

    /// Is this market a pure market, i.e., a single token market.
    pub fn is_pure(&self) -> bool {
        self.flag(MarketFlag::Pure)
    }

    /// Is this market enabled.
    pub fn is_enabled(&self) -> bool {
        self.flag(MarketFlag::Enabled)
    }

    /// Set enabled.
    ///
    /// Return previous value.
    pub fn set_enabled(&mut self, enabled: bool) -> bool {
        self.set_flag(MarketFlag::Enabled, enabled)
    }

    /// Is ADL enabled.
    pub fn is_adl_enabled(&self, is_long: bool) -> bool {
        if is_long {
            self.flag(MarketFlag::AutoDeleveragingEnabledForLong)
        } else {
            self.flag(MarketFlag::AutoDeleveragingEnabledForShort)
        }
    }

    /// Set ADL enabled.
    ///
    /// Return previous value.
    pub fn set_adl_enabled(&mut self, is_long: bool, enabled: bool) -> bool {
        if is_long {
            self.set_flag(MarketFlag::AutoDeleveragingEnabledForLong, enabled)
        } else {
            self.set_flag(MarketFlag::AutoDeleveragingEnabledForShort, enabled)
        }
    }

    /// Is GT Minting enabled.
    pub fn is_gt_minting_enabled(&self) -> bool {
        self.flag(MarketFlag::GTEnabled)
    }

    /// Set whether the GT minting is enabled.
    ///
    /// Return the previous value.
    pub fn set_is_gt_minting_enabled(&mut self, enabled: bool) -> bool {
        self.set_flag(MarketFlag::GTEnabled, enabled)
    }

    /// Returns whether the market is closed.
    pub fn is_closed(&self) -> bool {
        self.flag(MarketFlag::Closed)
    }

    /// Set whether the market is closed.
    ///
    /// Return previous value.
    pub(crate) fn set_closed(&mut self, closed: bool) -> Result<bool> {
        let clock = Clock::get()?;
        self.closed_state_updated_at = clock.unix_timestamp;
        Ok(self.set_flag(MarketFlag::Closed, closed))
    }

    /// Get pool of the given kind.
    #[inline]
    pub fn pool(&self, kind: PoolKind) -> Option<Pool> {
        self.state.pools.get(kind).map(|s| s.pool()).copied()
    }

    /// Try to get pool of the given kind.
    pub fn try_pool(&self, kind: PoolKind) -> gmsol_model::Result<&Pool> {
        Ok(self
            .state
            .pools
            .get(kind)
            .ok_or(gmsol_model::Error::MissingPoolKind(kind))?
            .pool())
    }

    /// Get clock of the given kind.
    pub fn clock(&self, kind: ClockKind) -> Option<i64> {
        self.state.clocks.get(kind).copied()
    }

    fn clocks(&self) -> &Clocks {
        &self.state.clocks
    }

    /// Validate the market.
    pub fn validate(&self, store: &Pubkey) -> Result<()> {
        self.validate_with_options(store, false)
    }

    /// Validate the market with options.
    pub(crate) fn validate_with_options(&self, store: &Pubkey, allow_closed: bool) -> Result<()> {
        require_keys_eq!(*store, self.store, CoreError::StoreMismatched);
        require!(self.is_enabled(), CoreError::DisabledMarket);
        if !allow_closed {
            require!(!self.is_closed(), CoreError::MarketClosed);
        }
        Ok(())
    }

    /// Get config.
    pub fn get_config(&self, key: &str) -> Result<&Factor> {
        let key = MarketConfigKey::from_str(key)
            .map_err(|_| error!(CoreError::InvalidMarketConfigKey))?;
        self.get_config_by_key(key)
            .ok_or_else(|| error!(CoreError::Unimplemented))
    }

    /// Get config by key.
    #[inline]
    pub fn get_config_by_key(&self, key: MarketConfigKey) -> Option<&Factor> {
        self.config.get(key)
    }

    /// Get config mutably.
    pub fn get_config_mut(&mut self, key: &str) -> Result<&mut Factor> {
        let key = MarketConfigKey::from_str(key)
            .map_err(|_| error!(CoreError::InvalidMarketConfigKey))?;
        self.get_config_by_key_mut(key)
    }

    /// Get config mutably by key.
    pub(crate) fn get_config_by_key_mut(&mut self, key: MarketConfigKey) -> Result<&mut Factor> {
        self.config
            .get_mut(key)
            .ok_or_else(|| error!(CoreError::Unimplemented))
    }

    /// Get config flag.
    pub fn get_config_flag(&self, key: &str) -> Result<bool> {
        let key = MarketConfigFlag::from_str(key)
            .map_err(|_| error!(CoreError::InvalidMarketConfigKey))?;
        Ok(self.get_config_flag_by_key(key))
    }

    /// Get config flag by key.
    #[inline]
    pub fn get_config_flag_by_key(&self, key: MarketConfigFlag) -> bool {
        self.config.flag(key)
    }

    /// Set config flag.
    ///
    /// Returns previous value.
    pub fn set_config_flag(&mut self, key: &str, value: bool) -> Result<bool> {
        let key = MarketConfigFlag::from_str(key)
            .map_err(|_| error!(CoreError::InvalidMarketConfigKey))?;
        Ok(self.set_config_flag_by_key(key, value))
    }

    /// Set config flag by key.
    ///
    /// Returns previous value.
    pub(crate) fn set_config_flag_by_key(&mut self, key: MarketConfigFlag, value: bool) -> bool {
        self.config.set_flag(key, value)
    }

    /// Get other market state.
    pub fn state(&self) -> &OtherState {
        &self.state.other
    }

    /// Get market indexer.
    pub fn indexer(&self) -> &Indexer {
        &self.indexer
    }

    /// Get market indexer mutably.
    pub fn indexer_mut(&mut self) -> &mut Indexer {
        &mut self.indexer
    }

    /// Update config with buffer.
    pub fn update_config_with_buffer(&mut self, buffer: &MarketConfigBuffer) -> Result<()> {
        for entry in buffer.iter() {
            let key = entry.key()?;
            let current_value = self
                .config
                .get_mut(key)
                .ok_or_else(|| error!(CoreError::Unimplemented))?;
            let new_value = entry.value();
            *current_value = new_value;
        }
        Ok(())
    }

    /// Get prices from oracle.
    pub fn prices(&self, oracle: &Oracle) -> Result<Prices<u128>> {
        oracle.market_prices(self)
    }

    /// Get max pool value for deposit.
    pub fn max_pool_value_for_deposit(&self, is_long_token: bool) -> gmsol_model::Result<Factor> {
        if is_long_token {
            Ok(self.config.max_pool_value_for_deposit_for_long_token)
        } else {
            Ok(self.config.max_pool_value_for_deposit_for_short_token)
        }
    }

    /// As a liquidity market.
    pub fn as_liquidity_market<'a>(
        &'a self,
        market_token: &'a Mint,
    ) -> AsLiquidityMarket<'a, Self> {
        AsLiquidityMarket::new(self, market_token)
    }

    /// Validate that this market is shiftable to the target market.
    pub fn validate_shiftable(&self, target: &Self) -> Result<()> {
        // Currently we only support the shift between markets with
        // with the same long tokens and short tokens.
        //
        // It should be possible to allow shift between markets with the compatible tokens in the future,
        // for example, allowing shifting from BTC[WSOL-USDC] to SOL[USDC-WSOL].

        require_keys_eq!(
            self.meta().long_token_mint,
            target.meta().long_token_mint,
            CoreError::TokenMintMismatched,
        );

        require_keys_eq!(
            self.meta().short_token_mint,
            target.meta().short_token_mint,
            CoreError::TokenMintMismatched,
        );

        Ok(())
    }

    /// Returns the address of virtual inventory for swaps.
    pub fn virtual_inventory_for_swaps(&self) -> Option<&Pubkey> {
        optional_address(&self.virtual_inventory_for_swaps)
    }

    /// Join a virtual inventory for swaps.
    ///
    /// # CHECK
    /// - The provided [`VirtualInventory`] must be used as a
    ///   virtual inventory for swaps.
    /// - The provided token map must be authorized.
    pub fn join_virtual_inventory_for_swaps_unchecked(
        &mut self,
        address: &Pubkey,
        virtual_inventory_for_swaps: &mut VirtualInventory,
        token_map: &impl TokenMapAccess,
    ) -> Result<()> {
        require_keys_neq!(*address, DEFAULT_PUBKEY);
        require!(
            self.virtual_inventory_for_swaps().is_none(),
            CoreError::PreconditionsAreNotMet
        );
        let long_amount_decimals = token_map
            .get(&self.meta().long_token_mint)
            .ok_or_else(|| {
                msg!("long token not found in the token map");
                error!(CoreError::Internal)
            })?
            .token_decimals();
        let short_amount_decimals = token_map
            .get(&self.meta().short_token_mint)
            .ok_or_else(|| {
                msg!("short token not found in the token map");
                error!(CoreError::Internal)
            })?
            .token_decimals();
        require!(
            virtual_inventory_for_swaps.decimals() == (long_amount_decimals, short_amount_decimals),
            CoreError::InvalidArgument,
        );
        self.virtual_inventory_for_swaps = *address;
        let liquidity_pool = self.liquidity_pool().map_err(ModelError::from)?;
        virtual_inventory_for_swaps.join_unchecked(Delta::new_both_sides(
            true,
            &(liquidity_pool
                .long_amount()
                .map_err(ModelError::from)?
                .try_into()
                .map_err(|_| error!(CoreError::TokenAmountOverflow))?),
            &(liquidity_pool
                .short_amount()
                .map_err(ModelError::from)?
                .try_into()
                .map_err(|_| error!(CoreError::TokenAmountOverflow))?),
        ))?;
        Ok(())
    }

    /// Leave the virtual inventory for swaps.
    ///
    /// # CHECK
    /// - The provided [`VirtualInventory`] must be the associated one.
    pub fn leave_virtual_inventory_for_swaps_unchecked(
        &mut self,
        virtual_inventory_for_swaps: &mut VirtualInventory,
    ) -> Result<()> {
        require!(
            self.virtual_inventory_for_swaps().is_some(),
            CoreError::PreconditionsAreNotMet
        );
        let liquidity_pool = self.liquidity_pool().map_err(ModelError::from)?;
        virtual_inventory_for_swaps.leave_unchecked(Delta::new_both_sides(
            true,
            &(liquidity_pool
                .long_amount()
                .map_err(ModelError::from)?
                .to_opposite_signed()
                .map_err(ModelError::from)?),
            &(liquidity_pool
                .short_amount()
                .map_err(ModelError::from)?
                .to_opposite_signed()
                .map_err(ModelError::from)?),
        ))?;
        self.virtual_inventory_for_swaps = DEFAULT_PUBKEY;
        Ok(())
    }

    /// Leave a disabled virtual inventory.
    ///
    /// # CHECK
    /// - The address and the provided [`VirtualInventory`] must match.
    pub fn leave_disabled_virtual_inventory_unchecked(
        &mut self,
        address: &Pubkey,
        virtual_inventory: &mut VirtualInventory,
    ) -> Result<()> {
        require!(
            virtual_inventory.is_disabled(),
            CoreError::PreconditionsAreNotMet
        );

        if self.virtual_inventory_for_swaps() == Some(address) {
            self.virtual_inventory_for_swaps = DEFAULT_PUBKEY;
        } else if self.virtual_inventory_for_positions() == Some(address) {
            self.virtual_inventory_for_positions = DEFAULT_PUBKEY;
        }

        virtual_inventory.leave_unchecked(Delta::new(None, None))?;

        Ok(())
    }

    /// Returns the address of virtual inventory for positions.
    pub fn virtual_inventory_for_positions(&self) -> Option<&Pubkey> {
        optional_address(&self.virtual_inventory_for_positions)
    }

    /// Join a virtual inventory for positions.
    ///
    /// # CHECK
    /// - The provided [`VirtualInventory`] must be used as a
    ///   virtual inventory for positions.
    pub fn join_virtual_inventory_for_positions_unchecked(
        &mut self,
        address: &Pubkey,
        virtual_inventory_for_positions: &mut VirtualInventory,
    ) -> Result<()> {
        require_keys_neq!(*address, DEFAULT_PUBKEY);
        require!(
            self.virtual_inventory_for_positions().is_none(),
            CoreError::PreconditionsAreNotMet
        );
        require!(
            virtual_inventory_for_positions.decimals() == (MARKET_DECIMALS, MARKET_DECIMALS),
            CoreError::Internal
        );
        self.virtual_inventory_for_positions = *address;
        let open_interest = self.open_interest().map_err(ModelError::from)?;
        let (long_amount, short_amount) = cancel_amounts(
            open_interest.long_amount().map_err(ModelError::from)?,
            open_interest.short_amount().map_err(ModelError::from)?,
        );
        virtual_inventory_for_positions.join_unchecked(Delta::new_both_sides(
            true,
            &(long_amount
                .try_into()
                .map_err(|_| error!(CoreError::TokenAmountOverflow))?),
            &(short_amount
                .try_into()
                .map_err(|_| error!(CoreError::TokenAmountOverflow))?),
        ))?;
        virtual_inventory_for_positions.cancel_amounts_unchecked()?;
        Ok(())
    }

    /// Leave the virtual inventory for positions.
    ///
    /// # CHECK
    /// - The provided [`VirtualInventory`] must be the associated one.
    pub fn leave_virtual_inventory_for_positions_unchecked(
        &mut self,
        virtual_inventory_for_positions: &mut VirtualInventory,
    ) -> Result<()> {
        require!(
            self.virtual_inventory_for_positions().is_some(),
            CoreError::PreconditionsAreNotMet
        );
        let open_interest = self.open_interest().map_err(ModelError::from)?;
        let (long_amount, short_amount) = cancel_amounts(
            open_interest.long_amount().map_err(ModelError::from)?,
            open_interest.short_amount().map_err(ModelError::from)?,
        );
        virtual_inventory_for_positions.leave_unchecked(Delta::new_both_sides(
            false,
            &(long_amount
                .try_into()
                .map_err(|_| error!(CoreError::TokenAmountOverflow))?),
            &(short_amount
                .try_into()
                .map_err(|_| error!(CoreError::TokenAmountOverflow))?),
        ))?;
        virtual_inventory_for_positions.cancel_amounts_unchecked()?;
        self.virtual_inventory_for_positions = DEFAULT_PUBKEY;
        Ok(())
    }
}

gmsol_utils::flags!(MarketFlag, MAX_MARKET_FLAGS, u8);

/// Market State.
#[zero_copy]
#[derive(BorshSerialize, BorshDeserialize, InitSpace)]
#[cfg_attr(feature = "debug", derive(derive_more::Debug))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct OtherState {
    #[cfg_attr(feature = "debug", debug(skip))]
    padding: [u8; 16],
    rev: u64,
    trade_count: u64,
    long_token_balance: u64,
    short_token_balance: u64,
    funding_factor_per_second: i128,
    #[cfg_attr(feature = "debug", debug(skip))]
    #[cfg_attr(feature = "serde", serde(with = "serde_bytes"))]
    reserved: [u8; 256],
}

impl OtherState {
    /// Get long token balance.
    pub fn long_token_balance_raw(&self) -> u64 {
        self.long_token_balance
    }

    /// Get short token balance.
    pub fn short_token_balance_raw(&self) -> u64 {
        self.short_token_balance
    }

    /// Get funding factor per second.
    pub fn funding_factor_per_second(&self) -> i128 {
        self.funding_factor_per_second
    }

    /// Get current trade count.
    pub fn trade_count(&self) -> u64 {
        self.trade_count
    }

    /// Next trade id.
    pub fn next_trade_id(&mut self) -> Result<u64> {
        let next_id = self
            .trade_count
            .checked_add(1)
            .ok_or_else(|| error!(CoreError::TokenAmountOverflow))?;
        self.trade_count = next_id;
        Ok(next_id)
    }
}

impl HasMarketMeta for Market {
    fn is_pure(&self) -> bool {
        self.is_pure()
    }

    fn market_meta(&self) -> &MarketMeta {
        &self.meta
    }
}

/// Market clocks.
#[zero_copy]
#[derive(BorshSerialize, BorshDeserialize, InitSpace)]
#[cfg_attr(feature = "debug", derive(derive_more::Debug))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Clocks {
    #[cfg_attr(feature = "debug", debug(skip))]
    padding: [u8; 8],
    rev: u64,
    /// Price impact distribution clock.
    price_impact_distribution: i64,
    /// Borrowing clock.
    borrowing: i64,
    /// Funding clock.
    funding: i64,
    /// ADL updated clock for long.
    adl_for_long: i64,
    /// ADL updated clock for short.
    adl_for_short: i64,
    #[cfg_attr(feature = "debug", debug(skip))]
    reserved: [i64; 3],
}

impl Clocks {
    fn init_to_current(&mut self) -> Result<()> {
        let current = Clock::get()?.unix_timestamp;
        self.price_impact_distribution = current;
        self.borrowing = current;
        self.funding = current;
        Ok(())
    }

    fn get(&self, kind: ClockKind) -> Option<&i64> {
        let clock = match kind {
            ClockKind::PriceImpactDistribution => &self.price_impact_distribution,
            ClockKind::Borrowing => &self.borrowing,
            ClockKind::Funding => &self.funding,
            ClockKind::AdlForLong => &self.adl_for_long,
            ClockKind::AdlForShort => &self.adl_for_short,
            _ => return None,
        };
        Some(clock)
    }

    fn get_mut(&mut self, kind: ClockKind) -> Option<&mut i64> {
        let clock = match kind {
            ClockKind::PriceImpactDistribution => &mut self.price_impact_distribution,
            ClockKind::Borrowing => &mut self.borrowing,
            ClockKind::Funding => &mut self.funding,
            ClockKind::AdlForLong => &mut self.adl_for_long,
            ClockKind::AdlForShort => &mut self.adl_for_short,
            _ => return None,
        };
        Some(clock)
    }
}

/// Market indexer.
#[zero_copy]
#[cfg_attr(feature = "debug", derive(derive_more::Debug))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Indexer {
    trade_count: u64,
    deposit_count: u64,
    withdrawal_count: u64,
    order_count: u64,
    shift_count: u64,
    glv_deposit_count: u64,
    glv_withdrawal_count: u64,
    #[cfg_attr(feature = "debug", debug(skip))]
    padding_0: [u8; 8],
    #[cfg_attr(feature = "debug", debug(skip))]
    #[cfg_attr(feature = "serde", serde(with = "serde_bytes"))]
    reserved: [u8; 128],
}

impl Indexer {
    /// Get current deposit count.
    pub fn deposit_count(&self) -> u64 {
        self.deposit_count
    }

    /// Get current withdrawal count.
    pub fn withdrawal_count(&self) -> u64 {
        self.withdrawal_count
    }

    /// Get current order count.
    pub fn order_count(&self) -> u64 {
        self.order_count
    }

    /// Get current shift count.
    pub fn shift_count(&self) -> u64 {
        self.shift_count
    }

    /// Get current GLV deposit count.
    pub fn glv_deposit_count(&self) -> u64 {
        self.glv_deposit_count
    }

    /// Get current GLV withdrawal count.
    pub fn glv_withdrawal_count(&self) -> u64 {
        self.glv_withdrawal_count
    }

    /// Next deposit id.
    pub fn next_deposit_id(&mut self) -> Result<u64> {
        let next_id = self
            .deposit_count
            .checked_add(1)
            .ok_or_else(|| error!(CoreError::TokenAmountOverflow))?;
        self.deposit_count = next_id;
        Ok(next_id)
    }

    /// Next withdrawal id.
    pub fn next_withdrawal_id(&mut self) -> Result<u64> {
        let next_id = self
            .withdrawal_count
            .checked_add(1)
            .ok_or_else(|| error!(CoreError::TokenAmountOverflow))?;
        self.withdrawal_count = next_id;
        Ok(next_id)
    }

    /// Next order id.
    pub fn next_order_id(&mut self) -> Result<u64> {
        let next_id = self
            .order_count
            .checked_add(1)
            .ok_or_else(|| error!(CoreError::TokenAmountOverflow))?;
        self.order_count = next_id;
        Ok(next_id)
    }

    /// Next shift id.
    pub fn next_shift_id(&mut self) -> Result<u64> {
        let next_id = self
            .shift_count
            .checked_add(1)
            .ok_or_else(|| error!(CoreError::TokenAmountOverflow))?;
        self.shift_count = next_id;
        Ok(next_id)
    }

    /// Next GLV deposit id.
    pub fn next_glv_deposit_id(&mut self) -> Result<u64> {
        let next_id = self
            .glv_deposit_count
            .checked_add(1)
            .ok_or_else(|| error!(CoreError::TokenAmountOverflow))?;
        self.glv_deposit_count = next_id;
        Ok(next_id)
    }

    /// Next GLV withdrawal id.
    pub fn next_glv_withdrawal_id(&mut self) -> Result<u64> {
        let next_id = self
            .glv_withdrawal_count
            .checked_add(1)
            .ok_or_else(|| error!(CoreError::TokenAmountOverflow))?;
        self.glv_withdrawal_count = next_id;
        Ok(next_id)
    }
}

impl From<MarketError> for CoreError {
    fn from(err: MarketError) -> Self {
        msg!("Market Error: {}", err);
        match err {
            MarketError::NotACollateralToken => Self::InvalidArgument,
            MarketError::ExceedMaxMarketConfigFactor => Self::InvalidArgument,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::events::{EventClocks, EventOtherState};

    #[test]
    fn test_event_clocks() {
        let clocks = Clocks {
            padding: Default::default(),
            rev: u64::MAX,
            price_impact_distribution: i64::MAX,
            borrowing: i64::MAX,
            funding: i64::MAX,
            adl_for_long: i64::MAX,
            adl_for_short: i64::MAX,
            reserved: Default::default(),
        };

        let event_clocks = EventClocks {
            padding: clocks.padding,
            rev: clocks.rev,
            price_impact_distribution: clocks.price_impact_distribution,
            borrowing: clocks.borrowing,
            funding: clocks.funding,
            adl_for_long: clocks.adl_for_long,
            adl_for_short: clocks.adl_for_short,
            reserved: clocks.reserved,
        };

        let mut data = Vec::with_capacity(Pool::INIT_SPACE);
        clocks
            .serialize(&mut data)
            .expect("failed to serialize `Clocks`");

        let mut event_data = Vec::with_capacity(Pool::INIT_SPACE);
        event_clocks
            .serialize(&mut event_data)
            .expect("failed to serialize `EventClocks`");

        assert_eq!(data, event_data);
    }

    #[test]
    fn test_event_other_state() {
        let clocks = OtherState {
            padding: Default::default(),
            rev: u64::MAX,
            trade_count: u64::MAX,
            long_token_balance: u64::MAX,
            short_token_balance: u64::MAX,
            funding_factor_per_second: i128::MAX,
            reserved: [0; 256],
        };

        let event_clocks = EventOtherState {
            padding: clocks.padding,
            rev: clocks.rev,
            trade_count: clocks.trade_count,
            long_token_balance: clocks.long_token_balance,
            short_token_balance: clocks.short_token_balance,
            funding_factor_per_second: clocks.funding_factor_per_second,
            reserved: clocks.reserved,
        };

        let mut data = Vec::with_capacity(Pool::INIT_SPACE);
        clocks
            .serialize(&mut data)
            .expect("failed to serialize `OtherState`");

        let mut event_data = Vec::with_capacity(Pool::INIT_SPACE);
        event_clocks
            .serialize(&mut event_data)
            .expect("failed to serialize `EventOtherState`");

        assert_eq!(data, event_data);
    }
}