tape-core 0.4.7

A decentralized object store using Solana.
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
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
use crate::types::*;
use bytemuck::{Pod, Zeroable};

use super::schedule::*;
use super::state::*;
use crate::system::*;

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PoolError {
    ScheduleFailed,
    PoolInactive,
    BalanceExceeded,
    EpochInvalid,
    StakeInvalid,
    StakeActive,
    StakeNotActive,
    ZeroShares,
    ZeroStake,
    ZeroCommission,
}

#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct StakingPool<const N: usize> {
    /// The total number of shares issued by this pool.
    pub shares: ShareAmount,

    /// The total stake held by this pool (excluding commission).
    pub stake: Coin<TAPE>,

    /// The rewards this pool has earned from being active and available to distribute to stakers
    pub rewards: Coin<TAPE>,

    /// The commission earned by the pool operator, available for withdrawal.
    pub commission: Coin<TAPE>,

    /// The current commission rate.
    pub commission_rate: BasisPoints,

    /// All scheduled/pending changes tied to this pool.
    pub schedule: PoolSchedule<N>,
}

unsafe impl<const N: usize> Zeroable for StakingPool<N> {}
unsafe impl<const N: usize> Pod for StakingPool<N> {}

impl<const N: usize> StakingPool<N> {
    pub fn new(commission_rate: BasisPoints) -> Self {
        Self {
            shares: ShareAmount::zero(),
            stake: Coin::<TAPE>::zero(),
            rewards: Coin::<TAPE>::zero(),
            commission: Coin::<TAPE>::zero(),
            commission_rate,
            schedule: PoolSchedule::new(),
        }
    }

    /// Get the current exchange rate (stake per share).
    pub fn get_current_rate(&self) -> ExchangeRate {
        // Ensure both stake and shares are zero or non-zero, any other state is invalid.
        debug_assert!(self.shares.is_zero() == self.stake.is_zero());

        if self.shares.is_zero() {
            ExchangeRate::flat()
        } else {
            ExchangeRate::new(
                self.stake.into(),
                self.shares.into()
            )
        }
    }

    /// Project the stake at a future epoch, valid for Next N epochs 
    /// (uses current exchange rate snapshot).
    pub fn calculate_stake_at(&self, epoch: EpochNumber) -> Coin<TAPE> {

        // Calculate current exchange rate (stake per share)
        let exchange_rate = self.get_current_rate();

        // Calculate net token additions (incoming - outgoing)
        let incoming = self.schedule.stake_sum(epoch);
        let outgoing = self.schedule.cancel_sum(epoch);
        let net_additions = incoming.saturating_sub(outgoing);

        // Convert outgoing shares to token amount
        let outgoing_shares = self.schedule.unstake_sum(epoch);
        let outgoing_tokens = exchange_rate
            .convert_to_tape_amount(outgoing_shares.into())
            .into();

        // Compute final stake: current stake + net additions - outgoing tokens
        self.stake
            .saturating_add(net_additions)
            .saturating_sub(outgoing_tokens)
    }

    /// Claim the full accumulated commission. Returns the amount and zeroes the commission
    /// balance.
    pub fn claim_commission(&mut self) -> Result<Coin<TAPE>, PoolError> {
        if self.commission.is_zero() {
            return Err(PoolError::ZeroCommission);
        }

        let amount = self.commission;

        self.commission = TAPE::zero();

        Ok(amount)
    }

    /// Advance the pool state to the next epoch, applying any scheduled changes and distributing
    /// rewards.
    pub fn advance_epoch(
        &mut self,
        current_epoch: EpochNumber,
        rewards_earned: Coin<TAPE>,
    ) -> Result<(), PoolError> {

        if let Some(commission_rate) = self.schedule.take_commission_change(current_epoch) {
            self.commission_rate = commission_rate;
        }

        let snapshot = self.get_current_rate();

        self.process_scheduled_reductions(current_epoch, snapshot)?;
        self.process_scheduled_additions(current_epoch, snapshot)?;

        if rewards_earned > TAPE::zero() {
            if self.stake.is_zero() {
                return Err(PoolError::StakeInvalid);
            }

            let commission_cut = (
                rewards_earned.as_u128() * self.commission_rate.as_u128() / BasisPoints::MAX as u128
            ) as u64;

            let rewards_net = rewards_earned.saturating_sub(commission_cut.into());

            self.commission = self.commission.saturating_add(commission_cut.into());
            self.rewards = self.rewards.saturating_add(rewards_net);
            self.stake = self.stake.saturating_add(rewards_net);
        }

        Ok(())
    }

    /// Stake tokens with this pool (schedules activation at E+2).
    pub fn stake_with_pool(
        &mut self,
        current_epoch: EpochNumber,
        stake_amount: Coin<TAPE>,
    ) -> Result<StakedTape, PoolError> {
        let activation_epoch = current_epoch + EpochNumber(2);
        self.stake_with_pool_at(current_epoch, activation_epoch, stake_amount)
    }

    /// Stake tokens with explicit activation epoch.
    /// Used for conditional immediate activation in low-quorum mode.
    ///
    /// If activation_epoch == current_epoch, the stake is applied immediately
    /// so the node can join committee_next without waiting for advance_pool.
    pub fn stake_with_pool_at(
        &mut self,
        current_epoch: EpochNumber,
        activation_epoch: EpochNumber,
        stake_amount: Coin<TAPE>,
    ) -> Result<StakedTape, PoolError> {
        if stake_amount.is_zero() {
            return Err(PoolError::ZeroStake);
        }

        let mut state = StakeState::new();

        // If activation is immediate, apply stake now and skip scheduling.
        // Otherwise, schedule for future activation via advance_pool.
        if activation_epoch == current_epoch {

            // The only call site that uses this branch gates 
            // on current_epoch == 0 (bootstrap, empty pool, rate = 1:1)
            debug_assert!(
                current_epoch == EpochNumber(0),
                "immediate activation is only safe at the bootstrap epoch",
            );

            let rate = self.get_current_rate();
            let shares: ShareAmount = rate.convert_to_other_amount(stake_amount.into()).into();

            self.stake = self.stake.saturating_add(stake_amount);
            self.shares = self.shares.saturating_add(shares);

            state.set_staked();
        } else {
            // Only schedule if activation is in the future
            self.schedule
                .stake(activation_epoch, stake_amount)
                .map_err(|_| PoolError::ScheduleFailed)?;
        }

        Ok(StakedTape {
            activation_epoch,
            amount: stake_amount,
            unlock_shares: ShareAmount::zero(),
            state,
        })
    }

