hopper-native 0.4.4

Low-level Solana backend for Hopper with zero-copy account access, syscalls, checked CPI infrastructure, PDA helpers, and entrypoint glue. no_std and no_alloc.
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
//! Sysvar access via direct syscalls.
//!
//! Provides zero-alloc, zero-deserialization access to Solana sysvars
//! by reading them directly into stack buffers via syscalls, including the
//! epoch schedule sysvar.

use crate::address::Address;
use crate::error::ProgramError;

// ── Clock ────────────────────────────────────────────────────────────

/// Clock sysvar data, read directly from the runtime.
#[repr(C)]
#[derive(Clone, Copy, Debug, Default)]
pub struct Clock {
    pub slot: u64,
    pub epoch_start_timestamp: i64,
    pub epoch: u64,
    pub leader_schedule_epoch: u64,
    pub unix_timestamp: i64,
}

/// Read the Clock sysvar.
#[inline]
pub fn get_clock() -> Result<Clock, ProgramError> {
    #[allow(unused_mut)]
    let mut clock = Clock::default();

    #[cfg(target_os = "solana")]
    {
        let rc =
            // SAFETY: This block is part of Hopper's reviewed zero-copy/backend boundary; surrounding checks and caller contracts uphold the required raw-pointer, layout, and aliasing invariants.
            unsafe { crate::syscalls::sol_get_clock_sysvar(&mut clock as *mut Clock as *mut u8) };
        if rc != 0 {
            return Err(ProgramError::UnsupportedSysvar);
        }
    }

    Ok(clock)
}

impl Clock {
    /// Read the Clock sysvar.
    ///
    /// Method-style alias for [`get_clock`], matching the `Sysvar::get()`
    /// ergonomics other Solana frameworks expose (`Clock::get()`).
    #[inline]
    pub fn get() -> Result<Self, ProgramError> {
        get_clock()
    }
}

// ── Rent ─────────────────────────────────────────────────────────────

/// Rent sysvar data.
#[repr(C)]
#[derive(Clone, Copy, Debug, Default)]
pub struct Rent {
    pub lamports_per_byte_year: u64,
    pub exemption_threshold: f64,
    pub burn_percent: u8,
}

/// Lamports charged per byte of account storage per year.
///
/// This is the launch-era value baked into Solana's original rent config. It
/// is a historical snapshot of a runtime-owned parameter; Mainnet now carries
/// the effective per-byte rate directly in the live [`Rent`] sysvar.
/// Reaping-relevant decisions must read that sysvar (see
/// [`Rent::minimum_balance`]), not this constant.
pub const LAMPORTS_PER_BYTE_YEAR: u64 = 3_480;

/// Years of rent an account must prepay to be rent-exempt.
///
/// Launch-era snapshot of the runtime's `exemption_threshold`. SIMD-0194
/// deprecated the field and Mainnet now stores `1.0`, while the effective
/// per-byte rate carries the complete price. The field remains in the wire
/// layout for compatibility.
pub const EXEMPTION_THRESHOLD_YEARS: u64 = 2;

/// Fixed per-account storage overhead charged by the cluster.
pub const ACCOUNT_STORAGE_OVERHEAD: u64 = 128;

/// Minimum balance for rent exemption **assuming the launch-era rent
/// constants** ([`LAMPORTS_PER_BYTE_YEAR`], [`EXEMPTION_THRESHOLD_YEARS`],
/// [`ACCOUNT_STORAGE_OVERHEAD`]).
///
/// This is the fast, allocation-free, syscall-free path: pure `const`
/// integer arithmetic over hardcoded constants. It is exact **for a cluster
/// running that legacy config** and byte-matches [`Rent::minimum_balance`]
/// when the live sysvar carries those same constants.
///
/// # SAFETY-CRITICAL caveat, do NOT gate reaping on this
///
/// Because the constants are hardcoded, this function cannot see a rent
/// *reprice*. It can overcharge after a reduction or under-fund after a later
/// increase. Any code path that decides whether an account is safe from
/// reaping, topping an account up to exemption, or gating a resize on it,
/// must therefore use the live value.
///
/// For those paths read the live [`Rent`] sysvar and call
/// [`Rent::minimum_balance`] (see [`crate::batch::require_rent_exempt_with`]
/// and [`crate::batch::realloc_checked_with`]). Keep this const form only
/// where a fixed legacy snapshot is explicitly intended.
#[inline]
pub const fn rent_exempt_minimum(data_len: usize) -> u64 {
    (data_len as u64 + ACCOUNT_STORAGE_OVERHEAD)
        * LAMPORTS_PER_BYTE_YEAR
        * EXEMPTION_THRESHOLD_YEARS
}

/// Read the Rent sysvar.
#[inline]
pub fn get_rent() -> Result<Rent, ProgramError> {
    #[allow(unused_mut)]
    let mut rent = Rent::default();

    #[cfg(target_os = "solana")]
    {
        // SAFETY: This block is part of Hopper's reviewed zero-copy/backend boundary; surrounding checks and caller contracts uphold the required raw-pointer, layout, and aliasing invariants.
        let rc = unsafe { crate::syscalls::sol_get_rent_sysvar(&mut rent as *mut Rent as *mut u8) };
        if rc != 0 {
            return Err(ProgramError::UnsupportedSysvar);
        }
    }

    Ok(rent)
}

impl Rent {
    /// Read the Rent sysvar.
    ///
    /// Method-style alias for [`get_rent`], matching the `Sysvar::get()`
    /// ergonomics other Solana frameworks expose (`Rent::get()`).
    #[inline]
    pub fn get() -> Result<Self, ProgramError> {
        get_rent()
    }

