rialo-stake-manager-interface 0.12.0

Instructions and constructors for stake management
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
// Copyright (c) Subzero Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

//! Instructions for the Stake Manager program.

use std::mem;

use rialo_s_instruction::{AccountMeta, Instruction};
use rialo_s_pubkey::Pubkey;
use serde::{Deserialize, Serialize};

/// Data structure for stake information
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone, Default)]
pub struct StakeInfo {
    /// The block's Unix timestamp (in milliseconds) when ActivateStake was called.
    /// Note: Activation takes effect at the next FreezeStakes call (epoch boundary),
    /// not immediately. A stake is "activating" while `activation_requested >= last_freeze_timestamp`
    /// and becomes "activated" when `activation_requested < last_freeze_timestamp`.
    pub activation_requested: Option<u64>,
    /// The block's Unix timestamp (in milliseconds) when DeactivateStake was called.
    /// Note: Deactivation takes effect at the next FreezeStakes call (epoch boundary),
    /// not immediately. A stake is "deactivating" while `deactivation_requested >= last_freeze_timestamp`
    /// and becomes "deactivated" when `deactivation_requested < last_freeze_timestamp`.
    pub deactivation_requested: Option<u64>,
    /// The amount of kelvins delegated to the validator.
    /// This balance becomes effective at the next epoch boundary (FreezeStakes) after `activation_requested`.
    pub delegated_balance: u64,
    /// References the ValidatorInfo account the `delegated_balance` was delegated to.
    pub validator: Option<Pubkey>,
    /// Account controlling the StakeInfo account using the StakeManager's
    /// instructions (hot wallet) for ActivateStake, DeactivateStake operations.
    pub admin_authority: Pubkey,
    /// Account required as signer for Withdraw operations (cold wallet).
    pub withdraw_authority: Pubkey,
    /// An optional account that receives the rewards if they don't compound.
    pub reward_receiver: Option<Pubkey>,
    /// Block slot at which a reward was last applied to this stake. `None`
    /// before any reward lands.
    ///
    /// Added in schema version 2. `#[serde(skip)]` so `StakeInfo`'s own
    /// bincode footprint stays the V1 wire layout (this field is never part of
    /// V1): a bare `bincode::serialize/deserialize` of `StakeInfo` is therefore
    /// byte-compatible with V1 records. The field is persisted only through the
    /// V2 envelope ([`StakeInfoV2`] via [`StakeInfoVersioned`]); reading a V1
    /// account yields `None`.
    ///
    /// Written (in the epoch-reward compounding path) but not yet read by any
    /// production consumer — it exercises the V2 migration machinery as the
    /// template's worked example. A real consumer must land (or this field be
    /// reconsidered) before `ENABLE_STAKE_INFO_V2` is activated.
    #[serde(skip)]
    pub last_reward_slot: Option<u64>,
}

/// Error type for converting a `StoredAccount` to `StakeInfo`.
#[cfg(feature = "typed-account")]
#[derive(Debug, thiserror::Error)]
pub enum StakeInfoParseError {
    /// The account is not owned by the StakeManager program.
    #[error("Account owner mismatch: expected {expected}, got {actual}")]
    InvalidOwner {
        expected: rialo_s_pubkey::Pubkey,
        actual: rialo_s_pubkey::Pubkey,
    },
    /// The account data could not be deserialized as `StakeInfo`.
    #[error("Failed to deserialize StakeInfo: {0}")]
    DeserializationFailed(#[from] bincode::Error),
}

#[cfg(feature = "typed-account")]
impl TryFrom<rialo_s_account::StoredAccount> for StakeInfo {
    type Error = StakeInfoParseError;

    /// Attempts to parse a `StoredAccount` as a `StakeInfo`.
    ///
    /// # Errors
    /// - `StakeInfoParseError::InvalidOwner` if the account is not owned by the StakeManager program.
    /// - `StakeInfoParseError::DeserializationFailed` if the account data cannot be deserialized.
    fn try_from(account: rialo_s_account::StoredAccount) -> Result<Self, Self::Error> {
        StakeInfo::try_from(&account)
    }
}

#[cfg(feature = "typed-account")]
impl TryFrom<&rialo_s_account::StoredAccount> for StakeInfo {
    type Error = StakeInfoParseError;

    /// Attempts to parse a reference to a `StoredAccount` as a `StakeInfo`.
    ///
    /// # Errors
    /// - `StakeInfoParseError::InvalidOwner` if the account is not owned by the StakeManager program.
    /// - `StakeInfoParseError::DeserializationFailed` if the account data cannot be deserialized.
    fn try_from(account: &rialo_s_account::StoredAccount) -> Result<Self, Self::Error> {
        use rialo_s_account::ReadableAccount;

        // Verify ownership
        let owner = *account.owner();
        if owner != crate::id() {
            return Err(StakeInfoParseError::InvalidOwner {
                expected: crate::id(),
                actual: owner,
            });
        }

        // Decode through the versioned envelope. The bytes are unchanged from
        // the pre-envelope format (bare bincode of the V1 layout); routing
        // through `StakeInfoVersioned` establishes the seam every reader uses.
        let versioned = StakeInfoVersioned::deserialize(account.data())?;
        Ok(StakeInfo::from(versioned))
    }
}

impl StakeInfo {
    /// Maximum serialized size of a StakeInfo account (bincode format).
    ///
    /// This assumes all `Option` fields are `Some` for sizing purposes,
    /// which is the typical case during a stake account's lifecycle.
    pub const MAX_SIZE: usize = const {
        // Check the in-memory size at compile time. The struct gained the
        // (serde-skipped) `last_reward_slot` field in V2, so the in-memory
        // size grew, but the *serialized* (V1 wire) size is unchanged.
        assert!(
            mem::size_of::<StakeInfo>() == 192,
            "StakeInfo size changed - update MAX_SIZE calculation below"
        );
        // Breakdown (bincode format — `last_reward_slot` is `#[serde(skip)]`,
        // so it does not appear in the wire footprint):
        // - 2 × `Option<u64>`: 2 × (1 + 8) = 18 bytes
        // - 1 × `u64`: 1 × 8 = 8 bytes
        // - 2 × `Option<Pubkey>`: 2 × (1 + 32) = 66 bytes
        // - 2 × `Pubkey`: 2 × 32 = 64 bytes
        // - Total: 156 bytes
        2 * (1 + mem::size_of::<u64>())
            + mem::size_of::<u64>()
            + 2 * (1 + mem::size_of::<Pubkey>())
            + 2 * mem::size_of::<Pubkey>()
    };