    /// Request a stake cancel from this pool.
    /// Caller provides the activation exchange rate for this stake.
    pub fn request_cancel(
        &mut self,
        stake: &mut StakedTape,
        current_epoch: EpochNumber,
    ) -> Result<EpochNumber, PoolError> {

        if !stake.is_staked() {
            return Err(PoolError::StakeInvalid);
        }

        if stake.amount.is_zero() {
            return Err(PoolError::StakeInvalid);
        }

        // If the stake is already active, cannot cancel
        if stake.activation_epoch <= current_epoch {
            return Err(PoolError::StakeActive);
        }

        let withdraw_epoch = stake.activation_epoch;

        // Schedule the stake principal to be canceled at activation_epoch.
        // The net result is 0 stake change at that epoch.
        self.schedule
            .cancel(withdraw_epoch, stake.amount)
            .map_err(|_| PoolError::ScheduleFailed)?;

        stake.set_withdrawing(withdraw_epoch);

        Ok(withdraw_epoch)
    }

    /// Request a withdrawal of stake from this pool. 
    /// (Caller provides the activation exchange rate for this stake)
    pub fn request_withdraw(
        &mut self,
        stake: &mut StakedTape,
        current_epoch: EpochNumber,
        stake_activation_rate: ExchangeRate,
    ) -> Result<EpochNumber, PoolError> {
        if !stake.is_staked() {
            return Err(PoolError::StakeInvalid);
        }

        if stake.amount.is_zero() {
            return Err(PoolError::StakeInvalid);
        }

        // If the stake is not yet active, the stake cannot be withdrawn, it must be canceled.
        if stake.activation_epoch > current_epoch {
            return Err(PoolError::StakeNotActive);
        }

        // This is an active stake withdraw, so we need to schedule a share removal
        // which would calculate rewards at withdraw time.

        let withdraw_epoch = current_epoch + EpochNumber(2);

        // Calculate the shares corresponding to this stake at activation rate
        let shares : ShareAmount = stake_activation_rate
            .convert_to_other_amount(stake.amount.into())
            .into();

        if shares.is_zero() {
            return Err(PoolError::ZeroShares);
        }

        self.schedule
            .unstake(withdraw_epoch, shares)
            .map_err(|_| PoolError::ScheduleFailed)?;

        stake.set_withdrawing(withdraw_epoch);
        stake.set_unlock_shares(shares);

        Ok(withdraw_epoch)
    }

    /// Withdrawn stake (capped by pool available rewards).
    /// Caller computes owed amount externally (e.g., via history or snapshot math).
    pub fn unstake_from_pool(
        &mut self,
        stake: &mut StakedTape,
        current_epoch: EpochNumber,
        owed_rewards: Coin<TAPE>,
    ) -> Result<Coin<TAPE>, PoolError> {
        if !stake.is_withdrawing() {
            return Err(PoolError::StakeInvalid);
        }

        let stake_withdraw_epoch = stake
            .state
            .withdraw_epoch()
            .ok_or(PoolError::StakeInvalid)?;

        if stake_withdraw_epoch > current_epoch {
            return Err(PoolError::EpochInvalid);
        }

        if stake.amount.is_zero() {
            return Err(PoolError::StakeInvalid);
        }

        // If the withdraw epoch is before or at activation, then no rewards are due.
        if stake_withdraw_epoch <= stake.activation_epoch {
            return Ok(TAPE::zero());
        }

        // Cap by available rewards
        let pay = if owed_rewards > self.rewards {
            self.rewards
        } else {
            owed_rewards
        };

        self.rewards = self.rewards
            .saturating_sub(pay);

        stake.set_withdrawn();

        Ok(pay)
    }

    /// Process pending stake additions and pre-active cancellations for the current_epoch.
    fn process_scheduled_additions(
        &mut self, current_epoch: EpochNumber,
        shapshot_rate: ExchangeRate,
        ) -> Result<(), PoolError> {

        // Sum all pending stake before or at current_epoch
        let incoming = self.schedule
            .take_incoming(current_epoch);

        // Sum all pre-active cancellations before or at current_epoch
        let outgoing = self.schedule
            .take_outgoing(current_epoch);

        // Net pending stake must be non-negative
        if outgoing > incoming {
            return Err(PoolError::BalanceExceeded);
        }

        // Increase stake by net added stake
        let net_added = incoming - outgoing;
        if net_added > TAPE::zero() {

            let incoming_shares = shapshot_rate
                .convert_to_other_amount(net_added.into())
                .into();
            
            self.shares = self.shares.saturating_add(incoming_shares);
            self.stake = self.stake.saturating_add(net_added);
        }

        Ok(())
    }

    /// Process pending share withdrawals for the current_epoch.
    ///
    /// Dust policy: we burn shares in a single aggregate step using floor of
    /// the sum, but each user is later paid floor of their own share count.
    /// The aggregate floor can exceed the sum of individual floors by up to
    /// (n - 1) flux when n users exit at the same epoch. That difference is
    /// retained in pool accounting (the rate stays exact) and the underlying
    /// tokens sit in the archive. It is not claimable by anyone and never
    /// causes an over-payment.
    fn process_scheduled_reductions(
        &mut self,
        current_epoch: EpochNumber,
        shapshot_rate: ExchangeRate,
    ) -> Result<(), PoolError> {

        // Sum all pending shares withdrawing before or at current_epoch
        let outgoing_shares = self.schedule
            .take_outgoing_shares(current_epoch);

        if outgoing_shares > self.shares {
            return Err(PoolError::BalanceExceeded);
        }

        // Convert shares to tape at the current price
        let net_removed = shapshot_rate
            .convert_to_tape_amount(outgoing_shares.into())
            .into();

        if self.stake < net_removed {
            return Err(PoolError::BalanceExceeded);
        }

        if outgoing_shares > ShareAmount::zero() {
            self.shares = self.shares
                .saturating_sub(outgoing_shares);

            self.stake = self.stake
                .saturating_sub(net_removed);
        }

        Ok(())
    }
}