    /// Minimum lamports for rent exemption at `data_len`, computed from the
    /// **live sysvar** values, the correct source for reaping-relevant
    /// decisions after a rent reprice.
    ///
    /// This follows Solana's own `solana_rent::Rent::minimum_balance` for the
    /// two thresholds any cluster has stored, with no floating point at all:
    ///
    /// ```text
    /// integer_part = (ACCOUNT_STORAGE_OVERHEAD + data_len) * rate
    /// threshold 1.0 => integer_part
    /// threshold 2.0 => integer_part * 2
    /// otherwise     => integer_part * ceil(threshold)   (never below Solana's
    ///                  `(integer_part as f64 * threshold) as u64`)
    /// ```
    ///
    /// SIMD-0194 made `1.0` the live wire marker and moved the full price into
    /// the rate field; `2.0` is the launch-era value. Both are matched by bit
    /// pattern (see [`scale_by_exemption_threshold`]), so a program that reads
    /// the sysvar links no soft-float code. A threshold no cluster has ever
    /// used rounds up to whole years, which can only overfund.
    ///
    /// The integer product uses saturating ops purely as an overflow guard;
    /// for every loader-permitted `data_len` (`<= 10_485_760`) and realistic
    /// `lamports_per_byte_year` it never saturates, so the byte-match with the
    /// runtime is exact (proven in the Kani harnesses below).
    #[inline]
    pub fn minimum_balance(&self, data_len: usize) -> u64 {
        // The same product Solana's `Rent::minimum_balance` computes, which
        // does not saturate either: the loader caps `data_len` at 10 MiB, so
        // the byte term is below 2^24 and the product below 2^64 for any
        // rate under 2^40 lamports per byte-year. `saturating_mul` here
        // linked and called the 128-bit `__multi3` helper (344 bytes, about
        // 50 CU) on every `init` (measured 2026-09-21).
        let bytes = data_len as u64;
        let integer_part = ACCOUNT_STORAGE_OVERHEAD
            .saturating_add(bytes)
            .wrapping_mul(self.lamports_per_byte_year);
        scale_by_exemption_threshold(integer_part, self.exemption_threshold.to_bits())
    }
}

/// `a * b`, saturating at `u64::MAX`, without the 128-bit multiply helper.
///
/// `u64::saturating_mul` and `checked_mul` lower to `umul.with.overflow`,
/// which SBF has no instruction for, so LLVM links `__multi3` (344 bytes)
/// and calls it (about 50 CU); the `a > u64::MAX / b` and `(a * b) / b != a`
/// guards are recognized as the same idiom and get the same helper.
/// Splitting both operands into 32-bit halves decides overflow with 64-bit
/// arithmetic only: the product exceeds 64 bits exactly when both high
/// halves are nonzero, when the cross term reaches 2^32, or when the final
/// add carries.
#[inline(always)]
pub const fn saturating_mul_u64(a: u64, b: u64) -> u64 {
    let (ah, al) = (a >> 32, a & 0xFFFF_FFFF);
    let (bh, bl) = (b >> 32, b & 0xFFFF_FFFF);
    if ah != 0 && bh != 0 {
        return u64::MAX;
    }
    // At most one high half is nonzero, so each term is a 32 x 32 product
    // and one addend is zero: exact in 64 bits.
    let cross = ah * bl + al * bh;
    if cross >> 32 != 0 {
        return u64::MAX;
    }
    match (cross << 32).checked_add(al * bl) {
        Some(product) => product,
        None => u64::MAX,
    }
}

/// Bit pattern of `1.0f64`, the SIMD-0194 live threshold marker.
const THRESHOLD_ONE_BITS: u64 = 0x3FF0_0000_0000_0000;
/// Bit pattern of `2.0f64`, the launch-era threshold.
const THRESHOLD_TWO_BITS: u64 = 0x4000_0000_0000_0000;

/// Apply the rent `exemption_threshold` (given as its IEEE-754 bit pattern)
/// to an integer lamport amount **without any floating-point instruction**.
///
/// sBPF has no FPU: every `f64` compare or multiply lowers to a soft-float
/// library call, and the launch-era formula's `(x as f64 * t) as u64`
/// fallback dragged `__muldf3`, `__floatundidf`, and `__fixunsdfdi` into
/// every program that read the Rent sysvar (measured 2026-09-21 on the
/// framework-comparison counter: 2,528 bytes of `.text` for a path no
/// cluster has ever taken). The two thresholds that have existed are
/// matched by bit pattern and are exact: `1.0`, the SIMD-0194 wire marker
/// every public cluster stores today, and the launch-era `2.0`. Any other
/// finite positive threshold is rounded **up** to a whole number of years
/// with integer arithmetic, which can only overfund, never underfund, so a
/// rent-exemption decision made through it stays safe. Saturates at
/// `u64::MAX` (an infinite threshold saturates too); a zero, negative, or
/// NaN threshold yields `0`, the same as the cast.
#[inline]
pub fn scale_by_exemption_threshold(integer_part: u64, threshold_bits: u64) -> u64 {
    if threshold_bits == THRESHOLD_ONE_BITS {
        return integer_part;
    }
    if threshold_bits == THRESHOLD_TWO_BITS {
        return integer_part.saturating_mul(2);
    }
    saturating_mul_u64(integer_part, ceil_years(threshold_bits))
}

