pallet_balances/
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//! # Balances Pallet
19//!
20//! The Balances pallet provides functionality for handling accounts and balances for a single
21//! token.
22//!
23//! It makes heavy use of concepts such as Holds and Freezes from the
24//! [`frame_support::traits::fungible`] traits, therefore you should read and understand those docs
25//! as a prerequisite to understanding this pallet.
26//!
27//! Also see the [`frame_tokens`] reference docs for higher level information regarding the
28//! place of this palet in FRAME.
29//!
30//! ## Overview
31//!
32//! The Balances pallet provides functions for:
33//!
34//! - Getting and setting free balances.
35//! - Retrieving total, reserved and unreserved balances.
36//! - Repatriating a reserved balance to a beneficiary account that exists.
37//! - Transferring a balance between accounts (when not reserved).
38//! - Slashing an account balance.
39//! - Account creation and removal.
40//! - Managing total issuance.
41//! - Setting and managing locks.
42//!
43//! ### Terminology
44//!
45//! - **Reaping an account:** The act of removing an account by resetting its nonce. Happens after
46//!   its total balance has become less than the Existential Deposit.
47//!
48//! ### Implementations
49//!
50//! The Balances pallet provides implementations for the following [`fungible`] traits. If these
51//! traits provide the functionality that you need, then you should avoid tight coupling with the
52//! Balances pallet.
53//!
54//! - [`fungible::Inspect`]
55//! - [`fungible::Mutate`]
56//! - [`fungible::Unbalanced`]
57//! - [`fungible::Balanced`]
58//! - [`fungible::BalancedHold`]
59//! - [`fungible::InspectHold`]
60//! - [`fungible::MutateHold`]
61//! - [`fungible::InspectFreeze`]
62//! - [`fungible::MutateFreeze`]
63//! - [`fungible::Imbalance`]
64//!
65//! It also implements the following [`Currency`] related traits, however they are deprecated and
66//! will eventually be removed.
67//!
68//! - [`Currency`]: Functions for dealing with a fungible assets system.
69//! - [`ReservableCurrency`]
70//! - [`NamedReservableCurrency`](frame_support::traits::NamedReservableCurrency):
71//! Functions for dealing with assets that can be reserved from an account.
72//! - [`LockableCurrency`](frame_support::traits::LockableCurrency): Functions for
73//! dealing with accounts that allow liquidity restrictions.
74//! - [`Imbalance`](frame_support::traits::Imbalance): Functions for handling
75//! imbalances between total issuance in the system and account balances. Must be used when a
76//! function creates new funds (e.g. a reward) or destroys some funds (e.g. a system fee).
77//!
78//! ## Usage
79//!
80//! The following examples show how to use the Balances pallet in your custom pallet.
81//!
82//! ### Examples from the FRAME
83//!
84//! The Contract pallet uses the `Currency` trait to handle gas payment, and its types inherit from
85//! `Currency`:
86//!
87//! ```
88//! use frame_support::traits::Currency;
89//! # pub trait Config: frame_system::Config {
90//! #   type Currency: Currency<Self::AccountId>;
91//! # }
92//!
93//! pub type BalanceOf<T> = <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;
94//! pub type NegativeImbalanceOf<T> = <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::NegativeImbalance;
95//!
96//! # fn main() {}
97//! ```
98//!
99//! The Staking pallet uses the `LockableCurrency` trait to lock a stash account's funds:
100//!
101//! ```
102//! use frame_support::traits::{WithdrawReasons, LockableCurrency};
103//! use sp_runtime::traits::Bounded;
104//! pub trait Config: frame_system::Config {
105//!     type Currency: LockableCurrency<Self::AccountId, Moment=frame_system::pallet_prelude::BlockNumberFor<Self>>;
106//! }
107//! # struct StakingLedger<T: Config> {
108//! #   stash: <T as frame_system::Config>::AccountId,
109//! #   total: <<T as Config>::Currency as frame_support::traits::Currency<<T as frame_system::Config>::AccountId>>::Balance,
110//! #   phantom: std::marker::PhantomData<T>,
111//! # }
112//! # const STAKING_ID: [u8; 8] = *b"staking ";
113//!
114//! fn update_ledger<T: Config>(
115//!     controller: &T::AccountId,
116//!     ledger: &StakingLedger<T>
117//! ) {
118//!     T::Currency::set_lock(
119//!         STAKING_ID,
120//!         &ledger.stash,
121//!         ledger.total,
122//!         WithdrawReasons::all()
123//!     );
124//!     // <Ledger<T>>::insert(controller, ledger); // Commented out as we don't have access to Staking's storage here.
125//! }
126//! # fn main() {}
127//! ```
128//!
129//! ## Genesis config
130//!
131//! The Balances pallet depends on the [`GenesisConfig`].
132//!
133//! ## Assumptions
134//!
135//! * Total issued balanced of all accounts should be less than `Config::Balance::max_value()`.
136//! * Existential Deposit is set to a value greater than zero.
137//!
138//! Note, you may find the Balances pallet still functions with an ED of zero when the
139//! `insecure_zero_ed` cargo feature is enabled. However this is not a configuration which is
140//! generally supported, nor will it be.
141//!
142//! [`frame_tokens`]: ../polkadot_sdk_docs/reference_docs/frame_tokens/index.html
143
144#![cfg_attr(not(feature = "std"), no_std)]
145mod benchmarking;
146mod impl_currency;
147mod impl_fungible;
148pub mod migration;
149mod tests;
150mod types;
151pub mod weights;
152
153extern crate alloc;
154
155use alloc::{
156	format,
157	string::{String, ToString},
158	vec::Vec,
159};
160use codec::{Codec, MaxEncodedLen};
161use core::{cmp, fmt::Debug, mem, result};
162use frame_support::{
163	ensure,
164	pallet_prelude::DispatchResult,
165	traits::{
166		tokens::{
167			fungible, BalanceStatus as Status, DepositConsequence,
168			Fortitude::{self, Force, Polite},
169			IdAmount,
170			Preservation::{Expendable, Preserve, Protect},
171			WithdrawConsequence,
172		},
173		Currency, Defensive, Get, OnUnbalanced, ReservableCurrency, StoredMap,
174	},
175	BoundedSlice, WeakBoundedVec,
176};
177use frame_system as system;
178pub use impl_currency::{NegativeImbalance, PositiveImbalance};
179use scale_info::TypeInfo;
180use sp_core::{sr25519::Pair as SrPair, Pair};
181use sp_runtime::{
182	traits::{
183		AtLeast32BitUnsigned, CheckedAdd, CheckedSub, MaybeSerializeDeserialize, Saturating,
184		StaticLookup, Zero,
185	},
186	ArithmeticError, DispatchError, FixedPointOperand, Perbill, RuntimeDebug, TokenError,
187};
188
189pub use types::{
190	AccountData, AdjustmentDirection, BalanceLock, DustCleaner, ExtraFlags, Reasons, ReserveData,
191};
192pub use weights::WeightInfo;
193
194pub use pallet::*;
195
196const LOG_TARGET: &str = "runtime::balances";
197
198// Default derivation(hard) for development accounts.
199const DEFAULT_ADDRESS_URI: &str = "//Sender//{}";
200
201type AccountIdLookupOf<T> = <<T as frame_system::Config>::Lookup as StaticLookup>::Source;
202
203#[frame_support::pallet]
204pub mod pallet {
205	use super::*;
206	use codec::HasCompact;
207	use frame_support::{
208		pallet_prelude::*,
209		traits::{fungible::Credit, tokens::Precision, VariantCount, VariantCountOf},
210	};
211	use frame_system::pallet_prelude::*;
212
213	pub type CreditOf<T, I> = Credit<<T as frame_system::Config>::AccountId, Pallet<T, I>>;
214
215	/// Default implementations of [`DefaultConfig`], which can be used to implement [`Config`].
216	pub mod config_preludes {
217		use super::*;
218		use frame_support::derive_impl;
219
220		pub struct TestDefaultConfig;
221
222		#[derive_impl(frame_system::config_preludes::TestDefaultConfig, no_aggregated_types)]
223		impl frame_system::DefaultConfig for TestDefaultConfig {}
224
225		#[frame_support::register_default_impl(TestDefaultConfig)]
226		impl DefaultConfig for TestDefaultConfig {
227			#[inject_runtime_type]
228			type RuntimeEvent = ();
229			#[inject_runtime_type]
230			type RuntimeHoldReason = ();
231			#[inject_runtime_type]
232			type RuntimeFreezeReason = ();
233
234			type Balance = u64;
235			type ExistentialDeposit = ConstUint<1>;
236
237			type ReserveIdentifier = ();
238			type FreezeIdentifier = Self::RuntimeFreezeReason;
239
240			type DustRemoval = ();
241
242			type MaxLocks = ConstU32<100>;
243			type MaxReserves = ConstU32<100>;
244			type MaxFreezes = VariantCountOf<Self::RuntimeFreezeReason>;
245
246			type WeightInfo = ();
247			type DoneSlashHandler = ();
248		}
249	}
250
251	#[pallet::config(with_default)]
252	pub trait Config<I: 'static = ()>: frame_system::Config {
253		/// The overarching event type.
254		#[pallet::no_default_bounds]
255		#[allow(deprecated)]
256		type RuntimeEvent: From<Event<Self, I>>
257			+ IsType<<Self as frame_system::Config>::RuntimeEvent>;
258
259		/// The overarching hold reason.
260		#[pallet::no_default_bounds]
261		type RuntimeHoldReason: Parameter + Member + MaxEncodedLen + Copy + VariantCount;
262
263		/// The overarching freeze reason.
264		#[pallet::no_default_bounds]
265		type RuntimeFreezeReason: VariantCount;
266
267		/// Weight information for extrinsics in this pallet.
268		type WeightInfo: WeightInfo;
269
270		/// The balance of an account.
271		type Balance: Parameter
272			+ Member
273			+ AtLeast32BitUnsigned
274			+ Codec
275			+ HasCompact<Type: DecodeWithMemTracking>
276			+ Default
277			+ Copy
278			+ MaybeSerializeDeserialize
279			+ Debug
280			+ MaxEncodedLen
281			+ TypeInfo
282			+ FixedPointOperand;
283
284		/// Handler for the unbalanced reduction when removing a dust account.
285		#[pallet::no_default_bounds]
286		type DustRemoval: OnUnbalanced<CreditOf<Self, I>>;
287
288		/// The minimum amount required to keep an account open. MUST BE GREATER THAN ZERO!
289		///
290		/// If you *really* need it to be zero, you can enable the feature `insecure_zero_ed` for
291		/// this pallet. However, you do so at your own risk: this will open up a major DoS vector.
292		/// In case you have multiple sources of provider references, you may also get unexpected
293		/// behaviour if you set this to zero.
294		///
295		/// Bottom line: Do yourself a favour and make it at least one!
296		#[pallet::constant]
297		#[pallet::no_default_bounds]
298		type ExistentialDeposit: Get<Self::Balance>;
299
300		/// The means of storing the balances of an account.
301		#[pallet::no_default]
302		type AccountStore: StoredMap<Self::AccountId, AccountData<Self::Balance>>;
303
304		/// The ID type for reserves.
305		///
306		/// Use of reserves is deprecated in favour of holds. See `https://github.com/paritytech/substrate/pull/12951/`
307		type ReserveIdentifier: Parameter + Member + MaxEncodedLen + Ord + Copy;
308
309		/// The ID type for freezes.
310		type FreezeIdentifier: Parameter + Member + MaxEncodedLen + Copy;
311
312		/// The maximum number of locks that should exist on an account.
313		/// Not strictly enforced, but used for weight estimation.
314		///
315		/// Use of locks is deprecated in favour of freezes. See `https://github.com/paritytech/substrate/pull/12951/`
316		#[pallet::constant]
317		type MaxLocks: Get<u32>;
318
319		/// The maximum number of named reserves that can exist on an account.
320		///
321		/// Use of reserves is deprecated in favour of holds. See `https://github.com/paritytech/substrate/pull/12951/`
322		#[pallet::constant]
323		type MaxReserves: Get<u32>;
324
325		/// The maximum number of individual freeze locks that can exist on an account at any time.
326		#[pallet::constant]
327		type MaxFreezes: Get<u32>;
328
329		/// Allows callbacks to other pallets so they can update their bookkeeping when a slash
330		/// occurs.
331		type DoneSlashHandler: fungible::hold::DoneSlash<
332			Self::RuntimeHoldReason,
333			Self::AccountId,
334			Self::Balance,
335		>;
336	}
337
338	/// The in-code storage version.
339	const STORAGE_VERSION: frame_support::traits::StorageVersion =
340		frame_support::traits::StorageVersion::new(1);
341
342	#[pallet::pallet]
343	#[pallet::storage_version(STORAGE_VERSION)]
344	pub struct Pallet<T, I = ()>(PhantomData<(T, I)>);
345
346	#[pallet::event]
347	#[pallet::generate_deposit(pub(super) fn deposit_event)]
348	pub enum Event<T: Config<I>, I: 'static = ()> {
349		/// An account was created with some free balance.
350		Endowed { account: T::AccountId, free_balance: T::Balance },
351		/// An account was removed whose balance was non-zero but below ExistentialDeposit,
352		/// resulting in an outright loss.
353		DustLost { account: T::AccountId, amount: T::Balance },
354		/// Transfer succeeded.
355		Transfer { from: T::AccountId, to: T::AccountId, amount: T::Balance },
356		/// A balance was set by root.
357		BalanceSet { who: T::AccountId, free: T::Balance },
358		/// Some balance was reserved (moved from free to reserved).
359		Reserved { who: T::AccountId, amount: T::Balance },
360		/// Some balance was unreserved (moved from reserved to free).
361		Unreserved { who: T::AccountId, amount: T::Balance },
362		/// Some balance was moved from the reserve of the first account to the second account.
363		/// Final argument indicates the destination balance type.
364		ReserveRepatriated {
365			from: T::AccountId,
366			to: T::AccountId,
367			amount: T::Balance,
368			destination_status: Status,
369		},
370		/// Some amount was deposited (e.g. for transaction fees).
371		Deposit { who: T::AccountId, amount: T::Balance },
372		/// Some amount was withdrawn from the account (e.g. for transaction fees).
373		Withdraw { who: T::AccountId, amount: T::Balance },
374		/// Some amount was removed from the account (e.g. for misbehavior).
375		Slashed { who: T::AccountId, amount: T::Balance },
376		/// Some amount was minted into an account.
377		Minted { who: T::AccountId, amount: T::Balance },
378		/// Some amount was burned from an account.
379		Burned { who: T::AccountId, amount: T::Balance },
380		/// Some amount was suspended from an account (it can be restored later).
381		Suspended { who: T::AccountId, amount: T::Balance },
382		/// Some amount was restored into an account.
383		Restored { who: T::AccountId, amount: T::Balance },
384		/// An account was upgraded.
385		Upgraded { who: T::AccountId },
386		/// Total issuance was increased by `amount`, creating a credit to be balanced.
387		Issued { amount: T::Balance },
388		/// Total issuance was decreased by `amount`, creating a debt to be balanced.
389		Rescinded { amount: T::Balance },
390		/// Some balance was locked.
391		Locked { who: T::AccountId, amount: T::Balance },
392		/// Some balance was unlocked.
393		Unlocked { who: T::AccountId, amount: T::Balance },
394		/// Some balance was frozen.
395		Frozen { who: T::AccountId, amount: T::Balance },
396		/// Some balance was thawed.
397		Thawed { who: T::AccountId, amount: T::Balance },
398		/// The `TotalIssuance` was forcefully changed.
399		TotalIssuanceForced { old: T::Balance, new: T::Balance },
400		/// An unexpected/defensive event was triggered.
401		Unexpected(UnexpectedKind),
402	}
403
404	/// Defensive/unexpected errors/events.
405	///
406	/// In case of observation in explorers, report it as an issue in polkadot-sdk.
407	#[derive(Clone, Encode, Decode, DecodeWithMemTracking, PartialEq, TypeInfo, RuntimeDebug)]
408	pub enum UnexpectedKind {
409		/// Balance was altered/dusted during an operation that should have NOT done so.
410		BalanceUpdated,
411		/// Mutating the account failed unexpectedly. This might lead to storage items in
412		/// `Balances` and the underlying account in `System` to be out of sync.
413		FailedToMutateAccount,
414	}
415
416	#[pallet::error]
417	pub enum Error<T, I = ()> {
418		/// Vesting balance too high to send value.
419		VestingBalance,
420		/// Account liquidity restrictions prevent withdrawal.
421		LiquidityRestrictions,
422		/// Balance too low to send value.
423		InsufficientBalance,
424		/// Value too low to create account due to existential deposit.
425		ExistentialDeposit,
426		/// Transfer/payment would kill account.
427		Expendability,
428		/// A vesting schedule already exists for this account.
429		ExistingVestingSchedule,
430		/// Beneficiary account must pre-exist.
431		DeadAccount,
432		/// Number of named reserves exceed `MaxReserves`.
433		TooManyReserves,
434		/// Number of holds exceed `VariantCountOf<T::RuntimeHoldReason>`.
435		TooManyHolds,
436		/// Number of freezes exceed `MaxFreezes`.
437		TooManyFreezes,
438		/// The issuance cannot be modified since it is already deactivated.
439		IssuanceDeactivated,
440		/// The delta cannot be zero.
441		DeltaZero,
442	}
443
444	/// The total units issued in the system.
445	#[pallet::storage]
446	#[pallet::whitelist_storage]
447	pub type TotalIssuance<T: Config<I>, I: 'static = ()> = StorageValue<_, T::Balance, ValueQuery>;
448
449	/// The total units of outstanding deactivated balance in the system.
450	#[pallet::storage]
451	#[pallet::whitelist_storage]
452	pub type InactiveIssuance<T: Config<I>, I: 'static = ()> =
453		StorageValue<_, T::Balance, ValueQuery>;
454
455	/// The Balances pallet example of storing the balance of an account.
456	///
457	/// # Example
458	///
459	/// ```nocompile
460	///  impl pallet_balances::Config for Runtime {
461	///    type AccountStore = StorageMapShim<Self::Account<Runtime>, frame_system::Provider<Runtime>, AccountId, Self::AccountData<Balance>>
462	///  }
463	/// ```
464	///
465	/// You can also store the balance of an account in the `System` pallet.
466	///
467	/// # Example
468	///
469	/// ```nocompile
470	///  impl pallet_balances::Config for Runtime {
471	///   type AccountStore = System
472	///  }
473	/// ```
474	///
475	/// But this comes with tradeoffs, storing account balances in the system pallet stores
476	/// `frame_system` data alongside the account data contrary to storing account balances in the
477	/// `Balances` pallet, which uses a `StorageMap` to store balances data only.
478	/// NOTE: This is only used in the case that this pallet is used to store balances.
479	#[pallet::storage]
480	pub type Account<T: Config<I>, I: 'static = ()> =
481		StorageMap<_, Blake2_128Concat, T::AccountId, AccountData<T::Balance>, ValueQuery>;
482
483	/// Any liquidity locks on some account balances.
484	/// NOTE: Should only be accessed when setting, changing and freeing a lock.
485	///
486	/// Use of locks is deprecated in favour of freezes. See `https://github.com/paritytech/substrate/pull/12951/`
487	#[pallet::storage]
488	pub type Locks<T: Config<I>, I: 'static = ()> = StorageMap<
489		_,
490		Blake2_128Concat,
491		T::AccountId,
492		WeakBoundedVec<BalanceLock<T::Balance>, T::MaxLocks>,
493		ValueQuery,
494	>;
495
496	/// Named reserves on some account balances.
497	///
498	/// Use of reserves is deprecated in favour of holds. See `https://github.com/paritytech/substrate/pull/12951/`
499	#[pallet::storage]
500	pub type Reserves<T: Config<I>, I: 'static = ()> = StorageMap<
501		_,
502		Blake2_128Concat,
503		T::AccountId,
504		BoundedVec<ReserveData<T::ReserveIdentifier, T::Balance>, T::MaxReserves>,
505		ValueQuery,
506	>;
507
508	/// Holds on account balances.
509	#[pallet::storage]
510	pub type Holds<T: Config<I>, I: 'static = ()> = StorageMap<
511		_,
512		Blake2_128Concat,
513		T::AccountId,
514		BoundedVec<
515			IdAmount<T::RuntimeHoldReason, T::Balance>,
516			VariantCountOf<T::RuntimeHoldReason>,
517		>,
518		ValueQuery,
519	>;
520
521	/// Freeze locks on account balances.
522	#[pallet::storage]
523	pub type Freezes<T: Config<I>, I: 'static = ()> = StorageMap<
524		_,
525		Blake2_128Concat,
526		T::AccountId,
527		BoundedVec<IdAmount<T::FreezeIdentifier, T::Balance>, T::MaxFreezes>,
528		ValueQuery,
529	>;
530
531	#[pallet::genesis_config]
532	pub struct GenesisConfig<T: Config<I>, I: 'static = ()> {
533		pub balances: Vec<(T::AccountId, T::Balance)>,
534		/// Derived development accounts(Optional):
535		/// - `u32`: The number of development accounts to generate.
536		/// - `T::Balance`: The initial balance assigned to each development account.
537		/// - `String`: An optional derivation(hard) string template.
538		/// - Must include `{}` as a placeholder for account indices.
539		/// - Defaults to `"//Sender//{}`" if `None`.
540		pub dev_accounts: Option<(u32, T::Balance, Option<String>)>,
541	}
542
543	impl<T: Config<I>, I: 'static> Default for GenesisConfig<T, I> {
544		fn default() -> Self {
545			Self { balances: Default::default(), dev_accounts: None }
546		}
547	}
548
549	#[pallet::genesis_build]
550	impl<T: Config<I>, I: 'static> BuildGenesisConfig for GenesisConfig<T, I> {
551		fn build(&self) {
552			let total = self.balances.iter().fold(Zero::zero(), |acc: T::Balance, &(_, n)| acc + n);
553
554			<TotalIssuance<T, I>>::put(total);
555
556			for (_, balance) in &self.balances {
557				assert!(
558					*balance >= <T as Config<I>>::ExistentialDeposit::get(),
559					"the balance of any account should always be at least the existential deposit.",
560				)
561			}
562
563			// ensure no duplicates exist.
564			let endowed_accounts = self
565				.balances
566				.iter()
567				.map(|(x, _)| x)
568				.cloned()
569				.collect::<alloc::collections::btree_set::BTreeSet<_>>();
570
571			assert!(
572				endowed_accounts.len() == self.balances.len(),
573				"duplicate balances in genesis."
574			);
575
576			// Generate additional dev accounts.
577			if let Some((num_accounts, balance, ref derivation)) = self.dev_accounts {
578				// Using the provided derivation string or default to `"//Sender//{}`".
579				Pallet::<T, I>::derive_dev_account(
580					num_accounts,
581					balance,
582					derivation.as_deref().unwrap_or(DEFAULT_ADDRESS_URI),
583				);
584			}
585			for &(ref who, free) in self.balances.iter() {
586				frame_system::Pallet::<T>::inc_providers(who);
587				assert!(T::AccountStore::insert(who, AccountData { free, ..Default::default() })
588					.is_ok());
589			}
590		}
591	}
592
593	#[pallet::hooks]
594	impl<T: Config<I>, I: 'static> Hooks<BlockNumberFor<T>> for Pallet<T, I> {
595		fn integrity_test() {
596			#[cfg(not(feature = "insecure_zero_ed"))]
597			assert!(
598				!<T as Config<I>>::ExistentialDeposit::get().is_zero(),
599				"The existential deposit must be greater than zero!"
600			);
601
602			assert!(
603				T::MaxFreezes::get() >= <T::RuntimeFreezeReason as VariantCount>::VARIANT_COUNT,
604				"MaxFreezes should be greater than or equal to the number of freeze reasons: {} < {}",
605				T::MaxFreezes::get(), <T::RuntimeFreezeReason as VariantCount>::VARIANT_COUNT,
606			);
607		}
608
609		#[cfg(feature = "try-runtime")]
610		fn try_state(n: BlockNumberFor<T>) -> Result<(), sp_runtime::TryRuntimeError> {
611			Self::do_try_state(n)
612		}
613	}
614
615	#[pallet::call(weight(<T as Config<I>>::WeightInfo))]
616	impl<T: Config<I>, I: 'static> Pallet<T, I> {
617		/// Transfer some liquid free balance to another account.
618		///
619		/// `transfer_allow_death` will set the `FreeBalance` of the sender and receiver.
620		/// If the sender's account is below the existential deposit as a result
621		/// of the transfer, the account will be reaped.
622		///
623		/// The dispatch origin for this call must be `Signed` by the transactor.
624		#[pallet::call_index(0)]
625		pub fn transfer_allow_death(
626			origin: OriginFor<T>,
627			dest: AccountIdLookupOf<T>,
628			#[pallet::compact] value: T::Balance,
629		) -> DispatchResult {
630			let source = ensure_signed(origin)?;
631			let dest = T::Lookup::lookup(dest)?;
632			<Self as fungible::Mutate<_>>::transfer(&source, &dest, value, Expendable)?;
633			Ok(())
634		}
635
636		/// Exactly as `transfer_allow_death`, except the origin must be root and the source account
637		/// may be specified.
638		#[pallet::call_index(2)]
639		pub fn force_transfer(
640			origin: OriginFor<T>,
641			source: AccountIdLookupOf<T>,
642			dest: AccountIdLookupOf<T>,
643			#[pallet::compact] value: T::Balance,
644		) -> DispatchResult {
645			ensure_root(origin)?;
646			let source = T::Lookup::lookup(source)?;
647			let dest = T::Lookup::lookup(dest)?;
648			<Self as fungible::Mutate<_>>::transfer(&source, &dest, value, Expendable)?;
649			Ok(())
650		}
651
652		/// Same as the [`transfer_allow_death`] call, but with a check that the transfer will not
653		/// kill the origin account.
654		///
655		/// 99% of the time you want [`transfer_allow_death`] instead.
656		///
657		/// [`transfer_allow_death`]: struct.Pallet.html#method.transfer
658		#[pallet::call_index(3)]
659		pub fn transfer_keep_alive(
660			origin: OriginFor<T>,
661			dest: AccountIdLookupOf<T>,
662			#[pallet::compact] value: T::Balance,
663		) -> DispatchResult {
664			let source = ensure_signed(origin)?;
665			let dest = T::Lookup::lookup(dest)?;
666			<Self as fungible::Mutate<_>>::transfer(&source, &dest, value, Preserve)?;
667			Ok(())
668		}
669
670		/// Transfer the entire transferable balance from the caller account.
671		///
672		/// NOTE: This function only attempts to transfer _transferable_ balances. This means that
673		/// any locked, reserved, or existential deposits (when `keep_alive` is `true`), will not be
674		/// transferred by this function. To ensure that this function results in a killed account,
675		/// you might need to prepare the account by removing any reference counters, storage
676		/// deposits, etc...
677		///
678		/// The dispatch origin of this call must be Signed.
679		///
680		/// - `dest`: The recipient of the transfer.
681		/// - `keep_alive`: A boolean to determine if the `transfer_all` operation should send all
682		///   of the funds the account has, causing the sender account to be killed (false), or
683		///   transfer everything except at least the existential deposit, which will guarantee to
684		///   keep the sender account alive (true).
685		#[pallet::call_index(4)]
686		pub fn transfer_all(
687			origin: OriginFor<T>,
688			dest: AccountIdLookupOf<T>,
689			keep_alive: bool,
690		) -> DispatchResult {
691			let transactor = ensure_signed(origin)?;
692			let keep_alive = if keep_alive { Preserve } else { Expendable };
693			let reducible_balance = <Self as fungible::Inspect<_>>::reducible_balance(
694				&transactor,
695				keep_alive,
696				Fortitude::Polite,
697			);
698			let dest = T::Lookup::lookup(dest)?;
699			<Self as fungible::Mutate<_>>::transfer(
700				&transactor,
701				&dest,
702				reducible_balance,
703				keep_alive,
704			)?;
705			Ok(())
706		}
707
708		/// Unreserve some balance from a user by force.
709		///
710		/// Can only be called by ROOT.
711		#[pallet::call_index(5)]
712		pub fn force_unreserve(
713			origin: OriginFor<T>,
714			who: AccountIdLookupOf<T>,
715			amount: T::Balance,
716		) -> DispatchResult {
717			ensure_root(origin)?;
718			let who = T::Lookup::lookup(who)?;
719			let _leftover = <Self as ReservableCurrency<_>>::unreserve(&who, amount);
720			Ok(())
721		}
722
723		/// Upgrade a specified account.
724		///
725		/// - `origin`: Must be `Signed`.
726		/// - `who`: The account to be upgraded.
727		///
728		/// This will waive the transaction fee if at least all but 10% of the accounts needed to
729		/// be upgraded. (We let some not have to be upgraded just in order to allow for the
730		/// possibility of churn).
731		#[pallet::call_index(6)]
732		#[pallet::weight(T::WeightInfo::upgrade_accounts(who.len() as u32))]
733		pub fn upgrade_accounts(
734			origin: OriginFor<T>,
735			who: Vec<T::AccountId>,
736		) -> DispatchResultWithPostInfo {
737			ensure_signed(origin)?;
738			if who.is_empty() {
739				return Ok(Pays::Yes.into())
740			}
741			let mut upgrade_count = 0;
742			for i in &who {
743				let upgraded = Self::ensure_upgraded(i);
744				if upgraded {
745					upgrade_count.saturating_inc();
746				}
747			}
748			let proportion_upgraded = Perbill::from_rational(upgrade_count, who.len() as u32);
749			if proportion_upgraded >= Perbill::from_percent(90) {
750				Ok(Pays::No.into())
751			} else {
752				Ok(Pays::Yes.into())
753			}
754		}
755
756		/// Set the regular balance of a given account.
757		///
758		/// The dispatch origin for this call is `root`.
759		#[pallet::call_index(8)]
760		#[pallet::weight(
761			T::WeightInfo::force_set_balance_creating() // Creates a new account.
762				.max(T::WeightInfo::force_set_balance_killing()) // Kills an existing account.
763		)]
764		pub fn force_set_balance(
765			origin: OriginFor<T>,
766			who: AccountIdLookupOf<T>,
767			#[pallet::compact] new_free: T::Balance,
768		) -> DispatchResult {
769			ensure_root(origin)?;
770			let who = T::Lookup::lookup(who)?;
771			let existential_deposit = Self::ed();
772
773			let wipeout = new_free < existential_deposit;
774			let new_free = if wipeout { Zero::zero() } else { new_free };
775
776			// First we try to modify the account's balance to the forced balance.
777			let old_free = Self::mutate_account_handling_dust(&who, false, |account| {
778				let old_free = account.free;
779				account.free = new_free;
780				old_free
781			})?;
782
783			// This will adjust the total issuance, which was not done by the `mutate_account`
784			// above.
785			if new_free > old_free {
786				mem::drop(PositiveImbalance::<T, I>::new(new_free - old_free));
787			} else if new_free < old_free {
788				mem::drop(NegativeImbalance::<T, I>::new(old_free - new_free));
789			}
790
791			Self::deposit_event(Event::BalanceSet { who, free: new_free });
792			Ok(())
793		}
794
795		/// Adjust the total issuance in a saturating way.
796		///
797		/// Can only be called by root and always needs a positive `delta`.
798		///
799		/// # Example
800		#[doc = docify::embed!("./src/tests/dispatchable_tests.rs", force_adjust_total_issuance_example)]
801		#[pallet::call_index(9)]
802		#[pallet::weight(T::WeightInfo::force_adjust_total_issuance())]
803		pub fn force_adjust_total_issuance(
804			origin: OriginFor<T>,
805			direction: AdjustmentDirection,
806			#[pallet::compact] delta: T::Balance,
807		) -> DispatchResult {
808			ensure_root(origin)?;
809
810			ensure!(delta > Zero::zero(), Error::<T, I>::DeltaZero);
811
812			let old = TotalIssuance::<T, I>::get();
813			let new = match direction {
814				AdjustmentDirection::Increase => old.saturating_add(delta),
815				AdjustmentDirection::Decrease => old.saturating_sub(delta),
816			};
817
818			ensure!(InactiveIssuance::<T, I>::get() <= new, Error::<T, I>::IssuanceDeactivated);
819			TotalIssuance::<T, I>::set(new);
820
821			Self::deposit_event(Event::<T, I>::TotalIssuanceForced { old, new });
822
823			Ok(())
824		}
825
826		/// Burn the specified liquid free balance from the origin account.
827		///
828		/// If the origin's account ends up below the existential deposit as a result
829		/// of the burn and `keep_alive` is false, the account will be reaped.
830		///
831		/// Unlike sending funds to a _burn_ address, which merely makes the funds inaccessible,
832		/// this `burn` operation will reduce total issuance by the amount _burned_.
833		#[pallet::call_index(10)]
834		#[pallet::weight(if *keep_alive {T::WeightInfo::burn_allow_death() } else {T::WeightInfo::burn_keep_alive()})]
835		pub fn burn(
836			origin: OriginFor<T>,
837			#[pallet::compact] value: T::Balance,
838			keep_alive: bool,
839		) -> DispatchResult {
840			let source = ensure_signed(origin)?;
841			let preservation = if keep_alive { Preserve } else { Expendable };
842			<Self as fungible::Mutate<_>>::burn_from(
843				&source,
844				value,
845				preservation,
846				Precision::Exact,
847				Polite,
848			)?;
849			Ok(())
850		}
851	}
852
853	impl<T: Config<I>, I: 'static> Pallet<T, I> {
854		/// Public function to get the total issuance.
855		pub fn total_issuance() -> T::Balance {
856			TotalIssuance::<T, I>::get()
857		}
858
859		/// Public function to get the inactive issuance.
860		pub fn inactive_issuance() -> T::Balance {
861			InactiveIssuance::<T, I>::get()
862		}
863
864		/// Public function to access the Locks storage.
865		pub fn locks(who: &T::AccountId) -> WeakBoundedVec<BalanceLock<T::Balance>, T::MaxLocks> {
866			Locks::<T, I>::get(who)
867		}
868
869		/// Public function to access the reserves storage.
870		pub fn reserves(
871			who: &T::AccountId,
872		) -> BoundedVec<ReserveData<T::ReserveIdentifier, T::Balance>, T::MaxReserves> {
873			Reserves::<T, I>::get(who)
874		}
875
876		fn ed() -> T::Balance {
877			T::ExistentialDeposit::get()
878		}
879		/// Ensure the account `who` is using the new logic.
880		///
881		/// Returns `true` if the account did get upgraded, `false` if it didn't need upgrading.
882		pub fn ensure_upgraded(who: &T::AccountId) -> bool {
883			let mut a = T::AccountStore::get(who);
884			if a.flags.is_new_logic() {
885				return false
886			}
887			a.flags.set_new_logic();
888			if !a.reserved.is_zero() && a.frozen.is_zero() {
889				if system::Pallet::<T>::providers(who) == 0 {
890					// Gah!! We have no provider refs :(
891					// This shouldn't practically happen, but we need a failsafe anyway: let's give
892					// them enough for an ED.
893					log::warn!(
894						target: LOG_TARGET,
895						"account with a non-zero reserve balance has no provider refs, account_id: '{:?}'.",
896						who
897					);
898					a.free = a.free.max(Self::ed());
899					system::Pallet::<T>::inc_providers(who);
900				}
901				let _ = system::Pallet::<T>::inc_consumers_without_limit(who).defensive();
902			}
903			// Should never fail - we're only setting a bit.
904			let _ = T::AccountStore::try_mutate_exists(who, |account| -> DispatchResult {
905				*account = Some(a);
906				Ok(())
907			});
908			Self::deposit_event(Event::Upgraded { who: who.clone() });
909			return true
910		}
911
912		/// Get the free balance of an account.
913		pub fn free_balance(who: impl core::borrow::Borrow<T::AccountId>) -> T::Balance {
914			Self::account(who.borrow()).free
915		}
916
917		/// Get the balance of an account that can be used for transfers, reservations, or any other
918		/// non-locking, non-transaction-fee activity. Will be at most `free_balance`.
919		pub fn usable_balance(who: impl core::borrow::Borrow<T::AccountId>) -> T::Balance {
920			<Self as fungible::Inspect<_>>::reducible_balance(who.borrow(), Expendable, Polite)
921		}
922
923		/// Get the balance of an account that can be used for paying transaction fees (not tipping,
924		/// or any other kind of fees, though). Will be at most `free_balance`.
925		///
926		/// This requires that the account stays alive.
927		pub fn usable_balance_for_fees(who: impl core::borrow::Borrow<T::AccountId>) -> T::Balance {
928			<Self as fungible::Inspect<_>>::reducible_balance(who.borrow(), Protect, Polite)
929		}
930
931		/// Get the reserved balance of an account.
932		pub fn reserved_balance(who: impl core::borrow::Borrow<T::AccountId>) -> T::Balance {
933			Self::account(who.borrow()).reserved
934		}
935
936		/// Get both the free and reserved balances of an account.
937		pub(crate) fn account(who: &T::AccountId) -> AccountData<T::Balance> {
938			T::AccountStore::get(who)
939		}
940
941		/// Mutate an account to some new value, or delete it entirely with `None`. Will enforce
942		/// `ExistentialDeposit` law, annulling the account as needed.
943		///
944		/// It returns the result from the closure. Any dust is handled through the low-level
945		/// `fungible::Unbalanced` trap-door for legacy dust management.
946		///
947		/// NOTE: Doesn't do any preparatory work for creating a new account, so should only be used
948		/// when it is known that the account already exists.
949		///
950		/// NOTE: LOW-LEVEL: This will not attempt to maintain total issuance. It is expected that
951		/// the caller will do this.
952		pub(crate) fn mutate_account_handling_dust<R>(
953			who: &T::AccountId,
954			force_consumer_bump: bool,
955			f: impl FnOnce(&mut AccountData<T::Balance>) -> R,
956		) -> Result<R, DispatchError> {
957			let (r, maybe_dust) = Self::mutate_account(who, force_consumer_bump, f)?;
958			if let Some(dust) = maybe_dust {
959				<Self as fungible::Unbalanced<_>>::handle_raw_dust(dust);
960			}
961			Ok(r)
962		}
963
964		/// Mutate an account to some new value, or delete it entirely with `None`. Will enforce
965		/// `ExistentialDeposit` law, annulling the account as needed.
966		///
967		/// It returns the result from the closure. Any dust is handled through the low-level
968		/// `fungible::Unbalanced` trap-door for legacy dust management.
969		///
970		/// NOTE: Doesn't do any preparatory work for creating a new account, so should only be used
971		/// when it is known that the account already exists.
972		///
973		/// NOTE: LOW-LEVEL: This will not attempt to maintain total issuance. It is expected that
974		/// the caller will do this.
975		pub(crate) fn try_mutate_account_handling_dust<R, E: From<DispatchError>>(
976			who: &T::AccountId,
977			force_consumer_bump: bool,
978			f: impl FnOnce(&mut AccountData<T::Balance>, bool) -> Result<R, E>,
979		) -> Result<R, E> {
980			let (r, maybe_dust) = Self::try_mutate_account(who, force_consumer_bump, f)?;
981			if let Some(dust) = maybe_dust {
982				<Self as fungible::Unbalanced<_>>::handle_raw_dust(dust);
983			}
984			Ok(r)
985		}
986
987		/// Mutate an account to some new value, or delete it entirely with `None`. Will enforce
988		/// `ExistentialDeposit` law, annulling the account as needed.
989		///
990		/// It returns both the result from the closure, and an optional amount of dust
991		/// which should be handled once it is known that all nested mutates that could affect
992		/// storage items what the dust handler touches have completed.
993		///
994		/// NOTE: Doesn't do any preparatory work for creating a new account, so should only be used
995		/// when it is known that the account already exists.
996		///
997		/// NOTE: LOW-LEVEL: This will not attempt to maintain total issuance. It is expected that
998		/// the caller will do this.
999		///
1000		/// NOTE: LOW-LEVEL: `force_consumer_bump` is mainly there to accomodate for locks, which
1001		/// have no ability in their API to return an error, and therefore better force increment
1002		/// the consumer, or else the system will be inconsistent. See `consumer_limits_tests`.
1003		pub(crate) fn mutate_account<R>(
1004			who: &T::AccountId,
1005			force_consumer_bump: bool,
1006			f: impl FnOnce(&mut AccountData<T::Balance>) -> R,
1007		) -> Result<(R, Option<T::Balance>), DispatchError> {
1008			Self::try_mutate_account(who, force_consumer_bump, |a, _| -> Result<R, DispatchError> {
1009				Ok(f(a))
1010			})
1011		}
1012
1013		/// Returns `true` when `who` has some providers or `insecure_zero_ed` feature is disabled.
1014		/// Returns `false` otherwise.
1015		#[cfg(not(feature = "insecure_zero_ed"))]
1016		fn have_providers_or_no_zero_ed(_: &T::AccountId) -> bool {
1017			true
1018		}
1019
1020		/// Returns `true` when `who` has some providers or `insecure_zero_ed` feature is disabled.
1021		/// Returns `false` otherwise.
1022		#[cfg(feature = "insecure_zero_ed")]
1023		fn have_providers_or_no_zero_ed(who: &T::AccountId) -> bool {
1024			frame_system::Pallet::<T>::providers(who) > 0
1025		}
1026
1027		/// Mutate an account to some new value, or delete it entirely with `None`. Will enforce
1028		/// `ExistentialDeposit` law, annulling the account as needed. This will do nothing if the
1029		/// result of `f` is an `Err`.
1030		///
1031		/// It returns both the result from the closure, and an optional amount of dust
1032		/// which should be handled once it is known that all nested mutates that could affect
1033		/// storage items what the dust handler touches have completed.
1034		///
1035		/// NOTE: Doesn't do any preparatory work for creating a new account, so should only be used
1036		/// when it is known that the account already exists.
1037		///
1038		/// NOTE: LOW-LEVEL: This will not attempt to maintain total issuance. It is expected that
1039		/// the caller will do this.
1040		pub(crate) fn try_mutate_account<R, E: From<DispatchError>>(
1041			who: &T::AccountId,
1042			force_consumer_bump: bool,
1043			f: impl FnOnce(&mut AccountData<T::Balance>, bool) -> Result<R, E>,
1044		) -> Result<(R, Option<T::Balance>), E> {
1045			Self::ensure_upgraded(who);
1046			let result = T::AccountStore::try_mutate_exists(who, |maybe_account| {
1047				let is_new = maybe_account.is_none();
1048				let mut account = maybe_account.take().unwrap_or_default();
1049				let did_provide =
1050					account.free >= Self::ed() && Self::have_providers_or_no_zero_ed(who);
1051				let did_consume =
1052					!is_new && (!account.reserved.is_zero() || !account.frozen.is_zero());
1053
1054				let result = f(&mut account, is_new)?;
1055
1056				let does_provide = account.free >= Self::ed();
1057				let does_consume = !account.reserved.is_zero() || !account.frozen.is_zero();
1058
1059				if !did_provide && does_provide {
1060					frame_system::Pallet::<T>::inc_providers(who);
1061				}
1062				if did_consume && !does_consume {
1063					frame_system::Pallet::<T>::dec_consumers(who);
1064				}
1065				if !did_consume && does_consume {
1066					if force_consumer_bump {
1067						// If we are forcing a consumer bump, we do it without limit.
1068						frame_system::Pallet::<T>::inc_consumers_without_limit(who)?;
1069					} else {
1070						frame_system::Pallet::<T>::inc_consumers(who)?;
1071					}
1072				}
1073				if does_consume && frame_system::Pallet::<T>::consumers(who) == 0 {
1074					// NOTE: This is a failsafe and should not happen for normal accounts. A normal
1075					// account should have gotten a consumer ref in `!did_consume && does_consume`
1076					// at some point.
1077					log::error!(target: LOG_TARGET, "Defensively bumping a consumer ref.");
1078					frame_system::Pallet::<T>::inc_consumers(who)?;
1079				}
1080				if did_provide && !does_provide {
1081					// This could reap the account so must go last.
1082					frame_system::Pallet::<T>::dec_providers(who).inspect_err(|_| {
1083						// best-effort revert consumer change.
1084						if did_consume && !does_consume {
1085							let _ = frame_system::Pallet::<T>::inc_consumers(who).defensive();
1086						}
1087						if !did_consume && does_consume {
1088							let _ = frame_system::Pallet::<T>::dec_consumers(who);
1089						}
1090					})?;
1091				}
1092
1093				let maybe_endowed = if is_new { Some(account.free) } else { None };
1094
1095				// Handle any steps needed after mutating an account.
1096				//
1097				// This includes DustRemoval unbalancing, in the case than the `new` account's total
1098				// balance is non-zero but below ED.
1099				//
1100				// Updates `maybe_account` to `Some` iff the account has sufficient balance.
1101				// Evaluates `maybe_dust`, which is `Some` containing the dust to be dropped, iff
1102				// some dust should be dropped.
1103				//
1104				// We should never be dropping if reserved is non-zero. Reserved being non-zero
1105				// should imply that we have a consumer ref, so this is economically safe.
1106				let ed = Self::ed();
1107				let maybe_dust = if account.free < ed && account.reserved.is_zero() {
1108					if account.free.is_zero() {
1109						None
1110					} else {
1111						Some(account.free)
1112					}
1113				} else {
1114					assert!(
1115						account.free.is_zero() || account.free >= ed || !account.reserved.is_zero()
1116					);
1117					*maybe_account = Some(account);
1118					None
1119				};
1120				Ok((maybe_endowed, maybe_dust, result))
1121			});
1122			result.map(|(maybe_endowed, maybe_dust, result)| {
1123				if let Some(endowed) = maybe_endowed {
1124					Self::deposit_event(Event::Endowed {
1125						account: who.clone(),
1126						free_balance: endowed,
1127					});
1128				}
1129				if let Some(amount) = maybe_dust {
1130					Pallet::<T, I>::deposit_event(Event::DustLost { account: who.clone(), amount });
1131				}
1132				(result, maybe_dust)
1133			})
1134		}
1135
1136		/// Update the account entry for `who`, given the locks.
1137		pub(crate) fn update_locks(who: &T::AccountId, locks: &[BalanceLock<T::Balance>]) {
1138			let bounded_locks = WeakBoundedVec::<_, T::MaxLocks>::force_from(
1139				locks.to_vec(),
1140				Some("Balances Update Locks"),
1141			);
1142
1143			if locks.len() as u32 > T::MaxLocks::get() {
1144				log::warn!(
1145					target: LOG_TARGET,
1146					"Warning: A user has more currency locks than expected. \
1147					A runtime configuration adjustment may be needed."
1148				);
1149			}
1150			let freezes = Freezes::<T, I>::get(who);
1151			let mut prev_frozen = Zero::zero();
1152			let mut after_frozen = Zero::zero();
1153			// We do not alter ED, so the account will not get dusted. Yet, consumer limit might be
1154			// full, therefore we pass `true` into `mutate_account` to make sure this cannot fail
1155			let res = Self::mutate_account(who, true, |b| {
1156				prev_frozen = b.frozen;
1157				b.frozen = Zero::zero();
1158				for l in locks.iter() {
1159					b.frozen = b.frozen.max(l.amount);
1160				}
1161				for l in freezes.iter() {
1162					b.frozen = b.frozen.max(l.amount);
1163				}
1164				after_frozen = b.frozen;
1165			});
1166			match res {
1167				Ok((_, None)) => {
1168					// expected -- all good.
1169				},
1170				Ok((_, Some(_dust))) => {
1171					Self::deposit_event(Event::Unexpected(UnexpectedKind::BalanceUpdated));
1172					defensive!("caused unexpected dusting/balance update.");
1173				},
1174				_ => {
1175					Self::deposit_event(Event::Unexpected(UnexpectedKind::FailedToMutateAccount));
1176					defensive!("errored in mutate_account");
1177				},
1178			}
1179
1180			match locks.is_empty() {
1181				true => Locks::<T, I>::remove(who),
1182				false => Locks::<T, I>::insert(who, bounded_locks),
1183			}
1184
1185			if prev_frozen > after_frozen {
1186				let amount = prev_frozen.saturating_sub(after_frozen);
1187				Self::deposit_event(Event::Unlocked { who: who.clone(), amount });
1188			} else if after_frozen > prev_frozen {
1189				let amount = after_frozen.saturating_sub(prev_frozen);
1190				Self::deposit_event(Event::Locked { who: who.clone(), amount });
1191			}
1192		}
1193
1194		/// Update the account entry for `who`, given the locks.
1195		pub(crate) fn update_freezes(
1196			who: &T::AccountId,
1197			freezes: BoundedSlice<IdAmount<T::FreezeIdentifier, T::Balance>, T::MaxFreezes>,
1198		) -> DispatchResult {
1199			let mut prev_frozen = Zero::zero();
1200			let mut after_frozen = Zero::zero();
1201			let (_, maybe_dust) = Self::mutate_account(who, false, |b| {
1202				prev_frozen = b.frozen;
1203				b.frozen = Zero::zero();
1204				for l in Locks::<T, I>::get(who).iter() {
1205					b.frozen = b.frozen.max(l.amount);
1206				}
1207				for l in freezes.iter() {
1208					b.frozen = b.frozen.max(l.amount);
1209				}
1210				after_frozen = b.frozen;
1211			})?;
1212			if maybe_dust.is_some() {
1213				Self::deposit_event(Event::Unexpected(UnexpectedKind::BalanceUpdated));
1214				defensive!("caused unexpected dusting/balance update.");
1215			}
1216			if freezes.is_empty() {
1217				Freezes::<T, I>::remove(who);
1218			} else {
1219				Freezes::<T, I>::insert(who, freezes);
1220			}
1221			if prev_frozen > after_frozen {
1222				let amount = prev_frozen.saturating_sub(after_frozen);
1223				Self::deposit_event(Event::Thawed { who: who.clone(), amount });
1224			} else if after_frozen > prev_frozen {
1225				let amount = after_frozen.saturating_sub(prev_frozen);
1226				Self::deposit_event(Event::Frozen { who: who.clone(), amount });
1227			}
1228			Ok(())
1229		}
1230
1231		/// Move the reserved balance of one account into the balance of another, according to
1232		/// `status`. This will respect freezes/locks only if `fortitude` is `Polite`.
1233		///
1234		/// Is a no-op if the value to be moved is zero.
1235		///
1236		/// NOTE: returns actual amount of transferred value in `Ok` case.
1237		pub(crate) fn do_transfer_reserved(
1238			slashed: &T::AccountId,
1239			beneficiary: &T::AccountId,
1240			value: T::Balance,
1241			precision: Precision,
1242			fortitude: Fortitude,
1243			status: Status,
1244		) -> Result<T::Balance, DispatchError> {
1245			if value.is_zero() {
1246				return Ok(Zero::zero())
1247			}
1248
1249			let max = <Self as fungible::InspectHold<_>>::reducible_total_balance_on_hold(
1250				slashed, fortitude,
1251			);
1252			let actual = match precision {
1253				Precision::BestEffort => value.min(max),
1254				Precision::Exact => value,
1255			};
1256			ensure!(actual <= max, TokenError::FundsUnavailable);
1257			if slashed == beneficiary {
1258				return match status {
1259					Status::Free => Ok(actual.saturating_sub(Self::unreserve(slashed, actual))),
1260					Status::Reserved => Ok(actual),
1261				}
1262			}
1263
1264			let ((_, maybe_dust_1), maybe_dust_2) = Self::try_mutate_account(
1265				beneficiary,
1266				false,
1267				|to_account, is_new| -> Result<((), Option<T::Balance>), DispatchError> {
1268					ensure!(!is_new, Error::<T, I>::DeadAccount);
1269					Self::try_mutate_account(slashed, false, |from_account, _| -> DispatchResult {
1270						match status {
1271							Status::Free =>
1272								to_account.free = to_account
1273									.free
1274									.checked_add(&actual)
1275									.ok_or(ArithmeticError::Overflow)?,
1276							Status::Reserved =>
1277								to_account.reserved = to_account
1278									.reserved
1279									.checked_add(&actual)
1280									.ok_or(ArithmeticError::Overflow)?,
1281						}
1282						from_account.reserved.saturating_reduce(actual);
1283						Ok(())
1284					})
1285				},
1286			)?;
1287
1288			if let Some(dust) = maybe_dust_1 {
1289				<Self as fungible::Unbalanced<_>>::handle_raw_dust(dust);
1290			}
1291			if let Some(dust) = maybe_dust_2 {
1292				<Self as fungible::Unbalanced<_>>::handle_raw_dust(dust);
1293			}
1294
1295			Self::deposit_event(Event::ReserveRepatriated {
1296				from: slashed.clone(),
1297				to: beneficiary.clone(),
1298				amount: actual,
1299				destination_status: status,
1300			});
1301			Ok(actual)
1302		}
1303
1304		/// Generate dev account from derivation(hard) string.
1305		pub fn derive_dev_account(num_accounts: u32, balance: T::Balance, derivation: &str) {
1306			// Ensure that the number of accounts is not zero.
1307			assert!(num_accounts > 0, "num_accounts must be greater than zero");
1308
1309			assert!(
1310				balance >= <T as Config<I>>::ExistentialDeposit::get(),
1311				"the balance of any account should always be at least the existential deposit.",
1312			);
1313
1314			assert!(
1315				derivation.contains("{}"),
1316				"Invalid derivation, expected `{{}}` as part of the derivation"
1317			);
1318
1319			for index in 0..num_accounts {
1320				// Replace "{}" in the derivation string with the index.
1321				let derivation_string = derivation.replace("{}", &index.to_string());
1322
1323				// Generate the key pair from the derivation string using sr25519.
1324				let pair: SrPair = Pair::from_string(&derivation_string, None)
1325					.expect(&format!("Failed to parse derivation string: {derivation_string}"));
1326
1327				// Convert the public key to AccountId.
1328				let who = T::AccountId::decode(&mut &pair.public().encode()[..])
1329					.expect(&format!("Failed to decode public key from pair: {:?}", pair.public()));
1330
1331				// Set the balance for the generated account.
1332				Self::mutate_account_handling_dust(&who, false, |account| {
1333					account.free = balance;
1334				})
1335				.expect(&format!("Failed to add account to keystore: {:?}", who));
1336			}
1337		}
1338	}
1339
1340	#[cfg(any(test, feature = "try-runtime"))]
1341	impl<T: Config<I>, I: 'static> Pallet<T, I> {
1342		pub(crate) fn do_try_state(
1343			_n: BlockNumberFor<T>,
1344		) -> Result<(), sp_runtime::TryRuntimeError> {
1345			Self::hold_and_freeze_count()?;
1346			Self::account_frozen_greater_than_locks()?;
1347			Self::account_frozen_greater_than_freezes()?;
1348			Ok(())
1349		}
1350
1351		fn hold_and_freeze_count() -> Result<(), sp_runtime::TryRuntimeError> {
1352			Holds::<T, I>::iter_keys().try_for_each(|k| {
1353				if Holds::<T, I>::decode_len(k).unwrap_or(0) >
1354					T::RuntimeHoldReason::VARIANT_COUNT as usize
1355				{
1356					Err("Found `Hold` with too many elements")
1357				} else {
1358					Ok(())
1359				}
1360			})?;
1361
1362			Freezes::<T, I>::iter_keys().try_for_each(|k| {
1363				if Freezes::<T, I>::decode_len(k).unwrap_or(0) > T::MaxFreezes::get() as usize {
1364					Err("Found `Freeze` with too many elements")
1365				} else {
1366					Ok(())
1367				}
1368			})?;
1369
1370			Ok(())
1371		}
1372
1373		fn account_frozen_greater_than_locks() -> Result<(), sp_runtime::TryRuntimeError> {
1374			Locks::<T, I>::iter().try_for_each(|(who, locks)| {
1375				let max_locks = locks.iter().map(|l| l.amount).max().unwrap_or_default();
1376				let frozen = T::AccountStore::get(&who).frozen;
1377				if max_locks > frozen {
1378					log::warn!(
1379						target: crate::LOG_TARGET,
1380						"Maximum lock of {:?} ({:?}) is greater than the frozen balance {:?}",
1381						who,
1382						max_locks,
1383						frozen
1384					);
1385					Err("bad locks".into())
1386				} else {
1387					Ok(())
1388				}
1389			})
1390		}
1391
1392		fn account_frozen_greater_than_freezes() -> Result<(), sp_runtime::TryRuntimeError> {
1393			Freezes::<T, I>::iter().try_for_each(|(who, freezes)| {
1394				let max_locks = freezes.iter().map(|l| l.amount).max().unwrap_or_default();
1395				let frozen = T::AccountStore::get(&who).frozen;
1396				if max_locks > frozen {
1397					log::warn!(
1398						target: crate::LOG_TARGET,
1399						"Maximum freeze of {:?} ({:?}) is greater than the frozen balance {:?}",
1400						who,
1401						max_locks,
1402						frozen
1403					);
1404					Err("bad freezes".into())
1405				} else {
1406					Ok(())
1407				}
1408			})
1409		}
1410	}
1411}