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, Exposure, Forcing, LedgerIntegrityState, MaxNominationsOf, Nominations,
28 NominationsQuota, PositiveImbalanceOf, RewardDestination, SnapshotStatus, StakingLedger,
29 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 Defensive, DefensiveSaturating, Get, Imbalance, InspectLockableCurrency, LockableCurrency,
42 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, SessionIndex, Stake,
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 None => Ok(LedgerIntegrityState::CorruptedKilled),
145 }
146 }
147
148 pub fn slashable_balance_of(stash: &T::AccountId) -> BalanceOf<T> {
150 Self::ledger(Stash(stash.clone())).map(|l| l.active).unwrap_or_default()
152 }
153
154 pub fn slashable_balance_of_vote_weight(
156 stash: &T::AccountId,
157 issuance: BalanceOf<T>,
158 ) -> VoteWeight {
159 T::CurrencyToVote::to_vote(Self::slashable_balance_of(stash), issuance)
160 }
161
162 pub fn weight_of_fn() -> Box<dyn Fn(&T::AccountId) -> VoteWeight> {
167 let issuance = asset::total_issuance::<T>();
170 Box::new(move |who: &T::AccountId| -> VoteWeight {
171 Self::slashable_balance_of_vote_weight(who, issuance)
172 })
173 }
174
175 pub fn weight_of(who: &T::AccountId) -> VoteWeight {
177 let issuance = asset::total_issuance::<T>();
178 Self::slashable_balance_of_vote_weight(who, issuance)
179 }
180
181 pub(crate) fn check_slash_cancelled(
183 era: EraIndex,
184 validator: &T::AccountId,
185 slash_fraction: Perbill,
186 ) -> bool {
187 let cancelled_slashes = CancelledSlashes::<T>::get(&era);
188 cancelled_slashes.iter().any(|(cancelled_validator, cancel_fraction)| {
189 *cancelled_validator == *validator && *cancel_fraction >= slash_fraction
190 })
191 }
192
193 pub(super) fn do_bond_extra(stash: &T::AccountId, additional: BalanceOf<T>) -> DispatchResult {
194 let mut ledger = Self::ledger(StakingAccount::Stash(stash.clone()))?;
195
196 let extra = if Self::is_virtual_staker(stash) {
199 additional
200 } else {
201 additional.min(asset::free_to_stake::<T>(stash))
203 };
204
205 ledger.total = ledger.total.checked_add(&extra).ok_or(ArithmeticError::Overflow)?;
206 ledger.active = ledger.active.checked_add(&extra).ok_or(ArithmeticError::Overflow)?;
207 ensure!(ledger.active >= Self::min_chilled_bond(), Error::<T>::InsufficientBond);
209
210 ledger.update()?;
212 if T::VoterList::contains(stash) {
214 let _ = T::VoterList::on_update(&stash, Self::weight_of(stash));
216 }
217
218 Self::deposit_event(Event::<T>::Bonded { stash: stash.clone(), amount: extra });
219
220 Ok(())
221 }
222
223 fn calculate_earliest_withdrawal_era(active_era: EraIndex) -> EraIndex {
227 let earliest_unlock_era_by_offence_queue = OffenceQueueEras::<T>::get()
229 .as_ref()
230 .and_then(|eras| eras.first())
231 .copied()
232 .unwrap_or(active_era)
234 .saturating_sub(1)
237 .saturating_add(T::BondingDuration::get());
240
241 active_era.min(earliest_unlock_era_by_offence_queue)
247 }
248
249 pub(super) fn do_withdraw_unbonded(controller: &T::AccountId) -> Result<Weight, DispatchError> {
250 let mut ledger = Self::ledger(Controller(controller.clone()))?;
251 let (stash, old_total) = (ledger.stash.clone(), ledger.total);
252 let active_era = Rotator::<T>::active_era();
253
254 if active_era > 1 {
256 Self::ensure_era_slashes_applied(active_era.saturating_sub(1))?;
257 }
258
259 let earliest_era_to_withdraw = Self::calculate_earliest_withdrawal_era(active_era);
260
261 log!(
262 debug,
263 "Withdrawing unbonded stake. Active_era is: {:?} | \
264 Earliest era we can allow withdrawing: {:?}",
265 active_era,
266 earliest_era_to_withdraw
267 );
268
269 ledger = ledger.consolidate_unlocked(earliest_era_to_withdraw);
271
272 let new_total = ledger.total;
273 debug_assert!(
274 new_total <= old_total,
275 "consolidate_unlocked should never increase the total balance of the ledger"
276 );
277
278 let used_weight = if ledger.unlocking.is_empty() &&
279 (ledger.active < Self::min_chilled_bond() || ledger.active.is_zero())
280 {
281 Self::kill_stash(&ledger.stash)?;
285
286 T::WeightInfo::withdraw_unbonded_kill()
287 } else {
288 ledger.update()?;
290
291 T::WeightInfo::withdraw_unbonded_update()
293 };
294
295 if new_total < old_total {
298 let value = old_total.defensive_saturating_sub(new_total);
300 Self::deposit_event(Event::<T>::Withdrawn { stash, amount: value });
301
302 T::EventListeners::on_withdraw(controller, value);
304 }
305
306 Ok(used_weight)
307 }
308
309 fn ensure_era_slashes_applied(era: EraIndex) -> Result<(), DispatchError> {
310 ensure!(
311 !UnappliedSlashes::<T>::contains_prefix(era),
312 Error::<T>::UnappliedSlashesInPreviousEra
313 );
314 Ok(())
315 }
316
317 pub(super) fn do_payout_stakers(
318 validator_stash: T::AccountId,
319 era: EraIndex,
320 ) -> DispatchResultWithPostInfo {
321 let page = Eras::<T>::get_next_claimable_page(era, &validator_stash).ok_or_else(|| {
322 Error::<T>::AlreadyClaimed.with_weight(T::WeightInfo::payout_stakers_alive_staked(0))
323 })?;
324
325 Self::do_payout_stakers_by_page(validator_stash, era, page)
326 }
327
328 pub(super) fn do_payout_stakers_by_page(
329 validator_stash: T::AccountId,
330 era: EraIndex,
331 page: Page,
332 ) -> DispatchResultWithPostInfo {
333 let current_era = CurrentEra::<T>::get().ok_or_else(|| {
335 Error::<T>::InvalidEraToReward
336 .with_weight(T::WeightInfo::payout_stakers_alive_staked(0))
337 })?;
338
339 let history_depth = T::HistoryDepth::get();
340
341 ensure!(
342 era <= current_era && era >= current_era.saturating_sub(history_depth),
343 Error::<T>::InvalidEraToReward
344 .with_weight(T::WeightInfo::payout_stakers_alive_staked(0))
345 );
346
347 ensure!(
348 page < Eras::<T>::exposure_page_count(era, &validator_stash),
349 Error::<T>::InvalidPage.with_weight(T::WeightInfo::payout_stakers_alive_staked(0))
350 );
351
352 let era_payout = Eras::<T>::get_validators_reward(era).ok_or_else(|| {
354 Error::<T>::InvalidEraToReward
355 .with_weight(T::WeightInfo::payout_stakers_alive_staked(0))
356 })?;
357
358 let account = StakingAccount::Stash(validator_stash.clone());
359 let ledger = Self::ledger(account.clone()).or_else(|_| {
360 if StakingLedger::<T>::is_bonded(account) {
361 Err(Error::<T>::NotController.into())
362 } else {
363 Err(Error::<T>::NotStash.with_weight(T::WeightInfo::payout_stakers_alive_staked(0)))
364 }
365 })?;
366
367 ledger.clone().update()?;
368
369 let stash = ledger.stash.clone();
370
371 if Eras::<T>::is_rewards_claimed(era, &stash, page) {
372 return Err(Error::<T>::AlreadyClaimed
373 .with_weight(T::WeightInfo::payout_stakers_alive_staked(0)))
374 }
375
376 Eras::<T>::set_rewards_as_claimed(era, &stash, page);
377
378 let exposure = Eras::<T>::get_paged_exposure(era, &stash, page).ok_or_else(|| {
379 Error::<T>::InvalidEraToReward
380 .with_weight(T::WeightInfo::payout_stakers_alive_staked(0))
381 })?;
382
383 let era_reward_points = Eras::<T>::get_reward_points(era);
393 let total_reward_points = era_reward_points.total;
394 let validator_reward_points =
395 era_reward_points.individual.get(&stash).copied().unwrap_or_else(Zero::zero);
396
397 if validator_reward_points.is_zero() {
399 return Ok(Some(T::WeightInfo::payout_stakers_alive_staked(0)).into())
400 }
401
402 let validator_total_reward_part =
405 Perbill::from_rational(validator_reward_points, total_reward_points);
406
407 let validator_total_payout = validator_total_reward_part * era_payout;
409
410 let validator_commission = Eras::<T>::get_validator_commission(era, &ledger.stash);
411 let validator_total_commission_payout = validator_commission * validator_total_payout;
413
414 let validator_leftover_payout =
415 validator_total_payout.defensive_saturating_sub(validator_total_commission_payout);
416 let validator_exposure_part = Perbill::from_rational(exposure.own(), exposure.total());
418 let validator_staking_payout = validator_exposure_part * validator_leftover_payout;
419 let page_stake_part = Perbill::from_rational(exposure.page_total(), exposure.total());
420 let validator_commission_payout = page_stake_part * validator_total_commission_payout;
422
423 Self::deposit_event(Event::<T>::PayoutStarted {
424 era_index: era,
425 validator_stash: stash.clone(),
426 page,
427 next: Eras::<T>::get_next_claimable_page(era, &stash),
428 });
429
430 let mut total_imbalance = PositiveImbalanceOf::<T>::zero();
431 if let Some((imbalance, dest)) =
433 Self::make_payout(&stash, validator_staking_payout + validator_commission_payout)
434 {
435 Self::deposit_event(Event::<T>::Rewarded { stash, dest, amount: imbalance.peek() });
436 total_imbalance.subsume(imbalance);
437 }
438
439 let mut nominator_payout_count: u32 = 0;
443
444 for nominator in exposure.others().iter() {
447 let nominator_exposure_part = Perbill::from_rational(nominator.value, exposure.total());
448
449 let nominator_reward: BalanceOf<T> =
450 nominator_exposure_part * validator_leftover_payout;
451 if let Some((imbalance, dest)) = Self::make_payout(&nominator.who, nominator_reward) {
453 nominator_payout_count += 1;
455 let e = Event::<T>::Rewarded {
456 stash: nominator.who.clone(),
457 dest,
458 amount: imbalance.peek(),
459 };
460 Self::deposit_event(e);
461 total_imbalance.subsume(imbalance);
462 }
463 }
464
465 T::Reward::on_unbalanced(total_imbalance);
466 debug_assert!(nominator_payout_count <= T::MaxExposurePageSize::get());
467
468 Ok(Some(T::WeightInfo::payout_stakers_alive_staked(nominator_payout_count)).into())
469 }
470
471 pub(crate) fn chill_stash(stash: &T::AccountId) {
473 let chilled_as_validator = Self::do_remove_validator(stash);
474 let chilled_as_nominator = Self::do_remove_nominator(stash);
475 if chilled_as_validator || chilled_as_nominator {
476 Self::deposit_event(Event::<T>::Chilled { stash: stash.clone() });
477 }
478 }
479
480 fn make_payout(
483 stash: &T::AccountId,
484 amount: BalanceOf<T>,
485 ) -> Option<(PositiveImbalanceOf<T>, RewardDestination<T::AccountId>)> {
486 if amount.is_zero() {
488 return None
489 }
490 let dest = Self::payee(StakingAccount::Stash(stash.clone()))?;
491
492 let maybe_imbalance = match dest {
493 RewardDestination::Stash => asset::mint_into_existing::<T>(stash, amount),
494 RewardDestination::Staked => Self::ledger(Stash(stash.clone()))
495 .and_then(|mut ledger| {
496 ledger.active += amount;
497 ledger.total += amount;
498 let r = asset::mint_into_existing::<T>(stash, amount);
499
500 let _ = ledger
501 .update()
502 .defensive_proof("ledger fetched from storage, so it exists; qed.");
503
504 Ok(r)
505 })
506 .unwrap_or_default(),
507 RewardDestination::Account(ref dest_account) =>
508 Some(asset::mint_creating::<T>(&dest_account, amount)),
509 RewardDestination::None => None,
510 #[allow(deprecated)]
511 RewardDestination::Controller => Self::bonded(stash)
512 .map(|controller| {
513 defensive!("Paying out controller as reward destination which is deprecated and should be migrated.");
514 asset::mint_creating::<T>(&controller, amount)
517 }),
518 };
519 maybe_imbalance.map(|imbalance| (imbalance, dest))
520 }
521
522 pub(crate) fn kill_stash(stash: &T::AccountId) -> DispatchResult {
530 StakingLedger::<T>::kill(&stash)?;
533
534 Self::do_remove_validator(&stash);
535 Self::do_remove_nominator(&stash);
536
537 Ok(())
538 }
539
540 #[cfg(test)]
541 pub(crate) fn reward_by_ids(validators_points: impl IntoIterator<Item = (T::AccountId, u32)>) {
542 Eras::<T>::reward_active_era(validators_points)
543 }
544
545 pub(crate) fn set_force_era(mode: Forcing) {
547 log!(info, "Setting force era mode {:?}.", mode);
548 ForceEra::<T>::put(mode);
549 Self::deposit_event(Event::<T>::ForceEra { mode });
550 }
551
552 #[cfg(feature = "runtime-benchmarks")]
553 pub fn add_era_stakers(
554 current_era: EraIndex,
555 stash: T::AccountId,
556 exposure: Exposure<T::AccountId, BalanceOf<T>>,
557 ) {
558 Eras::<T>::upsert_exposure(current_era, &stash, exposure);
559 }
560
561 #[cfg(feature = "runtime-benchmarks")]
562 pub fn set_slash_reward_fraction(fraction: Perbill) {
563 SlashRewardFraction::<T>::put(fraction);
564 }
565
566 pub(crate) fn get_npos_voters(
576 bounds: DataProviderBounds,
577 status: &SnapshotStatus<T::AccountId>,
578 ) -> Vec<VoterOf<Self>> {
579 let mut voters_size_tracker: StaticTracker<Self> = StaticTracker::default();
580
581 let page_len_prediction = {
582 let all_voter_count = T::VoterList::count();
583 bounds.count.unwrap_or(all_voter_count.into()).min(all_voter_count.into()).0
584 };
585
586 let mut all_voters = Vec::<_>::with_capacity(page_len_prediction as usize);
587
588 let weight_of = Self::weight_of_fn();
590
591 let mut voters_seen = 0u32;
592 let mut validators_taken = 0u32;
593 let mut nominators_taken = 0u32;
594 let mut min_active_stake = u64::MAX;
595
596 let mut sorted_voters = match status {
597 SnapshotStatus::Waiting => T::VoterList::iter(),
599 SnapshotStatus::Ongoing(account_id) => T::VoterList::iter_from(&account_id)
601 .defensive_unwrap_or(Box::new(vec![].into_iter())),
602 SnapshotStatus::Consumed => Box::new(vec![].into_iter()),
604 };
605
606 while all_voters.len() < page_len_prediction as usize &&
607 voters_seen < (NPOS_MAX_ITERATIONS_COEFFICIENT * page_len_prediction as u32)
608 {
609 let voter = match sorted_voters.next() {
610 Some(voter) => {
611 voters_seen.saturating_inc();
612 voter
613 },
614 None => break,
615 };
616
617 let voter_weight = weight_of(&voter);
618 if voter_weight.is_zero() {
620 log!(debug, "voter's active balance is 0. skip this voter.");
621 continue
622 }
623
624 if let Some(Nominations { targets, .. }) = <Nominators<T>>::get(&voter) {
625 if !targets.is_empty() {
626 let voter = (voter, voter_weight, targets);
631 if voters_size_tracker.try_register_voter(&voter, &bounds).is_err() {
632 Self::deposit_event(Event::<T>::SnapshotVotersSizeExceeded {
634 size: voters_size_tracker.size as u32,
635 });
636 break
637 }
638
639 all_voters.push(voter);
640 nominators_taken.saturating_inc();
641 } else {
642 defensive!("non-nominator fetched from voter list: {:?}", voter);
643 }
645 min_active_stake =
646 if voter_weight < min_active_stake { voter_weight } else { min_active_stake };
647 } else if Validators::<T>::contains_key(&voter) {
648 let self_vote = (
650 voter.clone(),
651 voter_weight,
652 vec![voter.clone()]
653 .try_into()
654 .expect("`MaxVotesPerVoter` must be greater than or equal to 1"),
655 );
656
657 if voters_size_tracker.try_register_voter(&self_vote, &bounds).is_err() {
658 Self::deposit_event(Event::<T>::SnapshotVotersSizeExceeded {
660 size: voters_size_tracker.size as u32,
661 });
662 break
663 }
664 all_voters.push(self_vote);
665 validators_taken.saturating_inc();
666 } else {
667 defensive!(
673 "invalid item in `VoterList`: {:?}, this nominator probably has too many nominations now",
674 voter,
675 );
676 }
677 }
678
679 debug_assert!(all_voters.capacity() == page_len_prediction as usize);
681
682 let min_active_stake: T::CurrencyBalance =
683 if all_voters.is_empty() { Zero::zero() } else { min_active_stake.into() };
684
685 MinimumActiveStake::<T>::put(min_active_stake);
686
687 all_voters
688 }
689
690 pub fn get_npos_targets(bounds: DataProviderBounds) -> Vec<T::AccountId> {
696 let mut targets_size_tracker: StaticTracker<Self> = StaticTracker::default();
697
698 let final_predicted_len = {
699 let all_target_count = T::TargetList::count();
700 bounds.count.unwrap_or(all_target_count.into()).min(all_target_count.into()).0
701 };
702
703 let mut all_targets = Vec::<T::AccountId>::with_capacity(final_predicted_len as usize);
704 let mut targets_seen = 0;
705
706 let mut targets_iter = T::TargetList::iter();
707 while all_targets.len() < final_predicted_len as usize &&
708 targets_seen < (NPOS_MAX_ITERATIONS_COEFFICIENT * final_predicted_len as u32)
709 {
710 let target = match targets_iter.next() {
711 Some(target) => {
712 targets_seen.saturating_inc();
713 target
714 },
715 None => break,
716 };
717
718 if targets_size_tracker.try_register_target(target.clone(), &bounds).is_err() {
719 log!(warn, "npos targets size exceeded, stopping iteration.");
721 Self::deposit_event(Event::<T>::SnapshotTargetsSizeExceeded {
722 size: targets_size_tracker.size as u32,
723 });
724 break
725 }
726
727 if Validators::<T>::contains_key(&target) {
728 all_targets.push(target);
729 }
730 }
731
732 log!(debug, "[bounds {:?}] generated {} npos targets", bounds, all_targets.len());
733
734 all_targets
735 }
736
737 pub fn do_add_nominator(who: &T::AccountId, nominations: Nominations<T>) {
746 if !Nominators::<T>::contains_key(who) {
747 let _ = T::VoterList::on_insert(who.clone(), Self::weight_of(who))
749 .defensive_unwrap_or_default();
750 }
751 Nominators::<T>::insert(who, nominations);
752 }
753
754 pub fn do_remove_nominator(who: &T::AccountId) -> bool {
763 let outcome = if Nominators::<T>::contains_key(who) {
764 Nominators::<T>::remove(who);
765 let _ = T::VoterList::on_remove(who);
766 true
767 } else {
768 false
769 };
770
771 outcome
772 }
773
774 pub fn do_add_validator(who: &T::AccountId, prefs: ValidatorPrefs) {
782 if !Validators::<T>::contains_key(who) {
783 let _ = T::VoterList::on_insert(who.clone(), Self::weight_of(who));
785 }
786 Validators::<T>::insert(who, prefs);
787 }
788
789 pub fn do_remove_validator(who: &T::AccountId) -> bool {
797 let outcome = if Validators::<T>::contains_key(who) {
798 Validators::<T>::remove(who);
799 let _ = T::VoterList::on_remove(who);
800 true
801 } else {
802 false
803 };
804
805 outcome
806 }
807
808 pub(crate) fn register_weight(weight: Weight) {
812 <frame_system::Pallet<T>>::register_extra_weight_unchecked(
813 weight,
814 DispatchClass::Mandatory,
815 );
816 }
817
818 pub fn eras_stakers(
825 era: EraIndex,
826 account: &T::AccountId,
827 ) -> Exposure<T::AccountId, BalanceOf<T>> {
828 Eras::<T>::get_full_exposure(era, account)
829 }
830
831 pub(super) fn do_migrate_currency(stash: &T::AccountId) -> DispatchResult {
832 if Self::is_virtual_staker(stash) {
833 return Self::do_migrate_virtual_staker(stash);
834 }
835
836 let ledger = Self::ledger(Stash(stash.clone()))?;
837 let staked: BalanceOf<T> = T::OldCurrency::balance_locked(STAKING_ID, stash).into();
838 ensure!(!staked.is_zero(), Error::<T>::AlreadyMigrated);
839 ensure!(ledger.total == staked, Error::<T>::BadState);
840
841 T::OldCurrency::remove_lock(STAKING_ID, &stash);
843
844 let max_hold = asset::free_to_stake::<T>(&stash);
846 let force_withdraw = if max_hold >= staked {
847 asset::update_stake::<T>(&stash, staked)?;
849 Zero::zero()
850 } else {
851 let force_withdraw = staked.saturating_sub(max_hold);
854
855 StakingLedger {
858 total: max_hold,
859 active: ledger.active.saturating_sub(force_withdraw),
860 ..ledger
862 }
863 .update()?;
864 force_withdraw
865 };
866
867 frame_system::Pallet::<T>::dec_consumers(&stash);
869
870 Self::deposit_event(Event::<T>::CurrencyMigrated { stash: stash.clone(), force_withdraw });
871 Ok(())
872 }
873
874 fn do_migrate_virtual_staker(stash: &T::AccountId) -> DispatchResult {
875 frame_system::Pallet::<T>::dec_consumers(&stash);
878
879 let actual_providers = frame_system::Pallet::<T>::providers(stash);
884
885 let expected_providers =
886 if asset::free_to_stake::<T>(&stash) >= asset::existential_deposit::<T>() {
889 2
890 } else {
891 1
892 };
893
894 ensure!(actual_providers <= expected_providers, Error::<T>::BadState);
896
897 ensure!(actual_providers == expected_providers, Error::<T>::AlreadyMigrated);
899
900 let _ = frame_system::Pallet::<T>::dec_providers(&stash)?;
902
903 return Ok(())
904 }
905}
906
907impl<T: Config> Pallet<T> {
908 pub fn api_nominations_quota(balance: BalanceOf<T>) -> u32 {
912 T::NominationsQuota::get_quota(balance)
913 }
914
915 pub fn api_eras_stakers(
916 era: EraIndex,
917 account: T::AccountId,
918 ) -> Exposure<T::AccountId, BalanceOf<T>> {
919 Self::eras_stakers(era, &account)
920 }
921
922 pub fn api_eras_stakers_page_count(era: EraIndex, account: T::AccountId) -> Page {
923 Eras::<T>::exposure_page_count(era, &account)
924 }
925
926 pub fn api_pending_rewards(era: EraIndex, account: T::AccountId) -> bool {
927 Eras::<T>::pending_rewards(era, &account)
928 }
929}
930
931impl<T: Config> ElectionDataProvider for Pallet<T> {
932 type AccountId = T::AccountId;
933 type BlockNumber = BlockNumberFor<T>;
934 type MaxVotesPerVoter = MaxNominationsOf<T>;
935
936 fn desired_targets() -> data_provider::Result<u32> {
937 Self::register_weight(T::DbWeight::get().reads(1));
938 Ok(ValidatorCount::<T>::get())
939 }
940
941 fn electing_voters(
942 bounds: DataProviderBounds,
943 page: PageIndex,
944 ) -> data_provider::Result<Vec<VoterOf<Self>>> {
945 let mut status = VoterSnapshotStatus::<T>::get();
946 let voters = Self::get_npos_voters(bounds, &status);
947
948 match (page, &status) {
950 (0, _) => status = SnapshotStatus::Waiting,
952
953 (_, SnapshotStatus::Waiting) | (_, SnapshotStatus::Ongoing(_)) => {
954 let maybe_last = voters.last().map(|(x, _, _)| x).cloned();
955
956 if let Some(ref last) = maybe_last {
957 let has_next =
958 T::VoterList::iter_from(last).ok().and_then(|mut i| i.next()).is_some();
959 if has_next {
960 status = SnapshotStatus::Ongoing(last.clone());
961 } else {
962 status = SnapshotStatus::Consumed;
963 }
964 }
965 },
966 (_, SnapshotStatus::Consumed) => (),
968 }
969
970 log!(
971 debug,
972 "[page {}, (next) status {:?}, bounds {:?}] generated {} npos voters [first: {:?}, last: {:?}]",
973 page,
974 status,
975 bounds,
976 voters.len(),
977 voters.first().map(|(x, y, _)| (x, y)),
978 voters.last().map(|(x, y, _)| (x, y)),
979 );
980
981 match status {
982 SnapshotStatus::Ongoing(_) => T::VoterList::lock(),
983 _ => T::VoterList::unlock(),
984 }
985
986 VoterSnapshotStatus::<T>::put(status);
987 debug_assert!(!bounds.slice_exhausted(&voters));
988
989 Ok(voters)
990 }
991
992 fn electing_voters_stateless(
993 bounds: DataProviderBounds,
994 ) -> data_provider::Result<Vec<VoterOf<Self>>> {
995 let voters = Self::get_npos_voters(bounds, &SnapshotStatus::Waiting);
996 log!(debug, "[stateless, bounds {:?}] generated {} npos voters", bounds, voters.len(),);
997 Ok(voters)
998 }
999
1000 fn electable_targets(
1001 bounds: DataProviderBounds,
1002 page: PageIndex,
1003 ) -> data_provider::Result<Vec<T::AccountId>> {
1004 if page > 0 {
1005 log!(warn, "multi-page target snapshot not supported, returning page 0.");
1006 }
1007
1008 let targets = Self::get_npos_targets(bounds);
1009 if bounds.exhausted(None, CountBound(targets.len() as u32).into()) {
1010 return Err("Target snapshot too big")
1011 }
1012
1013 debug_assert!(!bounds.slice_exhausted(&targets));
1014
1015 Ok(targets)
1016 }
1017
1018 fn next_election_prediction(_: BlockNumberFor<T>) -> BlockNumberFor<T> {
1019 debug_assert!(false, "this is deprecated and not used anymore");
1020 sp_runtime::traits::Bounded::max_value()
1021 }
1022
1023 #[cfg(feature = "runtime-benchmarks")]
1024 fn fetch_page(page: PageIndex) {
1025 session_rotation::EraElectionPlanner::<T>::do_elect_paged(page);
1026 }
1027
1028 #[cfg(feature = "runtime-benchmarks")]
1029 fn add_voter(
1030 voter: T::AccountId,
1031 weight: VoteWeight,
1032 targets: BoundedVec<T::AccountId, Self::MaxVotesPerVoter>,
1033 ) {
1034 let stake = <BalanceOf<T>>::try_from(weight).unwrap_or_else(|_| {
1035 panic!("cannot convert a VoteWeight into BalanceOf, benchmark needs reconfiguring.")
1036 });
1037 <Bonded<T>>::insert(voter.clone(), voter.clone());
1038 <Ledger<T>>::insert(voter.clone(), StakingLedger::<T>::new(voter.clone(), stake));
1039
1040 Self::do_add_nominator(&voter, Nominations { targets, submitted_in: 0, suppressed: false });
1041 }
1042
1043 #[cfg(feature = "runtime-benchmarks")]
1044 fn add_target(target: T::AccountId) {
1045 let stake = (Self::min_validator_bond() + 1u32.into()) * 100u32.into();
1046 <Bonded<T>>::insert(target.clone(), target.clone());
1047 <Ledger<T>>::insert(target.clone(), StakingLedger::<T>::new(target.clone(), stake));
1048 Self::do_add_validator(
1049 &target,
1050 ValidatorPrefs { commission: Perbill::zero(), blocked: false },
1051 );
1052 }
1053
1054 #[cfg(feature = "runtime-benchmarks")]
1055 fn clear() {
1056 #[allow(deprecated)]
1057 <Bonded<T>>::remove_all(None);
1058 #[allow(deprecated)]
1059 <Ledger<T>>::remove_all(None);
1060 #[allow(deprecated)]
1061 <Validators<T>>::remove_all();
1062 #[allow(deprecated)]
1063 <Nominators<T>>::remove_all();
1064
1065 T::VoterList::unsafe_clear();
1066 }
1067
1068 #[cfg(feature = "runtime-benchmarks")]
1069 fn put_snapshot(
1070 voters: Vec<VoterOf<Self>>,
1071 targets: Vec<T::AccountId>,
1072 target_stake: Option<VoteWeight>,
1073 ) {
1074 targets.into_iter().for_each(|v| {
1075 let stake: BalanceOf<T> = target_stake
1076 .and_then(|w| <BalanceOf<T>>::try_from(w).ok())
1077 .unwrap_or_else(|| Self::min_nominator_bond() * 100u32.into());
1078 <Bonded<T>>::insert(v.clone(), v.clone());
1079 <Ledger<T>>::insert(v.clone(), StakingLedger::<T>::new(v.clone(), stake));
1080 Self::do_add_validator(
1081 &v,
1082 ValidatorPrefs { commission: Perbill::zero(), blocked: false },
1083 );
1084 });
1085
1086 voters.into_iter().for_each(|(v, s, t)| {
1087 let stake = <BalanceOf<T>>::try_from(s).unwrap_or_else(|_| {
1088 panic!("cannot convert a VoteWeight into BalanceOf, benchmark needs reconfiguring.")
1089 });
1090 <Bonded<T>>::insert(v.clone(), v.clone());
1091 <Ledger<T>>::insert(v.clone(), StakingLedger::<T>::new(v.clone(), stake));
1092 Self::do_add_nominator(
1093 &v,
1094 Nominations { targets: t, submitted_in: 0, suppressed: false },
1095 );
1096 });
1097 }
1098
1099 #[cfg(feature = "runtime-benchmarks")]
1100 fn set_desired_targets(count: u32) {
1101 ValidatorCount::<T>::put(count);
1102 }
1103}
1104
1105impl<T: Config> rc_client::AHStakingInterface for Pallet<T> {
1106 type AccountId = T::AccountId;
1107 type MaxValidatorSet = T::MaxValidatorSet;
1108
1109 fn on_relay_session_report(report: rc_client::SessionReport<Self::AccountId>) -> Weight {
1118 log!(debug, "Received session report: {}", report,);
1119
1120 let rc_client::SessionReport {
1121 end_index,
1122 activation_timestamp,
1123 validator_points,
1124 leftover,
1125 } = report;
1126 debug_assert!(!leftover);
1127
1128 Eras::<T>::reward_active_era(validator_points.into_iter());
1130 session_rotation::Rotator::<T>::end_session(end_index, activation_timestamp)
1131 }
1132
1133 fn weigh_on_relay_session_report(
1134 _report: &rc_client::SessionReport<Self::AccountId>,
1135 ) -> Weight {
1136 T::WeightInfo::rc_on_session_report()
1138 }
1139
1140 fn on_new_offences(
1151 slash_session: SessionIndex,
1152 offences: Vec<rc_client::Offence<T::AccountId>>,
1153 ) -> Weight {
1154 log!(debug, "🦹 on_new_offences: {:?}", offences);
1155 let weight = T::WeightInfo::rc_on_offence(offences.len() as u32);
1156
1157 let Some(active_era) = ActiveEra::<T>::get() else {
1159 log!(warn, "🦹 on_new_offences: no active era; ignoring offence");
1160 return T::WeightInfo::rc_on_offence(0);
1161 };
1162
1163 let active_era_start_session = Rotator::<T>::active_era_start_session_index();
1164
1165 let offence_era = if slash_session >= active_era_start_session {
1168 active_era.index
1169 } else {
1170 match BondedEras::<T>::get()
1171 .iter()
1172 .rev()
1174 .find_map(|&(era, sesh)| if sesh <= slash_session { Some(era) } else { None })
1175 {
1176 Some(era) => era,
1177 None => {
1178 log!(warn, "🦹 on_offence: no era found for slash_session; ignoring offence");
1181 return T::WeightInfo::rc_on_offence(0);
1182 },
1183 }
1184 };
1185
1186 let oldest_reportable_offence_era = if T::SlashDeferDuration::get() == 0 {
1187 active_era.index.saturating_sub(T::BondingDuration::get())
1190 } else {
1191 active_era.index.saturating_sub(T::SlashDeferDuration::get().saturating_sub(1))
1194 };
1195
1196 let invulnerables = Invulnerables::<T>::get();
1197
1198 for o in offences {
1199 let slash_fraction = o.slash_fraction;
1200 let validator: <T as frame_system::Config>::AccountId = o.offender.into();
1201 if invulnerables.contains(&validator) {
1203 log!(debug, "🦹 on_offence: {:?} is invulnerable; ignoring offence", validator);
1204 continue
1205 }
1206
1207 if offence_era < oldest_reportable_offence_era {
1209 log!(warn, "🦹 on_new_offences: offence era {:?} too old; Can only accept offences from era {:?} or newer", offence_era, oldest_reportable_offence_era);
1210 Self::deposit_event(Event::<T>::OffenceTooOld {
1211 validator: validator.clone(),
1212 fraction: slash_fraction,
1213 offence_era,
1214 });
1215 continue;
1217 }
1218 let Some(exposure_overview) = <ErasStakersOverview<T>>::get(&offence_era, &validator)
1219 else {
1220 log!(
1223 warn,
1224 "🦹 on_offence: no exposure found for {:?} in era {}; ignoring offence",
1225 validator,
1226 offence_era
1227 );
1228 continue;
1229 };
1230
1231 Self::deposit_event(Event::<T>::OffenceReported {
1232 validator: validator.clone(),
1233 fraction: slash_fraction,
1234 offence_era,
1235 });
1236
1237 let prior_slash_fraction = ValidatorSlashInEra::<T>::get(offence_era, &validator)
1238 .map_or(Zero::zero(), |(f, _)| f);
1239
1240 if let Some(existing) = OffenceQueue::<T>::get(offence_era, &validator) {
1241 if slash_fraction.deconstruct() > existing.slash_fraction.deconstruct() {
1242 OffenceQueue::<T>::insert(
1243 offence_era,
1244 &validator,
1245 OffenceRecord {
1246 reporter: o.reporters.first().cloned(),
1247 reported_era: active_era.index,
1248 slash_fraction,
1249 ..existing
1250 },
1251 );
1252
1253 ValidatorSlashInEra::<T>::insert(
1255 offence_era,
1256 &validator,
1257 (slash_fraction, exposure_overview.own),
1258 );
1259
1260 log!(
1261 debug,
1262 "🦹 updated slash for {:?}: {:?} (prior: {:?})",
1263 validator,
1264 slash_fraction,
1265 prior_slash_fraction,
1266 );
1267 } else {
1268 log!(
1269 debug,
1270 "🦹 ignored slash for {:?}: {:?} (existing prior is larger: {:?})",
1271 validator,
1272 slash_fraction,
1273 prior_slash_fraction,
1274 );
1275 }
1276 } else if slash_fraction.deconstruct() > prior_slash_fraction.deconstruct() {
1277 ValidatorSlashInEra::<T>::insert(
1278 offence_era,
1279 &validator,
1280 (slash_fraction, exposure_overview.own),
1281 );
1282
1283 OffenceQueue::<T>::insert(
1284 offence_era,
1285 &validator,
1286 OffenceRecord {
1287 reporter: o.reporters.first().cloned(),
1288 reported_era: active_era.index,
1289 exposure_page: exposure_overview.page_count.saturating_sub(1),
1292 slash_fraction,
1293 prior_slash_fraction,
1294 },
1295 );
1296
1297 OffenceQueueEras::<T>::mutate(|q| {
1298 if let Some(eras) = q {
1299 log!(debug, "🦹 inserting offence era {} into existing queue", offence_era);
1300 eras.binary_search(&offence_era).err().map(|idx| {
1301 eras.try_insert(idx, offence_era).defensive_proof(
1302 "Offence era must be present in the existing queue",
1303 )
1304 });
1305 } else {
1306 let mut eras = WeakBoundedVec::default();
1307 log!(debug, "🦹 inserting offence era {} into empty queue", offence_era);
1308 let _ = eras
1309 .try_push(offence_era)
1310 .defensive_proof("Failed to push offence era into empty queue");
1311 *q = Some(eras);
1312 }
1313 });
1314
1315 log!(
1316 debug,
1317 "🦹 queued slash for {:?}: {:?} (prior: {:?})",
1318 validator,
1319 slash_fraction,
1320 prior_slash_fraction,
1321 );
1322 } else {
1323 log!(
1324 debug,
1325 "🦹 ignored slash for {:?}: {:?} (already slashed in era with prior: {:?})",
1326 validator,
1327 slash_fraction,
1328 prior_slash_fraction,
1329 );
1330 }
1331 }
1332
1333 weight
1334 }
1335
1336 fn weigh_on_new_offences(offence_count: u32) -> Weight {
1337 T::WeightInfo::rc_on_offence(offence_count)
1338 }
1339
1340 fn active_era_start_session_index() -> SessionIndex {
1341 Rotator::<T>::active_era_start_session_index()
1342 }
1343}
1344
1345impl<T: Config> ScoreProvider<T::AccountId> for Pallet<T> {
1346 type Score = VoteWeight;
1347
1348 fn score(who: &T::AccountId) -> Option<Self::Score> {
1349 Self::ledger(Stash(who.clone()))
1350 .ok()
1351 .and_then(|l| {
1352 if Nominators::<T>::contains_key(&l.stash) ||
1353 Validators::<T>::contains_key(&l.stash)
1354 {
1355 Some(l.active)
1356 } else {
1357 None
1358 }
1359 })
1360 .map(|a| {
1361 let issuance = asset::total_issuance::<T>();
1362 T::CurrencyToVote::to_vote(a, issuance)
1363 })
1364 }
1365
1366 #[cfg(feature = "runtime-benchmarks")]
1367 fn set_score_of(who: &T::AccountId, weight: Self::Score) {
1368 let active: BalanceOf<T> = weight.try_into().map_err(|_| ()).unwrap();
1371 let mut ledger = match Self::ledger(StakingAccount::Stash(who.clone())) {
1372 Ok(l) => l,
1373 Err(_) => StakingLedger::default_from(who.clone()),
1374 };
1375 ledger.active = active;
1376
1377 <Ledger<T>>::insert(who, ledger);
1378 <Bonded<T>>::insert(who, who);
1379 <Validators<T>>::insert(who, ValidatorPrefs::default());
1382
1383 let imbalance = asset::burn::<T>(asset::total_issuance::<T>());
1387 core::mem::forget(imbalance);
1390 }
1391}
1392
1393pub struct UseValidatorsMap<T>(core::marker::PhantomData<T>);
1397impl<T: Config> SortedListProvider<T::AccountId> for UseValidatorsMap<T> {
1398 type Score = BalanceOf<T>;
1399 type Error = ();
1400
1401 fn iter() -> Box<dyn Iterator<Item = T::AccountId>> {
1403 Box::new(Validators::<T>::iter().map(|(v, _)| v))
1404 }
1405 fn iter_from(
1406 start: &T::AccountId,
1407 ) -> Result<Box<dyn Iterator<Item = T::AccountId>>, Self::Error> {
1408 if Validators::<T>::contains_key(start) {
1409 let start_key = Validators::<T>::hashed_key_for(start);
1410 Ok(Box::new(Validators::<T>::iter_from(start_key).map(|(n, _)| n)))
1411 } else {
1412 Err(())
1413 }
1414 }
1415 fn lock() {}
1416 fn unlock() {}
1417 fn count() -> u32 {
1418 Validators::<T>::count()
1419 }
1420 fn contains(id: &T::AccountId) -> bool {
1421 Validators::<T>::contains_key(id)
1422 }
1423 fn on_insert(_: T::AccountId, _weight: Self::Score) -> Result<(), Self::Error> {
1424 Ok(())
1426 }
1427 fn get_score(id: &T::AccountId) -> Result<Self::Score, Self::Error> {
1428 Ok(Pallet::<T>::weight_of(id).into())
1429 }
1430 fn on_update(_: &T::AccountId, _weight: Self::Score) -> Result<(), Self::Error> {
1431 Ok(())
1433 }
1434 fn on_remove(_: &T::AccountId) -> Result<(), Self::Error> {
1435 Ok(())
1437 }
1438 fn unsafe_regenerate(
1439 _: impl IntoIterator<Item = T::AccountId>,
1440 _: Box<dyn Fn(&T::AccountId) -> Option<Self::Score>>,
1441 ) -> u32 {
1442 0
1444 }
1445 #[cfg(feature = "try-runtime")]
1446 fn try_state() -> Result<(), TryRuntimeError> {
1447 Ok(())
1448 }
1449
1450 fn unsafe_clear() {
1451 #[allow(deprecated)]
1452 Validators::<T>::remove_all();
1453 }
1454
1455 #[cfg(feature = "runtime-benchmarks")]
1456 fn score_update_worst_case(_who: &T::AccountId, _is_increase: bool) -> Self::Score {
1457 unimplemented!()
1458 }
1459}
1460
1461pub struct UseNominatorsAndValidatorsMap<T>(core::marker::PhantomData<T>);
1465impl<T: Config> SortedListProvider<T::AccountId> for UseNominatorsAndValidatorsMap<T> {
1466 type Error = ();
1467 type Score = VoteWeight;
1468
1469 fn iter() -> Box<dyn Iterator<Item = T::AccountId>> {
1470 Box::new(
1471 Validators::<T>::iter()
1472 .map(|(v, _)| v)
1473 .chain(Nominators::<T>::iter().map(|(n, _)| n)),
1474 )
1475 }
1476 fn iter_from(
1477 start: &T::AccountId,
1478 ) -> Result<Box<dyn Iterator<Item = T::AccountId>>, Self::Error> {
1479 if Validators::<T>::contains_key(start) {
1480 let start_key = Validators::<T>::hashed_key_for(start);
1481 Ok(Box::new(
1482 Validators::<T>::iter_from(start_key)
1483 .map(|(n, _)| n)
1484 .chain(Nominators::<T>::iter().map(|(x, _)| x)),
1485 ))
1486 } else if Nominators::<T>::contains_key(start) {
1487 let start_key = Nominators::<T>::hashed_key_for(start);
1488 Ok(Box::new(Nominators::<T>::iter_from(start_key).map(|(n, _)| n)))
1489 } else {
1490 Err(())
1491 }
1492 }
1493 fn lock() {}
1494 fn unlock() {}
1495 fn count() -> u32 {
1496 Nominators::<T>::count().saturating_add(Validators::<T>::count())
1497 }
1498 fn contains(id: &T::AccountId) -> bool {
1499 Nominators::<T>::contains_key(id) || Validators::<T>::contains_key(id)
1500 }
1501 fn on_insert(_: T::AccountId, _weight: Self::Score) -> Result<(), Self::Error> {
1502 Ok(())
1504 }
1505 fn get_score(id: &T::AccountId) -> Result<Self::Score, Self::Error> {
1506 Ok(Pallet::<T>::weight_of(id))
1507 }
1508 fn on_update(_: &T::AccountId, _weight: Self::Score) -> Result<(), Self::Error> {
1509 Ok(())
1511 }
1512 fn on_remove(_: &T::AccountId) -> Result<(), Self::Error> {
1513 Ok(())
1515 }
1516 fn unsafe_regenerate(
1517 _: impl IntoIterator<Item = T::AccountId>,
1518 _: Box<dyn Fn(&T::AccountId) -> Option<Self::Score>>,
1519 ) -> u32 {
1520 0
1522 }
1523
1524 #[cfg(feature = "try-runtime")]
1525 fn try_state() -> Result<(), TryRuntimeError> {
1526 Ok(())
1527 }
1528
1529 fn unsafe_clear() {
1530 #[allow(deprecated)]
1533 Nominators::<T>::remove_all();
1534 #[allow(deprecated)]
1535 Validators::<T>::remove_all();
1536 }
1537
1538 #[cfg(feature = "runtime-benchmarks")]
1539 fn score_update_worst_case(_who: &T::AccountId, _is_increase: bool) -> Self::Score {
1540 unimplemented!()
1541 }
1542}
1543
1544impl<T: Config> StakingInterface for Pallet<T> {
1545 type AccountId = T::AccountId;
1546 type Balance = BalanceOf<T>;
1547 type CurrencyToVote = T::CurrencyToVote;
1548
1549 fn minimum_nominator_bond() -> Self::Balance {
1550 Self::min_nominator_bond()
1551 }
1552
1553 fn minimum_validator_bond() -> Self::Balance {
1554 Self::min_validator_bond()
1555 }
1556
1557 fn stash_by_ctrl(controller: &Self::AccountId) -> Result<Self::AccountId, DispatchError> {
1558 Self::ledger(Controller(controller.clone()))
1559 .map(|l| l.stash)
1560 .map_err(|e| e.into())
1561 }
1562
1563 fn bonding_duration() -> EraIndex {
1564 T::BondingDuration::get()
1565 }
1566
1567 fn current_era() -> EraIndex {
1568 CurrentEra::<T>::get().unwrap_or(Zero::zero())
1569 }
1570
1571 fn stake(who: &Self::AccountId) -> Result<Stake<BalanceOf<T>>, DispatchError> {
1572 Self::ledger(Stash(who.clone()))
1573 .map(|l| Stake { total: l.total, active: l.active })
1574 .map_err(|e| e.into())
1575 }
1576
1577 fn bond_extra(who: &Self::AccountId, extra: Self::Balance) -> DispatchResult {
1578 Self::bond_extra(RawOrigin::Signed(who.clone()).into(), extra)
1579 }
1580
1581 fn unbond(who: &Self::AccountId, value: Self::Balance) -> DispatchResult {
1582 let ctrl = Self::bonded(who).ok_or(Error::<T>::NotStash)?;
1583 Self::unbond(RawOrigin::Signed(ctrl).into(), value)
1584 .map_err(|with_post| with_post.error)
1585 .map(|_| ())
1586 }
1587
1588 fn set_payee(stash: &Self::AccountId, reward_acc: &Self::AccountId) -> DispatchResult {
1589 ensure!(
1593 !Self::is_virtual_staker(stash) || stash != reward_acc,
1594 Error::<T>::RewardDestinationRestricted
1595 );
1596
1597 let ledger = Self::ledger(Stash(stash.clone()))?;
1598 let _ = ledger
1599 .set_payee(RewardDestination::Account(reward_acc.clone()))
1600 .defensive_proof("ledger was retrieved from storage, thus its bonded; qed.")?;
1601
1602 Ok(())
1603 }
1604
1605 fn chill(who: &Self::AccountId) -> DispatchResult {
1606 let ctrl = Self::bonded(who).ok_or(Error::<T>::NotStash)?;
1609 Self::chill(RawOrigin::Signed(ctrl).into())
1610 }
1611
1612 fn withdraw_unbonded(
1613 who: Self::AccountId,
1614 _num_slashing_spans: u32,
1615 ) -> Result<bool, DispatchError> {
1616 let ctrl = Self::bonded(&who).ok_or(Error::<T>::NotStash)?;
1617 Self::withdraw_unbonded(RawOrigin::Signed(ctrl.clone()).into(), 0)
1618 .map(|_| !StakingLedger::<T>::is_bonded(StakingAccount::Controller(ctrl)))
1619 .map_err(|with_post| with_post.error)
1620 }
1621
1622 fn bond(
1623 who: &Self::AccountId,
1624 value: Self::Balance,
1625 payee: &Self::AccountId,
1626 ) -> DispatchResult {
1627 Self::bond(
1628 RawOrigin::Signed(who.clone()).into(),
1629 value,
1630 RewardDestination::Account(payee.clone()),
1631 )
1632 }
1633
1634 fn nominate(who: &Self::AccountId, targets: Vec<Self::AccountId>) -> DispatchResult {
1635 let ctrl = Self::bonded(who).ok_or(Error::<T>::NotStash)?;
1636 let targets = targets.into_iter().map(T::Lookup::unlookup).collect::<Vec<_>>();
1637 Self::nominate(RawOrigin::Signed(ctrl).into(), targets)
1638 }
1639
1640 fn desired_validator_count() -> u32 {
1641 ValidatorCount::<T>::get()
1642 }
1643
1644 fn election_ongoing() -> bool {
1645 <T::ElectionProvider as ElectionProvider>::status().is_ok()
1646 }
1647
1648 fn force_unstake(who: Self::AccountId) -> sp_runtime::DispatchResult {
1649 Self::force_unstake(RawOrigin::Root.into(), who.clone(), 0)
1650 }
1651
1652 fn is_exposed_in_era(who: &Self::AccountId, era: &EraIndex) -> bool {
1653 ErasStakersPaged::<T>::iter_prefix((era,)).any(|((validator, _), exposure_page)| {
1654 validator == *who || exposure_page.others.iter().any(|i| i.who == *who)
1655 })
1656 }
1657
1658 fn status(
1659 who: &Self::AccountId,
1660 ) -> Result<sp_staking::StakerStatus<Self::AccountId>, DispatchError> {
1661 if !StakingLedger::<T>::is_bonded(StakingAccount::Stash(who.clone())) {
1662 return Err(Error::<T>::NotStash.into())
1663 }
1664
1665 let is_validator = Validators::<T>::contains_key(&who);
1666 let is_nominator = Nominators::<T>::get(&who);
1667
1668 use sp_staking::StakerStatus;
1669 match (is_validator, is_nominator.is_some()) {
1670 (false, false) => Ok(StakerStatus::Idle),
1671 (true, false) => Ok(StakerStatus::Validator),
1672 (false, true) => Ok(StakerStatus::Nominator(
1673 is_nominator.expect("is checked above; qed").targets.into_inner(),
1674 )),
1675 (true, true) => {
1676 defensive!("cannot be both validators and nominator");
1677 Err(Error::<T>::BadState.into())
1678 },
1679 }
1680 }
1681
1682 fn is_virtual_staker(who: &T::AccountId) -> bool {
1687 frame_system::Pallet::<T>::account_nonce(who).is_zero() &&
1688 VirtualStakers::<T>::contains_key(who)
1689 }
1690
1691 fn slash_reward_fraction() -> Perbill {
1692 SlashRewardFraction::<T>::get()
1693 }
1694
1695 sp_staking::runtime_benchmarks_enabled! {
1696 fn nominations(who: &Self::AccountId) -> Option<Vec<T::AccountId>> {
1697 Nominators::<T>::get(who).map(|n| n.targets.into_inner())
1698 }
1699
1700 fn add_era_stakers(
1701 current_era: &EraIndex,
1702 stash: &T::AccountId,
1703 exposures: Vec<(Self::AccountId, Self::Balance)>,
1704 ) {
1705 let others = exposures
1706 .iter()
1707 .map(|(who, value)| crate::IndividualExposure { who: who.clone(), value: *value })
1708 .collect::<Vec<_>>();
1709 let exposure = Exposure { total: Default::default(), own: Default::default(), others };
1710 Eras::<T>::upsert_exposure(*current_era, stash, exposure);
1711 }
1712
1713 fn set_current_era(era: EraIndex) {
1714 CurrentEra::<T>::put(era);
1715 }
1716
1717 fn max_exposure_page_size() -> Page {
1718 T::MaxExposurePageSize::get()
1719 }
1720 }
1721}
1722
1723impl<T: Config> sp_staking::StakingUnchecked for Pallet<T> {
1724 fn migrate_to_virtual_staker(who: &Self::AccountId) -> DispatchResult {
1725 asset::kill_stake::<T>(who)?;
1726 VirtualStakers::<T>::insert(who, ());
1727 Ok(())
1728 }
1729
1730 fn virtual_bond(
1734 keyless_who: &Self::AccountId,
1735 value: Self::Balance,
1736 payee: &Self::AccountId,
1737 ) -> DispatchResult {
1738 if StakingLedger::<T>::is_bonded(StakingAccount::Stash(keyless_who.clone())) {
1739 return Err(Error::<T>::AlreadyBonded.into())
1740 }
1741
1742 ensure!(keyless_who != payee, Error::<T>::RewardDestinationRestricted);
1744
1745 VirtualStakers::<T>::insert(keyless_who, ());
1747
1748 Self::deposit_event(Event::<T>::Bonded { stash: keyless_who.clone(), amount: value });
1749 let ledger = StakingLedger::<T>::new(keyless_who.clone(), value);
1750
1751 ledger.bond(RewardDestination::Account(payee.clone()))?;
1752
1753 Ok(())
1754 }
1755
1756 #[cfg(feature = "runtime-benchmarks")]
1758 fn migrate_to_direct_staker(who: &Self::AccountId) {
1759 assert!(VirtualStakers::<T>::contains_key(who));
1760 let ledger = StakingLedger::<T>::get(Stash(who.clone())).unwrap();
1761 let _ = asset::update_stake::<T>(who, ledger.total)
1762 .expect("funds must be transferred to stash");
1763 VirtualStakers::<T>::remove(who);
1764 }
1765}
1766
1767#[cfg(any(test, feature = "try-runtime"))]
1768impl<T: Config> Pallet<T> {
1769 pub(crate) fn do_try_state(_now: BlockNumberFor<T>) -> Result<(), TryRuntimeError> {
1770 if ActiveEra::<T>::get().is_none() && CurrentEra::<T>::get().is_none() {
1773 return Ok(());
1774 }
1775
1776 session_rotation::Rotator::<T>::do_try_state()?;
1777 session_rotation::Eras::<T>::do_try_state()?;
1778
1779 use frame_support::traits::fungible::Inspect;
1780 if T::CurrencyToVote::will_downscale(T::Currency::total_issuance()).map_or(false, |x| x) {
1781 log!(warn, "total issuance will cause T::CurrencyToVote to downscale -- report to maintainers.")
1782 }
1783
1784 Self::check_ledgers()?;
1785 Self::check_bonded_consistency()?;
1786 Self::check_payees()?;
1787 Self::check_paged_exposures()?;
1788 Self::check_count()?;
1789 Self::check_slash_health()?;
1790
1791 Ok(())
1792 }
1793
1794 fn check_bonded_consistency() -> Result<(), TryRuntimeError> {
1804 use alloc::collections::btree_set::BTreeSet;
1805
1806 let mut count_controller_double = 0;
1807 let mut count_double = 0;
1808 let mut count_none = 0;
1809 let mut controllers = BTreeSet::new();
1812
1813 for (stash, controller) in <Bonded<T>>::iter() {
1814 if !controllers.insert(controller.clone()) {
1815 count_controller_double += 1;
1816 }
1817
1818 match (<Ledger<T>>::get(&stash), <Ledger<T>>::get(&controller)) {
1819 (Some(_), Some(_)) =>
1820 if stash != controller {
1824 count_double += 1;
1825 },
1826 (None, None) => {
1827 count_none += 1;
1828 },
1829 _ => {},
1830 };
1831 }
1832
1833 if count_controller_double != 0 {
1834 log!(
1835 warn,
1836 "a controller is associated with more than one ledger ({} occurrences)",
1837 count_controller_double
1838 );
1839 };
1840
1841 if count_double != 0 {
1842 log!(warn, "single tuple of (stash, controller) pair bonds more than one ledger ({} occurrences)", count_double);
1843 }
1844
1845 if count_none != 0 {
1846 log!(warn, "inconsistent bonded state: (stash, controller) pair missing associated ledger ({} occurrences)", count_none);
1847 }
1848
1849 Ok(())
1850 }
1851
1852 fn check_payees() -> Result<(), TryRuntimeError> {
1857 for (stash, _) in Bonded::<T>::iter() {
1858 ensure!(Payee::<T>::get(&stash).is_some(), "bonded ledger does not have payee set");
1859 }
1860
1861 ensure!(
1862 (Ledger::<T>::iter().count() == Payee::<T>::iter().count()) &&
1863 (Ledger::<T>::iter().count() == Bonded::<T>::iter().count()),
1864 "number of entries in payee storage items does not match the number of bonded ledgers",
1865 );
1866
1867 Ok(())
1868 }
1869
1870 fn check_count() -> Result<(), TryRuntimeError> {
1876 ensure!(
1877 <T as Config>::VoterList::count() ==
1878 Nominators::<T>::count() + Validators::<T>::count(),
1879 "wrong external count"
1880 );
1881 ensure!(
1882 <T as Config>::TargetList::count() == Validators::<T>::count(),
1883 "wrong external count"
1884 );
1885 let max_validators_bound = crate::MaxWinnersOf::<T>::get();
1886 let max_winners_per_page_bound = crate::MaxWinnersPerPageOf::<T::ElectionProvider>::get();
1887 ensure!(
1888 max_validators_bound >= max_winners_per_page_bound,
1889 "max validators should be higher than per page bounds"
1890 );
1891 ensure!(ValidatorCount::<T>::get() <= max_validators_bound, Error::<T>::TooManyValidators);
1892 Ok(())
1893 }
1894
1895 fn check_ledgers() -> Result<(), TryRuntimeError> {
1903 Bonded::<T>::iter()
1904 .map(|(stash, ctrl)| {
1905 if VirtualStakers::<T>::contains_key(stash.clone()) {
1907 ensure!(
1908 asset::staked::<T>(&stash) == Zero::zero(),
1909 "virtual stakers should not have any staked balance"
1910 );
1911 ensure!(
1912 <Bonded<T>>::get(stash.clone()).unwrap() == stash.clone(),
1913 "stash and controller should be same"
1914 );
1915 ensure!(
1916 Ledger::<T>::get(stash.clone()).unwrap().stash == stash,
1917 "ledger corrupted for virtual staker"
1918 );
1919 ensure!(
1920 frame_system::Pallet::<T>::account_nonce(&stash).is_zero(),
1921 "virtual stakers are keyless and should not have any nonce"
1922 );
1923 let reward_destination = <Payee<T>>::get(stash.clone()).unwrap();
1924 if let RewardDestination::Account(payee) = reward_destination {
1925 ensure!(
1926 payee != stash.clone(),
1927 "reward destination should not be same as stash for virtual staker"
1928 );
1929 } else {
1930 return Err(DispatchError::Other(
1931 "reward destination must be of account variant for virtual staker",
1932 ));
1933 }
1934 } else {
1935 let integrity = Self::inspect_bond_state(&stash);
1936 if integrity != Ok(LedgerIntegrityState::Ok) {
1937 log!(
1939 error,
1940 "defensive: bonded stash {:?} has inconsistent ledger state: {:?}",
1941 stash,
1942 integrity
1943 );
1944 }
1945 }
1946
1947 Self::ensure_ledger_consistent(&ctrl)?;
1948 Self::ensure_ledger_role_and_min_bond(&ctrl)?;
1949 Ok(())
1950 })
1951 .collect::<Result<Vec<_>, _>>()?;
1952 Ok(())
1953 }
1954
1955 fn check_paged_exposures() -> Result<(), TryRuntimeError> {
1964 let Some(era) = ActiveEra::<T>::get().map(|a| a.index) else { return Ok(()) };
1965 let overview_and_pages = ErasStakersOverview::<T>::iter_prefix(era)
1966 .map(|(validator, metadata)| {
1967 let pages = ErasStakersPaged::<T>::iter_prefix((era, validator))
1968 .map(|(_idx, page)| page)
1969 .collect::<Vec<_>>();
1970 (metadata, pages)
1971 })
1972 .collect::<Vec<_>>();
1973
1974 ensure!(
1975 overview_and_pages.iter().flat_map(|(_m, pages)| pages).all(|page| {
1976 let expected = page
1977 .others
1978 .iter()
1979 .map(|e| e.value)
1980 .fold(BalanceOf::<T>::zero(), |acc, x| acc + x);
1981 page.page_total == expected
1982 }),
1983 "found wrong page_total"
1984 );
1985
1986 ensure!(
1987 overview_and_pages.iter().all(|(metadata, pages)| {
1988 let page_count_good = metadata.page_count == pages.len() as u32;
1989 let nominator_count_good = metadata.nominator_count ==
1990 pages.iter().map(|p| p.others.len() as u32).fold(0u32, |acc, x| acc + x);
1991 let total_good = metadata.total ==
1992 metadata.own +
1993 pages
1994 .iter()
1995 .fold(BalanceOf::<T>::zero(), |acc, page| acc + page.page_total);
1996
1997 page_count_good && nominator_count_good && total_good
1998 }),
1999 "found bad metadata"
2000 );
2001
2002 ensure!(
2003 overview_and_pages
2004 .iter()
2005 .map(|(metadata, _pages)| metadata.total)
2006 .fold(BalanceOf::<T>::zero(), |acc, x| acc + x) ==
2007 ErasTotalStake::<T>::get(era),
2008 "found bad eras total stake"
2009 );
2010
2011 Ok(())
2012 }
2013
2014 fn check_slash_health() -> Result<(), TryRuntimeError> {
2016 let offence_queue_eras = OffenceQueueEras::<T>::get().unwrap_or_default().into_inner();
2018 let mut sorted_offence_queue_eras = offence_queue_eras.clone();
2019 sorted_offence_queue_eras.sort();
2020 ensure!(
2021 sorted_offence_queue_eras == offence_queue_eras,
2022 "Offence queue eras are not sorted"
2023 );
2024 drop(sorted_offence_queue_eras);
2025
2026 let active_era = Rotator::<T>::active_era();
2028 let oldest_unprocessed_offence_era =
2029 offence_queue_eras.first().cloned().unwrap_or(active_era);
2030
2031 let oldest_unprocessed_offence_age =
2035 active_era.saturating_sub(oldest_unprocessed_offence_era);
2036
2037 if oldest_unprocessed_offence_age > 2.min(T::BondingDuration::get()) {
2039 log!(
2040 warn,
2041 "Offence queue has unprocessed offences from older than 2 eras: oldest offence era in queue {:?} (active era: {:?})",
2042 oldest_unprocessed_offence_era,
2043 active_era
2044 );
2045 }
2046
2047 ensure!(
2049 oldest_unprocessed_offence_age < T::BondingDuration::get() - 1,
2050 "offences from era less than 3 eras old from active era not processed yet"
2051 );
2052
2053 for e in offence_queue_eras {
2055 let count = OffenceQueue::<T>::iter_prefix(e).count();
2056 ensure!(count > 0, "Offence queue is empty for era listed in offence queue eras");
2057 log!(info, "Offence queue for era {:?} has {:?} offences queued", e, count);
2058 }
2059
2060 for era in (active_era.saturating_sub(T::BondingDuration::get()))..(active_era) {
2064 Self::ensure_era_slashes_applied(era)?;
2068 }
2069
2070 for (era, _) in CancelledSlashes::<T>::iter() {
2072 ensure!(era >= active_era, "Found cancelled slashes for era before active era");
2073 }
2074
2075 Ok(())
2076 }
2077
2078 fn ensure_ledger_role_and_min_bond(ctrl: &T::AccountId) -> Result<(), TryRuntimeError> {
2079 let ledger = Self::ledger(StakingAccount::Controller(ctrl.clone()))?;
2080 let stash = ledger.stash;
2081
2082 let is_nominator = Nominators::<T>::contains_key(&stash);
2083 let is_validator = Validators::<T>::contains_key(&stash);
2084
2085 match (is_nominator, is_validator) {
2086 (false, false) => {
2087 if ledger.active < Self::min_chilled_bond() && !ledger.active.is_zero() {
2088 log!(
2090 warn,
2091 "Chilled stash {:?} has less stake ({:?}) than minimum role bond ({:?})",
2092 stash,
2093 ledger.active,
2094 Self::min_chilled_bond()
2095 );
2096 }
2097 },
2099 (true, false) => {
2100 if ledger.active < Self::min_nominator_bond() {
2102 log!(
2103 warn,
2104 "Nominator {:?} has less stake ({:?}) than minimum role bond ({:?})",
2105 stash,
2106 ledger.active,
2107 Self::min_nominator_bond()
2108 );
2109 }
2110 },
2111 (false, true) => {
2112 if ledger.active < Self::min_validator_bond() {
2114 log!(
2115 warn,
2116 "Validator {:?} has less stake ({:?}) than minimum role bond ({:?})",
2117 stash,
2118 ledger.active,
2119 Self::min_validator_bond()
2120 );
2121 }
2122 },
2123 (true, true) => {
2124 ensure!(false, "Stash cannot be both nominator and validator");
2125 },
2126 }
2127 Ok(())
2128 }
2129
2130 fn ensure_ledger_consistent(ctrl: &T::AccountId) -> Result<(), TryRuntimeError> {
2131 let ledger = Self::ledger(StakingAccount::Controller(ctrl.clone()))?;
2133
2134 let real_total: BalanceOf<T> =
2135 ledger.unlocking.iter().fold(ledger.active, |a, c| a + c.value);
2136 ensure!(real_total == ledger.total, "ledger.total corrupt");
2137
2138 Ok(())
2139 }
2140}