    /// Maximum *on-disk record* size across all schema versions, including the
    /// version tag.
    ///
    /// `MAX_SIZE` is the V1 wire size (the bare bincode of the version-skipped
    /// `StakeInfo`/[`StakeInfoV1`]); a V2 record is one tag byte plus the
    /// bincode of [`StakeInfoV2`], which adds a third `Option<u64>`
    /// (`last_reward_slot`). Use this — not `MAX_SIZE` — for buffer
    /// pre-allocation, account sizing, and indexer size guards, so a V2 record
    /// is neither truncated nor rejected.
    pub const MAX_WIRE_SIZE: usize = 1 // STAKE_INFO_V2_TAG
        + 3 * (1 + mem::size_of::<u64>()) // activation, deactivation, last_reward_slot
        + mem::size_of::<u64>() // delegated_balance
        + 2 * (1 + mem::size_of::<Pubkey>()) // validator, reward_receiver
        + 2 * mem::size_of::<Pubkey>(); // admin, withdraw
}

/// Frozen on-disk layout of a `StakeInfo` at schema version 1.
///
/// This is a snapshot of the current `StakeInfo` field layout. It exists as a
/// **distinct** type — not an alias — so that when the in-memory `StakeInfo`
/// grows a field in a future schema bump, `StakeInfoV1`'s wire layout stays
/// frozen and old accounts keep decoding. bincode is positional, so this
/// type's wire layout is unaffected by V2 fields added to `StakeInfo`
/// (asserted by `v1_wire_is_frozen_against_the_v2_field`).
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone, Default)]
pub struct StakeInfoV1 {
    /// See [`StakeInfo::activation_requested`].
    pub activation_requested: Option<u64>,
    /// See [`StakeInfo::deactivation_requested`].
    pub deactivation_requested: Option<u64>,
    /// See [`StakeInfo::delegated_balance`].
    pub delegated_balance: u64,
    /// See [`StakeInfo::validator`].
    pub validator: Option<Pubkey>,
    /// See [`StakeInfo::admin_authority`].
    pub admin_authority: Pubkey,
    /// See [`StakeInfo::withdraw_authority`].
    pub withdraw_authority: Pubkey,
    /// See [`StakeInfo::reward_receiver`].
    pub reward_receiver: Option<Pubkey>,
}

/// On-disk layout of a `StakeInfo` at schema version 2.
///
/// Identical to [`StakeInfoV1`] plus `last_reward_slot`. Written only while the
/// `ENABLE_STAKE_INFO_V2` feature is active.
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone, Default)]
pub struct StakeInfoV2 {
    /// See [`StakeInfo::activation_requested`].
    pub activation_requested: Option<u64>,
    /// See [`StakeInfo::deactivation_requested`].
    pub deactivation_requested: Option<u64>,
    /// See [`StakeInfo::delegated_balance`].
    pub delegated_balance: u64,
    /// See [`StakeInfo::validator`].
    pub validator: Option<Pubkey>,
    /// See [`StakeInfo::admin_authority`].
    pub admin_authority: Pubkey,
    /// See [`StakeInfo::withdraw_authority`].
    pub withdraw_authority: Pubkey,
    /// See [`StakeInfo::reward_receiver`].
    pub reward_receiver: Option<Pubkey>,
    /// See [`StakeInfo::last_reward_slot`]. New in V2.
    pub last_reward_slot: Option<u64>,
}

/// Versioned envelope over the on-disk `StakeInfo` layouts.
///
/// **On-disk format.** V1 is the bare bincode of [`StakeInfoV1`] with no
/// discriminant — byte-identical to the pre-envelope format, so existing
/// accounts read back unchanged. V2 is a one-byte tag ([`STAKE_INFO_V2_TAG`])
/// followed by the bincode of [`StakeInfoV2`]. The tag is disjoint from any
/// valid V1 first byte (V1 begins with an `Option` discriminant, always `0` or
/// `1`), so the reader is tolerant: it dispatches on the leading byte and
/// decodes either format. This is the writer-gated migration template — V2 is
/// only written when `ENABLE_STAKE_INFO_V2` is active.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StakeInfoVersioned {
    /// Schema version 1 — the original `StakeInfo` layout (untagged on disk).
    V1(StakeInfoV1),
    /// Schema version 2 — adds `last_reward_slot` (tagged on disk).
    V2(StakeInfoV2),
}

/// Leading byte marking a V2 on-disk record. Chosen disjoint from a V1
/// record's first byte, which is always a bincode `Option` discriminant
/// (`0` or `1`); `2` can therefore never begin a valid V1 record.
pub const STAKE_INFO_V2_TAG: u8 = 2;

// bincode is only compiled in under `typed-account`, so the on-disk
// (de)serialization seam is gated on the same feature as the `TryFrom` readers.
#[cfg(feature = "typed-account")]
impl StakeInfoVersioned {
    /// Choose the on-disk version a writer should emit: V2 when
    /// `ENABLE_STAKE_INFO_V2` is active, V1 otherwise.
    pub fn encode(stake_info: &StakeInfo, v2_active: bool) -> Self {
        if v2_active {
            StakeInfoVersioned::V2(StakeInfoV2::from(stake_info))
        } else {
            StakeInfoVersioned::V1(StakeInfoV1::from(stake_info))
        }
    }