/// Ceiling of a double (given as bits) as a `u64`, saturating: the whole
/// number of years a non-standard threshold rounds up to. Zero, negative,
/// and NaN give `0`; anything in `(0, 1]` gives `1`; infinity saturates.
#[inline]
fn ceil_years(bits: u64) -> u64 {
    if bits >> 63 == 1 {
        return 0;
    }
    let exponent = ((bits >> 52) & 0x7FF) as i32;
    let mantissa = bits & ((1u64 << 52) - 1);
    if exponent == 0x7FF {
        return if mantissa == 0 { u64::MAX } else { 0 };
    }
    if exponent == 0 {
        // Zero, or a subnormal that still rounds up to one year.
        return if mantissa == 0 { 0 } else { 1 };
    }
    // value = 1.mantissa * 2^(exponent - 1023)
    let e = exponent - 1023;
    if e < 0 {
        return 1;
    }
    if e >= 64 {
        return u64::MAX;
    }
    let significand = (1u64 << 52) | mantissa;
    if e >= 52 {
        return significand << (e - 52);
    }
    let shift = (52 - e) as u32;
    let whole = significand >> shift;
    let fraction = significand & ((1u64 << shift) - 1);
    if fraction == 0 {
        whole
    } else {
        whole + 1
    }
}

// ── Epoch Schedule ───────────────────────────────────────────────────

/// Epoch schedule sysvar data.
///
/// Nobody wraps this at the native level. Useful for programs that
/// need to reason about epoch boundaries (staking, vesting, time locks).
#[repr(C)]
#[derive(Clone, Copy, Debug, Default)]
pub struct EpochSchedule {
    pub slots_per_epoch: u64,
    pub leader_schedule_slot_offset: u64,
    pub warmup: bool,
    pub first_normal_epoch: u64,
    pub first_normal_slot: u64,
}

// ABI lock: `sol_get_epoch_schedule_sysvar` memcpy's the runtime's
// `#[repr(C)]` `EpochSchedule` into this buffer. The canonical Agave
// definition (solana-sdk `epoch-schedule`) is `#[repr(C)]` with field
// order `slots_per_epoch, leader_schedule_slot_offset, warmup,
// first_normal_epoch, first_normal_slot`. The `bool` sits between two
// u64 fields, so the layout depends on `repr(C)` padding, any drift in
// field order or repr here silently misreads every field after `warmup`.
// These asserts fail the build if that ever happens.
const _: () = {
    assert!(core::mem::size_of::<EpochSchedule>() == 40);
    assert!(core::mem::align_of::<EpochSchedule>() == 8);
    assert!(core::mem::offset_of!(EpochSchedule, slots_per_epoch) == 0);
    assert!(core::mem::offset_of!(EpochSchedule, leader_schedule_slot_offset) == 8);
    assert!(core::mem::offset_of!(EpochSchedule, warmup) == 16);
    assert!(core::mem::offset_of!(EpochSchedule, first_normal_epoch) == 24);
    assert!(core::mem::offset_of!(EpochSchedule, first_normal_slot) == 32);
};

// The Clock sysvar is also memcpy'd from a `#[repr(C)]` runtime struct.
const _: () = {
    assert!(core::mem::size_of::<Clock>() == 40);
    assert!(core::mem::offset_of!(Clock, slot) == 0);
    assert!(core::mem::offset_of!(Clock, epoch_start_timestamp) == 8);
    assert!(core::mem::offset_of!(Clock, epoch) == 16);
    assert!(core::mem::offset_of!(Clock, leader_schedule_epoch) == 24);
    assert!(core::mem::offset_of!(Clock, unix_timestamp) == 32);
};

/// Read the EpochSchedule sysvar.
#[inline]
pub fn get_epoch_schedule() -> Result<EpochSchedule, ProgramError> {
    #[allow(unused_mut)]
    let mut schedule = EpochSchedule::default();

    #[cfg(target_os = "solana")]
    {
        // SAFETY: This block is part of Hopper's reviewed zero-copy/backend boundary; surrounding checks and caller contracts uphold the required raw-pointer, layout, and aliasing invariants.
        let rc = unsafe {
            crate::syscalls::sol_get_epoch_schedule_sysvar(
                &mut schedule as *mut EpochSchedule as *mut u8,
            )
        };
        if rc != 0 {
            return Err(ProgramError::UnsupportedSysvar);
        }
    }

    Ok(schedule)
}

impl EpochSchedule {
    /// Get the epoch for a given slot.
    #[inline]
    pub fn get_epoch(&self, slot: u64) -> u64 {
        if slot < self.first_normal_slot {
            // During warmup, epoch length doubles each epoch.
            // Initial epoch has 32 slots (MINIMUM_SLOTS_PER_EPOCH).
            if slot == 0 {
                return 0;
            }
            // log2(slot / 32) + 1, clamped.
            let mut epoch_len: u64 = 32; // MINIMUM_SLOTS_PER_EPOCH
            let mut epoch: u64 = 0;
            let mut slot_remaining = slot;
            while slot_remaining >= epoch_len {
                slot_remaining -= epoch_len;
                epoch += 1;
                epoch_len = epoch_len.saturating_mul(2);
            }
            epoch
        } else {
            let normal_slot_index = slot - self.first_normal_slot;
            self.first_normal_epoch + normal_slot_index / self.slots_per_epoch
        }
    }

    /// Get the first slot in the given epoch.
    #[inline]
    pub fn get_first_slot_in_epoch(&self, epoch: u64) -> u64 {
        if epoch <= self.first_normal_epoch {
            // Warmup: each epoch doubles in length starting from 32.
            if epoch == 0 {
                return 0;
            }
            // First slot = sum of all previous epoch lengths.
            // = 32 * (2^epoch - 1)
            let shift = epoch.min(63);
            32_u64.saturating_mul((1_u64 << shift).saturating_sub(1))
        } else {
            let normal_epoch_index = epoch - self.first_normal_epoch;
            self.first_normal_slot + normal_epoch_index * self.slots_per_epoch
        }
    }
}

// ── Well-known sysvar addresses ──────────────────────────────────────

/// Clock sysvar address.
pub const CLOCK_ID: Address = crate::address!("SysvarC1ock11111111111111111111111111111111");

