1use crate::{
21 asset,
22 election_size_tracker::StaticTracker,
23 log,
24 session_rotation::{self, Eras, Rotator},
25 slashing::OffenceRecord,
26 weights::WeightInfo,
27 BalanceOf, EraRewardPoints, Exposure, Forcing, LedgerIntegrityState, MaxNominationsOf,
28 Nominations, NominationsQuota, PositiveImbalanceOf, PotAccountProvider, RewardDestination,
29 RewardKind, RewardPoint, RewardPot, SnapshotStatus, StakingLedger, ValidatorPrefs, STAKING_ID,
30};
31use alloc::{boxed::Box, vec, vec::Vec};
32use frame_election_provider_support::{
33 bounds::CountBound, data_provider, DataProviderBounds, ElectionDataProvider, ElectionProvider,
34 PageIndex, ScoreProvider, SortedListProvider, VoteWeight, VoterOf,
35};
36use frame_support::{
37 defensive,
38 dispatch::WithPostDispatchInfo,
39 pallet_prelude::*,
40 traits::{
41 fungible::Mutate as FunMutate, tokens::Preservation, Defensive, DefensiveSaturating, Get,
42 Imbalance, InspectLockableCurrency, LockableCurrency, OnUnbalanced,
43 },
44 weights::Weight,
45 StorageDoubleMap,
46};
47use frame_system::{pallet_prelude::BlockNumberFor, RawOrigin};
48use pallet_staking_async_rc_client::{self as rc_client};
49use sp_runtime::{
50 traits::{CheckedAdd, Saturating, StaticLookup, Zero},
51 ArithmeticError, DispatchResult, Perbill,
52};
53use sp_staking::{
54 currency_to_vote::CurrencyToVote,
55 EraIndex, OnStakingUpdate, Page, ServiceKind, SessionIndex, Stake, StakerRewardCalculator,
56 StakingAccount::{self, Controller, Stash},
57 StakingInterface,
58};
59
60use super::pallet::*;
61
62#[cfg(feature = "try-runtime")]
63use frame_support::ensure;
64#[cfg(any(test, feature = "try-runtime"))]
65use sp_runtime::TryRuntimeError;
66
67const NPOS_MAX_ITERATIONS_COEFFICIENT: u32 = 2;
74
75impl<T: Config> Pallet<T> {
76 pub(crate) fn min_chilled_bond() -> BalanceOf<T> {
83 MinValidatorBond::<T>::get()
84 .min(MinNominatorBond::<T>::get())
85 .max(asset::existential_deposit::<T>())
86 }
87
88 pub(crate) fn min_validator_bond() -> BalanceOf<T> {
90 MinValidatorBond::<T>::get().max(asset::existential_deposit::<T>())
91 }
92
93 pub(crate) fn min_nominator_bond() -> BalanceOf<T> {
95 MinNominatorBond::<T>::get().max(asset::existential_deposit::<T>())
96 }
97
98 pub fn ledger(account: StakingAccount<T::AccountId>) -> Result<StakingLedger<T>, Error<T>> {
100 StakingLedger::<T>::get(account)
101 }
102
103 pub fn payee(account: StakingAccount<T::AccountId>) -> Option<RewardDestination<T::AccountId>> {
104 StakingLedger::<T>::reward_destination(account)
105 }
106
107 pub fn bonded(stash: &T::AccountId) -> Option<T::AccountId> {
109 StakingLedger::<T>::paired_account(Stash(stash.clone()))
110 }
111
112 pub(crate) fn inspect_bond_state(
119 stash: &T::AccountId,
120 ) -> Result<LedgerIntegrityState, Error<T>> {
121 let hold_or_lock = asset::staked::<T>(&stash)
123 .max(T::OldCurrency::balance_locked(STAKING_ID, &stash).into());
124
125 let controller = <Bonded<T>>::get(stash).ok_or_else(|| {
126 if hold_or_lock == Zero::zero() {
127 Error::<T>::NotStash
128 } else {
129 Error::<T>::BadState
130 }
131 })?;
132
133 match Ledger::<T>::get(controller) {
134 Some(ledger) => {
135 if ledger.stash != *stash {
136 Ok(LedgerIntegrityState::Corrupted)
137 } else {
138 if hold_or_lock != ledger.total {
139 Ok(LedgerIntegrityState::LockCorrupted)
140 } else {
141 Ok(LedgerIntegrityState::Ok)
142 }
143 }
144 },
145 None => Ok(LedgerIntegrityState::CorruptedKilled),
146 }
147 }
148
149 pub fn slashable_balance_of(stash: &T::AccountId) -> BalanceOf<T> {
151 Self::ledger(Stash(stash.clone())).map(|l| l.active).unwrap_or_default()
153 }
154
155 pub fn slashable_balance_of_vote_weight(
157 stash: &T::AccountId,
158 issuance: BalanceOf<T>,
159 ) -> VoteWeight {
160 T::CurrencyToVote::to_vote(Self::slashable_balance_of(stash), issuance)
161 }
162
163 pub fn weight_of_fn() -> Box<dyn Fn(&T::AccountId) -> VoteWeight> {
168 let issuance = asset::total_issuance::<T>();
171 Box::new(move |who: &T::AccountId| -> VoteWeight {
172 Self::slashable_balance_of_vote_weight(who, issuance)
173 })
174 }
175
176 pub fn weight_of(who: &T::AccountId) -> VoteWeight {
178 let issuance = asset::total_issuance::<T>();
179 Self::slashable_balance_of_vote_weight(who, issuance)
180 }
181
182 pub(crate) fn offence_era_of(application_era: EraIndex) -> EraIndex {
184 application_era.saturating_sub(T::SlashDeferDuration::get())
185 }
186
187 pub(crate) fn check_slash_cancelled(
189 era: EraIndex,
190 validator: &T::AccountId,
191 slash_fraction: Perbill,
192 ) -> bool {
193 let cancelled_slashes = CancelledSlashes::<T>::get(&era);
194 cancelled_slashes.iter().any(|(cancelled_validator, cancel_fraction)| {
195 *cancelled_validator == *validator && *cancel_fraction >= slash_fraction
196 })
197 }
198
199 pub(super) fn do_bond_extra(stash: &T::AccountId, additional: BalanceOf<T>) -> DispatchResult {
200 let mut ledger = Self::ledger(StakingAccount::Stash(stash.clone()))?;
201
202 let extra = if Self::is_virtual_staker(stash) {
205 additional
206 } else {
207 additional.min(asset::free_to_stake::<T>(stash))
209 };
210
211 ledger.total = ledger.total.checked_add(&extra).ok_or(ArithmeticError::Overflow)?;
212 ledger.active = ledger.active.checked_add(&extra).ok_or(ArithmeticError::Overflow)?;
213 ensure!(ledger.active >= Self::min_chilled_bond(), Error::<T>::InsufficientBond);
215
216 ledger.update()?;
218 if T::VoterList::contains(stash) {
220 let _ = T::VoterList::on_update(&stash, Self::weight_of(stash));
222 }
223
224 Self::deposit_event(Event::<T>::Bonded { stash: stash.clone(), amount: extra });
225
226 Ok(())
227 }
228
229 fn calculate_earliest_withdrawal_era(active_era: EraIndex) -> EraIndex {
233 let earliest_unlock_era_by_offence_queue = OffenceQueueEras::<T>::get()
235 .as_ref()
236 .and_then(|eras| eras.first())
237 .copied()
238 .unwrap_or(active_era)
240 .saturating_sub(1)
243 .saturating_add(T::BondingDuration::get());
250
251 active_era.min(earliest_unlock_era_by_offence_queue)
257 }
258
259 pub(super) fn do_withdraw_unbonded(controller: &T::AccountId) -> Result<Weight, DispatchError> {
260 let mut ledger = Self::ledger(Controller(controller.clone()))?;
261 let (stash, old_total) = (ledger.stash.clone(), ledger.total);
262 let active_era = Rotator::<T>::active_era();
263
264 if active_era > 1 {
266 Self::ensure_era_slashes_applied(active_era.saturating_sub(1))?;
267 }
268
269 let earliest_era_to_withdraw = Self::calculate_earliest_withdrawal_era(active_era);
270
271 log!(
272 debug,
273 "Withdrawing unbonded stake. Active_era is: {:?} | \
274 Earliest era we can allow withdrawing: {:?}",
275 active_era,
276 earliest_era_to_withdraw
277 );
278
279 ledger = ledger.consolidate_unlocked(earliest_era_to_withdraw);
281
282 let new_total = ledger.total;
283 debug_assert!(
284 new_total <= old_total,
285 "consolidate_unlocked should never increase the total balance of the ledger"
286 );
287
288 let ed = asset::existential_deposit::<T>();
289 let used_weight =
290 if ledger.unlocking.is_empty() && (ledger.active < ed || ledger.active.is_zero()) {
291 Self::kill_stash(&ledger.stash)?;
295
296 T::WeightInfo::withdraw_unbonded_kill()
297 } else {
298 ledger.update()?;
300
301 T::WeightInfo::withdraw_unbonded_update()
303 };
304
305 if new_total < old_total {
308 let value = old_total.defensive_saturating_sub(new_total);
310 Self::deposit_event(Event::<T>::Withdrawn { stash, amount: value });
311
312 T::EventListeners::on_withdraw(controller, value);
314 }
315
316 Ok(used_weight)
317 }
318
319 fn ensure_era_slashes_applied(era: EraIndex) -> Result<(), DispatchError> {
320 ensure!(
321 !UnappliedSlashes::<T>::contains_prefix(era),
322 Error::<T>::UnappliedSlashesInPreviousEra
323 );
324 Ok(())
325 }
326
327 pub(super) fn do_payout_stakers(
328 validator_stash: T::AccountId,
329 era: EraIndex,
330 ) -> DispatchResultWithPostInfo {
331 let page = Eras::<T>::get_next_claimable_page(era, &validator_stash).ok_or_else(|| {
332 Error::<T>::AlreadyClaimed.with_weight(T::WeightInfo::payout_stakers_alive_staked(0))
333 })?;
334
335 Self::do_payout_stakers_by_page(validator_stash, era, page)
336 }
337
338 pub(super) fn do_payout_stakers_by_page(
339 validator_stash: T::AccountId,
340 era: EraIndex,
341 page: Page,
342 ) -> DispatchResultWithPostInfo {
343 let current_era = CurrentEra::<T>::get().ok_or_else(|| {
345 Error::<T>::InvalidEraToReward
346 .with_weight(T::WeightInfo::payout_stakers_alive_staked(0))
347 })?;
348
349 let history_depth = T::HistoryDepth::get();
350
351 ensure!(
352 era <= current_era && era >= current_era.saturating_sub(history_depth),
353 Error::<T>::InvalidEraToReward
354 .with_weight(T::WeightInfo::payout_stakers_alive_staked(0))
355 );
356
357 ensure!(
358 page < Eras::<T>::exposure_page_count(era, &validator_stash),
359 Error::<T>::InvalidPage.with_weight(T::WeightInfo::payout_stakers_alive_staked(0))
360 );
361
362 let era_payout = Eras::<T>::get_stakers_reward(era).ok_or_else(|| {
364 Error::<T>::InvalidEraToReward
365 .with_weight(T::WeightInfo::payout_stakers_alive_staked(0))
366 })?;
367
368 let account = StakingAccount::Stash(validator_stash.clone());
369 let ledger = Self::ledger(account.clone()).or_else(|_| {
370 if StakingLedger::<T>::is_bonded(account) {
371 Err(Error::<T>::NotController.into())
372 } else {
373 Err(Error::<T>::NotStash.with_weight(T::WeightInfo::payout_stakers_alive_staked(0)))
374 }
375 })?;
376
377 ledger.clone().update()?;
378
379 let stash = ledger.stash.clone();
380
381 if Eras::<T>::is_rewards_claimed(era, &stash, page) {
382 return Err(Error::<T>::AlreadyClaimed
383 .with_weight(T::WeightInfo::payout_stakers_alive_staked(0)));
384 }
385
386 Eras::<T>::set_rewards_as_claimed(era, &stash, page);
387
388 let exposure = Eras::<T>::get_paged_exposure(era, &stash, page).ok_or_else(|| {
389 Error::<T>::InvalidEraToReward
390 .with_weight(T::WeightInfo::payout_stakers_alive_staked(0))
391 })?;
392
393 let era_reward_points = Eras::<T>::get_reward_points(era);
396 let total_reward_points = era_reward_points.total;
397 let validator_reward_points =
398 era_reward_points.individual.get(&stash).copied().unwrap_or_else(Zero::zero);
399
400 if validator_reward_points.is_zero() {
402 return Ok(Some(T::WeightInfo::payout_stakers_alive_staked(0)).into());
403 }
404
405 let validator_total_reward_part =
408 Perbill::from_rational(validator_reward_points, total_reward_points);
409
410 let validator_total_payout = validator_total_reward_part.mul_floor(era_payout);
412
413 let validator_commission = Eras::<T>::get_validator_commission(era, &ledger.stash);
414
415 let overview_own =
418 ErasStakersOverview::<T>::get(era, &stash).map(|o| o.own).unwrap_or_default();
419
420 let reward_split = T::StakerRewardCalculator::calculate_staker_reward(
421 validator_total_payout,
422 validator_commission,
423 overview_own,
424 exposure.total(),
425 );
426
427 let page_stake_part = Perbill::from_rational(exposure.page_total(), exposure.total());
430 let validator_staker_payout_for_page =
431 page_stake_part.mul_floor(reward_split.validator_payout);
432
433 Self::deposit_event(Event::<T>::PayoutStarted {
434 era_index: era,
435 validator_stash: stash.clone(),
436 page,
437 next: Eras::<T>::get_next_claimable_page(era, &stash),
438 });
439
440 if let Some(incentive) = Self::calculate_validator_incentive_for_page(
443 era,
444 &stash,
445 page_stake_part,
446 &era_reward_points,
447 ) {
448 Self::transfer_validator_incentive(era, &stash, incentive);
449 }
450
451 let use_dap_payout =
453 DisableMintingGuard::<T>::get().is_some_and(|guard_era| era >= guard_era);
454
455 let nominator_payout_count: u32 = if use_dap_payout {
456 Self::payout_from_provider(
457 era,
458 &stash,
459 validator_staker_payout_for_page,
460 &exposure,
461 overview_own,
462 reward_split.nominator_payout,
463 )
464 } else {
465 Self::payout_legacy_mint(
466 era,
467 &stash,
468 validator_staker_payout_for_page,
469 &exposure,
470 overview_own,
471 reward_split.nominator_payout,
472 )
473 };
474
475 debug_assert!(nominator_payout_count <= T::MaxExposurePageSize::get());
476
477 Ok(Some(T::WeightInfo::payout_stakers_alive_staked(nominator_payout_count)).into())
478 }
479
480 fn payout_from_provider(
482 era: EraIndex,
483 stash: &T::AccountId,
484 validator_payout: BalanceOf<T>,
485 exposure: &crate::PagedExposure<T::AccountId, BalanceOf<T>>,
486 overview_own: BalanceOf<T>,
487 total_nominator_payout: BalanceOf<T>,
488 ) -> u32 {
489 let mut nominator_payout_count: u32 = 0;
490
491 if let Some((amount, dest)) = Self::make_payout_from_provider(era, stash, validator_payout)
492 {
493 Self::deposit_event(Event::<T>::Rewarded { stash: stash.clone(), dest, amount });
494 }
495
496 let total_nominator_stake = exposure.total().saturating_sub(overview_own);
497 for nominator in exposure.others().iter() {
498 let nominator_exposure_part =
499 Perbill::from_rational(nominator.value, total_nominator_stake);
500 let nominator_reward: BalanceOf<T> =
501 nominator_exposure_part.mul_floor(total_nominator_payout);
502
503 if let Some((amount, dest)) =
504 Self::make_payout_from_provider(era, &nominator.who, nominator_reward)
505 {
506 nominator_payout_count.saturating_inc();
507 Self::deposit_event(Event::<T>::Rewarded {
508 stash: nominator.who.clone(),
509 dest,
510 amount,
511 });
512 }
513 }
514
515 nominator_payout_count
516 }
517
518 fn payout_legacy_mint(
520 era: EraIndex,
521 stash: &T::AccountId,
522 validator_payout: BalanceOf<T>,
523 exposure: &crate::PagedExposure<T::AccountId, BalanceOf<T>>,
524 overview_own: BalanceOf<T>,
525 total_nominator_payout: BalanceOf<T>,
526 ) -> u32 {
527 let mut nominator_payout_count: u32 = 0;
528 let mut total_imbalance = PositiveImbalanceOf::<T>::zero();
529
530 if let Some((imbalance, dest)) = Self::make_payout_legacy(era, stash, validator_payout) {
531 Self::deposit_event(Event::<T>::Rewarded {
532 stash: stash.clone(),
533 dest,
534 amount: imbalance.peek(),
535 });
536 total_imbalance.subsume(imbalance);
537 }
538
539 let total_nominator_stake = exposure.total().saturating_sub(overview_own);
540 for nominator in exposure.others().iter() {
541 let nominator_exposure_part =
542 Perbill::from_rational(nominator.value, total_nominator_stake);
543 let nominator_reward: BalanceOf<T> =
544 nominator_exposure_part.mul_floor(total_nominator_payout);
545
546 if let Some((imbalance, dest)) =
547 Self::make_payout_legacy(era, &nominator.who, nominator_reward)
548 {
549 nominator_payout_count.saturating_inc();
550 Self::deposit_event(Event::<T>::Rewarded {
551 stash: nominator.who.clone(),
552 dest,
553 amount: imbalance.peek(),
554 });
555 total_imbalance.subsume(imbalance);
556 }
557 }
558
559 T::Reward::on_unbalanced(total_imbalance);
560 nominator_payout_count
561 }
562
563 fn payout_account_for_dest(
565 stash: &T::AccountId,
566 dest: &RewardDestination<T::AccountId>,
567 ) -> Option<T::AccountId> {
568 match dest {
569 RewardDestination::Stash | RewardDestination::Staked => Some(stash.clone()),
570 RewardDestination::Account(ref dest_account) => Some(dest_account.clone()),
571 RewardDestination::None => None,
572 #[allow(deprecated)]
573 RewardDestination::Controller => Self::bonded(stash),
574 }
575 }
576
577 fn make_payout_from_provider(
579 era: EraIndex,
580 stash: &T::AccountId,
581 amount: BalanceOf<T>,
582 ) -> Option<(BalanceOf<T>, RewardDestination<T::AccountId>)> {
583 if amount.is_zero() {
584 return None;
585 }
586
587 let dest = match Self::payee(Stash(stash.clone())) {
588 Some(d) => d,
589 None => {
590 Self::deposit_event(Event::<T>::Unexpected(UnexpectedKind::MissingPayee {
591 era,
592 stash: stash.clone(),
593 }));
594 return None;
595 },
596 };
597
598 let payout_account = Self::payout_account_for_dest(stash, &dest)?;
599
600 let staker_rewards_pot =
601 T::RewardPots::pot_account(RewardPot::Era(era, RewardKind::StakerRewards));
602 if let Err(e) = T::Currency::transfer(
603 &staker_rewards_pot,
604 &payout_account,
605 amount,
606 Preservation::Expendable,
607 ) {
608 log!(
609 error,
610 "Failed to transfer reward from pot for era {:?}, stash {:?}: {:?}",
611 era,
612 stash,
613 e
614 );
615 return None;
616 }
617
618 if matches!(dest, RewardDestination::Staked) {
620 if let Ok(mut ledger) = Self::ledger(Stash(stash.clone())) {
621 ledger.active += amount;
622 ledger.total += amount;
623 let _ = ledger
624 .update()
625 .defensive_proof("ledger fetched from storage, so it exists; qed.");
626 }
627 }
628
629 Some((amount, dest))
630 }
631
632 fn make_payout_legacy(
634 era: EraIndex,
635 stash: &T::AccountId,
636 amount: BalanceOf<T>,
637 ) -> Option<(PositiveImbalanceOf<T>, RewardDestination<T::AccountId>)> {
638 if amount.is_zero() {
639 return None;
640 }
641 let dest = match Self::payee(StakingAccount::Stash(stash.clone())) {
642 Some(d) => d,
643 None => {
644 Self::deposit_event(Event::<T>::Unexpected(UnexpectedKind::MissingPayee {
645 era,
646 stash: stash.clone(),
647 }));
648 return None;
649 },
650 };
651
652 let maybe_imbalance = match dest {
653 RewardDestination::Stash => asset::mint_into_existing::<T>(stash, amount),
654 RewardDestination::Staked => Self::ledger(Stash(stash.clone()))
655 .and_then(|mut ledger| {
656 ledger.active += amount;
657 ledger.total += amount;
658 let r = asset::mint_into_existing::<T>(stash, amount);
659 let _ = ledger
660 .update()
661 .defensive_proof("ledger fetched from storage, so it exists; qed.");
662 Ok(r)
663 })
664 .unwrap_or_default(),
665 RewardDestination::Account(ref dest_account) => {
666 Some(asset::mint_creating::<T>(dest_account, amount))
667 },
668 RewardDestination::None => None,
669 #[allow(deprecated)]
670 RewardDestination::Controller => Self::bonded(stash).map(|controller| {
671 defensive!("Paying out controller as reward destination which is deprecated.");
672 asset::mint_creating::<T>(&controller, amount)
673 }),
674 };
675 maybe_imbalance.map(|imbalance| (imbalance, dest))
676 }
677
678 fn calculate_validator_incentive_for_page(
692 era: EraIndex,
693 stash: &T::AccountId,
694 page_stake_part: Perbill,
695 era_reward_points: &EraRewardPoints<T>,
696 ) -> Option<BalanceOf<T>> {
697 let era_incentive_budget = Eras::<T>::get_validator_incentive_budget(era);
698 if era_incentive_budget.is_zero() {
699 return None;
700 }
701
702 let validator_weight = match ErasValidatorIncentiveWeight::<T>::get(era, stash) {
703 Some(w) if !w.is_zero() => w,
705 _ => return None,
706 };
707
708 let share_part = if Eras::<T>::uses_weighted_points(era) {
711 let sum_weighted_points = ErasSumWeightedPoints::<T>::get(era);
716 if sum_weighted_points.is_zero() {
717 log!(warn, "Sum of weighted points is zero but budget exists for era {}", era);
718 Self::deposit_event(Event::<T>::Unexpected(
719 UnexpectedKind::ValidatorIncentiveWeightMismatch { era },
720 ));
721 return None;
722 }
723 let validator_points: RewardPoint =
724 era_reward_points.individual.get(stash).copied().unwrap_or(0);
725 let numerator = validator_weight.saturating_mul(BalanceOf::<T>::from(validator_points));
726 Perbill::from_rational(numerator, sum_weighted_points)
727 } else {
728 let total_weight = ErasSumValidatorIncentiveWeight::<T>::get(era);
732 if total_weight.is_zero() {
733 log!(
734 warn,
735 "Total validator incentive weight is zero but budget exists for era {}",
736 era
737 );
738 Self::deposit_event(Event::<T>::Unexpected(
739 UnexpectedKind::ValidatorIncentiveWeightMismatch { era },
740 ));
741 return None;
742 }
743 Perbill::from_rational(validator_weight, total_weight)
744 };
745
746 if share_part.is_zero() {
747 return None;
748 }
749
750 let validator_total_incentive = share_part.mul_floor(era_incentive_budget);
751 let validator_incentive_for_page = page_stake_part.mul_floor(validator_total_incentive);
752
753 if validator_incentive_for_page.is_zero() {
754 return None;
755 }
756
757 Some(validator_incentive_for_page)
758 }
759
760 fn transfer_validator_incentive(era: EraIndex, stash: &T::AccountId, amount: BalanceOf<T>) {
764 let Some(dest) = Self::payee(Stash(stash.clone())) else {
765 Self::deposit_event(Event::<T>::Unexpected(UnexpectedKind::MissingPayee {
766 era,
767 stash: stash.clone(),
768 }));
769 return;
770 };
771 let Some(payout_account) = Self::payout_account_for_dest(stash, &dest) else {
772 return;
774 };
775
776 let incentive_pot = T::RewardPots::pot_account(crate::RewardPot::Era(
777 era,
778 crate::RewardKind::ValidatorSelfStake,
779 ));
780
781 match T::Currency::transfer(
782 &incentive_pot,
783 &payout_account,
784 amount,
785 Preservation::Expendable,
786 ) {
787 Ok(_) => {
788 Self::deposit_event(Event::<T>::ValidatorIncentivePaid {
789 era,
790 validator_stash: stash.clone(),
791 dest,
792 amount,
793 });
794 },
795 Err(e) => {
796 log!(warn, "Failed to transfer liquid incentive: {:?}", e);
797 Self::deposit_event(Event::<T>::Unexpected(
798 UnexpectedKind::ValidatorIncentiveTransferFailed { era },
799 ));
800 defensive!("Validator incentive liquid transfer failed");
801 },
802 }
803 }
804
805 pub(crate) fn chill_stash(stash: &T::AccountId) {
807 let chilled_as_validator = Self::do_remove_validator(stash);
808 let chilled_as_nominator = Self::do_remove_nominator(stash);
809 if chilled_as_validator || chilled_as_nominator {
810 Self::deposit_event(Event::<T>::Chilled { stash: stash.clone() });
811 }
812 }
813
814 pub(crate) fn kill_stash(stash: &T::AccountId) -> DispatchResult {
823 StakingLedger::<T>::kill(&stash)?;
826
827 Self::do_remove_validator(&stash);
828 Self::do_remove_nominator(&stash);
829
830 LastValidatorEra::<T>::remove(&stash);
832
833 Ok(())
834 }
835
836 #[cfg(test)]
837 pub(crate) fn reward_by_ids(validators_points: impl IntoIterator<Item = (T::AccountId, u32)>) {
838 Eras::<T>::reward_active_era(ServiceKind::RelayConsensus, validators_points)
839 }
840
841 pub(crate) fn reward_service_points(
850 service: ServiceKind,
851 points: impl IntoIterator<Item = (T::AccountId, RewardPoint)>,
852 ) {
853 if service == ServiceKind::RelayConsensus {
854 defensive!("relay consensus points come only from the relay chain session report");
855 return;
856 }
857 let Some(era) = ActiveEra::<T>::get().map(|active| active.index) else {
858 log!(warn, "no active era, dropping {:?} points", service);
859 return;
860 };
861 let (exposed, dropped): (Vec<_>, Vec<_>) = points
862 .into_iter()
863 .partition(|(who, _)| Eras::<T>::was_validator_exposed(era, who));
864 let credited = exposed.len() as u32;
865 if credited > 0 {
866 Eras::<T>::reward_active_era(service, exposed);
867 }
868 Self::deposit_event(Event::<T>::ServicePointsCredited {
869 service,
870 era,
871 credited,
872 dropped: dropped.len() as u32,
873 });
874 }
875
876 pub(crate) fn set_force_era(mode: Forcing) {
878 log!(info, "Setting force era mode {:?}.", mode);
879 ForceEra::<T>::put(mode);
880 Self::deposit_event(Event::<T>::ForceEra { mode });
881 }
882
883 #[cfg(feature = "runtime-benchmarks")]
884 pub fn add_era_stakers(
885 current_era: EraIndex,
886 stash: T::AccountId,
887 exposure: Exposure<T::AccountId, BalanceOf<T>>,
888 ) {
889 Eras::<T>::upsert_exposure(current_era, &stash, exposure);
890 }
891
892 #[cfg(feature = "runtime-benchmarks")]
893 pub fn set_slash_reward_fraction(fraction: Perbill) {
894 SlashRewardFraction::<T>::put(fraction);
895 }
896
897 pub(crate) fn get_npos_voters(
907 bounds: DataProviderBounds,
908 status: &SnapshotStatus<T::AccountId>,
909 ) -> Vec<VoterOf<Self>> {
910 let mut voters_size_tracker: StaticTracker<Self> = StaticTracker::default();
911
912 let page_len_prediction = {
913 let all_voter_count = T::VoterList::count();
914 bounds.count.unwrap_or(all_voter_count.into()).min(all_voter_count.into()).0
915 };
916
917 let mut all_voters = Vec::<_>::with_capacity(page_len_prediction as usize);
918
919 let weight_of = Self::weight_of_fn();
921
922 let mut voters_seen = 0u32;
923 let mut validators_taken = 0u32;
924 let mut nominators_taken = 0u32;
925 let mut min_active_stake = u64::MAX;
926
927 let mut sorted_voters = match status {
928 SnapshotStatus::Waiting => T::VoterList::iter(),
930 SnapshotStatus::Ongoing(account_id) => T::VoterList::iter_from(&account_id)
932 .defensive_unwrap_or(Box::new(vec![].into_iter())),
933 SnapshotStatus::Consumed => Box::new(vec![].into_iter()),
935 };
936
937 while all_voters.len() < page_len_prediction as usize &&
938 voters_seen < (NPOS_MAX_ITERATIONS_COEFFICIENT * page_len_prediction as u32)
939 {
940 let voter = match sorted_voters.next() {
941 Some(voter) => {
942 voters_seen.saturating_inc();
943 voter
944 },
945 None => break,
946 };
947
948 let voter_weight = weight_of(&voter);
949 if voter_weight.is_zero() {
951 log!(debug, "voter's active balance is 0. skip this voter.");
952 continue;
953 }
954
955 if let Some(Nominations { targets, .. }) = <Nominators<T>>::get(&voter) {
956 if !targets.is_empty() {
957 let voter = (voter, voter_weight, targets);
962 if voters_size_tracker.try_register_voter(&voter, &bounds).is_err() {
963 Self::deposit_event(Event::<T>::SnapshotVotersSizeExceeded {
965 size: voters_size_tracker.size as u32,
966 });
967 break;
968 }
969
970 all_voters.push(voter);
971 nominators_taken.saturating_inc();
972 } else {
973 defensive!("non-nominator fetched from voter list: {:?}", voter);
974 }
976 min_active_stake =
977 if voter_weight < min_active_stake { voter_weight } else { min_active_stake };
978 } else if Validators::<T>::contains_key(&voter) {
979 let self_vote = (
981 voter.clone(),
982 voter_weight,
983 vec![voter.clone()]
984 .try_into()
985 .expect("`MaxVotesPerVoter` must be greater than or equal to 1"),
986 );
987
988 if voters_size_tracker.try_register_voter(&self_vote, &bounds).is_err() {
989 Self::deposit_event(Event::<T>::SnapshotVotersSizeExceeded {
991 size: voters_size_tracker.size as u32,
992 });
993 break;
994 }
995 all_voters.push(self_vote);
996 validators_taken.saturating_inc();
997 } else {
998 defensive!(
1004 "invalid item in `VoterList`: {:?}, this nominator probably has too many nominations now",
1005 voter,
1006 );
1007 }
1008 }
1009
1010 debug_assert!(all_voters.capacity() == page_len_prediction as usize);
1012
1013 let min_active_stake: T::CurrencyBalance =
1014 if all_voters.is_empty() { Zero::zero() } else { min_active_stake.into() };
1015
1016 MinimumActiveStake::<T>::put(min_active_stake);
1017
1018 all_voters
1019 }
1020
1021 pub fn get_npos_targets(bounds: DataProviderBounds) -> Vec<T::AccountId> {
1027 let mut targets_size_tracker: StaticTracker<Self> = StaticTracker::default();
1028
1029 let final_predicted_len = {
1030 let all_target_count = T::TargetList::count();
1031 bounds.count.unwrap_or(all_target_count.into()).min(all_target_count.into()).0
1032 };
1033
1034 let mut all_targets = Vec::<T::AccountId>::with_capacity(final_predicted_len as usize);
1035 let mut targets_seen = 0;
1036
1037 let mut targets_iter = T::TargetList::iter();
1038 while all_targets.len() < final_predicted_len as usize &&
1039 targets_seen < (NPOS_MAX_ITERATIONS_COEFFICIENT * final_predicted_len as u32)
1040 {
1041 let target = match targets_iter.next() {
1042 Some(target) => {
1043 targets_seen.saturating_inc();
1044 target
1045 },
1046 None => break,
1047 };
1048
1049 if targets_size_tracker.try_register_target(target.clone(), &bounds).is_err() {
1050 log!(warn, "npos targets size exceeded, stopping iteration.");
1052 Self::deposit_event(Event::<T>::SnapshotTargetsSizeExceeded {
1053 size: targets_size_tracker.size as u32,
1054 });
1055 break;
1056 }
1057
1058 if Validators::<T>::contains_key(&target) {
1059 all_targets.push(target);
1060 }
1061 }
1062
1063 log!(debug, "[bounds {:?}] generated {} npos targets", bounds, all_targets.len());
1064
1065 all_targets
1066 }
1067
1068 pub fn do_add_nominator(who: &T::AccountId, nominations: Nominations<T>) {
1077 if !Nominators::<T>::contains_key(who) {
1078 let _ = T::VoterList::on_insert(who.clone(), Self::weight_of(who))
1080 .defensive_unwrap_or_default();
1081 }
1082 Nominators::<T>::insert(who, nominations);
1083 }
1084
1085 pub fn do_remove_nominator(who: &T::AccountId) -> bool {
1094 let outcome = if Nominators::<T>::contains_key(who) {
1095 Nominators::<T>::remove(who);
1096 let _ = T::VoterList::on_remove(who);
1097 true
1098 } else {
1099 false
1100 };
1101
1102 outcome
1103 }
1104
1105 pub fn do_add_validator(who: &T::AccountId, prefs: ValidatorPrefs) {
1113 if !Validators::<T>::contains_key(who) {
1114 let _ = T::VoterList::on_insert(who.clone(), Self::weight_of(who));
1116 }
1117 Validators::<T>::insert(who, prefs);
1118 }
1119
1120 pub fn do_remove_validator(who: &T::AccountId) -> bool {
1128 let outcome = if Validators::<T>::contains_key(who) {
1129 Validators::<T>::remove(who);
1130 let _ = T::VoterList::on_remove(who);
1131 true
1132 } else {
1133 false
1134 };
1135
1136 outcome
1137 }
1138
1139 pub(crate) fn register_weight(weight: Weight) {
1143 <frame_system::Pallet<T>>::register_extra_weight_unchecked(
1144 weight,
1145 DispatchClass::Mandatory,
1146 );
1147 }
1148
1149 pub fn eras_stakers(
1156 era: EraIndex,
1157 account: &T::AccountId,
1158 ) -> Exposure<T::AccountId, BalanceOf<T>> {
1159 Eras::<T>::get_full_exposure(era, account)
1160 }
1161
1162 pub(super) fn do_migrate_currency(stash: &T::AccountId) -> DispatchResult {
1163 if Self::is_virtual_staker(stash) {
1164 return Self::do_migrate_virtual_staker(stash);
1165 }
1166
1167 let ledger = Self::ledger(Stash(stash.clone()))?;
1168 let staked: BalanceOf<T> = T::OldCurrency::balance_locked(STAKING_ID, stash).into();
1169 ensure!(!staked.is_zero(), Error::<T>::AlreadyMigrated);
1170 ensure!(ledger.total == staked, Error::<T>::BadState);
1171
1172 T::OldCurrency::remove_lock(STAKING_ID, &stash);
1174
1175 let max_hold = asset::free_to_stake::<T>(&stash);
1177 let force_withdraw = if max_hold >= staked {
1178 asset::update_stake::<T>(&stash, staked)?;
1180 Zero::zero()
1181 } else {
1182 let force_withdraw = staked.saturating_sub(max_hold);
1185
1186 StakingLedger {
1189 total: max_hold,
1190 active: ledger.active.saturating_sub(force_withdraw),
1191 ..ledger
1193 }
1194 .update()?;
1195 force_withdraw
1196 };
1197
1198 frame_system::Pallet::<T>::dec_consumers(&stash);
1200
1201 Self::deposit_event(Event::<T>::CurrencyMigrated { stash: stash.clone(), force_withdraw });
1202 Ok(())
1203 }
1204
1205 fn do_migrate_virtual_staker(stash: &T::AccountId) -> DispatchResult {
1206 frame_system::Pallet::<T>::dec_consumers(&stash);
1209
1210 let actual_providers = frame_system::Pallet::<T>::providers(stash);
1215
1216 let expected_providers =
1217 if asset::free_to_stake::<T>(&stash) >= asset::existential_deposit::<T>() {
1220 2
1221 } else {
1222 1
1223 };
1224
1225 ensure!(actual_providers <= expected_providers, Error::<T>::BadState);
1227
1228 ensure!(actual_providers == expected_providers, Error::<T>::AlreadyMigrated);
1230
1231 let _ = frame_system::Pallet::<T>::dec_providers(&stash)?;
1233
1234 return Ok(());
1235 }
1236}
1237
1238impl<T: Config> Pallet<T> {
1239 pub fn api_nominations_quota(balance: BalanceOf<T>) -> u32 {
1243 T::NominationsQuota::get_quota(balance)
1244 }
1245
1246 pub fn api_eras_stakers(
1247 era: EraIndex,
1248 account: T::AccountId,
1249 ) -> Exposure<T::AccountId, BalanceOf<T>> {
1250 Self::eras_stakers(era, &account)
1251 }
1252
1253 pub fn api_eras_stakers_page_count(era: EraIndex, account: T::AccountId) -> Page {
1254 Eras::<T>::exposure_page_count(era, &account)
1255 }
1256
1257 pub fn api_pending_rewards(era: EraIndex, account: T::AccountId) -> bool {
1258 Eras::<T>::pending_rewards(era, &account)
1259 }
1260}
1261
1262impl<T: Config> ElectionDataProvider for Pallet<T> {
1263 type AccountId = T::AccountId;
1264 type BlockNumber = BlockNumberFor<T>;
1265 type MaxVotesPerVoter = MaxNominationsOf<T>;
1266
1267 fn desired_targets() -> data_provider::Result<u32> {
1268 Self::register_weight(T::DbWeight::get().reads(1));
1269 Ok(ValidatorCount::<T>::get())
1270 }
1271
1272 fn electing_voters(
1273 bounds: DataProviderBounds,
1274 page: PageIndex,
1275 ) -> data_provider::Result<Vec<VoterOf<Self>>> {
1276 let mut status = VoterSnapshotStatus::<T>::get();
1277 let voters = Self::get_npos_voters(bounds, &status);
1278
1279 match (page, &status) {
1281 (0, _) => status = SnapshotStatus::Waiting,
1283
1284 (_, SnapshotStatus::Waiting) | (_, SnapshotStatus::Ongoing(_)) => {
1285 let maybe_last = voters.last().map(|(x, _, _)| x).cloned();
1286
1287 if let Some(ref last) = maybe_last {
1288 let has_next =
1289 T::VoterList::iter_from(last).ok().and_then(|mut i| i.next()).is_some();
1290 if has_next {
1291 status = SnapshotStatus::Ongoing(last.clone());
1292 } else {
1293 status = SnapshotStatus::Consumed;
1294 }
1295 }
1296 },
1297 (_, SnapshotStatus::Consumed) => (),
1299 }
1300
1301 log!(
1302 debug,
1303 "[page {}, (next) status {:?}, bounds {:?}] generated {} npos voters [first: {:?}, last: {:?}]",
1304 page,
1305 status,
1306 bounds,
1307 voters.len(),
1308 voters.first().map(|(x, y, _)| (x, y)),
1309 voters.last().map(|(x, y, _)| (x, y)),
1310 );
1311
1312 match status {
1313 SnapshotStatus::Ongoing(_) => T::VoterList::lock(),
1314 _ => T::VoterList::unlock(),
1315 }
1316
1317 VoterSnapshotStatus::<T>::put(status);
1318 debug_assert!(!bounds.slice_exhausted(&voters));
1319
1320 Ok(voters)
1321 }
1322
1323 fn electing_voters_stateless(
1324 bounds: DataProviderBounds,
1325 ) -> data_provider::Result<Vec<VoterOf<Self>>> {
1326 let voters = Self::get_npos_voters(bounds, &SnapshotStatus::Waiting);
1327 log!(debug, "[stateless, bounds {:?}] generated {} npos voters", bounds, voters.len(),);
1328 Ok(voters)
1329 }
1330
1331 fn electable_targets(
1332 bounds: DataProviderBounds,
1333 page: PageIndex,
1334 ) -> data_provider::Result<Vec<T::AccountId>> {
1335 if page > 0 {
1336 log!(warn, "multi-page target snapshot not supported, returning page 0.");
1337 }
1338
1339 let targets = Self::get_npos_targets(bounds);
1340 if bounds.exhausted(None, CountBound(targets.len() as u32).into()) {
1341 return Err("Target snapshot too big");
1342 }
1343
1344 debug_assert!(!bounds.slice_exhausted(&targets));
1345
1346 Ok(targets)
1347 }
1348
1349 fn next_election_prediction(_: BlockNumberFor<T>) -> BlockNumberFor<T> {
1350 debug_assert!(false, "this is deprecated and not used anymore");
1351 sp_runtime::traits::Bounded::max_value()
1352 }
1353
1354 #[cfg(feature = "runtime-benchmarks")]
1355 fn fetch_page(page: PageIndex) {
1356 session_rotation::EraElectionPlanner::<T>::do_elect_paged(page);
1357 }
1358
1359 #[cfg(feature = "runtime-benchmarks")]
1360 fn add_voter(
1361 voter: T::AccountId,
1362 weight: VoteWeight,
1363 targets: BoundedVec<T::AccountId, Self::MaxVotesPerVoter>,
1364 ) {
1365 let stake = <BalanceOf<T>>::try_from(weight).unwrap_or_else(|_| {
1366 panic!("cannot convert a VoteWeight into BalanceOf, benchmark needs reconfiguring.")
1367 });
1368 <Bonded<T>>::insert(voter.clone(), voter.clone());
1369 <Ledger<T>>::insert(voter.clone(), StakingLedger::<T>::new(voter.clone(), stake));
1370
1371 Self::do_add_nominator(&voter, Nominations { targets, submitted_in: 0, suppressed: false });
1372 }
1373
1374 #[cfg(feature = "runtime-benchmarks")]
1375 fn add_target(target: T::AccountId) {
1376 let stake = (Self::min_validator_bond() + 1u32.into()) * 100u32.into();
1377 <Bonded<T>>::insert(target.clone(), target.clone());
1378 <Ledger<T>>::insert(target.clone(), StakingLedger::<T>::new(target.clone(), stake));
1379 Self::do_add_validator(
1380 &target,
1381 ValidatorPrefs { commission: Perbill::zero(), blocked: false },
1382 );
1383 }
1384
1385 #[cfg(feature = "runtime-benchmarks")]
1386 fn clear() {
1387 #[allow(deprecated)]
1388 <Bonded<T>>::remove_all(None);
1389 #[allow(deprecated)]
1390 <Ledger<T>>::remove_all(None);
1391 #[allow(deprecated)]
1392 <Validators<T>>::remove_all();
1393 #[allow(deprecated)]
1394 <Nominators<T>>::remove_all();
1395
1396 T::VoterList::unsafe_clear();
1397 }
1398
1399 #[cfg(feature = "runtime-benchmarks")]
1400 fn put_snapshot(
1401 voters: Vec<VoterOf<Self>>,
1402 targets: Vec<T::AccountId>,
1403 target_stake: Option<VoteWeight>,
1404 ) {
1405 targets.into_iter().for_each(|v| {
1406 let stake: BalanceOf<T> = target_stake
1407 .and_then(|w| <BalanceOf<T>>::try_from(w).ok())
1408 .unwrap_or_else(|| Self::min_nominator_bond() * 100u32.into());
1409 <Bonded<T>>::insert(v.clone(), v.clone());
1410 <Ledger<T>>::insert(v.clone(), StakingLedger::<T>::new(v.clone(), stake));
1411 Self::do_add_validator(
1412 &v,
1413 ValidatorPrefs { commission: Perbill::zero(), blocked: false },
1414 );
1415 });
1416
1417 voters.into_iter().for_each(|(v, s, t)| {
1418 let stake = <BalanceOf<T>>::try_from(s).unwrap_or_else(|_| {
1419 panic!("cannot convert a VoteWeight into BalanceOf, benchmark needs reconfiguring.")
1420 });
1421 <Bonded<T>>::insert(v.clone(), v.clone());
1422 <Ledger<T>>::insert(v.clone(), StakingLedger::<T>::new(v.clone(), stake));
1423 Self::do_add_nominator(
1424 &v,
1425 Nominations { targets: t, submitted_in: 0, suppressed: false },
1426 );
1427 });
1428 }
1429
1430 #[cfg(feature = "runtime-benchmarks")]
1431 fn set_desired_targets(count: u32) {
1432 ValidatorCount::<T>::put(count);
1433 }
1434}
1435
1436impl<T: Config> sp_staking::RewardPoints<T::AccountId> for Pallet<T> {
1437 fn reward(service: ServiceKind, points: Vec<(T::AccountId, RewardPoint)>) {
1438 Self::reward_service_points(service, points);
1439 }
1440
1441 fn weight(entries: u32) -> Weight {
1442 T::WeightInfo::reward_service_points(entries)
1443 }
1444}
1445
1446impl<T: Config> rc_client::AHStakingInterface for Pallet<T> {
1447 type AccountId = T::AccountId;
1448 type MaxValidatorSet = T::MaxValidatorSet;
1449
1450 fn on_relay_session_report(report: rc_client::SessionReport<Self::AccountId>) -> Weight {
1459 log!(debug, "Received session report: {}", report,);
1460
1461 let rc_client::SessionReport {
1462 end_index,
1463 activation_timestamp,
1464 validator_points,
1465 leftover,
1466 } = report;
1467 debug_assert!(!leftover);
1468
1469 let validator_count = validator_points.len() as u32;
1470 Eras::<T>::reward_active_era(ServiceKind::RelayConsensus, validator_points.into_iter());
1472 session_rotation::Rotator::<T>::end_session(
1473 end_index,
1474 activation_timestamp,
1475 validator_count,
1476 )
1477 }
1478
1479 fn weigh_on_relay_session_report(report: &rc_client::SessionReport<Self::AccountId>) -> Weight {
1480 let era_start = if report.activation_timestamp.is_some() && !report.leftover {
1481 session_rotation::Rotator::<T>::notify_era_start_max_weight()
1482 } else {
1483 Weight::zero()
1484 };
1485 T::WeightInfo::rc_on_session_report(report.validator_points.len() as u32)
1486 .saturating_add(era_start)
1487 }
1488
1489 fn on_new_offences(
1500 slash_session: SessionIndex,
1501 offences: Vec<rc_client::Offence<T::AccountId>>,
1502 ) -> Weight {
1503 log!(debug, "🦹 on_new_offences: {:?}", offences);
1504 let weight = T::WeightInfo::rc_on_offence(offences.len() as u32);
1505
1506 let Some(active_era) = ActiveEra::<T>::get() else {
1508 log!(warn, "🦹 on_new_offences: no active era; ignoring offence");
1509 return T::WeightInfo::rc_on_offence(0);
1510 };
1511
1512 let active_era_start_session = Rotator::<T>::active_era_start_session_index();
1513
1514 let offence_era = if slash_session >= active_era_start_session {
1517 active_era.index
1518 } else {
1519 match BondedEras::<T>::get()
1520 .iter()
1521 .rev()
1523 .find_map(|&(era, sesh)| if sesh <= slash_session { Some(era) } else { None })
1524 {
1525 Some(era) => era,
1526 None => {
1527 log!(warn, "🦹 on_offence: no era found for slash_session; ignoring offence");
1530 return T::WeightInfo::rc_on_offence(0);
1531 },
1532 }
1533 };
1534
1535 let oldest_reportable_offence_era = if T::SlashDeferDuration::get() == 0 {
1536 active_era.index.saturating_sub(T::BondingDuration::get().saturating_sub(2))
1542 } else {
1543 active_era.index.saturating_sub(T::SlashDeferDuration::get().saturating_sub(1))
1546 };
1547
1548 for o in offences {
1549 let slash_fraction = o.slash_fraction;
1550 let validator: <T as frame_system::Config>::AccountId = o.offender.into();
1551
1552 if offence_era < oldest_reportable_offence_era {
1554 log!(warn, "🦹 on_new_offences: offence era {:?} too old; Can only accept offences from era {:?} or newer", offence_era, oldest_reportable_offence_era);
1555 Self::deposit_event(Event::<T>::OffenceTooOld {
1556 validator: validator.clone(),
1557 fraction: slash_fraction,
1558 offence_era,
1559 });
1560 continue;
1562 }
1563 let Some(exposure_overview) = <ErasStakersOverview<T>>::get(&offence_era, &validator)
1564 else {
1565 log!(
1568 warn,
1569 "🦹 on_offence: no exposure found for {:?} in era {}; ignoring offence",
1570 validator,
1571 offence_era
1572 );
1573 continue;
1574 };
1575
1576 Self::deposit_event(Event::<T>::OffenceReported {
1577 validator: validator.clone(),
1578 fraction: slash_fraction,
1579 offence_era,
1580 });
1581
1582 let prior_slash_fraction = ValidatorSlashInEra::<T>::get(offence_era, &validator)
1583 .map_or(Zero::zero(), |(f, _)| f);
1584
1585 if let Some(existing) = OffenceQueue::<T>::get(offence_era, &validator) {
1586 if slash_fraction.deconstruct() > existing.slash_fraction.deconstruct() {
1587 OffenceQueue::<T>::insert(
1588 offence_era,
1589 &validator,
1590 OffenceRecord {
1591 reporter: o.reporters.first().cloned(),
1592 reported_era: active_era.index,
1593 slash_fraction,
1594 ..existing
1595 },
1596 );
1597
1598 ValidatorSlashInEra::<T>::insert(
1600 offence_era,
1601 &validator,
1602 (slash_fraction, exposure_overview.own),
1603 );
1604
1605 log!(
1606 debug,
1607 "🦹 updated slash for {:?}: {:?} (prior: {:?})",
1608 validator,
1609 slash_fraction,
1610 prior_slash_fraction,
1611 );
1612 } else {
1613 log!(
1614 debug,
1615 "🦹 ignored slash for {:?}: {:?} (existing prior is larger: {:?})",
1616 validator,
1617 slash_fraction,
1618 prior_slash_fraction,
1619 );
1620 }
1621 } else if slash_fraction.deconstruct() > prior_slash_fraction.deconstruct() {
1622 ValidatorSlashInEra::<T>::insert(
1623 offence_era,
1624 &validator,
1625 (slash_fraction, exposure_overview.own),
1626 );
1627
1628 OffenceQueue::<T>::insert(
1629 offence_era,
1630 &validator,
1631 OffenceRecord {
1632 reporter: o.reporters.first().cloned(),
1633 reported_era: active_era.index,
1634 exposure_page: exposure_overview.page_count.saturating_sub(1),
1637 slash_fraction,
1638 prior_slash_fraction,
1639 },
1640 );
1641
1642 OffenceQueueEras::<T>::mutate(|q| {
1643 if let Some(eras) = q {
1644 log!(debug, "🦹 inserting offence era {} into existing queue", offence_era);
1645 eras.binary_search(&offence_era).err().map(|idx| {
1646 eras.try_insert(idx, offence_era).defensive_proof(
1647 "Offence era must be present in the existing queue",
1648 )
1649 });
1650 } else {
1651 let mut eras = WeakBoundedVec::default();
1652 log!(debug, "🦹 inserting offence era {} into empty queue", offence_era);
1653 let _ = eras
1654 .try_push(offence_era)
1655 .defensive_proof("Failed to push offence era into empty queue");
1656 *q = Some(eras);
1657 }
1658 });
1659
1660 log!(
1661 debug,
1662 "🦹 queued slash for {:?}: {:?} (prior: {:?})",
1663 validator,
1664 slash_fraction,
1665 prior_slash_fraction,
1666 );
1667 } else {
1668 log!(
1669 debug,
1670 "🦹 ignored slash for {:?}: {:?} (already slashed in era with prior: {:?})",
1671 validator,
1672 slash_fraction,
1673 prior_slash_fraction,
1674 );
1675 }
1676 }
1677
1678 weight
1679 }
1680
1681 fn weigh_on_new_offences(offence_count: u32) -> Weight {
1682 T::WeightInfo::rc_on_offence(offence_count)
1683 }
1684
1685 fn active_era_start_session_index() -> SessionIndex {
1686 Rotator::<T>::active_era_start_session_index()
1687 }
1688
1689 fn is_validator(who: &Self::AccountId) -> bool {
1690 Validators::<T>::contains_key(who)
1691 }
1692}
1693
1694impl<T: Config> ScoreProvider<T::AccountId> for Pallet<T> {
1695 type Score = VoteWeight;
1696
1697 fn score(who: &T::AccountId) -> Option<Self::Score> {
1698 Self::ledger(Stash(who.clone()))
1699 .ok()
1700 .and_then(|l| {
1701 if Nominators::<T>::contains_key(&l.stash) ||
1702 Validators::<T>::contains_key(&l.stash)
1703 {
1704 Some(l.active)
1705 } else {
1706 None
1707 }
1708 })
1709 .map(|a| {
1710 let issuance = asset::total_issuance::<T>();
1711 T::CurrencyToVote::to_vote(a, issuance)
1712 })
1713 }
1714
1715 #[cfg(feature = "runtime-benchmarks")]
1716 fn set_score_of(who: &T::AccountId, weight: Self::Score) {
1717 let active: BalanceOf<T> = weight.try_into().map_err(|_| ()).unwrap();
1720 let mut ledger = match Self::ledger(StakingAccount::Stash(who.clone())) {
1721 Ok(l) => l,
1722 Err(_) => StakingLedger::default_from(who.clone()),
1723 };
1724 ledger.active = active;
1725
1726 <Ledger<T>>::insert(who, ledger);
1727 <Bonded<T>>::insert(who, who);
1728 <Validators<T>>::insert(who, ValidatorPrefs::default());
1731
1732 let imbalance = asset::burn::<T>(asset::total_issuance::<T>());
1736 core::mem::forget(imbalance);
1739 }
1740}
1741
1742pub struct UseValidatorsMap<T>(core::marker::PhantomData<T>);
1746impl<T: Config> SortedListProvider<T::AccountId> for UseValidatorsMap<T> {
1747 type Score = BalanceOf<T>;
1748 type Error = ();
1749
1750 fn iter() -> Box<dyn Iterator<Item = T::AccountId>> {
1752 Box::new(Validators::<T>::iter().map(|(v, _)| v))
1753 }
1754 fn iter_from(
1755 start: &T::AccountId,
1756 ) -> Result<Box<dyn Iterator<Item = T::AccountId>>, Self::Error> {
1757 if Validators::<T>::contains_key(start) {
1758 let start_key = Validators::<T>::hashed_key_for(start);
1759 Ok(Box::new(Validators::<T>::iter_from(start_key).map(|(n, _)| n)))
1760 } else {
1761 Err(())
1762 }
1763 }
1764 fn lock() {}
1765 fn unlock() {}
1766 fn count() -> u32 {
1767 Validators::<T>::count()
1768 }
1769 fn contains(id: &T::AccountId) -> bool {
1770 Validators::<T>::contains_key(id)
1771 }
1772 fn on_insert(_: T::AccountId, _weight: Self::Score) -> Result<(), Self::Error> {
1773 Ok(())
1775 }
1776 fn get_score(id: &T::AccountId) -> Result<Self::Score, Self::Error> {
1777 Ok(Pallet::<T>::weight_of(id).into())
1778 }
1779 fn on_update(_: &T::AccountId, _weight: Self::Score) -> Result<(), Self::Error> {
1780 Ok(())
1782 }
1783 fn on_remove(_: &T::AccountId) -> Result<(), Self::Error> {
1784 Ok(())
1786 }
1787 fn unsafe_regenerate(
1788 _: impl IntoIterator<Item = T::AccountId>,
1789 _: Box<dyn Fn(&T::AccountId) -> Option<Self::Score>>,
1790 ) -> u32 {
1791 0
1793 }
1794 #[cfg(feature = "try-runtime")]
1795 fn try_state() -> Result<(), TryRuntimeError> {
1796 Ok(())
1797 }
1798
1799 fn unsafe_clear() {
1800 #[allow(deprecated)]
1801 Validators::<T>::remove_all();
1802 }
1803
1804 #[cfg(feature = "runtime-benchmarks")]
1805 fn score_update_worst_case(_who: &T::AccountId, _is_increase: bool) -> Self::Score {
1806 unimplemented!()
1807 }
1808}
1809
1810pub struct UseNominatorsAndValidatorsMap<T>(core::marker::PhantomData<T>);
1814impl<T: Config> SortedListProvider<T::AccountId> for UseNominatorsAndValidatorsMap<T> {
1815 type Error = ();
1816 type Score = VoteWeight;
1817
1818 fn iter() -> Box<dyn Iterator<Item = T::AccountId>> {
1819 Box::new(
1820 Validators::<T>::iter()
1821 .map(|(v, _)| v)
1822 .chain(Nominators::<T>::iter().map(|(n, _)| n)),
1823 )
1824 }
1825 fn iter_from(
1826 start: &T::AccountId,
1827 ) -> Result<Box<dyn Iterator<Item = T::AccountId>>, Self::Error> {
1828 if Validators::<T>::contains_key(start) {
1829 let start_key = Validators::<T>::hashed_key_for(start);
1830 Ok(Box::new(
1831 Validators::<T>::iter_from(start_key)
1832 .map(|(n, _)| n)
1833 .chain(Nominators::<T>::iter().map(|(x, _)| x)),
1834 ))
1835 } else if Nominators::<T>::contains_key(start) {
1836 let start_key = Nominators::<T>::hashed_key_for(start);
1837 Ok(Box::new(Nominators::<T>::iter_from(start_key).map(|(n, _)| n)))
1838 } else {
1839 Err(())
1840 }
1841 }
1842 fn lock() {}
1843 fn unlock() {}
1844 fn count() -> u32 {
1845 Nominators::<T>::count().saturating_add(Validators::<T>::count())
1846 }
1847 fn contains(id: &T::AccountId) -> bool {
1848 Nominators::<T>::contains_key(id) || Validators::<T>::contains_key(id)
1849 }
1850 fn on_insert(_: T::AccountId, _weight: Self::Score) -> Result<(), Self::Error> {
1851 Ok(())
1853 }
1854 fn get_score(id: &T::AccountId) -> Result<Self::Score, Self::Error> {
1855 Ok(Pallet::<T>::weight_of(id))
1856 }
1857 fn on_update(_: &T::AccountId, _weight: Self::Score) -> Result<(), Self::Error> {
1858 Ok(())
1860 }
1861 fn on_remove(_: &T::AccountId) -> Result<(), Self::Error> {
1862 Ok(())
1864 }
1865 fn unsafe_regenerate(
1866 _: impl IntoIterator<Item = T::AccountId>,
1867 _: Box<dyn Fn(&T::AccountId) -> Option<Self::Score>>,
1868 ) -> u32 {
1869 0
1871 }
1872
1873 #[cfg(feature = "try-runtime")]
1874 fn try_state() -> Result<(), TryRuntimeError> {
1875 Ok(())
1876 }
1877
1878 fn unsafe_clear() {
1879 #[allow(deprecated)]
1882 Nominators::<T>::remove_all();
1883 #[allow(deprecated)]
1884 Validators::<T>::remove_all();
1885 }
1886
1887 #[cfg(feature = "runtime-benchmarks")]
1888 fn score_update_worst_case(_who: &T::AccountId, _is_increase: bool) -> Self::Score {
1889 unimplemented!()
1890 }
1891}
1892
1893impl<T: Config> StakingInterface for Pallet<T> {
1894 type AccountId = T::AccountId;
1895 type Balance = BalanceOf<T>;
1896 type CurrencyToVote = T::CurrencyToVote;
1897
1898 fn minimum_nominator_bond() -> Self::Balance {
1899 Self::min_nominator_bond()
1900 }
1901
1902 fn minimum_validator_bond() -> Self::Balance {
1903 Self::min_validator_bond()
1904 }
1905
1906 fn stash_by_ctrl(controller: &Self::AccountId) -> Result<Self::AccountId, DispatchError> {
1907 Self::ledger(Controller(controller.clone()))
1908 .map(|l| l.stash)
1909 .map_err(|e| e.into())
1910 }
1911
1912 fn bonding_duration() -> EraIndex {
1917 T::BondingDuration::get()
1918 }
1919
1920 fn nominator_bonding_duration() -> EraIndex {
1934 if AreNominatorsSlashable::<T>::get() {
1935 T::BondingDuration::get()
1936 } else {
1937 T::NominatorFastUnbondDuration::get()
1938 }
1939 }
1940
1941 fn current_era() -> EraIndex {
1942 Rotator::<T>::active_era()
1945 }
1946
1947 fn stake(who: &Self::AccountId) -> Result<Stake<BalanceOf<T>>, DispatchError> {
1948 Self::ledger(Stash(who.clone()))
1949 .map(|l| Stake { total: l.total, active: l.active })
1950 .map_err(|e| e.into())
1951 }
1952
1953 fn bond_extra(who: &Self::AccountId, extra: Self::Balance) -> DispatchResult {
1954 Self::bond_extra(RawOrigin::Signed(who.clone()).into(), extra)
1955 }
1956
1957 fn unbond(who: &Self::AccountId, value: Self::Balance) -> DispatchResult {
1958 let ctrl = Self::bonded(who).ok_or(Error::<T>::NotStash)?;
1959 Self::unbond(RawOrigin::Signed(ctrl).into(), value)
1960 .map_err(|with_post| with_post.error)
1961 .map(|_| ())
1962 }
1963
1964 fn set_payee(stash: &Self::AccountId, reward_acc: &Self::AccountId) -> DispatchResult {
1965 ensure!(
1969 !Self::is_virtual_staker(stash) || stash != reward_acc,
1970 Error::<T>::RewardDestinationRestricted
1971 );
1972
1973 let ledger = Self::ledger(Stash(stash.clone()))?;
1974 let _ = ledger
1975 .set_payee(RewardDestination::Account(reward_acc.clone()))
1976 .defensive_proof("ledger was retrieved from storage, thus its bonded; qed.")?;
1977
1978 Ok(())
1979 }
1980
1981 fn chill(who: &Self::AccountId) -> DispatchResult {
1982 let ctrl = Self::bonded(who).ok_or(Error::<T>::NotStash)?;
1985 Self::chill(RawOrigin::Signed(ctrl).into())
1986 }
1987
1988 fn withdraw_unbonded(
1989 who: Self::AccountId,
1990 _num_slashing_spans: u32,
1991 ) -> Result<bool, DispatchError> {
1992 let ctrl = Self::bonded(&who).ok_or(Error::<T>::NotStash)?;
1993 Self::withdraw_unbonded(RawOrigin::Signed(ctrl.clone()).into(), 0)
1994 .map(|_| !StakingLedger::<T>::is_bonded(StakingAccount::Controller(ctrl)))
1995 .map_err(|with_post| with_post.error)
1996 }
1997
1998 fn bond(
1999 who: &Self::AccountId,
2000 value: Self::Balance,
2001 payee: &Self::AccountId,
2002 ) -> DispatchResult {
2003 Self::bond(
2004 RawOrigin::Signed(who.clone()).into(),
2005 value,
2006 RewardDestination::Account(payee.clone()),
2007 )
2008 }
2009
2010 fn nominate(who: &Self::AccountId, targets: Vec<Self::AccountId>) -> DispatchResult {
2011 let ctrl = Self::bonded(who).ok_or(Error::<T>::NotStash)?;
2012 let targets = targets.into_iter().map(T::Lookup::unlookup).collect::<Vec<_>>();
2013 Self::nominate(RawOrigin::Signed(ctrl).into(), targets)
2014 }
2015
2016 fn desired_validator_count() -> u32 {
2017 ValidatorCount::<T>::get()
2018 }
2019
2020 fn election_ongoing() -> bool {
2021 <T::ElectionProvider as ElectionProvider>::status().is_ok()
2022 }
2023
2024 fn force_unstake(who: Self::AccountId) -> sp_runtime::DispatchResult {
2025 Self::force_unstake(RawOrigin::Root.into(), who.clone(), 0)
2026 }
2027
2028 fn is_exposed_in_era(who: &Self::AccountId, era: &EraIndex) -> bool {
2029 ErasStakersPaged::<T>::iter_prefix((era,)).any(|((validator, _), exposure_page)| {
2030 validator == *who || exposure_page.others.iter().any(|i| i.who == *who)
2031 })
2032 }
2033
2034 fn status(
2035 who: &Self::AccountId,
2036 ) -> Result<sp_staking::StakerStatus<Self::AccountId>, DispatchError> {
2037 if !StakingLedger::<T>::is_bonded(StakingAccount::Stash(who.clone())) {
2038 return Err(Error::<T>::NotStash.into());
2039 }
2040
2041 let is_validator = Validators::<T>::contains_key(&who);
2042 let is_nominator = Nominators::<T>::get(&who);
2043
2044 use sp_staking::StakerStatus;
2045 match (is_validator, is_nominator.is_some()) {
2046 (false, false) => Ok(StakerStatus::Idle),
2047 (true, false) => Ok(StakerStatus::Validator),
2048 (false, true) => Ok(StakerStatus::Nominator(
2049 is_nominator.expect("is checked above; qed").targets.into_inner(),
2050 )),
2051 (true, true) => {
2052 defensive!("cannot be both validators and nominator");
2053 Err(Error::<T>::BadState.into())
2054 },
2055 }
2056 }
2057
2058 fn is_virtual_staker(who: &T::AccountId) -> bool {
2063 frame_system::Pallet::<T>::account_nonce(who).is_zero() &&
2064 VirtualStakers::<T>::contains_key(who)
2065 }
2066
2067 fn slash_reward_fraction() -> Perbill {
2068 SlashRewardFraction::<T>::get()
2069 }
2070
2071 sp_staking::runtime_benchmarks_enabled! {
2072 fn nominations(who: &Self::AccountId) -> Option<Vec<T::AccountId>> {
2073 Nominators::<T>::get(who).map(|n| n.targets.into_inner())
2074 }
2075
2076 fn add_era_stakers(
2077 current_era: &EraIndex,
2078 stash: &T::AccountId,
2079 exposures: Vec<(Self::AccountId, Self::Balance)>,
2080 ) {
2081 let others = exposures
2082 .iter()
2083 .map(|(who, value)| crate::IndividualExposure { who: who.clone(), value: *value })
2084 .collect::<Vec<_>>();
2085 let exposure = Exposure { total: Default::default(), own: Default::default(), others };
2086 Eras::<T>::upsert_exposure(*current_era, stash, exposure);
2087 }
2088
2089 fn max_exposure_page_size() -> Page {
2090 T::MaxExposurePageSize::get()
2091 }
2092 }
2093
2094 sp_staking::std_or_benchmarks_enabled! {
2095 fn set_era(era: EraIndex) {
2096 ActiveEra::<T>::put(crate::ActiveEraInfo { index: era, start: None });
2097 CurrentEra::<T>::put(era.saturating_add(1));
2099 }
2100 }
2101}
2102
2103impl<T: Config> sp_staking::StakingUnchecked for Pallet<T> {
2104 fn migrate_to_virtual_staker(who: &Self::AccountId) -> DispatchResult {
2105 asset::kill_stake::<T>(who)?;
2106 VirtualStakers::<T>::insert(who, ());
2107 Ok(())
2108 }
2109
2110 fn virtual_bond(
2114 keyless_who: &Self::AccountId,
2115 value: Self::Balance,
2116 payee: &Self::AccountId,
2117 ) -> DispatchResult {
2118 if StakingLedger::<T>::is_bonded(StakingAccount::Stash(keyless_who.clone())) {
2119 return Err(Error::<T>::AlreadyBonded.into());
2120 }
2121
2122 ensure!(keyless_who != payee, Error::<T>::RewardDestinationRestricted);
2124
2125 VirtualStakers::<T>::insert(keyless_who, ());
2127
2128 Self::deposit_event(Event::<T>::Bonded { stash: keyless_who.clone(), amount: value });
2129 let ledger = StakingLedger::<T>::new(keyless_who.clone(), value);
2130
2131 ledger.bond(RewardDestination::Account(payee.clone()))?;
2132
2133 Ok(())
2134 }
2135
2136 #[cfg(feature = "runtime-benchmarks")]
2138 fn migrate_to_direct_staker(who: &Self::AccountId) {
2139 assert!(VirtualStakers::<T>::contains_key(who));
2140 let ledger = StakingLedger::<T>::get(Stash(who.clone())).unwrap();
2141 let _ = asset::update_stake::<T>(who, ledger.total)
2142 .expect("funds must be transferred to stash");
2143 VirtualStakers::<T>::remove(who);
2144 }
2145}
2146
2147#[cfg(any(test, feature = "try-runtime"))]
2148impl<T: Config> Pallet<T> {
2149 pub(crate) fn do_try_state(_now: BlockNumberFor<T>) -> Result<(), TryRuntimeError> {
2150 if ActiveEra::<T>::get().is_none() && CurrentEra::<T>::get().is_none() {
2153 return Ok(());
2154 }
2155
2156 session_rotation::Rotator::<T>::do_try_state()?;
2157 session_rotation::Eras::<T>::do_try_state()?;
2158
2159 use frame_support::traits::fungible::Inspect;
2160 if T::CurrencyToVote::will_downscale(T::Currency::total_issuance()).map_or(false, |x| x) {
2161 log!(warn, "total issuance will cause T::CurrencyToVote to downscale -- report to maintainers.")
2162 }
2163
2164 Self::check_ledgers()?;
2165 Self::check_bonded_consistency()?;
2166 Self::check_payees()?;
2167 Self::check_paged_exposures()?;
2168 Self::check_count()?;
2169 Self::check_slash_health()?;
2170 Self::check_reward_mode_consistency()?;
2171
2172 Ok(())
2173 }
2174
2175 fn check_reward_mode_consistency() -> Result<(), TryRuntimeError> {
2180 if DisableMintingGuard::<T>::get().is_some() {
2182 ensure!(
2183 T::DisableMinting::get(),
2184 "DisableMintingGuard is set but DisableMinting is false. \
2185 Switching from non-minting back to legacy mode is not supported."
2186 );
2187 }
2188
2189 if T::DisableMinting::get() {
2190 if let Some(guard_era) = DisableMintingGuard::<T>::get() {
2191 let active_era = crate::session_rotation::Rotator::<T>::active_era();
2192 let history_depth = T::HistoryDepth::get();
2193 let oldest = active_era.saturating_sub(history_depth);
2194 for era in oldest..active_era {
2195 if era >= guard_era {
2196 ensure!(
2197 crate::reward::EraRewardManager::<T>::has_staker_rewards_pot(era),
2198 "Era pot missing for guarded era. Rewards cannot be paid."
2199 );
2200 }
2201 }
2202 } else {
2203 log!(
2207 warn,
2208 "DisableMinting=true but DisableMintingGuard is not set. \
2209 Expected only before the first era boundary after migration."
2210 );
2211 }
2212 }
2213 Ok(())
2214 }
2215
2216 fn check_bonded_consistency() -> Result<(), TryRuntimeError> {
2226 use alloc::collections::btree_set::BTreeSet;
2227
2228 let mut count_controller_double = 0;
2229 let mut count_double = 0;
2230 let mut count_none = 0;
2231 let mut controllers = BTreeSet::new();
2234
2235 for (stash, controller) in <Bonded<T>>::iter() {
2236 if !controllers.insert(controller.clone()) {
2237 count_controller_double += 1;
2238 }
2239
2240 match (<Ledger<T>>::get(&stash), <Ledger<T>>::get(&controller)) {
2241 (Some(_), Some(_)) =>
2242 {
2246 if stash != controller {
2247 count_double += 1;
2248 }
2249 },
2250 (None, None) => {
2251 count_none += 1;
2252 },
2253 _ => {},
2254 };
2255 }
2256
2257 if count_controller_double != 0 {
2258 log!(
2259 warn,
2260 "a controller is associated with more than one ledger ({} occurrences)",
2261 count_controller_double
2262 );
2263 };
2264
2265 if count_double != 0 {
2266 log!(warn, "single tuple of (stash, controller) pair bonds more than one ledger ({} occurrences)", count_double);
2267 }
2268
2269 if count_none != 0 {
2270 log!(warn, "inconsistent bonded state: (stash, controller) pair missing associated ledger ({} occurrences)", count_none);
2271 }
2272
2273 Ok(())
2274 }
2275
2276 fn check_payees() -> Result<(), TryRuntimeError> {
2281 for (stash, _) in Bonded::<T>::iter() {
2282 ensure!(Payee::<T>::get(&stash).is_some(), "bonded ledger does not have payee set");
2283 }
2284
2285 ensure!(
2286 (Ledger::<T>::iter().count() == Payee::<T>::iter().count()) &&
2287 (Ledger::<T>::iter().count() == Bonded::<T>::iter().count()),
2288 "number of entries in payee storage items does not match the number of bonded ledgers",
2289 );
2290
2291 Ok(())
2292 }
2293
2294 fn check_count() -> Result<(), TryRuntimeError> {
2298 crate::log!(
2302 debug,
2303 "VoterList count: {}, Nominators count: {}, Validators count: {}",
2304 <T as Config>::VoterList::count(),
2305 Nominators::<T>::count(),
2306 Validators::<T>::count()
2307 );
2308
2309 ensure!(
2310 <T as Config>::TargetList::count() == Validators::<T>::count(),
2311 "wrong external count"
2312 );
2313 let max_validators_bound = crate::MaxWinnersOf::<T>::get();
2314 let max_winners_per_page_bound = crate::MaxWinnersPerPageOf::<T::ElectionProvider>::get();
2315 ensure!(
2316 max_validators_bound >= max_winners_per_page_bound,
2317 "max validators should be higher than per page bounds"
2318 );
2319 ensure!(ValidatorCount::<T>::get() <= max_validators_bound, Error::<T>::TooManyValidators);
2320 Ok(())
2321 }
2322
2323 fn check_ledgers() -> Result<(), TryRuntimeError> {
2331 let mut chilled_undermin: Vec<T::AccountId> = Vec::new();
2332 let mut chilled_total: u32 = 0;
2333 let mut nominator_undermin: Vec<T::AccountId> = Vec::new();
2334 let mut nominator_total: u32 = 0;
2335 let mut validator_undermin: Vec<T::AccountId> = Vec::new();
2336 let mut validator_total: u32 = 0;
2337 let mut total_ledgers: u32 = 0;
2338
2339 Bonded::<T>::iter()
2340 .map(|(stash, ctrl)| {
2341 total_ledgers += 1;
2342 if VirtualStakers::<T>::contains_key(stash.clone()) {
2344 ensure!(
2345 asset::staked::<T>(&stash) == Zero::zero(),
2346 "virtual stakers should not have any staked balance"
2347 );
2348 ensure!(
2349 <Bonded<T>>::get(stash.clone()).unwrap() == stash.clone(),
2350 "stash and controller should be same"
2351 );
2352 ensure!(
2353 Ledger::<T>::get(stash.clone()).unwrap().stash == stash,
2354 "ledger corrupted for virtual staker"
2355 );
2356 ensure!(
2357 frame_system::Pallet::<T>::account_nonce(&stash).is_zero(),
2358 "virtual stakers are keyless and should not have any nonce"
2359 );
2360 let reward_destination = <Payee<T>>::get(stash.clone()).unwrap();
2361 if let RewardDestination::Account(payee) = reward_destination {
2362 ensure!(
2363 payee != stash.clone(),
2364 "reward destination should not be same as stash for virtual staker"
2365 );
2366 } else {
2367 return Err(DispatchError::Other(
2368 "reward destination must be of account variant for virtual staker",
2369 ));
2370 }
2371 } else {
2372 let integrity = Self::inspect_bond_state(&stash);
2373 if integrity != Ok(LedgerIntegrityState::Ok) {
2374 log!(
2376 error,
2377 "defensive: bonded stash {:?} has inconsistent ledger state: {:?}",
2378 stash,
2379 integrity
2380 );
2381 }
2382 }
2383
2384 Self::ensure_ledger_consistent(&ctrl)?;
2385 Self::collect_min_bond_violations(
2386 &ctrl,
2387 &mut chilled_undermin,
2388 &mut chilled_total,
2389 &mut nominator_undermin,
2390 &mut nominator_total,
2391 &mut validator_undermin,
2392 &mut validator_total,
2393 )?;
2394 Ok(())
2395 })
2396 .collect::<Result<Vec<_>, _>>()?;
2397
2398 if chilled_total > 0 {
2399 log!(
2400 warn,
2401 "{} chilled stashes (out of {} total ledgers) have less stake than minimum role bond ({:?}). Examples: {:?}",
2402 chilled_total,
2403 total_ledgers,
2404 Self::min_chilled_bond(),
2405 chilled_undermin,
2406 );
2407 }
2408 if nominator_total > 0 {
2409 log!(
2410 warn,
2411 "{} nominators (out of {} total ledgers) have less stake than minimum role bond ({:?}). Examples: {:?}",
2412 nominator_total,
2413 total_ledgers,
2414 Self::min_nominator_bond(),
2415 nominator_undermin,
2416 );
2417 }
2418 if validator_total > 0 {
2419 log!(
2420 warn,
2421 "{} validators (out of {} total ledgers) have less stake than minimum role bond ({:?}). Examples: {:?}",
2422 validator_total,
2423 total_ledgers,
2424 Self::min_validator_bond(),
2425 validator_undermin,
2426 );
2427 }
2428
2429 Ok(())
2430 }
2431
2432 fn check_paged_exposures() -> Result<(), TryRuntimeError> {
2443 let Some(era) = ActiveEra::<T>::get().map(|a| a.index) else { return Ok(()) };
2444 let overview_and_pages = ErasStakersOverview::<T>::iter_prefix(era)
2445 .map(|(validator, metadata)| {
2446 let last_validator_era = LastValidatorEra::<T>::get(&validator).unwrap_or_default();
2447 if last_validator_era != era && last_validator_era != era + 1 {
2449 log!(
2450 error,
2451 "Validator {:?} has incorrect LastValidatorEra (expected {:?} or {:?}, got {:?})",
2452 validator,
2453 era,
2454 era + 1,
2455 last_validator_era
2456 );
2457 }
2458
2459 let pages = ErasStakersPaged::<T>::iter_prefix((era, validator))
2460 .map(|(_idx, page)| page)
2461 .collect::<Vec<_>>();
2462 (metadata, pages)
2463 })
2464 .collect::<Vec<_>>();
2465
2466 ensure!(
2467 overview_and_pages.iter().flat_map(|(_m, pages)| pages).all(|page| {
2468 let expected = page
2469 .others
2470 .iter()
2471 .map(|e| e.value)
2472 .fold(BalanceOf::<T>::zero(), |acc, x| acc + x);
2473 page.page_total == expected
2474 }),
2475 "found wrong page_total"
2476 );
2477
2478 ensure!(
2479 overview_and_pages.iter().all(|(metadata, pages)| {
2480 let page_count_good = metadata.page_count == pages.len() as u32;
2481 let nominator_count_good = metadata.nominator_count ==
2482 pages.iter().map(|p| p.others.len() as u32).fold(0u32, |acc, x| acc + x);
2483 let total_good = metadata.total ==
2484 metadata.own +
2485 pages
2486 .iter()
2487 .fold(BalanceOf::<T>::zero(), |acc, page| acc + page.page_total);
2488
2489 page_count_good && nominator_count_good && total_good
2490 }),
2491 "found bad metadata"
2492 );
2493
2494 ensure!(
2495 overview_and_pages
2496 .iter()
2497 .map(|(metadata, _pages)| metadata.total)
2498 .fold(BalanceOf::<T>::zero(), |acc, x| acc + x) ==
2499 ErasTotalStake::<T>::get(era),
2500 "found bad eras total stake"
2501 );
2502
2503 Ok(())
2504 }
2505
2506 fn check_slash_health() -> Result<(), TryRuntimeError> {
2508 let offence_queue_eras = OffenceQueueEras::<T>::get().unwrap_or_default().into_inner();
2510 let mut sorted_offence_queue_eras = offence_queue_eras.clone();
2511 sorted_offence_queue_eras.sort();
2512 ensure!(
2513 sorted_offence_queue_eras == offence_queue_eras,
2514 "Offence queue eras are not sorted"
2515 );
2516 drop(sorted_offence_queue_eras);
2517
2518 let active_era = Rotator::<T>::active_era();
2520 let oldest_unprocessed_offence_era =
2521 offence_queue_eras.first().cloned().unwrap_or(active_era);
2522
2523 let oldest_unprocessed_offence_age =
2527 active_era.saturating_sub(oldest_unprocessed_offence_era);
2528
2529 if oldest_unprocessed_offence_age > 2.min(T::BondingDuration::get()) {
2531 log!(
2532 warn,
2533 "Offence queue has unprocessed offences from older than 2 eras: oldest offence era in queue {:?} (active era: {:?})",
2534 oldest_unprocessed_offence_era,
2535 active_era
2536 );
2537 }
2538
2539 ensure!(
2541 oldest_unprocessed_offence_age < T::BondingDuration::get() - 1,
2542 "offences from era less than 3 eras old from active era not processed yet"
2543 );
2544
2545 for e in offence_queue_eras {
2547 let count = OffenceQueue::<T>::iter_prefix(e).count();
2548 ensure!(count > 0, "Offence queue is empty for era listed in offence queue eras");
2549 log!(info, "Offence queue for era {:?} has {:?} offences queued", e, count);
2550 }
2551
2552 for era in (active_era.saturating_sub(T::BondingDuration::get()))..(active_era) {
2556 Self::ensure_era_slashes_applied(era)?;
2560 }
2561
2562 for (era, _) in CancelledSlashes::<T>::iter() {
2564 ensure!(era >= active_era, "Found cancelled slashes for era before active era");
2565 }
2566
2567 Ok(())
2568 }
2569
2570 fn collect_min_bond_violations(
2573 ctrl: &T::AccountId,
2574 chilled_undermin: &mut Vec<T::AccountId>,
2575 chilled_total: &mut u32,
2576 nominator_undermin: &mut Vec<T::AccountId>,
2577 nominator_total: &mut u32,
2578 validator_undermin: &mut Vec<T::AccountId>,
2579 validator_total: &mut u32,
2580 ) -> Result<(), TryRuntimeError> {
2581 const MAX_EXAMPLES: usize = 10;
2582 let ledger = Self::ledger(StakingAccount::Controller(ctrl.clone()))?;
2583 let stash = ledger.stash;
2584
2585 let is_nominator = Nominators::<T>::contains_key(&stash);
2586 let is_validator = Validators::<T>::contains_key(&stash);
2587
2588 match (is_nominator, is_validator) {
2589 (false, false) => {
2590 if ledger.active < Self::min_chilled_bond() && !ledger.active.is_zero() {
2591 *chilled_total += 1;
2593 if chilled_undermin.len() < MAX_EXAMPLES {
2594 chilled_undermin.push(stash.clone());
2595 }
2596 log!(
2597 trace,
2598 "Chilled stash {:?} has less stake ({:?}) than minimum role bond ({:?})",
2599 stash,
2600 ledger.active,
2601 Self::min_chilled_bond()
2602 );
2603 }
2604 },
2606 (true, false) => {
2607 if ledger.active < Self::min_nominator_bond() {
2609 *nominator_total += 1;
2610 if nominator_undermin.len() < MAX_EXAMPLES {
2611 nominator_undermin.push(stash.clone());
2612 }
2613 log!(
2614 trace,
2615 "Nominator {:?} has less stake ({:?}) than minimum role bond ({:?})",
2616 stash,
2617 ledger.active,
2618 Self::min_nominator_bond()
2619 );
2620 }
2621 },
2622 (false, true) => {
2623 if ledger.active < Self::min_validator_bond() {
2625 *validator_total += 1;
2626 if validator_undermin.len() < MAX_EXAMPLES {
2627 validator_undermin.push(stash.clone());
2628 }
2629 log!(
2630 trace,
2631 "Validator {:?} has less stake ({:?}) than minimum role bond ({:?})",
2632 stash,
2633 ledger.active,
2634 Self::min_validator_bond()
2635 );
2636 }
2637 },
2638 (true, true) => {
2639 ensure!(false, "Stash cannot be both nominator and validator");
2640 },
2641 }
2642 Ok(())
2643 }
2644
2645 fn ensure_ledger_consistent(ctrl: &T::AccountId) -> Result<(), TryRuntimeError> {
2646 let ledger = Self::ledger(StakingAccount::Controller(ctrl.clone()))?;
2648
2649 let real_total: BalanceOf<T> =
2650 ledger.unlocking.iter().fold(ledger.active, |a, c| a + c.value);
2651 ensure!(real_total == ledger.total, "ledger.total corrupt");
2652
2653 Ok(())
2654 }
2655}