    /// Serialize to the on-disk byte layout.
    ///
    /// V1 is the bare bincode of [`StakeInfoV1`] (byte-identical to the
    /// pre-envelope format). V2 is `STAKE_INFO_V2_TAG` followed by the bincode
    /// of [`StakeInfoV2`].
    pub fn serialize(&self) -> Result<Vec<u8>, bincode::Error> {
        match self {
            StakeInfoVersioned::V1(v1) => bincode::serialize(v1),
            StakeInfoVersioned::V2(v2) => {
                let mut out = Vec::with_capacity(StakeInfo::MAX_WIRE_SIZE);
                out.push(STAKE_INFO_V2_TAG);
                bincode::serialize_into(&mut out, v2)?;
                Ok(out)
            }
        }
    }

    /// Tolerantly deserialize either on-disk version.
    ///
    /// A leading [`STAKE_INFO_V2_TAG`] selects V2; any other leading byte (or
    /// empty input, which bincode rejects) is decoded as an untagged V1
    /// record.
    pub fn deserialize(bytes: &[u8]) -> Result<Self, bincode::Error> {
        match bytes.first() {
            Some(&STAKE_INFO_V2_TAG) => {
                Ok(StakeInfoVersioned::V2(bincode::deserialize(&bytes[1..])?))
            }
            _ => Ok(StakeInfoVersioned::V1(bincode::deserialize(bytes)?)),
        }
    }
}

impl From<StakeInfo> for StakeInfoV1 {
    fn from(s: StakeInfo) -> Self {
        StakeInfoV1::from(&s)
    }
}

impl From<&StakeInfo> for StakeInfoV1 {
    fn from(s: &StakeInfo) -> Self {
        StakeInfoV1 {
            activation_requested: s.activation_requested,
            deactivation_requested: s.deactivation_requested,
            delegated_balance: s.delegated_balance,
            validator: s.validator,
            admin_authority: s.admin_authority,
            withdraw_authority: s.withdraw_authority,
            reward_receiver: s.reward_receiver,
        }
    }
}

impl From<StakeInfoV1> for StakeInfo {
    fn from(v: StakeInfoV1) -> Self {
        StakeInfo {
            activation_requested: v.activation_requested,
            deactivation_requested: v.deactivation_requested,
            delegated_balance: v.delegated_balance,
            validator: v.validator,
            admin_authority: v.admin_authority,
            withdraw_authority: v.withdraw_authority,
            reward_receiver: v.reward_receiver,
            // V1 predates `last_reward_slot`; a V1 record reads back as "no
            // reward applied yet".
            last_reward_slot: None,
        }
    }
}

impl From<StakeInfo> for StakeInfoV2 {
    fn from(s: StakeInfo) -> Self {
        StakeInfoV2::from(&s)
    }
}

impl From<&StakeInfo> for StakeInfoV2 {
    fn from(s: &StakeInfo) -> Self {
        StakeInfoV2 {
            activation_requested: s.activation_requested,
            deactivation_requested: s.deactivation_requested,
            delegated_balance: s.delegated_balance,
            validator: s.validator,
            admin_authority: s.admin_authority,
            withdraw_authority: s.withdraw_authority,
            reward_receiver: s.reward_receiver,
            last_reward_slot: s.last_reward_slot,
        }
    }
}

impl From<StakeInfoV2> for StakeInfo {
    fn from(v: StakeInfoV2) -> Self {
        StakeInfo {
            activation_requested: v.activation_requested,
            deactivation_requested: v.deactivation_requested,
            delegated_balance: v.delegated_balance,
            validator: v.validator,
            admin_authority: v.admin_authority,
            withdraw_authority: v.withdraw_authority,
            reward_receiver: v.reward_receiver,
            last_reward_slot: v.last_reward_slot,
        }
    }
}

/// Defaults to the V1 wire form. Feature-gated writers use
/// `StakeInfoVersioned::encode` to choose V2; this conversion exists for
/// callers without a feature context.
impl From<StakeInfo> for StakeInfoVersioned {
    fn from(s: StakeInfo) -> Self {
        StakeInfoVersioned::V1(StakeInfoV1::from(s))
    }
}

/// Borrowing analogue of the owning conversion above (V1 wire form).
impl From<&StakeInfo> for StakeInfoVersioned {
    fn from(s: &StakeInfo) -> Self {
        StakeInfoVersioned::V1(StakeInfoV1::from(s))
    }
}

impl From<StakeInfoVersioned> for StakeInfo {
    fn from(v: StakeInfoVersioned) -> Self {
        match v {
            StakeInfoVersioned::V1(v1) => StakeInfo::from(v1),
            StakeInfoVersioned::V2(v2) => StakeInfo::from(v2),
        }
    }
}

/// Instructions supported by the Stake Manager program
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone)]
pub enum StakeManagerInstruction {
    /// Initialize the Stake Manager
    ///
    /// Accounts expected:
    /// 0. `[signer]` Withdraw authority account (typically a cold wallet)
    /// 1. `[writable]` Stake account to store StakeInfo (must already be owned by StakeManager)
    Initiate {
        /// The admin authority for the stake manager (hot wallet)
        admin_authority: Pubkey,
        /// The withdraw authority for the stake manager (cold wallet)
        withdraw_authority: Pubkey,
        /// Optional reward receiver account
        reward_receiver: Option<Pubkey>,
    },

    /// Activate stake by delegating to a validator
    ///
    /// Accounts expected:
    /// 0. `[writable]` Stake account containing StakeInfo
    /// 1. `[signer]` Admin authority account
    /// 2. `[writable]` New validator info account to delegate to (for AddStake CPI)
    /// 3. `[writable]` (Optional) Old validator info account (for SubStake CPI when changing validators during pending activation)
    ActivateStake,

    /// Deactivate stake
    ///
    /// Accounts expected:
    /// 0. `[writable]` Stake account containing StakeInfo
    /// 1. `[signer]` Admin authority account
    /// 2. `[writable]` Validator info account (the validator being deactivated from)
    DeactivateStake,

    /// Withdraw kelvins from stake account
    ///
    /// Accounts expected:
    /// 0. `[writable]` Stake account containing StakeInfo
    /// 1. `[writable, signer]` Withdraw authority account (receives the withdrawn kelvins)
    ///
    /// The amount must not exceed (stake account kelvins - delegated_balance)
    Withdraw {
        /// Amount of kelvins to withdraw
        amount: u64,
    },

