referrerpolicy=no-referrer-when-downgrade

pallet_balances/
impl_currency.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//! Implementations for the `Currency` family of traits.
19//!
20//! Note that `WithdrawReasons` are intentionally not used for anything in this implementation and
21//! are expected to be removed in the near future, once migration to `fungible::*` traits is done.
22
23use super::*;
24use frame_support::{
25	ensure,
26	pallet_prelude::DispatchResult,
27	traits::{
28		tokens::{fungible, BalanceStatus as Status, Fortitude::Polite, Precision::BestEffort},
29		Currency, DefensiveSaturating, ExistenceRequirement,
30		ExistenceRequirement::AllowDeath,
31		Get, Imbalance, InspectLockableCurrency, LockIdentifier, LockableCurrency,
32		NamedReservableCurrency, ReservableCurrency, SignedImbalance, TryDrop, WithdrawReasons,
33	},
34};
35use frame_system::pallet_prelude::BlockNumberFor;
36pub use imbalances::{NegativeImbalance, PositiveImbalance};
37use sp_runtime::traits::Bounded;
38
39// wrapping these imbalances in a private module is necessary to ensure absolute privacy
40// of the inner member.
41mod imbalances {
42	use super::*;
43	use alloc::boxed::Box;
44	use core::mem;
45	use frame_support::traits::{
46		tokens::imbalance::{
47			ImbalanceAccounting, TryMerge, UnsafeConstructorDestructor, UnsafeManualAccounting,
48		},
49		SameOrOther,
50	};
51
52	/// Opaque, move-only struct with private fields that serves as a token denoting that
53	/// funds have been created without any equal and opposite accounting.
54	#[must_use]
55	#[derive(Debug, PartialEq, Eq)]
56	pub struct PositiveImbalance<T: Config<I>, I: 'static = ()>(T::Balance);
57
58	impl<T: Config<I>, I: 'static> PositiveImbalance<T, I> {
59		/// Create a new positive imbalance from a balance.
60		pub fn new(amount: T::Balance) -> Self {
61			PositiveImbalance(amount)
62		}
63	}
64
65	/// Opaque, move-only struct with private fields that serves as a token denoting that
66	/// funds have been destroyed without any equal and opposite accounting.
67	#[must_use]
68	#[derive(Debug, PartialEq, Eq)]
69	pub struct NegativeImbalance<T: Config<I>, I: 'static = ()>(T::Balance);
70
71	impl<T, I> UnsafeConstructorDestructor<u128> for NegativeImbalance<T, I>
72	where
73		T: Config<I, Balance: From<u128> + Into<u128>>,
74		I: 'static,
75	{
76		fn unsafe_clone(&self) -> Box<dyn ImbalanceAccounting<u128>> {
77			Box::new(Self(self.0))
78		}
79		fn forget_imbalance(&mut self) -> u128 {
80			let amount = self.0.into();
81			self.0 = Zero::zero();
82			amount
83		}
84	}
85
86	impl<T, I> UnsafeManualAccounting<u128> for NegativeImbalance<T, I>
87	where
88		T: Config<I, Balance: From<u128> + Into<u128>>,
89		I: 'static,
90	{
91		fn saturating_subsume(&mut self, mut other: Box<dyn ImbalanceAccounting<u128>>) {
92			let amount = other.forget_imbalance();
93			self.0 = self.0.saturating_add(amount.into())
94		}
95	}
96
97	impl<T, I> ImbalanceAccounting<u128> for NegativeImbalance<T, I>
98	where
99		T: Config<I, Balance: From<u128> + Into<u128>>,
100		I: 'static,
101	{
102		fn amount(&self) -> u128 {
103			self.0.into()
104		}
105		fn saturating_take(&mut self, amount: u128) -> Box<dyn ImbalanceAccounting<u128>> {
106			Box::new(self.extract(amount.into()))
107		}
108	}
109
110	impl<T: Config<I>, I: 'static> NegativeImbalance<T, I> {
111		/// Create a new negative imbalance from a balance.
112		pub fn new(amount: T::Balance) -> Self {
113			NegativeImbalance(amount)
114		}
115	}
116
117	impl<T: Config<I>, I: 'static> TryDrop for PositiveImbalance<T, I> {
118		fn try_drop(self) -> result::Result<(), Self> {
119			self.drop_zero()
120		}
121	}
122
123	impl<T: Config<I>, I: 'static> Default for PositiveImbalance<T, I> {
124		fn default() -> Self {
125			Self::zero()
126		}
127	}
128
129	impl<T: Config<I>, I: 'static> Imbalance<T::Balance> for PositiveImbalance<T, I> {
130		type Opposite = NegativeImbalance<T, I>;
131
132		fn zero() -> Self {
133			Self(Zero::zero())
134		}
135		fn drop_zero(self) -> result::Result<(), Self> {
136			if self.0.is_zero() {
137				Ok(())
138			} else {
139				Err(self)
140			}
141		}
142		fn split(self, amount: T::Balance) -> (Self, Self) {
143			let first = self.0.min(amount);
144			let second = self.0 - first;
145
146			mem::forget(self);
147			(Self(first), Self(second))
148		}
149		fn extract(&mut self, amount: T::Balance) -> Self {
150			let new = self.0.min(amount);
151			self.0 = self.0 - new;
152			Self(new)
153		}
154		fn merge(mut self, other: Self) -> Self {
155			self.0 = self.0.saturating_add(other.0);
156			mem::forget(other);
157
158			self
159		}
160		fn subsume(&mut self, other: Self) {
161			self.0 = self.0.saturating_add(other.0);
162			mem::forget(other);
163		}
164		fn offset(self, other: Self::Opposite) -> SameOrOther<Self, Self::Opposite> {
165			let (a, b) = (self.0, other.0);
166			mem::forget((self, other));
167
168			if a > b {
169				SameOrOther::Same(Self(a - b))
170			} else if b > a {
171				SameOrOther::Other(NegativeImbalance::new(b - a))
172			} else {
173				SameOrOther::None
174			}
175		}
176		fn peek(&self) -> T::Balance {
177			self.0
178		}
179	}
180
181	impl<T: Config<I>, I: 'static> TryMerge for PositiveImbalance<T, I> {
182		fn try_merge(self, other: Self) -> Result<Self, (Self, Self)> {
183			Ok(self.merge(other))
184		}
185	}
186
187	impl<T: Config<I>, I: 'static> TryDrop for NegativeImbalance<T, I> {
188		fn try_drop(self) -> result::Result<(), Self> {
189			self.drop_zero()
190		}
191	}
192
193	impl<T: Config<I>, I: 'static> Default for NegativeImbalance<T, I> {
194		fn default() -> Self {
195			Self::zero()
196		}
197	}
198
199	impl<T: Config<I>, I: 'static> Imbalance<T::Balance> for NegativeImbalance<T, I> {
200		type Opposite = PositiveImbalance<T, I>;
201
202		fn zero() -> Self {
203			Self(Zero::zero())
204		}
205		fn drop_zero(self) -> result::Result<(), Self> {
206			if self.0.is_zero() {
207				Ok(())
208			} else {
209				Err(self)
210			}
211		}
212		fn split(self, amount: T::Balance) -> (Self, Self) {
213			let first = self.0.min(amount);
214			let second = self.0 - first;
215
216			mem::forget(self);
217			(Self(first), Self(second))
218		}
219		fn extract(&mut self, amount: T::Balance) -> Self {
220			let new = self.0.min(amount);
221			self.0 = self.0 - new;
222			Self(new)
223		}
224		fn merge(mut self, other: Self) -> Self {
225			self.0 = self.0.saturating_add(other.0);
226			mem::forget(other);
227
228			self
229		}
230		fn subsume(&mut self, other: Self) {
231			self.0 = self.0.saturating_add(other.0);
232			mem::forget(other);
233		}
234		fn offset(self, other: Self::Opposite) -> SameOrOther<Self, Self::Opposite> {
235			let (a, b) = (self.0, other.0);
236			mem::forget((self, other));
237
238			if a > b {
239				SameOrOther::Same(Self(a - b))
240			} else if b > a {
241				SameOrOther::Other(PositiveImbalance::new(b - a))
242			} else {
243				SameOrOther::None
244			}
245		}
246		fn peek(&self) -> T::Balance {
247			self.0
248		}
249	}
250
251	impl<T: Config<I>, I: 'static> TryMerge for NegativeImbalance<T, I> {
252		fn try_merge(self, other: Self) -> Result<Self, (Self, Self)> {
253			Ok(self.merge(other))
254		}
255	}
256
257	impl<T: Config<I>, I: 'static> Drop for PositiveImbalance<T, I> {
258		/// Basic drop handler will just square up the total issuance.
259		fn drop(&mut self) {
260			if !self.0.is_zero() {
261				<super::TotalIssuance<T, I>>::mutate(|v| *v = v.saturating_add(self.0));
262				Pallet::<T, I>::deposit_event(Event::<T, I>::Issued { amount: self.0 });
263			}
264		}
265	}
266
267	impl<T: Config<I>, I: 'static> Drop for NegativeImbalance<T, I> {
268		/// Basic drop handler will just square up the total issuance.
269		fn drop(&mut self) {
270			if !self.0.is_zero() {
271				<super::TotalIssuance<T, I>>::mutate(|v| *v = v.saturating_sub(self.0));
272				Pallet::<T, I>::deposit_event(Event::<T, I>::Rescinded { amount: self.0 });
273			}
274		}
275	}
276
277	impl<T: Config<I>, I: 'static> fungible::HandleImbalanceDrop<T::Balance>
278		for NegativeImbalance<T, I>
279	{
280		fn handle(amount: T::Balance) {
281			<super::TotalIssuance<T, I>>::mutate(|v| *v = v.saturating_sub(amount));
282			Pallet::<T, I>::deposit_event(Event::<T, I>::BurnedDebt { amount });
283		}
284	}
285
286	impl<T: Config<I>, I: 'static> fungible::HandleImbalanceDrop<T::Balance>
287		for PositiveImbalance<T, I>
288	{
289		fn handle(amount: T::Balance) {
290			<super::TotalIssuance<T, I>>::mutate(|v| *v = v.saturating_add(amount));
291			Pallet::<T, I>::deposit_event(Event::<T, I>::MintedCredit { amount });
292		}
293	}
294}
295
296impl<T: Config<I>, I: 'static> Currency<T::AccountId> for Pallet<T, I>
297where
298	T::Balance: MaybeSerializeDeserialize + Debug,
299{
300	type Balance = T::Balance;
301	type PositiveImbalance = PositiveImbalance<T, I>;
302	type NegativeImbalance = NegativeImbalance<T, I>;
303
304	fn total_balance(who: &T::AccountId) -> Self::Balance {
305		Self::account(who).total()
306	}
307
308	// Check if `value` amount of free balance can be slashed from `who`.
309	fn can_slash(who: &T::AccountId, value: Self::Balance) -> bool {
310		if value.is_zero() {
311			return true;
312		}
313		Self::free_balance(who) >= value
314	}
315
316	fn total_issuance() -> Self::Balance {
317		TotalIssuance::<T, I>::get()
318	}
319
320	fn active_issuance() -> Self::Balance {
321		<Self as fungible::Inspect<_>>::active_issuance()
322	}
323
324	fn deactivate(amount: Self::Balance) {
325		<Self as fungible::Unbalanced<_>>::deactivate(amount);
326	}
327
328	fn reactivate(amount: Self::Balance) {
329		<Self as fungible::Unbalanced<_>>::reactivate(amount);
330	}
331
332	fn minimum_balance() -> Self::Balance {
333		T::ExistentialDeposit::get()
334	}
335
336	// Burn funds from the total issuance, returning a positive imbalance for the amount burned.
337	// Is a no-op if amount to be burned is zero.
338	fn burn(mut amount: Self::Balance) -> Self::PositiveImbalance {
339		if amount.is_zero() {
340			return PositiveImbalance::zero();
341		}
342		<TotalIssuance<T, I>>::mutate(|issued| {
343			*issued = issued.checked_sub(&amount).unwrap_or_else(|| {
344				amount = *issued;
345				Zero::zero()
346			});
347		});
348
349		Pallet::<T, I>::deposit_event(Event::<T, I>::Rescinded { amount });
350		PositiveImbalance::new(amount)
351	}
352
353	// Create new funds into the total issuance, returning a negative imbalance
354	// for the amount issued.
355	// Is a no-op if amount to be issued it zero.
356	fn issue(mut amount: Self::Balance) -> Self::NegativeImbalance {
357		if amount.is_zero() {
358			return NegativeImbalance::zero();
359		}
360		<TotalIssuance<T, I>>::mutate(|issued| {
361			*issued = issued.checked_add(&amount).unwrap_or_else(|| {
362				amount = Self::Balance::max_value() - *issued;
363				Self::Balance::max_value()
364			})
365		});
366
367		Pallet::<T, I>::deposit_event(Event::<T, I>::Issued { amount });
368		NegativeImbalance::new(amount)
369	}
370
371	fn free_balance(who: &T::AccountId) -> Self::Balance {
372		Self::account(who).free
373	}
374
375	// Ensure that an account can withdraw from their free balance given any existing withdrawal
376	// restrictions like locks and vesting balance.
377	// Is a no-op if amount to be withdrawn is zero.
378	fn ensure_can_withdraw(
379		who: &T::AccountId,
380		amount: T::Balance,
381		_reasons: WithdrawReasons,
382		new_balance: T::Balance,
383	) -> DispatchResult {
384		if amount.is_zero() {
385			return Ok(());
386		}
387		ensure!(new_balance >= Self::account(who).frozen, Error::<T, I>::LiquidityRestrictions);
388		Ok(())
389	}
390
391	// Transfer some free balance from `transactor` to `dest`, respecting existence requirements.
392	// Is a no-op if value to be transferred is zero or the `transactor` is the same as `dest`.
393	fn transfer(
394		transactor: &T::AccountId,
395		dest: &T::AccountId,
396		value: Self::Balance,
397		existence_requirement: ExistenceRequirement,
398	) -> DispatchResult {
399		if value.is_zero() || transactor == dest {
400			return Ok(());
401		}
402		let keep_alive = match existence_requirement {
403			ExistenceRequirement::KeepAlive => Preserve,
404			ExistenceRequirement::AllowDeath => Expendable,
405		};
406		<Self as fungible::Mutate<_>>::transfer(transactor, dest, value, keep_alive)?;
407		Ok(())
408	}
409
410	/// Slash a target account `who`, returning the negative imbalance created and any left over
411	/// amount that could not be slashed.
412	///
413	/// Is a no-op if `value` to be slashed is zero or the account does not exist.
414	///
415	/// NOTE: `slash()` prefers free balance, but assumes that reserve balance can be drawn
416	/// from in extreme circumstances. `can_slash()` should be used prior to `slash()` to avoid
417	/// having to draw from reserved funds, however we err on the side of punishment if things are
418	/// inconsistent or `can_slash` wasn't used appropriately.
419	fn slash(who: &T::AccountId, value: Self::Balance) -> (Self::NegativeImbalance, Self::Balance) {
420		if value.is_zero() {
421			return (NegativeImbalance::zero(), Zero::zero());
422		}
423		if Self::total_balance(who).is_zero() {
424			return (NegativeImbalance::zero(), value);
425		}
426
427		let result = match Self::try_mutate_account_handling_dust(
428			who,
429			false,
430			|account, _is_new| -> Result<(Self::NegativeImbalance, Self::Balance), DispatchError> {
431				// Best value is the most amount we can slash following liveness rules.
432				let ed = T::ExistentialDeposit::get();
433				let actual = match system::Pallet::<T>::can_dec_provider(who) {
434					true => value.min(account.free),
435					false => value.min(account.free.saturating_sub(ed)),
436				};
437				account.free.saturating_reduce(actual);
438				let remaining = value.saturating_sub(actual);
439				Ok((NegativeImbalance::new(actual), remaining))
440			},
441		) {
442			Ok((imbalance, remaining)) => {
443				Self::deposit_event(Event::Slashed {
444					who: who.clone(),
445					amount: value.saturating_sub(remaining),
446				});
447				(imbalance, remaining)
448			},
449			Err(_) => (Self::NegativeImbalance::zero(), value),
450		};
451		result
452	}
453
454	/// Deposit some `value` into the free balance of an existing target account `who`.
455	///
456	/// Is a no-op if the `value` to be deposited is zero.
457	fn deposit_into_existing(
458		who: &T::AccountId,
459		value: Self::Balance,
460	) -> Result<Self::PositiveImbalance, DispatchError> {
461		if value.is_zero() {
462			return Ok(PositiveImbalance::zero());
463		}
464
465		Self::try_mutate_account_handling_dust(
466			who,
467			false,
468			|account, is_new| -> Result<Self::PositiveImbalance, DispatchError> {
469				ensure!(!is_new, Error::<T, I>::DeadAccount);
470				account.free = account.free.checked_add(&value).ok_or(ArithmeticError::Overflow)?;
471				Self::deposit_event(Event::Deposit { who: who.clone(), amount: value });
472				Ok(PositiveImbalance::new(value))
473			},
474		)
475	}
476
477	/// Deposit some `value` into the free balance of `who`, possibly creating a new account.
478	///
479	/// This function is a no-op if:
480	/// - the `value` to be deposited is zero; or
481	/// - the `value` to be deposited is less than the required ED and the account does not yet
482	///   exist; or
483	/// - the deposit would necessitate the account to exist and there are no provider references;
484	///   or
485	/// - `value` is so large it would cause the balance of `who` to overflow.
486	fn deposit_creating(who: &T::AccountId, value: Self::Balance) -> Self::PositiveImbalance {
487		if value.is_zero() {
488			return Self::PositiveImbalance::zero();
489		}
490
491		Self::try_mutate_account_handling_dust(
492			who,
493			false,
494			|account, is_new| -> Result<Self::PositiveImbalance, DispatchError> {
495				let ed = T::ExistentialDeposit::get();
496				ensure!(value >= ed || !is_new, Error::<T, I>::ExistentialDeposit);
497
498				// defensive only: overflow should never happen, however in case it does, then this
499				// operation is a no-op.
500				account.free = match account.free.checked_add(&value) {
501					Some(x) => x,
502					None => return Ok(Self::PositiveImbalance::zero()),
503				};
504
505				Self::deposit_event(Event::Deposit { who: who.clone(), amount: value });
506				Ok(PositiveImbalance::new(value))
507			},
508		)
509		.unwrap_or_else(|_| Self::PositiveImbalance::zero())
510	}
511
512	/// Withdraw some free balance from an account, respecting existence requirements.
513	///
514	/// Is a no-op if value to be withdrawn is zero.
515	fn withdraw(
516		who: &T::AccountId,
517		value: Self::Balance,
518		reasons: WithdrawReasons,
519		liveness: ExistenceRequirement,
520	) -> result::Result<Self::NegativeImbalance, DispatchError> {
521		if value.is_zero() {
522			return Ok(NegativeImbalance::zero());
523		}
524
525		Self::try_mutate_account_handling_dust(
526			who,
527			false,
528			|account, _| -> Result<Self::NegativeImbalance, DispatchError> {
529				let new_free_account =
530					account.free.checked_sub(&value).ok_or(Error::<T, I>::InsufficientBalance)?;
531
532				// bail if we need to keep the account alive and this would kill it.
533				let ed = T::ExistentialDeposit::get();
534				let would_be_dead = new_free_account < ed;
535				let would_kill = would_be_dead && account.free >= ed;
536				ensure!(liveness == AllowDeath || !would_kill, Error::<T, I>::Expendability);
537
538				Self::ensure_can_withdraw(who, value, reasons, new_free_account)?;
539
540				account.free = new_free_account;
541
542				Self::deposit_event(Event::Withdraw { who: who.clone(), amount: value });
543				Ok(NegativeImbalance::new(value))
544			},
545		)
546	}
547
548	/// Force the new free balance of a target account `who` to some new value `balance`.
549	fn make_free_balance_be(
550		who: &T::AccountId,
551		value: Self::Balance,
552	) -> SignedImbalance<Self::Balance, Self::PositiveImbalance> {
553		Self::try_mutate_account_handling_dust(
554			who,
555			false,
556			|account,
557			 is_new|
558			 -> Result<SignedImbalance<Self::Balance, Self::PositiveImbalance>, DispatchError> {
559				let ed = T::ExistentialDeposit::get();
560				// If we're attempting to set an existing account to less than ED, then
561				// bypass the entire operation. It's a no-op if you follow it through, but
562				// since this is an instance where we might account for a negative imbalance
563				// (in the dust cleaner of set_account) before we account for its actual
564				// equal and opposite cause (returned as an Imbalance), then in the
565				// instance that there's no other accounts on the system at all, we might
566				// underflow the issuance and our arithmetic will be off.
567				ensure!(value >= ed || !is_new, Error::<T, I>::ExistentialDeposit);
568
569				let imbalance = if account.free <= value {
570					SignedImbalance::Positive(PositiveImbalance::new(value - account.free))
571				} else {
572					SignedImbalance::Negative(NegativeImbalance::new(account.free - value))
573				};
574				account.free = value;
575				Self::deposit_event(Event::BalanceSet { who: who.clone(), free: account.free });
576				Ok(imbalance)
577			},
578		)
579		.unwrap_or_else(|_| SignedImbalance::Positive(Self::PositiveImbalance::zero()))
580	}
581}
582
583/// Validates whether an account can create a reserve without violating
584/// liquidity constraints.
585///
586/// This method performs liquidity checks without modifying the account state.
587fn ensure_can_reserve<T: Config<I>, I: 'static>(
588	who: &T::AccountId,
589	value: T::Balance,
590	check_existential_deposit: bool,
591) -> DispatchResult {
592	let AccountData { free, .. } = Pallet::<T, I>::account(who);
593
594	// Early validation: Check sufficient free balance
595	let new_free_balance = free.checked_sub(&value).ok_or(Error::<T, I>::InsufficientBalance)?;
596
597	// Conditionally validate existential deposit preservation
598	if check_existential_deposit {
599		let existential_deposit = T::ExistentialDeposit::get();
600		ensure!(new_free_balance >= existential_deposit, Error::<T, I>::Expendability);
601	}
602
603	Ok(())
604}
605
606impl<T: Config<I>, I: 'static> ReservableCurrency<T::AccountId> for Pallet<T, I>
607where
608	T::Balance: MaybeSerializeDeserialize + Debug,
609{
610	/// Check if `who` can reserve `value` from their free balance.
611	///
612	/// Always `true` if value to be reserved is zero.
613	fn can_reserve(who: &T::AccountId, value: Self::Balance) -> bool {
614		if value.is_zero() {
615			return true;
616		}
617		ensure_can_reserve::<T, I>(who, value, true).is_ok()
618	}
619
620	fn reserved_balance(who: &T::AccountId) -> Self::Balance {
621		Self::account(who).reserved
622	}
623
624	/// Move `value` from the free balance from `who` to their reserved balance.
625	///
626	/// Is a no-op if value to be reserved is zero.
627	fn reserve(who: &T::AccountId, value: Self::Balance) -> DispatchResult {
628		if value.is_zero() {
629			return Ok(());
630		}
631
632		Self::try_mutate_account_handling_dust(who, false, |account, _| -> DispatchResult {
633			account.free =
634				account.free.checked_sub(&value).ok_or(Error::<T, I>::InsufficientBalance)?;
635			account.reserved =
636				account.reserved.checked_add(&value).ok_or(ArithmeticError::Overflow)?;
637
638			// Check if it is possible to reserve before trying to mutate the account
639			ensure_can_reserve::<T, I>(who, value, false)
640		})?;
641
642		Self::deposit_event(Event::Reserved { who: who.clone(), amount: value });
643		Ok(())
644	}
645
646	/// Unreserve some funds, returning any amount that was unable to be unreserved.
647	///
648	/// Only acts on the part of the reserved balance that does not back a hold or a named reserve.
649	///
650	/// Is a no-op if the value to be unreserved is zero or the account does not exist.
651	///
652	/// NOTE: returns amount value which wasn't successfully unreserved.
653	fn unreserve(who: &T::AccountId, value: Self::Balance) -> Self::Balance {
654		Self::do_unreserve(who, value, None)
655	}
656
657	/// Slash from reserved balance, returning the negative imbalance created,
658	/// and any amount that was unable to be slashed.
659	///
660	/// Only acts on the part of the reserved balance that does not back a hold or a named reserve.
661	///
662	/// Is a no-op if the value to be slashed is zero or the account does not exist.
663	fn slash_reserved(
664		who: &T::AccountId,
665		value: Self::Balance,
666	) -> (Self::NegativeImbalance, Self::Balance) {
667		Self::do_slash_reserved(who, value, None)
668	}
669
670	/// Move the reserved balance of one account into the balance of another, according to `status`.
671	///
672	/// Only acts on the part of `slashed`'s reserved balance that does not back a hold or a named
673	/// reserve.
674	///
675	/// Is a no-op if:
676	/// - the value to be moved is zero; or
677	/// - the `slashed` id equal to `beneficiary` and the `status` is `Reserved`.
678	///
679	/// This is `Polite` and thus will not repatriate any funds which would lead the total balance
680	/// to be less than the frozen amount. Returns `Ok` with the amount that could not be moved,
681	/// which may be non-zero since the operation is done on a `BestEffort` basis.
682	fn repatriate_reserved(
683		slashed: &T::AccountId,
684		beneficiary: &T::AccountId,
685		value: Self::Balance,
686		status: Status,
687	) -> Result<Self::Balance, DispatchError> {
688		Self::do_repatriate_reserved(slashed, beneficiary, value, status, None)
689	}
690}
691
692/// The [`ReservableCurrency`] operations, for both the unnamed and the named reserves.
693///
694/// The unnamed operations pass `None` as `id`, the named ones pass their own reserve.
695impl<T: Config<I>, I: 'static> Pallet<T, I>
696where
697	T::Balance: MaybeSerializeDeserialize + Debug,
698{
699	/// [`ReservableCurrency::unreserve`], acting on at most `max_reserved_touchable(who, id)`.
700	pub(crate) fn do_unreserve(
701		who: &T::AccountId,
702		value: T::Balance,
703		id: Option<&T::ReserveIdentifier>,
704	) -> T::Balance {
705		if value.is_zero() {
706			return Zero::zero();
707		}
708		if <Self as Currency<_>>::total_balance(who).is_zero() {
709			return value;
710		}
711
712		let max = Self::max_reserved_touchable(who, id);
713		let actual = match Self::mutate_account_handling_dust(who, false, |account| {
714			let actual = value.min(max).min(account.reserved);
715			account.reserved -= actual;
716			// defensive only: this can never fail since total issuance which is at least
717			// free+reserved fits into the same data type.
718			account.free = account.free.defensive_saturating_add(actual);
719			actual
720		}) {
721			Ok(x) => x,
722			Err(_) => {
723				// This should never happen since we don't alter the total amount in the account.
724				// If it ever does, then we should fail gracefully though, indicating that nothing
725				// could be done.
726				return value;
727			},
728		};
729
730		Self::deposit_event(Event::Unreserved { who: who.clone(), amount: actual });
731		value - actual
732	}
733
734	/// [`ReservableCurrency::slash_reserved`], acting on at most
735	/// `max_reserved_touchable(who, id)`.
736	pub(crate) fn do_slash_reserved(
737		who: &T::AccountId,
738		value: T::Balance,
739		id: Option<&T::ReserveIdentifier>,
740	) -> (NegativeImbalance<T, I>, T::Balance) {
741		if value.is_zero() {
742			return (NegativeImbalance::zero(), Zero::zero());
743		}
744		if <Self as Currency<_>>::total_balance(who).is_zero() {
745			return (NegativeImbalance::zero(), value);
746		}
747
748		// NOTE: `mutate_account` may fail if it attempts to reduce the balance to the point that an
749		//   account is attempted to be illegally destroyed.
750
751		let max = Self::max_reserved_touchable(who, id);
752		match Self::mutate_account_handling_dust(who, false, |account| {
753			let actual = value.min(max).min(account.reserved);
754			account.reserved.saturating_reduce(actual);
755
756			// underflow should never happen, but it if does, there's nothing to be done here.
757			(NegativeImbalance::new(actual), value.saturating_sub(actual))
758		}) {
759			Ok((imbalance, not_slashed)) => {
760				Self::deposit_event(Event::Slashed {
761					who: who.clone(),
762					amount: value.saturating_sub(not_slashed),
763				});
764				(imbalance, not_slashed)
765			},
766			Err(_) => (NegativeImbalance::zero(), value),
767		}
768	}
769
770	/// [`ReservableCurrency::repatriate_reserved`], acting on at most
771	/// `max_reserved_touchable(slashed, id)`.
772	pub(crate) fn do_repatriate_reserved(
773		slashed: &T::AccountId,
774		beneficiary: &T::AccountId,
775		value: T::Balance,
776		status: Status,
777		id: Option<&T::ReserveIdentifier>,
778	) -> Result<T::Balance, DispatchError> {
779		let actual = Self::do_transfer_reserved(
780			slashed,
781			beneficiary,
782			value,
783			BestEffort,
784			Polite,
785			status,
786			id,
787		)?;
788		Ok(value.saturating_sub(actual))
789	}
790}
791
792impl<T: Config<I>, I: 'static> NamedReservableCurrency<T::AccountId> for Pallet<T, I>
793where
794	T::Balance: MaybeSerializeDeserialize + Debug,
795{
796	type ReserveIdentifier = T::ReserveIdentifier;
797
798	fn reserved_balance_named(id: &Self::ReserveIdentifier, who: &T::AccountId) -> Self::Balance {
799		let reserves = Self::reserves(who);
800		reserves
801			.binary_search_by_key(id, |data| data.id)
802			.map(|index| reserves[index].amount)
803			.unwrap_or_default()
804	}
805
806	/// Move `value` from the free balance from `who` to a named reserve balance.
807	///
808	/// Is a no-op if value to be reserved is zero.
809	fn reserve_named(
810		id: &Self::ReserveIdentifier,
811		who: &T::AccountId,
812		value: Self::Balance,
813	) -> DispatchResult {
814		if value.is_zero() {
815			return Ok(());
816		}
817
818		Reserves::<T, I>::try_mutate(who, |reserves| -> DispatchResult {
819			match reserves.binary_search_by_key(id, |data| data.id) {
820				Ok(index) => {
821					reserves[index].amount = reserves[index]
822						.amount
823						.checked_add(&value)
824						.ok_or(ArithmeticError::Overflow)?;
825				},
826				Err(index) => {
827					reserves
828						.try_insert(index, ReserveData { id: *id, amount: value })
829						.map_err(|_| Error::<T, I>::TooManyReserves)?;
830				},
831			};
832			<Self as ReservableCurrency<_>>::reserve(who, value)?;
833			Ok(())
834		})
835	}
836
837	/// Unreserve some funds, returning any amount that was unable to be unreserved.
838	///
839	/// Is a no-op if the value to be unreserved is zero.
840	fn unreserve_named(
841		id: &Self::ReserveIdentifier,
842		who: &T::AccountId,
843		value: Self::Balance,
844	) -> Self::Balance {
845		if value.is_zero() {
846			return Zero::zero();
847		}
848
849		Reserves::<T, I>::mutate_exists(who, |maybe_reserves| -> Self::Balance {
850			if let Some(reserves) = maybe_reserves.as_mut() {
851				match reserves.binary_search_by_key(id, |data| data.id) {
852					Ok(index) => {
853						let to_change = cmp::min(reserves[index].amount, value);
854
855						let remain = Self::do_unreserve(who, to_change, Some(id));
856
857						// remain should always be zero but just to be defensive here.
858						let actual = to_change.defensive_saturating_sub(remain);
859
860						// `actual <= to_change` and `to_change <= amount`; qed;
861						reserves[index].amount -= actual;
862
863						if reserves[index].amount.is_zero() {
864							if reserves.len() == 1 {
865								// no more named reserves
866								*maybe_reserves = None;
867							} else {
868								// remove this named reserve
869								reserves.remove(index);
870							}
871						}
872
873						value - actual
874					},
875					Err(_) => value,
876				}
877			} else {
878				value
879			}
880		})
881	}
882
883	/// Slash from reserved balance, returning the negative imbalance created,
884	/// and any amount that was unable to be slashed.
885	///
886	/// Is a no-op if the value to be slashed is zero.
887	fn slash_reserved_named(
888		id: &Self::ReserveIdentifier,
889		who: &T::AccountId,
890		value: Self::Balance,
891	) -> (Self::NegativeImbalance, Self::Balance) {
892		if value.is_zero() {
893			return (NegativeImbalance::zero(), Zero::zero());
894		}
895
896		Reserves::<T, I>::mutate_exists(
897			who,
898			|maybe_reserves| -> (Self::NegativeImbalance, Self::Balance) {
899				let Some(reserves) = maybe_reserves.as_mut() else {
900					return (NegativeImbalance::zero(), value);
901				};
902				match reserves.binary_search_by_key(id, |data| data.id) {
903					Ok(index) => {
904						let to_change = cmp::min(reserves[index].amount, value);
905
906						let (imb, remain) = Self::do_slash_reserved(who, to_change, Some(id));
907
908						// remain should always be zero but just to be defensive here.
909						let actual = to_change.defensive_saturating_sub(remain);
910
911						// `actual <= to_change` and `to_change <= amount`; qed;
912						reserves[index].amount -= actual;
913
914						if reserves[index].amount.is_zero() {
915							if reserves.len() == 1 {
916								// no more named reserves
917								*maybe_reserves = None;
918							} else {
919								// remove this named reserve
920								reserves.remove(index);
921							}
922						}
923
924						(imb, value - actual)
925					},
926					Err(_) => (NegativeImbalance::zero(), value),
927				}
928			},
929		)
930	}
931
932	/// Move the reserved balance of one account into the balance of another, according to `status`.
933	/// If `status` is `Reserved`, the balance will be reserved with given `id`.
934	///
935	/// Is a no-op if:
936	/// - the value to be moved is zero; or
937	/// - the `slashed` id equal to `beneficiary` and the `status` is `Reserved`.
938	fn repatriate_reserved_named(
939		id: &Self::ReserveIdentifier,
940		slashed: &T::AccountId,
941		beneficiary: &T::AccountId,
942		value: Self::Balance,
943		status: Status,
944	) -> Result<Self::Balance, DispatchError> {
945		if value.is_zero() {
946			return Ok(Zero::zero());
947		}
948
949		if slashed == beneficiary {
950			return match status {
951				Status::Free => Ok(Self::unreserve_named(id, slashed, value)),
952				Status::Reserved => {
953					Ok(value.saturating_sub(Self::reserved_balance_named(id, slashed)))
954				},
955			};
956		}
957
958		Reserves::<T, I>::try_mutate_exists(
959			slashed,
960			|maybe_reserves| -> Result<Self::Balance, DispatchError> {
961				let Some(reserves) = maybe_reserves.as_mut() else { return Ok(value) };
962				let Ok(index) = reserves.binary_search_by_key(id, |data| data.id) else {
963					return Ok(value);
964				};
965
966				let to_change = cmp::min(reserves[index].amount, value);
967
968				let actual = match status {
969					Status::Reserved => {
970						// make it the reserved under same identifier
971						Reserves::<T, I>::try_mutate_exists(
972							beneficiary,
973							|maybe_reserves| -> Result<T::Balance, DispatchError> {
974								let reserves = maybe_reserves.get_or_insert_default();
975								let actual = match reserves.binary_search_by_key(id, |data| data.id)
976								{
977									Ok(index) => {
978										let remain = Self::do_repatriate_reserved(
979											slashed,
980											beneficiary,
981											to_change,
982											status,
983											Some(id),
984										)?;
985
986										// remain should always be zero but just to be defensive
987										// here.
988										let actual = to_change.defensive_saturating_sub(remain);
989
990										// this add can't overflow but just to be defensive.
991										reserves[index].amount =
992											reserves[index].amount.defensive_saturating_add(actual);
993
994										actual
995									},
996									Err(index) => {
997										let remain = Self::do_repatriate_reserved(
998											slashed,
999											beneficiary,
1000											to_change,
1001											status,
1002											Some(id),
1003										)?;
1004
1005										// remain should always be zero but just to be defensive
1006										// here
1007										let actual = to_change.defensive_saturating_sub(remain);
1008
1009										if !actual.is_zero() {
1010											reserves
1011												.try_insert(
1012													index,
1013													ReserveData { id: *id, amount: actual },
1014												)
1015												.map_err(|_| Error::<T, I>::TooManyReserves)?;
1016										}
1017
1018										actual
1019									},
1020								};
1021
1022								if reserves.is_empty() {
1023									*maybe_reserves = None;
1024								}
1025
1026								Ok(actual)
1027							},
1028						)?
1029					},
1030					Status::Free => {
1031						let remain = Self::do_repatriate_reserved(
1032							slashed,
1033							beneficiary,
1034							to_change,
1035							status,
1036							Some(id),
1037						)?;
1038
1039						// remain should always be zero but just to be defensive here
1040						to_change.defensive_saturating_sub(remain)
1041					},
1042				};
1043
1044				// `actual <= to_change` and `to_change <= amount`; qed;
1045				reserves[index].amount -= actual;
1046
1047				if reserves[index].amount.is_zero() {
1048					if reserves.len() == 1 {
1049						// no more named reserves
1050						*maybe_reserves = None;
1051					} else {
1052						// remove this named reserve
1053						reserves.remove(index);
1054					}
1055				}
1056
1057				Ok(value - actual)
1058			},
1059		)
1060	}
1061}
1062
1063impl<T: Config<I>, I: 'static> LockableCurrency<T::AccountId> for Pallet<T, I>
1064where
1065	T::Balance: MaybeSerializeDeserialize + Debug,
1066{
1067	type Moment = BlockNumberFor<T>;
1068
1069	type MaxLocks = T::MaxLocks;
1070
1071	// Set or alter a lock on the balance of `who`.
1072	fn set_lock(
1073		id: LockIdentifier,
1074		who: &T::AccountId,
1075		amount: T::Balance,
1076		reasons: WithdrawReasons,
1077	) {
1078		if reasons.is_empty() || amount.is_zero() {
1079			Self::remove_lock(id, who);
1080			return;
1081		}
1082
1083		let mut new_lock = Some(BalanceLock { id, amount, reasons: reasons.into() });
1084		let mut locks = Self::locks(who)
1085			.into_iter()
1086			.filter_map(|l| if l.id == id { new_lock.take() } else { Some(l) })
1087			.collect::<Vec<_>>();
1088		if let Some(lock) = new_lock {
1089			locks.push(lock)
1090		}
1091		Self::update_locks(who, &locks[..]);
1092	}
1093
1094	// Extend a lock on the balance of `who`.
1095	// Is a no-op if lock amount is zero or `reasons` `is_none()`.
1096	fn extend_lock(
1097		id: LockIdentifier,
1098		who: &T::AccountId,
1099		amount: T::Balance,
1100		reasons: WithdrawReasons,
1101	) {
1102		if amount.is_zero() || reasons.is_empty() {
1103			return;
1104		}
1105		let mut new_lock = Some(BalanceLock { id, amount, reasons: reasons.into() });
1106		let mut locks = Self::locks(who)
1107			.into_iter()
1108			.filter_map(|l| {
1109				if l.id == id {
1110					new_lock.take().map(|nl| BalanceLock {
1111						id: l.id,
1112						amount: l.amount.max(nl.amount),
1113						reasons: l.reasons | nl.reasons,
1114					})
1115				} else {
1116					Some(l)
1117				}
1118			})
1119			.collect::<Vec<_>>();
1120		if let Some(lock) = new_lock {
1121			locks.push(lock)
1122		}
1123		Self::update_locks(who, &locks[..]);
1124	}
1125
1126	fn remove_lock(id: LockIdentifier, who: &T::AccountId) {
1127		let mut locks = Self::locks(who);
1128		locks.retain(|l| l.id != id);
1129		Self::update_locks(who, &locks[..]);
1130	}
1131}
1132
1133impl<T: Config<I>, I: 'static> InspectLockableCurrency<T::AccountId> for Pallet<T, I> {
1134	fn balance_locked(id: LockIdentifier, who: &T::AccountId) -> Self::Balance {
1135		Self::locks(who)
1136			.into_iter()
1137			.filter(|l| l.id == id)
1138			.fold(Zero::zero(), |acc, l| acc + l.amount)
1139	}
1140}