#[cfg(test)]
mod tests {
    use super::*;

    type TestPool = StakingPool<4>;

    fn epoch(n: u64) -> EpochNumber { EpochNumber(n) }
    fn tape(v: u64) -> Coin<TAPE> { TAPE(v) }
    fn shares(v: u64) -> ShareAmount { ShareAmount(v) }

    #[test]
    fn new_ok() {
        let p = TestPool::new(BasisPoints(1000));

        assert_eq!(p.stake, TAPE::zero());
        assert_eq!(p.shares, shares(0));
        assert_eq!(p.commission_rate, BasisPoints(1000));
    }

    #[test]
    fn stake_sched() {
        let mut p = TestPool::new(BasisPoints(0));
        let s = p.stake_with_pool(epoch(5), tape(700)).unwrap();

        assert_eq!(s.activation_epoch, epoch(7));
        assert_eq!(p.schedule.stake_sum(epoch(6)), tape(0));
        assert_eq!(p.schedule.stake_sum(epoch(7)), tape(700));
    }

    #[test]
    fn rate_empty_flat() {
        let p = TestPool::new(BasisPoints(0));
        assert_eq!(p.get_current_rate(), ExchangeRate::flat());
    }

    #[test]
    fn cancel_after_active_err() {
        let mut p = TestPool::new(BasisPoints(0));

        // Stake at E1 -> activate at E3
        let mut s = p.stake_with_pool(epoch(1), tape(700)).unwrap();

        // Walk to activation and make stake active
        p.advance_epoch(epoch(1), tape(0)).unwrap();
        p.advance_epoch(epoch(2), tape(0)).unwrap();
        p.advance_epoch(epoch(3), tape(0)).unwrap();

        // Cancel after activation should error
        let err = p.request_cancel(&mut s, epoch(3)).unwrap_err();
        assert!(matches!(err, PoolError::StakeActive));
    }

    #[test]
    fn withdraw_zero_amount_err() {
        let mut p = TestPool::new(BasisPoints(0));

        // Synthetic active stake with zero amount
        let mut s = StakedTape {
            amount: tape(0),
            activation_epoch: epoch(2),
            unlock_shares: ShareAmount::zero(),
            state: StakeState::new(),
        };

        // Current >= activation to avoid StakeNotActive
        let err = p.request_withdraw(&mut s, epoch(2), ExchangeRate::flat()).unwrap_err();
        assert!(matches!(err, PoolError::StakeInvalid));
    }

    #[test]
    fn advance_commission() {
        let mut p = TestPool::new(BasisPoints(1000)); // 10%

        // Activate 1_000 at E1 (raw insert for immediate activation)
        p.schedule.stake(epoch(1), tape(1_000)).unwrap();
        p.advance_epoch(epoch(1), tape(0)).unwrap();
        assert_eq!(p.stake, tape(1_000));

        // Add 500 gross at E2 → 10% commission, 450 net
        p.advance_epoch(epoch(2), tape(500)).unwrap();
        assert_eq!(p.commission, tape(50));
        assert_eq!(p.rewards, tape(450));
        assert_eq!(p.stake, tape(1_450));
    }

    #[test]
    fn adv_no_stake_err() {
        let mut p = TestPool::new(BasisPoints(0));
        let err = p.advance_epoch(epoch(1), tape(10)).unwrap_err();
        assert!(matches!(err, PoolError::StakeInvalid));
    }

    #[test]
    fn set_comm_next() {
        let mut p = TestPool::new(BasisPoints(1000));

        p.schedule.stake(epoch(1), tape(100)).unwrap();
        p.advance_epoch(epoch(1), tape(0)).unwrap();

        p.schedule.set_commission(epoch(4), BasisPoints(2000)).unwrap(); // applies at E4

        p.advance_epoch(epoch(3), tape(0)).unwrap();
        assert_eq!(p.commission_rate, BasisPoints(1000));

        p.advance_epoch(epoch(4), tape(0)).unwrap();
        assert_eq!(p.commission_rate, BasisPoints(2000));
    }

    #[test]
    fn process_pending() {
        let mut p = TestPool::new(BasisPoints(0));

        p.schedule.stake(epoch(1), tape(1000)).unwrap();
        p.advance_epoch(epoch(1), tape(0)).unwrap();

        let r1 = p.get_current_rate();

        assert_eq!(p.stake, tape(1000));
        assert_eq!(p.shares, r1.convert_to_other_amount(p.stake.into()).into());
    }

    #[test]
    fn balance_calc() {
        let mut p = TestPool::new(BasisPoints(0));

        p.schedule.stake(epoch(1), tape(1000)).unwrap();
        p.advance_epoch(epoch(1), tape(0)).unwrap(); // balance=1000

        // Schedule more stake for E5 and a withdraw at E6
        p.schedule.stake(epoch(5), tape(600)).unwrap();
        p.schedule.unstake(epoch(6), shares(200)).unwrap();

        // Projection uses current rate (flat 1:1 here)
        assert_eq!(p.calculate_stake_at(epoch(4)), tape(1000));
        assert_eq!(p.calculate_stake_at(epoch(5)), tape(1600));
        assert_eq!(p.calculate_stake_at(epoch(6)), tape(1400));
    }

    #[test]
    fn exceed_pre_active_err() {
        let mut p = TestPool::new(BasisPoints(0));

        p.schedule.stake(epoch(3), tape(100)).unwrap();
        p.schedule.cancel(epoch(3), tape(200)).unwrap();

        let err = p.advance_epoch(epoch(3), tape(0)).unwrap_err();
        assert!(matches!(err, PoolError::BalanceExceeded));
    }