    /// Change the admin authority of a stake account
    ///
    /// Accounts expected:
    /// 0. `[writable]` Stake account containing StakeInfo
    /// 1. `[signer]` Current admin authority OR current withdraw authority
    ChangeAdminAuthority {
        /// The new admin authority
        new_admin_authority: Pubkey,
    },

    /// Change the withdraw authority of a stake account
    ///
    /// Accounts expected:
    /// 0. `[writable]` Stake account containing StakeInfo
    /// 1. `[signer]` Current withdraw authority
    ChangeWithdrawAuthority {
        /// The new withdraw authority
        new_withdraw_authority: Pubkey,
    },

    /// Split a portion of stake from one account into another
    ///
    /// The source stake account must be activated (have `activation_requested` set)
    /// and not deactivating (`deactivation_requested` must be None).
    /// The target stake account must be uninitialized (owned by StakeManager but not initialized).
    ///
    /// This instruction copies the delegation state from source to target and transfers
    /// the specified amount of kelvins/stake.
    ///
    /// Accounts expected:
    /// 0. `[writable]` Source stake account (must be initialized/activated, not deactivating)
    /// 1. `[writable]` Target stake account (must be uninitialized, owned by StakeManager)
    /// 2. `[signer]` Admin authority (must match source's admin_authority)
    SplitStake {
        /// Amount of kelvins/stake to split off
        amount: u64,
    },

    /// Merge two stake accounts into one
    ///
    /// Both accounts must have the same admin_authority and withdraw_authority.
    /// The merge conditions depend on the state of both accounts:
    ///
    /// **Case 1: Both accounts are active (activation_requested < last_freeze_timestamp)**
    /// - Must have same validator
    /// - Must have same lockup_period
    /// - Neither can be deactivating (deactivation_requested must be None)
    ///
    /// **Case 2: Target is pending activation (activation_requested >= last_freeze_timestamp)**
    /// - Source must be: never activated, also pending (same validator), or fully unbonded
    ///
    /// After merge, the source account is closed (zeroed and all kelvins transferred to target).
    ///
    /// Accounts expected:
    /// 0. `[writable]` Source stake account (will be closed after merge)
    /// 1. `[writable]` Target stake account (will receive merged stake)
    /// 2. `[signer]` Admin authority (must match both accounts' admin_authority)
    /// 3. `[]` (Optional) Source's validator account (needed for unbonding period check in Case 2)
    MergeStake,

    /// Change the reward receiver for a stake account
    ///
    /// Setting reward_receiver to None means rewards will compound (be added to stake).
    /// Setting reward_receiver to Some(pubkey) means rewards will be sent to that account.
    ///
    /// Accounts expected:
    /// 0. `[writable]` Stake account containing StakeInfo
    /// 1. `[signer]` Withdraw authority (must match stake_account's withdraw_authority)
    ChangeRewardReceiver {
        /// New reward receiver, or None to clear (rewards will compound)
        new_reward_receiver: Option<Pubkey>,
    },
}

impl StakeManagerInstruction {
    /// Create a `StakeManagerInstruction::Initiate` `Instruction`
    ///
    /// # Account references
    ///   0. `[SIGNER]` Withdraw authority account (typically a cold wallet)
    ///   1. `[WRITE]` Stake account to store StakeInfo (must already be owned by StakeManager)
    ///
    /// # Arguments
    /// * `admin_authority` - The public key of the admin authority (hot wallet)
    /// * `withdraw_authority` - The public key of the withdraw authority (cold wallet)
    /// * `stake_account` - The public key of the stake account (must already be owned by StakeManager)
    /// * `reward_receiver` - Optional public key for the reward receiver
    ///
    /// # Returns
    /// * `Instruction` - A Solana instruction to be included in a transaction
    pub fn initiate(
        admin_authority: Pubkey,
        withdraw_authority: Pubkey,
        stake_account: Pubkey,
        reward_receiver: Option<Pubkey>,
    ) -> Instruction {
        Instruction::new_with_bincode(
            crate::id(),
            &StakeManagerInstruction::Initiate {
                admin_authority,
                withdraw_authority,
                reward_receiver,
            },
            vec![
                AccountMeta::new_readonly(withdraw_authority, true),
                AccountMeta::new(stake_account, false),
            ],
        )
    }

    /// Create a `StakeManagerInstruction::ActivateStake` `Instruction`
    ///
    /// Use this for first-time activation or reactivation after unbonding.
    /// When changing validators during pending activation, provide `old_validator` to
    /// include the old validator account required for the SubStake CPI. If `old_validator`
    /// is `None`, the instruction omits the old validator account.
    ///
    /// # Account references
    ///   0. `[WRITE]` Stake account containing StakeInfo
    ///   1. `[SIGNER]` Admin authority account
    ///   2. `[WRITE]` New validator info account to delegate to (for AddStake CPI)
    ///   3. `[WRITE]` (Optional) Old validator info account (for SubStake CPI when changing validators during pending activation)
    ///   4. `[]` Validator Registry program (for CPI to AddStake/SubStake)
    ///
    /// # Arguments
    /// * `stake_account` - The public key of the stake account
    /// * `admin_authority` - The public key of the admin authority
    /// * `new_validator` - The public key of the validator to delegate to
    /// * `old_validator` - Optional public key of the old validator (required when changing validators during pending activation)
    ///
    /// # Returns
    /// * `Instruction` - A Solana instruction to be included in a transaction
    pub fn activate_stake(
        stake_account: Pubkey,
        admin_authority: Pubkey,
        new_validator: Pubkey,
        old_validator: Option<Pubkey>,
    ) -> Instruction {
        let mut accounts = vec![
            AccountMeta::new(stake_account, false),
            AccountMeta::new_readonly(admin_authority, true),
            AccountMeta::new(new_validator, false),
        ];

        if let Some(old) = old_validator {
            accounts.push(AccountMeta::new(old, false));
        }

        accounts.push(AccountMeta::new_readonly(
            rialo_validator_registry_interface::id(),
            false,
        ));

        Instruction::new_with_bincode(
            crate::id(),
            &StakeManagerInstruction::ActivateStake,
            accounts,
        )
    }

