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
// 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>,
}
/// 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> {
use rialo_s_account::ReadableAccount;
// Verify ownership
let owner = *account.owner();
if owner != crate::id() {
return Err(StakeInfoParseError::InvalidOwner {
expected: crate::id(),
actual: owner,
});
}
// Deserialize the account data
let stake_info: StakeInfo = bincode::deserialize(account.data())?;
Ok(stake_info)
}
}
#[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,
});
}
// Deserialize the account data
let stake_info: StakeInfo = bincode::deserialize(account.data())?;
Ok(stake_info)
}
}
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
assert!(
mem::size_of::<StakeInfo>() == 176,
"StakeInfo size changed - update MAX_SIZE calculation below"
);
// Breakdown (bincode format):
// - 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>()
};
}
/// 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()),
};
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
);
}
}