gmsol-programs 0.9.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
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
use std::{
    borrow::Borrow,
    collections::BTreeMap,
    ops::{Deref, DerefMut},
    sync::Arc,
};

use anchor_lang::prelude::Pubkey;
use bitmaps::Bitmap;
use bytemuck::Zeroable;
use gmsol_model::{
    params::{
        fee::{
            BorrowingFeeKinkModelParams, BorrowingFeeKinkModelParamsForOneSide, BorrowingFeeParams,
            FundingFeeParams, LiquidationFeeParams,
        },
        position::PositionImpactDistributionParams,
        FeeParams, PositionParams, PriceImpactParams,
    },
    PoolKind,
};

use crate::{
    constants,
    gmsol_store::{
        accounts::{Market, Position},
        types::{MarketConfig, MarketMeta, Pool, PoolStorage, Pools},
    },
    model::{position::PositionKind, PositionModel, VirtualInventoryModel},
};

use super::clock::{AsClock, AsClockMut};

impl MarketMeta {
    /// Get token side.
    pub fn token_side(&self, token: &Pubkey) -> gmsol_model::Result<bool> {
        if *token == self.long_token_mint {
            Ok(true)
        } else if *token == self.short_token_mint {
            Ok(false)
        } else {
            Err(gmsol_model::Error::InvalidArgument("not a pool token"))
        }
    }
}

impl Pools {
    fn get(&self, kind: PoolKind) -> Option<&PoolStorage> {
        let pool = match kind {
            PoolKind::Primary => &self.primary,
            PoolKind::SwapImpact => &self.swap_impact,
            PoolKind::ClaimableFee => &self.claimable_fee,
            PoolKind::OpenInterestForLong => &self.open_interest_for_long,
            PoolKind::OpenInterestForShort => &self.open_interest_for_short,
            PoolKind::OpenInterestInTokensForLong => &self.open_interest_in_tokens_for_long,
            PoolKind::OpenInterestInTokensForShort => &self.open_interest_in_tokens_for_short,
            PoolKind::PositionImpact => &self.position_impact,
            PoolKind::BorrowingFactor => &self.borrowing_factor,
            PoolKind::FundingAmountPerSizeForLong => &self.funding_amount_per_size_for_long,
            PoolKind::FundingAmountPerSizeForShort => &self.funding_amount_per_size_for_short,
            PoolKind::ClaimableFundingAmountPerSizeForLong => {
                &self.claimable_funding_amount_per_size_for_long
            }
            PoolKind::ClaimableFundingAmountPerSizeForShort => {
                &self.claimable_funding_amount_per_size_for_short
            }
            PoolKind::CollateralSumForLong => &self.collateral_sum_for_long,
            PoolKind::CollateralSumForShort => &self.collateral_sum_for_short,
            PoolKind::TotalBorrowing => &self.total_borrowing,
            _ => return None,
        };
        Some(pool)
    }

    fn get_mut(&mut self, kind: PoolKind) -> Option<&mut PoolStorage> {
        let pool = match kind {
            PoolKind::Primary => &mut self.primary,
            PoolKind::SwapImpact => &mut self.swap_impact,
            PoolKind::ClaimableFee => &mut self.claimable_fee,
            PoolKind::OpenInterestForLong => &mut self.open_interest_for_long,
            PoolKind::OpenInterestForShort => &mut self.open_interest_for_short,
            PoolKind::OpenInterestInTokensForLong => &mut self.open_interest_in_tokens_for_long,
            PoolKind::OpenInterestInTokensForShort => &mut self.open_interest_in_tokens_for_short,
            PoolKind::PositionImpact => &mut self.position_impact,
            PoolKind::BorrowingFactor => &mut self.borrowing_factor,
            PoolKind::FundingAmountPerSizeForLong => &mut self.funding_amount_per_size_for_long,
            PoolKind::FundingAmountPerSizeForShort => &mut self.funding_amount_per_size_for_short,
            PoolKind::ClaimableFundingAmountPerSizeForLong => {
                &mut self.claimable_funding_amount_per_size_for_long
            }
            PoolKind::ClaimableFundingAmountPerSizeForShort => {
                &mut self.claimable_funding_amount_per_size_for_short
            }
            PoolKind::CollateralSumForLong => &mut self.collateral_sum_for_long,
            PoolKind::CollateralSumForShort => &mut self.collateral_sum_for_short,
            PoolKind::TotalBorrowing => &mut self.total_borrowing,
            _ => return None,
        };
        Some(pool)
    }
}

#[repr(u8)]
enum MarketConfigFlag {
    SkipBorrowingFeeForSmallerSide,
    IgnoreOpenInterestForUsageFactor,
    EnableMarketClosedParams,
    MarketClosedSkipBorrowingFeeForSmallerSide,
}

type MarketConfigFlags = Bitmap<{ constants::NUM_MARKET_CONFIG_FLAGS }>;

impl MarketConfig {
    fn flag(&self, flag: MarketConfigFlag) -> bool {
        MarketConfigFlags::from_value(self.flag.value).get(flag as usize)
    }

    fn use_market_closed_params(&self, is_market_closed: bool) -> bool {
        is_market_closed && self.flag(MarketConfigFlag::EnableMarketClosedParams)
    }

    fn min_collateral_factor_for_liquidation(&self, is_market_closed: bool) -> Option<u128> {
        let factor = if self.use_market_closed_params(is_market_closed) {
            self.market_closed_min_collateral_factor_for_liquidation
        } else {
            self.min_collateral_factor_for_liquidation
        };
        if factor == 0 {
            None
        } else {
            Some(factor)
        }
    }

