perpl-sdk 0.2.3

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
use alloy::primitives::U256;
use fastnum::{D64, D256, UD64, UD128, udec64};

use super::num;
use crate::{abi::dex::Exchange::PositionInfoV2, types};

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PositionType {
    Long = 0,
    Short = 1,
}

/// Open perpetual contract position.
#[derive(Clone, derive_more::Debug)]
pub struct Position {
    instant: types::StateInstant,
    funding_instant: types::StateInstant,
    perpetual_id: types::PerpetualId,
    account_id: types::AccountId,
    r#type: PositionType,
    #[debug("{entry_price}")]
    entry_price: UD64, // SC allocates 32 bits + 16 bits residue
    #[debug("{size}")]
    size: UD64, // SC allocates 40 bits
    #[debug("{deposit}")]
    deposit: UD128, // SC allocates 80 bits
    #[debug("{delta_pnl}")]
    delta_pnl: D256, // SC calculations and ABI use 256 bits
    #[debug("{premium_pnl}")]
    premium_pnl: D256, // SC calculations and ABI use 256 bits
    #[debug("{maintenance_margin_requirement}")]
    maintenance_margin_requirement: UD128,
}

impl Position {
    pub(crate) fn new(
        instant: types::StateInstant,
        perpetual_id: types::PerpetualId,
        info: &PositionInfoV2,
        collateral_converter: num::Converter,
        price_converter: num::Converter,
        size_converter: num::Converter,
        maintenance_margin: UD64,
    ) -> Self {
        let r#type = info.positionType.into();
        let entry_price = Self::effective_entry_price(
            r#type,
            info.pricePNS,
            info.priceResiduePNSQ16.to(),
            price_converter,
        );
        let size = size_converter.from_unsigned(info.lotLNS);
        Self {
            instant,
            funding_instant: instant,
            perpetual_id,
            account_id: info.accountId.to(),
            r#type,
            entry_price,
            size,
            deposit: collateral_converter.from_unsigned(info.depositCNS),
            delta_pnl: collateral_converter.from_signed(info.deltaPnlCNS),
            premium_pnl: collateral_converter.from_signed(info.premiumPnlCNS),
            maintenance_margin_requirement: entry_price.resize() * size.resize()
                / maintenance_margin.resize(),
        }
    }

