Skip to main content

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