perpl-sdk 0.2.2

Rust SDK for the Perpl decentralized perpetuals exchange
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
use alloy::primitives::{B256, I256, U256};
use fastnum::{D64, D256, UD64, UD128};

use super::*;
use crate::{abi::dex::Exchange::PerpetualInfoV2, types};

const FUNDING_RATE_SCALE: u8 = 5;
const LEVERAGE_SCALE: u8 = 2;

/// The block of the first funding event strictly after `block`.
///
/// Funding events fall on one exchange-wide grid of multiples of
/// `funding_interval`, shared by every contract. A contract activated
/// part-way through an interval therefore anchors to the *next* grid block,
/// not to the block on which it was activated.
///
/// The boundary case is deliberate: a `block` already on the grid advances a
/// full interval, because the event at that block belongs to the schedule
/// that was already running when the contract was activated.
///
/// A zero `funding_interval` has no grid to round onto; the block is returned
/// unchanged rather than dividing by zero, so that a malformed exchange
/// configuration degrades instead of panicking inside an event reducer.
fn next_funding_event_block(block: u64, funding_interval: u64) -> u64 {
    if funding_interval == 0 {
        return block;
    }
    block - (block % funding_interval) + funding_interval
}

/// Perpetual contract tradeable at the exchange.
///
/// Provides the current state of contract parameters, market data and
/// order book.
#[derive(Clone, derive_more::Debug)]
pub struct Perpetual {
    instant: types::StateInstant,
    state_instant: types::StateInstant,
    id: types::PerpetualId,
    name: String,
    symbol: String,
    is_paused: bool,

    price_converter: num::Converter,
    size_converter: num::Converter,
    leverage_converter: num::Converter,
    fee_converter: num::Converter,
    funding_rate_converter: num::Converter,
    funding_sum_converter: num::Converter,
    #[debug("{base_price}")]
    base_price: UD64, // SC allocates 32 bits

    fee_schedule: FeeSchedule,
    #[debug("{initial_margin}")]
    initial_margin: UD64, // SC allocates 16 bits
    #[debug("{maintenance_margin}")]
    maintenance_margin: UD64, // SC allocates 16 bits

    #[debug("{last_price}")]
    last_price: UD64, // SC allocates 32 bits
    last_price_block: Option<u64>,
    last_price_timestamp: u64,

    #[debug("{mark_price}")]
    mark_price: UD64, // SC allocates 32 bits
    mark_price_block: Option<u64>,
    mark_price_timestamp: u64,

    #[debug("{oracle_price}")]
    oracle_price: UD64, // SC allocates 32 bits
    oracle_price_block: Option<u64>,
    oracle_price_timestamp: u64,

    #[debug("{prev_funding_rate}")]
    prev_funding_rate: D64, // SC allocates 16 bits of precision
    #[debug("{:?}", next_funding_rate.map(|v| format!("{v}")))]
    next_funding_rate: Option<D64>, // SC allocates 16 bits of precision
    #[debug("{:?}", next_funding_payment.map(|v| format!("{v}")))]
    next_funding_payment: Option<D256>, // SC allocates 48 bits of precision
    next_funding_event_block: Option<u64>,
    funding_start_block: u64,

    oracle_feed_id: B256,
    is_oracle_used: bool,
    price_max_age_sec: u64,

    l3_book: OrderBook,

    #[debug("{open_interest}")]
    open_interest: UD128,
}

impl Perpetual {
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn new(
        instant: types::StateInstant,
        id: types::PerpetualId,
        info: &PerpetualInfoV2,
        fee_schedule: FeeSchedule,
        initial_margin: U256,
        maintenance_margin: U256,
    ) -> Self {
        let price_converter = num::Converter::new(info.priceDecimals.to());
        let size_converter = num::Converter::new(info.lotDecimals.to());
        let leverage_converter = num::Converter::new(LEVERAGE_SCALE);
        let fee_converter = num::fee_converter();
        let funding_rate_converter = num::Converter::new(FUNDING_RATE_SCALE);
        // Funding sum converter applies to PNS funding payments/sums, combines scaling
        // exponent and price decimals
        let funding_sum_converter = num::Converter::new(
            info.fundingSumScalingExp.to::<u8>() + info.priceDecimals.to::<u8>(),
        );
        Self {
            instant,
            state_instant: instant,
            id,
            name: info.name.clone(),
            symbol: info.symbol.clone(),
            is_paused: info.status == 0, // PerpetualStatus::Paused

            price_converter,
            size_converter,
            leverage_converter,
            fee_converter,
            funding_rate_converter,
            funding_sum_converter,
            base_price: price_converter.from_unsigned(info.basePricePNS),

            fee_schedule,
            // Margins are in hundredths
            initial_margin: leverage_converter.from_unsigned(initial_margin),
            // Margins are in hundredths
            maintenance_margin: leverage_converter.from_unsigned(maintenance_margin),

            last_price: price_converter.from_unsigned(info.lastPNS),
            last_price_block: None,
            last_price_timestamp: info.lastTimestamp.to(),

            mark_price: price_converter.from_unsigned(info.markPNS),
            mark_price_block: None,
            mark_price_timestamp: info.markTimestamp.to(),

            oracle_price: price_converter.from_unsigned(info.oraclePNS),
            oracle_price_block: None,
            oracle_price_timestamp: info.oracleTimestampSec.to(),

            prev_funding_rate: funding_rate_converter
                .from_signed(I256::try_from(info.fundingRatePct100k).unwrap()),
            next_funding_rate: None,
            next_funding_payment: None,
            next_funding_event_block: None,
            funding_start_block: info.fundingStartBlock.to(),

            oracle_feed_id: info.linkFeedId,
            is_oracle_used: !info.ignOracle,
            price_max_age_sec: info.refPriceMaxAgeSec.to(),

            l3_book: OrderBook::new(),

            open_interest: size_converter.from_unsigned(info.longOpenInterestLNS),
        }
    }