    #[allow(clippy::too_many_arguments)]
    pub(crate) fn opened(
        instant: types::StateInstant,
        perpetual_id: types::PerpetualId,
        account_id: types::AccountId,
        r#type: PositionType,
        price_pns: U256,
        price_residue_pnsq16: u32,
        price_converter: num::Converter,
        size: UD64,
        deposit: UD128,
        maintenance_margin: UD64,
    ) -> Self {
        let entry_price =
            Self::effective_entry_price(r#type, price_pns, price_residue_pnsq16, price_converter);
        Self {
            instant,
            funding_instant: instant,
            perpetual_id,
            account_id,
            r#type,
            entry_price,
            size,
            deposit,
            delta_pnl: D256::ZERO,
            premium_pnl: D256::ZERO,
            maintenance_margin_requirement: entry_price.resize() * size.resize()
                / maintenance_margin.resize(),
        }
    }

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

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

    /// ID of the account holding the position.
    pub fn account_id(&self) -> types::AccountId { self.account_id }

    /// Type of the position.
    pub fn r#type(&self) -> PositionType { self.r#type }

    /// Position entry price, full precision - including 16 bit rounding residue
    pub fn entry_price(&self) -> UD64 { self.entry_price }

    /// Size of the position.
    pub fn size(&self) -> UD64 { self.size }

    /// Collateral deposit / margin locked in the position.
    pub fn deposit(&self) -> UD128 { self.deposit }

    /// Unrealized Delta PnL of the position.
    pub fn delta_pnl(&self) -> D256 { self.delta_pnl }

    /// Unrealized Premium PnL of the position.
    pub fn premium_pnl(&self) -> D256 { self.premium_pnl }

    /// Unrealized PnL of the position.
    pub fn pnl(&self) -> D256 { self.delta_pnl + self.premium_pnl }

    /// Maintenance margin requirement of the position.
    pub fn maintenance_margin_requirement(&self) -> UD128 { self.maintenance_margin_requirement }

    /// Liquidation price of the position.
    pub fn liquidation_price(&self) -> UD64 {
        let side = if self.r#type.is_long() { D256::ONE } else { D256::ONE.neg() };
        let liquidation_price = self.entry_price.to_signed()
            + (side
                * (self.maintenance_margin_requirement.to_signed().resize()
                    - self.deposit.to_signed().resize()
                    - self.premium_pnl)
                / self.size.to_signed().resize())
            .resize();
        liquidation_price.max(D64::ZERO).unsigned_abs()
    }

    /// Bankruptcy price of the position.
    pub fn bankruptcy_price(&self) -> UD64 {
        let side = if self.r#type.is_long() { D256::ONE } else { D256::ONE.neg() };
        let bankruptcy_price = self.entry_price.to_signed()
            - (side * (self.deposit.to_signed().resize() + self.premium_pnl)
                / self.size.to_signed().resize())
            .resize();
        bankruptcy_price.max(D64::ZERO).unsigned_abs()
    }

    pub(crate) fn update_type(&mut self, instant: types::StateInstant, r#type: PositionType) {
        self.r#type = r#type;
        self.instant = instant;
    }

    pub(crate) fn update_entry_price(
        &mut self,
        instant: types::StateInstant,
        price_pns: U256,
        price_residue_pnsq16: u32,
        price_converter: num::Converter,
    ) {
        self.entry_price = Self::effective_entry_price(
            self.r#type,
            price_pns,
            price_residue_pnsq16,
            price_converter,
        );
        self.instant = instant;
    }

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

    pub(crate) fn update_deposit(&mut self, instant: types::StateInstant, deposit: UD128) {
        self.deposit = deposit;
        self.instant = instant;
    }
    pub(crate) fn update_premium_pnl(&mut self, instant: types::StateInstant, premium_pnl: D256) {
        self.premium_pnl = premium_pnl;
        self.instant = instant;
        self.funding_instant = instant;
    }

    pub(crate) fn apply_mark_price(&mut self, instant: types::StateInstant, mark_price: UD64) {
        let sign = if self.r#type.is_long() { D256::ONE } else { D256::ONE.neg() };
        self.delta_pnl = sign
            * (mark_price.resize().to_signed() - self.entry_price.resize().to_signed())
            * self.size.resize().to_signed();
        self.instant = instant;
    }

    pub(crate) fn apply_funding_payment(
        &mut self,
        instant: types::StateInstant,
        payment_per_unit: D256,
    ) -> bool {
        // Updating premium PnL only if it wasn't updated at the same instant
        if self.funding_instant >= instant {
            return false;
        }

        // Positive funding payment means longs pay shorts
        let sign = if self.r#type.is_long() { D256::ONE.neg() } else { D256::ONE };
        self.premium_pnl += sign * payment_per_unit * self.size.resize().to_signed();
        self.instant = instant;
        self.funding_instant = instant;
        true
    }

    pub(crate) fn apply_maintenance_margin(
        &mut self,
        instant: types::StateInstant,
        maintenance_margin: UD64,
    ) {
        self.maintenance_margin_requirement =
            self.entry_price.resize() * self.size.resize() / maintenance_margin.resize();
        self.instant = instant;
    }

    /// Calculates effective entry price considering:
    /// - CEIL rounding for LONG positions
    /// - FLOOR rounding for SHORT positions
    /// - 16 bit rounding residue preserved by the smart contract separately
    ///   from PNS rounded price
    ///
    ///   LONG  (stored entry_price = ceil):  
    ///   = (entry_price - 1) + residue / Q    if residue > 0
    ///   = entry_price                        if residue == 0
    ///
    ///   SHORT (stored entry_price = floor):
    ///   = entry_price  + residue / Q
    ///
    ///   where Q = 2^16 = 65536
    pub(crate) fn effective_entry_price(
        position_type: PositionType,
        price_pns: U256,
        price_residue_pnsq16: u32,
        price_converter: num::Converter,
    ) -> UD64 {
        const Q: UD64 = udec64!(65536).with_rounding_mode(fastnum::decimal::RoundingMode::Floor);
        if price_residue_pnsq16 == 0 {
            price_converter.from_unsigned(price_pns)
        } else {
            let mut entry_price = UD64::from_u64(price_pns.to())
                .with_rounding_mode(fastnum::decimal::RoundingMode::Floor); // SC allocates 32 bits
            if position_type.is_long() && entry_price >= UD64::ONE {
                entry_price -= UD64::ONE;
            }
            (entry_price
                + UD64::from_u32(price_residue_pnsq16)
                    .with_rounding_mode(fastnum::decimal::RoundingMode::Floor)
                    / Q)
                / price_converter.scale()
        }
    }
}

impl PositionType {
    pub fn is_long(&self) -> bool { matches!(self, PositionType::Long) }