    fn skip_borrowing_fee_for_smaller_side(&self, is_market_closed: bool) -> bool {
        if self.use_market_closed_params(is_market_closed) {
            self.flag(MarketConfigFlag::MarketClosedSkipBorrowingFeeForSmallerSide)
        } else {
            self.flag(MarketConfigFlag::SkipBorrowingFeeForSmallerSide)
        }
    }

    fn borrowing_fee_base_factor(&self, for_long: bool, is_market_closed: bool) -> u128 {
        match (self.use_market_closed_params(is_market_closed), for_long) {
            (true, _) => self.market_closed_borrowing_fee_base_factor,
            (false, true) => self.borrowing_fee_base_factor_for_long,
            (false, false) => self.borrowing_fee_base_factor_for_short,
        }
    }

    /// Returns above optimal usage borrowing fee factor.
    fn borrowing_fee_above_optimal_usage_factor(
        &self,
        for_long: bool,
        is_market_closed: bool,
    ) -> u128 {
        match (self.use_market_closed_params(is_market_closed), for_long) {
            (true, _) => self.market_closed_borrowing_fee_above_optimal_usage_factor,
            (false, true) => self.borrowing_fee_above_optimal_usage_factor_for_long,
            (false, false) => self.borrowing_fee_above_optimal_usage_factor_for_short,
        }
    }
}

#[repr(u8)]
#[allow(dead_code)]
enum MarketFlag {
    Enabled,
    Pure,
    AutoDeleveragingEnabledForLong,
    AutoDeleveragingEnabledForShort,
    GTEnabled,
    Closed,
}

type MarketFlags = Bitmap<{ constants::NUM_MARKET_FLAGS }>;

impl Market {
    fn try_pool(&self, kind: PoolKind) -> gmsol_model::Result<&Pool> {
        Ok(&self
            .state
            .pools
            .get(kind)
            .ok_or(gmsol_model::Error::MissingPoolKind(kind))?
            .pool)
    }

    fn try_pool_mut(&mut self, kind: PoolKind) -> gmsol_model::Result<&mut Pool> {
        Ok(&mut self
            .state
            .pools
            .get_mut(kind)
            .ok_or(gmsol_model::Error::MissingPoolKind(kind))?
            .pool)
    }

    fn flag(&self, flag: MarketFlag) -> bool {
        MarketFlags::from_value(self.flags.value).get(flag as usize)
    }

    fn is_closed(&self) -> bool {
        self.flag(MarketFlag::Closed)
    }
}

/// Swap Pricing Kind.
#[derive(Debug, Clone, Copy, Default)]
pub enum SwapPricingKind {
    /// Swap.
    #[default]
    Swap,
    /// Deposit.
    Deposit,
    /// Withdrawal.
    Withdrawal,
    /// Shift.
    Shift,
}

/// Market Model.
#[derive(Debug, Clone)]
pub struct MarketModel {
    market: Arc<Market>,
    supply: u64,
    swap_pricing: SwapPricingKind,
    vi_for_swaps: Option<VirtualInventoryModel>,
    vi_for_positions: Option<VirtualInventoryModel>,
    disable_vis: bool,
    order_fee_discount_factor: u128,
}

impl Deref for MarketModel {
    type Target = Market;

    fn deref(&self) -> &Self::Target {
        &self.market
    }
}

impl MarketModel {
    /// Create from parts.
    pub fn from_parts(market: Arc<Market>, supply: u64) -> Self {
        Self {
            market,
            supply,
            swap_pricing: Default::default(),
            vi_for_swaps: None,
            vi_for_positions: None,
            disable_vis: false,
            order_fee_discount_factor: 0,
        }
    }

    /// Get whether it is a pure market.
    pub fn is_pure(&self) -> bool {
        self.market.flag(MarketFlag::Pure)
    }

    /// Get swap pricing kind.
    pub fn swap_pricing(&self) -> &SwapPricingKind {
        &self.swap_pricing
    }

    /// Execute a function with the specified swap pricing kind.
    ///
    /// # Panic Safety
    /// This method uses RAII to ensure state is restored even if the closure panics.
    pub fn with_swap_pricing<T>(
        &mut self,
        swap_pricing: SwapPricingKind,
        f: impl FnOnce(&mut Self) -> T,
    ) -> T {
        struct SwapPricingGuard<'a> {
            model: &'a mut MarketModel,
            original_swap_pricing: SwapPricingKind,
        }

