Skip to main content

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