    pub fn is_short(&self) -> bool { matches!(self, PositionType::Short) }
}

impl From<u8> for PositionType {
    fn from(value: u8) -> Self {
        match value {
            0 => PositionType::Long,
            1 => PositionType::Short,
            _ => unreachable!(),
        }
    }
}

impl std::fmt::Display for PositionType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            PositionType::Long => write!(f, "Long"),
            PositionType::Short => write!(f, "Short"),
        }
    }
}

#[cfg(feature = "display")]
impl tabled::Tabled for Position {
    const LENGTH: usize = 9;

    fn fields(&self) -> Vec<std::borrow::Cow<'_, str>> {
        use colored::Colorize;
        vec![
            self.perpetual_id().to_string().into(),
            if self.r#type.is_long() {
                self.r#type().to_string().green().to_string().into()
            } else {
                self.r#type().to_string().red().to_string().into()
            },
            self.entry_price().to_string().into(),
            self.size().to_string().into(),
            self.deposit().to_string().into(),
            if self.delta_pnl.is_negative() {
                self.delta_pnl.to_string().red().to_string().into()
            } else {
                self.delta_pnl.to_string().green().to_string().into()
            },
            if self.premium_pnl.is_negative() {
                self.premium_pnl.to_string().red().to_string().into()
            } else {
                self.premium_pnl.to_string().green().to_string().into()
            },
            if self.pnl().is_negative() {
                self.pnl().to_string().red().to_string().into()
            } else {
                self.pnl().to_string().green().to_string().into()
            },
            format!("{:.6}", self.liquidation_price()).into(),
            format!("{:.6}", self.bankruptcy_price()).into(),
        ]
    }

    fn headers() -> Vec<std::borrow::Cow<'static, str>> {
        vec![
            "Perp ID".into(),
            "Type".into(),
            "Entry Price".into(),
            "Size".into(),
            "Deposit".into(),
            "Delta PnL".into(),
            "Premium PnL".into(),
            "Total PnL".into(),
            "Liq Price".into(),
            "Bnkrp Price".into(),
        ]
    }
}

#[cfg(test)]
mod tests {
    use fastnum::{dec256, udec64, udec128};

    use super::*;
    use crate::types::StateInstant;

    #[test]
    fn test_effective_entry_price() {
        let pc = num::Converter::new(4);
        assert_eq!(
            Position::effective_entry_price(PositionType::Long, U256::from(1), 0, pc),
            udec64!(0.0001)
        );
        assert_eq!(
            Position::effective_entry_price(PositionType::Long, U256::from(1), 1, pc),
            udec64!(0.00000000152587890625) // 1 / 65536 * 10 ^ -4
        );
        assert_eq!(
            Position::effective_entry_price(PositionType::Long, U256::from(10001), 8, pc),
            udec64!(1.00000001220703125) // 1 + (8 / 65536 * 10 ^ -4)
        );
        assert_eq!(
            Position::effective_entry_price(PositionType::Long, U256::from(10000), 65535, pc),
            udec64!(0.9999999984741210937) // 1 - (1 / 65536 * 10 ^ -4)
        );

        assert_eq!(
            Position::effective_entry_price(PositionType::Short, U256::from(1), 0, pc),
            udec64!(0.0001)
        );
        assert_eq!(
            Position::effective_entry_price(PositionType::Short, U256::from(0), 1, pc),
            udec64!(0.00000000152587890625) // 1 / 65536 * 10 ^ -4
        );
        assert_eq!(
            Position::effective_entry_price(PositionType::Short, U256::from(10000), 8, pc),
            udec64!(1.00000001220703125) // 1 + (8 / 65536 * 10 ^ -4)
        );
        assert_eq!(
            Position::effective_entry_price(PositionType::Short, U256::from(9999), 65535, pc),
            udec64!(0.9999999984741210937) // 1 - (1 / 65536 * 10 ^ -4)
        );
    }