        impl Drop for SwapPricingGuard<'_> {
            fn drop(&mut self) {
                self.model.swap_pricing = self.original_swap_pricing;
            }
        }

        let original_swap_pricing = self.swap_pricing;
        self.swap_pricing = swap_pricing;

        let guard = SwapPricingGuard {
            model: self,
            original_swap_pricing,
        };

        (f)(guard.model)
        // guard is automatically dropped at the end of scope, restoring original state
    }

    /// Execute a function with virtual inventory models from a map.
    ///
    /// This method temporarily replaces the virtual inventory models
    /// (for swaps and positions) of the `MarketModel` with models from the provided map,
    /// executes the provided function, and then restores the original values.
    ///
    /// The virtual inventory models are looked up from the map using the market's
    /// `virtual_inventory_for_swaps` and `virtual_inventory_for_positions` addresses.
    ///
    /// # Arguments
    /// * `vi_map` - A mutable reference to a map of Pubkey to VirtualInventoryModel
    /// * `f` - Function to execute with the temporary VI models
    ///
    /// # Returns
    /// The return value of the function `f`
    ///
    /// # Note
    /// The virtual inventory models are passed via a mutable reference to a map,
    /// allowing the caller to maintain access to the models and observe any
    /// state changes made during the function execution.
    ///
    /// # Panic Safety
    /// This method uses RAII to ensure state is restored even if the closure panics.
    ///
    /// # Notes
    /// - If the `MarketModel` already has virtual inventory models attached
    ///   (i.e. `vi_for_swaps` / `vi_for_positions` are `Some`), this function
    ///   will not load VI models from `vi_map` and will not write any changes
    ///   back to `vi_map`. In that case, only the existing in-model VI
    ///   instances are used and mutated.
    pub fn with_vi_models<T>(
        &mut self,
        vi_map: &mut BTreeMap<Pubkey, VirtualInventoryModel>,
        f: impl FnOnce(&mut Self) -> T,
    ) -> T {
        struct ViModelsGuard<'a> {
            model: &'a mut MarketModel,
            vi_map: &'a mut BTreeMap<Pubkey, VirtualInventoryModel>,
            vi_for_swaps_key: Option<Pubkey>,
            vi_for_positions_key: Option<Pubkey>,
            loaded_from_map_for_swaps: bool,
            loaded_from_map_for_positions: bool,
        }

        impl Drop for ViModelsGuard<'_> {
            fn drop(&mut self) {
                // All cleanup work must be done in Drop to ensure panic safety.
                // This includes:
                // 1. Moving VI models back to vi_map
                // 2. Setting vi_for_* to None in the model (via take())
                if self.loaded_from_map_for_swaps {
                    if let (Some(key), Some(vi_for_swaps_model)) =
                        (self.vi_for_swaps_key, self.model.vi_for_swaps.take())
                    {
                        self.vi_map.insert(key, vi_for_swaps_model);
                    }
                }
                if self.loaded_from_map_for_positions {
                    if let (Some(key), Some(vi_for_positions_model)) = (
                        self.vi_for_positions_key,
                        self.model.vi_for_positions.take(),
                    ) {
                        self.vi_map.insert(key, vi_for_positions_model);
                    }
                }
            }
        }

        // Determine the VI addresses, if any.
        let vi_for_swaps_key = (self.market.virtual_inventory_for_swaps != Pubkey::default())
            .then_some(self.market.virtual_inventory_for_swaps);
        let vi_for_positions_key = (self.market.virtual_inventory_for_positions
            != Pubkey::default())
        .then_some(self.market.virtual_inventory_for_positions);

        // Attach VI models from the map to the MarketModel *only if* the model
        // does not already have VI models attached. This ensures that nested
        // calls to `with_vi_models` reuse the same VI instances instead of
        // creating independent copies.
        let mut loaded_from_map_for_swaps = false;
        if self.vi_for_swaps.is_none() {
            if let Some(key) = vi_for_swaps_key {
                if let Some(vi_model) = vi_map.remove(&key) {
                    self.vi_for_swaps = Some(vi_model);
                    loaded_from_map_for_swaps = true;
                }
            }
        }

        let mut loaded_from_map_for_positions = false;
        if self.vi_for_positions.is_none() {
            if let Some(key) = vi_for_positions_key {
                if let Some(vi_model) = vi_map.remove(&key) {
                    self.vi_for_positions = Some(vi_model);
                    loaded_from_map_for_positions = true;
                }
            }
        }

        // Use a scope block to limit guard's lifetime to f's execution only.
        // This ensures:
        // 1. Panic safety: guard drop will restore VI models even if f panics
        // 2. vi_map is released immediately after f completes, allowing future access
        {
            let guard = ViModelsGuard {
                model: self,
                vi_map,
                vi_for_swaps_key,
                vi_for_positions_key,
                loaded_from_map_for_swaps,
                loaded_from_map_for_positions,
            };
            (f)(guard.model)
            // guard is dropped here, restoring VI models to vi_map
        }
    }

    /// Execute a function with or without virtual inventories depending on the given map.
    ///
    /// - If `vi_map` is `Some`, this will attach VI models from the map via [`Self::with_vi_models`].
    /// - If `vi_map` is `None`, this will temporarily disable VIs via [`Self::with_vis_disabled`].
    ///
    /// This is a small utility to unify the entry point of VI enable/disable logic so that
    /// callers do not need to duplicate branching between `with_vi_models` and
    /// `with_vis_disabled`.
    pub fn with_vis_if<T>(
        &mut self,
        vi_map: Option<&mut BTreeMap<Pubkey, VirtualInventoryModel>>,
        f: impl FnOnce(&mut Self) -> T,
    ) -> T {
        match vi_map {
            Some(vi_map) => self.with_vi_models(vi_map, f),
            None => self.with_vis_disabled(f),
        }
    }

    /// Execute a function with virtual inventories disabled.
    ///
    /// # Panic Safety
    /// This method uses RAII to ensure state is restored even if the closure panics.
    pub fn with_vis_disabled<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
        struct DisableVisGuard<'a> {
            model: &'a mut MarketModel,
            original_disable_vis: bool,
        }

        impl Drop for DisableVisGuard<'_> {
            fn drop(&mut self) {
                self.model.disable_vis = self.original_disable_vis;
            }
        }

        let original_disable_vis = self.disable_vis;
        self.disable_vis = true;

        let guard = DisableVisGuard {
            model: self,
            original_disable_vis,
        };

        (f)(guard.model)
        // guard is automatically dropped at the end of scope, restoring original state
    }

    /// Record transferred in.
    fn record_transferred_in(
        &mut self,
        is_long_token: bool,
        amount: u64,
    ) -> gmsol_model::Result<()> {
        let is_pure = self.market.flag(MarketFlag::Pure);
        let other = &self.market.state.other;

        if is_pure || is_long_token {
            self.make_market_mut().state.other.long_token_balance =
                other.long_token_balance.checked_add(amount).ok_or(
                    gmsol_model::Error::Computation("increasing long token balance"),
                )?;
        } else {
            self.make_market_mut().state.other.short_token_balance =
                other.short_token_balance.checked_add(amount).ok_or(
                    gmsol_model::Error::Computation("increasing short token balance"),
                )?;
        }

        Ok(())
    }

    /// Record transferred out.
    fn record_transferred_out(
        &mut self,
        is_long_token: bool,
        amount: u64,
    ) -> gmsol_model::Result<()> {
        let is_pure = self.market.flag(MarketFlag::Pure);
        let other = &self.market.state.other;

        if is_pure || is_long_token {
            self.make_market_mut().state.other.long_token_balance =
                other.long_token_balance.checked_sub(amount).ok_or(
                    gmsol_model::Error::Computation("decreasing long token balance"),
                )?;
        } else {
            self.make_market_mut().state.other.short_token_balance =
                other.short_token_balance.checked_sub(amount).ok_or(
                    gmsol_model::Error::Computation("decreasing long token balance"),
                )?;
        }

        Ok(())
    }

    fn balance_for_token(&self, is_long_token: bool) -> u64 {
        let other = &self.state.other;
        if is_long_token || self.market.flag(MarketFlag::Pure) {
            other.long_token_balance
        } else {
            other.short_token_balance
        }
    }

    fn make_market_mut(&mut self) -> &mut Market {
        Arc::make_mut(&mut self.market)
    }

    /// Check if the market has a virtual inventory address for swaps.
    fn has_vi_for_swaps_address(&self) -> bool {
        self.market.virtual_inventory_for_swaps != Pubkey::default()
    }

    /// Check if the market has a virtual inventory address for positions.
    fn has_vi_for_positions_address(&self) -> bool {
        self.market.virtual_inventory_for_positions != Pubkey::default()
    }

    /// Validate virtual inventory consistency for swaps.
    ///
    /// # Note
    /// We do not validate PDA address matching here because:
    /// - The assumption that the provided VI address must match the calculated PDA is too strong
    /// - PDA address calculation has high computational cost
    fn validate_vi_for_swaps(&self) -> gmsol_model::Result<()> {
        if self.disable_vis {
            return Ok(());
        }

        let market_has_vi = self.has_vi_for_swaps_address();
        let model_has_vi = self.vi_for_swaps.is_some();

        match (market_has_vi, model_has_vi) {
            (true, false) => Err(gmsol_model::Error::InvalidArgument(
                "virtual inventory for swaps should be present but is missing",
            )),
            (false, true) => Err(gmsol_model::Error::InvalidArgument(
                "virtual inventory for swaps should not be present but is provided",
            )),
            _ => Ok(()),
        }
    }

    /// Validate virtual inventory consistency for positions.
    ///
    /// # Note
    /// We do not validate PDA address matching here because:
    /// - The assumption that the provided VI address must match the calculated PDA is too strong
    /// - PDA address calculation has high computational cost
    fn validate_vi_for_positions(&self) -> gmsol_model::Result<()> {
        if self.disable_vis {
            return Ok(());
        }

        let market_has_vi = self.has_vi_for_positions_address();
        let model_has_vi = self.vi_for_positions.is_some();

        match (market_has_vi, model_has_vi) {
            (true, false) => Err(gmsol_model::Error::InvalidArgument(
                "virtual inventory for positions should be present but is missing",
            )),
            (false, true) => Err(gmsol_model::Error::InvalidArgument(
                "virtual inventory for positions should not be present but is provided",
            )),
            _ => Ok(()),
        }
    }

    /// Returns the time in seconds since last funding fee state update.
    pub fn passed_in_seconds_for_funding(&self) -> gmsol_model::Result<u64> {
        AsClock::from(&self.state.clocks.funding).passed_in_seconds()
    }

    /// Convert into an empty position model.
    ///
    /// # Notes
    /// - All position parameters unrelated to the model,
    ///   such as `owner` and `bump`, use zeroed values.
    pub fn into_empty_position(
        self,
        is_long: bool,
        collateral_token: Pubkey,
    ) -> gmsol_model::Result<PositionModel> {
        self.into_empty_position_opts(is_long, collateral_token, Default::default())
    }

    /// Convert into an empty position model with options.
    pub fn into_empty_position_opts(
        self,
        is_long: bool,
        collateral_token: Pubkey,
        options: PositionOptions,
    ) -> gmsol_model::Result<PositionModel> {
        const POSITION_SEED: &[u8] = b"position";

        if !(self.meta.long_token_mint == collateral_token
            || self.meta.short_token_mint == collateral_token)
        {
            return Err(gmsol_model::Error::InvalidArgument(
                "invalid `collateral_token`",
            ));
        }

        let owner = options.owner.unwrap_or_default();
        let store = &self.store;
        let market_token = &self.meta.market_token_mint;
        let kind = if is_long {
            PositionKind::Long
        } else {
            PositionKind::Short
        } as u8;

        let bump = if options.generate_bump {
            Pubkey::find_program_address(
                &[
                    POSITION_SEED,
                    store.as_ref(),
                    owner.as_ref(),
                    market_token.as_ref(),
                    collateral_token.as_ref(),
                    &[kind],
                ],
                &options.store_program_id,
            )
            .1
        } else {
            0
        };

        let position = Position {
            version: 0,
            bump,
            store: *store,
            kind,
            padding_0: Zeroable::zeroed(),
            created_at: options.created_at,
            owner,
            market_token: *market_token,
            collateral_token,
            state: Zeroable::zeroed(),
            reserved: Zeroable::zeroed(),
        };
        PositionModel::new(self, Arc::new(position))
    }

    /// Set order fee discount factor.
    pub fn set_order_fee_discount_factor(&mut self, factor: u128) {
        self.order_fee_discount_factor = factor;
    }
}

