pallet_nomination_pools/
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//! # Nomination Pools for Staking Delegation
19//!
20//! A pallet that allows members to delegate their stake to nominating pools. A nomination pool acts
21//! as nominator and nominates validators on the members' behalf.
22//!
23//! # Index
24//!
25//! * [Key terms](#key-terms)
26//! * [Usage](#usage)
27//! * [Implementor's Guide](#implementors-guide)
28//! * [Design](#design)
29//!
30//! ## Key Terms
31//!
32//!  * pool id: A unique identifier of each pool. Set to u32.
33//!  * bonded pool: Tracks the distribution of actively staked funds. See [`BondedPool`] and
34//! [`BondedPoolInner`].
35//! * reward pool: Tracks rewards earned by actively staked funds. See [`RewardPool`] and
36//!   [`RewardPools`].
37//! * unbonding sub pools: Collection of pools at different phases of the unbonding lifecycle. See
38//!   [`SubPools`] and [`SubPoolsStorage`].
39//! * members: Accounts that are members of pools. See [`PoolMember`] and [`PoolMembers`].
40//! * roles: Administrative roles of each pool, capable of controlling nomination, and the state of
41//!   the pool.
42//! * point: A unit of measure for a members portion of a pool's funds. Points initially have a
43//!   ratio of 1 (as set by `POINTS_TO_BALANCE_INIT_RATIO`) to balance, but as slashing happens,
44//!   this can change.
45//! * kick: The act of a pool administrator forcibly ejecting a member.
46//! * bonded account: A key-less account id derived from the pool id that acts as the bonded
47//!   account. This account registers itself as a nominator in the staking system, and follows
48//!   exactly the same rules and conditions as a normal staker. Its bond increases or decreases as
49//!   members join, it can `nominate` or `chill`, and might not even earn staking rewards if it is
50//!   not nominating proper validators.
51//! * reward account: A similar key-less account, that is set as the `Payee` account for the bonded
52//!   account for all staking rewards.
53//! * change rate: The rate at which pool commission can be changed. A change rate consists of a
54//!   `max_increase` and `min_delay`, dictating the maximum percentage increase that can be applied
55//!   to the commission per number of blocks.
56//! * throttle: An attempted commission increase is throttled if the attempted change falls outside
57//!   the change rate bounds.
58//!
59//! ## Usage
60//!
61//! ### Join
62//!
63//! An account can stake funds with a nomination pool by calling [`Call::join`].
64//!
65//! ### Claim rewards
66//!
67//! After joining a pool, a member can claim rewards by calling [`Call::claim_payout`].
68//!
69//! A pool member can also set a `ClaimPermission` with [`Call::set_claim_permission`], to allow
70//! other members to permissionlessly bond or withdraw their rewards by calling
71//! [`Call::bond_extra_other`] or [`Call::claim_payout_other`] respectively.
72//!
73//! For design docs see the [reward pool](#reward-pool) section.
74//!
75//! ### Leave
76//!
77//! In order to leave, a member must take two steps.
78//!
79//! First, they must call [`Call::unbond`]. The unbond extrinsic will start the unbonding process by
80//! unbonding all or a portion of the members funds.
81//!
82//! > A member can have up to [`Config::MaxUnbonding`] distinct active unbonding requests.
83//!
84//! Second, once [`sp_staking::StakingInterface::bonding_duration`] eras have passed, the member can
85//! call [`Call::withdraw_unbonded`] to withdraw any funds that are free.
86//!
87//! For design docs see the [bonded pool](#bonded-pool) and [unbonding sub
88//! pools](#unbonding-sub-pools) sections.
89//!
90//! ### Slashes
91//!
92//! Slashes are distributed evenly across the bonded pool and the unbonding pools from slash era+1
93//! through the slash apply era. Thus, any member who either
94//!
95//! 1. unbonded, or
96//! 2. was actively bonded
97//
98//! in the aforementioned range of eras will be affected by the slash. A member is slashed pro-rata
99//! based on its stake relative to the total slash amount.
100//!
101//! Slashing does not change any single member's balance. Instead, the slash will only reduce the
102//! balance associated with a particular pool. But, we never change the total *points* of a pool
103//! because of slashing. Therefore, when a slash happens, the ratio of points to balance changes in
104//! a pool. In other words, the value of one point, which is initially 1-to-1 against a unit of
105//! balance, is now less than one balance because of the slash.
106//!
107//! ### Administration
108//!
109//! A pool can be created with the [`Call::create`] call. Once created, the pools nominator or root
110//! user must call [`Call::nominate`] to start nominating. [`Call::nominate`] can be called at
111//! anytime to update validator selection.
112//!
113//! Similar to [`Call::nominate`], [`Call::chill`] will chill to pool in the staking system, and
114//! [`Call::pool_withdraw_unbonded`] will withdraw any unbonding chunks of the pool bonded account.
115//! The latter call is permissionless and can be called by anyone at any time.
116//!
117//! To help facilitate pool administration the pool has one of three states (see [`PoolState`]):
118//!
119//! * Open: Anyone can join the pool and no members can be permissionlessly removed.
120//! * Blocked: No members can join and some admin roles can kick members. Kicking is not instant,
121//!   and follows the same process of `unbond` and then `withdraw_unbonded`. In other words,
122//!   administrators can permissionlessly unbond other members.
123//! * Destroying: No members can join and all members can be permissionlessly removed with
124//!   [`Call::unbond`] and [`Call::withdraw_unbonded`]. Once a pool is in destroying state, it
125//!   cannot be reverted to another state.
126//!
127//! A pool has 4 administrative roles (see [`PoolRoles`]):
128//!
129//! * Depositor: creates the pool and is the initial member. They can only leave the pool once all
130//!   other members have left. Once they fully withdraw their funds, the pool is destroyed.
131//! * Nominator: can select which validators the pool nominates.
132//! * Bouncer: can change the pools state and kick members if the pool is blocked.
133//! * Root: can change the nominator, bouncer, or itself, manage and claim commission, and can
134//!   perform any of the actions the nominator or bouncer can.
135//!
136//! ### Commission
137//!
138//! A pool can optionally have a commission configuration, via the `root` role, set with
139//! [`Call::set_commission`] and claimed with [`Call::claim_commission`]. A payee account must be
140//! supplied with the desired commission percentage. Beyond the commission itself, a pool can have a
141//! maximum commission and a change rate.
142//!
143//! Importantly, both max commission  [`Call::set_commission_max`] and change rate
144//! [`Call::set_commission_change_rate`] can not be removed once set, and can only be set to more
145//! restrictive values (i.e. a lower max commission or a slower change rate) in subsequent updates.
146//!
147//! If set, a pool's commission is bound to [`GlobalMaxCommission`] at the time it is applied to
148//! pending rewards. [`GlobalMaxCommission`] is intended to be updated only via governance.
149//!
150//! When a pool is dissolved, any outstanding pending commission that has not been claimed will be
151//! transferred to the depositor.
152//!
153//! Implementation note: Commission is analogous to a separate member account of the pool, with its
154//! own reward counter in the form of `current_pending_commission`.
155//!
156//! Crucially, commission is applied to rewards based on the current commission in effect at the
157//! time rewards are transferred into the reward pool. This is to prevent the malicious behaviour of
158//! changing the commission rate to a very high value after rewards are accumulated, and thus claim
159//! an unexpectedly high chunk of the reward.
160//!
161//! ### Dismantling
162//!
163//! As noted, a pool is destroyed once
164//!
165//! 1. First, all members need to fully unbond and withdraw. If the pool state is set to
166//!    `Destroying`, this can happen permissionlessly.
167//! 2. The depositor itself fully unbonds and withdraws.
168//!
169//! > Note that at this point, based on the requirements of the staking system, the pool's bonded
170//! > account's stake might not be able to ge below a certain threshold as a nominator. At this
171//! > point, the pool should `chill` itself to allow the depositor to leave. See [`Call::chill`].
172//!
173//! ## Implementor's Guide
174//!
175//! Some notes and common mistakes that wallets/apps wishing to implement this pallet should be
176//! aware of:
177//!
178//!
179//! ### Pool Members
180//!
181//! * In general, whenever a pool member changes their total points, the chain will automatically
182//!   claim all their pending rewards for them. This is not optional, and MUST happen for the reward
183//!   calculation to remain correct (see the documentation of `bond` as an example). So, make sure
184//!   you are warning your users about it. They might be surprised if they see that they bonded an
185//!   extra 100 DOTs, and now suddenly their 5.23 DOTs in pending reward is gone. It is not gone, it
186//!   has been paid out to you!
187//! * Joining a pool implies transferring funds to the pool account. So it might be (based on which
188//!   wallet that you are using) that you no longer see the funds that are moved to the pool in your
189//!   “free balance” section. Make sure the user is aware of this, and not surprised by seeing this.
190//!   Also, the transfer that happens here is configured to to never accidentally destroy the sender
191//!   account. So to join a Pool, your sender account must remain alive with 1 DOT left in it. This
192//!   means, with 1 DOT as existential deposit, and 1 DOT as minimum to join a pool, you need at
193//!   least 2 DOT to join a pool. Consequently, if you are suggesting members to join a pool with
194//!   “Maximum possible value”, you must subtract 1 DOT to remain in the sender account to not
195//!   accidentally kill it.
196//! * Points and balance are not the same! Any pool member, at any point in time, can have points in
197//!   either the bonded pool or any of the unbonding pools. The crucial fact is that in any of these
198//!   pools, the ratio of point to balance is different and might not be 1. Each pool starts with a
199//!   ratio of 1, but as time goes on, for reasons such as slashing, the ratio gets broken. Over
200//!   time, 100 points in a bonded pool can be worth 90 DOTs. Make sure you are either representing
201//!   points as points (not as DOTs), or even better, always display both: “You have x points in
202//!   pool y which is worth z DOTs”. See here and here for examples of how to calculate point to
203//!   balance ratio of each pool (it is almost trivial ;))
204//!
205//! ### Pool Management
206//!
207//! * The pool will be seen from the perspective of the rest of the system as a single nominator.
208//!   Ergo, This nominator must always respect the `staking.minNominatorBond` limit. Similar to a
209//!   normal nominator, who has to first `chill` before fully unbonding, the pool must also do the
210//!   same. The pool’s bonded account will be fully unbonded only when the depositor wants to leave
211//!   and dismantle the pool. All that said, the message is: the depositor can only leave the chain
212//!   when they chill the pool first.
213//!
214//! ## Design
215//!
216//! _Notes_: this section uses pseudo code to explain general design and does not necessarily
217//! reflect the exact implementation. Additionally, a working knowledge of `pallet-staking`'s api is
218//! assumed.
219//!
220//! ### Goals
221//!
222//! * Maintain network security by upholding integrity of slashing events, sufficiently penalizing
223//!   members that where in the pool while it was backing a validator that got slashed.
224//! * Maximize scalability in terms of member count.
225//!
226//! In order to maintain scalability, all operations are independent of the number of members. To do
227//! this, delegation specific information is stored local to the member while the pool data
228//! structures have bounded datum.
229//!
230//! ### Bonded pool
231//!
232//! A bonded pool nominates with its total balance, excluding that which has been withdrawn for
233//! unbonding. The total points of a bonded pool are always equal to the sum of points of the
234//! delegation members. A bonded pool tracks its points and reads its bonded balance.
235//!
236//! When a member joins a pool, `amount_transferred` is transferred from the members account to the
237//! bonded pools account. Then the pool calls `staking::bond_extra(amount_transferred)` and issues
238//! new points which are tracked by the member and added to the bonded pool's points.
239//!
240//! When the pool already has some balance, we want the value of a point before the transfer to
241//! equal the value of a point after the transfer. So, when a member joins a bonded pool with a
242//! given `amount_transferred`, we maintain the ratio of bonded balance to points such that:
243//!
244//! ```text
245//! balance_after_transfer / points_after_transfer == balance_before_transfer / points_before_transfer;
246//! ```
247//!
248//! To achieve this, we issue points based on the following:
249//!
250//! ```text
251//! points_issued = (points_before_transfer / balance_before_transfer) * amount_transferred;
252//! ```
253//!
254//! For new bonded pools we can set the points issued per balance arbitrarily. In this
255//! implementation we use a 1 points to 1 balance ratio for pool creation (see
256//! [`POINTS_TO_BALANCE_INIT_RATIO`]).
257//!
258//! **Relevant extrinsics:**
259//!
260//! * [`Call::create`]
261//! * [`Call::join`]
262//!
263//! ### Reward pool
264//!
265//! When a pool is first bonded it sets up a deterministic, inaccessible account as its reward
266//! destination. This reward account combined with `RewardPool` compose a reward pool.
267//!
268//! Reward pools are completely separate entities to bonded pools. Along with its account, a reward
269//! pool also tracks its outstanding and claimed rewards as counters, in addition to pending and
270//! claimed commission. These counters are updated with `RewardPool::update_records`. The current
271//! reward counter of the pool (the total outstanding rewards, in points) is also callable with the
272//! `RewardPool::current_reward_counter` method.
273//!
274//! See [this link](https://hackmd.io/PFGn6wI5TbCmBYoEA_f2Uw) for an in-depth explanation of the
275//! reward pool mechanism.
276//!
277//! **Relevant extrinsics:**
278//!
279//! * [`Call::claim_payout`]
280//!
281//! ### Unbonding sub pools
282//!
283//! When a member unbonds, it's balance is unbonded in the bonded pool's account and tracked in an
284//! unbonding pool associated with the active era. If no such pool exists, one is created. To track
285//! which unbonding sub pool a member belongs too, a member tracks it's `unbonding_era`.
286//!
287//! When a member initiates unbonding it's claim on the bonded pool (`balance_to_unbond`) is
288//! computed as:
289//!
290//! ```text
291//! balance_to_unbond = (bonded_pool.balance / bonded_pool.points) * member.points;
292//! ```
293//!
294//! If this is the first transfer into an unbonding pool arbitrary amount of points can be issued
295//! per balance. In this implementation unbonding pools are initialized with a 1 point to 1 balance
296//! ratio (see [`POINTS_TO_BALANCE_INIT_RATIO`]). Otherwise, the unbonding pools hold the same
297//! points to balance ratio properties as the bonded pool, so member points in the unbonding pool
298//! are issued based on
299//!
300//! ```text
301//! new_points_issued = (points_before_transfer / balance_before_transfer) * balance_to_unbond;
302//! ```
303//!
304//! For scalability, a bound is maintained on the number of unbonding sub pools (see
305//! [`TotalUnbondingPools`]). An unbonding pool is removed once its older than `current_era -
306//! TotalUnbondingPools`. An unbonding pool is merged into the unbonded pool with
307//!
308//! ```text
309//! unbounded_pool.balance = unbounded_pool.balance + unbonding_pool.balance;
310//! unbounded_pool.points = unbounded_pool.points + unbonding_pool.points;
311//! ```
312//!
313//! This scheme "averages" out the points value in the unbonded pool.
314//!
315//! Once a members `unbonding_era` is older than `current_era -
316//! [sp_staking::StakingInterface::bonding_duration]`, it can can cash it's points out of the
317//! corresponding unbonding pool. If it's `unbonding_era` is older than `current_era -
318//! TotalUnbondingPools`, it can cash it's points from the unbonded pool.
319//!
320//! **Relevant extrinsics:**
321//!
322//! * [`Call::unbond`]
323//! * [`Call::withdraw_unbonded`]
324//!
325//! ### Slashing
326//!
327//! This section assumes that the slash computation is executed by
328//! `pallet_staking::StakingLedger::slash`, which passes the information to this pallet via
329//! [`sp_staking::OnStakingUpdate::on_slash`].
330//!
331//! Unbonding pools need to be slashed to ensure all nominators whom where in the bonded pool while
332//! it was backing a validator that equivocated are punished. Without these measures a member could
333//! unbond right after a validator equivocated with no consequences.
334//!
335//! This strategy is unfair to members who joined after the slash, because they get slashed as well,
336//! but spares members who unbond. The latter is much more important for security: if a pool's
337//! validators are attacking the network, their members need to unbond fast! Avoiding slashes gives
338//! them an incentive to do that if validators get repeatedly slashed.
339//!
340//! To be fair to joiners, this implementation also need joining pools, which are actively staking,
341//! in addition to the unbonding pools. For maintenance simplicity these are not implemented.
342//! Related: <https://github.com/paritytech/substrate/issues/10860>
343//!
344//! ### Limitations
345//!
346//! * PoolMembers cannot vote with their staked funds because they are transferred into the pools
347//!   account. In the future this can be overcome by allowing the members to vote with their bonded
348//!   funds via vote splitting.
349//! * PoolMembers cannot quickly transfer to another pool if they do no like nominations, instead
350//!   they must wait for the unbonding duration.
351
352#![cfg_attr(not(feature = "std"), no_std)]
353
354extern crate alloc;
355
356use adapter::{Member, Pool, StakeStrategy};
357use alloc::{collections::btree_map::BTreeMap, vec::Vec};
358use codec::{Codec, DecodeWithMemTracking};
359use core::{fmt::Debug, ops::Div};
360use frame_support::{
361	defensive, defensive_assert, ensure,
362	pallet_prelude::{MaxEncodedLen, *},
363	storage::bounded_btree_map::BoundedBTreeMap,
364	traits::{
365		fungible::{Inspect, InspectFreeze, Mutate, MutateFreeze},
366		tokens::{Fortitude, Preservation},
367		Contains, Defensive, DefensiveOption, DefensiveResult, DefensiveSaturating, Get,
368	},
369	DefaultNoBound, PalletError,
370};
371use scale_info::TypeInfo;
372use sp_core::U256;
373use sp_runtime::{
374	traits::{
375		AccountIdConversion, Bounded, CheckedAdd, CheckedSub, Convert, Saturating, StaticLookup,
376		Zero,
377	},
378	FixedPointNumber, Perbill,
379};
380use sp_staking::{EraIndex, StakingInterface};
381
382#[cfg(any(feature = "try-runtime", feature = "fuzzing", test, debug_assertions))]
383use sp_runtime::TryRuntimeError;
384
385/// The log target of this pallet.
386pub const LOG_TARGET: &str = "runtime::nomination-pools";
387// syntactic sugar for logging.
388#[macro_export]
389macro_rules! log {
390	($level:tt, $patter:expr $(, $values:expr)* $(,)?) => {
391		log::$level!(
392			target: $crate::LOG_TARGET,
393			concat!("[{:?}] 🏊‍♂️ ", $patter), <frame_system::Pallet<T>>::block_number() $(, $values)*
394		)
395	};
396}
397
398#[cfg(any(test, feature = "fuzzing"))]
399pub mod mock;
400#[cfg(test)]
401mod tests;
402
403pub mod adapter;
404pub mod migration;
405pub mod weights;
406
407pub use pallet::*;
408use sp_runtime::traits::BlockNumberProvider;
409pub use weights::WeightInfo;
410
411/// The balance type used by the currency system.
412pub type BalanceOf<T> =
413	<<T as Config>::Currency as Inspect<<T as frame_system::Config>::AccountId>>::Balance;
414/// Type used for unique identifier of each pool.
415pub type PoolId = u32;
416
417type AccountIdLookupOf<T> = <<T as frame_system::Config>::Lookup as StaticLookup>::Source;
418
419pub type BlockNumberFor<T> =
420	<<T as Config>::BlockNumberProvider as BlockNumberProvider>::BlockNumber;
421
422pub const POINTS_TO_BALANCE_INIT_RATIO: u32 = 1;
423
424/// Possible operations on the configuration values of this pallet.
425#[derive(
426	Encode,
427	Decode,
428	DecodeWithMemTracking,
429	MaxEncodedLen,
430	TypeInfo,
431	RuntimeDebugNoBound,
432	PartialEq,
433	Clone,
434)]
435pub enum ConfigOp<T: Codec + Debug> {
436	/// Don't change.
437	Noop,
438	/// Set the given value.
439	Set(T),
440	/// Remove from storage.
441	Remove,
442}
443
444/// The type of bonding that can happen to a pool.
445pub enum BondType {
446	/// Someone is bonding into the pool upon creation.
447	Create,
448	/// Someone is adding more funds later to this pool.
449	Extra,
450}
451
452/// How to increase the bond of a member.
453#[derive(Encode, Decode, DecodeWithMemTracking, Clone, Copy, Debug, PartialEq, Eq, TypeInfo)]
454pub enum BondExtra<Balance> {
455	/// Take from the free balance.
456	FreeBalance(Balance),
457	/// Take the entire amount from the accumulated rewards.
458	Rewards,
459}
460
461/// The type of account being created.
462#[derive(Encode, Decode)]
463enum AccountType {
464	Bonded,
465	Reward,
466}
467
468/// The permission a pool member can set for other accounts to claim rewards on their behalf.
469#[derive(
470	Encode,
471	Decode,
472	DecodeWithMemTracking,
473	MaxEncodedLen,
474	Clone,
475	Copy,
476	Debug,
477	PartialEq,
478	Eq,
479	TypeInfo,
480)]
481pub enum ClaimPermission {
482	/// Only the pool member themselves can claim their rewards.
483	Permissioned,
484	/// Anyone can compound rewards on a pool member's behalf.
485	PermissionlessCompound,
486	/// Anyone can withdraw rewards on a pool member's behalf.
487	PermissionlessWithdraw,
488	/// Anyone can withdraw and compound rewards on a pool member's behalf.
489	PermissionlessAll,
490}
491
492impl Default for ClaimPermission {
493	fn default() -> Self {
494		Self::PermissionlessWithdraw
495	}
496}
497
498impl ClaimPermission {
499	/// Permissionless compounding of pool rewards is allowed if the current permission is
500	/// `PermissionlessCompound`, or permissionless.
501	fn can_bond_extra(&self) -> bool {
502		matches!(self, ClaimPermission::PermissionlessAll | ClaimPermission::PermissionlessCompound)
503	}
504
505	/// Permissionless payout claiming is allowed if the current permission is
506	/// `PermissionlessWithdraw`, or permissionless.
507	fn can_claim_payout(&self) -> bool {
508		matches!(self, ClaimPermission::PermissionlessAll | ClaimPermission::PermissionlessWithdraw)
509	}
510}
511
512/// A member in a pool.
513#[derive(
514	Encode,
515	Decode,
516	MaxEncodedLen,
517	TypeInfo,
518	RuntimeDebugNoBound,
519	CloneNoBound,
520	PartialEqNoBound,
521	EqNoBound,
522)]
523#[cfg_attr(feature = "std", derive(DefaultNoBound))]
524#[scale_info(skip_type_params(T))]
525pub struct PoolMember<T: Config> {
526	/// The identifier of the pool to which `who` belongs.
527	pub pool_id: PoolId,
528	/// The quantity of points this member has in the bonded pool or in a sub pool if
529	/// `Self::unbonding_era` is some.
530	pub points: BalanceOf<T>,
531	/// The reward counter at the time of this member's last payout claim.
532	pub last_recorded_reward_counter: T::RewardCounter,
533	/// The eras in which this member is unbonding, mapped from era index to the number of
534	/// points scheduled to unbond in the given era.
535	pub unbonding_eras: BoundedBTreeMap<EraIndex, BalanceOf<T>, T::MaxUnbonding>,
536}
537
538impl<T: Config> PoolMember<T> {
539	/// The pending rewards of this member.
540	fn pending_rewards(
541		&self,
542		current_reward_counter: T::RewardCounter,
543	) -> Result<BalanceOf<T>, Error<T>> {
544		// accuracy note: Reward counters are `FixedU128` with base of 10^18. This value is being
545		// multiplied by a point. The worse case of a point is 10x the granularity of the balance
546		// (10x is the common configuration of `MaxPointsToBalance`).
547		//
548		// Assuming roughly the current issuance of polkadot (12,047,781,394,999,601,455, which is
549		// 1.2 * 10^9 * 10^10 = 1.2 * 10^19), the worse case point value is around 10^20.
550		//
551		// The final multiplication is:
552		//
553		// rc * 10^20 / 10^18 = rc * 100
554		//
555		// the implementation of `multiply_by_rational_with_rounding` shows that it will only fail
556		// if the final division is not enough to fit in u128. In other words, if `rc * 100` is more
557		// than u128::max. Given that RC is interpreted as reward per unit of point, and unit of
558		// point is equal to balance (normally), and rewards are usually a proportion of the points
559		// in the pool, the likelihood of rc reaching near u128::MAX is near impossible.
560
561		(current_reward_counter.defensive_saturating_sub(self.last_recorded_reward_counter))
562			.checked_mul_int(self.active_points())
563			.ok_or(Error::<T>::OverflowRisk)
564	}
565
566	/// Active balance of the member.
567	///
568	/// This is derived from the ratio of points in the pool to which the member belongs to.
569	/// Might return different values based on the pool state for the same member and points.
570	fn active_balance(&self) -> BalanceOf<T> {
571		if let Some(pool) = BondedPool::<T>::get(self.pool_id).defensive() {
572			pool.points_to_balance(self.points)
573		} else {
574			Zero::zero()
575		}
576	}
577
578	/// Total balance of the member, both active and unbonding.
579	/// Doesn't mutate state.
580	///
581	/// Worst case, iterates over [`TotalUnbondingPools`] member unbonding pools to calculate member
582	/// balance.
583	pub fn total_balance(&self) -> BalanceOf<T> {
584		let pool = match BondedPool::<T>::get(self.pool_id) {
585			Some(pool) => pool,
586			None => {
587				// this internal function is always called with a valid pool id.
588				defensive!("pool should exist; qed");
589				return Zero::zero();
590			},
591		};
592
593		let active_balance = pool.points_to_balance(self.active_points());
594
595		let sub_pools = match SubPoolsStorage::<T>::get(self.pool_id) {
596			Some(sub_pools) => sub_pools,
597			None => return active_balance,
598		};
599
600		let unbonding_balance = self.unbonding_eras.iter().fold(
601			BalanceOf::<T>::zero(),
602			|accumulator, (era, unlocked_points)| {
603				// if the `SubPools::with_era` has already been merged into the
604				// `SubPools::no_era` use this pool instead.
605				let era_pool = sub_pools.with_era.get(era).unwrap_or(&sub_pools.no_era);
606				accumulator + (era_pool.point_to_balance(*unlocked_points))
607			},
608		);
609
610		active_balance + unbonding_balance
611	}
612
613	/// Total points of this member, both active and unbonding.
614	fn total_points(&self) -> BalanceOf<T> {
615		self.active_points().saturating_add(self.unbonding_points())
616	}
617
618	/// Active points of the member.
619	fn active_points(&self) -> BalanceOf<T> {
620		self.points
621	}
622
623	/// Inactive points of the member, waiting to be withdrawn.
624	fn unbonding_points(&self) -> BalanceOf<T> {
625		self.unbonding_eras
626			.as_ref()
627			.iter()
628			.fold(BalanceOf::<T>::zero(), |acc, (_, v)| acc.saturating_add(*v))
629	}
630
631	/// Try and unbond `points_dissolved` from self, and in return mint `points_issued` into the
632	/// corresponding `era`'s unlock schedule.
633	///
634	/// In the absence of slashing, these two points are always the same. In the presence of
635	/// slashing, the value of points in different pools varies.
636	///
637	/// Returns `Ok(())` and updates `unbonding_eras` and `points` if success, `Err(_)` otherwise.
638	fn try_unbond(
639		&mut self,
640		points_dissolved: BalanceOf<T>,
641		points_issued: BalanceOf<T>,
642		unbonding_era: EraIndex,
643	) -> Result<(), Error<T>> {
644		if let Some(new_points) = self.points.checked_sub(&points_dissolved) {
645			match self.unbonding_eras.get_mut(&unbonding_era) {
646				Some(already_unbonding_points) =>
647					*already_unbonding_points =
648						already_unbonding_points.saturating_add(points_issued),
649				None => self
650					.unbonding_eras
651					.try_insert(unbonding_era, points_issued)
652					.map(|old| {
653						if old.is_some() {
654							defensive!("value checked to not exist in the map; qed");
655						}
656					})
657					.map_err(|_| Error::<T>::MaxUnbondingLimit)?,
658			}
659			self.points = new_points;
660			Ok(())
661		} else {
662			Err(Error::<T>::MinimumBondNotMet)
663		}
664	}
665
666	/// Withdraw any funds in [`Self::unbonding_eras`] who's deadline in reached and is fully
667	/// unlocked.
668	///
669	/// Returns a a subset of [`Self::unbonding_eras`] that got withdrawn.
670	///
671	/// Infallible, noop if no unbonding eras exist.
672	fn withdraw_unlocked(
673		&mut self,
674		current_era: EraIndex,
675	) -> BoundedBTreeMap<EraIndex, BalanceOf<T>, T::MaxUnbonding> {
676		// NOTE: if only drain-filter was stable..
677		let mut removed_points =
678			BoundedBTreeMap::<EraIndex, BalanceOf<T>, T::MaxUnbonding>::default();
679		self.unbonding_eras.retain(|e, p| {
680			if *e > current_era {
681				true
682			} else {
683				removed_points
684					.try_insert(*e, *p)
685					.expect("source map is bounded, this is a subset, will be bounded; qed");
686				false
687			}
688		});
689		removed_points
690	}
691}
692
693/// A pool's possible states.
694#[derive(
695	Encode,
696	Decode,
697	DecodeWithMemTracking,
698	MaxEncodedLen,
699	TypeInfo,
700	PartialEq,
701	RuntimeDebugNoBound,
702	Clone,
703	Copy,
704)]
705pub enum PoolState {
706	/// The pool is open to be joined, and is working normally.
707	Open,
708	/// The pool is blocked. No one else can join.
709	Blocked,
710	/// The pool is in the process of being destroyed.
711	///
712	/// All members can now be permissionlessly unbonded, and the pool can never go back to any
713	/// other state other than being dissolved.
714	Destroying,
715}
716
717/// Pool administration roles.
718///
719/// Any pool has a depositor, which can never change. But, all the other roles are optional, and
720/// cannot exist. Note that if `root` is set to `None`, it basically means that the roles of this
721/// pool can never change again (except via governance).
722#[derive(Encode, Decode, MaxEncodedLen, TypeInfo, Debug, PartialEq, Clone)]
723pub struct PoolRoles<AccountId> {
724	/// Creates the pool and is the initial member. They can only leave the pool once all other
725	/// members have left. Once they fully leave, the pool is destroyed.
726	pub depositor: AccountId,
727	/// Can change the nominator, bouncer, or itself and can perform any of the actions the
728	/// nominator or bouncer can.
729	pub root: Option<AccountId>,
730	/// Can select which validators the pool nominates.
731	pub nominator: Option<AccountId>,
732	/// Can change the pools state and kick members if the pool is blocked.
733	pub bouncer: Option<AccountId>,
734}
735
736// A pool's possible commission claiming permissions.
737#[derive(
738	PartialEq,
739	Eq,
740	Copy,
741	Clone,
742	Encode,
743	Decode,
744	DecodeWithMemTracking,
745	RuntimeDebug,
746	TypeInfo,
747	MaxEncodedLen,
748)]
749pub enum CommissionClaimPermission<AccountId> {
750	Permissionless,
751	Account(AccountId),
752}
753
754/// Pool commission.
755///
756/// The pool `root` can set commission configuration after pool creation. By default, all commission
757/// values are `None`. Pool `root` can also set `max` and `change_rate` configurations before
758/// setting an initial `current` commission.
759///
760/// `current` is a tuple of the commission percentage and payee of commission. `throttle_from`
761/// keeps track of which block `current` was last updated. A `max` commission value can only be
762/// decreased after the initial value is set, to prevent commission from repeatedly increasing.
763///
764/// An optional commission `change_rate` allows the pool to set strict limits to how much commission
765/// can change in each update, and how often updates can take place.
766#[derive(
767	Encode, Decode, DefaultNoBound, MaxEncodedLen, TypeInfo, DebugNoBound, PartialEq, Copy, Clone,
768)]
769#[codec(mel_bound(T: Config))]
770#[scale_info(skip_type_params(T))]
771pub struct Commission<T: Config> {
772	/// Optional commission rate of the pool along with the account commission is paid to.
773	pub current: Option<(Perbill, T::AccountId)>,
774	/// Optional maximum commission that can be set by the pool `root`. Once set, this value can
775	/// only be updated to a decreased value.
776	pub max: Option<Perbill>,
777	/// Optional configuration around how often commission can be updated, and when the last
778	/// commission update took place.
779	pub change_rate: Option<CommissionChangeRate<BlockNumberFor<T>>>,
780	/// The block from where throttling should be checked from. This value will be updated on all
781	/// commission updates and when setting an initial `change_rate`.
782	pub throttle_from: Option<BlockNumberFor<T>>,
783	// Whether commission can be claimed permissionlessly, or whether an account can claim
784	// commission. `Root` role can always claim.
785	pub claim_permission: Option<CommissionClaimPermission<T::AccountId>>,
786}
787
788impl<T: Config> Commission<T> {
789	/// Returns true if the current commission updating to `to` would exhaust the change rate
790	/// limits.
791	///
792	/// A commission update will be throttled (disallowed) if:
793	/// 1. not enough blocks have passed since the `throttle_from` block, if exists, or
794	/// 2. the new commission is greater than the maximum allowed increase.
795	fn throttling(&self, to: &Perbill) -> bool {
796		if let Some(t) = self.change_rate.as_ref() {
797			let commission_as_percent =
798				self.current.as_ref().map(|(x, _)| *x).unwrap_or(Perbill::zero());
799
800			// do not throttle if `to` is the same or a decrease in commission.
801			if *to <= commission_as_percent {
802				return false
803			}
804			// Test for `max_increase` throttling.
805			//
806			// Throttled if the attempted increase in commission is greater than `max_increase`.
807			if (*to).saturating_sub(commission_as_percent) > t.max_increase {
808				return true
809			}
810
811			// Test for `min_delay` throttling.
812			//
813			// Note: matching `None` is defensive only. `throttle_from` should always exist where
814			// `change_rate` has already been set, so this scenario should never happen.
815			return self.throttle_from.map_or_else(
816				|| {
817					defensive!("throttle_from should exist if change_rate is set");
818					true
819				},
820				|f| {
821					// if `min_delay` is zero (no delay), not throttling.
822					if t.min_delay == Zero::zero() {
823						false
824					} else {
825						// throttling if blocks passed is less than `min_delay`.
826						let blocks_surpassed =
827							T::BlockNumberProvider::current_block_number().saturating_sub(f);
828						blocks_surpassed < t.min_delay
829					}
830				},
831			)
832		}
833		false
834	}
835
836	/// Gets the pool's current commission, or returns Perbill::zero if none is set.
837	/// Bounded to global max if current is greater than `GlobalMaxCommission`.
838	fn current(&self) -> Perbill {
839		self.current
840			.as_ref()
841			.map_or(Perbill::zero(), |(c, _)| *c)
842			.min(GlobalMaxCommission::<T>::get().unwrap_or(Bounded::max_value()))
843	}
844
845	/// Set the pool's commission.
846	///
847	/// Update commission based on `current`. If a `None` is supplied, allow the commission to be
848	/// removed without any change rate restrictions. Updates `throttle_from` to the current block.
849	/// If the supplied commission is zero, `None` will be inserted and `payee` will be ignored.
850	fn try_update_current(&mut self, current: &Option<(Perbill, T::AccountId)>) -> DispatchResult {
851		self.current = match current {
852			None => None,
853			Some((commission, payee)) => {
854				ensure!(!self.throttling(commission), Error::<T>::CommissionChangeThrottled);
855				ensure!(
856					commission <= &GlobalMaxCommission::<T>::get().unwrap_or(Bounded::max_value()),
857					Error::<T>::CommissionExceedsGlobalMaximum
858				);
859				ensure!(
860					self.max.map_or(true, |m| commission <= &m),
861					Error::<T>::CommissionExceedsMaximum
862				);
863				if commission.is_zero() {
864					None
865				} else {
866					Some((*commission, payee.clone()))
867				}
868			},
869		};
870		self.register_update();
871		Ok(())
872	}
873
874	/// Set the pool's maximum commission.
875	///
876	/// The pool's maximum commission can initially be set to any value, and only smaller values
877	/// thereafter. If larger values are attempted, this function will return a dispatch error.
878	///
879	/// If `current.0` is larger than the updated max commission value, `current.0` will also be
880	/// updated to the new maximum. This will also register a `throttle_from` update.
881	/// A `PoolCommissionUpdated` event is triggered if `current.0` is updated.
882	fn try_update_max(&mut self, pool_id: PoolId, new_max: Perbill) -> DispatchResult {
883		ensure!(
884			new_max <= GlobalMaxCommission::<T>::get().unwrap_or(Bounded::max_value()),
885			Error::<T>::CommissionExceedsGlobalMaximum
886		);
887		if let Some(old) = self.max.as_mut() {
888			if new_max > *old {
889				return Err(Error::<T>::MaxCommissionRestricted.into())
890			}
891			*old = new_max;
892		} else {
893			self.max = Some(new_max)
894		};
895		let updated_current = self
896			.current
897			.as_mut()
898			.map(|(c, _)| {
899				let u = *c > new_max;
900				*c = (*c).min(new_max);
901				u
902			})
903			.unwrap_or(false);
904
905		if updated_current {
906			if let Some((_, payee)) = self.current.as_ref() {
907				Pallet::<T>::deposit_event(Event::<T>::PoolCommissionUpdated {
908					pool_id,
909					current: Some((new_max, payee.clone())),
910				});
911			}
912			self.register_update();
913		}
914		Ok(())
915	}
916
917	/// Set the pool's commission `change_rate`.
918	///
919	/// Once a change rate configuration has been set, only more restrictive values can be set
920	/// thereafter. These restrictions translate to increased `min_delay` values and decreased
921	/// `max_increase` values.
922	///
923	/// Update `throttle_from` to the current block upon setting change rate for the first time, so
924	/// throttling can be checked from this block.
925	fn try_update_change_rate(
926		&mut self,
927		change_rate: CommissionChangeRate<BlockNumberFor<T>>,
928	) -> DispatchResult {
929		ensure!(!&self.less_restrictive(&change_rate), Error::<T>::CommissionChangeRateNotAllowed);
930
931		if self.change_rate.is_none() {
932			self.register_update();
933		}
934		self.change_rate = Some(change_rate);
935		Ok(())
936	}
937
938	/// Updates a commission's `throttle_from` field to the current block.
939	fn register_update(&mut self) {
940		self.throttle_from = Some(T::BlockNumberProvider::current_block_number());
941	}
942
943	/// Checks whether a change rate is less restrictive than the current change rate, if any.
944	///
945	/// No change rate will always be less restrictive than some change rate, so where no
946	/// `change_rate` is currently set, `false` is returned.
947	fn less_restrictive(&self, new: &CommissionChangeRate<BlockNumberFor<T>>) -> bool {
948		self.change_rate
949			.as_ref()
950			.map(|c| new.max_increase > c.max_increase || new.min_delay < c.min_delay)
951			.unwrap_or(false)
952	}
953}
954
955/// Pool commission change rate preferences.
956///
957/// The pool root is able to set a commission change rate for their pool. A commission change rate
958/// consists of 2 values; (1) the maximum allowed commission change, and (2) the minimum amount of
959/// blocks that must elapse before commission updates are allowed again.
960///
961/// Commission change rates are not applied to decreases in commission.
962#[derive(
963	Encode, Decode, DecodeWithMemTracking, MaxEncodedLen, TypeInfo, Debug, PartialEq, Copy, Clone,
964)]
965pub struct CommissionChangeRate<BlockNumber> {
966	/// The maximum amount the commission can be updated by per `min_delay` period.
967	pub max_increase: Perbill,
968	/// How often an update can take place.
969	pub min_delay: BlockNumber,
970}
971
972/// Pool permissions and state
973#[derive(Encode, Decode, MaxEncodedLen, TypeInfo, DebugNoBound, PartialEq, Clone)]
974#[codec(mel_bound(T: Config))]
975#[scale_info(skip_type_params(T))]
976pub struct BondedPoolInner<T: Config> {
977	/// The commission rate of the pool.
978	pub commission: Commission<T>,
979	/// Count of members that belong to the pool.
980	pub member_counter: u32,
981	/// Total points of all the members in the pool who are actively bonded.
982	pub points: BalanceOf<T>,
983	/// See [`PoolRoles`].
984	pub roles: PoolRoles<T::AccountId>,
985	/// The current state of the pool.
986	pub state: PoolState,
987}
988
989/// A wrapper for bonded pools, with utility functions.
990///
991/// The main purpose of this is to wrap a [`BondedPoolInner`], with the account
992/// + id of the pool, for easier access.
993#[derive(RuntimeDebugNoBound)]
994#[cfg_attr(feature = "std", derive(Clone, PartialEq))]
995pub struct BondedPool<T: Config> {
996	/// The identifier of the pool.
997	id: PoolId,
998	/// The inner fields.
999	inner: BondedPoolInner<T>,
1000}
1001
1002impl<T: Config> core::ops::Deref for BondedPool<T> {
1003	type Target = BondedPoolInner<T>;
1004	fn deref(&self) -> &Self::Target {
1005		&self.inner
1006	}
1007}
1008
1009impl<T: Config> core::ops::DerefMut for BondedPool<T> {
1010	fn deref_mut(&mut self) -> &mut Self::Target {
1011		&mut self.inner
1012	}
1013}
1014
1015impl<T: Config> BondedPool<T> {
1016	/// Create a new bonded pool with the given roles and identifier.
1017	fn new(id: PoolId, roles: PoolRoles<T::AccountId>) -> Self {
1018		Self {
1019			id,
1020			inner: BondedPoolInner {
1021				commission: Commission::default(),
1022				member_counter: Zero::zero(),
1023				points: Zero::zero(),
1024				roles,
1025				state: PoolState::Open,
1026			},
1027		}
1028	}
1029
1030	/// Get [`Self`] from storage. Returns `None` if no entry for `pool_account` exists.
1031	pub fn get(id: PoolId) -> Option<Self> {
1032		BondedPools::<T>::try_get(id).ok().map(|inner| Self { id, inner })
1033	}
1034
1035	/// Get the bonded account id of this pool.
1036	fn bonded_account(&self) -> T::AccountId {
1037		Pallet::<T>::generate_bonded_account(self.id)
1038	}
1039
1040	/// Get the reward account id of this pool.
1041	fn reward_account(&self) -> T::AccountId {
1042		Pallet::<T>::generate_reward_account(self.id)
1043	}
1044
1045	/// Consume self and put into storage.
1046	fn put(self) {
1047		BondedPools::<T>::insert(self.id, self.inner);
1048	}
1049
1050	/// Consume self and remove from storage.
1051	fn remove(self) {
1052		BondedPools::<T>::remove(self.id);
1053	}
1054
1055	/// Convert the given amount of balance to points given the current pool state.
1056	///
1057	/// This is often used for bonding and issuing new funds into the pool.
1058	fn balance_to_point(&self, new_funds: BalanceOf<T>) -> BalanceOf<T> {
1059		let bonded_balance = T::StakeAdapter::active_stake(Pool::from(self.bonded_account()));
1060		Pallet::<T>::balance_to_point(bonded_balance, self.points, new_funds)
1061	}
1062
1063	/// Convert the given number of points to balance given the current pool state.
1064	///
1065	/// This is often used for unbonding.
1066	fn points_to_balance(&self, points: BalanceOf<T>) -> BalanceOf<T> {
1067		let bonded_balance = T::StakeAdapter::active_stake(Pool::from(self.bonded_account()));
1068		Pallet::<T>::point_to_balance(bonded_balance, self.points, points)
1069	}
1070
1071	/// Issue points to [`Self`] for `new_funds`.
1072	fn issue(&mut self, new_funds: BalanceOf<T>) -> BalanceOf<T> {
1073		let points_to_issue = self.balance_to_point(new_funds);
1074		self.points = self.points.saturating_add(points_to_issue);
1075		points_to_issue
1076	}
1077
1078	/// Dissolve some points from the pool i.e. unbond the given amount of points from this pool.
1079	/// This is the opposite of issuing some funds into the pool.
1080	///
1081	/// Mutates self in place, but does not write anything to storage.
1082	///
1083	/// Returns the equivalent balance amount that actually needs to get unbonded.
1084	fn dissolve(&mut self, points: BalanceOf<T>) -> BalanceOf<T> {
1085		// NOTE: do not optimize by removing `balance`. it must be computed before mutating
1086		// `self.point`.
1087		let balance = self.points_to_balance(points);
1088		self.points = self.points.saturating_sub(points);
1089		balance
1090	}
1091
1092	/// Increment the member counter. Ensures that the pool and system member limits are
1093	/// respected.
1094	fn try_inc_members(&mut self) -> Result<(), DispatchError> {
1095		ensure!(
1096			MaxPoolMembersPerPool::<T>::get()
1097				.map_or(true, |max_per_pool| self.member_counter < max_per_pool),
1098			Error::<T>::MaxPoolMembers
1099		);
1100		ensure!(
1101			MaxPoolMembers::<T>::get().map_or(true, |max| PoolMembers::<T>::count() < max),
1102			Error::<T>::MaxPoolMembers
1103		);
1104		self.member_counter = self.member_counter.checked_add(1).ok_or(Error::<T>::OverflowRisk)?;
1105		Ok(())
1106	}
1107
1108	/// Decrement the member counter.
1109	fn dec_members(mut self) -> Self {
1110		self.member_counter = self.member_counter.defensive_saturating_sub(1);
1111		self
1112	}
1113
1114	fn is_root(&self, who: &T::AccountId) -> bool {
1115		self.roles.root.as_ref().map_or(false, |root| root == who)
1116	}
1117
1118	fn is_bouncer(&self, who: &T::AccountId) -> bool {
1119		self.roles.bouncer.as_ref().map_or(false, |bouncer| bouncer == who)
1120	}
1121
1122	fn can_update_roles(&self, who: &T::AccountId) -> bool {
1123		self.is_root(who)
1124	}
1125
1126	fn can_nominate(&self, who: &T::AccountId) -> bool {
1127		self.is_root(who) ||
1128			self.roles.nominator.as_ref().map_or(false, |nominator| nominator == who)
1129	}
1130
1131	fn can_kick(&self, who: &T::AccountId) -> bool {
1132		self.state == PoolState::Blocked && (self.is_root(who) || self.is_bouncer(who))
1133	}
1134
1135	fn can_toggle_state(&self, who: &T::AccountId) -> bool {
1136		(self.is_root(who) || self.is_bouncer(who)) && !self.is_destroying()
1137	}
1138
1139	fn can_set_metadata(&self, who: &T::AccountId) -> bool {
1140		self.is_root(who) || self.is_bouncer(who)
1141	}
1142
1143	fn can_manage_commission(&self, who: &T::AccountId) -> bool {
1144		self.is_root(who)
1145	}
1146
1147	fn can_claim_commission(&self, who: &T::AccountId) -> bool {
1148		if let Some(permission) = self.commission.claim_permission.as_ref() {
1149			match permission {
1150				CommissionClaimPermission::Permissionless => true,
1151				CommissionClaimPermission::Account(account) => account == who || self.is_root(who),
1152			}
1153		} else {
1154			self.is_root(who)
1155		}
1156	}
1157
1158	fn is_destroying(&self) -> bool {
1159		matches!(self.state, PoolState::Destroying)
1160	}
1161
1162	fn is_destroying_and_only_depositor(&self, alleged_depositor_points: BalanceOf<T>) -> bool {
1163		// we need to ensure that `self.member_counter == 1` as well, because the depositor's
1164		// initial `MinCreateBond` (or more) is what guarantees that the ledger of the pool does not
1165		// get killed in the staking system, and that it does not fall below `MinimumNominatorBond`,
1166		// which could prevent other non-depositor members from fully leaving. Thus, all members
1167		// must withdraw, then depositor can unbond, and finally withdraw after waiting another
1168		// cycle.
1169		self.is_destroying() && self.points == alleged_depositor_points && self.member_counter == 1
1170	}
1171
1172	/// Whether or not the pool is ok to be in `PoolSate::Open`. If this returns an `Err`, then the
1173	/// pool is unrecoverable and should be in the destroying state.
1174	fn ok_to_be_open(&self) -> Result<(), DispatchError> {
1175		ensure!(!self.is_destroying(), Error::<T>::CanNotChangeState);
1176
1177		let bonded_balance = T::StakeAdapter::active_stake(Pool::from(self.bonded_account()));
1178		ensure!(!bonded_balance.is_zero(), Error::<T>::OverflowRisk);
1179
1180		let points_to_balance_ratio_floor = self
1181			.points
1182			// We checked for zero above
1183			.div(bonded_balance);
1184
1185		let max_points_to_balance = T::MaxPointsToBalance::get();
1186
1187		// Pool points can inflate relative to balance, but only if the pool is slashed.
1188		// If we cap the ratio of points:balance so one cannot join a pool that has been slashed
1189		// by `max_points_to_balance`%, if not zero.
1190		ensure!(
1191			points_to_balance_ratio_floor < max_points_to_balance.into(),
1192			Error::<T>::OverflowRisk
1193		);
1194
1195		// then we can be decently confident the bonding pool points will not overflow
1196		// `BalanceOf<T>`. Note that these are just heuristics.
1197
1198		Ok(())
1199	}
1200
1201	/// Check that the pool can accept a member with `new_funds`.
1202	fn ok_to_join(&self) -> Result<(), DispatchError> {
1203		ensure!(self.state == PoolState::Open, Error::<T>::NotOpen);
1204		self.ok_to_be_open()?;
1205		Ok(())
1206	}
1207
1208	fn ok_to_unbond_with(
1209		&self,
1210		caller: &T::AccountId,
1211		target_account: &T::AccountId,
1212		target_member: &PoolMember<T>,
1213		unbonding_points: BalanceOf<T>,
1214	) -> Result<(), DispatchError> {
1215		let is_permissioned = caller == target_account;
1216		let is_depositor = *target_account == self.roles.depositor;
1217		let is_full_unbond = unbonding_points == target_member.active_points();
1218
1219		let balance_after_unbond = {
1220			let new_depositor_points =
1221				target_member.active_points().saturating_sub(unbonding_points);
1222			let mut target_member_after_unbond = (*target_member).clone();
1223			target_member_after_unbond.points = new_depositor_points;
1224			target_member_after_unbond.active_balance()
1225		};
1226
1227		// any partial unbonding is only ever allowed if this unbond is permissioned.
1228		ensure!(
1229			is_permissioned || is_full_unbond,
1230			Error::<T>::PartialUnbondNotAllowedPermissionlessly
1231		);
1232
1233		// any unbond must comply with the balance condition:
1234		ensure!(
1235			is_full_unbond ||
1236				balance_after_unbond >=
1237					if is_depositor {
1238						Pallet::<T>::depositor_min_bond()
1239					} else {
1240						MinJoinBond::<T>::get()
1241					},
1242			Error::<T>::MinimumBondNotMet
1243		);
1244
1245		// additional checks:
1246		match (is_permissioned, is_depositor) {
1247			(true, false) => (),
1248			(true, true) => {
1249				// permission depositor unbond: if destroying and pool is empty, always allowed,
1250				// with no additional limits.
1251				if self.is_destroying_and_only_depositor(target_member.active_points()) {
1252					// everything good, let them unbond anything.
1253				} else {
1254					// depositor cannot fully unbond yet.
1255					ensure!(!is_full_unbond, Error::<T>::MinimumBondNotMet);
1256				}
1257			},
1258			(false, false) => {
1259				// If the pool is blocked, then an admin with kicking permissions can remove a
1260				// member. If the pool is being destroyed, anyone can remove a member
1261				debug_assert!(is_full_unbond);
1262				ensure!(
1263					self.can_kick(caller) || self.is_destroying(),
1264					Error::<T>::NotKickerOrDestroying
1265				)
1266			},
1267			(false, true) => {
1268				// the depositor can simply not be unbonded permissionlessly, period.
1269				return Err(Error::<T>::DoesNotHavePermission.into())
1270			},
1271		};
1272
1273		Ok(())
1274	}
1275
1276	/// # Returns
1277	///
1278	/// * Ok(()) if [`Call::withdraw_unbonded`] can be called, `Err(DispatchError)` otherwise.
1279	fn ok_to_withdraw_unbonded_with(
1280		&self,
1281		caller: &T::AccountId,
1282		target_account: &T::AccountId,
1283	) -> Result<(), DispatchError> {
1284		// This isn't a depositor
1285		let is_permissioned = caller == target_account;
1286		ensure!(
1287			is_permissioned || self.can_kick(caller) || self.is_destroying(),
1288			Error::<T>::NotKickerOrDestroying
1289		);
1290		Ok(())
1291	}
1292
1293	/// Bond exactly `amount` from `who`'s funds into this pool. Increases the [`TotalValueLocked`]
1294	/// by `amount`.
1295	///
1296	/// If the bond is [`BondType::Create`], [`Staking::bond`] is called, and `who` is allowed to be
1297	/// killed. Otherwise, [`Staking::bond_extra`] is called and `who` cannot be killed.
1298	///
1299	/// Returns `Ok(points_issues)`, `Err` otherwise.
1300	fn try_bond_funds(
1301		&mut self,
1302		who: &T::AccountId,
1303		amount: BalanceOf<T>,
1304		ty: BondType,
1305	) -> Result<BalanceOf<T>, DispatchError> {
1306		// We must calculate the points issued *before* we bond who's funds, else points:balance
1307		// ratio will be wrong.
1308		let points_issued = self.issue(amount);
1309
1310		T::StakeAdapter::pledge_bond(
1311			Member::from(who.clone()),
1312			Pool::from(self.bonded_account()),
1313			&self.reward_account(),
1314			amount,
1315			ty,
1316		)?;
1317		TotalValueLocked::<T>::mutate(|tvl| {
1318			tvl.saturating_accrue(amount);
1319		});
1320
1321		Ok(points_issued)
1322	}
1323
1324	// Set the state of `self`, and deposit an event if the state changed. State should never be set
1325	// directly in in order to ensure a state change event is always correctly deposited.
1326	fn set_state(&mut self, state: PoolState) {
1327		if self.state != state {
1328			self.state = state;
1329			Pallet::<T>::deposit_event(Event::<T>::StateChanged {
1330				pool_id: self.id,
1331				new_state: state,
1332			});
1333		};
1334	}
1335}
1336
1337/// A reward pool.
1338///
1339/// A reward pool is not so much a pool anymore, since it does not contain any shares or points.
1340/// Rather, simply to fit nicely next to bonded pool and unbonding pools in terms of terminology. In
1341/// reality, a reward pool is just a container for a few pool-dependent data related to the rewards.
1342#[derive(
1343	Encode,
1344	Decode,
1345	MaxEncodedLen,
1346	TypeInfo,
1347	CloneNoBound,
1348	PartialEqNoBound,
1349	EqNoBound,
1350	RuntimeDebugNoBound,
1351)]
1352#[cfg_attr(feature = "std", derive(DefaultNoBound))]
1353#[codec(mel_bound(T: Config))]
1354#[scale_info(skip_type_params(T))]
1355pub struct RewardPool<T: Config> {
1356	/// The last recorded value of the reward counter.
1357	///
1358	/// This is updated ONLY when the points in the bonded pool change, which means `join`,
1359	/// `bond_extra` and `unbond`, all of which is done through `update_recorded`.
1360	pub last_recorded_reward_counter: T::RewardCounter,
1361	/// The last recorded total payouts of the reward pool.
1362	///
1363	/// Payouts is essentially income of the pool.
1364	///
1365	/// Update criteria is same as that of `last_recorded_reward_counter`.
1366	pub last_recorded_total_payouts: BalanceOf<T>,
1367	/// Total amount that this pool has paid out so far to the members.
1368	pub total_rewards_claimed: BalanceOf<T>,
1369	/// The amount of commission pending to be claimed.
1370	pub total_commission_pending: BalanceOf<T>,
1371	/// The amount of commission that has been claimed.
1372	pub total_commission_claimed: BalanceOf<T>,
1373}
1374
1375impl<T: Config> RewardPool<T> {
1376	/// Getter for [`RewardPool::last_recorded_reward_counter`].
1377	pub(crate) fn last_recorded_reward_counter(&self) -> T::RewardCounter {
1378		self.last_recorded_reward_counter
1379	}
1380
1381	/// Register some rewards that are claimed from the pool by the members.
1382	fn register_claimed_reward(&mut self, reward: BalanceOf<T>) {
1383		self.total_rewards_claimed = self.total_rewards_claimed.saturating_add(reward);
1384	}
1385
1386	/// Update the recorded values of the reward pool.
1387	///
1388	/// This function MUST be called whenever the points in the bonded pool change, AND whenever the
1389	/// the pools commission is updated. The reason for the former is that a change in pool points
1390	/// will alter the share of the reward balance among pool members, and the reason for the latter
1391	/// is that a change in commission will alter the share of the reward balance among the pool.
1392	fn update_records(
1393		&mut self,
1394		id: PoolId,
1395		bonded_points: BalanceOf<T>,
1396		commission: Perbill,
1397	) -> Result<(), Error<T>> {
1398		let balance = Self::current_balance(id);
1399
1400		let (current_reward_counter, new_pending_commission) =
1401			self.current_reward_counter(id, bonded_points, commission)?;
1402
1403		// Store the reward counter at the time of this update. This is used in subsequent calls to
1404		// `current_reward_counter`, whereby newly pending rewards (in points) are added to this
1405		// value.
1406		self.last_recorded_reward_counter = current_reward_counter;
1407
1408		// Add any new pending commission that has been calculated from `current_reward_counter` to
1409		// determine the total pending commission at the time of this update.
1410		self.total_commission_pending =
1411			self.total_commission_pending.saturating_add(new_pending_commission);
1412
1413		// Total payouts are essentially the entire historical balance of the reward pool, equating
1414		// to the current balance + the total rewards that have left the pool + the total commission
1415		// that has left the pool.
1416		let last_recorded_total_payouts = balance
1417			.checked_add(&self.total_rewards_claimed.saturating_add(self.total_commission_claimed))
1418			.ok_or(Error::<T>::OverflowRisk)?;
1419
1420		// Store the total payouts at the time of this update.
1421		//
1422		// An increase in ED could cause `last_recorded_total_payouts` to decrease but we should not
1423		// allow that to happen since an already paid out reward cannot decrease. The reward account
1424		// might go in deficit temporarily in this exceptional case but it will be corrected once
1425		// new rewards are added to the pool.
1426		self.last_recorded_total_payouts =
1427			self.last_recorded_total_payouts.max(last_recorded_total_payouts);
1428
1429		Ok(())
1430	}
1431
1432	/// Get the current reward counter, based on the given `bonded_points` being the state of the
1433	/// bonded pool at this time.
1434	fn current_reward_counter(
1435		&self,
1436		id: PoolId,
1437		bonded_points: BalanceOf<T>,
1438		commission: Perbill,
1439	) -> Result<(T::RewardCounter, BalanceOf<T>), Error<T>> {
1440		let balance = Self::current_balance(id);
1441
1442		// Calculate the current payout balance. The first 3 values of this calculation added
1443		// together represent what the balance would be if no payouts were made. The
1444		// `last_recorded_total_payouts` is then subtracted from this value to cancel out previously
1445		// recorded payouts, leaving only the remaining payouts that have not been claimed.
1446		let current_payout_balance = balance
1447			.saturating_add(self.total_rewards_claimed)
1448			.saturating_add(self.total_commission_claimed)
1449			.saturating_sub(self.last_recorded_total_payouts);
1450
1451		// Split the `current_payout_balance` into claimable rewards and claimable commission
1452		// according to the current commission rate.
1453		let new_pending_commission = commission * current_payout_balance;
1454		let new_pending_rewards = current_payout_balance.saturating_sub(new_pending_commission);
1455
1456		// * accuracy notes regarding the multiplication in `checked_from_rational`:
1457		// `current_payout_balance` is a subset of the total_issuance at the very worse.
1458		// `bonded_points` are similarly, in a non-slashed pool, have the same granularity as
1459		// balance, and are thus below within the range of total_issuance. In the worse case
1460		// scenario, for `saturating_from_rational`, we have:
1461		//
1462		// dot_total_issuance * 10^18 / `minJoinBond`
1463		//
1464		// assuming `MinJoinBond == ED`
1465		//
1466		// dot_total_issuance * 10^18 / 10^10 = dot_total_issuance * 10^8
1467		//
1468		// which, with the current numbers, is a miniscule fraction of the u128 capacity.
1469		//
1470		// Thus, adding two values of type reward counter should be safe for ages in a chain like
1471		// Polkadot. The important note here is that `reward_pool.last_recorded_reward_counter` only
1472		// ever accumulates, but its semantics imply that it is less than total_issuance, when
1473		// represented as `FixedU128`, which means it is less than `total_issuance * 10^18`.
1474		//
1475		// * accuracy notes regarding `checked_from_rational` collapsing to zero, meaning that no
1476		//   reward can be claimed:
1477		//
1478		// largest `bonded_points`, such that the reward counter is non-zero, with `FixedU128` will
1479		// be when the payout is being computed. This essentially means `payout/bonded_points` needs
1480		// to be more than 1/1^18. Thus, assuming that `bonded_points` will always be less than `10
1481		// * dot_total_issuance`, if the reward_counter is the smallest possible value, the value of
1482		//   the
1483		// reward being calculated is:
1484		//
1485		// x / 10^20 = 1/ 10^18
1486		//
1487		// x = 100
1488		//
1489		// which is basically 10^-8 DOTs. See `smallest_claimable_reward` for an example of this.
1490		let current_reward_counter =
1491			T::RewardCounter::checked_from_rational(new_pending_rewards, bonded_points)
1492				.and_then(|ref r| self.last_recorded_reward_counter.checked_add(r))
1493				.ok_or(Error::<T>::OverflowRisk)?;
1494
1495		Ok((current_reward_counter, new_pending_commission))
1496	}
1497
1498	/// Current free balance of the reward pool.
1499	///
1500	/// This is sum of all the rewards that are claimable by pool members.
1501	fn current_balance(id: PoolId) -> BalanceOf<T> {
1502		T::Currency::reducible_balance(
1503			&Pallet::<T>::generate_reward_account(id),
1504			Preservation::Expendable,
1505			Fortitude::Polite,
1506		)
1507	}
1508}
1509
1510/// An unbonding pool. This is always mapped with an era.
1511#[derive(
1512	Encode,
1513	Decode,
1514	MaxEncodedLen,
1515	TypeInfo,
1516	DefaultNoBound,
1517	RuntimeDebugNoBound,
1518	CloneNoBound,
1519	PartialEqNoBound,
1520	EqNoBound,
1521)]
1522#[codec(mel_bound(T: Config))]
1523#[scale_info(skip_type_params(T))]
1524pub struct UnbondPool<T: Config> {
1525	/// The points in this pool.
1526	pub points: BalanceOf<T>,
1527	/// The funds in the pool.
1528	pub balance: BalanceOf<T>,
1529}
1530
1531impl<T: Config> UnbondPool<T> {
1532	fn balance_to_point(&self, new_funds: BalanceOf<T>) -> BalanceOf<T> {
1533		Pallet::<T>::balance_to_point(self.balance, self.points, new_funds)
1534	}
1535
1536	fn point_to_balance(&self, points: BalanceOf<T>) -> BalanceOf<T> {
1537		Pallet::<T>::point_to_balance(self.balance, self.points, points)
1538	}
1539
1540	/// Issue the equivalent points of `new_funds` into self.
1541	///
1542	/// Returns the actual amounts of points issued.
1543	fn issue(&mut self, new_funds: BalanceOf<T>) -> BalanceOf<T> {
1544		let new_points = self.balance_to_point(new_funds);
1545		self.points = self.points.saturating_add(new_points);
1546		self.balance = self.balance.saturating_add(new_funds);
1547		new_points
1548	}
1549
1550	/// Dissolve some points from the unbonding pool, reducing the balance of the pool
1551	/// proportionally. This is the opposite of `issue`.
1552	///
1553	/// Returns the actual amount of `Balance` that was removed from the pool.
1554	fn dissolve(&mut self, points: BalanceOf<T>) -> BalanceOf<T> {
1555		let balance_to_unbond = self.point_to_balance(points);
1556		self.points = self.points.saturating_sub(points);
1557		self.balance = self.balance.saturating_sub(balance_to_unbond);
1558
1559		balance_to_unbond
1560	}
1561}
1562
1563#[derive(
1564	Encode,
1565	Decode,
1566	MaxEncodedLen,
1567	TypeInfo,
1568	DefaultNoBound,
1569	RuntimeDebugNoBound,
1570	CloneNoBound,
1571	PartialEqNoBound,
1572	EqNoBound,
1573)]
1574#[codec(mel_bound(T: Config))]
1575#[scale_info(skip_type_params(T))]
1576pub struct SubPools<T: Config> {
1577	/// A general, era agnostic pool of funds that have fully unbonded. The pools
1578	/// of `Self::with_era` will lazily be merged into into this pool if they are
1579	/// older then `current_era - TotalUnbondingPools`.
1580	pub no_era: UnbondPool<T>,
1581	/// Map of era in which a pool becomes unbonded in => unbond pools.
1582	pub with_era: BoundedBTreeMap<EraIndex, UnbondPool<T>, TotalUnbondingPools<T>>,
1583}
1584
1585impl<T: Config> SubPools<T> {
1586	/// Merge the oldest `with_era` unbond pools into the `no_era` unbond pool.
1587	///
1588	/// This is often used whilst getting the sub-pool from storage, thus it consumes and returns
1589	/// `Self` for ergonomic purposes.
1590	fn maybe_merge_pools(mut self, current_era: EraIndex) -> Self {
1591		// Ex: if `TotalUnbondingPools` is 5 and current era is 10, we only want to retain pools
1592		// 6..=10. Note that in the first few eras where `checked_sub` is `None`, we don't remove
1593		// anything.
1594		if let Some(newest_era_to_remove) =
1595			current_era.checked_sub(T::PostUnbondingPoolsWindow::get())
1596		{
1597			self.with_era.retain(|k, v| {
1598				if *k > newest_era_to_remove {
1599					// keep
1600					true
1601				} else {
1602					// merge into the no-era pool
1603					self.no_era.points = self.no_era.points.saturating_add(v.points);
1604					self.no_era.balance = self.no_era.balance.saturating_add(v.balance);
1605					false
1606				}
1607			});
1608		}
1609
1610		self
1611	}
1612
1613	/// The sum of all unbonding balance, regardless of whether they are actually unlocked or not.
1614	#[cfg(any(feature = "try-runtime", feature = "fuzzing", test, debug_assertions))]
1615	fn sum_unbonding_balance(&self) -> BalanceOf<T> {
1616		self.no_era.balance.saturating_add(
1617			self.with_era
1618				.values()
1619				.fold(BalanceOf::<T>::zero(), |acc, pool| acc.saturating_add(pool.balance)),
1620		)
1621	}
1622}
1623
1624/// The maximum amount of eras an unbonding pool can exist prior to being merged with the
1625/// `no_era` pool. This is guaranteed to at least be equal to the staking `UnbondingDuration`. For
1626/// improved UX [`Config::PostUnbondingPoolsWindow`] should be configured to a non-zero value.
1627pub struct TotalUnbondingPools<T: Config>(PhantomData<T>);
1628
1629impl<T: Config> Get<u32> for TotalUnbondingPools<T> {
1630	fn get() -> u32 {
1631		// NOTE: this may be dangerous in the scenario bonding_duration gets decreased because
1632		// we would no longer be able to decode `BoundedBTreeMap::<EraIndex, UnbondPool<T>,
1633		// TotalUnbondingPools<T>>`, which uses `TotalUnbondingPools` as the bound
1634		T::StakeAdapter::bonding_duration() + T::PostUnbondingPoolsWindow::get()
1635	}
1636}
1637
1638#[frame_support::pallet]
1639pub mod pallet {
1640	use super::*;
1641	use frame_support::traits::StorageVersion;
1642	use frame_system::pallet_prelude::{
1643		ensure_root, ensure_signed, BlockNumberFor as SystemBlockNumberFor, OriginFor,
1644	};
1645	use sp_runtime::Perbill;
1646
1647	/// The in-code storage version.
1648	const STORAGE_VERSION: StorageVersion = StorageVersion::new(8);
1649
1650	#[pallet::pallet]
1651	#[pallet::storage_version(STORAGE_VERSION)]
1652	pub struct Pallet<T>(_);
1653
1654	#[pallet::config]
1655	pub trait Config: frame_system::Config {
1656		/// The overarching event type.
1657		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
1658
1659		/// Weight information for extrinsics in this pallet.
1660		type WeightInfo: weights::WeightInfo;
1661
1662		/// The currency type used for nomination pool.
1663		type Currency: Mutate<Self::AccountId>
1664			+ MutateFreeze<Self::AccountId, Id = Self::RuntimeFreezeReason>;
1665
1666		/// The overarching freeze reason.
1667		type RuntimeFreezeReason: From<FreezeReason>;
1668
1669		/// The type that is used for reward counter.
1670		///
1671		/// The arithmetic of the reward counter might saturate based on the size of the
1672		/// `Currency::Balance`. If this happens, operations fails. Nonetheless, this type should be
1673		/// chosen such that this failure almost never happens, as if it happens, the pool basically
1674		/// needs to be dismantled (or all pools migrated to a larger `RewardCounter` type, which is
1675		/// a PITA to do).
1676		///
1677		/// See the inline code docs of `Member::pending_rewards` and `RewardPool::update_recorded`
1678		/// for example analysis. A [`sp_runtime::FixedU128`] should be fine for chains with balance
1679		/// types similar to that of Polkadot and Kusama, in the absence of severe slashing (or
1680		/// prevented via a reasonable `MaxPointsToBalance`), for many many years to come.
1681		type RewardCounter: FixedPointNumber + MaxEncodedLen + TypeInfo + Default + codec::FullCodec;
1682
1683		/// The nomination pool's pallet id.
1684		#[pallet::constant]
1685		type PalletId: Get<frame_support::PalletId>;
1686
1687		/// The maximum pool points-to-balance ratio that an `open` pool can have.
1688		///
1689		/// This is important in the event slashing takes place and the pool's points-to-balance
1690		/// ratio becomes disproportional.
1691		///
1692		/// Moreover, this relates to the `RewardCounter` type as well, as the arithmetic operations
1693		/// are a function of number of points, and by setting this value to e.g. 10, you ensure
1694		/// that the total number of points in the system are at most 10 times the total_issuance of
1695		/// the chain, in the absolute worse case.
1696		///
1697		/// For a value of 10, the threshold would be a pool points-to-balance ratio of 10:1.
1698		/// Such a scenario would also be the equivalent of the pool being 90% slashed.
1699		#[pallet::constant]
1700		type MaxPointsToBalance: Get<u8>;
1701
1702		/// The maximum number of simultaneous unbonding chunks that can exist per member.
1703		#[pallet::constant]
1704		type MaxUnbonding: Get<u32>;
1705
1706		/// Infallible method for converting `Currency::Balance` to `U256`.
1707		type BalanceToU256: Convert<BalanceOf<Self>, U256>;
1708
1709		/// Infallible method for converting `U256` to `Currency::Balance`.
1710		type U256ToBalance: Convert<U256, BalanceOf<Self>>;
1711
1712		/// The interface for nominating.
1713		///
1714		/// Note: Switching to a new [`StakeStrategy`] might require a migration of the storage.
1715		type StakeAdapter: StakeStrategy<AccountId = Self::AccountId, Balance = BalanceOf<Self>>;
1716
1717		/// The amount of eras a `SubPools::with_era` pool can exist before it gets merged into the
1718		/// `SubPools::no_era` pool. In other words, this is the amount of eras a member will be
1719		/// able to withdraw from an unbonding pool which is guaranteed to have the correct ratio of
1720		/// points to balance; once the `with_era` pool is merged into the `no_era` pool, the ratio
1721		/// can become skewed due to some slashed ratio getting merged in at some point.
1722		type PostUnbondingPoolsWindow: Get<u32>;
1723
1724		/// The maximum length, in bytes, that a pools metadata maybe.
1725		type MaxMetadataLen: Get<u32>;
1726
1727		/// The origin that can manage pool configurations.
1728		type AdminOrigin: EnsureOrigin<Self::RuntimeOrigin>;
1729
1730		/// Provider for the block number. Normally this is the `frame_system` pallet.
1731		type BlockNumberProvider: BlockNumberProvider;
1732
1733		/// Restrict some accounts from participating in a nomination pool.
1734		type Filter: Contains<Self::AccountId>;
1735	}
1736
1737	/// The sum of funds across all pools.
1738	///
1739	/// This might be lower but never higher than the sum of `total_balance` of all [`PoolMembers`]
1740	/// because calling `pool_withdraw_unbonded` might decrease the total stake of the pool's
1741	/// `bonded_account` without adjusting the pallet-internal `UnbondingPool`'s.
1742	#[pallet::storage]
1743	pub type TotalValueLocked<T: Config> = StorageValue<_, BalanceOf<T>, ValueQuery>;
1744
1745	/// Minimum amount to bond to join a pool.
1746	#[pallet::storage]
1747	pub type MinJoinBond<T: Config> = StorageValue<_, BalanceOf<T>, ValueQuery>;
1748
1749	/// Minimum bond required to create a pool.
1750	///
1751	/// This is the amount that the depositor must put as their initial stake in the pool, as an
1752	/// indication of "skin in the game".
1753	///
1754	/// This is the value that will always exist in the staking ledger of the pool bonded account
1755	/// while all other accounts leave.
1756	#[pallet::storage]
1757	pub type MinCreateBond<T: Config> = StorageValue<_, BalanceOf<T>, ValueQuery>;
1758
1759	/// Maximum number of nomination pools that can exist. If `None`, then an unbounded number of
1760	/// pools can exist.
1761	#[pallet::storage]
1762	pub type MaxPools<T: Config> = StorageValue<_, u32, OptionQuery>;
1763
1764	/// Maximum number of members that can exist in the system. If `None`, then the count
1765	/// members are not bound on a system wide basis.
1766	#[pallet::storage]
1767	pub type MaxPoolMembers<T: Config> = StorageValue<_, u32, OptionQuery>;
1768
1769	/// Maximum number of members that may belong to pool. If `None`, then the count of
1770	/// members is not bound on a per pool basis.
1771	#[pallet::storage]
1772	pub type MaxPoolMembersPerPool<T: Config> = StorageValue<_, u32, OptionQuery>;
1773
1774	/// The maximum commission that can be charged by a pool. Used on commission payouts to bound
1775	/// pool commissions that are > `GlobalMaxCommission`, necessary if a future
1776	/// `GlobalMaxCommission` is lower than some current pool commissions.
1777	#[pallet::storage]
1778	pub type GlobalMaxCommission<T: Config> = StorageValue<_, Perbill, OptionQuery>;
1779
1780	/// Active members.
1781	///
1782	/// TWOX-NOTE: SAFE since `AccountId` is a secure hash.
1783	#[pallet::storage]
1784	pub type PoolMembers<T: Config> =
1785		CountedStorageMap<_, Twox64Concat, T::AccountId, PoolMember<T>>;
1786
1787	/// Storage for bonded pools.
1788	// To get or insert a pool see [`BondedPool::get`] and [`BondedPool::put`]
1789	#[pallet::storage]
1790	pub type BondedPools<T: Config> =
1791		CountedStorageMap<_, Twox64Concat, PoolId, BondedPoolInner<T>>;
1792
1793	/// Reward pools. This is where there rewards for each pool accumulate. When a members payout is
1794	/// claimed, the balance comes out of the reward pool. Keyed by the bonded pools account.
1795	#[pallet::storage]
1796	pub type RewardPools<T: Config> = CountedStorageMap<_, Twox64Concat, PoolId, RewardPool<T>>;
1797
1798	/// Groups of unbonding pools. Each group of unbonding pools belongs to a
1799	/// bonded pool, hence the name sub-pools. Keyed by the bonded pools account.
1800	#[pallet::storage]
1801	pub type SubPoolsStorage<T: Config> = CountedStorageMap<_, Twox64Concat, PoolId, SubPools<T>>;
1802
1803	/// Metadata for the pool.
1804	#[pallet::storage]
1805	pub type Metadata<T: Config> =
1806		CountedStorageMap<_, Twox64Concat, PoolId, BoundedVec<u8, T::MaxMetadataLen>, ValueQuery>;
1807
1808	/// Ever increasing number of all pools created so far.
1809	#[pallet::storage]
1810	pub type LastPoolId<T: Config> = StorageValue<_, u32, ValueQuery>;
1811
1812	/// A reverse lookup from the pool's account id to its id.
1813	///
1814	/// This is only used for slashing and on automatic withdraw update. In all other instances, the
1815	/// pool id is used, and the accounts are deterministically derived from it.
1816	#[pallet::storage]
1817	pub type ReversePoolIdLookup<T: Config> =
1818		CountedStorageMap<_, Twox64Concat, T::AccountId, PoolId, OptionQuery>;
1819
1820	/// Map from a pool member account to their opted claim permission.
1821	#[pallet::storage]
1822	pub type ClaimPermissions<T: Config> =
1823		StorageMap<_, Twox64Concat, T::AccountId, ClaimPermission, ValueQuery>;
1824
1825	#[pallet::genesis_config]
1826	pub struct GenesisConfig<T: Config> {
1827		pub min_join_bond: BalanceOf<T>,
1828		pub min_create_bond: BalanceOf<T>,
1829		pub max_pools: Option<u32>,
1830		pub max_members_per_pool: Option<u32>,
1831		pub max_members: Option<u32>,
1832		pub global_max_commission: Option<Perbill>,
1833	}
1834
1835	impl<T: Config> Default for GenesisConfig<T> {
1836		fn default() -> Self {
1837			Self {
1838				min_join_bond: Zero::zero(),
1839				min_create_bond: Zero::zero(),
1840				max_pools: Some(16),
1841				max_members_per_pool: Some(32),
1842				max_members: Some(16 * 32),
1843				global_max_commission: None,
1844			}
1845		}
1846	}
1847
1848	#[pallet::genesis_build]
1849	impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
1850		fn build(&self) {
1851			MinJoinBond::<T>::put(self.min_join_bond);
1852			MinCreateBond::<T>::put(self.min_create_bond);
1853
1854			if let Some(max_pools) = self.max_pools {
1855				MaxPools::<T>::put(max_pools);
1856			}
1857			if let Some(max_members_per_pool) = self.max_members_per_pool {
1858				MaxPoolMembersPerPool::<T>::put(max_members_per_pool);
1859			}
1860			if let Some(max_members) = self.max_members {
1861				MaxPoolMembers::<T>::put(max_members);
1862			}
1863			if let Some(global_max_commission) = self.global_max_commission {
1864				GlobalMaxCommission::<T>::put(global_max_commission);
1865			}
1866		}
1867	}
1868
1869	/// Events of this pallet.
1870	#[pallet::event]
1871	#[pallet::generate_deposit(pub(crate) fn deposit_event)]
1872	pub enum Event<T: Config> {
1873		/// A pool has been created.
1874		Created { depositor: T::AccountId, pool_id: PoolId },
1875		/// A member has became bonded in a pool.
1876		Bonded { member: T::AccountId, pool_id: PoolId, bonded: BalanceOf<T>, joined: bool },
1877		/// A payout has been made to a member.
1878		PaidOut { member: T::AccountId, pool_id: PoolId, payout: BalanceOf<T> },
1879		/// A member has unbonded from their pool.
1880		///
1881		/// - `balance` is the corresponding balance of the number of points that has been
1882		///   requested to be unbonded (the argument of the `unbond` transaction) from the bonded
1883		///   pool.
1884		/// - `points` is the number of points that are issued as a result of `balance` being
1885		/// dissolved into the corresponding unbonding pool.
1886		/// - `era` is the era in which the balance will be unbonded.
1887		/// In the absence of slashing, these values will match. In the presence of slashing, the
1888		/// number of points that are issued in the unbonding pool will be less than the amount
1889		/// requested to be unbonded.
1890		Unbonded {
1891			member: T::AccountId,
1892			pool_id: PoolId,
1893			balance: BalanceOf<T>,
1894			points: BalanceOf<T>,
1895			era: EraIndex,
1896		},
1897		/// A member has withdrawn from their pool.
1898		///
1899		/// The given number of `points` have been dissolved in return of `balance`.
1900		///
1901		/// Similar to `Unbonded` event, in the absence of slashing, the ratio of point to balance
1902		/// will be 1.
1903		Withdrawn {
1904			member: T::AccountId,
1905			pool_id: PoolId,
1906			balance: BalanceOf<T>,
1907			points: BalanceOf<T>,
1908		},
1909		/// A pool has been destroyed.
1910		Destroyed { pool_id: PoolId },
1911		/// The state of a pool has changed
1912		StateChanged { pool_id: PoolId, new_state: PoolState },
1913		/// A member has been removed from a pool.
1914		///
1915		/// The removal can be voluntary (withdrawn all unbonded funds) or involuntary (kicked).
1916		/// Any funds that are still delegated (i.e. dangling delegation) are released and are
1917		/// represented by `released_balance`.
1918		MemberRemoved { pool_id: PoolId, member: T::AccountId, released_balance: BalanceOf<T> },
1919		/// The roles of a pool have been updated to the given new roles. Note that the depositor
1920		/// can never change.
1921		RolesUpdated {
1922			root: Option<T::AccountId>,
1923			bouncer: Option<T::AccountId>,
1924			nominator: Option<T::AccountId>,
1925		},
1926		/// The active balance of pool `pool_id` has been slashed to `balance`.
1927		PoolSlashed { pool_id: PoolId, balance: BalanceOf<T> },
1928		/// The unbond pool at `era` of pool `pool_id` has been slashed to `balance`.
1929		UnbondingPoolSlashed { pool_id: PoolId, era: EraIndex, balance: BalanceOf<T> },
1930		/// A pool's commission setting has been changed.
1931		PoolCommissionUpdated { pool_id: PoolId, current: Option<(Perbill, T::AccountId)> },
1932		/// A pool's maximum commission setting has been changed.
1933		PoolMaxCommissionUpdated { pool_id: PoolId, max_commission: Perbill },
1934		/// A pool's commission `change_rate` has been changed.
1935		PoolCommissionChangeRateUpdated {
1936			pool_id: PoolId,
1937			change_rate: CommissionChangeRate<BlockNumberFor<T>>,
1938		},
1939		/// Pool commission claim permission has been updated.
1940		PoolCommissionClaimPermissionUpdated {
1941			pool_id: PoolId,
1942			permission: Option<CommissionClaimPermission<T::AccountId>>,
1943		},
1944		/// Pool commission has been claimed.
1945		PoolCommissionClaimed { pool_id: PoolId, commission: BalanceOf<T> },
1946		/// Topped up deficit in frozen ED of the reward pool.
1947		MinBalanceDeficitAdjusted { pool_id: PoolId, amount: BalanceOf<T> },
1948		/// Claimed excess frozen ED of af the reward pool.
1949		MinBalanceExcessAdjusted { pool_id: PoolId, amount: BalanceOf<T> },
1950		/// A pool member's claim permission has been updated.
1951		MemberClaimPermissionUpdated { member: T::AccountId, permission: ClaimPermission },
1952		/// A pool's metadata was updated.
1953		MetadataUpdated { pool_id: PoolId, caller: T::AccountId },
1954		/// A pool's nominating account (or the pool's root account) has nominated a validator set
1955		/// on behalf of the pool.
1956		PoolNominationMade { pool_id: PoolId, caller: T::AccountId },
1957		/// The pool is chilled i.e. no longer nominating.
1958		PoolNominatorChilled { pool_id: PoolId, caller: T::AccountId },
1959		/// Global parameters regulating nomination pools have been updated.
1960		GlobalParamsUpdated {
1961			min_join_bond: BalanceOf<T>,
1962			min_create_bond: BalanceOf<T>,
1963			max_pools: Option<u32>,
1964			max_members: Option<u32>,
1965			max_members_per_pool: Option<u32>,
1966			global_max_commission: Option<Perbill>,
1967		},
1968	}
1969
1970	#[pallet::error]
1971	#[cfg_attr(test, derive(PartialEq))]
1972	pub enum Error<T> {
1973		/// A (bonded) pool id does not exist.
1974		PoolNotFound,
1975		/// An account is not a member.
1976		PoolMemberNotFound,
1977		/// A reward pool does not exist. In all cases this is a system logic error.
1978		RewardPoolNotFound,
1979		/// A sub pool does not exist.
1980		SubPoolsNotFound,
1981		/// An account is already delegating in another pool. An account may only belong to one
1982		/// pool at a time.
1983		AccountBelongsToOtherPool,
1984		/// The member is fully unbonded (and thus cannot access the bonded and reward pool
1985		/// anymore to, for example, collect rewards).
1986		FullyUnbonding,
1987		/// The member cannot unbond further chunks due to reaching the limit.
1988		MaxUnbondingLimit,
1989		/// None of the funds can be withdrawn yet because the bonding duration has not passed.
1990		CannotWithdrawAny,
1991		/// The amount does not meet the minimum bond to either join or create a pool.
1992		///
1993		/// The depositor can never unbond to a value less than `Pallet::depositor_min_bond`. The
1994		/// caller does not have nominating permissions for the pool. Members can never unbond to a
1995		/// value below `MinJoinBond`.
1996		MinimumBondNotMet,
1997		/// The transaction could not be executed due to overflow risk for the pool.
1998		OverflowRisk,
1999		/// A pool must be in [`PoolState::Destroying`] in order for the depositor to unbond or for
2000		/// other members to be permissionlessly unbonded.
2001		NotDestroying,
2002		/// The caller does not have nominating permissions for the pool.
2003		NotNominator,
2004		/// Either a) the caller cannot make a valid kick or b) the pool is not destroying.
2005		NotKickerOrDestroying,
2006		/// The pool is not open to join
2007		NotOpen,
2008		/// The system is maxed out on pools.
2009		MaxPools,
2010		/// Too many members in the pool or system.
2011		MaxPoolMembers,
2012		/// The pools state cannot be changed.
2013		CanNotChangeState,
2014		/// The caller does not have adequate permissions.
2015		DoesNotHavePermission,
2016		/// Metadata exceeds [`Config::MaxMetadataLen`]
2017		MetadataExceedsMaxLen,
2018		/// Some error occurred that should never happen. This should be reported to the
2019		/// maintainers.
2020		Defensive(DefensiveError),
2021		/// Partial unbonding now allowed permissionlessly.
2022		PartialUnbondNotAllowedPermissionlessly,
2023		/// The pool's max commission cannot be set higher than the existing value.
2024		MaxCommissionRestricted,
2025		/// The supplied commission exceeds the max allowed commission.
2026		CommissionExceedsMaximum,
2027		/// The supplied commission exceeds global maximum commission.
2028		CommissionExceedsGlobalMaximum,
2029		/// Not enough blocks have surpassed since the last commission update.
2030		CommissionChangeThrottled,
2031		/// The submitted changes to commission change rate are not allowed.
2032		CommissionChangeRateNotAllowed,
2033		/// There is no pending commission to claim.
2034		NoPendingCommission,
2035		/// No commission current has been set.
2036		NoCommissionCurrentSet,
2037		/// Pool id currently in use.
2038		PoolIdInUse,
2039		/// Pool id provided is not correct/usable.
2040		InvalidPoolId,
2041		/// Bonding extra is restricted to the exact pending reward amount.
2042		BondExtraRestricted,
2043		/// No imbalance in the ED deposit for the pool.
2044		NothingToAdjust,
2045		/// No slash pending that can be applied to the member.
2046		NothingToSlash,
2047		/// The slash amount is too low to be applied.
2048		SlashTooLow,
2049		/// The pool or member delegation has already migrated to delegate stake.
2050		AlreadyMigrated,
2051		/// The pool or member delegation has not migrated yet to delegate stake.
2052		NotMigrated,
2053		/// This call is not allowed in the current state of the pallet.
2054		NotSupported,
2055		/// Account is restricted from participation in pools. This may happen if the account is
2056		/// staking in another way already.
2057		Restricted,
2058	}
2059
2060	#[derive(
2061		Encode, Decode, DecodeWithMemTracking, PartialEq, TypeInfo, PalletError, RuntimeDebug,
2062	)]
2063	pub enum DefensiveError {
2064		/// There isn't enough space in the unbond pool.
2065		NotEnoughSpaceInUnbondPool,
2066		/// A (bonded) pool id does not exist.
2067		PoolNotFound,
2068		/// A reward pool does not exist. In all cases this is a system logic error.
2069		RewardPoolNotFound,
2070		/// A sub pool does not exist.
2071		SubPoolsNotFound,
2072		/// The bonded account should only be killed by the staking system when the depositor is
2073		/// withdrawing
2074		BondedStashKilledPrematurely,
2075		/// The delegation feature is unsupported.
2076		DelegationUnsupported,
2077		/// Unable to slash to the member of the pool.
2078		SlashNotApplied,
2079	}
2080
2081	impl<T> From<DefensiveError> for Error<T> {
2082		fn from(e: DefensiveError) -> Error<T> {
2083			Error::<T>::Defensive(e)
2084		}
2085	}
2086
2087	/// A reason for freezing funds.
2088	#[pallet::composite_enum]
2089	pub enum FreezeReason {
2090		/// Pool reward account is restricted from going below Existential Deposit.
2091		#[codec(index = 0)]
2092		PoolMinBalance,
2093	}
2094
2095	#[pallet::call]
2096	impl<T: Config> Pallet<T> {
2097		/// Stake funds with a pool. The amount to bond is delegated (or transferred based on
2098		/// [`adapter::StakeStrategyType`]) from the member to the pool account and immediately
2099		/// increases the pool's bond.
2100		///
2101		/// The method of transferring the amount to the pool account is determined by
2102		/// [`adapter::StakeStrategyType`]. If the pool is configured to use
2103		/// [`adapter::StakeStrategyType::Delegate`], the funds remain in the account of
2104		/// the `origin`, while the pool gains the right to use these funds for staking.
2105		///
2106		/// # Note
2107		///
2108		/// * An account can only be a member of a single pool.
2109		/// * An account cannot join the same pool multiple times.
2110		/// * This call will *not* dust the member account, so the member must have at least
2111		///   `existential deposit + amount` in their account.
2112		/// * Only a pool with [`PoolState::Open`] can be joined
2113		#[pallet::call_index(0)]
2114		#[pallet::weight(T::WeightInfo::join())]
2115		pub fn join(
2116			origin: OriginFor<T>,
2117			#[pallet::compact] amount: BalanceOf<T>,
2118			pool_id: PoolId,
2119		) -> DispatchResult {
2120			let who = ensure_signed(origin)?;
2121			// ensure pool is not in an un-migrated state.
2122			ensure!(!Self::api_pool_needs_delegate_migration(pool_id), Error::<T>::NotMigrated);
2123
2124			// ensure account is not restricted from joining the pool.
2125			ensure!(!T::Filter::contains(&who), Error::<T>::Restricted);
2126
2127			ensure!(amount >= MinJoinBond::<T>::get(), Error::<T>::MinimumBondNotMet);
2128			// If a member already exists that means they already belong to a pool
2129			ensure!(!PoolMembers::<T>::contains_key(&who), Error::<T>::AccountBelongsToOtherPool);
2130
2131			let mut bonded_pool = BondedPool::<T>::get(pool_id).ok_or(Error::<T>::PoolNotFound)?;
2132			bonded_pool.ok_to_join()?;
2133
2134			let mut reward_pool = RewardPools::<T>::get(pool_id)
2135				.defensive_ok_or::<Error<T>>(DefensiveError::RewardPoolNotFound.into())?;
2136			// IMPORTANT: reward pool records must be updated with the old points.
2137			reward_pool.update_records(
2138				pool_id,
2139				bonded_pool.points,
2140				bonded_pool.commission.current(),
2141			)?;
2142
2143			bonded_pool.try_inc_members()?;
2144			let points_issued = bonded_pool.try_bond_funds(&who, amount, BondType::Extra)?;
2145
2146			PoolMembers::insert(
2147				who.clone(),
2148				PoolMember::<T> {
2149					pool_id,
2150					points: points_issued,
2151					// we just updated `last_known_reward_counter` to the current one in
2152					// `update_recorded`.
2153					last_recorded_reward_counter: reward_pool.last_recorded_reward_counter(),
2154					unbonding_eras: Default::default(),
2155				},
2156			);
2157
2158			Self::deposit_event(Event::<T>::Bonded {
2159				member: who,
2160				pool_id,
2161				bonded: amount,
2162				joined: true,
2163			});
2164
2165			bonded_pool.put();
2166			RewardPools::<T>::insert(pool_id, reward_pool);
2167
2168			Ok(())
2169		}
2170
2171		/// Bond `extra` more funds from `origin` into the pool to which they already belong.
2172		///
2173		/// Additional funds can come from either the free balance of the account, of from the
2174		/// accumulated rewards, see [`BondExtra`].
2175		///
2176		/// Bonding extra funds implies an automatic payout of all pending rewards as well.
2177		/// See `bond_extra_other` to bond pending rewards of `other` members.
2178		// NOTE: this transaction is implemented with the sole purpose of readability and
2179		// correctness, not optimization. We read/write several storage items multiple times instead
2180		// of just once, in the spirit reusing code.
2181		#[pallet::call_index(1)]
2182		#[pallet::weight(
2183			T::WeightInfo::bond_extra_transfer()
2184			.max(T::WeightInfo::bond_extra_other())
2185		)]
2186		pub fn bond_extra(origin: OriginFor<T>, extra: BondExtra<BalanceOf<T>>) -> DispatchResult {
2187			let who = ensure_signed(origin)?;
2188
2189			// ensure who is not in an un-migrated state.
2190			ensure!(
2191				!Self::api_member_needs_delegate_migration(who.clone()),
2192				Error::<T>::NotMigrated
2193			);
2194
2195			Self::do_bond_extra(who.clone(), who, extra)
2196		}
2197
2198		/// A bonded member can use this to claim their payout based on the rewards that the pool
2199		/// has accumulated since their last claimed payout (OR since joining if this is their first
2200		/// time claiming rewards). The payout will be transferred to the member's account.
2201		///
2202		/// The member will earn rewards pro rata based on the members stake vs the sum of the
2203		/// members in the pools stake. Rewards do not "expire".
2204		///
2205		/// See `claim_payout_other` to claim rewards on behalf of some `other` pool member.
2206		#[pallet::call_index(2)]
2207		#[pallet::weight(T::WeightInfo::claim_payout())]
2208		pub fn claim_payout(origin: OriginFor<T>) -> DispatchResult {
2209			let signer = ensure_signed(origin)?;
2210			// ensure signer is not in an un-migrated state.
2211			ensure!(
2212				!Self::api_member_needs_delegate_migration(signer.clone()),
2213				Error::<T>::NotMigrated
2214			);
2215
2216			Self::do_claim_payout(signer.clone(), signer)
2217		}
2218
2219		/// Unbond up to `unbonding_points` of the `member_account`'s funds from the pool. It
2220		/// implicitly collects the rewards one last time, since not doing so would mean some
2221		/// rewards would be forfeited.
2222		///
2223		/// Under certain conditions, this call can be dispatched permissionlessly (i.e. by any
2224		/// account).
2225		///
2226		/// # Conditions for a permissionless dispatch.
2227		///
2228		/// * The pool is blocked and the caller is either the root or bouncer. This is refereed to
2229		///   as a kick.
2230		/// * The pool is destroying and the member is not the depositor.
2231		/// * The pool is destroying, the member is the depositor and no other members are in the
2232		///   pool.
2233		///
2234		/// ## Conditions for permissioned dispatch (i.e. the caller is also the
2235		/// `member_account`):
2236		///
2237		/// * The caller is not the depositor.
2238		/// * The caller is the depositor, the pool is destroying and no other members are in the
2239		///   pool.
2240		///
2241		/// # Note
2242		///
2243		/// If there are too many unlocking chunks to unbond with the pool account,
2244		/// [`Call::pool_withdraw_unbonded`] can be called to try and minimize unlocking chunks.
2245		/// The [`StakingInterface::unbond`] will implicitly call [`Call::pool_withdraw_unbonded`]
2246		/// to try to free chunks if necessary (ie. if unbound was called and no unlocking chunks
2247		/// are available). However, it may not be possible to release the current unlocking chunks,
2248		/// in which case, the result of this call will likely be the `NoMoreChunks` error from the
2249		/// staking system.
2250		#[pallet::call_index(3)]
2251		#[pallet::weight(T::WeightInfo::unbond())]
2252		pub fn unbond(
2253			origin: OriginFor<T>,
2254			member_account: AccountIdLookupOf<T>,
2255			#[pallet::compact] unbonding_points: BalanceOf<T>,
2256		) -> DispatchResult {
2257			let who = ensure_signed(origin)?;
2258			let member_account = T::Lookup::lookup(member_account)?;
2259			// ensure member is not in an un-migrated state.
2260			ensure!(
2261				!Self::api_member_needs_delegate_migration(member_account.clone()),
2262				Error::<T>::NotMigrated
2263			);
2264
2265			let (mut member, mut bonded_pool, mut reward_pool) =
2266				Self::get_member_with_pools(&member_account)?;
2267
2268			bonded_pool.ok_to_unbond_with(&who, &member_account, &member, unbonding_points)?;
2269
2270			// Claim the the payout prior to unbonding. Once the user is unbonding their points no
2271			// longer exist in the bonded pool and thus they can no longer claim their payouts. It
2272			// is not strictly necessary to claim the rewards, but we do it here for UX.
2273			reward_pool.update_records(
2274				bonded_pool.id,
2275				bonded_pool.points,
2276				bonded_pool.commission.current(),
2277			)?;
2278			let _ = Self::do_reward_payout(
2279				&member_account,
2280				&mut member,
2281				&mut bonded_pool,
2282				&mut reward_pool,
2283			)?;
2284
2285			let current_era = T::StakeAdapter::current_era();
2286			let unbond_era = T::StakeAdapter::bonding_duration().saturating_add(current_era);
2287
2288			// Unbond in the actual underlying nominator.
2289			let unbonding_balance = bonded_pool.dissolve(unbonding_points);
2290			T::StakeAdapter::unbond(Pool::from(bonded_pool.bonded_account()), unbonding_balance)?;
2291
2292			// Note that we lazily create the unbonding pools here if they don't already exist
2293			let mut sub_pools = SubPoolsStorage::<T>::get(member.pool_id)
2294				.unwrap_or_default()
2295				.maybe_merge_pools(current_era);
2296
2297			// Update the unbond pool associated with the current era with the unbonded funds. Note
2298			// that we lazily create the unbond pool if it does not yet exist.
2299			if !sub_pools.with_era.contains_key(&unbond_era) {
2300				sub_pools
2301					.with_era
2302					.try_insert(unbond_era, UnbondPool::default())
2303					// The above call to `maybe_merge_pools` should ensure there is
2304					// always enough space to insert.
2305					.defensive_map_err::<Error<T>, _>(|_| {
2306						DefensiveError::NotEnoughSpaceInUnbondPool.into()
2307					})?;
2308			}
2309
2310			let points_unbonded = sub_pools
2311				.with_era
2312				.get_mut(&unbond_era)
2313				// The above check ensures the pool exists.
2314				.defensive_ok_or::<Error<T>>(DefensiveError::PoolNotFound.into())?
2315				.issue(unbonding_balance);
2316
2317			// Try and unbond in the member map.
2318			member.try_unbond(unbonding_points, points_unbonded, unbond_era)?;
2319
2320			Self::deposit_event(Event::<T>::Unbonded {
2321				member: member_account.clone(),
2322				pool_id: member.pool_id,
2323				points: points_unbonded,
2324				balance: unbonding_balance,
2325				era: unbond_era,
2326			});
2327
2328			// Now that we know everything has worked write the items to storage.
2329			SubPoolsStorage::insert(member.pool_id, sub_pools);
2330			Self::put_member_with_pools(&member_account, member, bonded_pool, reward_pool);
2331			Ok(())
2332		}
2333
2334		/// Call `withdraw_unbonded` for the pools account. This call can be made by any account.
2335		///
2336		/// This is useful if there are too many unlocking chunks to call `unbond`, and some
2337		/// can be cleared by withdrawing. In the case there are too many unlocking chunks, the user
2338		/// would probably see an error like `NoMoreChunks` emitted from the staking system when
2339		/// they attempt to unbond.
2340		#[pallet::call_index(4)]
2341		#[pallet::weight(T::WeightInfo::pool_withdraw_unbonded(*num_slashing_spans))]
2342		pub fn pool_withdraw_unbonded(
2343			origin: OriginFor<T>,
2344			pool_id: PoolId,
2345			num_slashing_spans: u32,
2346		) -> DispatchResult {
2347			let _ = ensure_signed(origin)?;
2348			// ensure pool is not in an un-migrated state.
2349			ensure!(!Self::api_pool_needs_delegate_migration(pool_id), Error::<T>::NotMigrated);
2350
2351			let pool = BondedPool::<T>::get(pool_id).ok_or(Error::<T>::PoolNotFound)?;
2352
2353			// For now we only allow a pool to withdraw unbonded if its not destroying. If the pool
2354			// is destroying then `withdraw_unbonded` can be used.
2355			ensure!(pool.state != PoolState::Destroying, Error::<T>::NotDestroying);
2356			T::StakeAdapter::withdraw_unbonded(
2357				Pool::from(pool.bonded_account()),
2358				num_slashing_spans,
2359			)?;
2360
2361			Ok(())
2362		}
2363
2364		/// Withdraw unbonded funds from `member_account`. If no bonded funds can be unbonded, an
2365		/// error is returned.
2366		///
2367		/// Under certain conditions, this call can be dispatched permissionlessly (i.e. by any
2368		/// account).
2369		///
2370		/// # Conditions for a permissionless dispatch
2371		///
2372		/// * The pool is in destroy mode and the target is not the depositor.
2373		/// * The target is the depositor and they are the only member in the sub pools.
2374		/// * The pool is blocked and the caller is either the root or bouncer.
2375		///
2376		/// # Conditions for permissioned dispatch
2377		///
2378		/// * The caller is the target and they are not the depositor.
2379		///
2380		/// # Note
2381		///
2382		/// - If the target is the depositor, the pool will be destroyed.
2383		/// - If the pool has any pending slash, we also try to slash the member before letting them
2384		/// withdraw. This calculation adds some weight overhead and is only defensive. In reality,
2385		/// pool slashes must have been already applied via permissionless [`Call::apply_slash`].
2386		#[pallet::call_index(5)]
2387		#[pallet::weight(
2388			T::WeightInfo::withdraw_unbonded_kill(*num_slashing_spans)
2389		)]
2390		pub fn withdraw_unbonded(
2391			origin: OriginFor<T>,
2392			member_account: AccountIdLookupOf<T>,
2393			num_slashing_spans: u32,
2394		) -> DispatchResultWithPostInfo {
2395			let caller = ensure_signed(origin)?;
2396			let member_account = T::Lookup::lookup(member_account)?;
2397			// ensure member is not in an un-migrated state.
2398			ensure!(
2399				!Self::api_member_needs_delegate_migration(member_account.clone()),
2400				Error::<T>::NotMigrated
2401			);
2402
2403			let mut member =
2404				PoolMembers::<T>::get(&member_account).ok_or(Error::<T>::PoolMemberNotFound)?;
2405			let current_era = T::StakeAdapter::current_era();
2406
2407			let bonded_pool = BondedPool::<T>::get(member.pool_id)
2408				.defensive_ok_or::<Error<T>>(DefensiveError::PoolNotFound.into())?;
2409			let mut sub_pools =
2410				SubPoolsStorage::<T>::get(member.pool_id).ok_or(Error::<T>::SubPoolsNotFound)?;
2411
2412			let slash_weight =
2413				// apply slash if any before withdraw.
2414				match Self::do_apply_slash(&member_account, None, false) {
2415					Ok(_) => T::WeightInfo::apply_slash(),
2416					Err(e) => {
2417						let no_pending_slash: DispatchResult = Err(Error::<T>::NothingToSlash.into());
2418						// This is an expected error. We add appropriate fees and continue withdrawal.
2419						if Err(e) == no_pending_slash {
2420							T::WeightInfo::apply_slash_fail()
2421						} else {
2422							// defensive: if we can't apply slash for some reason, we abort.
2423							return Err(Error::<T>::Defensive(DefensiveError::SlashNotApplied).into());
2424						}
2425					}
2426
2427				};
2428
2429			bonded_pool.ok_to_withdraw_unbonded_with(&caller, &member_account)?;
2430			let pool_account = bonded_pool.bonded_account();
2431
2432			// NOTE: must do this after we have done the `ok_to_withdraw_unbonded_other_with` check.
2433			let withdrawn_points = member.withdraw_unlocked(current_era);
2434			ensure!(!withdrawn_points.is_empty(), Error::<T>::CannotWithdrawAny);
2435
2436			// Before calculating the `balance_to_unbond`, we call withdraw unbonded to ensure the
2437			// `transferable_balance` is correct.
2438			let stash_killed = T::StakeAdapter::withdraw_unbonded(
2439				Pool::from(bonded_pool.bonded_account()),
2440				num_slashing_spans,
2441			)?;
2442
2443			// defensive-only: the depositor puts enough funds into the stash so that it will only
2444			// be destroyed when they are leaving.
2445			ensure!(
2446				!stash_killed || caller == bonded_pool.roles.depositor,
2447				Error::<T>::Defensive(DefensiveError::BondedStashKilledPrematurely)
2448			);
2449
2450			if stash_killed {
2451				// Maybe an extra consumer left on the pool account, if so, remove it.
2452				if frame_system::Pallet::<T>::consumers(&pool_account) == 1 {
2453					frame_system::Pallet::<T>::dec_consumers(&pool_account);
2454				}
2455
2456				// Note: This is not pretty, but we have to do this because of a bug where old pool
2457				// accounts might have had an extra consumer increment. We know at this point no
2458				// other pallet should depend on pool account so safe to do this.
2459				// Refer to following issues:
2460				// - https://github.com/paritytech/polkadot-sdk/issues/4440
2461				// - https://github.com/paritytech/polkadot-sdk/issues/2037
2462			}
2463
2464			let mut sum_unlocked_points: BalanceOf<T> = Zero::zero();
2465			let balance_to_unbond = withdrawn_points
2466				.iter()
2467				.fold(BalanceOf::<T>::zero(), |accumulator, (era, unlocked_points)| {
2468					sum_unlocked_points = sum_unlocked_points.saturating_add(*unlocked_points);
2469					if let Some(era_pool) = sub_pools.with_era.get_mut(era) {
2470						let balance_to_unbond = era_pool.dissolve(*unlocked_points);
2471						if era_pool.points.is_zero() {
2472							sub_pools.with_era.remove(era);
2473						}
2474						accumulator.saturating_add(balance_to_unbond)
2475					} else {
2476						// A pool does not belong to this era, so it must have been merged to the
2477						// era-less pool.
2478						accumulator.saturating_add(sub_pools.no_era.dissolve(*unlocked_points))
2479					}
2480				})
2481				// A call to this transaction may cause the pool's stash to get dusted. If this
2482				// happens before the last member has withdrawn, then all subsequent withdraws will
2483				// be 0. However the unbond pools do no get updated to reflect this. In the
2484				// aforementioned scenario, this check ensures we don't try to withdraw funds that
2485				// don't exist. This check is also defensive in cases where the unbond pool does not
2486				// update its balance (e.g. a bug in the slashing hook.) We gracefully proceed in
2487				// order to ensure members can leave the pool and it can be destroyed.
2488				.min(T::StakeAdapter::transferable_balance(
2489					Pool::from(bonded_pool.bonded_account()),
2490					Member::from(member_account.clone()),
2491				));
2492
2493			// this can fail if the pool uses `DelegateStake` strategy and the member delegation
2494			// is not claimed yet. See `Call::migrate_delegation()`.
2495			T::StakeAdapter::member_withdraw(
2496				Member::from(member_account.clone()),
2497				Pool::from(bonded_pool.bonded_account()),
2498				balance_to_unbond,
2499				num_slashing_spans,
2500			)?;
2501
2502			Self::deposit_event(Event::<T>::Withdrawn {
2503				member: member_account.clone(),
2504				pool_id: member.pool_id,
2505				points: sum_unlocked_points,
2506				balance: balance_to_unbond,
2507			});
2508
2509			let post_info_weight = if member.total_points().is_zero() {
2510				// remove any `ClaimPermission` associated with the member.
2511				ClaimPermissions::<T>::remove(&member_account);
2512
2513				// member being reaped.
2514				PoolMembers::<T>::remove(&member_account);
2515
2516				// Ensure any dangling delegation is withdrawn.
2517				let dangling_withdrawal = match T::StakeAdapter::member_delegation_balance(
2518					Member::from(member_account.clone()),
2519				) {
2520					Some(dangling_delegation) => {
2521						T::StakeAdapter::member_withdraw(
2522							Member::from(member_account.clone()),
2523							Pool::from(bonded_pool.bonded_account()),
2524							dangling_delegation,
2525							num_slashing_spans,
2526						)?;
2527						dangling_delegation
2528					},
2529					None => Zero::zero(),
2530				};
2531
2532				Self::deposit_event(Event::<T>::MemberRemoved {
2533					pool_id: member.pool_id,
2534					member: member_account.clone(),
2535					released_balance: dangling_withdrawal,
2536				});
2537
2538				if member_account == bonded_pool.roles.depositor {
2539					Pallet::<T>::dissolve_pool(bonded_pool);
2540					Weight::default()
2541				} else {
2542					bonded_pool.dec_members().put();
2543					SubPoolsStorage::<T>::insert(member.pool_id, sub_pools);
2544					T::WeightInfo::withdraw_unbonded_update(num_slashing_spans)
2545				}
2546			} else {
2547				// we certainly don't need to delete any pools, because no one is being removed.
2548				SubPoolsStorage::<T>::insert(member.pool_id, sub_pools);
2549				PoolMembers::<T>::insert(&member_account, member);
2550				T::WeightInfo::withdraw_unbonded_update(num_slashing_spans)
2551			};
2552
2553			Ok(Some(post_info_weight.saturating_add(slash_weight)).into())
2554		}
2555
2556		/// Create a new delegation pool.
2557		///
2558		/// # Arguments
2559		///
2560		/// * `amount` - The amount of funds to delegate to the pool. This also acts of a sort of
2561		///   deposit since the pools creator cannot fully unbond funds until the pool is being
2562		///   destroyed.
2563		/// * `index` - A disambiguation index for creating the account. Likely only useful when
2564		///   creating multiple pools in the same extrinsic.
2565		/// * `root` - The account to set as [`PoolRoles::root`].
2566		/// * `nominator` - The account to set as the [`PoolRoles::nominator`].
2567		/// * `bouncer` - The account to set as the [`PoolRoles::bouncer`].
2568		///
2569		/// # Note
2570		///
2571		/// In addition to `amount`, the caller will transfer the existential deposit; so the caller
2572		/// needs at have at least `amount + existential_deposit` transferable.
2573		#[pallet::call_index(6)]
2574		#[pallet::weight(T::WeightInfo::create())]
2575		pub fn create(
2576			origin: OriginFor<T>,
2577			#[pallet::compact] amount: BalanceOf<T>,
2578			root: AccountIdLookupOf<T>,
2579			nominator: AccountIdLookupOf<T>,
2580			bouncer: AccountIdLookupOf<T>,
2581		) -> DispatchResult {
2582			let depositor = ensure_signed(origin)?;
2583
2584			let pool_id = LastPoolId::<T>::try_mutate::<_, Error<T>, _>(|id| {
2585				*id = id.checked_add(1).ok_or(Error::<T>::OverflowRisk)?;
2586				Ok(*id)
2587			})?;
2588
2589			Self::do_create(depositor, amount, root, nominator, bouncer, pool_id)
2590		}
2591
2592		/// Create a new delegation pool with a previously used pool id
2593		///
2594		/// # Arguments
2595		///
2596		/// same as `create` with the inclusion of
2597		/// * `pool_id` - `A valid PoolId.
2598		#[pallet::call_index(7)]
2599		#[pallet::weight(T::WeightInfo::create())]
2600		pub fn create_with_pool_id(
2601			origin: OriginFor<T>,
2602			#[pallet::compact] amount: BalanceOf<T>,
2603			root: AccountIdLookupOf<T>,
2604			nominator: AccountIdLookupOf<T>,
2605			bouncer: AccountIdLookupOf<T>,
2606			pool_id: PoolId,
2607		) -> DispatchResult {
2608			let depositor = ensure_signed(origin)?;
2609
2610			ensure!(!BondedPools::<T>::contains_key(pool_id), Error::<T>::PoolIdInUse);
2611			ensure!(pool_id < LastPoolId::<T>::get(), Error::<T>::InvalidPoolId);
2612
2613			Self::do_create(depositor, amount, root, nominator, bouncer, pool_id)
2614		}
2615
2616		/// Nominate on behalf of the pool.
2617		///
2618		/// The dispatch origin of this call must be signed by the pool nominator or the pool
2619		/// root role.
2620		///
2621		/// This directly forwards the call to an implementation of `StakingInterface` (e.g.,
2622		/// `pallet-staking`) through [`Config::StakeAdapter`], on behalf of the bonded pool.
2623		///
2624		/// # Note
2625		///
2626		/// In addition to a `root` or `nominator` role of `origin`, the pool's depositor needs to
2627		/// have at least `depositor_min_bond` in the pool to start nominating.
2628		#[pallet::call_index(8)]
2629		#[pallet::weight(T::WeightInfo::nominate(validators.len() as u32))]
2630		pub fn nominate(
2631			origin: OriginFor<T>,
2632			pool_id: PoolId,
2633			validators: Vec<T::AccountId>,
2634		) -> DispatchResult {
2635			let who = ensure_signed(origin)?;
2636			let bonded_pool = BondedPool::<T>::get(pool_id).ok_or(Error::<T>::PoolNotFound)?;
2637			// ensure pool is not in an un-migrated state.
2638			ensure!(!Self::api_pool_needs_delegate_migration(pool_id), Error::<T>::NotMigrated);
2639			ensure!(bonded_pool.can_nominate(&who), Error::<T>::NotNominator);
2640
2641			let depositor_points = PoolMembers::<T>::get(&bonded_pool.roles.depositor)
2642				.ok_or(Error::<T>::PoolMemberNotFound)?
2643				.active_points();
2644
2645			ensure!(
2646				bonded_pool.points_to_balance(depositor_points) >= Self::depositor_min_bond(),
2647				Error::<T>::MinimumBondNotMet
2648			);
2649
2650			T::StakeAdapter::nominate(Pool::from(bonded_pool.bonded_account()), validators).map(
2651				|_| Self::deposit_event(Event::<T>::PoolNominationMade { pool_id, caller: who }),
2652			)
2653		}
2654
2655		/// Set a new state for the pool.
2656		///
2657		/// If a pool is already in the `Destroying` state, then under no condition can its state
2658		/// change again.
2659		///
2660		/// The dispatch origin of this call must be either:
2661		///
2662		/// 1. signed by the bouncer, or the root role of the pool,
2663		/// 2. if the pool conditions to be open are NOT met (as described by `ok_to_be_open`), and
2664		///    then the state of the pool can be permissionlessly changed to `Destroying`.
2665		#[pallet::call_index(9)]
2666		#[pallet::weight(T::WeightInfo::set_state())]
2667		pub fn set_state(
2668			origin: OriginFor<T>,
2669			pool_id: PoolId,
2670			state: PoolState,
2671		) -> DispatchResult {
2672			let who = ensure_signed(origin)?;
2673			let mut bonded_pool = BondedPool::<T>::get(pool_id).ok_or(Error::<T>::PoolNotFound)?;
2674			ensure!(bonded_pool.state != PoolState::Destroying, Error::<T>::CanNotChangeState);
2675			// ensure pool is not in an un-migrated state.
2676			ensure!(!Self::api_pool_needs_delegate_migration(pool_id), Error::<T>::NotMigrated);
2677
2678			if bonded_pool.can_toggle_state(&who) {
2679				bonded_pool.set_state(state);
2680			} else if bonded_pool.ok_to_be_open().is_err() && state == PoolState::Destroying {
2681				// If the pool has bad properties, then anyone can set it as destroying
2682				bonded_pool.set_state(PoolState::Destroying);
2683			} else {
2684				Err(Error::<T>::CanNotChangeState)?;
2685			}
2686
2687			bonded_pool.put();
2688
2689			Ok(())
2690		}
2691
2692		/// Set a new metadata for the pool.
2693		///
2694		/// The dispatch origin of this call must be signed by the bouncer, or the root role of the
2695		/// pool.
2696		#[pallet::call_index(10)]
2697		#[pallet::weight(T::WeightInfo::set_metadata(metadata.len() as u32))]
2698		pub fn set_metadata(
2699			origin: OriginFor<T>,
2700			pool_id: PoolId,
2701			metadata: Vec<u8>,
2702		) -> DispatchResult {
2703			let who = ensure_signed(origin)?;
2704			let metadata: BoundedVec<_, _> =
2705				metadata.try_into().map_err(|_| Error::<T>::MetadataExceedsMaxLen)?;
2706			ensure!(
2707				BondedPool::<T>::get(pool_id)
2708					.ok_or(Error::<T>::PoolNotFound)?
2709					.can_set_metadata(&who),
2710				Error::<T>::DoesNotHavePermission
2711			);
2712			// ensure pool is not in an un-migrated state.
2713			ensure!(!Self::api_pool_needs_delegate_migration(pool_id), Error::<T>::NotMigrated);
2714
2715			Metadata::<T>::mutate(pool_id, |pool_meta| *pool_meta = metadata);
2716
2717			Self::deposit_event(Event::<T>::MetadataUpdated { pool_id, caller: who });
2718
2719			Ok(())
2720		}
2721
2722		/// Update configurations for the nomination pools. The origin for this call must be
2723		/// [`Config::AdminOrigin`].
2724		///
2725		/// # Arguments
2726		///
2727		/// * `min_join_bond` - Set [`MinJoinBond`].
2728		/// * `min_create_bond` - Set [`MinCreateBond`].
2729		/// * `max_pools` - Set [`MaxPools`].
2730		/// * `max_members` - Set [`MaxPoolMembers`].
2731		/// * `max_members_per_pool` - Set [`MaxPoolMembersPerPool`].
2732		/// * `global_max_commission` - Set [`GlobalMaxCommission`].
2733		#[pallet::call_index(11)]
2734		#[pallet::weight(T::WeightInfo::set_configs())]
2735		pub fn set_configs(
2736			origin: OriginFor<T>,
2737			min_join_bond: ConfigOp<BalanceOf<T>>,
2738			min_create_bond: ConfigOp<BalanceOf<T>>,
2739			max_pools: ConfigOp<u32>,
2740			max_members: ConfigOp<u32>,
2741			max_members_per_pool: ConfigOp<u32>,
2742			global_max_commission: ConfigOp<Perbill>,
2743		) -> DispatchResult {
2744			T::AdminOrigin::ensure_origin(origin)?;
2745
2746			macro_rules! config_op_exp {
2747				($storage:ty, $op:ident) => {
2748					match $op {
2749						ConfigOp::Noop => (),
2750						ConfigOp::Set(v) => <$storage>::put(v),
2751						ConfigOp::Remove => <$storage>::kill(),
2752					}
2753				};
2754			}
2755
2756			config_op_exp!(MinJoinBond::<T>, min_join_bond);
2757			config_op_exp!(MinCreateBond::<T>, min_create_bond);
2758			config_op_exp!(MaxPools::<T>, max_pools);
2759			config_op_exp!(MaxPoolMembers::<T>, max_members);
2760			config_op_exp!(MaxPoolMembersPerPool::<T>, max_members_per_pool);
2761			config_op_exp!(GlobalMaxCommission::<T>, global_max_commission);
2762
2763			Self::deposit_event(Event::<T>::GlobalParamsUpdated {
2764				min_join_bond: MinJoinBond::<T>::get(),
2765				min_create_bond: MinCreateBond::<T>::get(),
2766				max_pools: MaxPools::<T>::get(),
2767				max_members: MaxPoolMembers::<T>::get(),
2768				max_members_per_pool: MaxPoolMembersPerPool::<T>::get(),
2769				global_max_commission: GlobalMaxCommission::<T>::get(),
2770			});
2771
2772			Ok(())
2773		}
2774
2775		/// Update the roles of the pool.
2776		///
2777		/// The root is the only entity that can change any of the roles, including itself,
2778		/// excluding the depositor, who can never change.
2779		///
2780		/// It emits an event, notifying UIs of the role change. This event is quite relevant to
2781		/// most pool members and they should be informed of changes to pool roles.
2782		#[pallet::call_index(12)]
2783		#[pallet::weight(T::WeightInfo::update_roles())]
2784		pub fn update_roles(
2785			origin: OriginFor<T>,
2786			pool_id: PoolId,
2787			new_root: ConfigOp<T::AccountId>,
2788			new_nominator: ConfigOp<T::AccountId>,
2789			new_bouncer: ConfigOp<T::AccountId>,
2790		) -> DispatchResult {
2791			let mut bonded_pool = match ensure_root(origin.clone()) {
2792				Ok(()) => BondedPool::<T>::get(pool_id).ok_or(Error::<T>::PoolNotFound)?,
2793				Err(sp_runtime::traits::BadOrigin) => {
2794					let who = ensure_signed(origin)?;
2795					let bonded_pool =
2796						BondedPool::<T>::get(pool_id).ok_or(Error::<T>::PoolNotFound)?;
2797					ensure!(bonded_pool.can_update_roles(&who), Error::<T>::DoesNotHavePermission);
2798					bonded_pool
2799				},
2800			};
2801
2802			// ensure pool is not in an un-migrated state.
2803			ensure!(!Self::api_pool_needs_delegate_migration(pool_id), Error::<T>::NotMigrated);
2804
2805			match new_root {
2806				ConfigOp::Noop => (),
2807				ConfigOp::Remove => bonded_pool.roles.root = None,
2808				ConfigOp::Set(v) => bonded_pool.roles.root = Some(v),
2809			};
2810			match new_nominator {
2811				ConfigOp::Noop => (),
2812				ConfigOp::Remove => bonded_pool.roles.nominator = None,
2813				ConfigOp::Set(v) => bonded_pool.roles.nominator = Some(v),
2814			};
2815			match new_bouncer {
2816				ConfigOp::Noop => (),
2817				ConfigOp::Remove => bonded_pool.roles.bouncer = None,
2818				ConfigOp::Set(v) => bonded_pool.roles.bouncer = Some(v),
2819			};
2820
2821			Self::deposit_event(Event::<T>::RolesUpdated {
2822				root: bonded_pool.roles.root.clone(),
2823				nominator: bonded_pool.roles.nominator.clone(),
2824				bouncer: bonded_pool.roles.bouncer.clone(),
2825			});
2826
2827			bonded_pool.put();
2828			Ok(())
2829		}
2830
2831		/// Chill on behalf of the pool.
2832		///
2833		/// The dispatch origin of this call can be signed by the pool nominator or the pool
2834		/// root role, same as [`Pallet::nominate`].
2835		///
2836		/// This directly forwards the call to an implementation of `StakingInterface` (e.g.,
2837		/// `pallet-staking`) through [`Config::StakeAdapter`], on behalf of the bonded pool.
2838		///
2839		/// Under certain conditions, this call can be dispatched permissionlessly (i.e. by any
2840		/// account).
2841		///
2842		/// # Conditions for a permissionless dispatch:
2843		/// * When pool depositor has less than `MinNominatorBond` staked, otherwise pool members
2844		///   are unable to unbond.
2845		///
2846		/// # Conditions for permissioned dispatch:
2847		/// * The caller is the pool's nominator or root.
2848		#[pallet::call_index(13)]
2849		#[pallet::weight(T::WeightInfo::chill())]
2850		pub fn chill(origin: OriginFor<T>, pool_id: PoolId) -> DispatchResult {
2851			let who = ensure_signed(origin)?;
2852			let bonded_pool = BondedPool::<T>::get(pool_id).ok_or(Error::<T>::PoolNotFound)?;
2853			// ensure pool is not in an un-migrated state.
2854			ensure!(!Self::api_pool_needs_delegate_migration(pool_id), Error::<T>::NotMigrated);
2855
2856			let depositor_points = PoolMembers::<T>::get(&bonded_pool.roles.depositor)
2857				.ok_or(Error::<T>::PoolMemberNotFound)?
2858				.active_points();
2859
2860			if bonded_pool.points_to_balance(depositor_points) >=
2861				T::StakeAdapter::minimum_nominator_bond()
2862			{
2863				ensure!(bonded_pool.can_nominate(&who), Error::<T>::NotNominator);
2864			}
2865
2866			T::StakeAdapter::chill(Pool::from(bonded_pool.bonded_account())).map(|_| {
2867				Self::deposit_event(Event::<T>::PoolNominatorChilled { pool_id, caller: who })
2868			})
2869		}
2870
2871		/// `origin` bonds funds from `extra` for some pool member `member` into their respective
2872		/// pools.
2873		///
2874		/// `origin` can bond extra funds from free balance or pending rewards when `origin ==
2875		/// other`.
2876		///
2877		/// In the case of `origin != other`, `origin` can only bond extra pending rewards of
2878		/// `other` members assuming set_claim_permission for the given member is
2879		/// `PermissionlessCompound` or `PermissionlessAll`.
2880		#[pallet::call_index(14)]
2881		#[pallet::weight(
2882			T::WeightInfo::bond_extra_transfer()
2883			.max(T::WeightInfo::bond_extra_other())
2884		)]
2885		pub fn bond_extra_other(
2886			origin: OriginFor<T>,
2887			member: AccountIdLookupOf<T>,
2888			extra: BondExtra<BalanceOf<T>>,
2889		) -> DispatchResult {
2890			let who = ensure_signed(origin)?;
2891			let member_account = T::Lookup::lookup(member)?;
2892			// ensure member is not in an un-migrated state.
2893			ensure!(
2894				!Self::api_member_needs_delegate_migration(member_account.clone()),
2895				Error::<T>::NotMigrated
2896			);
2897
2898			Self::do_bond_extra(who, member_account, extra)
2899		}
2900
2901		/// Allows a pool member to set a claim permission to allow or disallow permissionless
2902		/// bonding and withdrawing.
2903		///
2904		/// # Arguments
2905		///
2906		/// * `origin` - Member of a pool.
2907		/// * `permission` - The permission to be applied.
2908		#[pallet::call_index(15)]
2909		#[pallet::weight(T::DbWeight::get().reads_writes(1, 1))]
2910		pub fn set_claim_permission(
2911			origin: OriginFor<T>,
2912			permission: ClaimPermission,
2913		) -> DispatchResult {
2914			let who = ensure_signed(origin)?;
2915			ensure!(PoolMembers::<T>::contains_key(&who), Error::<T>::PoolMemberNotFound);
2916
2917			// ensure member is not in an un-migrated state.
2918			ensure!(
2919				!Self::api_member_needs_delegate_migration(who.clone()),
2920				Error::<T>::NotMigrated
2921			);
2922
2923			ClaimPermissions::<T>::mutate(who.clone(), |source| {
2924				*source = permission;
2925			});
2926
2927			Self::deposit_event(Event::<T>::MemberClaimPermissionUpdated {
2928				member: who,
2929				permission,
2930			});
2931
2932			Ok(())
2933		}
2934
2935		/// `origin` can claim payouts on some pool member `other`'s behalf.
2936		///
2937		/// Pool member `other` must have a `PermissionlessWithdraw` or `PermissionlessAll` claim
2938		/// permission for this call to be successful.
2939		#[pallet::call_index(16)]
2940		#[pallet::weight(T::WeightInfo::claim_payout())]
2941		pub fn claim_payout_other(origin: OriginFor<T>, other: T::AccountId) -> DispatchResult {
2942			let signer = ensure_signed(origin)?;
2943			// ensure member is not in an un-migrated state.
2944			ensure!(
2945				!Self::api_member_needs_delegate_migration(other.clone()),
2946				Error::<T>::NotMigrated
2947			);
2948
2949			Self::do_claim_payout(signer, other)
2950		}
2951
2952		/// Set the commission of a pool.
2953		//
2954		/// Both a commission percentage and a commission payee must be provided in the `current`
2955		/// tuple. Where a `current` of `None` is provided, any current commission will be removed.
2956		///
2957		/// - If a `None` is supplied to `new_commission`, existing commission will be removed.
2958		#[pallet::call_index(17)]
2959		#[pallet::weight(T::WeightInfo::set_commission())]
2960		pub fn set_commission(
2961			origin: OriginFor<T>,
2962			pool_id: PoolId,
2963			new_commission: Option<(Perbill, T::AccountId)>,
2964		) -> DispatchResult {
2965			let who = ensure_signed(origin)?;
2966			let mut bonded_pool = BondedPool::<T>::get(pool_id).ok_or(Error::<T>::PoolNotFound)?;
2967			// ensure pool is not in an un-migrated state.
2968			ensure!(!Self::api_pool_needs_delegate_migration(pool_id), Error::<T>::NotMigrated);
2969
2970			ensure!(bonded_pool.can_manage_commission(&who), Error::<T>::DoesNotHavePermission);
2971
2972			let mut reward_pool = RewardPools::<T>::get(pool_id)
2973				.defensive_ok_or::<Error<T>>(DefensiveError::RewardPoolNotFound.into())?;
2974			// IMPORTANT: make sure that everything up to this point is using the current commission
2975			// before it updates. Note that `try_update_current` could still fail at this point.
2976			reward_pool.update_records(
2977				pool_id,
2978				bonded_pool.points,
2979				bonded_pool.commission.current(),
2980			)?;
2981			RewardPools::insert(pool_id, reward_pool);
2982
2983			bonded_pool.commission.try_update_current(&new_commission)?;
2984			bonded_pool.put();
2985			Self::deposit_event(Event::<T>::PoolCommissionUpdated {
2986				pool_id,
2987				current: new_commission,
2988			});
2989			Ok(())
2990		}
2991
2992		/// Set the maximum commission of a pool.
2993		///
2994		/// - Initial max can be set to any `Perbill`, and only smaller values thereafter.
2995		/// - Current commission will be lowered in the event it is higher than a new max
2996		///   commission.
2997		#[pallet::call_index(18)]
2998		#[pallet::weight(T::WeightInfo::set_commission_max())]
2999		pub fn set_commission_max(
3000			origin: OriginFor<T>,
3001			pool_id: PoolId,
3002			max_commission: Perbill,
3003		) -> DispatchResult {
3004			let who = ensure_signed(origin)?;
3005			let mut bonded_pool = BondedPool::<T>::get(pool_id).ok_or(Error::<T>::PoolNotFound)?;
3006			// ensure pool is not in an un-migrated state.
3007			ensure!(!Self::api_pool_needs_delegate_migration(pool_id), Error::<T>::NotMigrated);
3008
3009			ensure!(bonded_pool.can_manage_commission(&who), Error::<T>::DoesNotHavePermission);
3010
3011			bonded_pool.commission.try_update_max(pool_id, max_commission)?;
3012			bonded_pool.put();
3013
3014			Self::deposit_event(Event::<T>::PoolMaxCommissionUpdated { pool_id, max_commission });
3015			Ok(())
3016		}
3017
3018		/// Set the commission change rate for a pool.
3019		///
3020		/// Initial change rate is not bounded, whereas subsequent updates can only be more
3021		/// restrictive than the current.
3022		#[pallet::call_index(19)]
3023		#[pallet::weight(T::WeightInfo::set_commission_change_rate())]
3024		pub fn set_commission_change_rate(
3025			origin: OriginFor<T>,
3026			pool_id: PoolId,
3027			change_rate: CommissionChangeRate<BlockNumberFor<T>>,
3028		) -> DispatchResult {
3029			let who = ensure_signed(origin)?;
3030			let mut bonded_pool = BondedPool::<T>::get(pool_id).ok_or(Error::<T>::PoolNotFound)?;
3031			// ensure pool is not in an un-migrated state.
3032			ensure!(!Self::api_pool_needs_delegate_migration(pool_id), Error::<T>::NotMigrated);
3033			ensure!(bonded_pool.can_manage_commission(&who), Error::<T>::DoesNotHavePermission);
3034
3035			bonded_pool.commission.try_update_change_rate(change_rate)?;
3036			bonded_pool.put();
3037
3038			Self::deposit_event(Event::<T>::PoolCommissionChangeRateUpdated {
3039				pool_id,
3040				change_rate,
3041			});
3042			Ok(())
3043		}
3044
3045		/// Claim pending commission.
3046		///
3047		/// The `root` role of the pool is _always_ allowed to claim the pool's commission.
3048		///
3049		/// If the pool has set `CommissionClaimPermission::Permissionless`, then any account can
3050		/// trigger the process of claiming the pool's commission.
3051		///
3052		/// If the pool has set its `CommissionClaimPermission` to `Account(acc)`, then only
3053		/// accounts
3054		/// * `acc`, and
3055		/// * the pool's root account
3056		///
3057		/// may call this extrinsic on behalf of the pool.
3058		///
3059		/// Pending commissions are paid out and added to the total claimed commission.
3060		/// The total pending commission is reset to zero.
3061		#[pallet::call_index(20)]
3062		#[pallet::weight(T::WeightInfo::claim_commission())]
3063		pub fn claim_commission(origin: OriginFor<T>, pool_id: PoolId) -> DispatchResult {
3064			let who = ensure_signed(origin)?;
3065			// ensure pool is not in an un-migrated state.
3066			ensure!(!Self::api_pool_needs_delegate_migration(pool_id), Error::<T>::NotMigrated);
3067
3068			Self::do_claim_commission(who, pool_id)
3069		}
3070
3071		/// Top up the deficit or withdraw the excess ED from the pool.
3072		///
3073		/// When a pool is created, the pool depositor transfers ED to the reward account of the
3074		/// pool. ED is subject to change and over time, the deposit in the reward account may be
3075		/// insufficient to cover the ED deficit of the pool or vice-versa where there is excess
3076		/// deposit to the pool. This call allows anyone to adjust the ED deposit of the
3077		/// pool by either topping up the deficit or claiming the excess.
3078		#[pallet::call_index(21)]
3079		#[pallet::weight(T::WeightInfo::adjust_pool_deposit())]
3080		pub fn adjust_pool_deposit(origin: OriginFor<T>, pool_id: PoolId) -> DispatchResult {
3081			let who = ensure_signed(origin)?;
3082			// ensure pool is not in an un-migrated state.
3083			ensure!(!Self::api_pool_needs_delegate_migration(pool_id), Error::<T>::NotMigrated);
3084
3085			Self::do_adjust_pool_deposit(who, pool_id)
3086		}
3087
3088		/// Set or remove a pool's commission claim permission.
3089		///
3090		/// Determines who can claim the pool's pending commission. Only the `Root` role of the pool
3091		/// is able to configure commission claim permissions.
3092		#[pallet::call_index(22)]
3093		#[pallet::weight(T::WeightInfo::set_commission_claim_permission())]
3094		pub fn set_commission_claim_permission(
3095			origin: OriginFor<T>,
3096			pool_id: PoolId,
3097			permission: Option<CommissionClaimPermission<T::AccountId>>,
3098		) -> DispatchResult {
3099			let who = ensure_signed(origin)?;
3100			let mut bonded_pool = BondedPool::<T>::get(pool_id).ok_or(Error::<T>::PoolNotFound)?;
3101			// ensure pool is not in an un-migrated state.
3102			ensure!(!Self::api_pool_needs_delegate_migration(pool_id), Error::<T>::NotMigrated);
3103			ensure!(bonded_pool.can_manage_commission(&who), Error::<T>::DoesNotHavePermission);
3104
3105			bonded_pool.commission.claim_permission = permission.clone();
3106			bonded_pool.put();
3107
3108			Self::deposit_event(Event::<T>::PoolCommissionClaimPermissionUpdated {
3109				pool_id,
3110				permission,
3111			});
3112
3113			Ok(())
3114		}
3115
3116		/// Apply a pending slash on a member.
3117		///
3118		/// Fails unless [`crate::pallet::Config::StakeAdapter`] is of strategy type:
3119		/// [`adapter::StakeStrategyType::Delegate`].
3120		///
3121		/// The pending slash amount of the member must be equal or more than `ExistentialDeposit`.
3122		/// This call can be dispatched permissionlessly (i.e. by any account). If the execution
3123		/// is successful, fee is refunded and caller may be rewarded with a part of the slash
3124		/// based on the [`crate::pallet::Config::StakeAdapter`] configuration.
3125		#[pallet::call_index(23)]
3126		#[pallet::weight(T::WeightInfo::apply_slash())]
3127		pub fn apply_slash(
3128			origin: OriginFor<T>,
3129			member_account: AccountIdLookupOf<T>,
3130		) -> DispatchResultWithPostInfo {
3131			ensure!(
3132				T::StakeAdapter::strategy_type() == adapter::StakeStrategyType::Delegate,
3133				Error::<T>::NotSupported
3134			);
3135
3136			let who = ensure_signed(origin)?;
3137			let member_account = T::Lookup::lookup(member_account)?;
3138			Self::do_apply_slash(&member_account, Some(who), true)?;
3139
3140			// If successful, refund the fees.
3141			Ok(Pays::No.into())
3142		}
3143
3144		/// Migrates delegated funds from the pool account to the `member_account`.
3145		///
3146		/// Fails unless [`crate::pallet::Config::StakeAdapter`] is of strategy type:
3147		/// [`adapter::StakeStrategyType::Delegate`].
3148		///
3149		/// This is a permission-less call and refunds any fee if claim is successful.
3150		///
3151		/// If the pool has migrated to delegation based staking, the staked tokens of pool members
3152		/// can be moved and held in their own account. See [`adapter::DelegateStake`]
3153		#[pallet::call_index(24)]
3154		#[pallet::weight(T::WeightInfo::migrate_delegation())]
3155		pub fn migrate_delegation(
3156			origin: OriginFor<T>,
3157			member_account: AccountIdLookupOf<T>,
3158		) -> DispatchResultWithPostInfo {
3159			let _caller = ensure_signed(origin)?;
3160
3161			// ensure `DelegateStake` strategy is used.
3162			ensure!(
3163				T::StakeAdapter::strategy_type() == adapter::StakeStrategyType::Delegate,
3164				Error::<T>::NotSupported
3165			);
3166
3167			// ensure member is not restricted from joining the pool.
3168			let member_account = T::Lookup::lookup(member_account)?;
3169			ensure!(!T::Filter::contains(&member_account), Error::<T>::Restricted);
3170
3171			let member =
3172				PoolMembers::<T>::get(&member_account).ok_or(Error::<T>::PoolMemberNotFound)?;
3173
3174			// ensure pool is migrated.
3175			ensure!(
3176				T::StakeAdapter::pool_strategy(Pool::from(Self::generate_bonded_account(
3177					member.pool_id
3178				))) == adapter::StakeStrategyType::Delegate,
3179				Error::<T>::NotMigrated
3180			);
3181
3182			let pool_contribution = member.total_balance();
3183			// ensure the pool contribution is greater than the existential deposit otherwise we
3184			// cannot transfer funds to member account.
3185			ensure!(
3186				pool_contribution >= T::Currency::minimum_balance(),
3187				Error::<T>::MinimumBondNotMet
3188			);
3189
3190			let delegation =
3191				T::StakeAdapter::member_delegation_balance(Member::from(member_account.clone()));
3192			// delegation should not exist.
3193			ensure!(delegation.is_none(), Error::<T>::AlreadyMigrated);
3194
3195			T::StakeAdapter::migrate_delegation(
3196				Pool::from(Pallet::<T>::generate_bonded_account(member.pool_id)),
3197				Member::from(member_account),
3198				pool_contribution,
3199			)?;
3200
3201			// if successful, we refund the fee.
3202			Ok(Pays::No.into())
3203		}
3204
3205		/// Migrate pool from [`adapter::StakeStrategyType::Transfer`] to
3206		/// [`adapter::StakeStrategyType::Delegate`].
3207		///
3208		/// Fails unless [`crate::pallet::Config::StakeAdapter`] is of strategy type:
3209		/// [`adapter::StakeStrategyType::Delegate`].
3210		///
3211		/// This call can be dispatched permissionlessly, and refunds any fee if successful.
3212		///
3213		/// If the pool has already migrated to delegation based staking, this call will fail.
3214		#[pallet::call_index(25)]
3215		#[pallet::weight(T::WeightInfo::pool_migrate())]
3216		pub fn migrate_pool_to_delegate_stake(
3217			origin: OriginFor<T>,
3218			pool_id: PoolId,
3219		) -> DispatchResultWithPostInfo {
3220			// gate this call to be called only if `DelegateStake` strategy is used.
3221			ensure!(
3222				T::StakeAdapter::strategy_type() == adapter::StakeStrategyType::Delegate,
3223				Error::<T>::NotSupported
3224			);
3225
3226			let _caller = ensure_signed(origin)?;
3227			// ensure pool exists.
3228			let bonded_pool = BondedPool::<T>::get(pool_id).ok_or(Error::<T>::PoolNotFound)?;
3229			ensure!(
3230				T::StakeAdapter::pool_strategy(Pool::from(bonded_pool.bonded_account())) ==
3231					adapter::StakeStrategyType::Transfer,
3232				Error::<T>::AlreadyMigrated
3233			);
3234
3235			Self::migrate_to_delegate_stake(pool_id)?;
3236			Ok(Pays::No.into())
3237		}
3238	}
3239
3240	#[pallet::hooks]
3241	impl<T: Config> Hooks<SystemBlockNumberFor<T>> for Pallet<T> {
3242		#[cfg(feature = "try-runtime")]
3243		fn try_state(_n: SystemBlockNumberFor<T>) -> Result<(), TryRuntimeError> {
3244			Self::do_try_state(u8::MAX)
3245		}
3246
3247		fn integrity_test() {
3248			assert!(
3249				T::MaxPointsToBalance::get() > 0,
3250				"Minimum points to balance ratio must be greater than 0"
3251			);
3252			assert!(
3253				T::StakeAdapter::bonding_duration() < TotalUnbondingPools::<T>::get(),
3254				"There must be more unbonding pools then the bonding duration /
3255				so a slash can be applied to relevant unbonding pools. (We assume /
3256				the bonding duration > slash deffer duration.",
3257			);
3258		}
3259	}
3260}
3261
3262impl<T: Config> Pallet<T> {
3263	/// The amount of bond that MUST REMAIN IN BONDED in ALL POOLS.
3264	///
3265	/// It is the responsibility of the depositor to put these funds into the pool initially. Upon
3266	/// unbond, they can never unbond to a value below this amount.
3267	///
3268	/// It is essentially `max { MinNominatorBond, MinCreateBond, MinJoinBond }`, where the former
3269	/// is coming from the staking pallet and the latter two are configured in this pallet.
3270	pub fn depositor_min_bond() -> BalanceOf<T> {
3271		T::StakeAdapter::minimum_nominator_bond()
3272			.max(MinCreateBond::<T>::get())
3273			.max(MinJoinBond::<T>::get())
3274			.max(T::Currency::minimum_balance())
3275	}
3276	/// Remove everything related to the given bonded pool.
3277	///
3278	/// Metadata and all of the sub-pools are also deleted. All accounts are dusted and the leftover
3279	/// of the reward account is returned to the depositor.
3280	pub fn dissolve_pool(bonded_pool: BondedPool<T>) {
3281		let reward_account = bonded_pool.reward_account();
3282		let bonded_account = bonded_pool.bonded_account();
3283
3284		ReversePoolIdLookup::<T>::remove(&bonded_account);
3285		RewardPools::<T>::remove(bonded_pool.id);
3286		SubPoolsStorage::<T>::remove(bonded_pool.id);
3287
3288		// remove the ED restriction from the pool reward account.
3289		let _ = Self::unfreeze_pool_deposit(&bonded_pool.reward_account()).defensive();
3290
3291		// Kill accounts from storage by making their balance go below ED. We assume that the
3292		// accounts have no references that would prevent destruction once we get to this point. We
3293		// don't work with the system pallet directly, but
3294		// 1. we drain the reward account and kill it. This account should never have any extra
3295		// consumers anyway.
3296		// 2. the bonded account should become a 'killed stash' in the staking system, and all of
3297		//    its consumers removed.
3298		defensive_assert!(
3299			frame_system::Pallet::<T>::consumers(&reward_account) == 0,
3300			"reward account of dissolving pool should have no consumers"
3301		);
3302		defensive_assert!(
3303			frame_system::Pallet::<T>::consumers(&bonded_account) == 0,
3304			"bonded account of dissolving pool should have no consumers"
3305		);
3306		defensive_assert!(
3307			T::StakeAdapter::total_stake(Pool::from(bonded_pool.bonded_account())) == Zero::zero(),
3308			"dissolving pool should not have any stake in the staking pallet"
3309		);
3310
3311		// This shouldn't fail, but if it does we don't really care. Remaining balance can consist
3312		// of unclaimed pending commission, erroneous transfers to the reward account, etc.
3313		let reward_pool_remaining = T::Currency::reducible_balance(
3314			&reward_account,
3315			Preservation::Expendable,
3316			Fortitude::Polite,
3317		);
3318		let _ = T::Currency::transfer(
3319			&reward_account,
3320			&bonded_pool.roles.depositor,
3321			reward_pool_remaining,
3322			Preservation::Expendable,
3323		);
3324
3325		defensive_assert!(
3326			T::Currency::total_balance(&reward_account) == Zero::zero(),
3327			"could not transfer all amount to depositor while dissolving pool"
3328		);
3329		// NOTE: Defensively force set balance to zero.
3330		T::Currency::set_balance(&reward_account, Zero::zero());
3331
3332		// dissolve pool account.
3333		let _ = T::StakeAdapter::dissolve(Pool::from(bonded_account)).defensive();
3334
3335		Self::deposit_event(Event::<T>::Destroyed { pool_id: bonded_pool.id });
3336		// Remove bonded pool metadata.
3337		Metadata::<T>::remove(bonded_pool.id);
3338
3339		bonded_pool.remove();
3340	}
3341
3342	/// Create the main, bonded account of a pool with the given id.
3343	pub fn generate_bonded_account(id: PoolId) -> T::AccountId {
3344		T::PalletId::get().into_sub_account_truncating((AccountType::Bonded, id))
3345	}
3346
3347	fn migrate_to_delegate_stake(id: PoolId) -> DispatchResult {
3348		T::StakeAdapter::migrate_nominator_to_agent(
3349			Pool::from(Self::generate_bonded_account(id)),
3350			&Self::generate_reward_account(id),
3351		)
3352	}
3353
3354	/// Create the reward account of a pool with the given id.
3355	pub fn generate_reward_account(id: PoolId) -> T::AccountId {
3356		// NOTE: in order to have a distinction in the test account id type (u128), we put
3357		// account_type first so it does not get truncated out.
3358		T::PalletId::get().into_sub_account_truncating((AccountType::Reward, id))
3359	}
3360
3361	/// Get the member with their associated bonded and reward pool.
3362	fn get_member_with_pools(
3363		who: &T::AccountId,
3364	) -> Result<(PoolMember<T>, BondedPool<T>, RewardPool<T>), Error<T>> {
3365		let member = PoolMembers::<T>::get(who).ok_or(Error::<T>::PoolMemberNotFound)?;
3366		let bonded_pool =
3367			BondedPool::<T>::get(member.pool_id).defensive_ok_or(DefensiveError::PoolNotFound)?;
3368		let reward_pool =
3369			RewardPools::<T>::get(member.pool_id).defensive_ok_or(DefensiveError::PoolNotFound)?;
3370		Ok((member, bonded_pool, reward_pool))
3371	}
3372
3373	/// Persist the member with their associated bonded and reward pool into storage, consuming
3374	/// all of them.
3375	fn put_member_with_pools(
3376		member_account: &T::AccountId,
3377		member: PoolMember<T>,
3378		bonded_pool: BondedPool<T>,
3379		reward_pool: RewardPool<T>,
3380	) {
3381		// The pool id of a member cannot change in any case, so we use it to make sure
3382		// `member_account` is the right one.
3383		debug_assert_eq!(PoolMembers::<T>::get(member_account).unwrap().pool_id, member.pool_id);
3384		debug_assert_eq!(member.pool_id, bonded_pool.id);
3385
3386		bonded_pool.put();
3387		RewardPools::insert(member.pool_id, reward_pool);
3388		PoolMembers::<T>::insert(member_account, member);
3389	}
3390
3391	/// Calculate the equivalent point of `new_funds` in a pool with `current_balance` and
3392	/// `current_points`.
3393	fn balance_to_point(
3394		current_balance: BalanceOf<T>,
3395		current_points: BalanceOf<T>,
3396		new_funds: BalanceOf<T>,
3397	) -> BalanceOf<T> {
3398		let u256 = T::BalanceToU256::convert;
3399		let balance = T::U256ToBalance::convert;
3400		match (current_balance.is_zero(), current_points.is_zero()) {
3401			(_, true) => new_funds.saturating_mul(POINTS_TO_BALANCE_INIT_RATIO.into()),
3402			(true, false) => {
3403				// The pool was totally slashed.
3404				// This is the equivalent of `(current_points / 1) * new_funds`.
3405				new_funds.saturating_mul(current_points)
3406			},
3407			(false, false) => {
3408				// Equivalent to (current_points / current_balance) * new_funds
3409				balance(
3410					u256(current_points)
3411						.saturating_mul(u256(new_funds))
3412						// We check for zero above
3413						.div(u256(current_balance)),
3414				)
3415			},
3416		}
3417	}
3418
3419	/// Calculate the equivalent balance of `points` in a pool with `current_balance` and
3420	/// `current_points`.
3421	fn point_to_balance(
3422		current_balance: BalanceOf<T>,
3423		current_points: BalanceOf<T>,
3424		points: BalanceOf<T>,
3425	) -> BalanceOf<T> {
3426		let u256 = T::BalanceToU256::convert;
3427		let balance = T::U256ToBalance::convert;
3428		if current_balance.is_zero() || current_points.is_zero() || points.is_zero() {
3429			// There is nothing to unbond
3430			return Zero::zero()
3431		}
3432
3433		// Equivalent of (current_balance / current_points) * points
3434		balance(
3435			u256(current_balance)
3436				.saturating_mul(u256(points))
3437				// We check for zero above
3438				.div(u256(current_points)),
3439		)
3440	}
3441
3442	/// If the member has some rewards, transfer a payout from the reward pool to the member.
3443	// Emits events and potentially modifies pool state if any arithmetic saturates, but does
3444	// not persist any of the mutable inputs to storage.
3445	fn do_reward_payout(
3446		member_account: &T::AccountId,
3447		member: &mut PoolMember<T>,
3448		bonded_pool: &mut BondedPool<T>,
3449		reward_pool: &mut RewardPool<T>,
3450	) -> Result<BalanceOf<T>, DispatchError> {
3451		debug_assert_eq!(member.pool_id, bonded_pool.id);
3452		debug_assert_eq!(&mut PoolMembers::<T>::get(member_account).unwrap(), member);
3453
3454		// a member who has no skin in the game anymore cannot claim any rewards.
3455		ensure!(!member.active_points().is_zero(), Error::<T>::FullyUnbonding);
3456
3457		let (current_reward_counter, _) = reward_pool.current_reward_counter(
3458			bonded_pool.id,
3459			bonded_pool.points,
3460			bonded_pool.commission.current(),
3461		)?;
3462
3463		// Determine the pending rewards. In scenarios where commission is 100%, `pending_rewards`
3464		// will be zero.
3465		let pending_rewards = member.pending_rewards(current_reward_counter)?;
3466		if pending_rewards.is_zero() {
3467			return Ok(pending_rewards)
3468		}
3469
3470		// IFF the reward is non-zero alter the member and reward pool info.
3471		member.last_recorded_reward_counter = current_reward_counter;
3472		reward_pool.register_claimed_reward(pending_rewards);
3473
3474		T::Currency::transfer(
3475			&bonded_pool.reward_account(),
3476			member_account,
3477			pending_rewards,
3478			// defensive: the depositor has put existential deposit into the pool and it stays
3479			// untouched, reward account shall not die.
3480			Preservation::Preserve,
3481		)?;
3482
3483		Self::deposit_event(Event::<T>::PaidOut {
3484			member: member_account.clone(),
3485			pool_id: member.pool_id,
3486			payout: pending_rewards,
3487		});
3488		Ok(pending_rewards)
3489	}
3490
3491	fn do_create(
3492		who: T::AccountId,
3493		amount: BalanceOf<T>,
3494		root: AccountIdLookupOf<T>,
3495		nominator: AccountIdLookupOf<T>,
3496		bouncer: AccountIdLookupOf<T>,
3497		pool_id: PoolId,
3498	) -> DispatchResult {
3499		// ensure depositor is not restricted from joining the pool.
3500		ensure!(!T::Filter::contains(&who), Error::<T>::Restricted);
3501
3502		let root = T::Lookup::lookup(root)?;
3503		let nominator = T::Lookup::lookup(nominator)?;
3504		let bouncer = T::Lookup::lookup(bouncer)?;
3505
3506		ensure!(amount >= Pallet::<T>::depositor_min_bond(), Error::<T>::MinimumBondNotMet);
3507		ensure!(
3508			MaxPools::<T>::get().map_or(true, |max_pools| BondedPools::<T>::count() < max_pools),
3509			Error::<T>::MaxPools
3510		);
3511		ensure!(!PoolMembers::<T>::contains_key(&who), Error::<T>::AccountBelongsToOtherPool);
3512		let mut bonded_pool = BondedPool::<T>::new(
3513			pool_id,
3514			PoolRoles {
3515				root: Some(root),
3516				nominator: Some(nominator),
3517				bouncer: Some(bouncer),
3518				depositor: who.clone(),
3519			},
3520		);
3521
3522		bonded_pool.try_inc_members()?;
3523		let points = bonded_pool.try_bond_funds(&who, amount, BondType::Create)?;
3524
3525		// Transfer the minimum balance for the reward account.
3526		T::Currency::transfer(
3527			&who,
3528			&bonded_pool.reward_account(),
3529			T::Currency::minimum_balance(),
3530			Preservation::Expendable,
3531		)?;
3532
3533		// Restrict reward account balance from going below ED.
3534		Self::freeze_pool_deposit(&bonded_pool.reward_account())?;
3535
3536		PoolMembers::<T>::insert(
3537			who.clone(),
3538			PoolMember::<T> {
3539				pool_id,
3540				points,
3541				last_recorded_reward_counter: Zero::zero(),
3542				unbonding_eras: Default::default(),
3543			},
3544		);
3545		RewardPools::<T>::insert(
3546			pool_id,
3547			RewardPool::<T> {
3548				last_recorded_reward_counter: Zero::zero(),
3549				last_recorded_total_payouts: Zero::zero(),
3550				total_rewards_claimed: Zero::zero(),
3551				total_commission_pending: Zero::zero(),
3552				total_commission_claimed: Zero::zero(),
3553			},
3554		);
3555		ReversePoolIdLookup::<T>::insert(bonded_pool.bonded_account(), pool_id);
3556
3557		Self::deposit_event(Event::<T>::Created { depositor: who.clone(), pool_id });
3558
3559		Self::deposit_event(Event::<T>::Bonded {
3560			member: who,
3561			pool_id,
3562			bonded: amount,
3563			joined: true,
3564		});
3565		bonded_pool.put();
3566
3567		Ok(())
3568	}
3569
3570	fn do_bond_extra(
3571		signer: T::AccountId,
3572		member_account: T::AccountId,
3573		extra: BondExtra<BalanceOf<T>>,
3574	) -> DispatchResult {
3575		// ensure account is not restricted from joining the pool.
3576		ensure!(!T::Filter::contains(&member_account), Error::<T>::Restricted);
3577
3578		if signer != member_account {
3579			ensure!(
3580				ClaimPermissions::<T>::get(&member_account).can_bond_extra(),
3581				Error::<T>::DoesNotHavePermission
3582			);
3583			ensure!(extra == BondExtra::Rewards, Error::<T>::BondExtraRestricted);
3584		}
3585
3586		let (mut member, mut bonded_pool, mut reward_pool) =
3587			Self::get_member_with_pools(&member_account)?;
3588
3589		// payout related stuff: we must claim the payouts, and updated recorded payout data
3590		// before updating the bonded pool points, similar to that of `join` transaction.
3591		reward_pool.update_records(
3592			bonded_pool.id,
3593			bonded_pool.points,
3594			bonded_pool.commission.current(),
3595		)?;
3596		let claimed = Self::do_reward_payout(
3597			&member_account,
3598			&mut member,
3599			&mut bonded_pool,
3600			&mut reward_pool,
3601		)?;
3602
3603		let (points_issued, bonded) = match extra {
3604			BondExtra::FreeBalance(amount) =>
3605				(bonded_pool.try_bond_funds(&member_account, amount, BondType::Extra)?, amount),
3606			BondExtra::Rewards =>
3607				(bonded_pool.try_bond_funds(&member_account, claimed, BondType::Extra)?, claimed),
3608		};
3609
3610		bonded_pool.ok_to_be_open()?;
3611		member.points =
3612			member.points.checked_add(&points_issued).ok_or(Error::<T>::OverflowRisk)?;
3613
3614		Self::deposit_event(Event::<T>::Bonded {
3615			member: member_account.clone(),
3616			pool_id: member.pool_id,
3617			bonded,
3618			joined: false,
3619		});
3620		Self::put_member_with_pools(&member_account, member, bonded_pool, reward_pool);
3621
3622		Ok(())
3623	}
3624
3625	fn do_claim_commission(who: T::AccountId, pool_id: PoolId) -> DispatchResult {
3626		let bonded_pool = BondedPool::<T>::get(pool_id).ok_or(Error::<T>::PoolNotFound)?;
3627		ensure!(bonded_pool.can_claim_commission(&who), Error::<T>::DoesNotHavePermission);
3628
3629		let mut reward_pool = RewardPools::<T>::get(pool_id)
3630			.defensive_ok_or::<Error<T>>(DefensiveError::RewardPoolNotFound.into())?;
3631
3632		// IMPORTANT: ensure newly pending commission not yet processed is added to
3633		// `total_commission_pending`.
3634		reward_pool.update_records(
3635			pool_id,
3636			bonded_pool.points,
3637			bonded_pool.commission.current(),
3638		)?;
3639
3640		let commission = reward_pool.total_commission_pending;
3641		ensure!(!commission.is_zero(), Error::<T>::NoPendingCommission);
3642
3643		let payee = bonded_pool
3644			.commission
3645			.current
3646			.as_ref()
3647			.map(|(_, p)| p.clone())
3648			.ok_or(Error::<T>::NoCommissionCurrentSet)?;
3649
3650		// Payout claimed commission.
3651		T::Currency::transfer(
3652			&bonded_pool.reward_account(),
3653			&payee,
3654			commission,
3655			Preservation::Preserve,
3656		)?;
3657
3658		// Add pending commission to total claimed counter.
3659		reward_pool.total_commission_claimed =
3660			reward_pool.total_commission_claimed.saturating_add(commission);
3661		// Reset total pending commission counter to zero.
3662		reward_pool.total_commission_pending = Zero::zero();
3663		RewardPools::<T>::insert(pool_id, reward_pool);
3664
3665		Self::deposit_event(Event::<T>::PoolCommissionClaimed { pool_id, commission });
3666		Ok(())
3667	}
3668
3669	pub(crate) fn do_claim_payout(
3670		signer: T::AccountId,
3671		member_account: T::AccountId,
3672	) -> DispatchResult {
3673		if signer != member_account {
3674			ensure!(
3675				ClaimPermissions::<T>::get(&member_account).can_claim_payout(),
3676				Error::<T>::DoesNotHavePermission
3677			);
3678		}
3679		let (mut member, mut bonded_pool, mut reward_pool) =
3680			Self::get_member_with_pools(&member_account)?;
3681
3682		let _ = Self::do_reward_payout(
3683			&member_account,
3684			&mut member,
3685			&mut bonded_pool,
3686			&mut reward_pool,
3687		)?;
3688
3689		Self::put_member_with_pools(&member_account, member, bonded_pool, reward_pool);
3690		Ok(())
3691	}
3692
3693	fn do_adjust_pool_deposit(who: T::AccountId, pool: PoolId) -> DispatchResult {
3694		let bonded_pool = BondedPool::<T>::get(pool).ok_or(Error::<T>::PoolNotFound)?;
3695
3696		let reward_acc = &bonded_pool.reward_account();
3697		let pre_frozen_balance =
3698			T::Currency::balance_frozen(&FreezeReason::PoolMinBalance.into(), reward_acc);
3699		let min_balance = T::Currency::minimum_balance();
3700
3701		if pre_frozen_balance == min_balance {
3702			return Err(Error::<T>::NothingToAdjust.into())
3703		}
3704
3705		// Update frozen amount with current ED.
3706		Self::freeze_pool_deposit(reward_acc)?;
3707
3708		if pre_frozen_balance > min_balance {
3709			// Transfer excess back to depositor.
3710			let excess = pre_frozen_balance.saturating_sub(min_balance);
3711			T::Currency::transfer(reward_acc, &who, excess, Preservation::Preserve)?;
3712			Self::deposit_event(Event::<T>::MinBalanceExcessAdjusted {
3713				pool_id: pool,
3714				amount: excess,
3715			});
3716		} else {
3717			// Transfer ED deficit from depositor to the pool
3718			let deficit = min_balance.saturating_sub(pre_frozen_balance);
3719			T::Currency::transfer(&who, reward_acc, deficit, Preservation::Expendable)?;
3720			Self::deposit_event(Event::<T>::MinBalanceDeficitAdjusted {
3721				pool_id: pool,
3722				amount: deficit,
3723			});
3724		}
3725
3726		Ok(())
3727	}
3728
3729	/// Slash member against the pending slash for the pool.
3730	fn do_apply_slash(
3731		member_account: &T::AccountId,
3732		reporter: Option<T::AccountId>,
3733		enforce_min_slash: bool,
3734	) -> DispatchResult {
3735		let member = PoolMembers::<T>::get(member_account).ok_or(Error::<T>::PoolMemberNotFound)?;
3736
3737		let pending_slash =
3738			Self::member_pending_slash(Member::from(member_account.clone()), member.clone())?;
3739
3740		// ensure there is something to slash.
3741		ensure!(!pending_slash.is_zero(), Error::<T>::NothingToSlash);
3742
3743		if enforce_min_slash {
3744			// ensure slashed amount is at least the minimum balance.
3745			ensure!(pending_slash >= T::Currency::minimum_balance(), Error::<T>::SlashTooLow);
3746		}
3747
3748		T::StakeAdapter::member_slash(
3749			Member::from(member_account.clone()),
3750			Pool::from(Pallet::<T>::generate_bonded_account(member.pool_id)),
3751			pending_slash,
3752			reporter,
3753		)
3754	}
3755
3756	/// Pending slash for a member.
3757	///
3758	/// Takes the pool_member object corresponding to the `member_account`.
3759	fn member_pending_slash(
3760		member_account: Member<T::AccountId>,
3761		pool_member: PoolMember<T>,
3762	) -> Result<BalanceOf<T>, DispatchError> {
3763		// only executed in tests: ensure the member account is correct.
3764		debug_assert!(
3765			PoolMembers::<T>::get(member_account.clone().get()).expect("member must exist") ==
3766				pool_member
3767		);
3768
3769		let pool_account = Pallet::<T>::generate_bonded_account(pool_member.pool_id);
3770		// if the pool doesn't have any pending slash, it implies the member also does not have any
3771		// pending slash.
3772		if T::StakeAdapter::pending_slash(Pool::from(pool_account.clone())).is_zero() {
3773			return Ok(Zero::zero())
3774		}
3775
3776		// this is their actual held balance that may or may not have been slashed.
3777		let actual_balance = T::StakeAdapter::member_delegation_balance(member_account)
3778			// no delegation implies the member delegation is not migrated yet to `DelegateStake`.
3779			.ok_or(Error::<T>::NotMigrated)?;
3780
3781		// this is their balance in the pool
3782		let expected_balance = pool_member.total_balance();
3783
3784		// return the amount to be slashed.
3785		Ok(actual_balance.saturating_sub(expected_balance))
3786	}
3787
3788	/// Apply freeze on reward account to restrict it from going below ED.
3789	pub(crate) fn freeze_pool_deposit(reward_acc: &T::AccountId) -> DispatchResult {
3790		T::Currency::set_freeze(
3791			&FreezeReason::PoolMinBalance.into(),
3792			reward_acc,
3793			T::Currency::minimum_balance(),
3794		)
3795	}
3796
3797	/// Removes the ED freeze on the reward account of `pool_id`.
3798	pub fn unfreeze_pool_deposit(reward_acc: &T::AccountId) -> DispatchResult {
3799		T::Currency::thaw(&FreezeReason::PoolMinBalance.into(), reward_acc)
3800	}
3801
3802	/// Ensure the correctness of the state of this pallet.
3803	///
3804	/// This should be valid before or after each state transition of this pallet.
3805	///
3806	/// ## Invariants:
3807	///
3808	/// First, let's consider pools:
3809	///
3810	/// * `BondedPools` and `RewardPools` must all have the EXACT SAME key-set.
3811	/// * `SubPoolsStorage` must be a subset of the above superset.
3812	/// * `Metadata` keys must be a subset of the above superset.
3813	/// * the count of the above set must be less than `MaxPools`.
3814	///
3815	/// Then, considering members as well:
3816	///
3817	/// * each `BondedPool.member_counter` must be:
3818	///   - correct (compared to actual count of member who have `.pool_id` this pool)
3819	///   - less than `MaxPoolMembersPerPool`.
3820	/// * each `member.pool_id` must correspond to an existing `BondedPool.id` (which implies the
3821	///   existence of the reward pool as well).
3822	/// * count of all members must be less than `MaxPoolMembers`.
3823	/// * each `BondedPool.points` must never be lower than the pool's balance.
3824	///
3825	/// Then, considering unbonding members:
3826	///
3827	/// for each pool:
3828	///   * sum of the balance that's tracked in all unbonding pools must be the same as the
3829	///     unbonded balance of the main account, as reported by the staking interface.
3830	///   * sum of the balance that's tracked in all unbonding pools, plus the bonded balance of the
3831	///     main account should be less than or qual to the total balance of the main account.
3832	///
3833	/// ## Sanity check level
3834	///
3835	/// To cater for tests that want to escape parts of these checks, this function is split into
3836	/// multiple `level`s, where the higher the level, the more checks we performs. So,
3837	/// `try_state(255)` is the strongest sanity check, and `0` performs no checks.
3838	#[cfg(any(feature = "try-runtime", feature = "fuzzing", test, debug_assertions))]
3839	pub fn do_try_state(level: u8) -> Result<(), TryRuntimeError> {
3840		if level.is_zero() {
3841			return Ok(())
3842		}
3843		// note: while a bit wacky, since they have the same key, even collecting to vec should
3844		// result in the same set of keys, in the same order.
3845		let bonded_pools = BondedPools::<T>::iter_keys().collect::<Vec<_>>();
3846		let reward_pools = RewardPools::<T>::iter_keys().collect::<Vec<_>>();
3847		ensure!(
3848			bonded_pools == reward_pools,
3849			"`BondedPools` and `RewardPools` must all have the EXACT SAME key-set."
3850		);
3851
3852		ensure!(
3853			SubPoolsStorage::<T>::iter_keys().all(|k| bonded_pools.contains(&k)),
3854			"`SubPoolsStorage` must be a subset of the above superset."
3855		);
3856		ensure!(
3857			Metadata::<T>::iter_keys().all(|k| bonded_pools.contains(&k)),
3858			"`Metadata` keys must be a subset of the above superset."
3859		);
3860
3861		ensure!(
3862			MaxPools::<T>::get().map_or(true, |max| bonded_pools.len() <= (max as usize)),
3863			Error::<T>::MaxPools
3864		);
3865
3866		for id in reward_pools {
3867			let account = Self::generate_reward_account(id);
3868			if T::Currency::reducible_balance(&account, Preservation::Expendable, Fortitude::Polite) <
3869				T::Currency::minimum_balance()
3870			{
3871				log!(
3872					warn,
3873					"reward pool of {:?}: {:?} (ed = {:?}), should only happen because ED has \
3874					changed recently. Pool operators should be notified to top up the reward \
3875					account",
3876					id,
3877					T::Currency::reducible_balance(
3878						&account,
3879						Preservation::Expendable,
3880						Fortitude::Polite
3881					),
3882					T::Currency::minimum_balance(),
3883				)
3884			}
3885		}
3886
3887		let mut pools_members = BTreeMap::<PoolId, u32>::new();
3888		let mut pools_members_pending_rewards = BTreeMap::<PoolId, BalanceOf<T>>::new();
3889		let mut all_members = 0u32;
3890		let mut total_balance_members = Default::default();
3891		PoolMembers::<T>::iter().try_for_each(|(_, d)| -> Result<(), TryRuntimeError> {
3892			let bonded_pool = BondedPools::<T>::get(d.pool_id).unwrap();
3893			ensure!(!d.total_points().is_zero(), "No member should have zero points");
3894			*pools_members.entry(d.pool_id).or_default() += 1;
3895			all_members += 1;
3896
3897			let reward_pool = RewardPools::<T>::get(d.pool_id).unwrap();
3898			if !bonded_pool.points.is_zero() {
3899				let commission = bonded_pool.commission.current();
3900				let (current_rc, _) = reward_pool
3901					.current_reward_counter(d.pool_id, bonded_pool.points, commission)
3902					.unwrap();
3903				let pending_rewards = d.pending_rewards(current_rc).unwrap();
3904				*pools_members_pending_rewards.entry(d.pool_id).or_default() += pending_rewards;
3905			} // else this pool has been heavily slashed and cannot have any rewards anymore.
3906			total_balance_members += d.total_balance();
3907
3908			Ok(())
3909		})?;
3910
3911		RewardPools::<T>::iter_keys().try_for_each(|id| -> Result<(), TryRuntimeError> {
3912			// the sum of the pending rewards must be less than the leftover balance. Since the
3913			// reward math rounds down, we might accumulate some dust here.
3914			let pending_rewards_lt_leftover_bal = RewardPool::<T>::current_balance(id) >=
3915				pools_members_pending_rewards.get(&id).copied().unwrap_or_default();
3916
3917			// If this happens, this is most likely due to an old bug and not a recent code change.
3918			// We warn about this in try-runtime checks but do not panic.
3919			if !pending_rewards_lt_leftover_bal {
3920				log::warn!(
3921					"pool {:?}, sum pending rewards = {:?}, remaining balance = {:?}",
3922					id,
3923					pools_members_pending_rewards.get(&id),
3924					RewardPool::<T>::current_balance(id)
3925				);
3926			}
3927			Ok(())
3928		})?;
3929
3930		let mut expected_tvl: BalanceOf<T> = Default::default();
3931		BondedPools::<T>::iter().try_for_each(|(id, inner)| -> Result<(), TryRuntimeError> {
3932			let bonded_pool = BondedPool { id, inner };
3933			ensure!(
3934				pools_members.get(&id).copied().unwrap_or_default() ==
3935				bonded_pool.member_counter,
3936				"Each `BondedPool.member_counter` must be equal to the actual count of members of this pool"
3937			);
3938			ensure!(
3939				MaxPoolMembersPerPool::<T>::get()
3940					.map_or(true, |max| bonded_pool.member_counter <= max),
3941				Error::<T>::MaxPoolMembers
3942			);
3943
3944			let depositor = PoolMembers::<T>::get(&bonded_pool.roles.depositor).unwrap();
3945			ensure!(
3946				bonded_pool.is_destroying_and_only_depositor(depositor.active_points()) ||
3947					depositor.active_points() >= MinCreateBond::<T>::get(),
3948				"depositor must always have MinCreateBond stake in the pool, except for when the \
3949				pool is being destroyed and the depositor is the last member",
3950			);
3951
3952			ensure!(
3953				bonded_pool.points >= bonded_pool.points_to_balance(bonded_pool.points),
3954				"Each `BondedPool.points` must never be lower than the pool's balance"
3955			);
3956
3957			expected_tvl += T::StakeAdapter::total_stake(Pool::from(bonded_pool.bonded_account()));
3958
3959			Ok(())
3960		})?;
3961
3962		ensure!(
3963			MaxPoolMembers::<T>::get().map_or(true, |max| all_members <= max),
3964			Error::<T>::MaxPoolMembers
3965		);
3966
3967		ensure!(
3968			TotalValueLocked::<T>::get() == expected_tvl,
3969			"TVL deviates from the actual sum of funds of all Pools."
3970		);
3971
3972		ensure!(
3973			TotalValueLocked::<T>::get() <= total_balance_members,
3974			"TVL must be equal to or less than the total balance of all PoolMembers."
3975		);
3976
3977		if level <= 1 {
3978			return Ok(())
3979		}
3980
3981		for (pool_id, _pool) in BondedPools::<T>::iter() {
3982			let pool_account = Pallet::<T>::generate_bonded_account(pool_id);
3983			let subs = SubPoolsStorage::<T>::get(pool_id).unwrap_or_default();
3984
3985			let sum_unbonding_balance = subs.sum_unbonding_balance();
3986			let bonded_balance = T::StakeAdapter::active_stake(Pool::from(pool_account.clone()));
3987			let total_balance = T::StakeAdapter::total_balance(Pool::from(pool_account.clone()))
3988				// At the time when StakeAdapter is changed to `DelegateStake` but pool is not yet
3989				// migrated, the total balance would be none.
3990				.unwrap_or(T::Currency::total_balance(&pool_account));
3991
3992			assert!(
3993				total_balance >= bonded_balance + sum_unbonding_balance,
3994				"faulty pool: {:?} / {:?}, total_balance {:?} >= bonded_balance {:?} + sum_unbonding_balance {:?}",
3995				pool_id,
3996				_pool,
3997				total_balance,
3998				bonded_balance,
3999				sum_unbonding_balance
4000			);
4001		}
4002
4003		// Warn if any pool has incorrect ED frozen. We don't want to fail hard as this could be a
4004		// result of an intentional ED change.
4005		let _ = Self::check_ed_imbalance()?;
4006
4007		Ok(())
4008	}
4009
4010	/// Check if any pool have an incorrect amount of ED frozen.
4011	///
4012	/// This can happen if the ED has changed since the pool was created.
4013	#[cfg(any(
4014		feature = "try-runtime",
4015		feature = "runtime-benchmarks",
4016		feature = "fuzzing",
4017		test,
4018		debug_assertions
4019	))]
4020	pub fn check_ed_imbalance() -> Result<(), DispatchError> {
4021		let mut failed: u32 = 0;
4022		BondedPools::<T>::iter_keys().for_each(|id| {
4023			let reward_acc = Self::generate_reward_account(id);
4024			let frozen_balance =
4025				T::Currency::balance_frozen(&FreezeReason::PoolMinBalance.into(), &reward_acc);
4026
4027			let expected_frozen_balance = T::Currency::minimum_balance();
4028			if frozen_balance != expected_frozen_balance {
4029				failed += 1;
4030				log::warn!(
4031					"pool {:?} has incorrect ED frozen that can result from change in ED. Expected  = {:?},  Actual = {:?}",
4032					id,
4033					expected_frozen_balance,
4034					frozen_balance,
4035				);
4036			}
4037		});
4038
4039		ensure!(failed == 0, "Some pools do not have correct ED frozen");
4040		Ok(())
4041	}
4042	/// Fully unbond the shares of `member`, when executed from `origin`.
4043	///
4044	/// This is useful for backwards compatibility with the majority of tests that only deal with
4045	/// full unbonding, not partial unbonding.
4046	#[cfg(any(feature = "runtime-benchmarks", test))]
4047	pub fn fully_unbond(
4048		origin: frame_system::pallet_prelude::OriginFor<T>,
4049		member: T::AccountId,
4050	) -> DispatchResult {
4051		let points = PoolMembers::<T>::get(&member).map(|d| d.active_points()).unwrap_or_default();
4052		let member_lookup = T::Lookup::unlookup(member);
4053		Self::unbond(origin, member_lookup, points)
4054	}
4055}
4056
4057impl<T: Config> Pallet<T> {
4058	/// Returns the pending rewards for the specified `who` account.
4059	///
4060	/// In the case of error, `None` is returned. Used by runtime API.
4061	pub fn api_pending_rewards(who: T::AccountId) -> Option<BalanceOf<T>> {
4062		if let Some(pool_member) = PoolMembers::<T>::get(who) {
4063			if let Some((reward_pool, bonded_pool)) = RewardPools::<T>::get(pool_member.pool_id)
4064				.zip(BondedPools::<T>::get(pool_member.pool_id))
4065			{
4066				let commission = bonded_pool.commission.current();
4067				let (current_reward_counter, _) = reward_pool
4068					.current_reward_counter(pool_member.pool_id, bonded_pool.points, commission)
4069					.ok()?;
4070				return pool_member.pending_rewards(current_reward_counter).ok()
4071			}
4072		}
4073
4074		None
4075	}
4076
4077	/// Returns the points to balance conversion for a specified pool.
4078	///
4079	/// If the pool ID does not exist, it returns 0 ratio points to balance. Used by runtime API.
4080	pub fn api_points_to_balance(pool_id: PoolId, points: BalanceOf<T>) -> BalanceOf<T> {
4081		if let Some(pool) = BondedPool::<T>::get(pool_id) {
4082			pool.points_to_balance(points)
4083		} else {
4084			Zero::zero()
4085		}
4086	}
4087
4088	/// Returns the equivalent `new_funds` balance to point conversion for a specified pool.
4089	///
4090	/// If the pool ID does not exist, returns 0 ratio balance to points. Used by runtime API.
4091	pub fn api_balance_to_points(pool_id: PoolId, new_funds: BalanceOf<T>) -> BalanceOf<T> {
4092		if let Some(pool) = BondedPool::<T>::get(pool_id) {
4093			let bonded_balance =
4094				T::StakeAdapter::active_stake(Pool::from(Self::generate_bonded_account(pool_id)));
4095			Pallet::<T>::balance_to_point(bonded_balance, pool.points, new_funds)
4096		} else {
4097			Zero::zero()
4098		}
4099	}
4100
4101	/// Returns the unapplied slash of the pool.
4102	///
4103	/// Pending slash is only applicable with [`adapter::DelegateStake`] strategy.
4104	pub fn api_pool_pending_slash(pool_id: PoolId) -> BalanceOf<T> {
4105		T::StakeAdapter::pending_slash(Pool::from(Self::generate_bonded_account(pool_id)))
4106	}
4107
4108	/// Returns the unapplied slash of a member.
4109	///
4110	/// Pending slash is only applicable with [`adapter::DelegateStake`] strategy.
4111	///
4112	/// If pending slash of the member exceeds `ExistentialDeposit`, it can be reported on
4113	/// chain via [`Call::apply_slash`].
4114	pub fn api_member_pending_slash(who: T::AccountId) -> BalanceOf<T> {
4115		PoolMembers::<T>::get(who.clone())
4116			.map(|pool_member| {
4117				Self::member_pending_slash(Member::from(who), pool_member).unwrap_or_default()
4118			})
4119			.unwrap_or_default()
4120	}
4121
4122	/// Checks whether pool needs to be migrated to [`adapter::StakeStrategyType::Delegate`]. Only
4123	/// applicable when the [`Config::StakeAdapter`] is [`adapter::DelegateStake`].
4124	///
4125	/// Useful to check this before calling [`Call::migrate_pool_to_delegate_stake`].
4126	pub fn api_pool_needs_delegate_migration(pool_id: PoolId) -> bool {
4127		// if the `Delegate` strategy is not used in the pallet, then no migration required.
4128		if T::StakeAdapter::strategy_type() != adapter::StakeStrategyType::Delegate {
4129			return false
4130		}
4131
4132		// if pool does not exist, return false.
4133		if !BondedPools::<T>::contains_key(pool_id) {
4134			return false
4135		}
4136
4137		let pool_account = Self::generate_bonded_account(pool_id);
4138
4139		// true if pool is still not migrated to `DelegateStake`.
4140		T::StakeAdapter::pool_strategy(Pool::from(pool_account)) !=
4141			adapter::StakeStrategyType::Delegate
4142	}
4143
4144	/// Checks whether member delegation needs to be migrated to
4145	/// [`adapter::StakeStrategyType::Delegate`]. Only applicable when the [`Config::StakeAdapter`]
4146	/// is [`adapter::DelegateStake`].
4147	///
4148	/// Useful to check this before calling [`Call::migrate_delegation`].
4149	pub fn api_member_needs_delegate_migration(who: T::AccountId) -> bool {
4150		// if the `Delegate` strategy is not used in the pallet, then no migration required.
4151		if T::StakeAdapter::strategy_type() != adapter::StakeStrategyType::Delegate {
4152			return false
4153		}
4154
4155		PoolMembers::<T>::get(who.clone())
4156			.map(|pool_member| {
4157				if Self::api_pool_needs_delegate_migration(pool_member.pool_id) {
4158					// the pool needs to be migrated before members can be migrated.
4159					return false
4160				}
4161
4162				let member_balance = pool_member.total_balance();
4163				let delegated_balance =
4164					T::StakeAdapter::member_delegation_balance(Member::from(who.clone()));
4165
4166				// if the member has no delegation but has some balance in the pool, then it needs
4167				// to be migrated.
4168				delegated_balance.is_none() && !member_balance.is_zero()
4169			})
4170			.unwrap_or_default()
4171	}
4172
4173	/// Contribution of the member in the pool.
4174	///
4175	/// Includes balance that is unbonded from staking but not claimed yet from the pool, therefore
4176	/// this balance can be higher than the staked funds.
4177	pub fn api_member_total_balance(who: T::AccountId) -> BalanceOf<T> {
4178		PoolMembers::<T>::get(who.clone())
4179			.map(|m| m.total_balance())
4180			.unwrap_or_default()
4181	}
4182
4183	/// Total balance contributed to the pool.
4184	pub fn api_pool_balance(pool_id: PoolId) -> BalanceOf<T> {
4185		T::StakeAdapter::total_balance(Pool::from(Self::generate_bonded_account(pool_id)))
4186			.unwrap_or_default()
4187	}
4188
4189	/// Returns the bonded account and reward account associated with the pool_id.
4190	pub fn api_pool_accounts(pool_id: PoolId) -> (T::AccountId, T::AccountId) {
4191		let bonded_account = Self::generate_bonded_account(pool_id);
4192		let reward_account = Self::generate_reward_account(pool_id);
4193		(bonded_account, reward_account)
4194	}
4195}
4196
4197impl<T: Config> sp_staking::OnStakingUpdate<T::AccountId, BalanceOf<T>> for Pallet<T> {
4198	/// Reduces the balances of the [`SubPools`], that belong to the pool involved in the
4199	/// slash, to the amount that is defined in the `slashed_unlocking` field of
4200	/// [`sp_staking::OnStakingUpdate::on_slash`]
4201	///
4202	/// Emits the `PoolsSlashed` event.
4203	fn on_slash(
4204		pool_account: &T::AccountId,
4205		// Bonded balance is always read directly from staking, therefore we don't need to update
4206		// anything here.
4207		slashed_bonded: BalanceOf<T>,
4208		slashed_unlocking: &BTreeMap<EraIndex, BalanceOf<T>>,
4209		total_slashed: BalanceOf<T>,
4210	) {
4211		let Some(pool_id) = ReversePoolIdLookup::<T>::get(pool_account) else { return };
4212		// As the slashed account belongs to a `BondedPool` the `TotalValueLocked` decreases and
4213		// an event is emitted.
4214		TotalValueLocked::<T>::mutate(|tvl| {
4215			tvl.defensive_saturating_reduce(total_slashed);
4216		});
4217
4218		if let Some(mut sub_pools) = SubPoolsStorage::<T>::get(pool_id) {
4219			// set the reduced balance for each of the `SubPools`
4220			slashed_unlocking.iter().for_each(|(era, slashed_balance)| {
4221				if let Some(pool) = sub_pools.with_era.get_mut(era).defensive() {
4222					pool.balance = *slashed_balance;
4223					Self::deposit_event(Event::<T>::UnbondingPoolSlashed {
4224						era: *era,
4225						pool_id,
4226						balance: *slashed_balance,
4227					});
4228				}
4229			});
4230			SubPoolsStorage::<T>::insert(pool_id, sub_pools);
4231		} else if !slashed_unlocking.is_empty() {
4232			defensive!("Expected SubPools were not found");
4233		}
4234		Self::deposit_event(Event::<T>::PoolSlashed { pool_id, balance: slashed_bonded });
4235	}
4236
4237	/// Reduces the overall `TotalValueLocked` if a withdrawal happened for a pool involved in the
4238	/// staking withdraw.
4239	fn on_withdraw(pool_account: &T::AccountId, amount: BalanceOf<T>) {
4240		if ReversePoolIdLookup::<T>::get(pool_account).is_some() {
4241			TotalValueLocked::<T>::mutate(|tvl| {
4242				tvl.saturating_reduce(amount);
4243			});
4244		}
4245	}
4246}
4247
4248/// A utility struct that provides a way to check if a given account is a pool member.
4249pub struct AllPoolMembers<T: Config>(PhantomData<T>);
4250impl<T: Config> Contains<T::AccountId> for AllPoolMembers<T> {
4251	fn contains(t: &T::AccountId) -> bool {
4252		PoolMembers::<T>::contains_key(t)
4253	}
4254}