    #[test]
    fn test_apply_mark_price() {
        let pc = num::Converter::new(4);
        let mut pos = Position::opened(
            StateInstant::default(),
            1,
            1,
            PositionType::Long,
            U256::from(100),
            0,
            pc,
            udec64!(10),
            UD128::ZERO,
            UD64::ONE,
        );

        pos.apply_mark_price(StateInstant::default(), udec64!(0.015));
        assert_eq!(pos.delta_pnl(), dec256!(0.05));

        pos.apply_mark_price(StateInstant::default(), udec64!(0.005));
        assert_eq!(pos.delta_pnl(), dec256!(-0.05));

        let mut pos = Position::opened(
            StateInstant::default(),
            1,
            1,
            PositionType::Short,
            U256::from(100),
            0,
            pc,
            udec64!(10),
            UD128::ZERO,
            UD64::ONE,
        );
        pos.apply_mark_price(StateInstant::default(), udec64!(0.015));
        assert_eq!(pos.delta_pnl(), dec256!(-0.05));

        pos.apply_mark_price(StateInstant::default(), udec64!(0.005));
        assert_eq!(pos.delta_pnl(), dec256!(0.05));
    }

    #[test]
    fn test_apply_funding_payment() {
        let pc = num::Converter::new(4);
        let (i0, i1, i2) =
            (StateInstant::default(), StateInstant::new(1, 1), StateInstant::new(2, 2));
        let mut pos = Position::opened(
            i0,
            1,
            1,
            PositionType::Long,
            U256::from(100),
            0,
            pc,
            udec64!(10),
            UD128::ZERO,
            UD64::ONE,
        );

        assert!(pos.apply_funding_payment(i1, dec256!(5)));
        assert_eq!(pos.premium_pnl(), dec256!(-50));

        assert!(pos.apply_funding_payment(i2, dec256!(-10)));
        assert_eq!(pos.premium_pnl(), dec256!(50));

        assert!(!pos.apply_funding_payment(i2, dec256!(-10)));

        let mut pos = Position::opened(
            i0,
            1,
            1,
            PositionType::Short,
            U256::from(100),
            0,
            pc,
            udec64!(10),
            UD128::ZERO,
            UD64::ONE,
        );

        pos.apply_funding_payment(i1, dec256!(5));
        assert_eq!(pos.premium_pnl(), dec256!(50));

        pos.apply_funding_payment(i2, dec256!(-10));
        assert_eq!(pos.premium_pnl(), dec256!(-50));
    }

    // Funding-accrual vs. position-mutating events (Bug 44).
    //
    // `Exchange::apply_events` settles the block's scheduled funding before the
    // block's decreases, so the tick lands on each position's pre-decrease size
    // and the SDK matches the contract's re-derived premium. The tests below
    // verify that ordering at the Position level. A short of size 10 receives
    // +5*10 = +50 for a `payment_per_unit` of 5.
    fn short_at(instant: StateInstant) -> Position {
        Position::opened(
            instant,
            1,
            1,
            PositionType::Short,
            U256::from(100),
            0,
            num::Converter::new(4),
            udec64!(10),
            UD128::ZERO,
            UD64::ONE,
        )
    }

    // ── A/B/C: funding + decrease(s) in the SAME (funding-event) block ──────
    //
    // Scenario, matching the incident (one block holds the funding effect AND the
    // decreases):
    //
    // Block N:
    // the short (size 10) already exists and carries a funding balance —
    // opened earlier, with a prior funding tick that set premium = 50.
    //
    // Block N + m:
    // the funding-event block. Its scheduled funding takes effect here, in the
    // same block as the decrease(s), in some on-chain order:
    //     Tx A   decrease (10 -> 6)
    //     Tx B   decrease   (6 -> 3) [two-decrease test only]
    //     C      funding takes effect (effective-dated; not itself a tx)
    //
    // The contract re-derives premium at block N+m as
    //   (fundingSumAtBlock - entryFundingSum) * size / scaling
    // (`CalculationsLib::computePremiumPnl`), with `getFundingSumAtBlock`
    // returning the sum "prior to OR AT" the block, so the remaining premium is
    // (sn - entry) * final_size — independent of the on-chain order of A, B, C.
    //
    // `apply_events` settles the funding (C) in Pass 1, on each position's
    // pre-decrease size, before Pass 2 applies the decreases (A, B) — so the
    // SDK matches the contract for any order. These Position-level tests mirror
    // that ordering (funding first, then the decreases). so=5 -> sn=6 gives a
    // one-tick per-lot funding Δ=1; short of size 10, entry funding sum 0.