/// Rent sysvar address.
pub const RENT_ID: Address = crate::address!("SysvarRent111111111111111111111111111111111");

/// Epoch schedule sysvar address.
pub const EPOCH_SCHEDULE_ID: Address =
    crate::address!("SysvarEpochSchedu1e111111111111111111111111");

/// SlotHashes sysvar address.
pub const SLOT_HASHES_ID: Address = crate::address!("SysvarS1otHashes111111111111111111111111111");

/// StakeHistory sysvar address.
pub const STAKE_HISTORY_ID: Address =
    crate::address!("SysvarStakeHistory1111111111111111111111111");

/// Instructions sysvar address (for instruction introspection).
pub const INSTRUCTIONS_ID: Address = crate::address!("Sysvar1nstructions1111111111111111111111111");

/// EpochRewards sysvar address (SIMD-0118).
pub const EPOCH_REWARDS_ID: Address =
    crate::address!("SysvarEpochRewards1111111111111111111111111");

// ── Generalized sysvar access (sol_get_sysvar) ──────────────────────

/// Copy `dst.len()` bytes starting at `offset` from the sysvar identified
/// by `sysvar_id` into `dst`.
///
/// This wraps the modern `sol_get_sysvar` syscall, the only zero-copy way
/// to read large sysvars (SlotHashes, StakeHistory) without passing them
/// as instruction accounts. Returns `Err(UnsupportedSysvar)` on syscall
/// failure (e.g. reading past the sysvar's length).
#[inline]
pub fn get_sysvar_into(
    sysvar_id: &Address,
    offset: u64,
    dst: &mut [u8],
) -> Result<(), ProgramError> {
    #[cfg(target_os = "solana")]
    {
        // SAFETY: `sysvar_id` is a 32-byte address; `dst` is valid for its
        // own length; the syscall copies exactly `dst.len()` bytes.
        let rc = unsafe {
            crate::syscalls::sol_get_sysvar(
                sysvar_id.as_array().as_ptr(),
                dst.as_mut_ptr(),
                offset,
                dst.len() as u64,
            )
        };
        if rc != 0 {
            return Err(ProgramError::UnsupportedSysvar);
        }
    }
    #[cfg(not(target_os = "solana"))]
    {
        let _ = (sysvar_id, offset, dst);
    }
    Ok(())
}

// ── Epoch stake (sol_get_epoch_stake, SIMD-0133) ────────────────────

/// Get the current-epoch activated stake of the vote account at `vote`.
#[inline]
pub fn get_epoch_stake(vote: &Address) -> u64 {
    #[cfg(target_os = "solana")]
    {
        // SAFETY: `vote` is a 32-byte address pointer the syscall reads.
        unsafe { crate::syscalls::sol_get_epoch_stake(vote.as_array().as_ptr()) }
    }
    #[cfg(not(target_os = "solana"))]
    {
        let _ = vote;
        0
    }
}

/// Get the cluster-wide total activated stake for the current epoch.
#[inline]
pub fn get_total_epoch_stake() -> u64 {
    #[cfg(target_os = "solana")]
    {
        // SAFETY: a null `vote_address` is the documented request for the
        // cluster total (SIMD-0133).
        unsafe { crate::syscalls::sol_get_epoch_stake(core::ptr::null()) }
    }
    #[cfg(not(target_os = "solana"))]
    {
        0
    }
}

// ── LastRestartSlot (SIMD-0047) ─────────────────────────────────────

/// LastRestartSlot sysvar address.
pub const LAST_RESTART_SLOT_ID: Address =
    crate::address!("SysvarLastRestartS1ot1111111111111111111111");

/// Read the slot of the last cluster restart (hard fork), or `0` if the
/// cluster has never been restarted.
///
/// This wraps the dedicated `sol_get_last_restart_slot` syscall
/// (SIMD-0047). Programs that must reason about whether state predates a
/// restart (oracle freshness, liveness windows) read it here instead of
/// passing the sysvar as an account.
#[inline]
pub fn get_last_restart_slot() -> Result<u64, ProgramError> {
    #[allow(unused_mut)]
    let mut slot: u64 = 0;
    #[cfg(target_os = "solana")]
    {
        // SAFETY: the syscall writes a single `u64` into the 8-byte buffer
        // `slot` points at; `slot` is a live stack local for the call.
        let rc =
            unsafe { crate::syscalls::sol_get_last_restart_slot(&mut slot as *mut u64 as *mut u8) };
        if rc != 0 {
            return Err(ProgramError::UnsupportedSysvar);
        }
    }
    Ok(slot)
}

// ── SlotHashes ──────────────────────────────────────────────────────

/// One `(slot, hash)` entry from the SlotHashes sysvar.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SlotHash {
    pub slot: u64,
    pub hash: [u8; 32],
}

/// Read the most recent `(slot, hash)` from the SlotHashes sysvar.
///
/// SlotHashes is a length-prefixed list ordered most-recent-first:
/// `u64 count` then `count` entries of `slot(u64) + hash([u8;32])`. This
/// reads just the count and the first entry (48 bytes total) via
/// `sol_get_sysvar`, avoiding the cost of materializing the full 16 KiB
/// sysvar. Returns `Ok(None)` when the list is empty.
#[inline]
pub fn slot_hashes_latest() -> Result<Option<SlotHash>, ProgramError> {
    let mut count_buf = [0u8; 8];
    get_sysvar_into(&SLOT_HASHES_ID, 0, &mut count_buf)?;
    let count = u64::from_le_bytes(count_buf);
    if count == 0 {
        return Ok(None);
    }
    let mut entry = [0u8; 40];
    get_sysvar_into(&SLOT_HASHES_ID, 8, &mut entry)?;
    let slot = u64::from_le_bytes([
        entry[0], entry[1], entry[2], entry[3], entry[4], entry[5], entry[6], entry[7],
    ]);
    let mut hash = [0u8; 32];
    hash.copy_from_slice(&entry[8..40]);
    Ok(Some(SlotHash { slot, hash }))
}

