-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathprocessor.rs
More file actions
2096 lines (1868 loc) · 81.7 KB
/
Copy pathprocessor.rs
File metadata and controls
2096 lines (1868 loc) · 81.7 KB
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
//! program state processor
use {
crate::{
error::SinglePoolError,
inline_mpl_token_metadata::{
self,
instruction::{create_metadata_accounts_v3, update_metadata_accounts_v2},
pda::find_metadata_account,
state::DataV2,
},
instruction::{self as svsp_instruction, SinglePoolInstruction},
state::{SinglePool, SinglePoolAccountType},
DEPOSIT_SOL_FEE_BPS, MAX_BPS, MINT_DECIMALS, PERPETUAL_NEW_WARMUP_COOLDOWN_RATE_EPOCH,
PHANTOM_TOKEN_AMOUNT, POOL_MINT_AUTHORITY_PREFIX, POOL_MINT_PREFIX,
POOL_MPL_AUTHORITY_PREFIX, POOL_ONRAMP_PREFIX, POOL_PREFIX, POOL_STAKE_AUTHORITY_PREFIX,
POOL_STAKE_PREFIX, VOTE_STATE_AUTHORIZED_WITHDRAWER_END,
VOTE_STATE_AUTHORIZED_WITHDRAWER_START, VOTE_STATE_DISCRIMINATOR_END,
},
borsh::BorshDeserialize,
solana_account_info::{next_account_info, AccountInfo},
solana_borsh::v1::try_from_slice_unchecked,
solana_clock::Clock,
solana_cpi::{invoke, invoke_signed},
solana_get_sysvar::GetSysvar,
solana_msg::msg,
solana_native_token::LAMPORTS_PER_SOL,
solana_program_entrypoint::ProgramResult,
solana_program_error::ProgramError,
solana_program_pack::Pack,
solana_pubkey::Pubkey,
solana_rent::Rent,
solana_stake_interface::{
self as stake,
state::{Meta, Stake, StakeActivationStatus, StakeStateV2},
sysvar::stake_history::StakeHistorySysvar,
},
solana_system_interface::{instruction as system_instruction, program as system_program},
solana_sysvar::SysvarSerialize,
solana_vote_interface::program as vote_program,
spl_token_interface::{self as spl_token, state::Mint},
};
/// Determine the canonical value of the pool from its staked and stake-able lamports
fn pool_net_asset_value(
pool_stake_info: &AccountInfo,
pool_onramp_info: &AccountInfo,
rent: &Rent,
) -> u64 {
// these numbers should typically be equal, but might differ during StakeState upgrades
let pool_rent_exempt_reserve = rent.minimum_balance(pool_stake_info.data_len());
let onramp_rent_exempt_reserve = rent.minimum_balance(pool_onramp_info.data_len());
// NAV is all lamports in both accounts less rent
let main_stake_value = pool_stake_info
.lamports()
.saturating_sub(pool_rent_exempt_reserve);
let onramp_value = pool_onramp_info
.lamports()
.saturating_sub(onramp_rent_exempt_reserve);
main_stake_value.saturating_add(onramp_value)
}
/// Calculate pool tokens to mint, given outstanding token supply, pool NAV, and deposit amount
fn calculate_deposit_amount(
pre_token_supply: u64,
pre_pool_nav: u64,
user_deposit_amount: u64,
) -> Option<u64> {
if pre_pool_nav == 0 || pre_token_supply == 0 {
Some(user_deposit_amount)
} else {
u64::try_from(
(user_deposit_amount as u128)
.checked_mul(pre_token_supply as u128)?
.checked_div(pre_pool_nav as u128)?,
)
.ok()
}
}
/// Calculate pool value to return, given outstanding token supply, pool NAV, and tokens to redeem
fn calculate_withdraw_amount(
pre_token_supply: u64,
pre_pool_nav: u64,
user_tokens_to_burn: u64,
) -> Option<u64> {
let numerator = (user_tokens_to_burn as u128).checked_mul(pre_pool_nav as u128)?;
let denominator = pre_token_supply as u128;
if numerator < denominator || denominator == 0 {
Some(0)
} else {
u64::try_from(numerator.checked_div(denominator)?).ok()
}
}
/// Deserialize the stake state from `AccountInfo`
fn get_stake_state(stake_account_info: &AccountInfo) -> Result<(Meta, Stake), ProgramError> {
match deserialize_stake(stake_account_info) {
Ok(StakeStateV2::Stake(meta, stake, _)) => Ok((meta, stake)),
_ => Err(SinglePoolError::WrongStakeState.into()),
}
}
/// Deserialize the stake amount from `AccountInfo`
fn get_stake_amount(stake_account_info: &AccountInfo) -> Result<u64, ProgramError> {
Ok(get_stake_state(stake_account_info)?.1.delegation.stake)
}
/// Wrapper so if we ever change stake deserialization we have it in one place
fn deserialize_stake(stake_account_info: &AccountInfo) -> Result<StakeStateV2, ProgramError> {
Ok(try_from_slice_unchecked::<StakeStateV2>(
&stake_account_info.data.borrow(),
)?)
}
/// Determine if stake is fully active with history
fn is_stake_fully_active(stake_activation_status: &StakeActivationStatus) -> bool {
matches!(stake_activation_status, StakeActivationStatus {
effective,
activating: 0,
deactivating: 0,
} if *effective > 0)
}
/// Determine if stake is newly activating with history
fn is_stake_newly_activating(stake_activation_status: &StakeActivationStatus) -> bool {
matches!(stake_activation_status, StakeActivationStatus {
effective: 0,
activating,
deactivating: 0,
} if *activating > 0)
}
/// Check pool account address for the validator vote account
fn check_pool_address(
program_id: &Pubkey,
vote_account_address: &Pubkey,
check_address: &Pubkey,
) -> Result<u8, ProgramError> {
check_pool_pda(
program_id,
vote_account_address,
check_address,
&crate::find_pool_address_and_bump,
"pool",
SinglePoolError::InvalidPoolAccount,
)
}
/// Check pool stake account address for the pool account
fn check_pool_stake_address(
program_id: &Pubkey,
pool_address: &Pubkey,
check_address: &Pubkey,
) -> Result<u8, ProgramError> {
check_pool_pda(
program_id,
pool_address,
check_address,
&crate::find_pool_stake_address_and_bump,
"stake account",
SinglePoolError::InvalidPoolStakeAccount,
)
}
/// Check pool on-ramp account address for the pool account
fn check_pool_onramp_address(
program_id: &Pubkey,
pool_address: &Pubkey,
check_address: &Pubkey,
) -> Result<u8, ProgramError> {
check_pool_pda(
program_id,
pool_address,
check_address,
&crate::find_pool_onramp_address_and_bump,
"onramp account",
SinglePoolError::InvalidPoolOnRampAccount,
)
}
/// Check pool mint address for the pool account
fn check_pool_mint_address(
program_id: &Pubkey,
pool_address: &Pubkey,
check_address: &Pubkey,
) -> Result<u8, ProgramError> {
check_pool_pda(
program_id,
pool_address,
check_address,
&crate::find_pool_mint_address_and_bump,
"mint",
SinglePoolError::InvalidPoolMint,
)
}
/// Check pool stake authority address for the pool account
fn check_pool_stake_authority_address(
program_id: &Pubkey,
pool_address: &Pubkey,
check_address: &Pubkey,
) -> Result<u8, ProgramError> {
check_pool_pda(
program_id,
pool_address,
check_address,
&crate::find_pool_stake_authority_address_and_bump,
"stake authority",
SinglePoolError::InvalidPoolStakeAuthority,
)
}
/// Check pool mint authority address for the pool account
fn check_pool_mint_authority_address(
program_id: &Pubkey,
pool_address: &Pubkey,
check_address: &Pubkey,
) -> Result<u8, ProgramError> {
check_pool_pda(
program_id,
pool_address,
check_address,
&crate::find_pool_mint_authority_address_and_bump,
"mint authority",
SinglePoolError::InvalidPoolMintAuthority,
)
}
/// Check pool MPL authority address for the pool account
fn check_pool_mpl_authority_address(
program_id: &Pubkey,
pool_address: &Pubkey,
check_address: &Pubkey,
) -> Result<u8, ProgramError> {
check_pool_pda(
program_id,
pool_address,
check_address,
&crate::find_pool_mpl_authority_address_and_bump,
"MPL authority",
SinglePoolError::InvalidPoolMplAuthority,
)
}
fn check_pool_pda(
program_id: &Pubkey,
base_address: &Pubkey,
check_address: &Pubkey,
pda_lookup_fn: &dyn Fn(&Pubkey, &Pubkey) -> (Pubkey, u8),
pda_name: &str,
pool_error: SinglePoolError,
) -> Result<u8, ProgramError> {
let (derived_address, bump_seed) = pda_lookup_fn(program_id, base_address);
if *check_address != derived_address {
msg!(
"Incorrect {} address for base {}: expected {}, received {}",
pda_name,
base_address,
derived_address,
check_address,
);
Err(pool_error.into())
} else {
Ok(bump_seed)
}
}
/// Check vote account is owned by the vote program and not a legacy variant
fn check_vote_account(vote_account_info: &AccountInfo) -> Result<(), ProgramError> {
check_account_owner(vote_account_info, &vote_program::id())?;
let vote_account_data = &vote_account_info.try_borrow_data()?;
let state_variant = vote_account_data
.get(..VOTE_STATE_DISCRIMINATOR_END)
.and_then(|s| s.try_into().ok())
.ok_or(SinglePoolError::UnparseableVoteAccount)?;
#[allow(clippy::manual_range_patterns)]
match u32::from_le_bytes(state_variant) {
1 | 2 | 3 => Ok(()),
0 => Err(SinglePoolError::LegacyVoteAccount.into()),
_ => Err(SinglePoolError::UnparseableVoteAccount.into()),
}
}
/// Check pool mint address and return notional token supply.
/// Phantom tokens exist to represent pool-locked stake in calculations.
fn check_pool_mint_with_supply(
program_id: &Pubkey,
pool_address: &Pubkey,
pool_mint_info: &AccountInfo,
) -> Result<u64, ProgramError> {
check_pool_mint_address(program_id, pool_address, pool_mint_info.key)?;
let pool_mint_data = pool_mint_info.try_borrow_data()?;
let pool_mint = Mint::unpack_from_slice(&pool_mint_data)?;
Ok(pool_mint.supply.saturating_add(PHANTOM_TOKEN_AMOUNT))
}
/// Check MPL metadata account address for the pool mint
fn check_mpl_metadata_account_address(
metadata_address: &Pubkey,
pool_mint: &Pubkey,
) -> Result<(), ProgramError> {
let (metadata_account_pubkey, _) = find_metadata_account(pool_mint);
if metadata_account_pubkey != *metadata_address {
Err(SinglePoolError::InvalidMetadataAccount.into())
} else {
Ok(())
}
}
/// Check system program address
fn check_system_program(program_id: &Pubkey) -> Result<(), ProgramError> {
if *program_id != system_program::id() {
msg!(
"Expected system program {}, received {}",
system_program::id(),
program_id
);
Err(ProgramError::IncorrectProgramId)
} else {
Ok(())
}
}
/// Check token program address
fn check_token_program(address: &Pubkey) -> Result<(), ProgramError> {
if *address != spl_token::id() {
msg!(
"Incorrect token program, expected {}, received {}",
spl_token::id(),
address
);
Err(ProgramError::IncorrectProgramId)
} else {
Ok(())
}
}
/// Check stake program address
fn check_stake_program(program_id: &Pubkey) -> Result<(), ProgramError> {
if *program_id != stake::program::id() {
msg!(
"Expected stake program {}, received {}",
stake::program::id(),
program_id
);
Err(ProgramError::IncorrectProgramId)
} else {
Ok(())
}
}
/// Check MPL metadata program
fn check_mpl_metadata_program(program_id: &Pubkey) -> Result<(), ProgramError> {
if *program_id != inline_mpl_token_metadata::id() {
msg!(
"Expected MPL metadata program {}, received {}",
inline_mpl_token_metadata::id(),
program_id
);
Err(ProgramError::IncorrectProgramId)
} else {
Ok(())
}
}
/// Check account owner is the given program
fn check_account_owner(
account_info: &AccountInfo,
program_id: &Pubkey,
) -> Result<(), ProgramError> {
if *program_id != *account_info.owner {
msg!(
"Expected account to be owned by program {}, received {}",
program_id,
account_info.owner
);
Err(ProgramError::IncorrectProgramId)
} else {
Ok(())
}
}
/// Minimum balance of delegated stake required to create a pool. We require at least
/// 1 sol to avoid minting tokens for these lamports (locking them in the pool) since
/// they will *become* locked after the BPF Stake 5.0.0 upgrade.
///
/// We also track any future (currently unplanned) minimum delegation increase, to ensure
/// a new pool is always valid for `DelegateStake`.
fn minimum_pool_balance() -> Result<u64, ProgramError> {
Ok(std::cmp::max(
stake::tools::get_minimum_delegation()?,
LAMPORTS_PER_SOL,
))
}
/// Program state handler.
pub struct Processor {}
impl Processor {
#[allow(clippy::too_many_arguments)]
fn stake_merge<'a>(
pool_account_key: &Pubkey,
source_account: AccountInfo<'a>,
authority: AccountInfo<'a>,
bump_seed: u8,
destination_account: AccountInfo<'a>,
clock: AccountInfo<'a>,
stake_history: AccountInfo<'a>,
) -> Result<(), ProgramError> {
let authority_seeds = &[
POOL_STAKE_AUTHORITY_PREFIX,
pool_account_key.as_ref(),
&[bump_seed],
];
let signers = &[&authority_seeds[..]];
invoke_signed(
&stake::instruction::merge(destination_account.key, source_account.key, authority.key)
[0],
&[
destination_account,
source_account,
clock,
stake_history,
authority,
],
signers,
)
}
fn stake_split<'a>(
pool_account_key: &Pubkey,
stake_account: AccountInfo<'a>,
authority: AccountInfo<'a>,
bump_seed: u8,
amount: u64,
split_stake: AccountInfo<'a>,
) -> Result<(), ProgramError> {
let authority_seeds = &[
POOL_STAKE_AUTHORITY_PREFIX,
pool_account_key.as_ref(),
&[bump_seed],
];
let signers = &[&authority_seeds[..]];
let split_instruction =
stake::instruction::split(stake_account.key, authority.key, amount, split_stake.key);
invoke_signed(
split_instruction.last().unwrap(),
&[stake_account, split_stake, authority],
signers,
)
}
#[allow(clippy::too_many_arguments)]
fn stake_authorize<'a>(
pool_account_key: &Pubkey,
stake_account: AccountInfo<'a>,
stake_authority: AccountInfo<'a>,
bump_seed: u8,
new_stake_authority: &Pubkey,
clock: AccountInfo<'a>,
) -> Result<(), ProgramError> {
let authority_seeds = &[
POOL_STAKE_AUTHORITY_PREFIX,
pool_account_key.as_ref(),
&[bump_seed],
];
let signers = &[&authority_seeds[..]];
let authorize_instruction = stake::instruction::authorize(
stake_account.key,
stake_authority.key,
new_stake_authority,
stake::state::StakeAuthorize::Staker,
None,
);
invoke_signed(
&authorize_instruction,
&[
stake_account.clone(),
clock.clone(),
stake_authority.clone(),
],
signers,
)?;
let authorize_instruction = stake::instruction::authorize(
stake_account.key,
stake_authority.key,
new_stake_authority,
stake::state::StakeAuthorize::Withdrawer,
None,
);
invoke_signed(
&authorize_instruction,
&[stake_account, clock, stake_authority],
signers,
)
}
#[allow(clippy::too_many_arguments)]
fn stake_withdraw<'a>(
pool_account_key: &Pubkey,
stake_account: AccountInfo<'a>,
stake_authority: AccountInfo<'a>,
bump_seed: u8,
destination_account: AccountInfo<'a>,
clock: AccountInfo<'a>,
stake_history: AccountInfo<'a>,
lamports: u64,
) -> Result<(), ProgramError> {
let authority_seeds = &[
POOL_STAKE_AUTHORITY_PREFIX,
pool_account_key.as_ref(),
&[bump_seed],
];
let signers = &[&authority_seeds[..]];
let withdraw_instruction = stake::instruction::withdraw(
stake_account.key,
stake_authority.key,
destination_account.key,
lamports,
None,
);
invoke_signed(
&withdraw_instruction,
&[
stake_account,
destination_account,
clock,
stake_history,
stake_authority,
],
signers,
)
}
#[allow(clippy::too_many_arguments)]
fn token_mint_to<'a>(
pool_account_key: &Pubkey,
token_program: AccountInfo<'a>,
mint: AccountInfo<'a>,
destination: AccountInfo<'a>,
authority: AccountInfo<'a>,
bump_seed: u8,
amount: u64,
) -> Result<(), ProgramError> {
let authority_seeds = &[
POOL_MINT_AUTHORITY_PREFIX,
pool_account_key.as_ref(),
&[bump_seed],
];
let signers = &[&authority_seeds[..]];
let ix = spl_token::instruction::mint_to(
token_program.key,
mint.key,
destination.key,
authority.key,
&[],
amount,
)?;
invoke_signed(&ix, &[mint, destination, authority], signers)
}
#[allow(clippy::too_many_arguments)]
fn token_burn<'a>(
pool_account_key: &Pubkey,
token_program: AccountInfo<'a>,
burn_account: AccountInfo<'a>,
mint: AccountInfo<'a>,
authority: AccountInfo<'a>,
bump_seed: u8,
amount: u64,
) -> Result<(), ProgramError> {
let authority_seeds = &[
POOL_MINT_AUTHORITY_PREFIX,
pool_account_key.as_ref(),
&[bump_seed],
];
let signers = &[&authority_seeds[..]];
let ix = spl_token::instruction::burn(
token_program.key,
burn_account.key,
mint.key,
authority.key,
&[],
amount,
)?;
invoke_signed(&ix, &[burn_account, mint, authority], signers)
}
fn process_initialize_pool(program_id: &Pubkey, accounts: &[AccountInfo]) -> ProgramResult {
let account_info_iter = &mut accounts.iter();
let vote_account_info = next_account_info(account_info_iter)?;
let pool_info = next_account_info(account_info_iter)?;
let pool_stake_info = next_account_info(account_info_iter)?;
let pool_mint_info = next_account_info(account_info_iter)?;
let pool_stake_authority_info = next_account_info(account_info_iter)?;
let pool_mint_authority_info = next_account_info(account_info_iter)?;
let rent_info = next_account_info(account_info_iter)?;
let rent = &Rent::from_account_info(rent_info)?;
let clock_info = next_account_info(account_info_iter)?;
let stake_history_info = next_account_info(account_info_iter)?;
let stake_config_info = next_account_info(account_info_iter)?;
let system_program_info = next_account_info(account_info_iter)?;
let token_program_info = next_account_info(account_info_iter)?;
let stake_program_info = next_account_info(account_info_iter)?;
check_vote_account(vote_account_info)?;
let pool_bump_seed = check_pool_address(program_id, vote_account_info.key, pool_info.key)?;
let stake_bump_seed =
check_pool_stake_address(program_id, pool_info.key, pool_stake_info.key)?;
let mint_bump_seed =
check_pool_mint_address(program_id, pool_info.key, pool_mint_info.key)?;
let stake_authority_bump_seed = check_pool_stake_authority_address(
program_id,
pool_info.key,
pool_stake_authority_info.key,
)?;
let mint_authority_bump_seed = check_pool_mint_authority_address(
program_id,
pool_info.key,
pool_mint_authority_info.key,
)?;
check_system_program(system_program_info.key)?;
check_token_program(token_program_info.key)?;
check_stake_program(stake_program_info.key)?;
let pool_seeds = &[
POOL_PREFIX,
vote_account_info.key.as_ref(),
&[pool_bump_seed],
];
let pool_signers = &[&pool_seeds[..]];
let stake_seeds = &[
POOL_STAKE_PREFIX,
pool_info.key.as_ref(),
&[stake_bump_seed],
];
let stake_signers = &[&stake_seeds[..]];
let mint_seeds = &[POOL_MINT_PREFIX, pool_info.key.as_ref(), &[mint_bump_seed]];
let mint_signers = &[&mint_seeds[..]];
let stake_authority_seeds = &[
POOL_STAKE_AUTHORITY_PREFIX,
pool_info.key.as_ref(),
&[stake_authority_bump_seed],
];
let stake_authority_signers = &[&stake_authority_seeds[..]];
let mint_authority_seeds = &[
POOL_MINT_AUTHORITY_PREFIX,
pool_info.key.as_ref(),
&[mint_authority_bump_seed],
];
let mint_authority_signers = &[&mint_authority_seeds[..]];
// create the pool. user has already transferred in rent
let pool_space = SinglePool::size_of();
if !rent.is_exempt(pool_info.lamports(), pool_space) {
return Err(SinglePoolError::WrongRentAmount.into());
}
if pool_info.data_len() != 0 {
return Err(SinglePoolError::PoolAlreadyInitialized.into());
}
invoke_signed(
&system_instruction::allocate(pool_info.key, pool_space as u64),
core::slice::from_ref(pool_info),
pool_signers,
)?;
invoke_signed(
&system_instruction::assign(pool_info.key, program_id),
core::slice::from_ref(pool_info),
pool_signers,
)?;
let mut pool = try_from_slice_unchecked::<SinglePool>(&pool_info.data.borrow())?;
pool.account_type = SinglePoolAccountType::Pool;
pool.vote_account_address = *vote_account_info.key;
borsh::to_writer(&mut pool_info.data.borrow_mut()[..], &pool)?;
// create the pool mint. user has already transferred in rent
let mint_space = spl_token::state::Mint::LEN;
invoke_signed(
&system_instruction::allocate(pool_mint_info.key, mint_space as u64),
core::slice::from_ref(pool_mint_info),
mint_signers,
)?;
invoke_signed(
&system_instruction::assign(pool_mint_info.key, token_program_info.key),
core::slice::from_ref(pool_mint_info),
mint_signers,
)?;
invoke_signed(
&spl_token::instruction::initialize_mint2(
token_program_info.key,
pool_mint_info.key,
pool_mint_authority_info.key,
None,
MINT_DECIMALS,
)?,
core::slice::from_ref(pool_mint_info),
mint_authority_signers,
)?;
// create the pool stake account. user has already transferred in rent plus at
// least the minimum
let minimum_pool_balance = minimum_pool_balance()?;
let stake_space = StakeStateV2::size_of();
let stake_rent_plus_initial = rent
.minimum_balance(stake_space)
.saturating_add(minimum_pool_balance);
if pool_stake_info.lamports() < stake_rent_plus_initial {
return Err(SinglePoolError::WrongRentAmount.into());
}
let authorized = stake::state::Authorized::auto(pool_stake_authority_info.key);
invoke_signed(
&system_instruction::allocate(pool_stake_info.key, stake_space as u64),
core::slice::from_ref(pool_stake_info),
stake_signers,
)?;
invoke_signed(
&system_instruction::assign(pool_stake_info.key, stake_program_info.key),
core::slice::from_ref(pool_stake_info),
stake_signers,
)?;
invoke_signed(
&stake::instruction::initialize_checked(pool_stake_info.key, &authorized),
&[
pool_stake_info.clone(),
rent_info.clone(),
pool_stake_authority_info.clone(),
pool_stake_authority_info.clone(),
],
stake_authority_signers,
)?;
// delegate stake so it activates
invoke_signed(
&stake::instruction::delegate_stake(
pool_stake_info.key,
pool_stake_authority_info.key,
vote_account_info.key,
),
&[
pool_stake_info.clone(),
vote_account_info.clone(),
clock_info.clone(),
stake_history_info.clone(),
stake_config_info.clone(),
pool_stake_authority_info.clone(),
],
stake_authority_signers,
)?;
Ok(())
}
fn process_replenish_pool(program_id: &Pubkey, accounts: &[AccountInfo]) -> ProgramResult {
let account_info_iter = &mut accounts.iter();
let vote_account_info = next_account_info(account_info_iter)?;
let pool_info = next_account_info(account_info_iter)?;
let pool_stake_info = next_account_info(account_info_iter)?;
let pool_onramp_info = next_account_info(account_info_iter)?;
let pool_stake_authority_info = next_account_info(account_info_iter)?;
let clock_info = next_account_info(account_info_iter)?;
let clock = &Clock::from_account_info(clock_info)?;
let stake_history_info = next_account_info(account_info_iter)?;
let stake_config_info = next_account_info(account_info_iter)?;
let stake_program_info = next_account_info(account_info_iter)?;
let rent = Rent::get()?;
let stake_history = &StakeHistorySysvar(clock.epoch);
check_vote_account(vote_account_info)?;
check_pool_address(program_id, vote_account_info.key, pool_info.key)?;
SinglePool::from_account_info(pool_info, program_id)?;
check_pool_stake_address(program_id, pool_info.key, pool_stake_info.key)?;
check_pool_onramp_address(program_id, pool_info.key, pool_onramp_info.key)?;
let stake_authority_bump_seed = check_pool_stake_authority_address(
program_id,
pool_info.key,
pool_stake_authority_info.key,
)?;
check_stake_program(stake_program_info.key)?;
let minimum_delegation = stake::tools::get_minimum_delegation()?;
// we expect these numbers to be equal but get them separately in case of future changes
let pool_rent_exempt_reserve = rent.minimum_balance(pool_stake_info.data_len());
let onramp_rent_exempt_reserve = rent.minimum_balance(pool_onramp_info.data_len());
// get main pool account, we require it to be fully active for most operations
let (_, pool_stake_state) = get_stake_state(pool_stake_info)?;
let pool_stake_status = pool_stake_state
.delegation
.stake_activating_and_deactivating_v2(
clock.epoch,
stake_history,
PERPETUAL_NEW_WARMUP_COOLDOWN_RATE_EPOCH,
);
let pool_stake_is_fully_active = is_stake_fully_active(&pool_stake_status);
// get on-ramp and its status. we have to match because unlike the main account it could be Initialized
// if it doesnt exist, it must first be created with InitializePoolOnRamp
let (option_onramp_status, onramp_deactivation_epoch) =
match deserialize_stake(pool_onramp_info) {
Ok(StakeStateV2::Initialized(_)) => (None, u64::MAX),
Ok(StakeStateV2::Stake(_, stake, _)) => (
Some(stake.delegation.stake_activating_and_deactivating_v2(
clock.epoch,
stake_history,
PERPETUAL_NEW_WARMUP_COOLDOWN_RATE_EPOCH,
)),
stake.delegation.deactivation_epoch,
),
_ => return Err(SinglePoolError::OnRampDoesntExist.into()),
};
let stake_authority_seeds = &[
POOL_STAKE_AUTHORITY_PREFIX,
pool_info.key.as_ref(),
&[stake_authority_bump_seed],
];
let stake_authority_signers = &[&stake_authority_seeds[..]];
// if pool stake is deactivating this epoch, or has fully deactivated, delegate it
// this may happen as a result of `DeactivateDelinquent`
if pool_stake_state.delegation.deactivation_epoch == clock.epoch
|| (pool_stake_state.delegation.deactivation_epoch < clock.epoch
&& pool_stake_status.effective == 0)
{
invoke_signed(
&stake::instruction::delegate_stake(
pool_stake_info.key,
pool_stake_authority_info.key,
vote_account_info.key,
),
&[
pool_stake_info.clone(),
vote_account_info.clone(),
clock_info.clone(),
stake_history_info.clone(),
stake_config_info.clone(),
pool_stake_authority_info.clone(),
],
stake_authority_signers,
)?;
}
// if pool is fully active, we can move stake to the main account and lamports to the on-ramp
if pool_stake_is_fully_active {
// determine excess lamports in the main account before we touch either of them
let pool_excess_lamports = pool_stake_info
.lamports()
.saturating_sub(pool_stake_state.delegation.stake)
.saturating_sub(pool_rent_exempt_reserve);
// if the on-ramp is fully active, move its stake to the main pool account
if let Some(ref onramp_status) = option_onramp_status {
if is_stake_fully_active(onramp_status) {
invoke_signed(
&stake::instruction::move_stake(
pool_onramp_info.key,
pool_stake_info.key,
pool_stake_authority_info.key,
onramp_status.effective,
),
&[
pool_onramp_info.clone(),
pool_stake_info.clone(),
pool_stake_authority_info.clone(),
],
stake_authority_signers,
)?;
}
}
// if there are any excess lamports to move to the on-ramp, move them
if pool_excess_lamports > 0 {
invoke_signed(
&stake::instruction::move_lamports(
pool_stake_info.key,
pool_onramp_info.key,
pool_stake_authority_info.key,
pool_excess_lamports,
),
&[
pool_stake_info.clone(),
pool_onramp_info.clone(),
pool_stake_authority_info.clone(),
],
stake_authority_signers,
)?;
}
// finally, delegate the on-ramp account if it has sufficient undelegated lamports
// if activating, this means more lamports than the current activating delegation
// in all cases, this means having enough to cover the minimum delegation
// we do nothing if partially active. we know it cannot be fully active because of MoveStake
let onramp_non_rent_lamports = pool_onramp_info
.lamports()
.saturating_sub(onramp_rent_exempt_reserve);
let must_delegate_onramp = match option_onramp_status.unwrap_or_default() {
// activating
StakeActivationStatus {
effective: 0,
activating,
deactivating: 0,
} if activating > 0 => {
onramp_non_rent_lamports >= minimum_delegation
&& onramp_non_rent_lamports > activating
}
// inactive, or deactivating this epoch due to DeactivateDelinquent
// effective may be nonzero here because we are using the status prior to MoveStake
StakeActivationStatus {
effective: _,
activating: 0,
deactivating,
} if deactivating == 0 || onramp_deactivation_epoch == clock.epoch => {
onramp_non_rent_lamports >= minimum_delegation
}
// partially active, partially inactive, or some state beyond mortal reckoning
_ => false,
};
if must_delegate_onramp {
invoke_signed(
&stake::instruction::delegate_stake(
pool_onramp_info.key,
pool_stake_authority_info.key,
vote_account_info.key,
),
&[
pool_onramp_info.clone(),
vote_account_info.clone(),
clock_info.clone(),
stake_history_info.clone(),
stake_config_info.clone(),
pool_stake_authority_info.clone(),
],
stake_authority_signers,
)?;
}
}
Ok(())
}
fn process_deposit_stake(program_id: &Pubkey, accounts: &[AccountInfo]) -> ProgramResult {
let account_info_iter = &mut accounts.iter();
let pool_info = next_account_info(account_info_iter)?;
let pool_stake_info = next_account_info(account_info_iter)?;
let pool_onramp_info = next_account_info(account_info_iter)?;
let pool_mint_info = next_account_info(account_info_iter)?;
let pool_stake_authority_info = next_account_info(account_info_iter)?;
let pool_mint_authority_info = next_account_info(account_info_iter)?;
let user_stake_info = next_account_info(account_info_iter)?;
let user_token_account_info = next_account_info(account_info_iter)?;
let user_lamport_account_info = next_account_info(account_info_iter)?;
let clock_info = next_account_info(account_info_iter)?;
let clock = &Clock::from_account_info(clock_info)?;
let stake_history_info = next_account_info(account_info_iter)?;
let token_program_info = next_account_info(account_info_iter)?;
let stake_program_info = next_account_info(account_info_iter)?;
let rent = &Rent::get()?;
let stake_history = &StakeHistorySysvar(clock.epoch);
SinglePool::from_account_info(pool_info, program_id)?;