referrerpolicy=no-referrer-when-downgrade

sp_staking/
lib.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18#![cfg_attr(not(feature = "std"), no_std)]
19
20//! A crate which contains primitives that are useful for implementation that uses staking
21//! approaches in general. Definitions related to sessions, slashing, etc go here.
22
23extern crate alloc;
24
25use crate::currency_to_vote::CurrencyToVote;
26use alloc::{collections::btree_map::BTreeMap, vec, vec::Vec};
27use codec::{Decode, DecodeWithMemTracking, Encode, FullCodec, HasCompact, MaxEncodedLen};
28use core::ops::{Add, AddAssign, Sub, SubAssign};
29use scale_info::TypeInfo;
30use sp_runtime::{
31	traits::{AtLeast32BitUnsigned, Zero},
32	Debug, DispatchError, DispatchResult, Perbill, Saturating, Weight,
33};
34
35pub mod budget;
36pub mod offence;
37
38pub mod currency_to_vote;
39
40/// Simple index type with which we can count sessions.
41pub type SessionIndex = u32;
42
43/// Counter for the number of eras that have passed.
44pub type EraIndex = u32;
45
46/// Type for identifying a page.
47pub type Page = u32;
48
49/// The service for which validators earn reward points.
50#[derive(
51	Clone,
52	Copy,
53	PartialEq,
54	Eq,
55	Debug,
56	Encode,
57	Decode,
58	DecodeWithMemTracking,
59	TypeInfo,
60	MaxEncodedLen,
61)]
62#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
63pub enum ServiceKind {
64	/// Relay chain consensus: validating and authoring on the relay chain.
65	#[codec(index = 0)]
66	RelayConsensus,
67	/// Authoring blocks on system chains.
68	#[codec(index = 1)]
69	Collation,
70}
71
72/// Credits era points to validators.
73pub trait RewardPoints<AccountId> {
74	/// Credit `points` earned for `service` to the active era.
75	fn reward(service: ServiceKind, points: Vec<(AccountId, u32)>);
76
77	/// Weight of [`Self::reward`] for `entries` entries.
78	fn weight(entries: u32) -> Weight;
79}
80
81/// Trait for reporting additional validator reward points.
82///
83/// Note: This is interface is similar to [`RewardPoints`], but is a legacy version thereof which
84/// doesn't support service-specific points.
85pub trait RewardsReporter<ValidatorId> {
86	fn reward_by_ids(validators_points: impl IntoIterator<Item = (ValidatorId, u32)>);
87}
88
89impl RewardsReporter<sp_runtime::AccountId32> for () {
90	fn reward_by_ids(_validators_points: impl IntoIterator<Item = (sp_runtime::AccountId32, u32)>) {
91	}
92}
93
94/// Representation of a staking account, which may be a stash or controller account.
95///
96/// Note: once the controller is completely deprecated, this enum can also be deprecated in favor of
97/// the stash account. Tracking issue: <https://github.com/paritytech/substrate/issues/6927>.
98#[derive(Clone, Debug)]
99pub enum StakingAccount<AccountId> {
100	Stash(AccountId),
101	Controller(AccountId),
102}
103
104#[cfg(feature = "std")]
105impl<AccountId> From<AccountId> for StakingAccount<AccountId> {
106	fn from(account: AccountId) -> Self {
107		StakingAccount::Stash(account)
108	}
109}
110
111/// Representation of the status of a staker.
112#[derive(Debug, TypeInfo)]
113#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize, PartialEq, Eq, Clone))]
114pub enum StakerStatus<AccountId> {
115	/// Chilling.
116	Idle,
117	/// Declaring desire in validate, i.e author blocks.
118	Validator,
119	/// Declaring desire to nominate, delegate, or generally approve of the given set of others.
120	Nominator(Vec<AccountId>),
121}
122
123/// A struct that reflects stake that an account has in the staking system. Provides a set of
124/// methods to operate on it's properties. Aimed at making `StakingInterface` more concise.
125#[derive(Debug, Clone, Copy, Eq, PartialEq, Default)]
126pub struct Stake<Balance> {
127	/// The total stake that `stash` has in the staking system. This includes the
128	/// `active` stake, and any funds currently in the process of unbonding via
129	/// [`StakingInterface::unbond`].
130	///
131	/// # Note
132	///
133	/// This is only guaranteed to reflect the amount locked by the staking system. If there are
134	/// non-staking locks on the bonded pair's balance this amount is going to be larger in
135	/// reality.
136	pub total: Balance,
137	/// The total amount of the stash's balance that will be at stake in any forthcoming
138	/// rounds.
139	pub active: Balance,
140}
141
142/// A generic staking event listener.
143///
144/// Note that the interface is designed in a way that the events are fired post-action, so any
145/// pre-action data that is needed needs to be passed to interface methods. The rest of the data can
146/// be retrieved by using `StakingInterface`.
147#[impl_trait_for_tuples::impl_for_tuples(10)]
148pub trait OnStakingUpdate<AccountId, Balance> {
149	/// Fired when the stake amount of someone updates.
150	///
151	/// This is effectively any changes to the bond amount, such as bonding more funds, and
152	/// unbonding.
153	fn on_stake_update(_who: &AccountId, _prev_stake: Option<Stake<Balance>>) {}
154
155	/// Fired when someone sets their intention to nominate.
156	///
157	/// This should never be fired for existing nominators.
158	fn on_nominator_add(_who: &AccountId) {}
159
160	/// Fired when an existing nominator updates their nominations.
161	///
162	/// Note that this is not fired when a nominator changes their stake. For that,
163	/// `on_stake_update` should be used, followed by querying whether `who` was a validator or a
164	/// nominator.
165	fn on_nominator_update(_who: &AccountId, _prev_nominations: Vec<AccountId>) {}
166
167	/// Fired when someone removes their intention to nominate, either due to chill or validating.
168	///
169	/// The set of nominations at the time of removal is provided as it can no longer be fetched in
170	/// any way.
171	fn on_nominator_remove(_who: &AccountId, _nominations: Vec<AccountId>) {}
172
173	/// Fired when someone sets their intention to validate.
174	///
175	/// Note validator preference changes are not communicated, but could be added if needed.
176	fn on_validator_add(_who: &AccountId) {}
177
178	/// Fired when an existing validator updates their preferences.
179	///
180	/// Note validator preference changes are not communicated, but could be added if needed.
181	fn on_validator_update(_who: &AccountId) {}
182
183	/// Fired when someone removes their intention to validate, either due to chill or nominating.
184	fn on_validator_remove(_who: &AccountId) {}
185
186	/// Fired when someone is fully unstaked.
187	fn on_unstake(_who: &AccountId) {}
188
189	/// Fired when a staker is slashed.
190	///
191	/// * `stash` - The stash of the staker whom the slash was applied to.
192	/// * `slashed_active` - The new bonded balance of the staker after the slash was applied.
193	/// * `slashed_unlocking` - A map of slashed eras, and the balance of that unlocking chunk after
194	///   the slash is applied. Any era not present in the map is not affected at all.
195	/// * `slashed_total` - The aggregated balance that was lost due to the slash.
196	fn on_slash(
197		_stash: &AccountId,
198		_slashed_active: Balance,
199		_slashed_unlocking: &BTreeMap<EraIndex, Balance>,
200		_slashed_total: Balance,
201	) {
202	}
203
204	/// Fired when a portion of a staker's balance has been withdrawn.
205	fn on_withdraw(_stash: &AccountId, _amount: Balance) {}
206}
207
208/// A generic representation of a staking implementation.
209///
210/// This interface uses the terminology of NPoS, but it is aims to be generic enough to cover other
211/// implementations as well.
212pub trait StakingInterface {
213	/// Balance type used by the staking system.
214	type Balance: Sub<Output = Self::Balance>
215		+ Ord
216		+ PartialEq
217		+ Default
218		+ Copy
219		+ MaxEncodedLen
220		+ FullCodec
221		+ TypeInfo
222		+ Saturating;
223
224	/// AccountId type used by the staking system.
225	type AccountId: Clone + core::fmt::Debug;
226
227	/// Means of converting Currency to VoteWeight.
228	type CurrencyToVote: CurrencyToVote<Self::Balance>;
229
230	/// The minimum amount required to bond in order to set nomination intentions. This does not
231	/// necessarily mean the nomination will be counted in an election, but instead just enough to
232	/// be stored as a nominator. In other words, this is the minimum amount to register the
233	/// intention to nominate.
234	fn minimum_nominator_bond() -> Self::Balance;
235
236	/// The minimum amount required to bond in order to set validation intentions.
237	fn minimum_validator_bond() -> Self::Balance;
238
239	/// Return a stash account that is controlled by a `controller`.
240	///
241	/// ## Note
242	///
243	/// The controller abstraction is not permanent and might go away. Avoid using this as much as
244	/// possible.
245	fn stash_by_ctrl(controller: &Self::AccountId) -> Result<Self::AccountId, DispatchError>;
246
247	/// Number of eras that staked funds must remain bonded for.
248	///
249	/// This is the full bonding duration used by validators and recent ex-validators.
250	fn bonding_duration() -> EraIndex;
251
252	/// Number of eras that staked funds of a pure nominator must remain bonded for.
253	///
254	/// Same as [`Self::bonding_duration`] by default, but can be lower for pure nominators
255	/// (who have not been validators in recent eras) when nominators are not slashable.
256	///
257	/// Note: The actual unbonding duration for a specific account may vary:
258	/// - Validators always use [`Self::bonding_duration`]
259	/// - Nominators who were recently validators use [`Self::bonding_duration`]
260	/// - Pure nominators (never validators, or not validators in recent eras) may use a shorter
261	///   duration when not slashable
262	fn nominator_bonding_duration() -> EraIndex {
263		Self::bonding_duration()
264	}
265
266	/// The current era index.
267	///
268	/// This should be the latest planned era that the staking system knows about.
269	fn current_era() -> EraIndex;
270
271	/// Returns the [`Stake`] of `who`.
272	fn stake(who: &Self::AccountId) -> Result<Stake<Self::Balance>, DispatchError>;
273
274	/// Total stake of a staker, `Err` if not a staker.
275	fn total_stake(who: &Self::AccountId) -> Result<Self::Balance, DispatchError> {
276		Self::stake(who).map(|s| s.total)
277	}
278
279	/// Total active portion of a staker's [`Stake`], `Err` if not a staker.
280	fn active_stake(who: &Self::AccountId) -> Result<Self::Balance, DispatchError> {
281		Self::stake(who).map(|s| s.active)
282	}
283
284	/// Returns whether a staker is unbonding, `Err` if not a staker at all.
285	fn is_unbonding(who: &Self::AccountId) -> Result<bool, DispatchError> {
286		Self::stake(who).map(|s| s.active != s.total)
287	}
288
289	/// Returns whether a staker is FULLY unbonding, `Err` if not a staker at all.
290	fn fully_unbond(who: &Self::AccountId) -> DispatchResult {
291		Self::unbond(who, Self::stake(who)?.active)
292	}
293
294	/// Bond (lock) `value` of `who`'s balance, while forwarding any rewards to `payee`.
295	fn bond(who: &Self::AccountId, value: Self::Balance, payee: &Self::AccountId)
296		-> DispatchResult;
297
298	/// Have `who` nominate `validators`.
299	fn nominate(who: &Self::AccountId, validators: Vec<Self::AccountId>) -> DispatchResult;
300
301	/// Chill `who`.
302	fn chill(who: &Self::AccountId) -> DispatchResult;
303
304	/// Bond some extra amount in `who`'s free balance against the active bonded balance of
305	/// the account. The amount extra actually bonded will never be more than `who`'s free
306	/// balance.
307	fn bond_extra(who: &Self::AccountId, extra: Self::Balance) -> DispatchResult;
308
309	/// Schedule a portion of the active bonded balance to be unlocked at era
310	/// [Self::current_era] + [`Self::bonding_duration`].
311	///
312	/// Once the unlock era has been reached, [`Self::withdraw_unbonded`] can be called to unlock
313	/// the funds.
314	///
315	/// The amount of times this can be successfully called is limited based on how many distinct
316	/// eras funds are schedule to unlock in. Calling [`Self::withdraw_unbonded`] after some unlock
317	/// schedules have reached their unlocking era should allow more calls to this function.
318	fn unbond(stash: &Self::AccountId, value: Self::Balance) -> DispatchResult;
319
320	/// Set the reward destination for the ledger associated with the stash.
321	fn set_payee(stash: &Self::AccountId, reward_acc: &Self::AccountId) -> DispatchResult;
322
323	/// Unlock any funds schedule to unlock before or at the current era.
324	///
325	/// Returns whether the stash was killed because of this withdraw or not.
326	fn withdraw_unbonded(
327		stash: Self::AccountId,
328		num_slashing_spans: u32,
329	) -> Result<bool, DispatchError>;
330
331	/// The ideal number of active validators.
332	fn desired_validator_count() -> u32;
333
334	/// Whether or not there is an ongoing election.
335	fn election_ongoing() -> bool;
336
337	/// Force a current staker to become completely unstaked, immediately.
338	fn force_unstake(who: Self::AccountId) -> DispatchResult;
339
340	/// Checks whether an account `staker` has been exposed in an era.
341	fn is_exposed_in_era(who: &Self::AccountId, era: &EraIndex) -> bool;
342
343	/// Return the status of the given staker, `Err` if not staked at all.
344	fn status(who: &Self::AccountId) -> Result<StakerStatus<Self::AccountId>, DispatchError>;
345
346	/// Checks whether or not this is a validator account.
347	fn is_validator(who: &Self::AccountId) -> bool {
348		Self::status(who).map(|s| matches!(s, StakerStatus::Validator)).unwrap_or(false)
349	}
350
351	/// Checks whether the staker is a virtual account.
352	///
353	/// A virtual staker is an account whose locks are not managed by the [`StakingInterface`]
354	/// implementation but by an external pallet. See [`StakingUnchecked::virtual_bond`] for more
355	/// details.
356	fn is_virtual_staker(who: &Self::AccountId) -> bool;
357
358	/// Get the nominations of a stash, if they are a nominator, `None` otherwise.
359	fn nominations(who: &Self::AccountId) -> Option<Vec<Self::AccountId>> {
360		match Self::status(who) {
361			Ok(StakerStatus::Nominator(t)) => Some(t),
362			_ => None,
363		}
364	}
365
366	/// Returns the fraction of the slash to be rewarded to reporter.
367	fn slash_reward_fraction() -> Perbill;
368
369	#[cfg(feature = "runtime-benchmarks")]
370	fn max_exposure_page_size() -> Page;
371
372	#[cfg(feature = "runtime-benchmarks")]
373	fn add_era_stakers(
374		current_era: &EraIndex,
375		stash: &Self::AccountId,
376		exposures: Vec<(Self::AccountId, Self::Balance)>,
377	);
378
379	/// Benchmark and test helper to set both active and current era.
380	#[cfg(any(feature = "std", feature = "runtime-benchmarks"))]
381	fn set_era(era: EraIndex);
382}
383
384/// Set of low level apis to manipulate staking ledger.
385///
386/// These apis bypass some or all safety checks and should only be used if you know what you are
387/// doing.
388pub trait StakingUnchecked: StakingInterface {
389	/// Migrate an existing staker to a virtual staker.
390	///
391	/// It would release all funds held by the implementation pallet.
392	fn migrate_to_virtual_staker(who: &Self::AccountId) -> DispatchResult;
393
394	/// Book-keep a new bond for `keyless_who` without applying any locks (hence virtual).
395	///
396	/// It is important that `keyless_who` is a keyless account and therefore cannot interact with
397	/// staking pallet directly. Caller is responsible for ensuring the passed amount is locked and
398	/// valid.
399	fn virtual_bond(
400		keyless_who: &Self::AccountId,
401		value: Self::Balance,
402		payee: &Self::AccountId,
403	) -> DispatchResult;
404
405	/// Migrate a virtual staker to a direct staker.
406	///
407	/// Only used for testing.
408	#[cfg(feature = "runtime-benchmarks")]
409	fn migrate_to_direct_staker(who: &Self::AccountId);
410}
411
412/// The amount of exposure for an era that an individual nominator has (susceptible to slashing).
413#[derive(
414	PartialEq,
415	Eq,
416	PartialOrd,
417	Ord,
418	Clone,
419	Encode,
420	Decode,
421	DecodeWithMemTracking,
422	Debug,
423	TypeInfo,
424	Copy,
425)]
426pub struct IndividualExposure<AccountId, Balance: HasCompact> {
427	/// The stash account of the nominator in question.
428	pub who: AccountId,
429	/// Amount of funds exposed.
430	#[codec(compact)]
431	pub value: Balance,
432}
433
434/// A snapshot of the stake backing a single validator in the system.
435#[derive(
436	PartialEq, Eq, PartialOrd, Ord, Clone, Encode, Decode, DecodeWithMemTracking, Debug, TypeInfo,
437)]
438pub struct Exposure<AccountId, Balance: HasCompact> {
439	/// The total balance backing this validator.
440	#[codec(compact)]
441	pub total: Balance,
442	/// The validator's own stash that is exposed.
443	#[codec(compact)]
444	pub own: Balance,
445	/// The portions of nominators stashes that are exposed.
446	pub others: Vec<IndividualExposure<AccountId, Balance>>,
447}
448
449impl<AccountId, Balance: Default + HasCompact> Default for Exposure<AccountId, Balance> {
450	fn default() -> Self {
451		Self { total: Default::default(), own: Default::default(), others: vec![] }
452	}
453}
454
455impl<
456		AccountId: Clone,
457		Balance: HasCompact + AtLeast32BitUnsigned + Copy + codec::MaxEncodedLen,
458	> Exposure<AccountId, Balance>
459{
460	/// Splits self into two instances of exposures.
461	///
462	/// `n_others` individual exposures are consumed from self and returned as part of the new
463	/// exposure.
464	///
465	/// Since this method splits `others` of a single exposure, `total.own` will be the same for
466	/// both `self` and the returned exposure.
467	pub fn split_others(&mut self, n_others: u32) -> Self {
468		let head_others: Vec<_> =
469			self.others.drain(..(n_others as usize).min(self.others.len())).collect();
470
471		let total_others_head: Balance = head_others
472			.iter()
473			.fold(Zero::zero(), |acc: Balance, o| acc.saturating_add(o.value));
474
475		self.total = self.total.saturating_sub(total_others_head);
476
477		Self {
478			total: total_others_head.saturating_add(self.own),
479			own: self.own,
480			others: head_others,
481		}
482	}
483
484	/// Converts an `Exposure` into `PagedExposureMetadata` and multiple chunks of
485	/// `IndividualExposure` with each chunk having maximum of `page_size` elements.
486	pub fn into_pages(
487		self,
488		page_size: Page,
489	) -> (PagedExposureMetadata<Balance>, Vec<ExposurePage<AccountId, Balance>>) {
490		let individual_chunks = self.others.chunks(page_size as usize);
491		let mut exposure_pages: Vec<ExposurePage<AccountId, Balance>> =
492			Vec::with_capacity(individual_chunks.len());
493
494		for chunk in individual_chunks {
495			let mut page_total: Balance = Zero::zero();
496			let mut others: Vec<IndividualExposure<AccountId, Balance>> =
497				Vec::with_capacity(chunk.len());
498			for individual in chunk.iter() {
499				page_total.saturating_accrue(individual.value);
500				others.push(IndividualExposure {
501					who: individual.who.clone(),
502					value: individual.value,
503				})
504			}
505			exposure_pages.push(ExposurePage { page_total, others });
506		}
507
508		(
509			PagedExposureMetadata {
510				total: self.total,
511				own: self.own,
512				nominator_count: self.others.len() as u32,
513				page_count: exposure_pages.len() as Page,
514			},
515			exposure_pages,
516		)
517	}
518}
519
520/// A snapshot of the stake backing a single validator in the system.
521#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Encode, Decode, Debug, TypeInfo)]
522pub struct ExposurePage<AccountId, Balance: HasCompact> {
523	/// The total balance of this chunk/page.
524	#[codec(compact)]
525	pub page_total: Balance,
526	/// The portions of nominators stashes that are exposed.
527	pub others: Vec<IndividualExposure<AccountId, Balance>>,
528}
529
530impl<A, B: Default + HasCompact> Default for ExposurePage<A, B> {
531	fn default() -> Self {
532		ExposurePage { page_total: Default::default(), others: vec![] }
533	}
534}
535
536/// Returns an exposure page from a set of individual exposures.
537impl<A, B: HasCompact + Default + AddAssign + SubAssign + Clone> From<Vec<IndividualExposure<A, B>>>
538	for ExposurePage<A, B>
539{
540	fn from(exposures: Vec<IndividualExposure<A, B>>) -> Self {
541		exposures.into_iter().fold(ExposurePage::default(), |mut page, e| {
542			page.page_total += e.value.clone();
543			page.others.push(e);
544			page
545		})
546	}
547}
548
549/// Metadata for Paged Exposure of a validator such as total stake across pages and page count.
550///
551/// In combination with the associated `ExposurePage`s, it can be used to reconstruct a full
552/// `Exposure` set of a validator. This is useful for cases where we want to query full set of
553/// `Exposure` as one page (for backward compatibility).
554#[derive(
555	PartialEq,
556	Eq,
557	PartialOrd,
558	Ord,
559	Clone,
560	Encode,
561	Decode,
562	Debug,
563	TypeInfo,
564	Default,
565	MaxEncodedLen,
566	Copy,
567)]
568pub struct PagedExposureMetadata<Balance: HasCompact + codec::MaxEncodedLen> {
569	/// The total balance backing this validator.
570	#[codec(compact)]
571	pub total: Balance,
572	/// The validator's own stash that is exposed.
573	#[codec(compact)]
574	pub own: Balance,
575	/// Number of nominators backing this validator.
576	pub nominator_count: u32,
577	/// Number of pages of nominators.
578	pub page_count: Page,
579}
580
581impl<Balance> PagedExposureMetadata<Balance>
582where
583	Balance: HasCompact
584		+ codec::MaxEncodedLen
585		+ Add<Output = Balance>
586		+ Sub<Output = Balance>
587		+ sp_runtime::Saturating
588		+ PartialEq
589		+ Copy
590		+ sp_runtime::traits::Debug,
591{
592	/// Consumes self and returns the result of the metadata updated with `other_balances` and
593	/// of adding `other_num` nominators to the metadata.
594	///
595	/// `Max` is a getter of the maximum number of nominators per page.
596	pub fn update_with<Max: sp_core::Get<u32>>(
597		self,
598		others_balance: Balance,
599		others_num: u32,
600	) -> Self {
601		let page_limit = Max::get().max(1);
602		let new_nominator_count = self.nominator_count.saturating_add(others_num);
603		let new_page_count = new_nominator_count
604			.saturating_add(page_limit)
605			.saturating_sub(1)
606			.saturating_div(page_limit);
607
608		Self {
609			total: self.total.saturating_add(others_balance),
610			own: self.own,
611			nominator_count: new_nominator_count,
612			page_count: new_page_count,
613		}
614	}
615}
616
617/// A type that belongs only in the context of an `Agent`.
618///
619/// `Agent` is someone that manages delegated funds from [`Delegator`] accounts. It can
620/// then use these funds to participate in the staking system. It can never use its own funds to
621/// stake. They instead (virtually bond)[`StakingUnchecked::virtual_bond`] into the staking system
622/// and are also called `Virtual Stakers`.
623///
624/// The `Agent` is also responsible for managing rewards and slashing for all the `Delegators` that
625/// have delegated funds to it.
626#[derive(Clone, Debug)]
627pub struct Agent<T>(T);
628impl<T> From<T> for Agent<T> {
629	fn from(acc: T) -> Self {
630		Agent(acc)
631	}
632}
633
634impl<T> Agent<T> {
635	pub fn get(self) -> T {
636		self.0
637	}
638}
639
640/// A type that belongs only in the context of a `Delegator`.
641///
642/// `Delegator` is someone that delegates funds to an `Agent`, allowing them to pool funds
643/// along with other delegators and participate in the staking system.
644#[derive(Clone, Debug)]
645pub struct Delegator<T>(T);
646impl<T> From<T> for Delegator<T> {
647	fn from(acc: T) -> Self {
648		Delegator(acc)
649	}
650}
651
652impl<T> Delegator<T> {
653	pub fn get(self) -> T {
654		self.0
655	}
656}
657
658/// Trait to provide delegation functionality for stakers.
659pub trait DelegationInterface {
660	/// Balance type used by the staking system.
661	type Balance: Sub<Output = Self::Balance>
662		+ Ord
663		+ PartialEq
664		+ Default
665		+ Copy
666		+ MaxEncodedLen
667		+ FullCodec
668		+ TypeInfo
669		+ Saturating;
670
671	/// AccountId type used by the staking system.
672	type AccountId: Clone + core::fmt::Debug;
673
674	/// Returns effective balance of the `Agent` account. `None` if not an `Agent`.
675	///
676	/// This takes into account any pending slashes to `Agent` against the delegated balance.
677	fn agent_balance(agent: Agent<Self::AccountId>) -> Option<Self::Balance>;
678
679	/// Returns the total amount of funds that is unbonded and can be withdrawn from the `Agent`
680	/// account. `None` if not an `Agent`.
681	fn agent_transferable_balance(agent: Agent<Self::AccountId>) -> Option<Self::Balance>;
682
683	/// Returns the total amount of funds delegated. `None` if not a `Delegator`.
684	fn delegator_balance(delegator: Delegator<Self::AccountId>) -> Option<Self::Balance>;
685
686	/// Register `Agent` such that it can accept delegation.
687	fn register_agent(
688		agent: Agent<Self::AccountId>,
689		reward_account: &Self::AccountId,
690	) -> DispatchResult;
691
692	/// Removes `Agent` registration.
693	///
694	/// This should only be allowed if the agent has no staked funds.
695	fn remove_agent(agent: Agent<Self::AccountId>) -> DispatchResult;
696
697	/// Add delegation to the `Agent`.
698	fn delegate(
699		delegator: Delegator<Self::AccountId>,
700		agent: Agent<Self::AccountId>,
701		amount: Self::Balance,
702	) -> DispatchResult;
703
704	/// Withdraw or revoke delegation to `Agent`.
705	///
706	/// If there are `Agent` funds upto `amount` available to withdraw, then those funds would
707	/// be released to the `delegator`
708	fn withdraw_delegation(
709		delegator: Delegator<Self::AccountId>,
710		agent: Agent<Self::AccountId>,
711		amount: Self::Balance,
712		num_slashing_spans: u32,
713	) -> DispatchResult;
714
715	/// Returns pending slashes posted to the `Agent` account. None if not an `Agent`.
716	///
717	/// Slashes to `Agent` account are not immediate and are applied lazily. Since `Agent`
718	/// has an unbounded number of delegators, immediate slashing is not possible.
719	fn pending_slash(agent: Agent<Self::AccountId>) -> Option<Self::Balance>;
720
721	/// Apply a pending slash to an `Agent` by slashing `value` from `delegator`.
722	///
723	/// A reporter may be provided (if one exists) in order for the implementor to reward them,
724	/// if applicable.
725	fn delegator_slash(
726		agent: Agent<Self::AccountId>,
727		delegator: Delegator<Self::AccountId>,
728		value: Self::Balance,
729		maybe_reporter: Option<Self::AccountId>,
730	) -> DispatchResult;
731}
732
733/// Trait to provide functionality for direct stakers to migrate to delegation agents.
734/// See [`DelegationInterface`] for more details on delegation.
735pub trait DelegationMigrator {
736	/// Balance type used by the staking system.
737	type Balance: Sub<Output = Self::Balance>
738		+ Ord
739		+ PartialEq
740		+ Default
741		+ Copy
742		+ MaxEncodedLen
743		+ FullCodec
744		+ TypeInfo
745		+ Saturating;
746
747	/// AccountId type used by the staking system.
748	type AccountId: Clone + core::fmt::Debug;
749
750	/// Migrate an existing `Nominator` to `Agent` account.
751	///
752	/// The implementation should ensure the `Nominator` account funds are moved to an escrow
753	/// from which `Agents` can later release funds to its `Delegators`.
754	fn migrate_nominator_to_agent(
755		agent: Agent<Self::AccountId>,
756		reward_account: &Self::AccountId,
757	) -> DispatchResult;
758
759	/// Migrate `value` of delegation to `delegator` from a migrating agent.
760	///
761	/// When a direct `Nominator` migrates to `Agent`, the funds are kept in escrow. This function
762	/// allows the `Agent` to release the funds to the `delegator`.
763	fn migrate_delegation(
764		agent: Agent<Self::AccountId>,
765		delegator: Delegator<Self::AccountId>,
766		value: Self::Balance,
767	) -> DispatchResult;
768
769	/// Drop the `Agent` account and its associated delegators.
770	///
771	/// Also removed from [`StakingUnchecked`] as a Virtual Staker. Useful for testing.
772	#[cfg(feature = "runtime-benchmarks")]
773	fn force_kill_agent(agent: Agent<Self::AccountId>);
774}
775
776/// Handler for determining how much of a balance should be paid out on the current era.
777///
778/// [`budget::IssuanceCurve`] is the successor to this trait, decoupling issuance computation
779/// from staking state.
780pub trait EraPayout<Balance> {
781	/// Determine the payout for this era.
782	///
783	/// Returns the amount to be paid to stakers in this era, as well as whatever else should be
784	/// paid out ("the rest").
785	fn era_payout(
786		total_staked: Balance,
787		total_issuance: Balance,
788		era_duration_millis: u64,
789	) -> (Balance, Balance);
790}
791
792impl<Balance: Default> EraPayout<Balance> for () {
793	fn era_payout(
794		_total_staked: Balance,
795		_total_issuance: Balance,
796		_era_duration_millis: u64,
797	) -> (Balance, Balance) {
798		(Default::default(), Default::default())
799	}
800}
801
802/// Result of splitting a validator's staking reward between the validator and their nominators.
803///
804/// Produced by [`StakerRewardCalculator::calculate_staker_reward`].
805#[derive(Debug, Clone, PartialEq, Eq)]
806pub struct StakerRewardResult<Balance> {
807	/// Total payout for the validator (commission + proportional stake reward).
808	pub validator_payout: Balance,
809	/// Total payout for all nominators, to be split proportionally by the caller.
810	pub nominator_payout: Balance,
811}
812
813/// Handles two independent reward calculations:
814///
815/// 1. **Staker reward split** ([`Self::calculate_staker_reward`]) — determines how a validator's
816///    staking reward is divided between the validator and their nominators.
817///
818/// 2. **Validator incentive weight** ([`Self::calculate_validator_incentive_weight`]) — determines
819///    a validator's relative share of a separate validator incentive pot, based on self-stake. This
820///    incentive pot is validator-only; nominators do not receive from it.
821pub trait StakerRewardCalculator<Balance> {
822	/// Compute a weight for this validator's share of the validator incentive pot.
823	///
824	/// Called once per validator during era planning. All validators' weights are summed, and
825	/// each validator's incentive payout is proportional to `their_weight / total_weight`.
826	fn calculate_validator_incentive_weight(self_stake: Balance) -> Balance;
827
828	/// Split a validator's staking reward into validator and nominator portions.
829	fn calculate_staker_reward(
830		validator_total_reward: Balance,
831		validator_commission: Perbill,
832		validator_own_stake: Balance,
833		total_exposure: Balance,
834	) -> StakerRewardResult<Balance>;
835}
836
837impl<Balance: Default> StakerRewardCalculator<Balance> for () {
838	fn calculate_validator_incentive_weight(_self_stake: Balance) -> Balance {
839		Default::default()
840	}
841
842	fn calculate_staker_reward(
843		_validator_total_reward: Balance,
844		_validator_commission: Perbill,
845		_validator_own_stake: Balance,
846		_total_exposure: Balance,
847	) -> StakerRewardResult<Balance> {
848		StakerRewardResult {
849			validator_payout: Default::default(),
850			nominator_payout: Default::default(),
851		}
852	}
853}
854
855sp_core::generate_feature_enabled_macro!(runtime_benchmarks_enabled, feature = "runtime-benchmarks", $);
856sp_core::generate_feature_enabled_macro!(std_or_benchmarks_enabled, any(feature = "std", feature = "runtime-benchmarks"), $);
857
858#[cfg(test)]
859mod tests {
860	use sp_core::ConstU32;
861
862	use super::*;
863
864	#[test]
865	fn update_with_works() {
866		let metadata = PagedExposureMetadata::<u32> {
867			total: 1000,
868			own: 0, // don't care
869			nominator_count: 10,
870			page_count: 1,
871		};
872
873		assert_eq!(
874			metadata.update_with::<ConstU32<10>>(1, 1),
875			PagedExposureMetadata { total: 1001, own: 0, nominator_count: 11, page_count: 2 },
876		);
877
878		assert_eq!(
879			metadata.update_with::<ConstU32<5>>(1, 1),
880			PagedExposureMetadata { total: 1001, own: 0, nominator_count: 11, page_count: 3 },
881		);
882
883		assert_eq!(
884			metadata.update_with::<ConstU32<4>>(1, 1),
885			PagedExposureMetadata { total: 1001, own: 0, nominator_count: 11, page_count: 3 },
886		);
887
888		assert_eq!(
889			metadata.update_with::<ConstU32<1>>(1, 1),
890			PagedExposureMetadata { total: 1001, own: 0, nominator_count: 11, page_count: 11 },
891		);
892	}
893
894	#[test]
895	fn individual_exposures_to_exposure_works() {
896		let exposure_1 = IndividualExposure { who: 1, value: 10u32 };
897		let exposure_2 = IndividualExposure { who: 2, value: 20 };
898		let exposure_3 = IndividualExposure { who: 3, value: 30 };
899
900		let exposure_page: ExposurePage<u32, u32> = vec![exposure_1, exposure_2, exposure_3].into();
901
902		assert_eq!(
903			exposure_page,
904			ExposurePage { page_total: 60, others: vec![exposure_1, exposure_2, exposure_3] },
905		);
906	}
907
908	#[test]
909	fn empty_individual_exposures_to_exposure_works() {
910		let empty_exposures: Vec<IndividualExposure<u32, u32>> = vec![];
911
912		let exposure_page: ExposurePage<u32, u32> = empty_exposures.into();
913		assert_eq!(exposure_page, ExposurePage { page_total: 0, others: vec![] });
914	}
915
916	#[test]
917	fn exposure_split_others_works() {
918		let exposure = Exposure {
919			total: 100,
920			own: 20,
921			others: vec![
922				IndividualExposure { who: 1, value: 20u32 },
923				IndividualExposure { who: 2, value: 20 },
924				IndividualExposure { who: 3, value: 20 },
925				IndividualExposure { who: 4, value: 20 },
926			],
927		};
928
929		let mut exposure_0 = exposure.clone();
930		// split others with with 0 `n_others` is a noop and returns an empty exposure (with `own`
931		// only).
932		let split_exposure = exposure_0.split_others(0);
933		assert_eq!(exposure_0, exposure);
934		assert_eq!(split_exposure, Exposure { total: 20, own: 20, others: vec![] });
935
936		let mut exposure_1 = exposure.clone();
937		// split individual exposures so that the returned exposure has 1 individual exposure.
938		let split_exposure = exposure_1.split_others(1);
939		assert_eq!(exposure_1.own, 20);
940		assert_eq!(exposure_1.total, 20 + 3 * 20);
941		assert_eq!(exposure_1.others.len(), 3);
942
943		assert_eq!(split_exposure.own, 20);
944		assert_eq!(split_exposure.total, 20 + 1 * 20);
945		assert_eq!(split_exposure.others.len(), 1);
946
947		let mut exposure_3 = exposure.clone();
948		// split individual exposures so that the returned exposure has 3 individual exposures,
949		// which are consumed from the original exposure.
950		let split_exposure = exposure_3.split_others(3);
951		assert_eq!(exposure_3.own, 20);
952		assert_eq!(exposure_3.total, 20 + 1 * 20);
953		assert_eq!(exposure_3.others.len(), 1);
954
955		assert_eq!(split_exposure.own, 20);
956		assert_eq!(split_exposure.total, 20 + 3 * 20);
957		assert_eq!(split_exposure.others.len(), 3);
958
959		let mut exposure_max = exposure.clone();
960		// split others with with more `n_others` than the number of others in the exposure
961		// consumes all the individual exposures of the original Exposure and returns them in the
962		// new exposure.
963		let split_exposure = exposure_max.split_others(u32::MAX);
964		assert_eq!(split_exposure, exposure);
965		assert_eq!(exposure_max, Exposure { total: 20, own: 20, others: vec![] });
966	}
967}