// ── StakeHistory ────────────────────────────────────────────────────

/// One epoch's stake-history entry.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct StakeHistoryEntry {
    pub epoch: u64,
    pub effective: u64,
    pub activating: u64,
    pub deactivating: u64,
}

/// Read the most recent stake-history entry.
///
/// StakeHistory is a length-prefixed list ordered most-recent-first:
/// `u64 count` then entries of `epoch(u64) + effective(u64) +
/// activating(u64) + deactivating(u64)` (32 bytes each). Returns
/// `Ok(None)` when the history is empty.
#[inline]
pub fn stake_history_latest() -> Result<Option<StakeHistoryEntry>, ProgramError> {
    let mut count_buf = [0u8; 8];
    get_sysvar_into(&STAKE_HISTORY_ID, 0, &mut count_buf)?;
    let count = u64::from_le_bytes(count_buf);
    if count == 0 {
        return Ok(None);
    }
    let mut entry = [0u8; 32];
    get_sysvar_into(&STAKE_HISTORY_ID, 8, &mut entry)?;
    let rd = |o: usize| {
        u64::from_le_bytes([
            entry[o],
            entry[o + 1],
            entry[o + 2],
            entry[o + 3],
            entry[o + 4],
            entry[o + 5],
            entry[o + 6],
            entry[o + 7],
        ])
    };
    Ok(Some(StakeHistoryEntry {
        epoch: rd(0),
        effective: rd(8),
        activating: rd(16),
        deactivating: rd(24),
    }))
}

// ── EpochRewards (SIMD-0118) ────────────────────────────────────────

/// EpochRewards sysvar data (SIMD-0118).
///
/// Surfaces the partitioned-rewards distribution state for the current
/// epoch: how many lamports are being paid out, how far distribution has
/// progressed, and whether the rewards period is still active. Staking and
/// airdrop programs read it to gate behaviour during the distribution
/// window.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct EpochRewards {
    /// First block height at which rewards distribution begins this epoch.
    pub distribution_starting_block_height: u64,
    /// Number of partitions the distribution is split across.
    pub num_partitions: u64,
    /// Blockhash of the parent of the epoch's first block.
    pub parent_blockhash: [u8; 32],
    /// Total rewards points calculated for the epoch.
    pub total_points: u128,
    /// Total rewards (lamports) calculated for the epoch.
    pub total_rewards: u64,
    /// Rewards (lamports) distributed so far this epoch.
    pub distributed_rewards: u64,
    /// Whether the rewards period (calculation + distribution) is active.
    pub active: bool,
}

/// Wire size of the bincode-serialized EpochRewards sysvar account data.
///
/// `8 + 8 + 32 + 16 + 8 + 8 + 1`. Unlike Clock/Rent/EpochSchedule (which
/// have dedicated syscalls that memcpy a `#[repr(C)]` struct), EpochRewards
/// is only reachable through `sol_get_sysvar`, which returns the sysvar
/// *account data* in bincode form: a flat little-endian field concatenation
/// with no padding. The decoder below mirrors that image byte-for-byte
/// rather than casting a `#[repr(C)]` struct (whose `u128` would force
/// 16-byte alignment and 96-byte size, reading past the 81-byte image).
const EPOCH_REWARDS_LEN: usize = 81;

#[inline]
fn decode_epoch_rewards(buf: &[u8; EPOCH_REWARDS_LEN]) -> EpochRewards {
    let rd8 = |o: usize| {
        u64::from_le_bytes([
            buf[o],
            buf[o + 1],
            buf[o + 2],
            buf[o + 3],
            buf[o + 4],
            buf[o + 5],
            buf[o + 6],
            buf[o + 7],
        ])
    };
    let mut parent_blockhash = [0u8; 32];
    parent_blockhash.copy_from_slice(&buf[16..48]);
    let mut points = [0u8; 16];
    points.copy_from_slice(&buf[48..64]);
    EpochRewards {
        distribution_starting_block_height: rd8(0),
        num_partitions: rd8(8),
        parent_blockhash,
        total_points: u128::from_le_bytes(points),
        total_rewards: rd8(64),
        distributed_rewards: rd8(72),
        active: buf[80] != 0,
    }
}

