referrerpolicy=no-referrer-when-downgrade

frame_support/traits/tokens/fungibles/
regular.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//! `Inspect` and `Mutate` traits for working with regular balances.
19//!
20//! See the [`crate::traits::fungibles`] doc for more information about fungibles traits.
21
22use core::marker::PhantomData;
23
24use crate::{
25	ensure,
26	traits::{
27		tokens::{
28			misc::{
29				Balance, DepositConsequence,
30				Fortitude::{self, Force, Polite},
31				Precision::{self, BestEffort, Exact},
32				Preservation::{self, Expendable},
33				Provenance::{self, Extant},
34				WithdrawConsequence,
35			},
36			AssetId,
37		},
38		SameOrOther, TryDrop,
39	},
40};
41use sp_arithmetic::traits::{CheckedAdd, CheckedSub, One};
42use sp_runtime::{traits::Saturating, ArithmeticError, DispatchError, TokenError};
43
44use super::{Credit, Debt, HandleImbalanceDrop, Imbalance};
45
46/// Trait for providing balance-inspection access to a set of named fungible assets.
47pub trait Inspect<AccountId>: Sized {
48	/// Means of identifying one asset class from another.
49	type AssetId: AssetId;
50
51	/// Scalar type for representing balance of an account.
52	type Balance: Balance;
53
54	/// The total amount of issuance in the system.
55	fn total_issuance(asset: Self::AssetId) -> Self::Balance;
56
57	/// The total amount of issuance in the system excluding those which are controlled by the
58	/// system.
59	fn active_issuance(asset: Self::AssetId) -> Self::Balance {
60		Self::total_issuance(asset)
61	}
62
63	/// The minimum balance any single account may have.
64	fn minimum_balance(asset: Self::AssetId) -> Self::Balance;
65
66	/// Get the total amount of funds whose ultimate beneficial ownership can be determined as
67	/// `who`.
68	///
69	/// This may include funds which are wholly inaccessible to `who`, either temporarily or even
70	/// indefinitely.
71	///
72	/// For the amount of the balance which is currently free to be removed from the account without
73	/// error, use `reducible_balance`.
74	///
75	/// For the amount of the balance which may eventually be free to be removed from the account,
76	/// use `balance()`.
77	fn total_balance(asset: Self::AssetId, who: &AccountId) -> Self::Balance;
78
79	/// Get the balance of `who` which does not include funds which are exclusively allocated to
80	/// subsystems of the chain ("on hold" or "reserved").
81	///
82	/// In general this isn't especially useful outside of tests, and for practical purposes, you'll
83	/// want to use `reducible_balance()`.
84	fn balance(asset: Self::AssetId, who: &AccountId) -> Self::Balance;
85
86	/// Get the maximum amount that `who` can withdraw/transfer successfully based on whether the
87	/// account should be kept alive (`preservation`) or whether we are willing to force the
88	/// transfer and potentially go below user-level restrictions on the minimum amount of the
89	/// account.
90	///
91	/// Always less than `free_balance()`.
92	fn reducible_balance(
93		asset: Self::AssetId,
94		who: &AccountId,
95		preservation: Preservation,
96		force: Fortitude,
97	) -> Self::Balance;
98
99	/// Returns `true` if the `asset` balance of `who` may be increased by `amount`.
100	///
101	/// - `asset`: The asset that should be deposited.
102	/// - `who`: The account of which the balance should be increased by `amount`.
103	/// - `amount`: How much should the balance be increased?
104	/// - `mint`: Will `amount` be minted to deposit it into `account`?
105	fn can_deposit(
106		asset: Self::AssetId,
107		who: &AccountId,
108		amount: Self::Balance,
109		provenance: Provenance,
110	) -> DepositConsequence;
111
112	/// Returns `Failed` if the `asset` balance of `who` may not be decreased by `amount`, otherwise
113	/// the consequence.
114	fn can_withdraw(
115		asset: Self::AssetId,
116		who: &AccountId,
117		amount: Self::Balance,
118	) -> WithdrawConsequence<Self::Balance>;
119
120	/// Returns `true` if an `asset` exists.
121	fn asset_exists(asset: Self::AssetId) -> bool;
122
123	/// Returns `true` if the `asset` exists and is sufficient, `false` otherwise.
124	///
125	/// Defaults to `false`; implementations which track sufficiency should override this.
126	fn is_sufficient(_asset: Self::AssetId) -> bool {
127		false
128	}
129}
130
131/// Special dust type which can be type-safely converted into a `Credit`.
132#[must_use]
133pub struct Dust<A, T: Unbalanced<A>>(pub T::AssetId, pub T::Balance);
134
135impl<A, T: Balanced<A>> Dust<A, T> {
136	/// Convert `Dust` into an instance of `Credit`.
137	pub fn into_credit(self) -> Credit<A, T> {
138		Credit::<A, T>::new(self.0, self.1)
139	}
140}
141
142/// A fungible token class where the balance can be set arbitrarily.
143///
144/// **WARNING**
145/// Do not use this directly unless you want trouble, since it allows you to alter account balances
146/// without keeping the issuance up to date. It has no safeguards against accidentally creating
147/// token imbalances in your system leading to accidental inflation or deflation. It's really just
148/// for the underlying datatype to implement so the user gets the much safer `Balanced` trait to
149/// use.
150pub trait Unbalanced<AccountId>: Inspect<AccountId> {
151	/// Create some dust and handle it with `Self::handle_dust`. This is an unbalanced operation
152	/// and it must only be used when an account is modified in a raw fashion, outside of the entire
153	/// fungibles API. The `amount` is capped at `Self::minimum_balance() - 1`.
154	///
155	/// This should not be reimplemented.
156	fn handle_raw_dust(asset: Self::AssetId, amount: Self::Balance) {
157		Self::handle_dust(Dust(
158			asset.clone(),
159			amount.min(Self::minimum_balance(asset).saturating_sub(One::one())),
160		))
161	}
162
163	/// Do something with the dust which has been destroyed from the system. `Dust` can be converted
164	/// into a `Credit` with the `Balanced` trait impl.
165	fn handle_dust(dust: Dust<AccountId, Self>);
166
167	/// Forcefully set the balance of `who` to `amount`.
168	///
169	/// If this call executes successfully, you can `assert_eq!(Self::balance(), amount);`.
170	///
171	/// For implementations which include one or more balances on hold, then these are *not*
172	/// included in the `amount`.
173	///
174	/// This function does its best to force the balance change through, but will not break system
175	/// invariants such as any Existential Deposits needed or overflows/underflows.
176	/// If this cannot be done for some reason (e.g. because the account cannot be created, deleted
177	/// or would overflow) then an `Err` is returned.
178	fn write_balance(
179		asset: Self::AssetId,
180		who: &AccountId,
181		amount: Self::Balance,
182	) -> Result<Option<Self::Balance>, DispatchError>;
183
184	/// Set the total issuance to `amount`.
185	fn set_total_issuance(asset: Self::AssetId, amount: Self::Balance);
186
187	/// Reduce the balance of `who` by `amount`.
188	///
189	/// If `precision` is `Exact` and it cannot be reduced by that amount for
190	/// some reason, return `Err` and don't reduce it at all. If `precision` is `BestEffort`, then
191	/// reduce the balance of `who` by the most that is possible, up to `amount`.
192	///
193	/// In either case, if `Ok` is returned then the inner is the amount by which is was reduced.
194	/// Minimum balance will be respected and thus the returned amount may be up to
195	/// `Self::minimum_balance() - 1` greater than `amount` in the case that the reduction caused
196	/// the account to be deleted.
197	fn decrease_balance(
198		asset: Self::AssetId,
199		who: &AccountId,
200		mut amount: Self::Balance,
201		precision: Precision,
202		preservation: Preservation,
203		force: Fortitude,
204	) -> Result<Self::Balance, DispatchError> {
205		let old_balance = Self::balance(asset.clone(), who);
206		let reducible = Self::reducible_balance(asset.clone(), who, preservation, force);
207		match precision {
208			BestEffort => amount = amount.min(reducible),
209			Exact => ensure!(reducible >= amount, TokenError::FundsUnavailable),
210		}
211		let new_balance = old_balance.checked_sub(&amount).ok_or(TokenError::FundsUnavailable)?;
212		if let Some(dust) = Self::write_balance(asset.clone(), who, new_balance)? {
213			Self::handle_dust(Dust(asset, dust));
214		}
215		Ok(old_balance.saturating_sub(new_balance))
216	}
217
218	/// Increase the balance of `who` by `amount`.
219	///
220	/// If it cannot be increased by that amount for some reason, return `Err` and don't increase
221	/// it at all. If Ok, return the imbalance.
222	/// Minimum balance will be respected and an error will be returned if
223	/// `amount < Self::minimum_balance()` when the account of `who` is zero.
224	fn increase_balance(
225		asset: Self::AssetId,
226		who: &AccountId,
227		amount: Self::Balance,
228		precision: Precision,
229	) -> Result<Self::Balance, DispatchError> {
230		let old_balance = Self::balance(asset.clone(), who);
231		let new_balance = if let BestEffort = precision {
232			old_balance.saturating_add(amount)
233		} else {
234			old_balance.checked_add(&amount).ok_or(ArithmeticError::Overflow)?
235		};
236		if new_balance < Self::minimum_balance(asset.clone()) {
237			// Attempt to increase from 0 to below minimum -> stays at zero.
238			if let BestEffort = precision {
239				Ok(Self::Balance::default())
240			} else {
241				Err(TokenError::BelowMinimum.into())
242			}
243		} else {
244			if new_balance == old_balance {
245				Ok(Self::Balance::default())
246			} else {
247				if let Some(dust) = Self::write_balance(asset.clone(), who, new_balance)? {
248					Self::handle_dust(Dust(asset, dust));
249				}
250				Ok(new_balance.saturating_sub(old_balance))
251			}
252		}
253	}
254
255	/// Reduce the active issuance by some amount.
256	fn deactivate(_asset: Self::AssetId, _: Self::Balance) {}
257
258	/// Increase the active issuance by some amount, up to the outstanding amount reduced.
259	fn reactivate(_asset: Self::AssetId, _: Self::Balance) {}
260}
261
262/// Trait for providing a basic fungible asset.
263pub trait Mutate<AccountId>: Inspect<AccountId> + Unbalanced<AccountId>
264where
265	AccountId: Eq,
266{
267	/// Increase the balance of `who` by exactly `amount`, minting new tokens. If that isn't
268	/// possible then an `Err` is returned and nothing is changed.
269	fn mint_into(
270		asset: Self::AssetId,
271		who: &AccountId,
272		amount: Self::Balance,
273	) -> Result<Self::Balance, DispatchError> {
274		Self::total_issuance(asset.clone())
275			.checked_add(&amount)
276			.ok_or(ArithmeticError::Overflow)?;
277		let actual = Self::increase_balance(asset.clone(), who, amount, Exact)?;
278		Self::set_total_issuance(
279			asset.clone(),
280			Self::total_issuance(asset.clone()).saturating_add(actual),
281		);
282		Self::done_mint_into(asset, who, amount);
283		Ok(actual)
284	}
285
286	/// Decrease the balance of `who` by at least `amount`, possibly slightly more in the case of
287	/// minimum-balance requirements, burning the tokens. If that isn't possible then an `Err` is
288	/// returned and nothing is changed. If successful, the amount of tokens reduced is returned.
289	fn burn_from(
290		asset: Self::AssetId,
291		who: &AccountId,
292		amount: Self::Balance,
293		preservation: Preservation,
294		precision: Precision,
295		force: Fortitude,
296	) -> Result<Self::Balance, DispatchError> {
297		let actual = Self::reducible_balance(asset.clone(), who, preservation, force).min(amount);
298		ensure!(actual == amount || precision == BestEffort, TokenError::FundsUnavailable);
299		Self::total_issuance(asset.clone())
300			.checked_sub(&actual)
301			.ok_or(ArithmeticError::Overflow)?;
302		let actual =
303			Self::decrease_balance(asset.clone(), who, actual, BestEffort, preservation, force)?;
304		Self::set_total_issuance(
305			asset.clone(),
306			Self::total_issuance(asset.clone()).saturating_sub(actual),
307		);
308		Self::done_burn_from(asset, who, actual);
309		Ok(actual)
310	}
311
312	/// Attempt to decrease the `asset` balance of `who` by `amount`.
313	///
314	/// Equivalent to `burn_from`, except with an expectation that within the bounds of some
315	/// universal issuance, the total assets `suspend`ed and `resume`d will be equivalent. The
316	/// implementation may be configured such that the total assets suspended may never be less than
317	/// the total assets resumed (which is the invariant for an issuing system), or the reverse
318	/// (which the invariant in a non-issuing system).
319	///
320	/// Because of this expectation, any metadata associated with the asset is expected to survive
321	/// the suspect-resume cycle.
322	fn shelve(
323		asset: Self::AssetId,
324		who: &AccountId,
325		amount: Self::Balance,
326	) -> Result<Self::Balance, DispatchError> {
327		let actual = Self::reducible_balance(asset.clone(), who, Expendable, Polite).min(amount);
328		ensure!(actual == amount, TokenError::FundsUnavailable);
329		Self::total_issuance(asset.clone())
330			.checked_sub(&actual)
331			.ok_or(ArithmeticError::Overflow)?;
332		let actual =
333			Self::decrease_balance(asset.clone(), who, actual, BestEffort, Expendable, Polite)?;
334		Self::set_total_issuance(
335			asset.clone(),
336			Self::total_issuance(asset.clone()).saturating_sub(actual),
337		);
338		Self::done_shelve(asset, who, actual);
339		Ok(actual)
340	}
341
342	/// Attempt to increase the `asset` balance of `who` by `amount`.
343	///
344	/// Equivalent to `mint_into`, except with an expectation that within the bounds of some
345	/// universal issuance, the total assets `suspend`ed and `resume`d will be equivalent. The
346	/// implementation may be configured such that the total assets suspended may never be less than
347	/// the total assets resumed (which is the invariant for an issuing system), or the reverse
348	/// (which the invariant in a non-issuing system).
349	///
350	/// Because of this expectation, any metadata associated with the asset is expected to survive
351	/// the suspect-resume cycle.
352	fn restore(
353		asset: Self::AssetId,
354		who: &AccountId,
355		amount: Self::Balance,
356	) -> Result<Self::Balance, DispatchError> {
357		Self::total_issuance(asset.clone())
358			.checked_add(&amount)
359			.ok_or(ArithmeticError::Overflow)?;
360		let actual = Self::increase_balance(asset.clone(), who, amount, Exact)?;
361		Self::set_total_issuance(
362			asset.clone(),
363			Self::total_issuance(asset.clone()).saturating_add(actual),
364		);
365		Self::done_restore(asset, who, amount);
366		Ok(actual)
367	}
368
369	/// Transfer funds from one account into another.
370	///
371	/// A transfer where the source and destination account are identical is treated as No-OP after
372	/// checking the preconditions.
373	fn transfer(
374		asset: Self::AssetId,
375		source: &AccountId,
376		dest: &AccountId,
377		amount: Self::Balance,
378		preservation: Preservation,
379	) -> Result<Self::Balance, DispatchError> {
380		let _extra = Self::can_withdraw(asset.clone(), source, amount)
381			.into_result(preservation != Expendable)?;
382		Self::can_deposit(asset.clone(), dest, amount, Extant).into_result()?;
383		if source == dest {
384			return Ok(amount);
385		}
386
387		Self::decrease_balance(asset.clone(), source, amount, BestEffort, preservation, Polite)?;
388		// This should never fail as we checked `can_deposit` earlier. But we do a best-effort
389		// anyway.
390		let _ = Self::increase_balance(asset.clone(), dest, amount, BestEffort);
391		Self::done_transfer(asset, source, dest, amount);
392		Ok(amount)
393	}
394
395	/// Simple infallible function to force an account to have a particular balance, good for use
396	/// in tests and benchmarks but not recommended for production code owing to the lack of
397	/// error reporting.
398	///
399	/// Returns the new balance.
400	fn set_balance(asset: Self::AssetId, who: &AccountId, amount: Self::Balance) -> Self::Balance {
401		let b = Self::balance(asset.clone(), who);
402		if b > amount {
403			Self::burn_from(asset, who, b - amount, Expendable, BestEffort, Force)
404				.map(|d| b.saturating_sub(d))
405		} else {
406			Self::mint_into(asset, who, amount - b).map(|d| b.saturating_add(d))
407		}
408		.unwrap_or(b)
409	}
410	fn done_mint_into(_asset: Self::AssetId, _who: &AccountId, _amount: Self::Balance) {}
411	fn done_burn_from(_asset: Self::AssetId, _who: &AccountId, _amount: Self::Balance) {}
412	fn done_shelve(_asset: Self::AssetId, _who: &AccountId, _amount: Self::Balance) {}
413	fn done_restore(_asset: Self::AssetId, _who: &AccountId, _amount: Self::Balance) {}
414	fn done_transfer(
415		_asset: Self::AssetId,
416		_source: &AccountId,
417		_dest: &AccountId,
418		_amount: Self::Balance,
419	) {
420	}
421}
422
423/// Simple handler for an imbalance drop which increases the total issuance of the system by the
424/// imbalance amount. Used for leftover debt.
425pub struct IncreaseIssuance<AccountId, U>(PhantomData<(AccountId, U)>);
426impl<AccountId, U: Unbalanced<AccountId>> HandleImbalanceDrop<U::AssetId, U::Balance>
427	for IncreaseIssuance<AccountId, U>
428{
429	fn handle(asset: U::AssetId, amount: U::Balance) {
430		U::set_total_issuance(asset.clone(), U::total_issuance(asset).saturating_add(amount))
431	}
432}
433
434/// Simple handler for an imbalance drop which decreases the total issuance of the system by the
435/// imbalance amount. Used for leftover credit.
436pub struct DecreaseIssuance<AccountId, U>(PhantomData<(AccountId, U)>);
437impl<AccountId, U: Unbalanced<AccountId>> HandleImbalanceDrop<U::AssetId, U::Balance>
438	for DecreaseIssuance<AccountId, U>
439{
440	fn handle(asset: U::AssetId, amount: U::Balance) {
441		U::set_total_issuance(asset.clone(), U::total_issuance(asset).saturating_sub(amount))
442	}
443}
444
445/// A fungible token class where any creation and deletion of tokens is semi-explicit and where the
446/// total supply is maintained automatically.
447///
448/// This is auto-implemented when a token class has `Unbalanced` implemented.
449pub trait Balanced<AccountId>: Inspect<AccountId> + Unbalanced<AccountId> {
450	/// The type for managing what happens when an instance of `Debt` is dropped without being used.
451	type OnDropDebt: HandleImbalanceDrop<Self::AssetId, Self::Balance>;
452	/// The type for managing what happens when an instance of `Credit` is dropped without being
453	/// used.
454	type OnDropCredit: HandleImbalanceDrop<Self::AssetId, Self::Balance>;
455
456	/// Reduce the total issuance by `amount` and return the according imbalance. The imbalance will
457	/// typically be used to reduce an account by the same amount with e.g. `settle`.
458	///
459	/// This is infallible, but doesn't guarantee that the entire `amount` is burnt, for example
460	/// in the case of underflow.
461	fn rescind(asset: Self::AssetId, amount: Self::Balance) -> Debt<AccountId, Self> {
462		let old = Self::total_issuance(asset.clone());
463		let new = old.saturating_sub(amount);
464		Self::set_total_issuance(asset.clone(), new);
465		let delta = old - new;
466		Self::done_rescind(asset.clone(), delta);
467		Imbalance::<Self::AssetId, Self::Balance, Self::OnDropDebt, Self::OnDropCredit>::new(
468			asset, delta,
469		)
470	}
471
472	/// Increase the total issuance by `amount` and return the according imbalance. The imbalance
473	/// will typically be used to increase an account by the same amount with e.g.
474	/// `resolve_into_existing` or `resolve_creating`.
475	///
476	/// This is infallible, but doesn't guarantee that the entire `amount` is issued, for example
477	/// in the case of overflow.
478	fn issue(asset: Self::AssetId, amount: Self::Balance) -> Credit<AccountId, Self> {
479		let old = Self::total_issuance(asset.clone());
480		let new = old.saturating_add(amount);
481		Self::set_total_issuance(asset.clone(), new);
482		let delta = new - old;
483		Self::done_issue(asset.clone(), delta);
484		Imbalance::<Self::AssetId, Self::Balance, Self::OnDropCredit, Self::OnDropDebt>::new(
485			asset, delta,
486		)
487	}
488
489	/// Produce a pair of imbalances that cancel each other out exactly.
490	///
491	/// This is just the same as burning and issuing the same amount and has no effect on the
492	/// total issuance.
493	///
494	/// This is infallible, but doesn't guarantee that the entire `amount` is used to create the
495	/// pair, for example in the case where the amounts would cause overflow or underflow in
496	/// [`Balanced::issue`] or [`Balanced::rescind`].
497	fn pair(
498		asset: Self::AssetId,
499		amount: Self::Balance,
500	) -> Result<(Debt<AccountId, Self>, Credit<AccountId, Self>), DispatchError> {
501		let issued = Self::issue(asset.clone(), amount);
502		let rescinded = Self::rescind(asset, amount);
503		// Need to check amount in case by some edge case both issued and rescinded are below
504		// `amount` by the exact same value
505		if issued.peek() != rescinded.peek() || issued.peek() != amount {
506			// Issued and rescinded will be dropped automatically
507			Err("Failed to issue and rescind equal amounts".into())
508		} else {
509			Ok((rescinded, issued))
510		}
511	}
512
513	/// Mints `value` into the account of `who`, creating it as needed.
514	///
515	/// If `precision` is `BestEffort` and `value` in full could not be minted (e.g. due to
516	/// overflow), then the maximum is minted, up to `value`. If `precision` is `Exact`, then
517	/// exactly `value` must be minted into the account of `who` or the operation will fail with an
518	/// `Err` and nothing will change.
519	///
520	/// If the operation is successful, this will return `Ok` with a `Debt` of the total value
521	/// added to the account.
522	fn deposit(
523		asset: Self::AssetId,
524		who: &AccountId,
525		value: Self::Balance,
526		precision: Precision,
527	) -> Result<Debt<AccountId, Self>, DispatchError> {
528		let increase = Self::increase_balance(asset.clone(), who, value, precision)?;
529		Self::done_deposit(asset.clone(), who, increase);
530		Ok(Imbalance::<Self::AssetId, Self::Balance, Self::OnDropDebt, Self::OnDropCredit>::new(
531			asset, increase,
532		))
533	}
534
535	/// Removes `value` balance from `who` account if possible.
536	///
537	/// If `precision` is `BestEffort` and `value` in full could not be removed (e.g. due to
538	/// underflow), then the maximum is removed, up to `value`. If `precision` is `Exact`, then
539	/// exactly `value` must be removed from the account of `who` or the operation will fail with an
540	/// `Err` and nothing will change.
541	///
542	/// If the removal is needed but not possible, then it returns `Err` and nothing is changed.
543	/// If the account needed to be deleted, then slightly more than `value` may be removed from the
544	/// account owning since up to (but not including) minimum balance may also need to be removed.
545	///
546	/// If the operation is successful, this will return `Ok` with a `Credit` of the total value
547	/// removed from the account.
548	fn withdraw(
549		asset: Self::AssetId,
550		who: &AccountId,
551		value: Self::Balance,
552		precision: Precision,
553		preservation: Preservation,
554		force: Fortitude,
555	) -> Result<Credit<AccountId, Self>, DispatchError> {
556		let decrease =
557			Self::decrease_balance(asset.clone(), who, value, precision, preservation, force)?;
558		Self::done_withdraw(asset.clone(), who, decrease);
559		Ok(Imbalance::<Self::AssetId, Self::Balance, Self::OnDropCredit, Self::OnDropDebt>::new(
560			asset, decrease,
561		))
562	}
563
564	/// The balance of `who` is increased in order to counter `credit`. If the whole of `credit`
565	/// cannot be countered, then nothing is changed and the original `credit` is returned in an
566	/// `Err`.
567	///
568	/// Please note: If `credit.peek()` is less than `Self::minimum_balance()`, then `who` must
569	/// already exist for this to succeed.
570	fn resolve(
571		who: &AccountId,
572		credit: Credit<AccountId, Self>,
573	) -> Result<(), Credit<AccountId, Self>> {
574		let v = credit.peek();
575		let debt = match Self::deposit(credit.asset(), who, v, Exact) {
576			Err(_) => return Err(credit),
577			Ok(d) => d,
578		};
579		if let Ok(result) = credit.offset(debt) {
580			let result = result.try_drop();
581			debug_assert!(result.is_ok(), "ok deposit return must be equal to credit value; qed");
582		} else {
583			debug_assert!(false, "debt.asset is credit.asset; qed");
584		}
585		Ok(())
586	}
587
588	/// The balance of `who` is decreased in order to counter `debt`. If the whole of `debt`
589	/// cannot be countered, then nothing is changed and the original `debt` is returned in an
590	/// `Err`.
591	fn settle(
592		who: &AccountId,
593		debt: Debt<AccountId, Self>,
594		preservation: Preservation,
595	) -> Result<Credit<AccountId, Self>, Debt<AccountId, Self>> {
596		let amount = debt.peek();
597		let asset = debt.asset();
598		let credit = match Self::withdraw(asset.clone(), who, amount, Exact, preservation, Polite) {
599			Err(_) => return Err(debt),
600			Ok(d) => d,
601		};
602		match credit.offset(debt) {
603			Ok(SameOrOther::None) => Ok(Credit::<AccountId, Self>::zero(asset)),
604			Ok(SameOrOther::Same(dust)) => Ok(dust),
605			Ok(SameOrOther::Other(rest)) => {
606				debug_assert!(false, "ok withdraw return must be at least debt value; qed");
607				Err(rest)
608			},
609			Err(_) => {
610				debug_assert!(false, "debt.asset is credit.asset; qed");
611				Ok(Credit::<AccountId, Self>::zero(asset))
612			},
613		}
614	}
615
616	fn done_rescind(_asset: Self::AssetId, _amount: Self::Balance) {}
617	fn done_issue(_asset: Self::AssetId, _amount: Self::Balance) {}
618	fn done_deposit(_asset: Self::AssetId, _who: &AccountId, _amount: Self::Balance) {}
619	fn done_withdraw(_asset: Self::AssetId, _who: &AccountId, _amount: Self::Balance) {}
620}
621
622/// Dummy implementation of [`Inspect`]
623#[cfg(feature = "std")]
624impl<AccountId> Inspect<AccountId> for () {
625	type AssetId = u32;
626	type Balance = u32;
627	fn total_issuance(_: Self::AssetId) -> Self::Balance {
628		0
629	}
630	fn minimum_balance(_: Self::AssetId) -> Self::Balance {
631		0
632	}
633	fn total_balance(_: Self::AssetId, _: &AccountId) -> Self::Balance {
634		0
635	}
636	fn balance(_: Self::AssetId, _: &AccountId) -> Self::Balance {
637		0
638	}
639	fn reducible_balance(
640		_: Self::AssetId,
641		_: &AccountId,
642		_: Preservation,
643		_: Fortitude,
644	) -> Self::Balance {
645		0
646	}
647	fn can_deposit(
648		_: Self::AssetId,
649		_: &AccountId,
650		_: Self::Balance,
651		_: Provenance,
652	) -> DepositConsequence {
653		DepositConsequence::Success
654	}
655	fn can_withdraw(
656		_: Self::AssetId,
657		_: &AccountId,
658		_: Self::Balance,
659	) -> WithdrawConsequence<Self::Balance> {
660		WithdrawConsequence::Success
661	}
662	fn asset_exists(_: Self::AssetId) -> bool {
663		false
664	}
665}
666
667/// Dummy implementation of [`Unbalanced`]
668#[cfg(feature = "std")]
669impl<AccountId> Unbalanced<AccountId> for () {
670	fn handle_dust(_: Dust<AccountId, Self>) {}
671	fn write_balance(
672		_: Self::AssetId,
673		_: &AccountId,
674		_: Self::Balance,
675	) -> Result<Option<Self::Balance>, DispatchError> {
676		Ok(None)
677	}
678	fn set_total_issuance(_: Self::AssetId, _: Self::Balance) {}
679}
680
681/// Dummy implementation of [`Mutate`]
682#[cfg(feature = "std")]
683impl<AccountId: Eq> Mutate<AccountId> for () {}