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