    #[test]
    fn test_funding_applied_before_same_block_decrease() {
        // The tick due at i2 is applied even though the position is also touched by a
        // decrease in the same block, because funding (Pass 1) runs first (Bug
        // 44 fix).
        let (i1, i2) = (StateInstant::new(1, 1), StateInstant::new(2, 2));
        let mut pos = short_at(StateInstant::default());
        assert!(pos.apply_funding_payment(i1, dec256!(5))); // premium = 50
        // Pass 1: funding on the full pre-decrease size 10.
        assert!(
            pos.apply_funding_payment(i2, dec256!(5)),
            "funding must be applied before the same-block decrease"
        );
        assert_eq!(pos.premium_pnl(), dec256!(100));
        // Pass 2: a decrease at i2 (value unchanged here to isolate the tick) does not
        // drop it.
        pos.update_premium_pnl(i2, pos.premium_pnl());
        assert_eq!(pos.premium_pnl(), dec256!(100));
    }

    #[test]
    fn test_funding_block_single_decrease_matches_sc() {
        let (i1, i2) = (StateInstant::new(1, 1), StateInstant::new(2, 2));
        // Block N: short size 10 with a prior funding tick (premium = so*10 = 50).
        let mut pos = short_at(StateInstant::default());
        assert!(pos.apply_funding_payment(i1, dec256!(5)));
        // Block N+m (funding-event block). Pass 1: the tick Δ=1 lands on the FULL
        // pre-decrease size 10 first -> premium = 50 + 1*10 = 60 (per-lot sum
        // now sn=6).
        assert!(pos.apply_funding_payment(i2, dec256!(1)));
        assert_eq!(pos.premium_pnl(), dec256!(60));
        // Pass 2: decrease 10 -> 6 (closes 4), realized at sn=6: fundingCNS = 6*4 = 24.
        pos.update_size(i2, udec64!(6));
        pos.update_premium_pnl(i2, pos.premium_pnl() - dec256!(24));
        // Matches the contract: (sn - entry) * final_size = 6 * 6 = 36 (the old bug
        // gave 26).
        assert_eq!(pos.premium_pnl(), dec256!(36));
    }

    #[test]
    fn test_funding_block_two_decreases_matches_sc() {
        // The A/B/C scenario: block N+m holds TWO decreases (A, B) AND the funding tick
        // (C). Funding (Pass 1) runs first, so the result equals the contract's
        // value for any on-chain tx order of A, B, C.
        let (i1, i2) = (StateInstant::new(1, 1), StateInstant::new(2, 2));
        // Block N: short size 10 with a prior funding tick (premium = 50).
        let mut pos = short_at(StateInstant::default());
        assert!(pos.apply_funding_payment(i1, dec256!(5)));
        // Pass 1: tick Δ=1 on the FULL pre-decrease size 10 -> 60.
        assert!(pos.apply_funding_payment(i2, dec256!(1)));
        assert_eq!(pos.premium_pnl(), dec256!(60));
        // Pass 2 -- A: 10 -> 6 (closes 4), fundingCNS_A = 6*4 = 24.
        pos.update_size(i2, udec64!(6));
        pos.update_premium_pnl(i2, pos.premium_pnl() - dec256!(24)); // 36
        // Pass 2 -- B: 6 -> 3 (closes 3), fundingCNS_B = 6*3 = 18.
        pos.update_size(i2, udec64!(3));
        pos.update_premium_pnl(i2, pos.premium_pnl() - dec256!(18)); // 18
        // Matches the contract: (sn - entry) * final_size = 6 * 3 = 18 (the old bug
        // gave 8).
        assert_eq!(pos.premium_pnl(), dec256!(18));
    }