    /// Create a `StakeManagerInstruction::DeactivateStake` `Instruction`
    ///
    /// # Account references
    ///   0. `[WRITE]` Stake account containing StakeInfo
    ///   1. `[SIGNER]` Admin authority account
    ///   2. `[WRITE]` Validator info account (the validator being deactivated from)
    ///   3. `[]` Validator Registry program (for CPI to SubStake)
    ///
    /// # Arguments
    /// * `stake_account` - The public key of the stake account
    /// * `admin_authority` - The public key of the admin authority
    /// * `validator` - The public key of the validator info account
    ///
    /// # Returns
    /// * `Instruction` - A Solana instruction to be included in a transaction
    pub fn deactivate_stake(
        stake_account: Pubkey,
        admin_authority: Pubkey,
        validator: Pubkey,
    ) -> Instruction {
        Instruction::new_with_bincode(
            crate::id(),
            &StakeManagerInstruction::DeactivateStake,
            vec![
                AccountMeta::new(stake_account, false),
                AccountMeta::new_readonly(admin_authority, true),
                AccountMeta::new(validator, false),
                AccountMeta::new_readonly(rialo_validator_registry_interface::id(), false),
            ],
        )
    }

    /// Create a `StakeManagerInstruction::Withdraw` `Instruction`
    ///
    /// Use this for withdrawing from stake accounts that have NOT been deactivated
    /// (i.e., never activated, or currently active but with undelegated balance).
    ///
    /// For withdrawing from deactivated/deactivating stake accounts, use
    /// `withdraw_with_validator` instead.
    ///
    /// # Account references
    ///   0. `[WRITE]` Stake account containing StakeInfo
    ///   1. `[WRITE, SIGNER]` Withdraw authority account (receives the withdrawn kelvins)
    ///
    /// # Arguments
    /// * `stake_account` - The public key of the stake account
    /// * `withdraw_authority` - The public key of the withdraw authority
    /// * `amount` - The amount of kelvins to withdraw
    ///
    /// # Returns
    /// * `Instruction` - A Solana instruction to be included in a transaction
    pub fn withdraw(stake_account: Pubkey, withdraw_authority: Pubkey, amount: u64) -> Instruction {
        Instruction::new_with_bincode(
            crate::id(),
            &StakeManagerInstruction::Withdraw { amount },
            vec![
                AccountMeta::new(stake_account, false),
                AccountMeta::new(withdraw_authority, true),
            ],
        )
    }

    /// Create a `StakeManagerInstruction::Withdraw` `Instruction` withwith
    /// a validator account required for verifying the completed unbonding period.
    ///
    /// Use this for withdrawing from stake accounts after the unbonding period.
    /// The validator account is required to check the unbonding period and determine
    /// if the full balance (including delegated balance) can be withdrawn.
    ///
    /// # Account references
    ///   0. `[WRITE]` Stake account containing StakeInfo
    ///   1. `[WRITE, SIGNER]` Withdraw authority account (receives the withdrawn kelvins)
    ///   2. `[]` Validator info account (the validator the stake was delegated to)
    ///
    /// # Arguments
    /// * `stake_account` - The public key of the stake account
    /// * `withdraw_authority` - The public key of the withdraw authority
    /// * `validator` - The public key of the validator info account
    /// * `amount` - The amount of kelvins to withdraw
    ///
    /// # Returns
    /// * `Instruction` - A Solana instruction to be included in a transaction
    pub fn withdraw_after_unbonding(
        stake_account: Pubkey,
        withdraw_authority: Pubkey,
        validator: Pubkey,
        amount: u64,
    ) -> Instruction {
        Instruction::new_with_bincode(
            crate::id(),
            &StakeManagerInstruction::Withdraw { amount },
            vec![
                AccountMeta::new(stake_account, false),
                AccountMeta::new(withdraw_authority, true),
                AccountMeta::new_readonly(validator, false),
            ],
        )
    }

    /// Create a `StakeManagerInstruction::ChangeAdminAuthority` `Instruction`
    ///
    /// # Account references
    ///   0. `[WRITE]` Stake account containing StakeInfo
    ///   1. `[SIGNER]` Current admin authority OR current withdraw authority
    ///
    /// # Arguments
    /// * `stake_account` - The public key of the stake account
    /// * `current_authority` - The public key of the current admin or withdraw authority
    /// * `new_admin_authority` - The public key of the new admin authority
    ///
    /// # Returns
    /// * `Instruction` - A Solana instruction to be included in a transaction
    pub fn change_admin_authority(
        stake_account: Pubkey,
        current_authority: Pubkey,
        new_admin_authority: Pubkey,
    ) -> Instruction {
        Instruction::new_with_bincode(
            crate::id(),
            &StakeManagerInstruction::ChangeAdminAuthority {
                new_admin_authority,
            },
            vec![
                AccountMeta::new(stake_account, false),
                AccountMeta::new_readonly(current_authority, true),
            ],
        )
    }

    /// Create a `StakeManagerInstruction::ChangeWithdrawAuthority` `Instruction`
    ///
    /// # Account references
    ///   0. `[WRITE]` Stake account containing StakeInfo
    ///   1. `[SIGNER]` Current withdraw authority
    ///
    /// # Arguments
    /// * `stake_account` - The public key of the stake account
    /// * `current_withdraw_authority` - The public key of the current withdraw authority
    /// * `new_withdraw_authority` - The public key of the new withdraw authority
    ///
    /// # Returns
    /// * `Instruction` - A Solana instruction to be included in a transaction
    pub fn change_withdraw_authority(
        stake_account: Pubkey,
        current_withdraw_authority: Pubkey,
        new_withdraw_authority: Pubkey,
    ) -> Instruction {
        Instruction::new_with_bincode(
            crate::id(),
            &StakeManagerInstruction::ChangeWithdrawAuthority {
                new_withdraw_authority,
            },
            vec![
                AccountMeta::new(stake_account, false),
                AccountMeta::new_readonly(current_withdraw_authority, true),
            ],
        )
    }