/// Read the EpochRewards sysvar (SIMD-0118).
///
/// Reads the bincode account-data image via `sol_get_sysvar` and decodes
/// it without alignment assumptions. Off-chain this returns the zeroed
/// default (`active = false`). Returns `Err(UnsupportedSysvar)` if the
/// syscall fails (e.g. the sysvar is unavailable on the cluster).
#[inline]
pub fn get_epoch_rewards() -> Result<EpochRewards, ProgramError> {
    let mut buf = [0u8; EPOCH_REWARDS_LEN];
    get_sysvar_into(&EPOCH_REWARDS_ID, 0, &mut buf)?;
    Ok(decode_epoch_rewards(&buf))
}

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

    /// Reproduce the byte image the runtime memcpy's for EpochSchedule and
    /// confirm every field reads from the offset the syscall writes. This
    /// is the runtime counterpart to the compile-time offset asserts: it
    /// proves the read side, not just the struct shape.
    #[test]
    fn epoch_schedule_reads_canonical_byte_image() {
        // Devnet/mainnet default: 432_000 slots/epoch, no warmup.
        let mut buf = [0u8; 40];
        buf[0..8].copy_from_slice(&432_000u64.to_le_bytes()); // slots_per_epoch
        buf[8..16].copy_from_slice(&432_000u64.to_le_bytes()); // leader_schedule_slot_offset
        buf[16] = 0; // warmup = false
                     // bytes 17..24 are padding
        buf[24..32].copy_from_slice(&0u64.to_le_bytes()); // first_normal_epoch
        buf[32..40].copy_from_slice(&0u64.to_le_bytes()); // first_normal_slot

        // SAFETY: `EpochSchedule` is repr(C), size 40, and `buf` is 40 bytes
        // matching the canonical wire image asserted above.
        let sched: EpochSchedule = unsafe { core::ptr::read(buf.as_ptr() as *const EpochSchedule) };
        assert_eq!(sched.slots_per_epoch, 432_000);
        assert_eq!(sched.leader_schedule_slot_offset, 432_000);
        assert!(!sched.warmup);
        assert_eq!(sched.first_normal_epoch, 0);
        assert_eq!(sched.first_normal_slot, 0);
    }

    #[test]
    fn clock_reads_canonical_byte_image() {
        let mut buf = [0u8; 40];
        buf[0..8].copy_from_slice(&123u64.to_le_bytes()); // slot
        buf[8..16].copy_from_slice(&1_600_000_000i64.to_le_bytes()); // epoch_start_timestamp
        buf[16..24].copy_from_slice(&7u64.to_le_bytes()); // epoch
        buf[24..32].copy_from_slice(&8u64.to_le_bytes()); // leader_schedule_epoch
        buf[32..40].copy_from_slice(&1_600_000_500i64.to_le_bytes()); // unix_timestamp

        // SAFETY: `Clock` is repr(C), size 40, matching this 40-byte image.
        let clock: Clock = unsafe { core::ptr::read(buf.as_ptr() as *const Clock) };
        assert_eq!(clock.slot, 123);
        assert_eq!(clock.epoch_start_timestamp, 1_600_000_000);
        assert_eq!(clock.epoch, 7);
        assert_eq!(clock.leader_schedule_epoch, 8);
        assert_eq!(clock.unix_timestamp, 1_600_000_500);
    }

    /// Build the canonical bincode image for EpochRewards and confirm the
    /// decoder reads every field from the byte offset the runtime writes.
    /// This is the read-side proof for the no-dedicated-syscall sysvar.
    #[test]
    fn epoch_rewards_decodes_canonical_byte_image() {
        let mut buf = [0u8; EPOCH_REWARDS_LEN];
        buf[0..8].copy_from_slice(&100u64.to_le_bytes()); // distribution_starting_block_height
        buf[8..16].copy_from_slice(&8u64.to_le_bytes()); // num_partitions
        buf[16..48].copy_from_slice(&[7u8; 32]); // parent_blockhash
        buf[48..64].copy_from_slice(&123_456_789u128.to_le_bytes()); // total_points
        buf[64..72].copy_from_slice(&5_000_000u64.to_le_bytes()); // total_rewards
        buf[72..80].copy_from_slice(&1_250_000u64.to_le_bytes()); // distributed_rewards
        buf[80] = 1; // active = true

        let er = decode_epoch_rewards(&buf);
        assert_eq!(er.distribution_starting_block_height, 100);
        assert_eq!(er.num_partitions, 8);
        assert_eq!(er.parent_blockhash, [7u8; 32]);
        assert_eq!(er.total_points, 123_456_789);
        assert_eq!(er.total_rewards, 5_000_000);
        assert_eq!(er.distributed_rewards, 1_250_000);
        assert!(er.active);
    }

    #[test]
    fn epoch_rewards_off_chain_is_zeroed_default() {
        // Off-chain `get_sysvar_into` is a no-op, so the getter yields the
        // zeroed default with `active = false`.
        let er = get_epoch_rewards().unwrap();
        assert_eq!(er, EpochRewards::default());
        assert!(!er.active);
    }
}

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

    /// Loader bound on serialized account data (10 MiB), the largest
    /// `data_len` any rent calculation ever sees on-chain.
    const LOADER_MAX_DATA_LEN: usize = 10_485_760;

    /// Transcription of Solana's `Rent::minimum_balance_unchecked`, including
    /// the SIMD-0194 `1.0` and legacy `2.0` integer fast paths.
    fn solana_reference_minimum_balance(data_len: usize, lpby: u64, threshold: f64) -> u64 {
        let bytes = data_len as u64;
        let integer_part = (ACCOUNT_STORAGE_OVERHEAD + bytes).saturating_mul(lpby);
        if threshold == 1.0 {
            integer_part
        } else if threshold == 2.0 {
            integer_part.saturating_mul(2)
        } else {
            (integer_part as f64 * threshold) as u64
        }
    }

    fn rent_with(lpby: u64, threshold: f64) -> Rent {
        Rent {
            lamports_per_byte_year: lpby,
            exemption_threshold: threshold,
            burn_percent: 0,
        }
    }

    /// The const fast-path must not overflow or panic at the data-length
    /// extremes the loader permits (0 and 10 MiB).
    #[test]
    fn const_rent_exempt_minimum_no_overflow_at_extremes() {
        assert_eq!(
            rent_exempt_minimum(0),
            ACCOUNT_STORAGE_OVERHEAD * LAMPORTS_PER_BYTE_YEAR * EXEMPTION_THRESHOLD_YEARS
        );
        let max = rent_exempt_minimum(LOADER_MAX_DATA_LEN);
        let expected = (LOADER_MAX_DATA_LEN as u64 + ACCOUNT_STORAGE_OVERHEAD)
            * LAMPORTS_PER_BYTE_YEAR
            * EXEMPTION_THRESHOLD_YEARS;
        assert_eq!(max, expected);
        // Sanity: comfortably inside u64.
        assert!(max < u64::MAX / 2);
    }

    /// The sysvar path must not overflow or panic even with a wildly
    /// repriced `lamports_per_byte_year` at the maximum data length: the
    /// saturating integer product keeps the arithmetic safe.
    #[test]
    fn sysvar_minimum_balance_no_overflow_at_extremes() {
        // Far past any realistic rate.
        let rent = rent_with(1u64 << 40, 2.0);
        let _ = rent.minimum_balance(LOADER_MAX_DATA_LEN);
        // data_len = 0 lower extreme.
        assert_eq!(
            rent.minimum_balance(0),
            solana_reference_minimum_balance(0, 1u64 << 40, 2.0)
        );
    }

    /// The const path and sysvar path agree at the launch-era snapshot.
    #[test]
    fn const_and_sysvar_agree_at_launch_snapshot() {
        let rent = rent_with(LAMPORTS_PER_BYTE_YEAR, EXEMPTION_THRESHOLD_YEARS as f64);
        for &dl in &[
            0usize,
            1,
            127,
            128,
            1024,
            10_240,
            1_000_000,
            LOADER_MAX_DATA_LEN,
        ] {
            assert_eq!(
                rent_exempt_minimum(dl),
                rent.minimum_balance(dl),
                "const vs sysvar mismatch at data_len={dl}"
            );
        }
    }

    /// The sysvar path must byte-match Solana's runtime formula across a
    /// range of data sizes, repriced per-byte costs, and fractional
    /// thresholds, including a `lamports_per_byte_year` past f64's 53-bit
    /// exact-integer range, where the old all-f64 form could drift.
    #[test]
    fn sysvar_minimum_balance_byte_matches_solana_reference() {
        let cases: &[(usize, u64, f64)] = &[
            (0, 6_333, 1.0),
            (167_829, 6_333, 1.0),
            (0, 3_480, 2.0),
            (165, 3_480, 2.0),
            (10_240, 3_480, 2.0),
            (1_000_000, 6_960, 2.0),  // hypothetical 2x reprice
            (500_000, 3_480, 3.0),    // whole-year non-default threshold
            (10_485_760, 3_480, 2.0), // max size
            // `lpby` just past f64's 2^53 exact-integer range, the case
            // that motivates the integer product + single f64 step (an
            // all-f64 formula would lose a lamport here). `data_len` is
            // kept small so the *integer* product stays inside u64: at
            // this `lpby`, (overhead + data_len) must be < ~2044 or the
            // product overflows u64 entirely (a regime Solana itself
            // never reaches, `lpby` is a fixed cluster constant).
            (1_024, 9_007_199_254_740_993, 2.0),
        ];
        for &(dl, lpby, threshold) in cases {
            let rent = rent_with(lpby, threshold);
            assert_eq!(
                rent.minimum_balance(dl),
                solana_reference_minimum_balance(dl, lpby, threshold),
                "sysvar minimum_balance != Solana reference at dl={dl}, lpby={lpby}, threshold={threshold}"
            );
        }
    }

    /// The float-free threshold scaling: exact for the two thresholds any
    /// cluster has stored, and for every other finite positive threshold a
    /// whole-year round-up that is never below the float cast the runtime
    /// historically used.
    #[test]
    fn saturating_mul_u64_matches_the_library_operator() {
        let samples = [
            0u64,
            1,
            2,
            3,
            128,
            153,
            3_480,
            5_080,
            6_333,
            10_485_888,
            u32::MAX as u64,
            u32::MAX as u64 + 1,
            1 << 40,
            u64::MAX / 3,
            u64::MAX / 2,
            u64::MAX / 2 + 1,
            u64::MAX - 1,
            u64::MAX,
        ];
        for &a in &samples {
            for &b in &samples {
                assert_eq!(saturating_mul_u64(a, b), a.saturating_mul(b), "{a} * {b}");
            }
        }
    }

    #[test]
    fn threshold_scaling_is_float_free_and_never_underfunds() {
        fn reference(integer_part: u64, threshold: f64) -> u64 {
            (integer_part as f64 * threshold) as u64
        }
        let amounts: [u64; 8] = [
            0,
            1,
            7,
            128 * 3_480,
            890_880,
            1_740_445_440,
            1 << 40,
            1 << 52,
        ];
        let whole_thresholds: [f64; 4] = [1.0, 2.0, 3.0, 4.0];
        let fractional: [(f64, u64); 10] = [
            (0.5, 1),
            (1.5, 2),
            (2.5, 3),
            (0.25, 1),
            (0.75, 1),
            (1.1, 2),
            (1.7, 2),
            (0.3, 1),
            (2.9, 3),
            (3.33, 4),
        ];
        for &amount in &amounts {
            for &threshold in &whole_thresholds {
                assert_eq!(
                    scale_by_exemption_threshold(amount, threshold.to_bits()),
                    reference(amount, threshold),
                    "amount {amount} threshold {threshold}"
                );
            }
            for &(threshold, years) in &fractional {
                let ours = scale_by_exemption_threshold(amount, threshold.to_bits());
                assert_eq!(ours, amount.saturating_mul(years), "threshold {threshold}");
                assert!(
                    ours >= reference(amount, threshold),
                    "amount {amount} threshold {threshold}: {ours} underfunds"
                );
            }
            // Degenerate thresholds: zero, negative, and NaN yield 0 like the
            // cast; a subnormal rounds up to one year; infinity saturates.
            assert_eq!(scale_by_exemption_threshold(amount, 0.0f64.to_bits()), 0);
            assert_eq!(scale_by_exemption_threshold(amount, (-1.0f64).to_bits()), 0);
            assert_eq!(scale_by_exemption_threshold(amount, f64::NAN.to_bits()), 0);
            assert_eq!(
                scale_by_exemption_threshold(amount, f64::MIN_POSITIVE.to_bits() >> 1),
                amount
            );
            let saturated = if amount == 0 { 0 } else { u64::MAX };
            assert_eq!(
                scale_by_exemption_threshold(amount, f64::INFINITY.to_bits()),
                saturated
            );
        }
        // Huge thresholds saturate.
        let huge: f64 = (1u64 << 63) as f64;
        assert_eq!(scale_by_exemption_threshold(2, huge.to_bits()), u64::MAX);
        let astronomical: f64 = 1e300;
        assert_eq!(
            scale_by_exemption_threshold(1, astronomical.to_bits()),
            u64::MAX
        );
        let exactly_2_pow_60: f64 = (1u64 << 60) as f64;
        assert_eq!(
            scale_by_exemption_threshold(1, exactly_2_pow_60.to_bits()),
            1 << 60
        );
        assert_eq!(
            scale_by_exemption_threshold(u64::MAX, 1.0f64.to_bits()),
            u64::MAX
        );
        assert_eq!(
            scale_by_exemption_threshold(u64::MAX, 2.0f64.to_bits()),
            u64::MAX
        );
    }

    /// The correctness gap the safety work closes: after an UPWARD rent
    /// reprice the live sysvar demands strictly more than the const path,
    /// so gating reaping on the const would under-fund.
    #[test]
    fn repriced_sysvar_exceeds_const_underestimate() {
        let dl = 4_096;
        let const_min = rent_exempt_minimum(dl);
        // Cluster doubled the per-byte cost.
        let repriced = rent_with(LAMPORTS_PER_BYTE_YEAR * 2, EXEMPTION_THRESHOLD_YEARS as f64);
        let sysvar_min = repriced.minimum_balance(dl);
        assert!(
            sysvar_min > const_min,
            "expected repriced sysvar minimum ({sysvar_min}) > const minimum ({const_min})"
        );
        assert_eq!(sysvar_min, const_min * 2);
    }
}