    #[test]
    fn test_maintenance_margin_requirement() {
        let pc = num::Converter::new(4);
        let i0 = StateInstant::default();
        let (mm1, mm2) = (udec64!(20), udec64!(10));

        let mut pos = Position::opened(
            i0,
            1,
            1,
            PositionType::Long,
            U256::from(1000000),
            0,
            pc,
            udec64!(10),
            udec128!(100),
            mm1,
        );
        assert_eq!(pos.maintenance_margin_requirement(), udec128!(50));

        pos.update_entry_price(i0, U256::from(800000), 0, pc);
        pos.apply_maintenance_margin(i0, mm1);
        assert_eq!(pos.maintenance_margin_requirement(), udec128!(40));

        pos.update_size(i0, udec64!(20));
        pos.apply_maintenance_margin(i0, mm1);
        assert_eq!(pos.maintenance_margin_requirement(), udec128!(80));

        pos.apply_maintenance_margin(i0, mm2);
        assert_eq!(pos.maintenance_margin_requirement(), udec128!(160));

        let mut pos = Position::opened(
            i0,
            1,
            1,
            PositionType::Short,
            U256::from(1000000),
            0,
            pc,
            udec64!(10),
            udec128!(100),
            mm1,
        );
        assert_eq!(pos.maintenance_margin_requirement(), udec128!(50));

        pos.update_entry_price(i0, U256::from(800000), 0, pc);
        pos.apply_maintenance_margin(i0, mm1);
        assert_eq!(pos.maintenance_margin_requirement(), udec128!(40));

        pos.update_size(i0, udec64!(20));
        pos.apply_maintenance_margin(i0, mm1);
        assert_eq!(pos.maintenance_margin_requirement(), udec128!(80));

        pos.apply_maintenance_margin(i0, mm2);
        assert_eq!(pos.maintenance_margin_requirement(), udec128!(160));
    }

    #[test]
    fn test_liquidation_price() {
        let pc = num::Converter::new(4);
        let (i0, i1) = (StateInstant::default(), StateInstant::new(1, 1));
        let mm1 = udec64!(20);

        let mut pos = Position::opened(
            i0,
            1,
            1,
            PositionType::Long,
            U256::from(1000000),
            0,
            pc,
            udec64!(10),
            udec128!(100),
            mm1,
        );
        assert_eq!(pos.liquidation_price(), udec64!(95));

        assert!(pos.apply_funding_payment(i1, dec256!(5)));
        assert_eq!(pos.liquidation_price(), udec64!(100));

        let mut pos = Position::opened(
            i0,
            1,
            1,
            PositionType::Short,
            U256::from(1000000),
            0,
            pc,
            udec64!(10),
            udec128!(100),
            mm1,
        );
        assert_eq!(pos.liquidation_price(), udec64!(105));

        assert!(pos.apply_funding_payment(i1, dec256!(-5)));
        assert_eq!(pos.liquidation_price(), udec64!(100));
    }

    #[test]
    fn test_bankruptcy_price() {
        let pc = num::Converter::new(4);
        let (i0, i1) = (StateInstant::default(), StateInstant::new(1, 1));
        let mm1 = udec64!(20);

        let mut pos = Position::opened(
            i0,
            1,
            1,
            PositionType::Long,
            U256::from(1000000),
            0,
            pc,
            udec64!(10),
            udec128!(100),
            mm1,
        );
        assert_eq!(pos.bankruptcy_price(), udec64!(90));

        assert!(pos.apply_funding_payment(i1, dec256!(5)));
        assert_eq!(pos.bankruptcy_price(), udec64!(95));

        let mut pos = Position::opened(
            i0,
            1,
            1,
            PositionType::Short,
            U256::from(1000000),
            0,
            pc,
            udec64!(10),
            udec128!(100),
            mm1,
        );
        assert_eq!(pos.bankruptcy_price(), udec64!(110));

        assert!(pos.apply_funding_payment(i1, dec256!(-5)));
        assert_eq!(pos.bankruptcy_price(), udec64!(105));
    }