/// Options for creating a position model.
#[derive(Debug, Clone)]
pub struct PositionOptions {
    /// The owner of the position.
    ///
    /// If set to `None`, the `owner` will use the default pubkey.
    pub owner: Option<Pubkey>,
    /// The timestamp of the position creation.
    pub created_at: i64,
    /// Whether to generate a bump seed.
    ///
    /// If set `false`, the `bump` will be fixed to `0`.
    pub generate_bump: bool,
    /// The store program ID used to generate the bump seed.
    pub store_program_id: Pubkey,
}

impl Default for PositionOptions {
    fn default() -> Self {
        Self {
            owner: None,
            created_at: 0,
            generate_bump: false,
            store_program_id: crate::gmsol_store::ID,
        }
    }
}

impl gmsol_model::BaseMarket<{ constants::MARKET_DECIMALS }> for MarketModel {
    type Num = u128;

    type Signed = i128;

    type Pool = Pool;

    fn liquidity_pool(&self) -> gmsol_model::Result<&Self::Pool> {
        self.try_pool(PoolKind::Primary)
    }

    fn claimable_fee_pool(&self) -> gmsol_model::Result<&Self::Pool> {
        self.try_pool(PoolKind::ClaimableFee)
    }

    fn swap_impact_pool(&self) -> gmsol_model::Result<&Self::Pool> {
        self.try_pool(PoolKind::SwapImpact)
    }

