-
Notifications
You must be signed in to change notification settings - Fork 44
/
state.rs
1354 lines (1210 loc) · 49 KB
/
state.rs
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
// SPDX-FileCopyrightText: 2021 Chorus One AG
// SPDX-License-Identifier: GPL-3.0
//! State transition types
use std::ops::Range;
use serde::Serialize;
use borsh::{BorshDeserialize, BorshSchema, BorshSerialize};
use solana_program::borsh::get_instance_packed_len;
use solana_program::clock::Clock;
use solana_program::{
account_info::AccountInfo, clock::Epoch, entrypoint::ProgramResult, msg,
program_error::ProgramError, program_pack::Pack, pubkey::Pubkey, rent::Rent, sysvar::Sysvar,
};
use spl_token::state::Mint;
use crate::error::LidoError;
use crate::logic::get_reserve_available_balance;
use crate::metrics::Metrics;
use crate::processor::StakeType;
use crate::token::{self, Lamports, Rational, StLamports};
use crate::util::serialize_b58;
use crate::{
account_map::{AccountMap, AccountSet, EntryConstantSize, PubkeyAndEntry},
MINIMUM_STAKE_ACCOUNT_BALANCE, MINT_AUTHORITY, RESERVE_ACCOUNT, STAKE_AUTHORITY,
};
use crate::{REWARDS_WITHDRAW_AUTHORITY, VALIDATOR_STAKE_ACCOUNT, VALIDATOR_UNSTAKE_ACCOUNT};
pub const LIDO_VERSION: u8 = 0;
/// Size of a serialized `Lido` struct excluding validators and maintainers.
///
/// To update this, run the tests and replace the value here with the test output.
pub const LIDO_CONSTANT_SIZE: usize = 357;
pub const VALIDATOR_CONSTANT_SIZE: usize = 89;
pub type Validators = AccountMap<Validator>;
impl Validators {
pub fn iter_active(&self) -> impl Iterator<Item = &Validator> {
self.iter_entries().filter(|&v| v.active)
}
pub fn iter_active_entries(&self) -> impl Iterator<Item = &PubkeyAndEntry<Validator>> {
self.entries.iter().filter(|&v| v.entry.active)
}
}
pub type Maintainers = AccountSet;
impl EntryConstantSize for Validator {
const SIZE: usize = VALIDATOR_CONSTANT_SIZE;
}
impl EntryConstantSize for () {
const SIZE: usize = 0;
}
/// The exchange rate used for deposits and rewards distribution.
///
/// The exchange rate of SOL to stSOL is determined by the SOL balance of
/// Solido, and the total stSOL supply: every stSOL represents a share of
/// ownership of the SOL pool.
///
/// Deposits do not change the exchange rate: we mint new stSOL proportional to
/// the amount deposited, to keep the exchange rate constant. However, rewards
/// *do* change the exchange rate. This is how rewards get distributed to stSOL
/// holders without any transactions: their stSOL will be worth more SOL.
///
/// Let's call an increase of the SOL balance that mints a proportional amount
/// of stSOL a *deposit*, and an increase of the SOL balance that does not mint
/// any stSOL a *donation*. The ordering of donations relative to one another is
/// not relevant, and the order of deposits relative to one another is not
/// relevant either. But the order of deposits relative to donations is: if you
/// deposit before a donation, you get more stSOL than when you deposit after.
/// If you deposit before, you benefit from the reward, if you deposit after,
/// you do not. In formal terms, *deposit and and donate do not commute*.
///
/// This presents a problem if we want to do rewards distribution in multiple
/// steps (one step per validator). Reward distribution is a combination of a
/// donation (the observed rewards minus fees), and a deposit (the fees, which
/// get paid as stSOL). Because deposit and donate do not commute, different
/// orders of observing validator rewards would lead to different outcomes. We
/// don't want that.
///
/// To resolve this, we use a fixed exchange rate, and update it once per epoch.
/// This means that a donation no longer changes the exchange rate (not
/// instantly at least). That means that we can observe validator rewards in any
/// order we like. A different way of thinking about this, is that by fixing
/// the exchange rate for the duration of the epoch, all the different ways of
/// ordering donations and deposits have the same outcome, so every sequence of
/// deposits and donations is equivalent to one where they all happen
/// simultaneously at the start of the epoch. Time within an epoch ceases to
/// exist, the only thing relevant is the epoch.
///
/// When we update the exchange rate, we set the values to the balance that we
/// inferred by tracking all changes. This does not include any external
/// modifications (validation rewards paid into stake accounts) that were not
/// yet observed at the time of the update.
///
/// When we observe the actual validator balance in `WithdrawInactiveStake`, the
/// difference between the tracked balance and the observed balance, is a
/// donation that will be returned to the reserve account.
///
/// We collect the rewards accumulated by a validator with the
/// `CollectValidatorFee` instruction. This function distributes the accrued
/// rewards paid to the Solido program (as we enforce that 100% of the fees goes
/// to the Solido program).
///
/// `CollectValidatorFee` is blocked in a given epoch, until we update the
/// exchange rate in that epoch. Validation rewards are distributed at the start
/// of the epoch. This means that in epoch `i`:
///
/// 1. `UpdateExchangeRate` updates the exchange rate to what it was at the end
/// of epoch `i - 1`.
/// 2. `CollectValidatorFee` runs for every validator, and observes the
/// rewards. Deposits (including those for fees) in epoch `i` therefore use
/// the exchange rate at the end of epoch `i - 1`, so deposits in epoch `i`
/// do not benefit from rewards received in epoch `i`.
/// 3. Epoch `i + 1` starts, and validation rewards are paid into validator's
/// vote accounts.
/// 4. `UpdateExchangeRate` updates the exchange rate to what it was at the end
/// of epoch `i`. Everybody who deposited in epoch `i` (users, as well as fee
/// recipients) now benefit from the validation rewards received in epoch `i`.
/// 5. Etc.
#[repr(C)]
#[derive(
Clone, Debug, Default, BorshDeserialize, BorshSerialize, BorshSchema, Eq, PartialEq, Serialize,
)]
pub struct ExchangeRate {
/// The epoch in which we last called `UpdateExchangeRate`.
pub computed_in_epoch: Epoch,
/// The amount of stSOL that existed at that time.
pub st_sol_supply: StLamports,
/// The amount of SOL we managed at that time, according to our internal
/// bookkeeping, so excluding the validation rewards paid at the start of
/// epoch `computed_in_epoch`.
pub sol_balance: Lamports,
}
impl ExchangeRate {
/// Convert SOL to stSOL.
pub fn exchange_sol(&self, amount: Lamports) -> token::Result<StLamports> {
// The exchange rate starts out at 1:1, if there are no deposits yet.
// If we minted stSOL but there is no SOL, then also assume a 1:1 rate.
if self.st_sol_supply == StLamports(0) || self.sol_balance == Lamports(0) {
return Ok(StLamports(amount.0));
}
let rate = Rational {
numerator: self.st_sol_supply.0,
denominator: self.sol_balance.0,
};
// The result is in Lamports, because the type system considers Rational
// dimensionless, but in this case `rate` has dimensions stSOL/SOL, so
// we need to re-wrap the result in the right type.
(amount * rate).map(|x| StLamports(x.0))
}
/// Convert stSOL to SOL.
pub fn exchange_st_sol(&self, amount: StLamports) -> Result<Lamports, LidoError> {
// If there is no stSOL in existence, it cannot be exchanged.
if self.st_sol_supply == StLamports(0) {
msg!("Cannot exchange stSOL for SOL, because no stSTOL has been minted.");
return Err(LidoError::InvalidAmount);
}
let rate = Rational {
numerator: self.sol_balance.0,
denominator: self.st_sol_supply.0,
};
// The result is in StLamports, because the type system considers Rational
// dimensionless, but in this case `rate` has dimensions SOL/stSOL, so
// we need to re-wrap the result in the right type.
Ok((amount * rate).map(|x| Lamports(x.0))?)
}
}
#[repr(C)]
#[derive(
Clone, Debug, Default, BorshDeserialize, BorshSerialize, BorshSchema, Eq, PartialEq, Serialize,
)]
pub struct Lido {
/// Version number for the Lido
pub lido_version: u8,
/// Manager of the Lido program, able to execute administrative functions
#[serde(serialize_with = "serialize_b58")]
pub manager: Pubkey,
/// The SPL Token mint address for stSOL.
#[serde(serialize_with = "serialize_b58")]
pub st_sol_mint: Pubkey,
/// Exchange rate to use when depositing.
pub exchange_rate: ExchangeRate,
/// Bump seeds for signing messages on behalf of the authority
pub sol_reserve_account_bump_seed: u8,
pub stake_authority_bump_seed: u8,
pub mint_authority_bump_seed: u8,
pub rewards_withdraw_authority_bump_seed: u8,
/// How rewards are distributed.
pub reward_distribution: RewardDistribution,
/// Accounts of the fee recipients.
pub fee_recipients: FeeRecipients,
/// Metrics for informational purposes.
///
/// Metrics are only written to, no program logic should depend on these values.
/// An off-chain program can load a snapshot of the `Lido` struct, and expose
/// these metrics.
pub metrics: Metrics,
/// Map of enrolled validators, maps their vote account to `Validator` details.
pub validators: Validators,
/// The set of maintainers.
///
/// Maintainers are granted low security risk privileges. Maintainers are
/// expected to run the maintenance daemon, that invokes the maintenance
/// operations. These are gated on the signer being present in this set.
/// In the future we plan to make maintenance operations callable by anybody.
pub maintainers: Maintainers,
}
impl Lido {
/// Calculates the total size of Lido given two variables: `max_validators`
/// and `max_maintainers`, the maximum number of maintainers and validators,
/// respectively. It creates default structures for both and sum its sizes
/// with Lido's constant size.
pub fn calculate_size(max_validators: u32, max_maintainers: u32) -> usize {
let lido_instance = Lido {
validators: Validators::new_fill_default(max_validators),
maintainers: Maintainers::new_fill_default(max_maintainers),
..Default::default()
};
get_instance_packed_len(&lido_instance).unwrap()
}
/// Confirm that the given account is Solido's stSOL mint.
pub fn check_mint_is_st_sol_mint(&self, mint_account_info: &AccountInfo) -> ProgramResult {
if &self.st_sol_mint != mint_account_info.key {
msg!(
"Expected to find our stSOL mint ({}), but got {} instead.",
self.st_sol_mint,
mint_account_info.key
);
return Err(LidoError::InvalidStSolAccount.into());
}
Ok(())
}
/// Confirm that the given account is an SPL token account with our stSOL mint as mint.
pub fn check_is_st_sol_account(&self, token_account_info: &AccountInfo) -> ProgramResult {
if token_account_info.owner != &spl_token::id() {
msg!(
"Expected SPL token account to be owned by {}, but it's owned by {} instead.",
spl_token::id(),
token_account_info.owner
);
return Err(LidoError::InvalidStSolAccountOwner.into());
}
let token_account =
match spl_token::state::Account::unpack_from_slice(&token_account_info.data.borrow()) {
Ok(account) => account,
Err(..) => {
msg!(
"Expected an SPL token account at {}.",
token_account_info.key
);
return Err(LidoError::InvalidStSolAccount.into());
}
};
if token_account.mint != self.st_sol_mint {
msg!(
"Expected mint of {} to be our stSOL mint ({}), but found {}.",
token_account_info.key,
self.st_sol_mint,
token_account.mint,
);
return Err(LidoError::InvalidFeeRecipient.into());
}
Ok(())
}
/// Checks if the passed manager is the same as the one stored in the state
pub fn check_manager(&self, manager: &AccountInfo) -> ProgramResult {
if &self.manager != manager.key {
msg!("Invalid manager, not the same as the one stored in state");
return Err(LidoError::InvalidManager.into());
}
Ok(())
}
/// Checks if the passed maintainer belong to the list of maintainers
pub fn check_maintainer(&self, maintainer: &AccountInfo) -> ProgramResult {
if !&self.maintainers.entries.contains(&PubkeyAndEntry {
pubkey: *maintainer.key,
entry: (),
}) {
msg!(
"Invalid maintainer, account {} is not present in the maintainers list.",
maintainer.key
);
return Err(LidoError::InvalidMaintainer.into());
}
Ok(())
}
/// Check if the passed treasury fee account is the one configured.
///
/// Also confirm that the recipient is still an stSOL account.
pub fn check_treasury_fee_st_sol_account(&self, st_sol_account: &AccountInfo) -> ProgramResult {
if &self.fee_recipients.treasury_account != st_sol_account.key {
msg!("Invalid treasury fee stSOL account, not the same as the one stored in state.");
return Err(LidoError::InvalidFeeRecipient.into());
}
self.check_is_st_sol_account(st_sol_account)
}
/// Check if the passed developer fee account is the one configured.
///
/// Also confirm that the recipient is still an stSOL account.
pub fn check_developer_fee_st_sol_account(
&self,
st_sol_account: &AccountInfo,
) -> ProgramResult {
if &self.fee_recipients.developer_account != st_sol_account.key {
msg!("Invalid developer fee stSOL account, not the same as the one stored in state.");
return Err(LidoError::InvalidFeeRecipient.into());
}
self.check_is_st_sol_account(st_sol_account)
}
/// Return the address of the reserve account, the account where SOL gets
/// deposited into.
pub fn get_reserve_account(
&self,
program_id: &Pubkey,
solido_address: &Pubkey,
) -> Result<Pubkey, ProgramError> {
Pubkey::create_program_address(
&[
&solido_address.to_bytes()[..],
RESERVE_ACCOUNT,
&[self.sol_reserve_account_bump_seed],
],
program_id,
)
.map_err(|_| LidoError::InvalidReserveAccount.into())
}
/// Confirm that the reserve account belongs to this Lido instance, return
/// the reserve address.
pub fn check_reserve_account(
&self,
program_id: &Pubkey,
solido_address: &Pubkey,
reserve_account_info: &AccountInfo,
) -> Result<Pubkey, ProgramError> {
let reserve_id = self.get_reserve_account(program_id, solido_address)?;
if reserve_id != *reserve_account_info.key {
msg!("Invalid reserve account");
return Err(LidoError::InvalidReserveAccount.into());
}
Ok(reserve_id)
}
/// Return the address of the stake authority, the program-derived address
/// that can sign staking instructions.
pub fn get_stake_authority(
&self,
program_id: &Pubkey,
solido_address: &Pubkey,
) -> Result<Pubkey, ProgramError> {
Pubkey::create_program_address(
&[
&solido_address.to_bytes()[..],
STAKE_AUTHORITY,
&[self.stake_authority_bump_seed],
],
program_id,
)
.map_err(|_| ProgramError::InvalidSeeds)
}
/// Confirm that the stake authority belongs to this Lido instance, return
/// the stake authority address.
pub fn check_stake_authority(
&self,
program_id: &Pubkey,
solido_address: &Pubkey,
stake_authority_account_info: &AccountInfo,
) -> Result<Pubkey, ProgramError> {
let authority = self.get_stake_authority(program_id, solido_address)?;
if &authority != stake_authority_account_info.key {
msg!(
"Invalid stake authority, expected {} but got {}.",
authority,
stake_authority_account_info.key
);
return Err(LidoError::InvalidStakeAuthority.into());
}
Ok(authority)
}
/// Return the address of the rewards withdraw authority, the
/// program-derived address that can sign on behalf of vote accounts.
pub fn get_rewards_withdraw_authority(
&self,
program_id: &Pubkey,
solido_address: &Pubkey,
) -> Result<Pubkey, ProgramError> {
Pubkey::create_program_address(
&[
&solido_address.to_bytes()[..],
REWARDS_WITHDRAW_AUTHORITY,
&[self.rewards_withdraw_authority_bump_seed],
],
program_id,
)
.map_err(|_| ProgramError::InvalidSeeds)
}
/// Confirm that the rewards withdraw authority belongs to this Lido
/// instance, return the rewards authority address.
pub fn check_rewards_withdraw_authority(
&self,
program_id: &Pubkey,
solido_address: &Pubkey,
rewards_withdraw_authority_account_info: &AccountInfo,
) -> Result<Pubkey, ProgramError> {
let authority = self.get_rewards_withdraw_authority(program_id, solido_address)?;
if &authority != rewards_withdraw_authority_account_info.key {
msg!(
"Invalid rewards withdraw authority, expected {} but got {}.",
authority,
rewards_withdraw_authority_account_info.key
);
return Err(LidoError::InvalidRewardsWithdrawAuthority.into());
}
Ok(authority)
}
pub fn get_mint_authority(
&self,
program_id: &Pubkey,
solido_address: &Pubkey,
) -> Result<Pubkey, ProgramError> {
Pubkey::create_program_address(
&[
&solido_address.to_bytes()[..],
MINT_AUTHORITY,
&[self.mint_authority_bump_seed],
],
program_id,
)
.map_err(|_| ProgramError::InvalidSeeds)
}
/// Confirm that the amount to stake is more than the minimum stake amount,
/// and that we have sufficient SOL in the reserve.
pub fn check_can_stake_amount(
&self,
reserve: &AccountInfo,
sysvar_rent: &AccountInfo,
amount: Lamports,
) -> Result<(), ProgramError> {
if amount < MINIMUM_STAKE_ACCOUNT_BALANCE {
msg!("Trying to stake less than the minimum stake account balance.");
msg!(
"Need as least {} but got {}.",
MINIMUM_STAKE_ACCOUNT_BALANCE,
amount
);
return Err(LidoError::InvalidAmount.into());
}
let rent: Rent = Rent::from_account_info(sysvar_rent)?;
let available_reserve_amount = get_reserve_available_balance(&rent, reserve)?;
if amount > available_reserve_amount {
msg!(
"The requested amount {} is greater than the available amount {}, \
considering rent-exemption",
amount,
available_reserve_amount
);
return Err(LidoError::AmountExceedsReserve.into());
}
Ok(())
}
/// Confirm that `stake_account` is the account at the given seed for the validator.
///
/// Returns the bump seed for the derived address.
pub fn check_stake_account(
program_id: &Pubkey,
solido_address: &Pubkey,
validator: &PubkeyAndEntry<Validator>,
stake_account_seed: u64,
stake_account: &AccountInfo,
authority: &[u8],
) -> Result<u8, ProgramError> {
let (stake_addr, stake_addr_bump_seed) = validator
.find_stake_account_address_with_authority(
program_id,
solido_address,
authority,
stake_account_seed,
);
if &stake_addr != stake_account.key {
msg!(
"The derived stake address for seed {} is {}, \
but the instruction received {} instead.",
stake_account_seed,
stake_addr,
stake_account.key,
);
msg!(
"Note: this can happen during normal operation when instructions \
race, and one updates the validator's seeds before the other executes."
);
return Err(LidoError::InvalidStakeAccount.into());
}
Ok(stake_addr_bump_seed)
}
pub fn save(&self, account: &AccountInfo) -> ProgramResult {
// NOTE: If you ended up here because the tests are failing because the
// runtime complained that an account's size was modified by a program
// that wasn't its owner, double check that the name passed to
// ProgramTest matches the name of the crate.
BorshSerialize::serialize(self, &mut *account.data.borrow_mut())?;
Ok(())
}
/// Compute the total amount of SOL managed by this instance.
///
/// This includes staked as well as non-staked SOL. It excludes SOL in the
/// reserve that effectively locked because it is needed to keep the reserve
/// rent-exempt.
///
/// The computation is based on the amount of SOL per validator that we track
/// ourselves, so if there are any unobserved rewards in the stake accounts,
/// these will not be included.
pub fn get_sol_balance(
&self,
rent: &Rent,
reserve: &AccountInfo,
) -> Result<Lamports, LidoError> {
let effective_reserve_balance = get_reserve_available_balance(rent, reserve)?;
// The remaining SOL managed is all in stake accounts.
let validator_balance: token::Result<Lamports> = self
.validators
.iter_entries()
.map(|v| v.stake_accounts_balance)
.sum();
let result = validator_balance.and_then(|s| s + effective_reserve_balance)?;
Ok(result)
}
/// Return the total amount of stSOL in existence.
///
/// The total is the amount minted so far, plus any unminted rewards that validators
/// are entitled to, but haven’t claimed yet.
pub fn get_st_sol_supply(&self, st_sol_mint: &AccountInfo) -> Result<StLamports, ProgramError> {
self.check_mint_is_st_sol_mint(st_sol_mint)?;
let st_sol_mint = Mint::unpack_from_slice(&st_sol_mint.data.borrow())?;
let minted_supply = StLamports(st_sol_mint.supply);
let credit: token::Result<StLamports> =
self.validators.iter_entries().map(|v| v.fee_credit).sum();
let result = credit.and_then(|s| s + minted_supply)?;
Ok(result)
}
pub fn check_exchange_rate_last_epoch(
&self,
clock: &Clock,
method: &str,
) -> Result<(), LidoError> {
if self.exchange_rate.computed_in_epoch < clock.epoch {
msg!(
"The exchange rate is outdated, it was last computed in epoch {}, \
but now it is epoch {}.",
self.exchange_rate.computed_in_epoch,
clock.epoch,
);
msg!("Please call UpdateExchangeRate before calling {}.", method);
return Err(LidoError::ExchangeRateNotUpdatedInThisEpoch);
}
Ok(())
}
}
#[repr(C)]
#[derive(Clone, Debug, Eq, PartialEq, BorshDeserialize, BorshSerialize, BorshSchema, Serialize)]
pub struct Validator {
/// Fees in stSOL that the validator is entitled too, but hasn't claimed yet.
pub fee_credit: StLamports,
/// SPL token account denominated in stSOL to transfer fees to when claiming them.
#[serde(serialize_with = "serialize_b58")]
pub fee_address: Pubkey,
/// Seeds for active stake accounts.
pub stake_seeds: SeedRange,
/// Seeds for inactive stake accounts.
pub unstake_seeds: SeedRange,
/// Sum of the balances of the stake accounts and unstake accounts.
pub stake_accounts_balance: Lamports,
/// Sum of the balances of the unstake accounts.
pub unstake_accounts_balance: Lamports,
/// Controls if a validator is allowed to have new stake deposits.
/// When removing a validator, this flag should be set to `false`.
pub active: bool,
}
#[repr(C)]
#[derive(
Clone, Debug, Default, Eq, PartialEq, BorshDeserialize, BorshSerialize, BorshSchema, Serialize,
)]
pub struct SeedRange {
/// Start (inclusive) of the seed range for stake accounts.
///
/// When we stake deposited SOL, we take it out of the reserve account, and
/// transfer it to a stake account. The stake account address is a derived
/// address derived from a.o. the validator address, and a seed. After
/// creation, it takes one or more epochs for the stake to become fully
/// activated. While stake is activating, we may want to activate additional
/// stake, so we need a new stake account. Therefore we have a range of
/// seeds. When we need a new stake account, we bump `end`. When the account
/// with seed `begin` is 100% active, we deposit that stake account into the
/// pool and bump `begin`. Accounts are not reused.
///
/// The program enforces that creating new stake accounts is only allowed at
/// the `end` seed, and depositing active stake is only allowed from the
/// `begin` seed. This ensures that maintainers don’t race and accidentally
/// stake more to this validator than intended. If the seed has changed
/// since the instruction was created, the transaction fails.
///
/// When we unstake SOL, we follow an analogous symmetric mechanism. We
/// split the validator's stake in two, and retrieve the funds of the second
/// to the reserve account where it can be re-staked.
pub begin: u64,
/// End (exclusive) of the seed range for stake accounts.
pub end: u64,
}
impl IntoIterator for &SeedRange {
type Item = u64;
type IntoIter = Range<u64>;
fn into_iter(self) -> Self::IntoIter {
Range {
start: self.begin,
end: self.end,
}
}
}
impl Validator {
pub fn new(fee_address: Pubkey) -> Validator {
Validator {
fee_address,
..Default::default()
}
}
/// Return the balance in only the stake accounts, excluding the unstake accounts.
pub fn effective_stake_balance(&self) -> Lamports {
(self.stake_accounts_balance - self.unstake_accounts_balance)
.expect("Unstake balance cannot exceed the validator's total stake balance.")
}
}
impl Default for Validator {
fn default() -> Self {
Validator {
fee_address: Pubkey::default(),
fee_credit: StLamports(0),
stake_seeds: SeedRange { begin: 0, end: 0 },
unstake_seeds: SeedRange { begin: 0, end: 0 },
stake_accounts_balance: Lamports(0),
unstake_accounts_balance: Lamports(0),
active: true,
}
}
}
impl Validator {
pub fn has_stake_accounts(&self) -> bool {
self.stake_seeds.begin != self.stake_seeds.end
}
pub fn has_unstake_accounts(&self) -> bool {
self.unstake_seeds.begin != self.unstake_seeds.end
}
pub fn check_can_be_removed(&self) -> Result<(), LidoError> {
if self.active {
return Err(LidoError::ValidatorIsStillActive);
}
if self.fee_credit != StLamports(0) {
return Err(LidoError::ValidatorHasUnclaimedCredit);
}
if self.has_stake_accounts() {
return Err(LidoError::ValidatorShouldHaveNoStakeAccounts);
}
if self.has_unstake_accounts() {
return Err(LidoError::ValidatorShouldHaveNoUnstakeAccounts);
}
// If not, this is a bug.
assert_eq!(self.stake_accounts_balance, Lamports(0));
Ok(())
}
pub fn show_removed_error_msg(error: &Result<(), LidoError>) {
if let Err(err) = error {
match err {
LidoError::ValidatorIsStillActive => {
msg!(
"Refusing to remove validator because it is still active, deactivate it first."
);
}
LidoError::ValidatorHasUnclaimedCredit => {
msg!(
"Validator still has tokens to claim. Reclaim tokens before removing the validator"
);
}
LidoError::ValidatorShouldHaveNoStakeAccounts => {
msg!("Refusing to remove validator because it still has stake accounts, unstake them first.");
}
LidoError::ValidatorShouldHaveNoUnstakeAccounts => {
msg!("Refusing to remove validator because it still has unstake accounts, withdraw them first.");
}
_ => {
msg!("Invalid error when removing a validator: shouldn't happen.");
}
}
}
}
}
impl PubkeyAndEntry<Validator> {
pub fn find_stake_account_address_with_authority(
&self,
program_id: &Pubkey,
solido_account: &Pubkey,
authority: &[u8],
seed: u64,
) -> (Pubkey, u8) {
let seeds = [
&solido_account.to_bytes(),
&self.pubkey.to_bytes(),
authority,
&seed.to_le_bytes()[..],
];
Pubkey::find_program_address(&seeds, program_id)
}
pub fn find_stake_account_address(
&self,
program_id: &Pubkey,
solido_account: &Pubkey,
seed: u64,
stake_type: StakeType,
) -> (Pubkey, u8) {
let authority = match stake_type {
StakeType::Stake => VALIDATOR_STAKE_ACCOUNT,
StakeType::Unstake => VALIDATOR_UNSTAKE_ACCOUNT,
};
self.find_stake_account_address_with_authority(program_id, solido_account, authority, seed)
}
}
/// Determines how rewards are split up among these parties, represented as the
/// number of parts of the total. For example, if each party has 1 part, then
/// they all get an equal share of the reward.
#[derive(
Clone, Default, Debug, Eq, PartialEq, BorshSerialize, BorshDeserialize, BorshSchema, Serialize,
)]
pub struct RewardDistribution {
pub treasury_fee: u32,
pub validation_fee: u32,
pub developer_fee: u32,
pub st_sol_appreciation: u32,
}
/// Specifies the fee recipients, accounts that should be created by Lido's minter
#[derive(
Clone, Default, Debug, Eq, PartialEq, BorshSerialize, BorshDeserialize, BorshSchema, Serialize,
)]
pub struct FeeRecipients {
#[serde(serialize_with = "serialize_b58")]
pub treasury_account: Pubkey,
#[serde(serialize_with = "serialize_b58")]
pub developer_account: Pubkey,
}
impl RewardDistribution {
pub fn sum(&self) -> u64 {
// These adds don't overflow because we widen from u32 to u64 first.
self.treasury_fee as u64
+ self.validation_fee as u64
+ self.developer_fee as u64
+ self.st_sol_appreciation as u64
}
pub fn treasury_fraction(&self) -> Rational {
Rational {
numerator: self.treasury_fee as u64,
denominator: self.sum(),
}
}
pub fn validation_fraction(&self) -> Rational {
Rational {
numerator: self.validation_fee as u64,
denominator: self.sum(),
}
}
pub fn developer_fraction(&self) -> Rational {
Rational {
numerator: self.developer_fee as u64,
denominator: self.sum(),
}
}
/// Split the reward according to the distribution defined in this instance.
///
/// Fees are all rounded down, and the remainder goes to stSOL appreciation.
/// This means that the outputs may not sum to the input, even when
/// `st_sol_appreciation` is 0.
///
/// Returns the fee amounts in SOL. stSOL should be minted for those when
/// they get distributed. This acts like a deposit: it is like the fee
/// recipients received their fee in SOL outside of Solido, and then
/// deposited it. The remaining SOL, which is not taken as a fee, acts as a
/// donation to the pool, and makes the SOL value of stSOL go up. It is not
/// included in the output, as nothing needs to be done to handle it.
pub fn split_reward(&self, amount: Lamports, num_validators: u64) -> token::Result<Fees> {
use std::ops::Add;
let treasury_amount = (amount * self.treasury_fraction())?;
let developer_amount = (amount * self.developer_fraction())?;
// The actual amount that goes to validation can be a tiny bit lower
// than the target amount, when the number of validators does not divide
// the target amount. The loss is at most `num_validators` Lamports.
let validation_amount = (amount * self.validation_fraction())?;
let reward_per_validator = (validation_amount / num_validators)?;
// Sanity check: We should not produce more fees than we had to split in
// the first place.
let total_fees = Lamports(0)
.add(treasury_amount)?
.add(developer_amount)?
.add((reward_per_validator * num_validators)?)?;
assert!(total_fees <= amount);
let st_sol_appreciation_amount = (amount - total_fees)?;
let result = Fees {
treasury_amount,
reward_per_validator,
developer_amount,
st_sol_appreciation_amount,
};
Ok(result)
}
}
/// The result of [`RewardDistribution::split_reward`].
///
/// It contains only the fees. The amount that goes to stSOL value appreciation
/// is implicitly the remainder.
#[derive(Debug, PartialEq, Eq)]
pub struct Fees {
pub treasury_amount: Lamports,
pub reward_per_validator: Lamports,
pub developer_amount: Lamports,
/// Remainder of the reward.
///
/// This is not a fee, and it is not paid out explicitly, but when summed
/// with the other fields in this struct, that totals the input amount.
pub st_sol_appreciation_amount: Lamports,
}
#[cfg(test)]
mod test_lido {
use super::*;
use solana_program::program_error::ProgramError;
#[test]
fn test_account_map_required_bytes_relates_to_maximum_entries() {
for buffer_size in 0..8_000 {
let max_entries = Validators::maximum_entries(buffer_size);
let needed_size = Validators::required_bytes(max_entries);
assert!(
needed_size <= buffer_size || max_entries == 0,
"Buffer of len {} can fit {} validators which need {} bytes.",
buffer_size,
max_entries,
needed_size,
);
let max_entries = Maintainers::maximum_entries(buffer_size);
let needed_size = Maintainers::required_bytes(max_entries);
assert!(
needed_size <= buffer_size || max_entries == 0,
"Buffer of len {} can fit {} maintainers which need {} bytes.",
buffer_size,
max_entries,
needed_size,
);
}
}
#[test]
fn test_validators_size() {
let validator = get_instance_packed_len(&Validator::default()).unwrap();
assert_eq!(validator, Validator::SIZE);
let one_len = get_instance_packed_len(&Validators::new_fill_default(1)).unwrap();
let two_len = get_instance_packed_len(&Validators::new_fill_default(2)).unwrap();
assert_eq!(one_len, Validators::required_bytes(1));
assert_eq!(two_len, Validators::required_bytes(2));
assert_eq!(
two_len - one_len,
std::mem::size_of::<Pubkey>() + Validator::SIZE
);
}
#[test]
fn test_lido_constant_size() {
// The minimal size of the struct is its size without any validators and
// maintainers.
let minimal = Lido::default();
let mut data = Vec::new();
BorshSerialize::serialize(&minimal, &mut data).unwrap();
let num_entries = 0;
let size_validators = Validators::required_bytes(num_entries);
let size_maintainers = Maintainers::required_bytes(num_entries);
assert_eq!(
data.len() - size_validators - size_maintainers,
LIDO_CONSTANT_SIZE
);
}
#[test]
fn test_lido_serialization_roundtrips() {
use solana_sdk::borsh::try_from_slice_unchecked;
let mut validators = Validators::new(10_000);
validators
.add(Pubkey::new_unique(), Validator::new(Pubkey::new_unique()))
.unwrap();
let maintainers = Maintainers::new(1);
let lido = Lido {
lido_version: 0,
manager: Pubkey::new_unique(),
st_sol_mint: Pubkey::new_unique(),
exchange_rate: ExchangeRate {
computed_in_epoch: 11,
sol_balance: Lamports(13),
st_sol_supply: StLamports(17),
},
sol_reserve_account_bump_seed: 1,
stake_authority_bump_seed: 2,
mint_authority_bump_seed: 3,
rewards_withdraw_authority_bump_seed: 4,
reward_distribution: RewardDistribution {
treasury_fee: 2,
validation_fee: 3,