referrerpolicy=no-referrer-when-downgrade

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