    #[test]
    fn exceed_shares_err() {
        let mut p = TestPool::new(BasisPoints(0));

        p.schedule.stake(epoch(1), tape(1000)).unwrap();
        p.advance_epoch(epoch(1), tape(0)).unwrap();

        p.schedule.unstake(epoch(2), shares(1500)).unwrap();
        let err = p.advance_epoch(epoch(2), tape(0)).unwrap_err();

        assert!(matches!(err, PoolError::BalanceExceeded));
    }

    #[test]
    fn withdraw_pre_active() {
        let mut p = TestPool::new(BasisPoints(0));

        // Create a pre-active stake at current=5 → activation=7
        let mut s = p.stake_with_pool(epoch(5), tape(500)).unwrap();

        // Since activation is in the future, we should get an error trying to withdraw
        let err = p.request_withdraw(&mut s, epoch(5), ExchangeRate::flat()).unwrap_err();
        assert!(matches!(err, PoolError::StakeNotActive));

        // Instead, request a cancel
        let we = p.request_cancel(&mut s, epoch(5)).unwrap();

        assert_eq!(we, epoch(7)); // current(5)+2
        assert_eq!(p.schedule.cancel_sum(epoch(7)), tape(500));
        assert_eq!(p.schedule.unstake_sum(epoch(7)), shares(0));
    }

    #[test]
    fn withdraw_active() {
        let mut p = TestPool::new(BasisPoints(0));
        let flat = ExchangeRate::flat();

        // Stake at E1 → activation E3
        let mut s = p.stake_with_pool(epoch(1), tape(1000)).unwrap();

        // Advance epochs so activation snapshot exists and stake is active
        p.advance_epoch(epoch(1), tape(0)).unwrap();
        p.advance_epoch(epoch(2), tape(0)).unwrap();
        p.advance_epoch(epoch(3), tape(0)).unwrap();

        // Request at E3 → withdraw at E5; shares computed from rate at activation (E3)
        let activation_rate = flat;
        let we = p.request_withdraw(&mut s, epoch(3), activation_rate).unwrap();

        assert_eq!(we, epoch(5));
        assert_eq!(p.schedule.unstake_sum(epoch(5)), shares(1000));
    }

    #[test]
    fn withdraw_pre_no_rewards() {
        let mut p = TestPool::new(BasisPoints(0));

        // Pre-active: stake at E5 → activation E7
        let mut s = p.stake_with_pool(epoch(5), tape(500)).unwrap();
        p.request_cancel(&mut s, epoch(5)).unwrap(); // withdraw E7

        // Walk epochs
        p.advance_epoch(epoch(6), tape(0)).unwrap();
        p.advance_epoch(epoch(7), tape(0)).unwrap();

        // No rewards owed for pre-active cancel
        let paid = p.unstake_from_pool(&mut s, epoch(8), tape(0)).unwrap();

        assert_eq!(paid, tape(0));
    }

    #[test]
    fn rate_change_and_withdraw() {
        let mut p = TestPool::new(BasisPoints(0));

        // Seed the pool so rewards can be earned.
        p.schedule.stake(epoch(0), tape(100)).unwrap();

        // Create a user stake at current=E1 → activation=E3 (E+2)
        let mut s = p.stake_with_pool(epoch(1), tape(100)).unwrap();

        // E1: activate seed
        p.advance_epoch(epoch(1), tape(0)).unwrap();
        let r1 = p.get_current_rate();
        assert_eq!(r1, ExchangeRate { tape: 100, other: 100 });

        // E2: rewards 10
        p.advance_epoch(epoch(2), tape(10)).unwrap();
        let r2 = p.get_current_rate();
        assert_eq!(r2, ExchangeRate { tape: 110, other: 100 });

        // E3: user's 100 activates at pre-rewards snapshot (110/100), then rewards 10 land
        p.advance_epoch(epoch(3), tape(10)).unwrap();
        let r3 = p.get_current_rate();
        assert_eq!(r3, ExchangeRate { tape: 220, other: 190 });

        // Request at E3 → withdraw epoch = E5 (E+2)
        let activation_rate = r3; // rate at activation E3
        p.request_withdraw(&mut s, epoch(3), activation_rate).unwrap();

        // E4: rewards 30
        p.advance_epoch(epoch(4), tape(30)).unwrap();
        let r4 = p.get_current_rate();
        assert_eq!(r4, ExchangeRate { tape: 250, other: 190 });

        // E5: process share withdrawal at the pre-rewards snapshot, then rewards 30 land
        p.advance_epoch(epoch(5), tape(30)).unwrap();
        let r5 = p.get_current_rate();

        // After burning 86 shares at the E5 snapshot (250/190), stake and shares should be:
        // burned stake = floor(86 * 250 / 190) = 113; stake=137+30=167, shares=104
        assert_eq!(r5, ExchangeRate { tape: 167, other: 104 });
        assert_eq!(p.stake, tape(167));
        assert_eq!(p.shares, shares(104));

        // Compute owed rewards for the user:
        // shares_user = floor(100 * 190 / 220) = 86
        // tape_at_r4 = floor(86 * 250 / 190) = 113
        // owed = 113 - 100 = 13

        let user_shares: ShareAmount = r3
            .convert_to_other_amount(s.amount.into())
            .into();
        let tape_at_r4: Coin<TAPE> = r4
            .convert_to_tape_amount(user_shares.into())
            .into();
        let owed = tape_at_r4.saturating_sub(s.amount);

        let paid = p.unstake_from_pool(&mut s, epoch(5), owed).unwrap();
        assert_eq!(paid, owed);

        // Rewards pool started at 0 and got +10 (E2) +10 (E3) +30 (E4) +30 (E5) = 80,
        // then we paid 13 to the user.
        assert_eq!(p.rewards, tape(67));
    }