    fn open_interest_pool(&self, is_long: bool) -> gmsol_model::Result<&Self::Pool> {
        self.try_pool(if is_long {
            PoolKind::OpenInterestForLong
        } else {
            PoolKind::OpenInterestForShort
        })
    }

    fn open_interest_in_tokens_pool(&self, is_long: bool) -> gmsol_model::Result<&Self::Pool> {
        self.try_pool(if is_long {
            PoolKind::OpenInterestInTokensForLong
        } else {
            PoolKind::OpenInterestInTokensForShort
        })
    }

    fn collateral_sum_pool(&self, is_long: bool) -> gmsol_model::Result<&Self::Pool> {
        let kind = if is_long {
            PoolKind::CollateralSumForLong
        } else {
            PoolKind::CollateralSumForShort
        };
        self.try_pool(kind)
    }

    fn virtual_inventory_for_swaps_pool(
        &self,
    ) -> gmsol_model::Result<Option<impl Deref<Target = Self::Pool>>> {
        if self.disable_vis {
            return Ok(None);
        }
        self.validate_vi_for_swaps()?;
        Ok(self.vi_for_swaps.as_ref().map(|vi| vi.pool()))
    }

    fn virtual_inventory_for_positions_pool(
        &self,
    ) -> gmsol_model::Result<Option<impl Deref<Target = Self::Pool>>> {
        if self.disable_vis {
            return Ok(None);
        }
        self.validate_vi_for_positions()?;
        Ok(self.vi_for_positions.as_ref().map(|vi| vi.pool()))
    }

    fn usd_to_amount_divisor(&self) -> Self::Num {
        constants::MARKET_USD_TO_AMOUNT_DIVISOR
    }

    fn max_pool_amount(&self, is_long_token: bool) -> gmsol_model::Result<Self::Num> {
        if is_long_token {
            Ok(self.config.max_pool_amount_for_long_token)
        } else {
            Ok(self.config.max_pool_amount_for_short_token)
        }
    }

    fn pnl_factor_config(
        &self,
        kind: gmsol_model::PnlFactorKind,
        is_long: bool,
    ) -> gmsol_model::Result<Self::Num> {
        use gmsol_model::PnlFactorKind;

        match (kind, is_long) {
            (PnlFactorKind::MaxAfterDeposit, true) => {
                Ok(self.config.max_pnl_factor_for_long_deposit)
            }
            (PnlFactorKind::MaxAfterDeposit, false) => {
                Ok(self.config.max_pnl_factor_for_short_deposit)
            }
            (PnlFactorKind::MaxAfterWithdrawal, true) => {
                Ok(self.config.max_pnl_factor_for_long_withdrawal)
            }
            (PnlFactorKind::MaxAfterWithdrawal, false) => {
                Ok(self.config.max_pnl_factor_for_short_withdrawal)
            }
            (PnlFactorKind::MaxForTrader, true) => Ok(self.config.max_pnl_factor_for_long_trader),
            (PnlFactorKind::MaxForTrader, false) => Ok(self.config.max_pnl_factor_for_short_trader),
            (PnlFactorKind::ForAdl, true) => Ok(self.config.max_pnl_factor_for_long_adl),
            (PnlFactorKind::ForAdl, false) => Ok(self.config.max_pnl_factor_for_short_adl),
            (PnlFactorKind::MinAfterAdl, true) => Ok(self.config.min_pnl_factor_after_long_adl),
            (PnlFactorKind::MinAfterAdl, false) => Ok(self.config.min_pnl_factor_after_short_adl),
            _ => Err(gmsol_model::Error::InvalidArgument("missing pnl factor")),
        }
    }