// =====================================================================
// Kani proof harnesses for the rent arithmetic.
// =====================================================================
//
// These mirror the existing native Kani conventions (see
// `raw_input.rs::kani_proofs`): a `#[cfg(kani)]` module of `#[kani::proof]`
// harnesses over symbolic inputs bounded by the loader's limits, run by
// `cargo kani -p hopper-native`. They discharge the three safety claims the
// SAFETY-RENT work rests on:
//
//   (1) the const fast path cannot overflow for any loader-permitted
//       `data_len`;
//   (2) the sysvar path's integer product cannot overflow for any
//       loader-permitted `data_len` and any realistic (repriced)
//       `lamports_per_byte_year`, and its saturating ops never actually
//       saturate in that range (so the byte-match with the runtime is
//       exact); and
//   (3) the const and sysvar forms AGREE at the launch-era snapshot.
#[cfg(kani)]
mod kani_rent_proofs {
    use super::*;

    /// Loader bound on serialized account data (10 MiB).
    const LOADER_MAX_DATA_LEN: usize = 10_485_760;

    /// Generous upper bound on a repriced `lamports_per_byte_year`: 2^40 is
    /// ~1.1e12 and far past any realistic rent change,
    /// yet the integer product still provably cannot overflow u64.
    const MAX_LAMPORTS_PER_BYTE_YEAR: u64 = 1 << 40;