    #[test]
    fn rewards_only() {
        let mut p = TestPool::new(BasisPoints(0));

        // Seed and activate 100 at E1
        p.schedule.stake(epoch(0), tape(100)).unwrap();
        p.advance_epoch(epoch(1), tape(0)).unwrap();
        assert_eq!(p.stake, tape(100));
        assert_eq!(p.shares, shares(100));

        // E2 +50 rewards; shares unchanged
        p.advance_epoch(epoch(2), tape(50)).unwrap();
        assert_eq!(p.stake, tape(150));
        assert_eq!(p.shares, shares(100));
        assert_eq!(p.rewards, tape(50));

        // E3 +25 rewards; shares unchanged
        p.advance_epoch(epoch(3), tape(25)).unwrap();
        assert_eq!(p.stake, tape(175));
        assert_eq!(p.shares, shares(100));
        assert_eq!(p.rewards, tape(75));

        // Rate follows stake/shares
        let r3 = p.get_current_rate();
        assert_eq!(r3, ExchangeRate { tape: 175, other: 100 });
    }

     #[test]
    fn pre_active_cancel_no_shares() {
        let mut p = TestPool::new(BasisPoints(0));

        // User stakes at E1 -> activation E3
        let mut s = p.stake_with_pool(epoch(1), tape(200)).unwrap();

        // Before activation, cancel the stake (withdraw_epoch=E3)
        let we = p.request_cancel(&mut s, epoch(1)).unwrap();
        assert_eq!(we, epoch(3));

        // Walk epochs; since it was pre-active, no shares should be minted ever
        p.advance_epoch(epoch(1), tape(0)).unwrap();
        p.advance_epoch(epoch(2), tape(0)).unwrap();
        p.advance_epoch(epoch(3), tape(0)).unwrap();

        assert_eq!(p.shares, shares(0));
        assert_eq!(p.stake, tape(0));
        assert_eq!(p.rewards, tape(0));

        // No rewards owed for pre-active cancel path
        let paid = p.unstake_from_pool(&mut s, epoch(3), tape(0)).unwrap();
        assert_eq!(paid, tape(0));
    }

    #[test]
    fn two_users_fair_split() {
        let mut p = TestPool::new(BasisPoints(0));

        // Seed pool so rewards can be earned
        p.schedule.stake(epoch(0), tape(100)).unwrap();

        // Alice stakes at E1 -> activation E3
        let mut a = p.stake_with_pool(epoch(1), tape(100)).unwrap();

        p.advance_epoch(epoch(1), tape(0)).unwrap();   // E1
        p.advance_epoch(epoch(2), tape(60)).unwrap();  // E2: rewards 60, A not yet active
        p.advance_epoch(epoch(3), tape(40)).unwrap();  // E3: rewards 40, A activates this epoch

        let r3 = p.get_current_rate();

        // Bob stakes at E3 -> activation E5
        let mut b = p.stake_with_pool(epoch(3), tape(100)).unwrap();

        // Alice withdraws at E3 → E5
        p.request_withdraw(&mut a, epoch(3), r3).unwrap();

        // E4: rewards 50 (A accrues this epoch; Bob not yet active)
        p.advance_epoch(epoch(4), tape(50)).unwrap();
        let r4 = p.get_current_rate();

        // E5: rewards 0; process Alices withdrawal
        p.advance_epoch(epoch(5), tape(0)).unwrap();
        let r5 = p.get_current_rate();

        // Compute A owed from activation rate r3 to r4 only
        let a_shares: ShareAmount = r3.convert_to_other_amount(a.amount.into()).into();
        let a_tape_at_r4: Coin<TAPE> = r4.convert_to_tape_amount(a_shares.into()).into();
        let a_owed = a_tape_at_r4.saturating_sub(a.amount);
        let paid_a = p.unstake_from_pool(&mut a, epoch(5), a_owed).unwrap();
        assert_eq!(paid_a, a_owed);

        // Now Bob activates at E5; schedule Bob withdraw at E5 → E7
        let r5_activation = r5;
        p.request_withdraw(&mut b, epoch(5), r5_activation).unwrap();

        // E6: add rewards 30 (Bob accrues this epoch)
        p.advance_epoch(epoch(6), tape(30)).unwrap();
        let r6 = p.get_current_rate();

        // E7: process Bob withdrawal
        p.advance_epoch(epoch(7), tape(0)).unwrap();

        // Compute Bob owed from r5 to r6 only
        let b_shares: ShareAmount = r5_activation.convert_to_other_amount(b.amount.into()).into();
        let b_tape_at_r6: Coin<TAPE> = r6.convert_to_tape_amount(b_shares.into()).into();
        let b_owed = b_tape_at_r6.saturating_sub(b.amount);
        let paid_b = p.unstake_from_pool(&mut b, epoch(7), b_owed).unwrap();

        assert_eq!(paid_b, b_owed);

        // No overpayment: paid <= total pool rewards accumulated
        // Total rewards collected by pool were 60 + 40 + 50 + 30 = 180; ensure paid_a + paid_b <= 180
        assert!(paid_a.as_u64() + paid_b.as_u64() <= 180);
    }

    #[test]
    fn withdraw_and_cap() {
        let mut p = TestPool::new(BasisPoints(0));

        // Seed the pool so rewards can be earned.
        p.schedule.stake(epoch(0), tape(100)).unwrap();

        // Create a user stake at current=E1 → activation=E3 (E+2)
        let mut s = p.stake_with_pool(epoch(1), tape(100)).unwrap();

        p.advance_epoch(epoch(1), tape(0)).unwrap();
        let r1 = p.get_current_rate();
        assert_eq!(r1, ExchangeRate { tape: 100, other: 100 });
        p.advance_epoch(epoch(2), tape(10)).unwrap();
        let r2 = p.get_current_rate();
        assert_eq!(r2, ExchangeRate { tape: 110, other: 100 });
        p.advance_epoch(epoch(3), tape(10)).unwrap();
        let r3 = p.get_current_rate();
        assert_eq!(r3, ExchangeRate { tape: 220, other: 190 });

        // Request at E3 → withdraw epoch = E5 (E+2)
        let activation_rate = r3; // rate at activation E3
        p.request_withdraw(&mut s, epoch(3), activation_rate).unwrap();

        // Add rewards AFTER activation.
        p.advance_epoch(epoch(4), tape(30)).unwrap();
        let r4 = p.get_current_rate();
        assert_eq!(r4, ExchangeRate { tape: 250, other: 190 });
        p.advance_epoch(epoch(5), tape(30)).unwrap();

        // Cap rewards pool to 10
        p.rewards = tape(10);

        // Compute owed using the last pre-withdraw snapshot (r4)
        let shares = activation_rate.convert_to_other_amount(s.amount.into());
        let owed = tape(r4.convert_to_tape_amount(shares).saturating_sub(s.amount.into()));

        let paid = p.unstake_from_pool(&mut s, epoch(5), owed).unwrap();
        assert_eq!(paid, tape(10));
        assert_eq!(p.rewards, tape(0));
    }