    #[test]
    fn test_liquidation_price_after_funding_received() {
        // Complements test_liquidation_price, which only drives premium NEGATIVE
        // (funding paid). Here the position RECEIVES funding, driving premium
        // to +50 and moving the liquidation price AWAY from entry — long 95 ->
        // 90, short 105 -> 110. Setup mirrors test_liquidation_price (entry
        // 100, size 10, deposit 100, mm 20 -> MMR 50).
        let pc = num::Converter::new(4);
        let (i0, i1) = (StateInstant::default(), StateInstant::new(1, 1));
        let mm1 = udec64!(20);

        // Long receives funding when longs are paid (negative payment).
        let mut pos = Position::opened(
            i0,
            1,
            1,
            PositionType::Long,
            U256::from(1000000),
            0,
            pc,
            udec64!(10),
            udec128!(100),
            mm1,
        );
        assert_eq!(pos.liquidation_price(), udec64!(95)); // 100 + (50-100-0)/10
        assert!(pos.apply_funding_payment(i1, dec256!(-5)), "long receives funding");
        assert_eq!(pos.premium_pnl(), dec256!(50)); // long sign -1: += -1*(-5)*10 = +50
        assert_eq!(pos.liquidation_price(), udec64!(90)); // 100 + (50-100-50)/10

        // Short receives funding when shorts are paid (positive payment).
        let mut pos = Position::opened(
            i0,
            1,
            1,
            PositionType::Short,
            U256::from(1000000),
            0,
            pc,
            udec64!(10),
            udec128!(100),
            mm1,
        );
        assert_eq!(pos.liquidation_price(), udec64!(105)); // 100 - (50-100-0)/10
        assert!(pos.apply_funding_payment(i1, dec256!(5)), "short receives funding");
        assert_eq!(pos.premium_pnl(), dec256!(50)); // short sign +1: += 1*5*10 = +50
        assert_eq!(pos.liquidation_price(), udec64!(110)); // 100 - (50-100-50)/10
    }

    #[test]
    fn test_bankruptcy_price_after_funding_received() {
        // Complements test_bankruptcy_price (premium negative only). The position
        // RECEIVES funding (+50): long bank 90 -> 85, short bank 110 -> 115.
        // Same setup as test_bankruptcy_price.
        let pc = num::Converter::new(4);
        let (i0, i1) = (StateInstant::default(), StateInstant::new(1, 1));
        let mm1 = udec64!(20);

        let mut pos = Position::opened(
            i0,
            1,
            1,
            PositionType::Long,
            U256::from(1000000),
            0,
            pc,
            udec64!(10),
            udec128!(100),
            mm1,
        );
        assert_eq!(pos.bankruptcy_price(), udec64!(90)); // 100 - (100+0)/10
        assert!(pos.apply_funding_payment(i1, dec256!(-5)), "long receives funding"); // premium +50
        assert_eq!(pos.bankruptcy_price(), udec64!(85)); // 100 - (100+50)/10

        let mut pos = Position::opened(
            i0,
            1,
            1,
            PositionType::Short,
            U256::from(1000000),
            0,
            pc,
            udec64!(10),
            udec128!(100),
            mm1,
        );
        assert_eq!(pos.bankruptcy_price(), udec64!(110)); // 100 + (100+0)/10
        assert!(pos.apply_funding_payment(i1, dec256!(5)), "short receives funding"); // premium +50
        assert_eq!(pos.bankruptcy_price(), udec64!(115)); // 100 + (100+50)/10
    }

    #[test]
    fn test_apply_mark_price_with_residue() {
        let i0 = StateInstant::default();
        let half_lsb = dec256!(0.0000005);
        let pc = num::Converter::new(6);

        let mut pos = Position::opened(
            i0,
            1,
            1,
            PositionType::Long,
            U256::from(100000000),
            32768, // residue = Q/2
            pc,
            udec64!(10),
            UD128::ZERO,
            UD64::ONE,
        );
        pos.apply_mark_price(i0, udec64!(100));
        // mark - effective = 100 - (100 - 0.5e-6) = +0.5e-6, * size 10 = 0.5e-5
        assert_eq!(pos.delta_pnl(), half_lsb * dec256!(10));

        let mut pos = Position::opened(
            i0,
            1,
            1,
            PositionType::Short,
            U256::from(100000000),
            32768,
            pc,
            udec64!(10),
            UD128::ZERO,
            UD64::ONE,
        );
        pos.apply_mark_price(i0, udec64!(100));
        // short: sign flip, effective = entry + 0.5e-6, (mark - effective) = -0.5e-6
        // delta_pnl = -1 * -0.5e-6 * 10 = 0.5e-5
        assert_eq!(pos.delta_pnl(), half_lsb * dec256!(10));

        // residue = 0 reproduces legacy behavior byte-identically.
        let mut pos = Position::opened(
            i0,
            1,
            1,
            PositionType::Long,
            U256::from(100000000),
            0,
            pc,
            udec64!(10),
            UD128::ZERO,
            UD64::ONE,
        );
        pos.apply_mark_price(i0, udec64!(150));
        assert_eq!(pos.delta_pnl(), dec256!(500));
    }
}