    #[allow(clippy::too_many_arguments)]
    pub(crate) fn added(
        instant: types::StateInstant,
        id: types::PerpetualId,
        name: String,
        symbol: String,
        is_paused: bool,
        price_decimals: u8,
        size_decimals: u8,
        base_price: U256,
        fee_schedule: FeeSchedule,
        initial_margin: U256,
        maintenance_margin: U256,
    ) -> Self {
        let price_converter = num::Converter::new(price_decimals);
        let size_converter = num::Converter::new(size_decimals);
        let leverage_converter = num::Converter::new(LEVERAGE_SCALE);
        let fee_converter = num::fee_converter();
        let funding_rate_converter = num::Converter::new(FUNDING_RATE_SCALE);
        // Funding sum scaling exp is configured separately via
        // `setFundingSumScalingExp` and starts at 0 until that event arrives
        let funding_sum_converter = num::Converter::new(price_decimals);
        Self {
            instant,
            state_instant: instant,
            id,
            name,
            symbol,
            is_paused,

            price_converter,
            size_converter,
            leverage_converter,
            fee_converter,
            funding_rate_converter,
            funding_sum_converter,
            base_price: price_converter.from_unsigned(base_price),

            fee_schedule,
            // Margins are in hundredths
            initial_margin: leverage_converter.from_unsigned(initial_margin),
            // Margins are in hundredths
            maintenance_margin: leverage_converter.from_unsigned(maintenance_margin),

            last_price: UD64::ZERO,
            last_price_block: None,
            last_price_timestamp: 0,

            mark_price: UD64::ZERO,
            mark_price_block: None,
            mark_price_timestamp: 0,

            oracle_price: UD64::ZERO,
            oracle_price_block: None,
            oracle_price_timestamp: 0,

            prev_funding_rate: D64::ZERO,
            next_funding_rate: None,
            next_funding_payment: None,
            next_funding_event_block: None,
            funding_start_block: 0,

            oracle_feed_id: B256::ZERO,
            is_oracle_used: true,
            price_max_age_sec: 60,

            l3_book: OrderBook::new(),

            open_interest: UD128::ZERO,
        }
    }

    /// Instant the perpetual contract state is consistent with or was last
    /// updated at.
    pub fn instant(&self) -> types::StateInstant { self.instant }

    /// ID of the perpetual contract.
    pub fn id(&self) -> types::PerpetualId { self.id }

    /// Name of the perpetual contract.
    pub fn name(&self) -> String { self.name.clone() }

    /// Symbol of the perpetual contract.
    pub fn symbol(&self) -> String { self.symbol.clone() }

    /// Indicates if the perpetual contract is paused.
    pub fn is_paused(&self) -> bool { self.is_paused }

    /// Converter of prices between internal fixed-point and decimal
    /// representations.
    pub fn price_converter(&self) -> num::Converter { self.price_converter }

    /// Converter of sizes between internal fixed-point and decimal
    /// representations.
    pub fn size_converter(&self) -> num::Converter { self.size_converter }

    /// Converter of leverage/margin between internal fixed-point and decimal
    /// representations.
    pub fn leverage_converter(&self) -> num::Converter { self.leverage_converter }

    /// Converter of fees between internal fixed-point and decimal
    /// representations.
    pub fn fee_converter(&self) -> num::Converter { self.fee_converter }

    /// Converter of funding rates between internal fixed-point and decimal
    /// representations.
    pub fn funding_rate_converter(&self) -> num::Converter { self.funding_rate_converter }

    /// Converter for funding sums / per-unit funding payments.
    /// Scales by `10^(fundingSumScalingExp + priceDecimals)` as funding
    /// sums/payments are originaly in price numeric system.
    pub fn funding_sum_converter(&self) -> num::Converter { self.funding_sum_converter }

    /// Fee schedule the contract resolves its fees from: a `(taker, maker)` fee
    /// pair per account fee tier, plus the key identifying whether the schedule
    /// is shared with other contracts.
    pub fn fee_schedule(&self) -> FeeSchedule { self.fee_schedule }

    /// Base (fee tier 0) maker fee, gets collected only on position
    /// opening/increasing.
    ///
    /// Use [`Self::maker_fee_for_tier`] with an account's
    /// [`Account::fee_tier`] for the rate that account is actually charged.
    pub fn maker_fee(&self) -> UD64 { self.fee_schedule.base_maker_fee() }