    /// Create a `StakeManagerInstruction::SplitStake` `Instruction`
    ///
    /// # Account references
    ///   0. `[WRITE]` Source stake account (must be initialized/activated, not deactivating)
    ///   1. `[WRITE]` Target stake account (must be uninitialized, owned by StakeManager)
    ///   2. `[SIGNER]` Admin authority (must match source's admin_authority)
    ///
    /// # Arguments
    /// * `source_stake_account` - The public key of the source stake account
    /// * `target_stake_account` - The public key of the target stake account
    /// * `admin_authority` - The public key of the admin authority
    /// * `amount` - The amount of kelvins/stake to split off
    ///
    /// # Returns
    /// * `Instruction` - A Solana instruction to be included in a transaction
    pub fn split_stake(
        source_stake_account: Pubkey,
        target_stake_account: Pubkey,
        admin_authority: Pubkey,
        amount: u64,
    ) -> Instruction {
        Instruction::new_with_bincode(
            crate::id(),
            &StakeManagerInstruction::SplitStake { amount },
            vec![
                AccountMeta::new(source_stake_account, false),
                AccountMeta::new(target_stake_account, false),
                AccountMeta::new_readonly(admin_authority, true),
            ],
        )
    }

    /// Create a `StakeManagerInstruction::MergeStake` `Instruction`
    ///
    /// Use this when both accounts are active and have the same validator, or when
    /// the source was never activated.
    ///
    /// For merging unbonded source stake into a pending target, use
    /// `merge_stake_with_validator` instead.
    ///
    /// # Account references
    ///   0. `[WRITE]` Source stake account (will be closed after merge)
    ///   1. `[WRITE]` Target stake account (will receive merged stake)
    ///   2. `[SIGNER]` Admin authority (must match both accounts' admin_authority)
    ///
    /// # Arguments
    /// * `source_stake_account` - The public key of the source stake account
    /// * `target_stake_account` - The public key of the target stake account
    /// * `admin_authority` - The public key of the admin authority
    ///
    /// # Returns
    /// * `Instruction` - A Solana instruction to be included in a transaction
    pub fn merge_stake(
        source_stake_account: Pubkey,
        target_stake_account: Pubkey,
        admin_authority: Pubkey,
    ) -> Instruction {
        Instruction::new_with_bincode(
            crate::id(),
            &StakeManagerInstruction::MergeStake,
            vec![
                AccountMeta::new(source_stake_account, false),
                AccountMeta::new(target_stake_account, false),
                AccountMeta::new_readonly(admin_authority, true),
            ],
        )
    }

    /// Create a `StakeManagerInstruction::MergeStake` `Instruction` with
    /// a validator account required for verifying the completed unbonding period.
    ///
    /// Use this when merging unbonded source stake into a pending target.
    /// The validator account is required to check the unbonding period.
    ///
    /// # Account references
    ///   0. `[WRITE]` Source stake account (will be closed after merge)
    ///   1. `[WRITE]` Target stake account (will receive merged stake)
    ///   2. `[SIGNER]` Admin authority (must match both accounts' admin_authority)
    ///   3. `[]` Source's validator account (for unbonding period check)
    ///
    /// # Arguments
    /// * `source_stake_account` - The public key of the source stake account
    /// * `target_stake_account` - The public key of the target stake account
    /// * `admin_authority` - The public key of the admin authority
    /// * `source_validator` - The public key of the source's validator account
    ///
    /// # Returns
    /// * `Instruction` - A Solana instruction to be included in a transaction
    pub fn merge_stake_after_unbonding(
        source_stake_account: Pubkey,
        target_stake_account: Pubkey,
        admin_authority: Pubkey,
        source_validator: Pubkey,
    ) -> Instruction {
        Instruction::new_with_bincode(
            crate::id(),
            &StakeManagerInstruction::MergeStake,
            vec![
                AccountMeta::new(source_stake_account, false),
                AccountMeta::new(target_stake_account, false),
                AccountMeta::new_readonly(admin_authority, true),
                AccountMeta::new_readonly(source_validator, false),
            ],
        )
    }