    fn reserve_factor(&self) -> gmsol_model::Result<Self::Num> {
        Ok(self.config.reserve_factor)
    }

    fn open_interest_reserve_factor(&self) -> gmsol_model::Result<Self::Num> {
        Ok(self.config.open_interest_reserve_factor)
    }

    fn max_open_interest(&self, is_long: bool) -> gmsol_model::Result<Self::Num> {
        if is_long {
            Ok(self.config.max_open_interest_for_long)
        } else {
            Ok(self.config.max_open_interest_for_short)
        }
    }

    fn ignore_open_interest_for_usage_factor(&self) -> gmsol_model::Result<bool> {
        Ok(self
            .config
            .flag(MarketConfigFlag::IgnoreOpenInterestForUsageFactor))
    }
}

impl gmsol_model::SwapMarket<{ constants::MARKET_DECIMALS }> for MarketModel {
    fn swap_impact_params(&self) -> gmsol_model::Result<PriceImpactParams<Self::Num>> {
        Ok(PriceImpactParams::builder()
            .exponent(self.config.swap_impact_exponent)
            .positive_factor(self.config.swap_impact_positive_factor)
            .negative_factor(self.config.swap_impact_negative_factor)
            .build())
    }

    fn swap_fee_params(&self) -> gmsol_model::Result<FeeParams<Self::Num>> {
        let params = match self.swap_pricing {
            SwapPricingKind::Shift => FeeParams::builder()
                .fee_receiver_factor(self.config.swap_fee_receiver_factor)
                .positive_impact_fee_factor(0)
                .negative_impact_fee_factor(0)
                .build(),
            SwapPricingKind::Swap | SwapPricingKind::Deposit | SwapPricingKind::Withdrawal => {
                FeeParams::builder()
                    .fee_receiver_factor(self.config.swap_fee_receiver_factor)
                    .positive_impact_fee_factor(self.config.swap_fee_factor_for_positive_impact)
                    .negative_impact_fee_factor(self.config.swap_fee_factor_for_negative_impact)
                    .build()
            }
        };

        Ok(params)
    }
}

impl gmsol_model::PositionImpactMarket<{ constants::MARKET_DECIMALS }> for MarketModel {
    fn position_impact_pool(&self) -> gmsol_model::Result<&Self::Pool> {
        self.try_pool(PoolKind::PositionImpact)
    }

    fn position_impact_params(&self) -> gmsol_model::Result<PriceImpactParams<Self::Num>> {
        let config = &self.config;
        Ok(PriceImpactParams::builder()
            .exponent(config.position_impact_exponent)
            .positive_factor(config.position_impact_positive_factor)
            .negative_factor(config.position_impact_negative_factor)
            .build())
    }

    fn position_impact_distribution_params(
        &self,
    ) -> gmsol_model::Result<PositionImpactDistributionParams<Self::Num>> {
        let config = &self.config;
        Ok(PositionImpactDistributionParams::builder()
            .distribute_factor(config.position_impact_distribute_factor)
            .min_position_impact_pool_amount(config.min_position_impact_pool_amount)
            .build())
    }

    fn passed_in_seconds_for_position_impact_distribution(&self) -> gmsol_model::Result<u64> {
        AsClock::from(&self.state.clocks.price_impact_distribution).passed_in_seconds()
    }
}

impl gmsol_model::BorrowingFeeMarket<{ constants::MARKET_DECIMALS }> for MarketModel {
    fn borrowing_factor_pool(&self) -> gmsol_model::Result<&Self::Pool> {
        self.try_pool(PoolKind::BorrowingFactor)
    }

    fn total_borrowing_pool(&self) -> gmsol_model::Result<&Self::Pool> {
        self.try_pool(PoolKind::TotalBorrowing)
    }

    fn borrowing_fee_params(&self) -> gmsol_model::Result<BorrowingFeeParams<Self::Num>> {
        Ok(BorrowingFeeParams::builder()
            .receiver_factor(self.config.borrowing_fee_receiver_factor)
            .factor_for_long(self.config.borrowing_fee_factor_for_long)
            .factor_for_short(self.config.borrowing_fee_factor_for_short)
            .exponent_for_long(self.config.borrowing_fee_exponent_for_long)
            .exponent_for_short(self.config.borrowing_fee_exponent_for_short)
            .skip_borrowing_fee_for_smaller_side(
                self.config
                    .skip_borrowing_fee_for_smaller_side(self.is_closed()),
            )
            .build())
    }

    fn passed_in_seconds_for_borrowing(&self) -> gmsol_model::Result<u64> {
        AsClock::from(&self.state.clocks.borrowing).passed_in_seconds()
    }

    fn borrowing_fee_kink_model_params(
        &self,
    ) -> gmsol_model::Result<BorrowingFeeKinkModelParams<Self::Num>> {
        let is_closed = self.is_closed();
        Ok(BorrowingFeeKinkModelParams::builder()
            .long(
                BorrowingFeeKinkModelParamsForOneSide::builder()
                    .optimal_usage_factor(self.config.borrowing_fee_optimal_usage_factor_for_long)
                    .base_borrowing_factor(self.config.borrowing_fee_base_factor(true, is_closed))
                    .above_optimal_usage_borrowing_factor(
                        self.config
                            .borrowing_fee_above_optimal_usage_factor(true, is_closed),
                    )
                    .build(),
            )
            .short(
                BorrowingFeeKinkModelParamsForOneSide::builder()
                    .optimal_usage_factor(self.config.borrowing_fee_optimal_usage_factor_for_short)
                    .base_borrowing_factor(self.config.borrowing_fee_base_factor(false, is_closed))
                    .above_optimal_usage_borrowing_factor(
                        self.config
                            .borrowing_fee_above_optimal_usage_factor(false, is_closed),
                    )
                    .build(),
            )
            .build())
    }
}