    /// Base (fee tier 0) taker fee, gets collected only on position
    /// opening/increasing.
    ///
    /// Use [`Self::taker_fee_for_tier`] with an account's
    /// [`Account::fee_tier`] for the rate that account is actually charged.
    pub fn taker_fee(&self) -> UD64 { self.fee_schedule.base_taker_fee() }

    /// Maker fee charged to an account of the given fee tier.
    pub fn maker_fee_for_tier(&self, tier: types::FeeTier) -> UD64 {
        self.fee_schedule.maker_fee(tier)
    }

    /// Taker fee charged to an account of the given fee tier.
    pub fn taker_fee_for_tier(&self, tier: types::FeeTier) -> UD64 {
        self.fee_schedule.taker_fee(tier)
    }

    /// Minimal initial margin fraction required to open a position.
    pub fn initial_margin(&self) -> UD64 { self.initial_margin }

    /// Minimal maintenance margin fraction required to keep a position.
    pub fn maintenance_margin(&self) -> UD64 { self.maintenance_margin }

    /// The price last trade was executed at.
    pub fn last_price(&self) -> UD64 { self.last_price }

    /// Instant the last trade was executed at.
    /// Block number available only from real-time events, not from the initial
    /// snapshot.
    pub fn last_price_instant(&self) -> types::StateInstant {
        types::StateInstant::new(
            self.last_price_block.unwrap_or_default(),
            self.last_price_timestamp,
        )
    }

    /// Unix timestamp (in seconds) of the last trade.
    pub fn last_price_timestamp(&self) -> u64 { self.last_price_timestamp }

    /// Mark price of the contract.
    pub fn mark_price(&self) -> UD64 { self.mark_price }

    /// Instant the mark price was updated at.
    /// Block number available only from real-time events, not from the initial
    /// snapshot.
    pub fn mark_price_instant(&self) -> types::StateInstant {
        types::StateInstant::new(
            self.mark_price_block.unwrap_or_default(),
            self.mark_price_timestamp,
        )
    }

    /// Unix timestamp (in seconds) of the most recent mark price update.
    pub fn mark_price_timestamp(&self) -> u64 { self.mark_price_timestamp }

    /// Indicates that the mark price is obsolete and will not be accepted
    /// during the order/position settlement
    pub fn is_mark_price_obsolete(&self) -> bool {
        self.mark_price_timestamp + self.price_max_age_sec <= self.instant.block_timestamp()
    }

    /// Oracle price of the contract.
    pub fn oracle_price(&self) -> UD64 { self.oracle_price }

    /// Instant the oracle price was updated at.
    /// Block number available only from real-time events, not from the initial
    /// snapshot.
    pub fn oracle_price_instant(&self) -> types::StateInstant {
        types::StateInstant::new(
            self.oracle_price_block.unwrap_or_default(),
            self.oracle_price_timestamp,
        )
    }

    /// Unix timestamp (in seconds) of the most recent oracle price update.
    pub fn oracle_price_timestamp(&self) -> u64 { self.oracle_price_timestamp }

    /// Indicates that the oracle price is obsolete and will not be accepted
    /// during the order/position settlement
    pub fn is_oracle_price_obsolete(&self) -> bool {
        self.oracle_price_timestamp + self.price_max_age_sec <= self.instant.block_timestamp()
    }

    /// The funding rate applied at the previous funding event.
    pub fn funding_rate(&self) -> D64 {
        if let Some((next, bl)) = self.next_funding_rate.zip(self.next_funding_event_block)
            && bl <= self.state_instant.block_number()
        {
            next
        } else {
            self.prev_funding_rate
        }
    }

    /// If the next funding rate has been set.
    pub fn has_next_funding_rate(&self) -> bool {
        self.next_funding_rate.is_some()
            && self
                .next_funding_event_block
                .is_some_and(|bl| bl > self.state_instant.block_number())
    }

    /// The next funding rate, if scheduled.
    pub fn next_funding_rate(&self) -> Option<D64> {
        if self.has_next_funding_rate() { self.next_funding_rate } else { None }
    }

    /// Starting block number of funding intervals.
    /// Use [`Exchange::funding_interval_blocks`] to get interval "duration" in
    /// blocks.
    pub fn funding_start_block(&self) -> u64 { self.funding_start_block }

    /// The block number of the next funding event, if scheduled.
    pub fn next_funding_event_block(&self) -> Option<u64> { self.next_funding_event_block }

    /// Feed ID of ChainLink DataStreams price oracle.
    pub fn oracle_feed_id(&self) -> B256 { self.oracle_feed_id }

    /// If perpetual contract relues on oracle prices.
    pub fn is_oracle_used(&self) -> bool { self.is_oracle_used }

    /// Max age in seconds for oracle/mark prices.
    pub fn price_max_age_sec(&self) -> u64 { self.price_max_age_sec }

    /// Get a specific order by ID.
    pub fn get_order(&self, order_id: types::OrderId) -> Option<&Order> {
        self.l3_book.get_order(order_id).map(|o| &*(*o))
    }

    /// Total number of orders in the book.
    pub fn total_orders(&self) -> usize { self.l3_book.total_orders() }

    /// Up to date L3 order book.
    pub fn l3_book(&self) -> &OrderBook { &self.l3_book }