    /// The const path's integer arithmetic never overflows for any
    /// loader-permitted `data_len`, and the function returns exactly the
    /// checked value.
    #[kani::proof]
    fn const_rent_exempt_minimum_never_overflows() {
        let data_len: usize = kani::any();
        kani::assume(data_len <= LOADER_MAX_DATA_LEN);

        // Each `checked_*` doubles as the no-overflow proof for the `*`/`+`
        // in `rent_exempt_minimum`.
        let sum = (data_len as u64)
            .checked_add(ACCOUNT_STORAGE_OVERHEAD)
            .unwrap();
        let per_year = sum.checked_mul(LAMPORTS_PER_BYTE_YEAR).unwrap();
        let total = per_year.checked_mul(EXEMPTION_THRESHOLD_YEARS).unwrap();

        assert_eq!(rent_exempt_minimum(data_len), total);
    }

    /// The sysvar path's integer product never overflows for any
    /// loader-permitted `data_len` and any realistic `lamports_per_byte_year`,
    /// and its saturating ops equal the checked ops (never saturate) in that
    /// range.
    #[kani::proof]
    fn sysvar_minimum_balance_integer_part_never_overflows() {
        let data_len: usize = kani::any();
        let lpby: u64 = kani::any();
        kani::assume(data_len <= LOADER_MAX_DATA_LEN);
        kani::assume(lpby <= MAX_LAMPORTS_PER_BYTE_YEAR);

        let bytes = data_len as u64;
        let checked = ACCOUNT_STORAGE_OVERHEAD
            .checked_add(bytes)
            .and_then(|s| s.checked_mul(lpby));
        assert!(checked.is_some());

        let saturating = ACCOUNT_STORAGE_OVERHEAD
            .saturating_add(bytes)
            .saturating_mul(lpby);
        assert_eq!(saturating, checked.unwrap());
    }

    /// Const and sysvar forms agree at the launch-era snapshot.
    #[kani::proof]
    fn const_and_sysvar_agree_at_launch_snapshot() {
        let data_len: usize = kani::any();
        kani::assume(data_len <= LOADER_MAX_DATA_LEN);

        let rent = Rent {
            lamports_per_byte_year: LAMPORTS_PER_BYTE_YEAR,
            exemption_threshold: EXEMPTION_THRESHOLD_YEARS as f64,
            burn_percent: 0,
        };

        assert_eq!(
            rent_exempt_minimum(data_len),
            rent.minimum_balance(data_len)
        );
    }
}