    #[test]
    fn withdraw_early_err() {
        let mut p = TestPool::new(BasisPoints(0));

        // Stake at E1 → activate E3
        let mut s = p.stake_with_pool(epoch(1), tape(100)).unwrap();
        p.advance_epoch(epoch(1), tape(0)).unwrap();
        p.advance_epoch(epoch(2), tape(0)).unwrap();
        p.advance_epoch(epoch(3), tape(0)).unwrap();

        // Request at E3 → withdraw at E5
        let activation_rate = p.get_current_rate();
        p.request_withdraw(&mut s, epoch(3), activation_rate).unwrap();

        // Try to claim at E4 < withdraw → error
        p.advance_epoch(epoch(4), tape(0)).unwrap(); // advance to E4
 
        let r4 = p.get_current_rate();
        let shares = activation_rate.convert_to_other_amount(s.amount.into());
        let owed = tape(r4.convert_to_tape_amount(shares).saturating_sub(s.amount.into()));
        let err = p.unstake_from_pool(&mut s, epoch(4), owed).unwrap_err();
        assert!(matches!(err, PoolError::EpochInvalid));
    }

    #[test]
    fn alice_single() {
        let mut p = TestPool::new(BasisPoints(0));

        // Alice stakes at E0 → activation E2 (E+2)
        let mut alice = p.stake_with_pool(epoch(0), tape(1000)).unwrap();

        // E1: no rewards, still pre-active
        p.advance_epoch(epoch(1), tape(0)).unwrap();

        // E2: activation (no rewards)
        p.advance_epoch(epoch(2), tape(0)).unwrap();
        let r2 = p.get_current_rate();
        assert_eq!(r2, ExchangeRate { tape: 1000, other: 1000 });

        // E3: pool earns 1000
        p.advance_epoch(epoch(3), tape(1000)).unwrap();

        // Request withdraw at E3 → withdraw at E5
        p.request_withdraw(&mut alice, epoch(3), r2).unwrap();

        // E4: no rewards; compute owed at E4 (pre-withdraw snapshot)
        p.advance_epoch(epoch(4), tape(0)).unwrap();
        let r4 = p.get_current_rate();

        // Compute owed using activation shares and E4 rate
        let shares = r2.convert_to_other_amount(alice.amount.into());
        let tape_at_r4 = r4.convert_to_tape_amount(shares);
        let owed = tape(tape_at_r4.saturating_sub(alice.amount.into()));

        // E5: process withdraw; then pay rewards
        p.advance_epoch(epoch(5), tape(0)).unwrap();

        let paid = p.unstake_from_pool(&mut alice, epoch(5), owed).unwrap();
        assert_eq!(paid, owed);
        assert!(paid > TAPE(0));
    }

    #[test]
    fn alice_bob_split() {
        let mut p = TestPool::new(BasisPoints(0));

        // E0: both stake → activate E2
        let mut alice = p.stake_with_pool(epoch(0), tape(1000)).unwrap();
        let mut bob   = p.stake_with_pool(epoch(0), tape(1000)).unwrap();

        p.advance_epoch(epoch(1), tape(0)).unwrap();
        p.advance_epoch(epoch(2), tape(0)).unwrap(); // E2: both active
        let r2 = p.get_current_rate();

        // E3: rewards 1000
        p.advance_epoch(epoch(3), tape(1000)).unwrap();

        // Both request at E3 → withdraw E5
        let activation_rate = r2;
        let wa = p.request_withdraw(&mut alice, epoch(3), activation_rate).unwrap();
        let wb = p.request_withdraw(&mut bob,   epoch(3), activation_rate).unwrap();
        assert_eq!(wa, epoch(5));
        assert_eq!(wb, epoch(5));

        // E4: settle, no rewards
        p.advance_epoch(epoch(4), tape(0)).unwrap();
        let r4 = p.get_current_rate();

        // E5: claim
        p.advance_epoch(epoch(5), tape(0)).unwrap();

        let shares = activation_rate.convert_to_other_amount(tape(1000).into());
        let owed_each = tape(r4.convert_to_tape_amount(shares).saturating_sub(1000));

        let ra = p.unstake_from_pool(&mut alice, epoch(5), owed_each).unwrap();
        let rb = p.unstake_from_pool(&mut bob,   epoch(5), owed_each).unwrap();

        assert_ne!(ra, 0.into());
        assert_eq!(ra, rb);
    }

    #[test]
    fn commission_round() {
        let mut p = TestPool::new(BasisPoints(1000)); // 10%

        // E0 stake → activate E2
        let mut alice = p.stake_with_pool(epoch(0), tape(1000)).unwrap();

        p.advance_epoch(epoch(1), tape(0)).unwrap();   // E1
        p.advance_epoch(epoch(2), tape(0)).unwrap();   // E2 active
        let r2 = p.get_current_rate();
        p.advance_epoch(epoch(3), tape(202)).unwrap(); // E3 rewards gross=202 → commission=20, net=182

        assert_eq!(p.commission, tape(20));
        assert_eq!(p.rewards, tape(182));

        // Request at E3 → withdraw E5; no more rewards
        let activation_rate = r2;
        p.request_withdraw(&mut alice, epoch(3), activation_rate).unwrap();
        p.advance_epoch(epoch(4), tape(0)).unwrap();

        let r4 = p.get_current_rate();
        p.advance_epoch(epoch(5), tape(0)).unwrap();

        let shares = activation_rate.convert_to_other_amount(alice.amount.into());
        let owed = tape(r4.convert_to_tape_amount(shares).saturating_sub(alice.amount.into()));
        let paid = p.unstake_from_pool(&mut alice, epoch(5), owed).unwrap();

        assert_eq!(paid, tape(182));
        assert_eq!(p.commission, tape(20));
    }