    /// Open interest size.
    pub fn open_interest(&self) -> UD128 { self.open_interest }

    /// Open interest amount.
    pub fn open_interest_amount(&self) -> UD128 { self.open_interest * self.last_price.resize() }

    pub(crate) fn base_price(&self) -> UD64 { self.base_price }

    pub(crate) fn update_state_instant(&mut self, instant: types::StateInstant) {
        // Update state instant first
        self.state_instant = instant;

        // Check for expired orders
        self.l3_book.check_expired(instant);
    }

    /// If a scheduled funding payment takes effect at `instant` (i.e. this is
    /// the funding-event block), returns the now-effective rate together with
    /// the per-unit payment, and consumes the payment so it cannot fire again;
    /// otherwise returns `None`.
    ///
    /// Funding is effective-dated: the payment was scheduled by an earlier
    /// `FundingEventCompleted` for this later block. `Exchange::apply_events`
    /// applies it in Pass 1 — to every position on its **pre-event** size,
    /// before the block's size-changing events — matching the contract, which
    /// settles a funding-event block at the new funding sum regardless of
    /// same-block decreases.
    pub(crate) fn take_funding_payment(
        &mut self,
        instant: types::StateInstant,
    ) -> Option<(D64, D256)> {
        if self
            .next_funding_event_block
            .is_some_and(|fe| fe == instant.block_number())
        {
            let rate = self.next_funding_rate.unwrap_or(self.prev_funding_rate);
            self.next_funding_payment
                .take()
                .map(|payment| (rate, payment))
        } else {
            None
        }
    }

    pub(crate) fn add_order(&mut self, order: Order) -> Result<(), DexError> {
        self.l3_book
            .add_order(&order)
            .map_err(|err| DexError::OrderBook(self.id, err))?;
        Ok(())
    }

    /// Add orders from a snapshot, reconstructing FIFO order from linked list
    /// pointers.
    ///
    /// Uses the `prev_order_id`/`next_order_id` fields from the snapshot to
    /// determine the correct queue position within each price level.
    pub(crate) fn add_orders_from_snapshot(&mut self, orders: Vec<Order>) -> Result<(), DexError> {
        self.l3_book
            .add_orders_from_snapshot(&orders)
            .map_err(|err| DexError::OrderBook(self.id, err))?;
        Ok(())
    }

    pub(crate) fn update_order(&mut self, order: Order) -> Result<(), DexError> {
        let prev = self
            .l3_book
            .get_order(order.order_id())
            .cloned()
            .ok_or(DexError::OrderNotFound(self.id, order.order_id()))?;

        if prev.price() != order.price() {
            // Price changed: remove from old level, add to new level (back of queue)
            self.l3_book
                .remove_order(&prev)
                .map_err(|err| DexError::OrderBook(self.id, err))?;
            self.l3_book
                .add_order(&order)
                .map_err(|err| DexError::OrderBook(self.id, err))?;
        } else if order.size() > prev.size() {
            // Size INCREASED at same price: move to back of queue (loses priority)
            self.l3_book
                .move_to_back(&order, &prev)
                .map_err(|err| DexError::OrderBook(self.id, err))?;
        } else if prev.expiry_block() > 0
            && prev.expiry_block() < order.instant().block_number()
            && prev.expiry_block() != order.expiry_block()
        {
            // Expired order got new expiry: move to back of queue (loses priority)
            self.l3_book
                .move_to_back(&order, &prev)
                .map_err(|err| DexError::OrderBook(self.id, err))?;
        } else {
            // Size decreased or unchanged: keep queue position
            self.l3_book
                .update_order(&order, &prev)
                .map_err(|err| DexError::OrderBook(self.id, err))?;
        }
        Ok(())
    }

    pub(crate) fn remove_order(&mut self, order_id: types::OrderId) -> Result<Order, DexError> {
        let order = self
            .l3_book
            .get_order(order_id)
            .cloned()
            .ok_or(DexError::OrderNotFound(self.id, order_id))?;
        self.l3_book
            .remove_order(&order)
            .map_err(|err| DexError::OrderBook(self.id, err))
    }

    pub(crate) fn update_paused(
        &mut self,
        instant: types::StateInstant,
        paused: bool,
        funding_interval: u64,
    ) {
        self.is_paused = paused;
        self.instant = instant;
        // Funding start block is set on first unpausing. The anchor is the
        // first funding-grid block after the unpause, not the unpause block
        // itself - see `next_funding_event_block`.
        if !paused && self.funding_start_block == 0 {
            self.funding_start_block =
                next_funding_event_block(instant.block_number(), funding_interval)
        }
    }

    pub(crate) fn update_fee_schedule(
        &mut self,
        instant: types::StateInstant,
        fee_schedule: FeeSchedule,
    ) {
        self.fee_schedule = fee_schedule;
        self.instant = instant;
    }

    /// Repoints the contract at another schedule, keeping the rates when the
    /// new key is the contract's own custom schedule - the `FeeScheduleSet`
    /// under that id carries the values in that case.
    pub(crate) fn update_fee_schedule_key(
        &mut self,
        instant: types::StateInstant,
        key: FeeScheduleKey,
    ) {
        self.fee_schedule = self.fee_schedule.with_key(key);
        self.instant = instant;
    }