impl gmsol_model::PerpMarket<{ constants::MARKET_DECIMALS }> for MarketModel {
    fn funding_factor_per_second(&self) -> &Self::Signed {
        &self.state.other.funding_factor_per_second
    }

    fn funding_amount_per_size_pool(&self, is_long: bool) -> gmsol_model::Result<&Self::Pool> {
        let kind = if is_long {
            PoolKind::FundingAmountPerSizeForLong
        } else {
            PoolKind::FundingAmountPerSizeForShort
        };
        self.try_pool(kind)
    }

    fn claimable_funding_amount_per_size_pool(
        &self,
        is_long: bool,
    ) -> gmsol_model::Result<&Self::Pool> {
        let kind = if is_long {
            PoolKind::ClaimableFundingAmountPerSizeForLong
        } else {
            PoolKind::ClaimableFundingAmountPerSizeForShort
        };
        self.try_pool(kind)
    }

    fn funding_amount_per_size_adjustment(&self) -> Self::Num {
        constants::FUNDING_AMOUNT_PER_SIZE_ADJUSTMENT
    }

    fn funding_fee_params(&self) -> gmsol_model::Result<FundingFeeParams<Self::Num>> {
        Ok(FundingFeeParams::builder()
            .exponent(self.config.funding_fee_exponent)
            .funding_factor(self.config.funding_fee_factor)
            .max_factor_per_second(self.config.funding_fee_max_factor_per_second)
            .min_factor_per_second(self.config.funding_fee_min_factor_per_second)
            .increase_factor_per_second(self.config.funding_fee_increase_factor_per_second)
            .decrease_factor_per_second(self.config.funding_fee_decrease_factor_per_second)
            .threshold_for_stable_funding(self.config.funding_fee_threshold_for_stable_funding)
            .threshold_for_decrease_funding(self.config.funding_fee_threshold_for_decrease_funding)
            .build())
    }

    fn position_params(&self) -> gmsol_model::Result<PositionParams<Self::Num>> {
        Ok(PositionParams::builder()
            .min_position_size_usd(self.config.min_position_size_usd)
            .min_collateral_value(self.config.min_collateral_value)
            .min_collateral_factor(self.config.min_collateral_factor)
            .max_positive_position_impact_factor(self.config.max_positive_position_impact_factor)
            .max_negative_position_impact_factor(self.config.max_negative_position_impact_factor)
            .max_position_impact_factor_for_liquidations(
                self.config.max_position_impact_factor_for_liquidations,
            )
            .min_collateral_factor_for_liquidation(
                self.config
                    .min_collateral_factor_for_liquidation(self.is_closed()),
            )
            .build())
    }

    fn order_fee_params(&self) -> gmsol_model::Result<FeeParams<Self::Num>> {
        Ok(FeeParams::builder()
            .fee_receiver_factor(self.config.order_fee_receiver_factor)
            .positive_impact_fee_factor(self.config.order_fee_factor_for_positive_impact)
            .negative_impact_fee_factor(self.config.order_fee_factor_for_negative_impact)
            .build()
            .with_discount_factor(self.order_fee_discount_factor))
    }

    fn min_collateral_factor_for_open_interest_multiplier(
        &self,
        is_long: bool,
    ) -> gmsol_model::Result<Self::Num> {
        if is_long {
            Ok(self
                .config
                .min_collateral_factor_for_open_interest_multiplier_for_long)
        } else {
            Ok(self
                .config
                .min_collateral_factor_for_open_interest_multiplier_for_short)
        }
    }

    fn liquidation_fee_params(&self) -> gmsol_model::Result<LiquidationFeeParams<Self::Num>> {
        Ok(LiquidationFeeParams::builder()
            .factor(self.config.liquidation_fee_factor)
            .receiver_factor(self.config.liquidation_fee_receiver_factor)
            .build())
    }
}

impl gmsol_model::LiquidityMarket<{ constants::MARKET_DECIMALS }> for MarketModel {
    fn total_supply(&self) -> Self::Num {
        u128::from(self.supply)
    }

    fn max_pool_value_for_deposit(&self, is_long_token: bool) -> gmsol_model::Result<Self::Num> {
        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)
        }
    }
}

impl gmsol_model::Bank<Pubkey> for MarketModel {
    type Num = u64;

    fn record_transferred_in_by_token<Q: ?Sized + Borrow<Pubkey>>(
        &mut self,
        token: &Q,
        amount: &Self::Num,
    ) -> gmsol_model::Result<()> {
        let is_long_token = self.market.meta.token_side(token.borrow())?;
        self.record_transferred_in(is_long_token, *amount)?;
        Ok(())
    }

    fn record_transferred_out_by_token<Q: ?Sized + Borrow<Pubkey>>(
        &mut self,
        token: &Q,
        amount: &Self::Num,
    ) -> gmsol_model::Result<()> {
        let is_long_token = self.market.meta.token_side(token.borrow())?;
        self.record_transferred_out(is_long_token, *amount)?;
        Ok(())
    }

    fn balance<Q: Borrow<Pubkey> + ?Sized>(&self, token: &Q) -> gmsol_model::Result<Self::Num> {
        let side = self.market.meta.token_side(token.borrow())?;
        Ok(self.balance_for_token(side))
    }
}