    #[test]
    fn early_blocked() {
        let mut p = TestPool::new(BasisPoints(0));

        // Stake at E1 → activate E3
        let mut alice = p.stake_with_pool(epoch(1), tape(500)).unwrap();

        // Make sure activation snapshot exists
        p.advance_epoch(epoch(2), tape(0)).unwrap();
        p.advance_epoch(epoch(3), tape(0)).unwrap();
        let r3 = p.get_current_rate();

        // Request at E3 → withdraw E5
        let activation_rate = r3;
        p.request_withdraw(&mut alice, epoch(3), activation_rate).unwrap();

        // Trying to claim at E4 (< E5) must error
        p.advance_epoch(epoch(4), tape(0)).unwrap();

        let shares = activation_rate.convert_to_other_amount(alice.amount.into());
        let owed = tape(r3.convert_to_tape_amount(shares).saturating_sub(alice.amount.into()));
        let err = p.unstake_from_pool(&mut alice, epoch(4), owed).unwrap_err();

        assert!(matches!(err, PoolError::EpochInvalid));
    }

    #[test]
    fn maintain_ratio() {
        let mut p = TestPool::new(BasisPoints(0));

        // Alice stakes 1000 at E0 (E2 active)
        let mut alice = p.stake_with_pool(epoch(0), tape(1000)).unwrap();
        p.advance_epoch(epoch(1), tape(0)).unwrap();
        p.advance_epoch(epoch(2), tape(0)).unwrap();
        let r2 = p.get_current_rate();

        // Bob stakes 2000 at E1 (E3 active)
        let mut bob = p.stake_with_pool(epoch(1), tape(2000)).unwrap();
        p.advance_epoch(epoch(3), tape(1000)).unwrap(); // Rewards when both are active
        let r3 = p.get_current_rate();

        // Alice requests at E3 → E5
        let activation_rate_e2 = r2;
        p.request_withdraw(&mut alice, epoch(3), activation_rate_e2).unwrap();

        // Bob requests at E4 → E6
        p.advance_epoch(epoch(4), tape(1000)).unwrap();
        let r4 = p.get_current_rate();

        let activation_rate_e3 = r3;
        p.request_withdraw(&mut bob, epoch(4), activation_rate_e3).unwrap();

        // Walk to E5 and let Alice claim
        p.advance_epoch(epoch(5), tape(0)).unwrap();
        let r5 = p.get_current_rate();

        let alice_shares = activation_rate_e2.convert_to_other_amount(alice.amount.into());
        let ra_owed = tape(r4.convert_to_tape_amount(alice_shares).saturating_sub(alice.amount.into()));
        let ra = p.unstake_from_pool(&mut alice, epoch(5), ra_owed).unwrap();

        // Walk to E6 and let Bob claim
        p.advance_epoch(epoch(6), tape(0)).unwrap();
        let bob_shares = activation_rate_e3.convert_to_other_amount(bob.amount.into());
        let rb_owed = tape(r5.convert_to_tape_amount(bob_shares).saturating_sub(bob.amount.into()));
        let rb = p.unstake_from_pool(&mut bob, epoch(6), rb_owed).unwrap();

        // Basic sanity: both > 0, reflect different active windows
        assert!(ra > TAPE(0));
        assert!(rb > TAPE(0));
    }

    #[test]
    fn claim_commission_full() {
        let mut p = TestPool::new(BasisPoints(1000));
        p.commission = TAPE(1_234);

        let claimed = p.claim_commission().expect("claim commission");

        assert_eq!(claimed, TAPE(1_234));
        assert_eq!(p.commission, TAPE(0));
    }

    #[test]
    fn claim_commission_empty_err() {
        let mut p = TestPool::new(BasisPoints(1000));
        let err = p.claim_commission().unwrap_err();

        assert!(matches!(err, PoolError::ZeroCommission));
    }

    #[test]
    fn stake_immediate_activation() {
        let mut p = TestPool::new(BasisPoints(0));

        // Immediate activation is only valid at the bootstrap epoch.
        let s = p.stake_with_pool_at(epoch(0), epoch(0), tape(1000)).unwrap();

        assert_eq!(s.activation_epoch, epoch(0));

        // Pool should have the stake and shares applied immediately
        assert_eq!(p.stake, tape(1000), "pool.stake should be updated immediately");
        assert!(!p.shares.is_zero(), "pool.shares should be updated immediately");

        // Immediate activation skips scheduling
        assert_eq!(p.schedule.stake_sum(epoch(0)), tape(0));
    }

    #[test]
    fn stake_delayed_activation() {
        let mut p = TestPool::new(BasisPoints(0));

        // Stake at current epoch (E5) with activation at E7 (delayed)
        let s = p.stake_with_pool_at(epoch(5), epoch(7), tape(1000)).unwrap();

        assert_eq!(s.activation_epoch, epoch(7));

        // Pool should NOT have stake applied yet (will be applied at E7)
        assert_eq!(p.stake, tape(0), "pool.stake should still be zero");
        assert!(p.shares.is_zero(), "pool.shares should still be zero");

        // Schedule should have the stake for future activation
        assert_eq!(p.schedule.stake_sum(epoch(7)), tape(1000));
    }

