referrerpolicy=no-referrer-when-downgrade

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