    pub(crate) fn update_base_maker_fee(&mut self, instant: types::StateInstant, maker_fee: UD64) {
        self.fee_schedule = self.fee_schedule.with_base_maker_fee(maker_fee);
        self.instant = instant;
    }

    pub(crate) fn update_base_taker_fee(&mut self, instant: types::StateInstant, taker_fee: UD64) {
        self.fee_schedule = self.fee_schedule.with_base_taker_fee(taker_fee);
        self.instant = instant;
    }

    pub(crate) fn update_initial_margin(
        &mut self,
        instant: types::StateInstant,
        initial_margin: UD64,
    ) {
        self.initial_margin = initial_margin;
        self.instant = instant;
    }

    pub(crate) fn update_maintenance_margin(
        &mut self,
        instant: types::StateInstant,
        maintenance_margin: UD64,
    ) {
        self.maintenance_margin = maintenance_margin;
        self.instant = instant;
    }

    pub(crate) fn update_last_price(&mut self, instant: types::StateInstant, last_price: UD64) {
        self.last_price = last_price;
        self.last_price_block = Some(instant.block_number());
        self.last_price_timestamp = instant.block_timestamp();
        self.instant = instant;
    }

    pub(crate) fn update_mark_price(&mut self, instant: types::StateInstant, mark_price: UD64) {
        self.mark_price = mark_price;
        self.mark_price_block = Some(instant.block_number());
        self.mark_price_timestamp = instant.block_timestamp();
        self.instant = instant;
    }

    pub(crate) fn update_oracle_price(&mut self, instant: types::StateInstant, oracle_price: UD64) {
        self.oracle_price = oracle_price;
        self.oracle_price_block = Some(instant.block_number());
        self.oracle_price_timestamp = instant.block_timestamp();
        self.instant = instant;
    }

    pub(crate) fn update_funding(
        &mut self,
        instant: types::StateInstant,
        funding_rate: D64,
        funding_payment: D256,
        block_num: u64,
    ) {
        if let Some(next) = self.next_funding_rate
            && self
                .next_funding_event_block
                .expect("next_funding_event_block set")
                < block_num
        {
            self.prev_funding_rate = next;
        }
        self.next_funding_rate = Some(funding_rate);
        self.next_funding_payment = Some(funding_payment);
        self.next_funding_event_block = Some(block_num);
        self.instant = instant;
    }

    pub(crate) fn update_funding_sum_scaling_exp(&mut self, instant: types::StateInstant, exp: u8) {
        // Funding sum converter applies to PNS funding payments/sums,
        // so combines specified scaling exponent and price decimals
        self.funding_sum_converter = num::Converter::new(exp + self.price_converter.decimals());
        self.instant = instant;
    }

    pub(crate) fn update_oracle_feed_id(
        &mut self,
        instant: types::StateInstant,
        oracle_feed_id: B256,
    ) {
        self.oracle_feed_id = oracle_feed_id;
        self.instant = instant;
    }

    pub(crate) fn update_is_oracle_used(
        &mut self,
        instant: types::StateInstant,
        is_oracle_used: bool,
    ) {
        self.is_oracle_used = is_oracle_used;
        self.instant = instant;
    }

    pub(crate) fn update_price_max_age_sec(
        &mut self,
        instant: types::StateInstant,
        price_max_age_sec: u64,
    ) {
        self.price_max_age_sec = price_max_age_sec;
        self.instant = instant;
    }

    pub(crate) fn update_open_interest(
        &mut self,
        instant: types::StateInstant,
        prev_size: UD64,
        new_size: UD64,
    ) {
        self.open_interest -= prev_size.resize();
        self.open_interest += new_size.resize();
        self.instant = instant;
    }

    /// Create a minimal Perpetual for testing purposes.
    #[cfg(test)]
    pub(crate) fn for_testing(id: types::PerpetualId) -> Self { Self::testing(id) }

    // Only reachable from `for_testing` (#[cfg(test)]) and `for_test`
    // (#[cfg(any(test, feature = "test-utils"))]), so unused in normal builds.
    #[cfg(any(test, feature = "test-utils"))]
    fn testing(id: types::PerpetualId) -> Self {
        Self {
            instant: types::StateInstant::new(0, 0),
            state_instant: types::StateInstant::new(0, 0),
            id,
            name: "TEST".to_string(),
            symbol: "TEST".to_string(),
            is_paused: false,
            price_converter: num::Converter::new(0),
            size_converter: num::Converter::new(0),
            leverage_converter: num::Converter::new(2),
            fee_converter: num::fee_converter(),
            funding_rate_converter: num::Converter::new(5),
            funding_sum_converter: num::Converter::new(0),
            base_price: UD64::ZERO,
            fee_schedule: FeeSchedule::flat(FeeScheduleKey::Default, UD64::ZERO, UD64::ZERO),
            initial_margin: UD64::ZERO,
            maintenance_margin: UD64::ZERO,
            last_price: UD64::ZERO,
            last_price_block: None,
            last_price_timestamp: 0,
            mark_price: UD64::ZERO,
            mark_price_block: None,
            mark_price_timestamp: 0,
            oracle_price: UD64::ZERO,
            oracle_price_block: None,
            oracle_price_timestamp: 0,
            prev_funding_rate: D64::ZERO,
            next_funding_rate: None,
            next_funding_payment: None,
            next_funding_event_block: None,
            funding_start_block: 0,
            oracle_feed_id: B256::ZERO,
            is_oracle_used: false,
            price_max_age_sec: 0,
            l3_book: OrderBook::new(),
            open_interest: UD128::ZERO,
        }
    }
}