    #[test]
    fn boundary_dust_regression() {
        // pre-rewards pool value 1502 mod 1500: a 500-share withdrawal
        // settles to exactly 0 owed at the snapshot rate. Under the old
        // post-mutation rate, the same shares would have been overpaid by 1.
        let mut p = TestPool::new(BasisPoints(0));

        p.schedule.stake(epoch(0), tape(1500)).unwrap();
        p.advance_epoch(epoch(0), tape(0)).unwrap();

        p.advance_epoch(epoch(1), tape(2)).unwrap();
        assert_eq!(p.stake, tape(1502));
        assert_eq!(p.shares, shares(1500));

        p.schedule.unstake(epoch(2), shares(500)).unwrap();

        let snapshot = p.get_current_rate();
        assert_eq!(snapshot, ExchangeRate { tape: 1502, other: 1500 });

        p.advance_epoch(epoch(2), tape(0)).unwrap();

        // Reductions burned 500 shares at the snapshot rate
        // -floor(500 * 1502 / 1500) = -500 stake
        assert_eq!(p.stake, tape(1002));
        assert_eq!(p.shares, shares(1000));

        let tokens_at_snapshot: Coin<TAPE> =
            snapshot.convert_to_tape_amount(500u64).into();
        let owed = tokens_at_snapshot.saturating_sub(tape(500));
        assert_eq!(owed, tape(0), "withdrawer must settle at snapshot rate");

        // The buggy path would have used the post-mutation rate (1002/1000),
        // giving floor(500 * 1002 / 1000) - 500 = 1 flux of overpay.
        let post_rate = p.get_current_rate();
        let buggy: Coin<TAPE> = post_rate.convert_to_tape_amount(500u64).into();
        assert_eq!(buggy.saturating_sub(tape(500)), tape(1));
    }

    #[test]
    fn gap_settles_at_single_span_rate() {
        // Node misses several epochs, then advances once. All withdrawals
        // scheduled in the gap settle at the same closing-span rate.
        let mut p = TestPool::new(BasisPoints(0));

        p.schedule.stake(epoch(0), tape(1000)).unwrap();
        p.advance_epoch(epoch(0), tape(0)).unwrap();
        p.advance_epoch(epoch(1), tape(50)).unwrap();
        assert_eq!(p.stake, tape(1050));

        // Two withdrawals scheduled in the gap
        p.schedule.unstake(epoch(3), shares(100)).unwrap();
        p.schedule.unstake(epoch(4), shares(200)).unwrap();

        let span_rate = p.get_current_rate();
        assert_eq!(span_rate, ExchangeRate { tape: 1050, other: 1000 });

        // Skip epochs 2-4, advance only at epoch 5 with new rewards
        p.advance_epoch(epoch(5), tape(7)).unwrap();

        // Aggregate reduction: floor(300 * 1050/1000) = 315 stake.
        // Then 7 rewards land on remaining 700 shares.
        assert_eq!(p.stake, tape(1050 - 315 + 7));
        assert_eq!(p.shares, shares(700));

        // Each withdrawer's payout uses the same span rate
        let tokens_100: Coin<TAPE> = span_rate.convert_to_tape_amount(100u64).into();
        let tokens_200: Coin<TAPE> = span_rate.convert_to_tape_amount(200u64).into();
        assert_eq!(tokens_100, tape(105));
        assert_eq!(tokens_200, tape(210));
    }

    #[test]
    fn aggregate_withdrawal_dust_stays_in_pool() {
        // Two withdrawers exit at the same epoch with 1 share each at rate 3/2.
        // Aggregate floor removes 3 stake; sum of individual floors at unstake
        // time is 1 + 1 = 2. The 1-flux difference is retained in the pool's
        // accounting (rate stays at 3/2) and the underlying token sits in the
        // archive, unclaimable. Lock the direction so it can never flip to an
        // over-payment.
        let mut p = TestPool::new(BasisPoints(0));

        p.schedule.stake(epoch(0), tape(200)).unwrap();
        p.advance_epoch(epoch(0), tape(0)).unwrap();
        p.advance_epoch(epoch(1), tape(100)).unwrap();
        assert_eq!(p.get_current_rate(), ExchangeRate { tape: 300, other: 200 });

        p.schedule.unstake(epoch(2), shares(1)).unwrap();
        p.schedule.unstake(epoch(2), shares(1)).unwrap();

        let snapshot = p.get_current_rate();
        p.advance_epoch(epoch(2), tape(0)).unwrap();

        // Aggregate: floor(2 * 300 / 200) = 3 stake removed
        assert_eq!(p.stake, tape(297));
        assert_eq!(p.shares, shares(198));
        // Rate is preserved: dust does not shift the price for remaining stakers
        assert_eq!(p.get_current_rate(), ExchangeRate { tape: 297, other: 198 });

        // Per-user payout at snapshot rate: floor(1 * 3/2) = 1 each
        let per_user_tokens: Coin<TAPE> =
            snapshot.convert_to_tape_amount(1u64).into();
        assert_eq!(per_user_tokens, tape(1));

        // Sum of individuals (2) is strictly less than the aggregate (3),
        // confirming dust direction is toward the pool, never the withdrawer.
    }

    #[test]
    fn activator_at_boundary_earns_rewards() {
        // E+ specific: an activator whose shares mint at the same epoch as a
        // reward distribution shares in that epoch's rewards.
        let mut p = TestPool::new(BasisPoints(0));

        p.schedule.stake(epoch(0), tape(1000)).unwrap();
        p.advance_epoch(epoch(0), tape(0)).unwrap();

        // Bob activates at epoch 2 with 100 TAPE
        p.schedule.stake(epoch(2), tape(100)).unwrap();

        // Epoch 2 advance with 100 TAPE rewards
        p.advance_epoch(epoch(2), tape(100)).unwrap();

        // Additions mint at snapshot (1.0): +100 shares.
        // Rewards distribute over post-mutation set (1100 shares total).
        assert_eq!(p.stake, tape(1200));
        assert_eq!(p.shares, shares(1100));

        let bob_value: Coin<TAPE> = p.get_current_rate()
            .convert_to_tape_amount(100u64)
            .into();
        assert_eq!(bob_value, tape(109));
    }
}