impl gmsol_model::BaseMarketMut<{ constants::MARKET_DECIMALS }> for MarketModel {
    fn liquidity_pool_mut(&mut self) -> gmsol_model::Result<&mut Self::Pool> {
        self.make_market_mut().try_pool_mut(PoolKind::Primary)
    }

    fn claimable_fee_pool_mut(&mut self) -> gmsol_model::Result<&mut Self::Pool> {
        self.make_market_mut().try_pool_mut(PoolKind::ClaimableFee)
    }

    fn virtual_inventory_for_swaps_pool_mut(
        &mut self,
    ) -> gmsol_model::Result<Option<impl DerefMut<Target = Self::Pool>>> {
        if self.disable_vis {
            return Ok(None);
        }
        self.validate_vi_for_swaps()?;
        Ok(self.vi_for_swaps.as_mut().map(|vi| vi.pool_mut()))
    }
}

impl gmsol_model::SwapMarketMut<{ constants::MARKET_DECIMALS }> for MarketModel {
    fn swap_impact_pool_mut(&mut self) -> gmsol_model::Result<&mut Self::Pool> {
        self.make_market_mut().try_pool_mut(PoolKind::SwapImpact)
    }
}

impl gmsol_model::PositionImpactMarketMut<{ constants::MARKET_DECIMALS }> for MarketModel {
    fn position_impact_pool_mut(&mut self) -> gmsol_model::Result<&mut Self::Pool> {
        self.make_market_mut()
            .try_pool_mut(PoolKind::PositionImpact)
    }

    fn just_passed_in_seconds_for_position_impact_distribution(
        &mut self,
    ) -> gmsol_model::Result<u64> {
        AsClockMut::from(
            &mut self
                .make_market_mut()
                .state
                .clocks
                .price_impact_distribution,
        )
        .just_passed_in_seconds()
    }
}

impl gmsol_model::PerpMarketMut<{ constants::MARKET_DECIMALS }> for MarketModel {
    fn just_passed_in_seconds_for_funding(&mut self) -> gmsol_model::Result<u64> {
        AsClockMut::from(&mut self.make_market_mut().state.clocks.funding).just_passed_in_seconds()
    }

    fn funding_factor_per_second_mut(&mut self) -> &mut Self::Signed {
        &mut self.make_market_mut().state.other.funding_factor_per_second
    }

    fn open_interest_pool_mut(&mut self, is_long: bool) -> gmsol_model::Result<&mut Self::Pool> {
        self.make_market_mut().try_pool_mut(if is_long {
            PoolKind::OpenInterestForLong
        } else {
            PoolKind::OpenInterestForShort
        })
    }

    fn open_interest_in_tokens_pool_mut(
        &mut self,
        is_long: bool,
    ) -> gmsol_model::Result<&mut Self::Pool> {
        self.make_market_mut().try_pool_mut(if is_long {
            PoolKind::OpenInterestInTokensForLong
        } else {
            PoolKind::OpenInterestInTokensForShort
        })
    }

    fn funding_amount_per_size_pool_mut(
        &mut self,
        is_long: bool,
    ) -> gmsol_model::Result<&mut Self::Pool> {
        self.make_market_mut().try_pool_mut(if is_long {
            PoolKind::FundingAmountPerSizeForLong
        } else {
            PoolKind::FundingAmountPerSizeForShort
        })
    }

    fn claimable_funding_amount_per_size_pool_mut(
        &mut self,
        is_long: bool,
    ) -> gmsol_model::Result<&mut Self::Pool> {
        self.make_market_mut().try_pool_mut(if is_long {
            PoolKind::ClaimableFundingAmountPerSizeForLong
        } else {
            PoolKind::ClaimableFundingAmountPerSizeForShort
        })
    }

    fn collateral_sum_pool_mut(&mut self, is_long: bool) -> gmsol_model::Result<&mut Self::Pool> {
        self.make_market_mut().try_pool_mut(if is_long {
            PoolKind::CollateralSumForLong
        } else {
            PoolKind::CollateralSumForShort
        })
    }

    fn total_borrowing_pool_mut(&mut self) -> gmsol_model::Result<&mut Self::Pool> {
        self.make_market_mut()
            .try_pool_mut(PoolKind::TotalBorrowing)
    }

    fn virtual_inventory_for_positions_pool_mut(
        &mut self,
    ) -> gmsol_model::Result<Option<impl DerefMut<Target = Self::Pool>>> {
        if self.disable_vis {
            return Ok(None);
        }
        self.validate_vi_for_positions()?;
        Ok(self.vi_for_positions.as_mut().map(|vi| vi.pool_mut()))
    }
}

impl gmsol_model::LiquidityMarketMut<{ constants::MARKET_DECIMALS }> for MarketModel {
    fn mint(&mut self, amount: &Self::Num) -> gmsol_model::Result<()> {
        let new_mint: u64 = (*amount)
            .try_into()
            .map_err(|_| gmsol_model::Error::Overflow)?;
        let new_supply = self
            .supply
            .checked_add(new_mint)
            .ok_or(gmsol_model::Error::Overflow)?;
        self.supply = new_supply;
        Ok(())
    }

    fn burn(&mut self, amount: &Self::Num) -> gmsol_model::Result<()> {
        let new_burn: u64 = (*amount)
            .try_into()
            .map_err(|_| gmsol_model::Error::Overflow)?;
        let new_supply = self
            .supply
            .checked_sub(new_burn)
            .ok_or(gmsol_model::Error::Overflow)?;
        self.supply = new_supply;
        Ok(())
    }
}