    /// Create a `StakeManagerInstruction::ChangeRewardReceiver` `Instruction`
    ///
    /// # Account references
    ///   0. `[WRITE]` Stake account containing StakeInfo
    ///   1. `[SIGNER]` Withdraw authority (must match stake_account's withdraw_authority)
    ///
    /// # Arguments
    /// * `stake_account` - The public key of the stake account
    /// * `withdraw_authority` - The public key of the withdraw authority
    /// * `new_reward_receiver` - Optional new reward receiver, or None to clear (rewards will compound)
    ///
    /// # Returns
    /// * `Instruction` - A Solana instruction to be included in a transaction
    pub fn change_reward_receiver(
        stake_account: Pubkey,
        withdraw_authority: Pubkey,
        new_reward_receiver: Option<Pubkey>,
    ) -> Instruction {
        Instruction::new_with_bincode(
            crate::id(),
            &StakeManagerInstruction::ChangeRewardReceiver {
                new_reward_receiver,
            },
            vec![
                AccountMeta::new(stake_account, false),
                AccountMeta::new_readonly(withdraw_authority, true),
            ],
        )
    }
}

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

    #[test]
    fn test_initiate_instruction_with_reward_receiver() {
        let admin_authority = Pubkey::new_unique();
        let withdraw_authority = Pubkey::new_unique();
        let stake_account = Pubkey::new_unique();
        let reward_receiver = Pubkey::new_unique();

        // Create the initiate instruction with reward receiver
        let instruction = StakeManagerInstruction::initiate(
            admin_authority,
            withdraw_authority,
            stake_account,
            Some(reward_receiver),
        );

        // Verify the program ID
        assert_eq!(instruction.program_id, crate::id());

        // Expected accounts:
        let expected_accounts = vec![
            AccountMeta::new_readonly(withdraw_authority, true),
            AccountMeta::new(stake_account, false),
        ];

        // Verify accounts
        assert_eq!(instruction.accounts, expected_accounts);

        // Deserialize and verify instruction data
        let decoded_instruction: StakeManagerInstruction =
            bincode::deserialize(&instruction.data).unwrap();

        match decoded_instruction {
            StakeManagerInstruction::Initiate {
                admin_authority: decoded_admin_authority,
                withdraw_authority: decoded_withdraw_authority,
                reward_receiver: decoded_reward_receiver,
            } => {
                assert_eq!(decoded_admin_authority, admin_authority);
                assert_eq!(decoded_withdraw_authority, withdraw_authority);
                assert_eq!(decoded_reward_receiver, Some(reward_receiver));
            }
            _ => panic!("Expected Initiate instruction"),
        }
    }

    #[test]
    fn test_initiate_instruction_without_reward_receiver() {
        let admin_authority = Pubkey::new_unique();
        let withdraw_authority = Pubkey::new_unique();
        let stake_account = Pubkey::new_unique();

        // Create the initiate instruction without reward receiver
        let instruction = StakeManagerInstruction::initiate(
            admin_authority,
            withdraw_authority,
            stake_account,
            None,
        );

        // Verify the program ID
        assert_eq!(instruction.program_id, crate::id());

        // Expected accounts:
        let expected_accounts = vec![
            AccountMeta::new_readonly(withdraw_authority, true),
            AccountMeta::new(stake_account, false),
        ];

        // Verify accounts
        assert_eq!(instruction.accounts, expected_accounts);

        // Deserialize and verify instruction data
        let decoded_instruction: StakeManagerInstruction =
            bincode::deserialize(&instruction.data).unwrap();

        match decoded_instruction {
            StakeManagerInstruction::Initiate {
                admin_authority: decoded_admin_authority,
                withdraw_authority: decoded_withdraw_authority,
                reward_receiver: decoded_reward_receiver,
            } => {
                assert_eq!(decoded_admin_authority, admin_authority);
                assert_eq!(decoded_withdraw_authority, withdraw_authority);
                assert_eq!(decoded_reward_receiver, None);
            }
            _ => panic!("Expected Initiate instruction"),
        }
    }

    #[test]
    fn test_change_admin_authority_instruction() {
        let stake_account = Pubkey::new_unique();
        let current_authority = Pubkey::new_unique();
        let new_admin_authority = Pubkey::new_unique();

        let instruction = StakeManagerInstruction::change_admin_authority(
            stake_account,
            current_authority,
            new_admin_authority,
        );

        // Verify the program ID
        assert_eq!(instruction.program_id, crate::id());

        // Expected accounts:
        let expected_accounts = vec![
            AccountMeta::new(stake_account, false),
            AccountMeta::new_readonly(current_authority, true),
        ];

        // Verify accounts
        assert_eq!(instruction.accounts, expected_accounts);

        // Deserialize and verify instruction data
        let decoded_instruction: StakeManagerInstruction =
            bincode::deserialize(&instruction.data).unwrap();

        match decoded_instruction {
            StakeManagerInstruction::ChangeAdminAuthority {
                new_admin_authority: decoded_new_admin,
            } => {
                assert_eq!(decoded_new_admin, new_admin_authority);
            }
            _ => panic!("Expected ChangeAdminAuthority instruction"),
        }
    }

    #[test]
    fn test_change_withdraw_authority_instruction() {
        let stake_account = Pubkey::new_unique();
        let current_withdraw_authority = Pubkey::new_unique();
        let new_withdraw_authority = Pubkey::new_unique();

        let instruction = StakeManagerInstruction::change_withdraw_authority(
            stake_account,
            current_withdraw_authority,
            new_withdraw_authority,
        );

        // Verify the program ID
        assert_eq!(instruction.program_id, crate::id());

        // Expected accounts:
        let expected_accounts = vec![
            AccountMeta::new(stake_account, false),
            AccountMeta::new_readonly(current_withdraw_authority, true),
        ];

        // Verify accounts
        assert_eq!(instruction.accounts, expected_accounts);

        // Deserialize and verify instruction data
        let decoded_instruction: StakeManagerInstruction =
            bincode::deserialize(&instruction.data).unwrap();

        match decoded_instruction {
            StakeManagerInstruction::ChangeWithdrawAuthority {
                new_withdraw_authority: decoded_new_withdraw,
            } => {
                assert_eq!(decoded_new_withdraw, new_withdraw_authority);
            }
            _ => panic!("Expected ChangeWithdrawAuthority instruction"),
        }
    }

    #[test]
    fn test_stake_info_max_size_matches_bincode() {
        // Create a StakeInfo with all Option fields set to Some (maximum size case)
        let max_stake_info = StakeInfo {
            activation_requested: Some(u64::MAX),
            deactivation_requested: Some(u64::MAX),
            delegated_balance: u64::MAX,
            validator: Some(Pubkey::new_unique()),
            admin_authority: Pubkey::new_unique(),
            withdraw_authority: Pubkey::new_unique(),
            reward_receiver: Some(Pubkey::new_unique()),
            last_reward_slot: Some(u64::MAX),
        };

        let serialized_size = bincode::serialized_size(&max_stake_info).unwrap() as usize;
        assert_eq!(
            serialized_size,
            StakeInfo::MAX_SIZE,
            "StakeInfo::MAX_SIZE ({}) does not match actual bincode serialized size ({})",
            StakeInfo::MAX_SIZE,
            serialized_size
        );
    }

    /// V1-shaped sample: `last_reward_slot` is `None`, so it round-trips
    /// losslessly through the V1 wire form.
    fn sample_stake_info() -> StakeInfo {
        StakeInfo {
            activation_requested: Some(123),
            deactivation_requested: None,
            delegated_balance: 42,
            validator: Some(Pubkey::new_unique()),
            admin_authority: Pubkey::new_unique(),
            withdraw_authority: Pubkey::new_unique(),
            reward_receiver: Some(Pubkey::new_unique()),
            last_reward_slot: None,
        }
    }

    /// V2-shaped sample: carries a `last_reward_slot`, only preserved by V2.
    fn sample_stake_info_v2() -> StakeInfo {
        StakeInfo {
            last_reward_slot: Some(9999),
            ..sample_stake_info()
        }
    }

    #[test]
    fn v1_default_conversion_round_trips_v1_shaped_value() {
        let original = sample_stake_info();
        let versioned = StakeInfoVersioned::from(original.clone());
        assert_eq!(
            versioned,
            StakeInfoVersioned::V1(StakeInfoV1::from(original.clone()))
        );
        // StakeInfo -> V1 -> StakeInfo is the identity when last_reward_slot is None.
        assert_eq!(StakeInfo::from(versioned), original);
    }

    #[test]
    fn v1_wire_is_frozen_against_the_v2_field() {
        // The V1 layout must not change when StakeInfo grows a V2 field: two
        // StakeInfos differing only in last_reward_slot must produce identical
        // V1 bytes (the field is dropped on the V1 path). Both derive from one
        // base so they differ in nothing else.
        let base = sample_stake_info();
        let with_field = StakeInfo {
            last_reward_slot: Some(9999),
            ..base.clone()
        };
        let base_v1 = bincode::serialize(&StakeInfoV1::from(&base)).unwrap();
        let with_field_v1 = bincode::serialize(&StakeInfoV1::from(&with_field)).unwrap();
        assert_eq!(
            base_v1, with_field_v1,
            "StakeInfoV1 wire format is not frozen"
        );
    }

    #[cfg(feature = "typed-account")]
    #[test]
    fn v2_tag_is_disjoint_from_v1_first_byte() {
        // A V1 record begins with an Option discriminant (0 or 1); the V2 tag
        // must never collide with it, or the tolerant reader would misdetect.
        let v1_bytes = bincode::serialize(&StakeInfoV1::from(&sample_stake_info())).unwrap();
        assert!(
            v1_bytes[0] == 0 || v1_bytes[0] == 1,
            "unexpected V1 first byte {}",
            v1_bytes[0]
        );
        assert_ne!(v1_bytes[0], STAKE_INFO_V2_TAG);
    }

    #[cfg(feature = "typed-account")]
    #[test]
    fn v1_serialize_is_untagged_and_round_trips() {
        let original = sample_stake_info();
        let bytes = StakeInfoVersioned::encode(&original, false)
            .serialize()
            .unwrap();
        assert_ne!(bytes[0], STAKE_INFO_V2_TAG, "V1 must be untagged");
        let decoded = StakeInfoVersioned::deserialize(&bytes).unwrap();
        assert_eq!(StakeInfo::from(decoded), original);
    }

    #[cfg(feature = "typed-account")]
    #[test]
    fn v1_serialize_is_byte_identical_to_pre_envelope_bincode() {
        // Load-bearing "existing accounts read unchanged" guarantee: the V1
        // envelope output must be byte-for-byte equal to the bare bincode the
        // pre-envelope code path wrote. Catches any silent V1 wire drift.
        let original = sample_stake_info();
        let pre_envelope = bincode::serialize(&original).unwrap();
        let v1_envelope = StakeInfoVersioned::encode(&original, false)
            .serialize()
            .unwrap();
        assert_eq!(
            pre_envelope, v1_envelope,
            "V1 envelope serialization drifted from the pre-envelope bincode"
        );
    }

    #[cfg(feature = "typed-account")]
    #[test]
    fn v2_serialize_is_tagged_and_preserves_last_reward_slot() {
        let original = sample_stake_info_v2();
        let bytes = StakeInfoVersioned::encode(&original, true)
            .serialize()
            .unwrap();
        assert_eq!(bytes[0], STAKE_INFO_V2_TAG, "V2 must be tagged");
        let decoded = StakeInfoVersioned::deserialize(&bytes).unwrap();
        assert_eq!(
            decoded,
            StakeInfoVersioned::V2(StakeInfoV2::from(&original))
        );
        // Full round-trip preserves the V2-only field.
        assert_eq!(StakeInfo::from(decoded), original);
    }

    #[cfg(feature = "typed-account")]
    #[test]
    fn max_wire_size_matches_largest_v2_record() {
        // `MAX_WIRE_SIZE` is hand-computed and used as the indexer's hard
        // reject threshold, so pin it to the actual largest serialized V2
        // record (all `Option`s `Some`). If a future field changes the V2
        // layout without updating the constant, this fails instead of silently
        // rejecting valid records.
        let max = StakeInfo {
            activation_requested: Some(u64::MAX),
            deactivation_requested: Some(u64::MAX),
            delegated_balance: u64::MAX,
            validator: Some(Pubkey::new_unique()),
            admin_authority: Pubkey::new_unique(),
            withdraw_authority: Pubkey::new_unique(),
            reward_receiver: Some(Pubkey::new_unique()),
            last_reward_slot: Some(u64::MAX),
        };
        let wire = StakeInfoVersioned::encode(&max, true).serialize().unwrap();
        assert_eq!(
            wire.len(),
            StakeInfo::MAX_WIRE_SIZE,
            "MAX_WIRE_SIZE ({}) does not match the largest serialized V2 record ({})",
            StakeInfo::MAX_WIRE_SIZE,
            wire.len(),
        );
    }

    #[cfg(feature = "typed-account")]
    #[test]
    fn encode_selects_version_by_feature_flag() {
        let s = sample_stake_info_v2();
        assert!(matches!(
            StakeInfoVersioned::encode(&s, false),
            StakeInfoVersioned::V1(_)
        ));
        assert!(matches!(
            StakeInfoVersioned::encode(&s, true),
            StakeInfoVersioned::V2(_)
        ));
    }

    #[cfg(feature = "typed-account")]
    #[test]
    fn legacy_v1_bytes_decode_through_tolerant_reader() {
        // Bytes written before V2 existed are a bare bincode of the V1 shape
        // (no tag). The tolerant reader must decode them as V1, yielding
        // last_reward_slot = None.
        let original = sample_stake_info();
        let legacy_bytes = bincode::serialize(&StakeInfoV1::from(&original)).unwrap();

        let decoded = StakeInfoVersioned::deserialize(&legacy_bytes).unwrap();
        assert_eq!(
            decoded,
            StakeInfoVersioned::V1(StakeInfoV1::from(&original))
        );
        assert_eq!(StakeInfo::from(decoded).last_reward_slot, None);
    }
}