/// Test utility builders for `Perpetual`.
///
/// Gated behind the `test-utils` feature to keep internal mutation methods
/// (`add_order`, `update_last_price`, etc.) at their current `pub(crate)`
/// visibility. Downstream crates opt in via `features = ["test-utils"]` in
/// their `[dev-dependencies]` so these helpers are never available in
/// production builds.
#[cfg(any(test, feature = "test-utils"))]
impl Perpetual {
    pub fn for_test(id: types::PerpetualId) -> Self { Self::testing(id) }

    pub fn with_last_price(mut self, price: UD64) -> Self {
        self.last_price = price;
        self
    }

    pub fn with_last_price_timestamp(mut self, timestamp: u64) -> Self {
        self.last_price_timestamp = timestamp;
        self
    }

    pub fn with_bid(mut self, price: UD64, size: UD64) -> Self {
        use std::num::NonZeroU16;
        let order_id =
            NonZeroU16::new((self.l3_book.total_orders() + 1) as u16).expect("order id overflow");
        let order = Order::for_l3_testing(types::OrderType::OpenLong, price, size, 0, order_id, 0);
        self.l3_book
            .add_order(&order)
            .expect("failed to add bid order");
        self
    }

    pub fn with_ask(mut self, price: UD64, size: UD64) -> Self {
        use std::num::NonZeroU16;
        let order_id =
            NonZeroU16::new((self.l3_book.total_orders() + 1) as u16).expect("order id overflow");
        let order = Order::for_l3_testing(types::OrderType::OpenShort, price, size, 0, order_id, 0);
        self.l3_book
            .add_order(&order)
            .expect("failed to add ask order");
        self
    }
}

#[cfg(feature = "display")]
impl std::fmt::Display for Perpetual {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        use colored::Colorize;
        use tabled::{
            Table,
            settings::{Alignment, Style, object::Cell},
        };

        let mut table = Table::from_iter(vec![
            vec![
                format!(
                    "Last: {}\n{}",
                    self.last_price.to_string().green(),
                    self.last_price_instant()
                ),
                format!(
                    "Mark: {}\n{}",
                    if self.is_mark_price_obsolete() {
                        self.mark_price.to_string().red()
                    } else {
                        self.mark_price.to_string().green()
                    },
                    self.mark_price_instant(),
                ),
                format!(
                    "Oracle: {}\n{}",
                    if self.is_oracle_used {
                        if self.is_oracle_price_obsolete() {
                            self.oracle_price.to_string().red()
                        } else {
                            self.oracle_price.to_string().green()
                        }
                    } else {
                        "N/A".red()
                    },
                    if self.is_oracle_used {
                        self.oracle_price_instant().to_string()
                    } else {
                        "".to_string()
                    },
                ),
                format!(
                    "Funding Rate: {}\nnext: {}",
                    if self.funding_rate().is_negative() {
                        self.funding_rate().to_string().red()
                    } else {
                        self.funding_rate().to_string().green()
                    },
                    if let Some((nfr, nfb)) = self
                        .next_funding_rate()
                        .zip(self.next_funding_event_block())
                    {
                        if nfr.is_negative() {
                            format!("{} @ #{}", nfr, nfb).red()
                        } else {
                            format!("{} @ #{}", nfr, nfb).green()
                        }
                    } else {
                        "TBA".to_string().dimmed()
                    },
                ),
                format!(
                    "Open Interest: {}\namount: ${}",
                    self.open_interest.to_string().cyan(),
                    self.open_interest_amount()
                        .trunc_with_scale(2)
                        .to_string()
                        .cyan(),
                ),
            ],
            vec![
                // Base rates only, plus the schedule they resolve from - the
                // discounted tiers are rendered once per schedule with the
                // exchange rather than repeated per contract
                format!(
                    "Fees: {} / {} (tkr/mkr, {})",
                    self.fee_schedule.base_taker_fee(),
                    self.fee_schedule.base_maker_fee(),
                    self.fee_schedule.key(),
                ),
                format!("Margin: {} / {} (ini/mnt)", self.initial_margin, self.maintenance_margin),
                format!("Price Max Age: {}", self.price_max_age_sec),
                format!("Funding Start: {}", self.funding_start_block),
            ],
        ]);
        table.with(Style::modern());
        table.modify(Cell::new(0, 4), Alignment::right());

        writeln!(
            f,
            "{}\n{}",
            format_args!(
                "{} {}",
                format!("* Perp #{} {}", self.id, self.symbol).bold().cyan(),
                if self.is_paused { "PAUSED ".bright_red() } else { Default::default() },
            ),
            table,
        )?;

        // Render the order book in alternate mode
        if f.alternate() && self.l3_book().total_orders() > 0 {
            writeln!(f, "{:}", self.l3_book)?;
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use std::num::NonZeroU16;

    use fastnum::{dec64, dec256, udec64};

    use super::*;

    fn oid(n: u16) -> types::OrderId { NonZeroU16::new(n).expect("test order id must be non-zero") }

    /// One hour of blocks, the funding interval the exchange reports on
    /// mainnet. Any non-trivial value exercises the same arithmetic.
    const INTERVAL: u64 = 8571;

    fn at(block: u64) -> types::StateInstant { types::StateInstant::new(block, 1_700_000_000) }

    #[test]
    fn next_funding_event_block_rounds_up_to_the_grid() {
        assert_eq!(next_funding_event_block(1, INTERVAL), INTERVAL);
        assert_eq!(next_funding_event_block(INTERVAL - 1, INTERVAL), INTERVAL);
        // A block already on the grid advances a whole interval - the event at
        // that block belongs to the schedule already running.
        assert_eq!(next_funding_event_block(INTERVAL, INTERVAL), 2 * INTERVAL);
        assert_eq!(next_funding_event_block(0, INTERVAL), INTERVAL);
        // Every result is on the grid and strictly ahead of the input.
        for block in [1u64, 5_000, 8_570, 8_571, 97_627_404, 99_360_126] {
            let next = next_funding_event_block(block, INTERVAL);
            assert_eq!(next % INTERVAL, 0, "block {block} produced off-grid {next}");
            assert!(next > block, "block {block} produced non-advancing {next}");
        }
    }

    #[test]
    fn next_funding_event_block_tolerates_a_zero_interval() {
        assert_eq!(next_funding_event_block(1_234, 0), 1_234);
    }

    #[test]
    fn first_unpause_anchors_funding_to_the_grid_not_the_observed_block() {
        let mut perp = Perpetual::for_testing(1);
        assert_eq!(perp.funding_start_block(), 0);

        // Activation part-way through an interval: the observed block is NOT
        // the anchor. Mirrors the mainnet listing at block 97,627,404, which
        // the contract anchored to 97,632,261.
        perp.update_paused(at(97_627_404), false, INTERVAL);

        assert_eq!(perp.funding_start_block(), 97_632_261);
        assert_eq!(perp.funding_start_block() % INTERVAL, 0);
        assert!(!perp.is_paused());
    }

    #[test]
    fn unpause_on_a_grid_block_anchors_to_the_following_interval() {
        let mut perp = Perpetual::for_testing(1);
        perp.update_paused(at(INTERVAL), false, INTERVAL);
        assert_eq!(perp.funding_start_block(), 2 * INTERVAL);
    }

    #[test]
    fn funding_anchor_is_written_once_and_survives_a_repause() {
        let mut perp = Perpetual::for_testing(1);

        // The listing batch unpauses and re-pauses in one transaction: the
        // contract is activated but not tradeable. The anchor is taken on the
        // unpause and must not move afterwards.
        perp.update_paused(at(97_627_404), false, INTERVAL);
        let anchor = perp.funding_start_block();
        assert_eq!(anchor % INTERVAL, 0, "the preserved anchor must be a grid block");
        perp.update_paused(at(97_627_404), true, INTERVAL);

        assert_eq!(perp.funding_start_block(), anchor);
        assert!(perp.is_paused());

        // A later unpause must not re-anchor either.
        perp.update_paused(at(98_000_000), false, INTERVAL);
        assert_eq!(perp.funding_start_block(), anchor);
    }

    #[test]
    fn pause_never_sets_the_funding_anchor() {
        let mut perp = Perpetual::for_testing(1);
        perp.update_paused(at(97_627_404), true, INTERVAL);
        assert_eq!(perp.funding_start_block(), 0);
    }

    #[test]
    fn update_order_expired_order_renewal_moves_to_back() {
        let mut perp = Perpetual::for_testing(1);

        // Create two orders at the same price
        // Order 1: expires at block 100
        // Order 2: no expiry
        let order1 = Order::for_l3_testing(
            types::OrderType::OpenShort, // Ask
            udec64!(100),                // price
            udec64!(1.0),                // size
            50,                          // block_number
            oid(1),                      // order_id
            101,                         // account_id
        )
        .with_expiry_block(100);

        let order2 = Order::for_l3_testing(
            types::OrderType::OpenShort,
            udec64!(100),
            udec64!(2.0),
            50,
            oid(2),
            102,
        );

        // Add orders: FIFO is [1, 2]
        perp.add_order(order1).unwrap();
        perp.add_order(order2).unwrap();

        // Verify initial FIFO order
        let orders: Vec<_> = perp.l3_book.ask_orders().map(|o| o.order_id()).collect();
        assert_eq!(orders, vec![oid(1), oid(2)], "Initial FIFO should be [1, 2]");

        // Now simulate time passing: we're at block 150 (order 1 is expired at block
        // 100) Update order 1 with a new expiry (block 200)
        let order1_renewed = Order::for_l3_testing(
            types::OrderType::OpenShort,
            udec64!(100),
            udec64!(1.0),
            150, // current block
            oid(1),
            101,
        )
        .with_expiry_block(200); // new expiry

        perp.update_order(order1_renewed).unwrap();

        // Order 1 should have moved to back: FIFO is [2, 1]
        let orders: Vec<_> = perp.l3_book.ask_orders().map(|o| o.order_id()).collect();
        assert_eq!(orders, vec![oid(2), oid(1)], "After expiry renewal, FIFO should be [2, 1]");
    }

    #[test]
    fn update_order_non_expired_order_keeps_position() {
        let mut perp = Perpetual::for_testing(1);

        // Create two orders at the same price
        // Order 1: expires at block 100
        let order1 = Order::for_l3_testing(
            types::OrderType::OpenShort,
            udec64!(100),
            udec64!(1.0),
            50,
            oid(1),
            101,
        )
        .with_expiry_block(100);

        let order2 = Order::for_l3_testing(
            types::OrderType::OpenShort,
            udec64!(100),
            udec64!(2.0),
            50,
            oid(2),
            102,
        );

        perp.add_order(order1).unwrap();
        perp.add_order(order2).unwrap();

        // Update order 1 at block 80 (NOT expired yet) with new expiry
        let order1_updated = Order::for_l3_testing(
            types::OrderType::OpenShort,
            udec64!(100),
            udec64!(1.0),
            80, // current block < expiry_block(100)
            oid(1),
            101,
        )
        .with_expiry_block(200);

        perp.update_order(order1_updated).unwrap();

        // Order 1 should keep its position: FIFO is [1, 2]
        let orders: Vec<_> = perp.l3_book.ask_orders().map(|o| o.order_id()).collect();
        assert_eq!(orders, vec![oid(1), oid(2)], "Non-expired order should keep position");
    }

    // ── Funding schedule: effective-dating, single-consumption, prev/next rate
    // boundary ── These pin `take_funding_payment` / `update_funding` /
    // `funding_rate`, which the fix's Pass-1 funding relies on. `for_testing`
    // applies no converter, so scheduled values pass through unchanged.

    #[test]
    fn perpetual_funding_effective_dated_consumed_once() {
        // take_funding_payment yields the scheduled (rate, payment) ONLY at the exact
        // funding-event block, consumes it (cannot fire twice), and never auto-applies
        // a block that was skipped.
        let mut perp = Perpetual::for_testing(1);
        perp.update_funding(types::StateInstant::new(1, 1), dec64!(0.02), dec256!(1.25), 3);

        // Before the event block: not due.
        assert_eq!(perp.take_funding_payment(types::StateInstant::new(2, 2)), None);
        // At the event block: due, exactly once.
        assert_eq!(
            perp.take_funding_payment(types::StateInstant::new(3, 3)),
            Some((dec64!(0.02), dec256!(1.25))),
        );
        // Consumed: a second read at the same block yields nothing.
        assert_eq!(perp.take_funding_payment(types::StateInstant::new(3, 3)), None);
        // A later block never picks up the (already-passed) schedule.
        assert_eq!(perp.take_funding_payment(types::StateInstant::new(4, 4)), None);
    }

    #[test]
    fn perpetual_funding_rate_prev_next_boundary() {
        // funding_rate() reads state_instant: prev while state_instant.block < the
        // event block, next at/after it. state_instant advances only via
        // update_state_instant (NOT update_funding / take_funding_payment).
        let mut perp = Perpetual::for_testing(2);
        perp.update_funding(types::StateInstant::new(1, 1), dec64!(0.02), dec256!(1.25), 3);

        assert_eq!(perp.funding_rate(), D64::ZERO); // state (0,0): 3 <= 0? no -> prev
        assert!(perp.has_next_funding_rate()); // 3 > 0
        perp.update_state_instant(types::StateInstant::new(2, 2));
        assert_eq!(perp.funding_rate(), D64::ZERO); // 3 <= 2? no -> prev
        perp.update_state_instant(types::StateInstant::new(3, 3));
        assert_eq!(perp.funding_rate(), dec64!(0.02)); // 3 <= 3? yes -> next (at boundary)
        assert!(!perp.has_next_funding_rate()); // 3 > 3? no
        perp.update_state_instant(types::StateInstant::new(4, 4));
        assert_eq!(perp.funding_rate(), dec64!(0.02)); // 3 <= 4? yes -> next
    }

    #[test]
    fn perpetual_update_funding_prev_rollover() {
        // A second update_funding that supersedes an unconsumed schedule (older event
        // block < new block) rolls the old next rate into prev — the only
        // post-construction writer of prev_funding_rate.
        let mut perp = Perpetual::for_testing(3);
        perp.update_funding(types::StateInstant::new(1, 1), dec64!(0.02), dec256!(1.0), 3);
        perp.update_funding(types::StateInstant::new(2, 2), dec64!(0.03), dec256!(2.0), 5);
        // prev is now the superseded 0.02; next is 0.03 @ block 5.
        perp.update_state_instant(types::StateInstant::new(4, 4));
        assert_eq!(perp.funding_rate(), dec64!(0.02)); // 5 <= 4? no -> prev (rolled 0.02)
        perp.update_state_instant(types::StateInstant::new(5, 5));
        assert_eq!(perp.funding_rate(), dec64!(0.03)); // 5 <= 5? yes -> next
    }
}