pallet_assets/
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//! # Assets Pallet
19//!
20//! A simple, secure module for dealing with sets of assets implementing
21//! [`fungible`](frame_support::traits::fungible) traits, via [`fungibles`] traits.
22//!
23//! The pallet 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//! See the [`frame_tokens`] reference docs for more information about the place of the
28//! Assets pallet in FRAME.
29//!
30//! ## Overview
31//!
32//! The Assets module provides functionality for asset management of fungible asset classes
33//! with a fixed supply, including:
34//!
35//! * Asset Issuance (Minting)
36//! * Asset Transferal
37//! * Asset Freezing
38//! * Asset Destruction (Burning)
39//! * Delegated Asset Transfers ("Approval API")
40//!
41//! To use it in your runtime, you need to implement the assets [`Config`].
42//!
43//! The supported dispatchable functions are documented in the [`Call`] enum.
44//!
45//! ### Terminology
46//!
47//! * **Admin**: An account ID uniquely privileged to be able to unfreeze (thaw) an account and its
48//!   assets, as well as forcibly transfer a particular class of assets between arbitrary accounts
49//!   and reduce the balance of a particular class of assets of arbitrary accounts.
50//! * **Asset issuance/minting**: The creation of a new asset, whose total supply will belong to the
51//!   account designated as the beneficiary of the asset. This is a privileged operation.
52//! * **Asset transfer**: The reduction of the balance of an asset of one account with the
53//!   corresponding increase in the balance of another.
54//! * **Asset destruction**: The process of reducing the balance of an asset of one account. This is
55//!   a privileged operation.
56//! * **Fungible asset**: An asset whose units are interchangeable.
57//! * **Issuer**: An account ID uniquely privileged to be able to mint a particular class of assets.
58//! * **Freezer**: An account ID uniquely privileged to be able to freeze an account from
59//!   transferring a particular class of assets.
60//! * **Freezing**: Removing the possibility of an unpermissioned transfer of an asset from a
61//!   particular account.
62//! * **Non-fungible asset**: An asset for which each unit has unique characteristics.
63//! * **Owner**: An account ID uniquely privileged to be able to destroy a particular asset class,
64//!   or to set the Issuer, Freezer, Reserves, or Admin of that asset class.
65//! * **Approval**: The act of allowing an account the permission to transfer some balance of asset
66//!   from the approving account into some third-party destination account.
67//! * **Sufficiency**: The idea of a minimum-balance of an asset being sufficient to allow the
68//!   account's existence on the system without requiring any other existential-deposit.
69//!
70//! ### Goals
71//!
72//! The assets system in Substrate is designed to make the following possible:
73//!
74//! * Issue new assets in a permissioned or permissionless way, if permissionless, then with a
75//!   deposit required.
76//! * Allow accounts to be delegated the ability to transfer assets without otherwise existing
77//!   on-chain (*approvals*).
78//! * Move assets between accounts.
79//! * Update an asset class's total supply.
80//! * Allow administrative activities by specially privileged accounts including freezing account
81//!   balances and minting/burning assets.
82//!
83//! ## Interface
84//!
85//! ### Permissionless Functions
86//!
87//! * `create`: Creates a new asset class, taking the required deposit.
88//! * `transfer`: Transfer sender's assets to another account.
89//! * `transfer_keep_alive`: Transfer sender's assets to another account, keeping the sender alive.
90//! * `approve_transfer`: Create or increase an delegated transfer.
91//! * `cancel_approval`: Rescind a previous approval.
92//! * `transfer_approved`: Transfer third-party's assets to another account.
93//! * `touch`: Create an asset account for non-provider assets. Caller must place a deposit.
94//! * `refund`: Return the deposit (if any) of the caller's asset account or a consumer reference
95//!   (if any) of the caller's account.
96//! * `refund_other`: Return the deposit (if any) of a specified asset account.
97//! * `touch_other`: Create an asset account for specified account. Caller must place a deposit.
98//!
99//! ### Permissioned Functions
100//!
101//! * `force_create`: Creates a new asset class without taking any deposit.
102//! * `force_set_metadata`: Set the metadata of an asset class.
103//! * `force_clear_metadata`: Remove the metadata of an asset class.
104//! * `force_asset_status`: Alter an asset class's attributes.
105//! * `force_cancel_approval`: Rescind a previous approval.
106//!
107//! ### Privileged Functions
108//!
109//! * `destroy`: Destroys an entire asset class; called by the asset class's Owner.
110//! * `mint`: Increases the asset balance of an account; called by the asset class's Issuer.
111//! * `burn`: Decreases the asset balance of an account; called by the asset class's Admin.
112//! * `force_transfer`: Transfers between arbitrary accounts; called by the asset class's Admin.
113//! * `freeze`: Disallows further `transfer`s from an account; called by the asset class's Freezer.
114//! * `thaw`: Allows further `transfer`s to and from an account; called by the asset class's Admin.
115//! * `transfer_ownership`: Changes an asset class's Owner; called by the asset class's Owner.
116//! * `set_team`: Changes an asset class's Admin, Freezer and Issuer; called by the asset class's
117//!   Owner.
118//! * `set_metadata`: Set the metadata of an asset class; called by the asset class's Owner.
119//! * `clear_metadata`: Remove the metadata of an asset class; called by the asset class's Owner.
120//! * `set_reserves`: Set the reserve information of an asset class; called by the asset class's
121//!   Owner.
122//! * `block`: Disallows further `transfer`s to and from an account; called by the asset class's
123//!   Freezer.
124//!
125//! Please refer to the [`Call`] enum and its associated variants for documentation on each
126//! function.
127//!
128//! ### Public Functions
129//! <!-- Original author of descriptions: @gavofyork -->
130//!
131//! * `balance` - Get the asset `id` balance of `who`.
132//! * `total_supply` - Get the total supply of an asset `id`.
133//!
134//! Please refer to the [`Pallet`] struct for details on publicly available functions.
135//!
136//! ### Callbacks
137//!
138//! Using `CallbackHandle` associated type, user can configure custom callback functions which are
139//! executed when new asset is created or an existing asset is destroyed.
140//!
141//! ## Related Modules
142//!
143//! * [`System`](../frame_system/index.html)
144//! * [`Support`](../frame_support/index.html)
145//!
146//! [`frame_tokens`]: ../polkadot_sdk_docs/reference_docs/frame_tokens/index.html
147
148// This recursion limit is needed because we have too many benchmarks and benchmarking will fail if
149// we add more without this limit.
150#![recursion_limit = "1024"]
151// Ensure we're `no_std` when compiling for Wasm.
152#![cfg_attr(not(feature = "std"), no_std)]
153
154#[cfg(feature = "runtime-benchmarks")]
155pub mod benchmarking;
156pub mod migration;
157#[cfg(test)]
158pub mod mock;
159#[cfg(test)]
160mod tests;
161pub mod weights;
162
163mod extra_mutator;
164pub use extra_mutator::*;
165mod functions;
166mod impl_fungibles;
167mod impl_stored_map;
168mod types;
169pub use types::*;
170
171extern crate alloc;
172extern crate core;
173
174use scale_info::TypeInfo;
175use sp_runtime::{
176	traits::{AtLeast32BitUnsigned, CheckedAdd, CheckedSub, Saturating, StaticLookup, Zero},
177	ArithmeticError, DispatchError, TokenError,
178};
179
180use alloc::vec::Vec;
181use core::{fmt::Debug, marker::PhantomData};
182use frame_support::{
183	dispatch::DispatchResult,
184	ensure,
185	pallet_prelude::DispatchResultWithPostInfo,
186	storage::KeyPrefixIterator,
187	traits::{
188		tokens::{
189			fungibles, DepositConsequence, Fortitude,
190			Preservation::{Expendable, Preserve},
191			WithdrawConsequence,
192		},
193		BalanceStatus::Reserved,
194		Currency, EnsureOriginWithArg, Incrementable, ReservableCurrency, StoredMap,
195	},
196};
197use frame_system::Config as SystemConfig;
198
199pub use pallet::*;
200pub use weights::WeightInfo;
201
202type AccountIdLookupOf<T> = <<T as frame_system::Config>::Lookup as StaticLookup>::Source;
203const LOG_TARGET: &str = "runtime::assets";
204
205/// Trait with callbacks that are executed after successful asset creation or destruction.
206pub trait AssetsCallback<AssetId, AccountId> {
207	/// Indicates that asset with `id` was successfully created by the `owner`
208	fn created(_id: &AssetId, _owner: &AccountId) -> Result<(), ()> {
209		Ok(())
210	}
211
212	/// Indicates that asset with `id` has just been destroyed
213	fn destroyed(_id: &AssetId) -> Result<(), ()> {
214		Ok(())
215	}
216}
217
218#[impl_trait_for_tuples::impl_for_tuples(10)]
219impl<AssetId, AccountId> AssetsCallback<AssetId, AccountId> for Tuple {
220	fn created(id: &AssetId, owner: &AccountId) -> Result<(), ()> {
221		for_tuples!( #( Tuple::created(id, owner)?; )* );
222		Ok(())
223	}
224
225	fn destroyed(id: &AssetId) -> Result<(), ()> {
226		for_tuples!( #( Tuple::destroyed(id)?; )* );
227		Ok(())
228	}
229}
230
231/// Auto-increment the [`NextAssetId`] when an asset is created.
232///
233/// This has not effect if the [`NextAssetId`] value is not present.
234pub struct AutoIncAssetId<T, I = ()>(PhantomData<(T, I)>);
235impl<T: Config<I>, I> AssetsCallback<T::AssetId, T::AccountId> for AutoIncAssetId<T, I>
236where
237	T::AssetId: Incrementable,
238{
239	fn created(_: &T::AssetId, _: &T::AccountId) -> Result<(), ()> {
240		let Some(next_id) = NextAssetId::<T, I>::get() else {
241			// Auto increment for the asset id is not enabled.
242			return Ok(());
243		};
244		let next_id = next_id.increment().ok_or(())?;
245		NextAssetId::<T, I>::put(next_id);
246		Ok(())
247	}
248}
249
250#[frame_support::pallet]
251pub mod pallet {
252	use super::*;
253	use codec::HasCompact;
254	use frame_support::{
255		pallet_prelude::*,
256		traits::{tokens::ProvideAssetReserves, AccountTouch, ContainsPair},
257	};
258	use frame_system::pallet_prelude::*;
259
260	/// The in-code storage version.
261	const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);
262
263	/// The maximum number of configurable reserve locations for one asset class.
264	pub const MAX_RESERVES: u32 = 5;
265
266	#[pallet::pallet]
267	#[pallet::storage_version(STORAGE_VERSION)]
268	pub struct Pallet<T, I = ()>(_);
269
270	#[cfg(feature = "runtime-benchmarks")]
271	pub trait BenchmarkHelper<AssetIdParameter, ReserveIdParameter> {
272		fn create_asset_id_parameter(id: u32) -> AssetIdParameter;
273		fn create_reserve_id_parameter(id: u32) -> ReserveIdParameter;
274	}
275	#[cfg(feature = "runtime-benchmarks")]
276	impl<AssetIdParameter: From<u32>> BenchmarkHelper<AssetIdParameter, ()> for () {
277		fn create_asset_id_parameter(id: u32) -> AssetIdParameter {
278			id.into()
279		}
280		fn create_reserve_id_parameter(_: u32) -> () {
281			()
282		}
283	}
284
285	/// Default implementations of [`DefaultConfig`], which can be used to implement [`Config`].
286	pub mod config_preludes {
287		use super::*;
288		use frame_support::derive_impl;
289		pub struct TestDefaultConfig;
290
291		#[derive_impl(frame_system::config_preludes::TestDefaultConfig, no_aggregated_types)]
292		impl frame_system::DefaultConfig for TestDefaultConfig {}
293
294		#[frame_support::register_default_impl(TestDefaultConfig)]
295		impl DefaultConfig for TestDefaultConfig {
296			#[inject_runtime_type]
297			type RuntimeEvent = ();
298			type Balance = u64;
299			type RemoveItemsLimit = ConstU32<5>;
300			type AssetId = u32;
301			type AssetIdParameter = u32;
302			type ReserveData = ();
303			type AssetDeposit = ConstUint<1>;
304			type AssetAccountDeposit = ConstUint<10>;
305			type MetadataDepositBase = ConstUint<1>;
306			type MetadataDepositPerByte = ConstUint<1>;
307			type ApprovalDeposit = ConstUint<1>;
308			type StringLimit = ConstU32<50>;
309			type Freezer = ();
310			type Holder = ();
311			type Extra = ();
312			type CallbackHandle = ();
313			type WeightInfo = ();
314			#[cfg(feature = "runtime-benchmarks")]
315			type BenchmarkHelper = ();
316		}
317	}
318
319	#[pallet::config(with_default)]
320	/// The module configuration trait.
321	pub trait Config<I: 'static = ()>: frame_system::Config {
322		/// The overarching event type.
323		#[pallet::no_default_bounds]
324		#[allow(deprecated)]
325		type RuntimeEvent: From<Event<Self, I>>
326			+ IsType<<Self as frame_system::Config>::RuntimeEvent>;
327
328		/// The units in which we record balances.
329		type Balance: Member
330			+ Parameter
331			+ HasCompact<Type: DecodeWithMemTracking>
332			+ AtLeast32BitUnsigned
333			+ Default
334			+ Copy
335			+ MaybeSerializeDeserialize
336			+ MaxEncodedLen
337			+ TypeInfo;
338
339		/// Max number of items to destroy per `destroy_accounts` and `destroy_approvals` call.
340		///
341		/// Must be configured to result in a weight that makes each call fit in a block.
342		#[pallet::constant]
343		type RemoveItemsLimit: Get<u32>;
344
345		/// Identifier for the class of asset.
346		type AssetId: Member + Parameter + Clone + MaybeSerializeDeserialize + MaxEncodedLen;
347
348		/// Wrapper around `Self::AssetId` to use in dispatchable call signatures. Allows the use
349		/// of compact encoding in instances of the pallet, which will prevent breaking changes
350		/// resulting from the removal of `HasCompact` from `Self::AssetId`.
351		///
352		/// This type includes the `From<Self::AssetId>` bound, since tightly coupled pallets may
353		/// want to convert an `AssetId` into a parameter for calling dispatchable functions
354		/// directly.
355		type AssetIdParameter: Parameter + From<Self::AssetId> + Into<Self::AssetId> + MaxEncodedLen;
356
357		/// Information about reserve locations for a class of asset.
358		type ReserveData: Debug + Parameter + MaybeSerializeDeserialize + MaxEncodedLen;
359
360		/// The currency mechanism.
361		#[pallet::no_default]
362		type Currency: ReservableCurrency<Self::AccountId>;
363
364		/// Standard asset class creation is only allowed if the origin attempting it and the
365		/// asset class are in this set.
366		#[pallet::no_default]
367		type CreateOrigin: EnsureOriginWithArg<
368			Self::RuntimeOrigin,
369			Self::AssetId,
370			Success = Self::AccountId,
371		>;
372
373		/// The origin which may forcibly create or destroy an asset or otherwise alter privileged
374		/// attributes.
375		#[pallet::no_default]
376		type ForceOrigin: EnsureOrigin<Self::RuntimeOrigin>;
377
378		/// The basic amount of funds that must be reserved for an asset.
379		#[pallet::constant]
380		#[pallet::no_default_bounds]
381		type AssetDeposit: Get<DepositBalanceOf<Self, I>>;
382
383		/// The amount of funds that must be reserved for a non-provider asset account to be
384		/// maintained.
385		#[pallet::constant]
386		#[pallet::no_default_bounds]
387		type AssetAccountDeposit: Get<DepositBalanceOf<Self, I>>;
388
389		/// The basic amount of funds that must be reserved when adding metadata to your asset.
390		#[pallet::constant]
391		#[pallet::no_default_bounds]
392		type MetadataDepositBase: Get<DepositBalanceOf<Self, I>>;
393
394		/// The additional funds that must be reserved for the number of bytes you store in your
395		/// metadata.
396		#[pallet::constant]
397		#[pallet::no_default_bounds]
398		type MetadataDepositPerByte: Get<DepositBalanceOf<Self, I>>;
399
400		/// The amount of funds that must be reserved when creating a new approval.
401		#[pallet::constant]
402		#[pallet::no_default_bounds]
403		type ApprovalDeposit: Get<DepositBalanceOf<Self, I>>;
404
405		/// The maximum length of a name or symbol stored on-chain.
406		#[pallet::constant]
407		type StringLimit: Get<u32>;
408
409		/// A hook to allow a per-asset, per-account minimum balance to be enforced. This must be
410		/// respected in all permissionless operations.
411		type Freezer: FrozenBalance<Self::AssetId, Self::AccountId, Self::Balance>;
412
413		/// A hook to inspect a per-asset, per-account balance that is held. This goes in
414		/// accordance with balance model.
415		type Holder: BalanceOnHold<Self::AssetId, Self::AccountId, Self::Balance>;
416
417		/// Additional data to be stored with an account's asset balance.
418		type Extra: Member + Parameter + Default + MaxEncodedLen;
419
420		/// Callback methods for asset state change (e.g. asset created or destroyed)
421		///
422		/// Types implementing the [`AssetsCallback`] can be chained when listed together as a
423		/// tuple.
424		/// The [`AutoIncAssetId`] callback, in conjunction with the [`NextAssetId`], can be
425		/// used to set up auto-incrementing asset IDs for this collection.
426		type CallbackHandle: AssetsCallback<Self::AssetId, Self::AccountId>;
427
428		/// Weight information for extrinsics in this pallet.
429		type WeightInfo: WeightInfo;
430
431		/// Helper trait for benchmarks.
432		#[cfg(feature = "runtime-benchmarks")]
433		type BenchmarkHelper: BenchmarkHelper<Self::AssetIdParameter, Self::ReserveData>;
434	}
435
436	#[pallet::storage]
437	/// Details of an asset.
438	pub type Asset<T: Config<I>, I: 'static = ()> = StorageMap<
439		_,
440		Blake2_128Concat,
441		T::AssetId,
442		AssetDetails<T::Balance, T::AccountId, DepositBalanceOf<T, I>>,
443	>;
444
445	#[pallet::storage]
446	/// The holdings of a specific account for a specific asset.
447	pub type Account<T: Config<I>, I: 'static = ()> = StorageDoubleMap<
448		_,
449		Blake2_128Concat,
450		T::AssetId,
451		Blake2_128Concat,
452		T::AccountId,
453		AssetAccountOf<T, I>,
454	>;
455
456	#[pallet::storage]
457	/// Approved balance transfers. First balance is the amount approved for transfer. Second
458	/// is the amount of `T::Currency` reserved for storing this.
459	/// First key is the asset ID, second key is the owner and third key is the delegate.
460	pub type Approvals<T: Config<I>, I: 'static = ()> = StorageNMap<
461		_,
462		(
463			NMapKey<Blake2_128Concat, T::AssetId>,
464			NMapKey<Blake2_128Concat, T::AccountId>, // owner
465			NMapKey<Blake2_128Concat, T::AccountId>, // delegate
466		),
467		Approval<T::Balance, DepositBalanceOf<T, I>>,
468	>;
469
470	#[pallet::storage]
471	/// Metadata of an asset.
472	pub type Metadata<T: Config<I>, I: 'static = ()> = StorageMap<
473		_,
474		Blake2_128Concat,
475		T::AssetId,
476		AssetMetadata<DepositBalanceOf<T, I>, BoundedVec<u8, T::StringLimit>>,
477		ValueQuery,
478	>;
479
480	/// Maps an asset to a list of its configured reserve information.
481	#[pallet::storage]
482	pub type Reserves<T: Config<I>, I: 'static = ()> = StorageMap<
483		_,
484		Blake2_128Concat,
485		T::AssetId,
486		BoundedVec<T::ReserveData, ConstU32<MAX_RESERVES>>,
487		ValueQuery,
488	>;
489
490	/// The asset ID enforced for the next asset creation, if any present. Otherwise, this storage
491	/// item has no effect.
492	///
493	/// This can be useful for setting up constraints for IDs of the new assets. For example, by
494	/// providing an initial [`NextAssetId`] and using the [`crate::AutoIncAssetId`] callback, an
495	/// auto-increment model can be applied to all new asset IDs.
496	///
497	/// The initial next asset ID can be set using the [`GenesisConfig`] or the
498	/// [SetNextAssetId](`migration::next_asset_id::SetNextAssetId`) migration.
499	#[pallet::storage]
500	pub type NextAssetId<T: Config<I>, I: 'static = ()> = StorageValue<_, T::AssetId, OptionQuery>;
501
502	#[pallet::genesis_config]
503	#[derive(frame_support::DefaultNoBound)]
504	pub struct GenesisConfig<T: Config<I>, I: 'static = ()> {
505		/// Genesis assets: id, owner, is_sufficient, min_balance
506		pub assets: Vec<(T::AssetId, T::AccountId, bool, T::Balance)>,
507		/// Genesis metadata: id, name, symbol, decimals
508		pub metadata: Vec<(T::AssetId, Vec<u8>, Vec<u8>, u8)>,
509		/// Genesis accounts: id, account_id, balance
510		pub accounts: Vec<(T::AssetId, T::AccountId, T::Balance)>,
511		/// Genesis [`NextAssetId`].
512		///
513		/// Refer to the [`NextAssetId`] item for more information.
514		///
515		/// This does not enforce the asset ID for the [assets](`GenesisConfig::assets`) within the
516		/// genesis config. It sets the [`NextAssetId`] after they have been created.
517		pub next_asset_id: Option<T::AssetId>,
518		/// Genesis assets and their reserves
519		pub reserves: Vec<(T::AssetId, Vec<T::ReserveData>)>,
520	}
521
522	#[pallet::genesis_build]
523	impl<T: Config<I>, I: 'static> BuildGenesisConfig for GenesisConfig<T, I> {
524		fn build(&self) {
525			for (id, owner, is_sufficient, min_balance) in &self.assets {
526				assert!(!Asset::<T, I>::contains_key(id), "Asset id already in use");
527				assert!(!min_balance.is_zero(), "Min balance should not be zero");
528				Asset::<T, I>::insert(
529					id,
530					AssetDetails {
531						owner: owner.clone(),
532						issuer: owner.clone(),
533						admin: owner.clone(),
534						freezer: owner.clone(),
535						supply: Zero::zero(),
536						deposit: Zero::zero(),
537						min_balance: *min_balance,
538						is_sufficient: *is_sufficient,
539						accounts: 0,
540						sufficients: 0,
541						approvals: 0,
542						status: AssetStatus::Live,
543					},
544				);
545			}
546
547			for (id, name, symbol, decimals) in &self.metadata {
548				assert!(Asset::<T, I>::contains_key(id), "Asset does not exist");
549
550				let bounded_name: BoundedVec<u8, T::StringLimit> =
551					name.clone().try_into().expect("asset name is too long");
552				let bounded_symbol: BoundedVec<u8, T::StringLimit> =
553					symbol.clone().try_into().expect("asset symbol is too long");
554
555				let metadata = AssetMetadata {
556					deposit: Zero::zero(),
557					name: bounded_name,
558					symbol: bounded_symbol,
559					decimals: *decimals,
560					is_frozen: false,
561				};
562				Metadata::<T, I>::insert(id, metadata);
563			}
564
565			for (id, account_id, amount) in &self.accounts {
566				let result = <Pallet<T, I>>::increase_balance(
567					id.clone(),
568					account_id,
569					*amount,
570					|details| -> DispatchResult {
571						debug_assert!(
572							details.supply.checked_add(&amount).is_some(),
573							"checked in prep; qed"
574						);
575						details.supply = details.supply.saturating_add(*amount);
576						Ok(())
577					},
578				);
579				assert!(result.is_ok());
580			}
581
582			if let Some(next_asset_id) = &self.next_asset_id {
583				NextAssetId::<T, I>::put(next_asset_id);
584			}
585
586			for (id, reserves) in &self.reserves {
587				assert!(!Reserves::<T, I>::contains_key(id), "Asset id already in use");
588				let reserves = BoundedVec::try_from(reserves.clone()).expect("too many reserves");
589				Reserves::<T, I>::insert(id, reserves);
590			}
591		}
592	}
593
594	#[pallet::event]
595	#[pallet::generate_deposit(pub(super) fn deposit_event)]
596	pub enum Event<T: Config<I>, I: 'static = ()> {
597		/// Some asset class was created.
598		Created { asset_id: T::AssetId, creator: T::AccountId, owner: T::AccountId },
599		/// Some assets were issued.
600		Issued { asset_id: T::AssetId, owner: T::AccountId, amount: T::Balance },
601		/// Some assets were transferred.
602		Transferred {
603			asset_id: T::AssetId,
604			from: T::AccountId,
605			to: T::AccountId,
606			amount: T::Balance,
607		},
608		/// Some assets were destroyed.
609		Burned { asset_id: T::AssetId, owner: T::AccountId, balance: T::Balance },
610		/// The management team changed.
611		TeamChanged {
612			asset_id: T::AssetId,
613			issuer: T::AccountId,
614			admin: T::AccountId,
615			freezer: T::AccountId,
616		},
617		/// The owner changed.
618		OwnerChanged { asset_id: T::AssetId, owner: T::AccountId },
619		/// Some account `who` was frozen.
620		Frozen { asset_id: T::AssetId, who: T::AccountId },
621		/// Some account `who` was thawed.
622		Thawed { asset_id: T::AssetId, who: T::AccountId },
623		/// Some asset `asset_id` was frozen.
624		AssetFrozen { asset_id: T::AssetId },
625		/// Some asset `asset_id` was thawed.
626		AssetThawed { asset_id: T::AssetId },
627		/// Accounts were destroyed for given asset.
628		AccountsDestroyed { asset_id: T::AssetId, accounts_destroyed: u32, accounts_remaining: u32 },
629		/// Approvals were destroyed for given asset.
630		ApprovalsDestroyed {
631			asset_id: T::AssetId,
632			approvals_destroyed: u32,
633			approvals_remaining: u32,
634		},
635		/// An asset class is in the process of being destroyed.
636		DestructionStarted { asset_id: T::AssetId },
637		/// An asset class was destroyed.
638		Destroyed { asset_id: T::AssetId },
639		/// Some asset class was force-created.
640		ForceCreated { asset_id: T::AssetId, owner: T::AccountId },
641		/// New metadata has been set for an asset.
642		MetadataSet {
643			asset_id: T::AssetId,
644			name: Vec<u8>,
645			symbol: Vec<u8>,
646			decimals: u8,
647			is_frozen: bool,
648		},
649		/// Metadata has been cleared for an asset.
650		MetadataCleared { asset_id: T::AssetId },
651		/// (Additional) funds have been approved for transfer to a destination account.
652		ApprovedTransfer {
653			asset_id: T::AssetId,
654			source: T::AccountId,
655			delegate: T::AccountId,
656			amount: T::Balance,
657		},
658		/// An approval for account `delegate` was cancelled by `owner`.
659		ApprovalCancelled { asset_id: T::AssetId, owner: T::AccountId, delegate: T::AccountId },
660		/// An `amount` was transferred in its entirety from `owner` to `destination` by
661		/// the approved `delegate`.
662		TransferredApproved {
663			asset_id: T::AssetId,
664			owner: T::AccountId,
665			delegate: T::AccountId,
666			destination: T::AccountId,
667			amount: T::Balance,
668		},
669		/// An asset has had its attributes changed by the `Force` origin.
670		AssetStatusChanged { asset_id: T::AssetId },
671		/// The min_balance of an asset has been updated by the asset owner.
672		AssetMinBalanceChanged { asset_id: T::AssetId, new_min_balance: T::Balance },
673		/// Some account `who` was created with a deposit from `depositor`.
674		Touched { asset_id: T::AssetId, who: T::AccountId, depositor: T::AccountId },
675		/// Some account `who` was blocked.
676		Blocked { asset_id: T::AssetId, who: T::AccountId },
677		/// Some assets were deposited (e.g. for transaction fees).
678		Deposited { asset_id: T::AssetId, who: T::AccountId, amount: T::Balance },
679		/// Some assets were withdrawn from the account (e.g. for transaction fees).
680		Withdrawn { asset_id: T::AssetId, who: T::AccountId, amount: T::Balance },
681		/// Reserve information was set or updated for `asset_id`.
682		ReservesUpdated { asset_id: T::AssetId, reserves: Vec<T::ReserveData> },
683		/// Reserve information was removed for `asset_id`.
684		ReservesRemoved { asset_id: T::AssetId },
685	}
686
687	#[pallet::error]
688	pub enum Error<T, I = ()> {
689		/// Account balance must be greater than or equal to the transfer amount.
690		BalanceLow,
691		/// The account to alter does not exist.
692		NoAccount,
693		/// The signing account has no permission to do the operation.
694		NoPermission,
695		/// The given asset ID is unknown.
696		Unknown,
697		/// The origin account is frozen.
698		Frozen,
699		/// The asset ID is already taken.
700		InUse,
701		/// Invalid witness data given.
702		BadWitness,
703		/// Minimum balance should be non-zero.
704		MinBalanceZero,
705		/// Unable to increment the consumer reference counters on the account. Either no provider
706		/// reference exists to allow a non-zero balance of a non-self-sufficient asset, or one
707		/// fewer then the maximum number of consumers has been reached.
708		UnavailableConsumer,
709		/// Invalid metadata given.
710		BadMetadata,
711		/// No approval exists that would allow the transfer.
712		Unapproved,
713		/// The source account would not survive the transfer and it needs to stay alive.
714		WouldDie,
715		/// The asset-account already exists.
716		AlreadyExists,
717		/// The asset-account doesn't have an associated deposit.
718		NoDeposit,
719		/// The operation would result in funds being burned.
720		WouldBurn,
721		/// The asset is a live asset and is actively being used. Usually emit for operations such
722		/// as `start_destroy` which require the asset to be in a destroying state.
723		LiveAsset,
724		/// The asset is not live, and likely being destroyed.
725		AssetNotLive,
726		/// The asset status is not the expected status.
727		IncorrectStatus,
728		/// The asset should be frozen before the given operation.
729		NotFrozen,
730		/// Callback action resulted in error
731		CallbackFailed,
732		/// The asset ID must be equal to the [`NextAssetId`].
733		BadAssetId,
734		/// The asset cannot be destroyed because some accounts for this asset contain freezes.
735		ContainsFreezes,
736		/// The asset cannot be destroyed because some accounts for this asset contain holds.
737		ContainsHolds,
738		/// Tried setting too many reserves.
739		TooManyReserves,
740	}
741
742	#[pallet::call(weight(<T as Config<I>>::WeightInfo))]
743	impl<T: Config<I>, I: 'static> Pallet<T, I> {
744		/// Issue a new class of fungible assets from a public origin.
745		///
746		/// This new asset class has no assets initially and its owner is the origin.
747		///
748		/// The origin must conform to the configured `CreateOrigin` and have sufficient funds free.
749		///
750		/// Funds of sender are reserved by `AssetDeposit`.
751		///
752		/// Parameters:
753		/// - `id`: The identifier of the new asset. This must not be currently in use to identify
754		/// an existing asset. If [`NextAssetId`] is set, then this must be equal to it.
755		/// - `admin`: The admin of this class of assets. The admin is the initial address of each
756		/// member of the asset class's admin team.
757		/// - `min_balance`: The minimum balance of this new asset that any single account must
758		/// have. If an account's balance is reduced below this, then it collapses to zero.
759		///
760		/// Emits `Created` event when successful.
761		///
762		/// Weight: `O(1)`
763		#[pallet::call_index(0)]
764		pub fn create(
765			origin: OriginFor<T>,
766			id: T::AssetIdParameter,
767			admin: AccountIdLookupOf<T>,
768			min_balance: T::Balance,
769		) -> DispatchResult {
770			let id: T::AssetId = id.into();
771			let owner = T::CreateOrigin::ensure_origin(origin, &id)?;
772			let admin = T::Lookup::lookup(admin)?;
773
774			ensure!(!Asset::<T, I>::contains_key(&id), Error::<T, I>::InUse);
775			ensure!(!min_balance.is_zero(), Error::<T, I>::MinBalanceZero);
776
777			if let Some(next_id) = NextAssetId::<T, I>::get() {
778				ensure!(id == next_id, Error::<T, I>::BadAssetId);
779			}
780
781			let deposit = T::AssetDeposit::get();
782			T::Currency::reserve(&owner, deposit)?;
783
784			Asset::<T, I>::insert(
785				id.clone(),
786				AssetDetails {
787					owner: owner.clone(),
788					issuer: admin.clone(),
789					admin: admin.clone(),
790					freezer: admin.clone(),
791					supply: Zero::zero(),
792					deposit,
793					min_balance,
794					is_sufficient: false,
795					accounts: 0,
796					sufficients: 0,
797					approvals: 0,
798					status: AssetStatus::Live,
799				},
800			);
801			ensure!(T::CallbackHandle::created(&id, &owner).is_ok(), Error::<T, I>::CallbackFailed);
802			Self::deposit_event(Event::Created {
803				asset_id: id,
804				creator: owner.clone(),
805				owner: admin,
806			});
807
808			Ok(())
809		}
810
811		/// Issue a new class of fungible assets from a privileged origin.
812		///
813		/// This new asset class has no assets initially.
814		///
815		/// The origin must conform to `ForceOrigin`.
816		///
817		/// Unlike `create`, no funds are reserved.
818		///
819		/// - `id`: The identifier of the new asset. This must not be currently in use to identify
820		/// an existing asset. If [`NextAssetId`] is set, then this must be equal to it.
821		/// - `owner`: The owner of this class of assets. The owner has full superuser permissions
822		/// over this asset, but may later change and configure the permissions using
823		/// `transfer_ownership` and `set_team`.
824		/// - `min_balance`: The minimum balance of this new asset that any single account must
825		/// have. If an account's balance is reduced below this, then it collapses to zero.
826		///
827		/// Emits `ForceCreated` event when successful.
828		///
829		/// Weight: `O(1)`
830		#[pallet::call_index(1)]
831		pub fn force_create(
832			origin: OriginFor<T>,
833			id: T::AssetIdParameter,
834			owner: AccountIdLookupOf<T>,
835			is_sufficient: bool,
836			#[pallet::compact] min_balance: T::Balance,
837		) -> DispatchResult {
838			T::ForceOrigin::ensure_origin(origin)?;
839			let owner = T::Lookup::lookup(owner)?;
840			let id: T::AssetId = id.into();
841			Self::do_force_create(id, owner, is_sufficient, min_balance)
842		}
843
844		/// Start the process of destroying a fungible asset class.
845		///
846		/// `start_destroy` is the first in a series of extrinsics that should be called, to allow
847		/// destruction of an asset class.
848		///
849		/// The origin must conform to `ForceOrigin` or must be `Signed` by the asset's `owner`.
850		///
851		/// - `id`: The identifier of the asset to be destroyed. This must identify an existing
852		///   asset.
853		///
854		/// It will fail with either [`Error::ContainsHolds`] or [`Error::ContainsFreezes`] if
855		/// an account contains holds or freezes in place.
856		#[pallet::call_index(2)]
857		pub fn start_destroy(origin: OriginFor<T>, id: T::AssetIdParameter) -> DispatchResult {
858			let maybe_check_owner = match T::ForceOrigin::try_origin(origin) {
859				Ok(_) => None,
860				Err(origin) => Some(ensure_signed(origin)?),
861			};
862			let id: T::AssetId = id.into();
863			Self::do_start_destroy(id, maybe_check_owner)
864		}
865
866		/// Destroy all accounts associated with a given asset.
867		///
868		/// `destroy_accounts` should only be called after `start_destroy` has been called, and the
869		/// asset is in a `Destroying` state.
870		///
871		/// Due to weight restrictions, this function may need to be called multiple times to fully
872		/// destroy all accounts. It will destroy `RemoveItemsLimit` accounts at a time.
873		///
874		/// - `id`: The identifier of the asset to be destroyed. This must identify an existing
875		///   asset.
876		///
877		/// Each call emits the `Event::DestroyedAccounts` event.
878		#[pallet::call_index(3)]
879		#[pallet::weight(T::WeightInfo::destroy_accounts(T::RemoveItemsLimit::get()))]
880		pub fn destroy_accounts(
881			origin: OriginFor<T>,
882			id: T::AssetIdParameter,
883		) -> DispatchResultWithPostInfo {
884			ensure_signed(origin)?;
885			let id: T::AssetId = id.into();
886			let removed_accounts = Self::do_destroy_accounts(id, T::RemoveItemsLimit::get())?;
887			Ok(Some(T::WeightInfo::destroy_accounts(removed_accounts)).into())
888		}
889
890		/// Destroy all approvals associated with a given asset up to the max (T::RemoveItemsLimit).
891		///
892		/// `destroy_approvals` should only be called after `start_destroy` has been called, and the
893		/// asset is in a `Destroying` state.
894		///
895		/// Due to weight restrictions, this function may need to be called multiple times to fully
896		/// destroy all approvals. It will destroy `RemoveItemsLimit` approvals at a time.
897		///
898		/// - `id`: The identifier of the asset to be destroyed. This must identify an existing
899		///   asset.
900		///
901		/// Each call emits the `Event::DestroyedApprovals` event.
902		#[pallet::call_index(4)]
903		#[pallet::weight(T::WeightInfo::destroy_approvals(T::RemoveItemsLimit::get()))]
904		pub fn destroy_approvals(
905			origin: OriginFor<T>,
906			id: T::AssetIdParameter,
907		) -> DispatchResultWithPostInfo {
908			ensure_signed(origin)?;
909			let id: T::AssetId = id.into();
910			let removed_approvals = Self::do_destroy_approvals(id, T::RemoveItemsLimit::get())?;
911			Ok(Some(T::WeightInfo::destroy_approvals(removed_approvals)).into())
912		}
913
914		/// Complete destroying asset and unreserve currency.
915		///
916		/// `finish_destroy` should only be called after `start_destroy` has been called, and the
917		/// asset is in a `Destroying` state. All accounts or approvals should be destroyed before
918		/// hand.
919		///
920		/// - `id`: The identifier of the asset to be destroyed. This must identify an existing
921		///   asset.
922		///
923		/// Each successful call emits the `Event::Destroyed` event.
924		#[pallet::call_index(5)]
925		pub fn finish_destroy(origin: OriginFor<T>, id: T::AssetIdParameter) -> DispatchResult {
926			ensure_signed(origin)?;
927			let id: T::AssetId = id.into();
928			Self::do_finish_destroy(id)
929		}
930
931		/// Mint assets of a particular class.
932		///
933		/// The origin must be Signed and the sender must be the Issuer of the asset `id`.
934		///
935		/// - `id`: The identifier of the asset to have some amount minted.
936		/// - `beneficiary`: The account to be credited with the minted assets.
937		/// - `amount`: The amount of the asset to be minted.
938		///
939		/// Emits `Issued` event when successful.
940		///
941		/// Weight: `O(1)`
942		/// Modes: Pre-existing balance of `beneficiary`; Account pre-existence of `beneficiary`.
943		#[pallet::call_index(6)]
944		pub fn mint(
945			origin: OriginFor<T>,
946			id: T::AssetIdParameter,
947			beneficiary: AccountIdLookupOf<T>,
948			#[pallet::compact] amount: T::Balance,
949		) -> DispatchResult {
950			let origin = ensure_signed(origin)?;
951			let beneficiary = T::Lookup::lookup(beneficiary)?;
952			let id: T::AssetId = id.into();
953			Self::do_mint(id, &beneficiary, amount, Some(origin))?;
954			Ok(())
955		}
956
957		/// Reduce the balance of `who` by as much as possible up to `amount` assets of `id`.
958		///
959		/// Origin must be Signed and the sender should be the Manager of the asset `id`.
960		///
961		/// Bails with `NoAccount` if the `who` is already dead.
962		///
963		/// - `id`: The identifier of the asset to have some amount burned.
964		/// - `who`: The account to be debited from.
965		/// - `amount`: The maximum amount by which `who`'s balance should be reduced.
966		///
967		/// Emits `Burned` with the actual amount burned. If this takes the balance to below the
968		/// minimum for the asset, then the amount burned is increased to take it to zero.
969		///
970		/// Weight: `O(1)`
971		/// Modes: Post-existence of `who`; Pre & post Zombie-status of `who`.
972		#[pallet::call_index(7)]
973		pub fn burn(
974			origin: OriginFor<T>,
975			id: T::AssetIdParameter,
976			who: AccountIdLookupOf<T>,
977			#[pallet::compact] amount: T::Balance,
978		) -> DispatchResult {
979			let origin = ensure_signed(origin)?;
980			let who = T::Lookup::lookup(who)?;
981			let id: T::AssetId = id.into();
982
983			let f = DebitFlags { keep_alive: false, best_effort: true };
984			Self::do_burn(id, &who, amount, Some(origin), f)?;
985			Ok(())
986		}
987
988		/// Move some assets from the sender account to another.
989		///
990		/// Origin must be Signed.
991		///
992		/// - `id`: The identifier of the asset to have some amount transferred.
993		/// - `target`: The account to be credited.
994		/// - `amount`: The amount by which the sender's balance of assets should be reduced and
995		/// `target`'s balance increased. The amount actually transferred may be slightly greater in
996		/// the case that the transfer would otherwise take the sender balance above zero but below
997		/// the minimum balance. Must be greater than zero.
998		///
999		/// Emits `Transferred` with the actual amount transferred. If this takes the source balance
1000		/// to below the minimum for the asset, then the amount transferred is increased to take it
1001		/// to zero.
1002		///
1003		/// Weight: `O(1)`
1004		/// Modes: Pre-existence of `target`; Post-existence of sender; Account pre-existence of
1005		/// `target`.
1006		#[pallet::call_index(8)]
1007		pub fn transfer(
1008			origin: OriginFor<T>,
1009			id: T::AssetIdParameter,
1010			target: AccountIdLookupOf<T>,
1011			#[pallet::compact] amount: T::Balance,
1012		) -> DispatchResult {
1013			let origin = ensure_signed(origin)?;
1014			let dest = T::Lookup::lookup(target)?;
1015			let id: T::AssetId = id.into();
1016
1017			let f = TransferFlags { keep_alive: false, best_effort: false, burn_dust: false };
1018			Self::do_transfer(id, &origin, &dest, amount, None, f).map(|_| ())
1019		}
1020
1021		/// Move some assets from the sender account to another, keeping the sender account alive.
1022		///
1023		/// Origin must be Signed.
1024		///
1025		/// - `id`: The identifier of the asset to have some amount transferred.
1026		/// - `target`: The account to be credited.
1027		/// - `amount`: The amount by which the sender's balance of assets should be reduced and
1028		/// `target`'s balance increased. The amount actually transferred may be slightly greater in
1029		/// the case that the transfer would otherwise take the sender balance above zero but below
1030		/// the minimum balance. Must be greater than zero.
1031		///
1032		/// Emits `Transferred` with the actual amount transferred. If this takes the source balance
1033		/// to below the minimum for the asset, then the amount transferred is increased to take it
1034		/// to zero.
1035		///
1036		/// Weight: `O(1)`
1037		/// Modes: Pre-existence of `target`; Post-existence of sender; Account pre-existence of
1038		/// `target`.
1039		#[pallet::call_index(9)]
1040		pub fn transfer_keep_alive(
1041			origin: OriginFor<T>,
1042			id: T::AssetIdParameter,
1043			target: AccountIdLookupOf<T>,
1044			#[pallet::compact] amount: T::Balance,
1045		) -> DispatchResult {
1046			let source = ensure_signed(origin)?;
1047			let dest = T::Lookup::lookup(target)?;
1048			let id: T::AssetId = id.into();
1049
1050			let f = TransferFlags { keep_alive: true, best_effort: false, burn_dust: false };
1051			Self::do_transfer(id, &source, &dest, amount, None, f).map(|_| ())
1052		}
1053
1054		/// Move some assets from one account to another.
1055		///
1056		/// Origin must be Signed and the sender should be the Admin of the asset `id`.
1057		///
1058		/// - `id`: The identifier of the asset to have some amount transferred.
1059		/// - `source`: The account to be debited.
1060		/// - `dest`: The account to be credited.
1061		/// - `amount`: The amount by which the `source`'s balance of assets should be reduced and
1062		/// `dest`'s balance increased. The amount actually transferred may be slightly greater in
1063		/// the case that the transfer would otherwise take the `source` balance above zero but
1064		/// below the minimum balance. Must be greater than zero.
1065		///
1066		/// Emits `Transferred` with the actual amount transferred. If this takes the source balance
1067		/// to below the minimum for the asset, then the amount transferred is increased to take it
1068		/// to zero.
1069		///
1070		/// Weight: `O(1)`
1071		/// Modes: Pre-existence of `dest`; Post-existence of `source`; Account pre-existence of
1072		/// `dest`.
1073		#[pallet::call_index(10)]
1074		pub fn force_transfer(
1075			origin: OriginFor<T>,
1076			id: T::AssetIdParameter,
1077			source: AccountIdLookupOf<T>,
1078			dest: AccountIdLookupOf<T>,
1079			#[pallet::compact] amount: T::Balance,
1080		) -> DispatchResult {
1081			let origin = ensure_signed(origin)?;
1082			let source = T::Lookup::lookup(source)?;
1083			let dest = T::Lookup::lookup(dest)?;
1084			let id: T::AssetId = id.into();
1085
1086			let f = TransferFlags { keep_alive: false, best_effort: false, burn_dust: false };
1087			Self::do_transfer(id, &source, &dest, amount, Some(origin), f).map(|_| ())
1088		}
1089
1090		/// Disallow further unprivileged transfers of an asset `id` from an account `who`. `who`
1091		/// must already exist as an entry in `Account`s of the asset. If you want to freeze an
1092		/// account that does not have an entry, use `touch_other` first.
1093		///
1094		/// Origin must be Signed and the sender should be the Freezer of the asset `id`.
1095		///
1096		/// - `id`: The identifier of the asset to be frozen.
1097		/// - `who`: The account to be frozen.
1098		///
1099		/// Emits `Frozen`.
1100		///
1101		/// Weight: `O(1)`
1102		#[pallet::call_index(11)]
1103		pub fn freeze(
1104			origin: OriginFor<T>,
1105			id: T::AssetIdParameter,
1106			who: AccountIdLookupOf<T>,
1107		) -> DispatchResult {
1108			let origin = ensure_signed(origin)?;
1109			let id: T::AssetId = id.into();
1110
1111			let d = Asset::<T, I>::get(&id).ok_or(Error::<T, I>::Unknown)?;
1112			ensure!(
1113				d.status == AssetStatus::Live || d.status == AssetStatus::Frozen,
1114				Error::<T, I>::IncorrectStatus
1115			);
1116			ensure!(origin == d.freezer, Error::<T, I>::NoPermission);
1117			let who = T::Lookup::lookup(who)?;
1118
1119			Account::<T, I>::try_mutate(&id, &who, |maybe_account| -> DispatchResult {
1120				maybe_account.as_mut().ok_or(Error::<T, I>::NoAccount)?.status =
1121					AccountStatus::Frozen;
1122				Ok(())
1123			})?;
1124
1125			Self::deposit_event(Event::<T, I>::Frozen { asset_id: id, who });
1126			Ok(())
1127		}
1128
1129		/// Allow unprivileged transfers to and from an account again.
1130		///
1131		/// Origin must be Signed and the sender should be the Admin of the asset `id`.
1132		///
1133		/// - `id`: The identifier of the asset to be frozen.
1134		/// - `who`: The account to be unfrozen.
1135		///
1136		/// Emits `Thawed`.
1137		///
1138		/// Weight: `O(1)`
1139		#[pallet::call_index(12)]
1140		pub fn thaw(
1141			origin: OriginFor<T>,
1142			id: T::AssetIdParameter,
1143			who: AccountIdLookupOf<T>,
1144		) -> DispatchResult {
1145			let origin = ensure_signed(origin)?;
1146			let id: T::AssetId = id.into();
1147
1148			let details = Asset::<T, I>::get(&id).ok_or(Error::<T, I>::Unknown)?;
1149			ensure!(
1150				details.status == AssetStatus::Live || details.status == AssetStatus::Frozen,
1151				Error::<T, I>::IncorrectStatus
1152			);
1153			ensure!(origin == details.admin, Error::<T, I>::NoPermission);
1154			let who = T::Lookup::lookup(who)?;
1155
1156			Account::<T, I>::try_mutate(&id, &who, |maybe_account| -> DispatchResult {
1157				maybe_account.as_mut().ok_or(Error::<T, I>::NoAccount)?.status =
1158					AccountStatus::Liquid;
1159				Ok(())
1160			})?;
1161
1162			Self::deposit_event(Event::<T, I>::Thawed { asset_id: id, who });
1163			Ok(())
1164		}
1165
1166		/// Disallow further unprivileged transfers for the asset class.
1167		///
1168		/// Origin must be Signed and the sender should be the Freezer of the asset `id`.
1169		///
1170		/// - `id`: The identifier of the asset to be frozen.
1171		///
1172		/// Emits `Frozen`.
1173		///
1174		/// Weight: `O(1)`
1175		#[pallet::call_index(13)]
1176		pub fn freeze_asset(origin: OriginFor<T>, id: T::AssetIdParameter) -> DispatchResult {
1177			let origin = ensure_signed(origin)?;
1178			let id: T::AssetId = id.into();
1179
1180			Asset::<T, I>::try_mutate(id.clone(), |maybe_details| {
1181				let d = maybe_details.as_mut().ok_or(Error::<T, I>::Unknown)?;
1182				ensure!(d.status == AssetStatus::Live, Error::<T, I>::AssetNotLive);
1183				ensure!(origin == d.freezer, Error::<T, I>::NoPermission);
1184
1185				d.status = AssetStatus::Frozen;
1186
1187				Self::deposit_event(Event::<T, I>::AssetFrozen { asset_id: id });
1188				Ok(())
1189			})
1190		}
1191
1192		/// Allow unprivileged transfers for the asset again.
1193		///
1194		/// Origin must be Signed and the sender should be the Admin of the asset `id`.
1195		///
1196		/// - `id`: The identifier of the asset to be thawed.
1197		///
1198		/// Emits `Thawed`.
1199		///
1200		/// Weight: `O(1)`
1201		#[pallet::call_index(14)]
1202		pub fn thaw_asset(origin: OriginFor<T>, id: T::AssetIdParameter) -> DispatchResult {
1203			let origin = ensure_signed(origin)?;
1204			let id: T::AssetId = id.into();
1205
1206			Asset::<T, I>::try_mutate(id.clone(), |maybe_details| {
1207				let d = maybe_details.as_mut().ok_or(Error::<T, I>::Unknown)?;
1208				ensure!(origin == d.admin, Error::<T, I>::NoPermission);
1209				ensure!(d.status == AssetStatus::Frozen, Error::<T, I>::NotFrozen);
1210
1211				d.status = AssetStatus::Live;
1212
1213				Self::deposit_event(Event::<T, I>::AssetThawed { asset_id: id });
1214				Ok(())
1215			})
1216		}
1217
1218		/// Change the Owner of an asset.
1219		///
1220		/// Origin must be Signed and the sender should be the Owner of the asset `id`.
1221		///
1222		/// - `id`: The identifier of the asset.
1223		/// - `owner`: The new Owner of this asset.
1224		///
1225		/// Emits `OwnerChanged`.
1226		///
1227		/// Weight: `O(1)`
1228		#[pallet::call_index(15)]
1229		pub fn transfer_ownership(
1230			origin: OriginFor<T>,
1231			id: T::AssetIdParameter,
1232			owner: AccountIdLookupOf<T>,
1233		) -> DispatchResult {
1234			let origin = ensure_signed(origin)?;
1235			let owner = T::Lookup::lookup(owner)?;
1236			let id: T::AssetId = id.into();
1237
1238			Asset::<T, I>::try_mutate(id.clone(), |maybe_details| {
1239				let details = maybe_details.as_mut().ok_or(Error::<T, I>::Unknown)?;
1240				ensure!(details.status == AssetStatus::Live, Error::<T, I>::AssetNotLive);
1241				ensure!(origin == details.owner, Error::<T, I>::NoPermission);
1242				if details.owner == owner {
1243					return Ok(());
1244				}
1245
1246				let metadata_deposit = Metadata::<T, I>::get(&id).deposit;
1247				let deposit = details.deposit + metadata_deposit;
1248
1249				// Move the deposit to the new owner.
1250				T::Currency::repatriate_reserved(&details.owner, &owner, deposit, Reserved)?;
1251
1252				details.owner = owner.clone();
1253
1254				Self::deposit_event(Event::OwnerChanged { asset_id: id, owner });
1255				Ok(())
1256			})
1257		}
1258
1259		/// Change the Issuer, Admin and Freezer of an asset.
1260		///
1261		/// Origin must be Signed and the sender should be the Owner of the asset `id`.
1262		///
1263		/// - `id`: The identifier of the asset to be frozen.
1264		/// - `issuer`: The new Issuer of this asset.
1265		/// - `admin`: The new Admin of this asset.
1266		/// - `freezer`: The new Freezer of this asset.
1267		///
1268		/// Emits `TeamChanged`.
1269		///
1270		/// Weight: `O(1)`
1271		#[pallet::call_index(16)]
1272		pub fn set_team(
1273			origin: OriginFor<T>,
1274			id: T::AssetIdParameter,
1275			issuer: AccountIdLookupOf<T>,
1276			admin: AccountIdLookupOf<T>,
1277			freezer: AccountIdLookupOf<T>,
1278		) -> DispatchResult {
1279			let origin = ensure_signed(origin)?;
1280			let issuer = T::Lookup::lookup(issuer)?;
1281			let admin = T::Lookup::lookup(admin)?;
1282			let freezer = T::Lookup::lookup(freezer)?;
1283			let id: T::AssetId = id.into();
1284
1285			Asset::<T, I>::try_mutate(id.clone(), |maybe_details| {
1286				let details = maybe_details.as_mut().ok_or(Error::<T, I>::Unknown)?;
1287				ensure!(details.status == AssetStatus::Live, Error::<T, I>::AssetNotLive);
1288				ensure!(origin == details.owner, Error::<T, I>::NoPermission);
1289
1290				details.issuer = issuer.clone();
1291				details.admin = admin.clone();
1292				details.freezer = freezer.clone();
1293
1294				Self::deposit_event(Event::TeamChanged { asset_id: id, issuer, admin, freezer });
1295				Ok(())
1296			})
1297		}
1298
1299		/// Set the metadata for an asset.
1300		///
1301		/// Origin must be Signed and the sender should be the Owner of the asset `id`.
1302		///
1303		/// Funds of sender are reserved according to the formula:
1304		/// `MetadataDepositBase + MetadataDepositPerByte * (name.len + symbol.len)` taking into
1305		/// account any already reserved funds.
1306		///
1307		/// - `id`: The identifier of the asset to update.
1308		/// - `name`: The user friendly name of this asset. Limited in length by `StringLimit`.
1309		/// - `symbol`: The exchange symbol for this asset. Limited in length by `StringLimit`.
1310		/// - `decimals`: The number of decimals this asset uses to represent one unit.
1311		///
1312		/// Emits `MetadataSet`.
1313		///
1314		/// Weight: `O(1)`
1315		#[pallet::call_index(17)]
1316		#[pallet::weight(T::WeightInfo::set_metadata(name.len() as u32, symbol.len() as u32))]
1317		pub fn set_metadata(
1318			origin: OriginFor<T>,
1319			id: T::AssetIdParameter,
1320			name: Vec<u8>,
1321			symbol: Vec<u8>,
1322			decimals: u8,
1323		) -> DispatchResult {
1324			let origin = ensure_signed(origin)?;
1325			let id: T::AssetId = id.into();
1326			Self::do_set_metadata(id, &origin, name, symbol, decimals)
1327		}
1328
1329		/// Clear the metadata for an asset.
1330		///
1331		/// Origin must be Signed and the sender should be the Owner of the asset `id`.
1332		///
1333		/// Any deposit is freed for the asset owner.
1334		///
1335		/// - `id`: The identifier of the asset to clear.
1336		///
1337		/// Emits `MetadataCleared`.
1338		///
1339		/// Weight: `O(1)`
1340		#[pallet::call_index(18)]
1341		pub fn clear_metadata(origin: OriginFor<T>, id: T::AssetIdParameter) -> DispatchResult {
1342			let origin = ensure_signed(origin)?;
1343			let id: T::AssetId = id.into();
1344
1345			let d = Asset::<T, I>::get(&id).ok_or(Error::<T, I>::Unknown)?;
1346			ensure!(d.status == AssetStatus::Live, Error::<T, I>::AssetNotLive);
1347			ensure!(origin == d.owner, Error::<T, I>::NoPermission);
1348
1349			Metadata::<T, I>::try_mutate_exists(id.clone(), |metadata| {
1350				let deposit = metadata.take().ok_or(Error::<T, I>::Unknown)?.deposit;
1351				T::Currency::unreserve(&d.owner, deposit);
1352				Self::deposit_event(Event::MetadataCleared { asset_id: id });
1353				Ok(())
1354			})
1355		}
1356
1357		/// Force the metadata for an asset to some value.
1358		///
1359		/// Origin must be ForceOrigin.
1360		///
1361		/// Any deposit is left alone.
1362		///
1363		/// - `id`: The identifier of the asset to update.
1364		/// - `name`: The user friendly name of this asset. Limited in length by `StringLimit`.
1365		/// - `symbol`: The exchange symbol for this asset. Limited in length by `StringLimit`.
1366		/// - `decimals`: The number of decimals this asset uses to represent one unit.
1367		///
1368		/// Emits `MetadataSet`.
1369		///
1370		/// Weight: `O(N + S)` where N and S are the length of the name and symbol respectively.
1371		#[pallet::call_index(19)]
1372		#[pallet::weight(T::WeightInfo::force_set_metadata(name.len() as u32, symbol.len() as u32))]
1373		pub fn force_set_metadata(
1374			origin: OriginFor<T>,
1375			id: T::AssetIdParameter,
1376			name: Vec<u8>,
1377			symbol: Vec<u8>,
1378			decimals: u8,
1379			is_frozen: bool,
1380		) -> DispatchResult {
1381			T::ForceOrigin::ensure_origin(origin)?;
1382			let id: T::AssetId = id.into();
1383
1384			let bounded_name: BoundedVec<u8, T::StringLimit> =
1385				name.clone().try_into().map_err(|_| Error::<T, I>::BadMetadata)?;
1386
1387			let bounded_symbol: BoundedVec<u8, T::StringLimit> =
1388				symbol.clone().try_into().map_err(|_| Error::<T, I>::BadMetadata)?;
1389
1390			ensure!(Asset::<T, I>::contains_key(&id), Error::<T, I>::Unknown);
1391			Metadata::<T, I>::try_mutate_exists(id.clone(), |metadata| {
1392				let deposit = metadata.take().map_or(Zero::zero(), |m| m.deposit);
1393				*metadata = Some(AssetMetadata {
1394					deposit,
1395					name: bounded_name,
1396					symbol: bounded_symbol,
1397					decimals,
1398					is_frozen,
1399				});
1400
1401				Self::deposit_event(Event::MetadataSet {
1402					asset_id: id,
1403					name,
1404					symbol,
1405					decimals,
1406					is_frozen,
1407				});
1408				Ok(())
1409			})
1410		}
1411
1412		/// Clear the metadata for an asset.
1413		///
1414		/// Origin must be ForceOrigin.
1415		///
1416		/// Any deposit is returned.
1417		///
1418		/// - `id`: The identifier of the asset to clear.
1419		///
1420		/// Emits `MetadataCleared`.
1421		///
1422		/// Weight: `O(1)`
1423		#[pallet::call_index(20)]
1424		pub fn force_clear_metadata(
1425			origin: OriginFor<T>,
1426			id: T::AssetIdParameter,
1427		) -> DispatchResult {
1428			T::ForceOrigin::ensure_origin(origin)?;
1429			let id: T::AssetId = id.into();
1430
1431			let d = Asset::<T, I>::get(&id).ok_or(Error::<T, I>::Unknown)?;
1432			Metadata::<T, I>::try_mutate_exists(id.clone(), |metadata| {
1433				let deposit = metadata.take().ok_or(Error::<T, I>::Unknown)?.deposit;
1434				T::Currency::unreserve(&d.owner, deposit);
1435				Self::deposit_event(Event::MetadataCleared { asset_id: id });
1436				Ok(())
1437			})
1438		}
1439
1440		/// Alter the attributes of a given asset.
1441		///
1442		/// Origin must be `ForceOrigin`.
1443		///
1444		/// - `id`: The identifier of the asset.
1445		/// - `owner`: The new Owner of this asset.
1446		/// - `issuer`: The new Issuer of this asset.
1447		/// - `admin`: The new Admin of this asset.
1448		/// - `freezer`: The new Freezer of this asset.
1449		/// - `min_balance`: The minimum balance of this new asset that any single account must
1450		/// have. If an account's balance is reduced below this, then it collapses to zero.
1451		/// - `is_sufficient`: Whether a non-zero balance of this asset is deposit of sufficient
1452		/// value to account for the state bloat associated with its balance storage. If set to
1453		/// `true`, then non-zero balances may be stored without a `consumer` reference (and thus
1454		/// an ED in the Balances pallet or whatever else is used to control user-account state
1455		/// growth).
1456		/// - `is_frozen`: Whether this asset class is frozen except for permissioned/admin
1457		/// instructions.
1458		///
1459		/// Emits `AssetStatusChanged` with the identity of the asset.
1460		///
1461		/// Weight: `O(1)`
1462		#[pallet::call_index(21)]
1463		pub fn force_asset_status(
1464			origin: OriginFor<T>,
1465			id: T::AssetIdParameter,
1466			owner: AccountIdLookupOf<T>,
1467			issuer: AccountIdLookupOf<T>,
1468			admin: AccountIdLookupOf<T>,
1469			freezer: AccountIdLookupOf<T>,
1470			#[pallet::compact] min_balance: T::Balance,
1471			is_sufficient: bool,
1472			is_frozen: bool,
1473		) -> DispatchResult {
1474			T::ForceOrigin::ensure_origin(origin)?;
1475			let id: T::AssetId = id.into();
1476
1477			Asset::<T, I>::try_mutate(id.clone(), |maybe_asset| {
1478				let mut asset = maybe_asset.take().ok_or(Error::<T, I>::Unknown)?;
1479				ensure!(asset.status != AssetStatus::Destroying, Error::<T, I>::AssetNotLive);
1480				asset.owner = T::Lookup::lookup(owner)?;
1481				asset.issuer = T::Lookup::lookup(issuer)?;
1482				asset.admin = T::Lookup::lookup(admin)?;
1483				asset.freezer = T::Lookup::lookup(freezer)?;
1484				asset.min_balance = min_balance;
1485				asset.is_sufficient = is_sufficient;
1486				if is_frozen {
1487					asset.status = AssetStatus::Frozen;
1488				} else {
1489					asset.status = AssetStatus::Live;
1490				}
1491				*maybe_asset = Some(asset);
1492
1493				Self::deposit_event(Event::AssetStatusChanged { asset_id: id });
1494				Ok(())
1495			})
1496		}
1497
1498		/// Approve an amount of asset for transfer by a delegated third-party account.
1499		///
1500		/// Origin must be Signed.
1501		///
1502		/// Ensures that `ApprovalDeposit` worth of `Currency` is reserved from signing account
1503		/// for the purpose of holding the approval. If some non-zero amount of assets is already
1504		/// approved from signing account to `delegate`, then it is topped up or unreserved to
1505		/// meet the right value.
1506		///
1507		/// NOTE: The signing account does not need to own `amount` of assets at the point of
1508		/// making this call.
1509		///
1510		/// - `id`: The identifier of the asset.
1511		/// - `delegate`: The account to delegate permission to transfer asset.
1512		/// - `amount`: The amount of asset that may be transferred by `delegate`. If there is
1513		/// already an approval in place, then this acts additively.
1514		///
1515		/// Emits `ApprovedTransfer` on success.
1516		///
1517		/// Weight: `O(1)`
1518		#[pallet::call_index(22)]
1519		pub fn approve_transfer(
1520			origin: OriginFor<T>,
1521			id: T::AssetIdParameter,
1522			delegate: AccountIdLookupOf<T>,
1523			#[pallet::compact] amount: T::Balance,
1524		) -> DispatchResult {
1525			let owner = ensure_signed(origin)?;
1526			let delegate = T::Lookup::lookup(delegate)?;
1527			let id: T::AssetId = id.into();
1528			Self::do_approve_transfer(id, &owner, &delegate, amount)
1529		}
1530
1531		/// Cancel all of some asset approved for delegated transfer by a third-party account.
1532		///
1533		/// Origin must be Signed and there must be an approval in place between signer and
1534		/// `delegate`.
1535		///
1536		/// Unreserves any deposit previously reserved by `approve_transfer` for the approval.
1537		///
1538		/// - `id`: The identifier of the asset.
1539		/// - `delegate`: The account delegated permission to transfer asset.
1540		///
1541		/// Emits `ApprovalCancelled` on success.
1542		///
1543		/// Weight: `O(1)`
1544		#[pallet::call_index(23)]
1545		pub fn cancel_approval(
1546			origin: OriginFor<T>,
1547			id: T::AssetIdParameter,
1548			delegate: AccountIdLookupOf<T>,
1549		) -> DispatchResult {
1550			let owner = ensure_signed(origin)?;
1551			let delegate = T::Lookup::lookup(delegate)?;
1552			let id: T::AssetId = id.into();
1553			let mut d = Asset::<T, I>::get(&id).ok_or(Error::<T, I>::Unknown)?;
1554			ensure!(d.status == AssetStatus::Live, Error::<T, I>::AssetNotLive);
1555
1556			let approval = Approvals::<T, I>::take((id.clone(), &owner, &delegate))
1557				.ok_or(Error::<T, I>::Unknown)?;
1558			T::Currency::unreserve(&owner, approval.deposit);
1559
1560			d.approvals.saturating_dec();
1561			Asset::<T, I>::insert(id.clone(), d);
1562
1563			Self::deposit_event(Event::ApprovalCancelled { asset_id: id, owner, delegate });
1564			Ok(())
1565		}
1566
1567		/// Cancel all of some asset approved for delegated transfer by a third-party account.
1568		///
1569		/// Origin must be either ForceOrigin or Signed origin with the signer being the Admin
1570		/// account of the asset `id`.
1571		///
1572		/// Unreserves any deposit previously reserved by `approve_transfer` for the approval.
1573		///
1574		/// - `id`: The identifier of the asset.
1575		/// - `delegate`: The account delegated permission to transfer asset.
1576		///
1577		/// Emits `ApprovalCancelled` on success.
1578		///
1579		/// Weight: `O(1)`
1580		#[pallet::call_index(24)]
1581		pub fn force_cancel_approval(
1582			origin: OriginFor<T>,
1583			id: T::AssetIdParameter,
1584			owner: AccountIdLookupOf<T>,
1585			delegate: AccountIdLookupOf<T>,
1586		) -> DispatchResult {
1587			let id: T::AssetId = id.into();
1588			let mut d = Asset::<T, I>::get(&id).ok_or(Error::<T, I>::Unknown)?;
1589			ensure!(d.status == AssetStatus::Live, Error::<T, I>::AssetNotLive);
1590			T::ForceOrigin::try_origin(origin)
1591				.map(|_| ())
1592				.or_else(|origin| -> DispatchResult {
1593					let origin = ensure_signed(origin)?;
1594					ensure!(origin == d.admin, Error::<T, I>::NoPermission);
1595					Ok(())
1596				})?;
1597
1598			let owner = T::Lookup::lookup(owner)?;
1599			let delegate = T::Lookup::lookup(delegate)?;
1600
1601			let approval = Approvals::<T, I>::take((id.clone(), &owner, &delegate))
1602				.ok_or(Error::<T, I>::Unknown)?;
1603			T::Currency::unreserve(&owner, approval.deposit);
1604			d.approvals.saturating_dec();
1605			Asset::<T, I>::insert(id.clone(), d);
1606
1607			Self::deposit_event(Event::ApprovalCancelled { asset_id: id, owner, delegate });
1608			Ok(())
1609		}
1610
1611		/// Transfer some asset balance from a previously delegated account to some third-party
1612		/// account.
1613		///
1614		/// Origin must be Signed and there must be an approval in place by the `owner` to the
1615		/// signer.
1616		///
1617		/// If the entire amount approved for transfer is transferred, then any deposit previously
1618		/// reserved by `approve_transfer` is unreserved.
1619		///
1620		/// - `id`: The identifier of the asset.
1621		/// - `owner`: The account which previously approved for a transfer of at least `amount` and
1622		/// from which the asset balance will be withdrawn.
1623		/// - `destination`: The account to which the asset balance of `amount` will be transferred.
1624		/// - `amount`: The amount of assets to transfer.
1625		///
1626		/// Emits `TransferredApproved` on success.
1627		///
1628		/// Weight: `O(1)`
1629		#[pallet::call_index(25)]
1630		pub fn transfer_approved(
1631			origin: OriginFor<T>,
1632			id: T::AssetIdParameter,
1633			owner: AccountIdLookupOf<T>,
1634			destination: AccountIdLookupOf<T>,
1635			#[pallet::compact] amount: T::Balance,
1636		) -> DispatchResult {
1637			let delegate = ensure_signed(origin)?;
1638			let owner = T::Lookup::lookup(owner)?;
1639			let destination = T::Lookup::lookup(destination)?;
1640			let id: T::AssetId = id.into();
1641			Self::do_transfer_approved(id, &owner, &delegate, &destination, amount)
1642		}
1643
1644		/// Create an asset account for non-provider assets.
1645		///
1646		/// A deposit will be taken from the signer account.
1647		///
1648		/// - `origin`: Must be Signed; the signer account must have sufficient funds for a deposit
1649		///   to be taken.
1650		/// - `id`: The identifier of the asset for the account to be created.
1651		///
1652		/// Emits `Touched` event when successful.
1653		#[pallet::call_index(26)]
1654		#[pallet::weight(T::WeightInfo::touch())]
1655		pub fn touch(origin: OriginFor<T>, id: T::AssetIdParameter) -> DispatchResult {
1656			let who = ensure_signed(origin)?;
1657			let id: T::AssetId = id.into();
1658			Self::do_touch(id, who.clone(), who)
1659		}
1660
1661		/// Return the deposit (if any) of an asset account or a consumer reference (if any) of an
1662		/// account.
1663		///
1664		/// The origin must be Signed.
1665		///
1666		/// - `id`: The identifier of the asset for which the caller would like the deposit
1667		///   refunded.
1668		/// - `allow_burn`: If `true` then assets may be destroyed in order to complete the refund.
1669		///
1670		/// It will fail with either [`Error::ContainsHolds`] or [`Error::ContainsFreezes`] if
1671		/// the asset account contains holds or freezes in place.
1672		///
1673		/// Emits `Refunded` event when successful.
1674		#[pallet::call_index(27)]
1675		#[pallet::weight(T::WeightInfo::refund())]
1676		pub fn refund(
1677			origin: OriginFor<T>,
1678			id: T::AssetIdParameter,
1679			allow_burn: bool,
1680		) -> DispatchResult {
1681			let id: T::AssetId = id.into();
1682			Self::do_refund(id, ensure_signed(origin)?, allow_burn)
1683		}
1684
1685		/// Sets the minimum balance of an asset.
1686		///
1687		/// Only works if there aren't any accounts that are holding the asset or if
1688		/// the new value of `min_balance` is less than the old one.
1689		///
1690		/// Origin must be Signed and the sender has to be the Owner of the
1691		/// asset `id`.
1692		///
1693		/// - `id`: The identifier of the asset.
1694		/// - `min_balance`: The new value of `min_balance`.
1695		///
1696		/// Emits `AssetMinBalanceChanged` event when successful.
1697		#[pallet::call_index(28)]
1698		pub fn set_min_balance(
1699			origin: OriginFor<T>,
1700			id: T::AssetIdParameter,
1701			min_balance: T::Balance,
1702		) -> DispatchResult {
1703			let origin = ensure_signed(origin)?;
1704			let id: T::AssetId = id.into();
1705
1706			let mut details = Asset::<T, I>::get(&id).ok_or(Error::<T, I>::Unknown)?;
1707			ensure!(origin == details.owner, Error::<T, I>::NoPermission);
1708
1709			let old_min_balance = details.min_balance;
1710			// If the asset is marked as sufficient it won't be allowed to
1711			// change the min_balance.
1712			ensure!(!details.is_sufficient, Error::<T, I>::NoPermission);
1713
1714			// Ensure that either the new min_balance is less than old
1715			// min_balance or there aren't any accounts holding the asset.
1716			ensure!(
1717				min_balance < old_min_balance || details.accounts == 0,
1718				Error::<T, I>::NoPermission
1719			);
1720
1721			details.min_balance = min_balance;
1722			Asset::<T, I>::insert(&id, details);
1723
1724			Self::deposit_event(Event::AssetMinBalanceChanged {
1725				asset_id: id,
1726				new_min_balance: min_balance,
1727			});
1728			Ok(())
1729		}
1730
1731		/// Create an asset account for `who`.
1732		///
1733		/// A deposit will be taken from the signer account.
1734		///
1735		/// - `origin`: Must be Signed; the signer account must have sufficient funds for a deposit
1736		///   to be taken.
1737		/// - `id`: The identifier of the asset for the account to be created, the asset status must
1738		///   be live.
1739		/// - `who`: The account to be created.
1740		///
1741		/// Emits `Touched` event when successful.
1742		#[pallet::call_index(29)]
1743		#[pallet::weight(T::WeightInfo::touch_other())]
1744		pub fn touch_other(
1745			origin: OriginFor<T>,
1746			id: T::AssetIdParameter,
1747			who: AccountIdLookupOf<T>,
1748		) -> DispatchResult {
1749			let origin = ensure_signed(origin)?;
1750			let who = T::Lookup::lookup(who)?;
1751			let id: T::AssetId = id.into();
1752			Self::do_touch(id, who, origin)
1753		}
1754
1755		/// Return the deposit (if any) of a target asset account. Useful if you are the depositor.
1756		///
1757		/// The origin must be Signed and either the account owner, depositor, or asset `Admin`. In
1758		/// order to burn a non-zero balance of the asset, the caller must be the account and should
1759		/// use `refund`.
1760		///
1761		/// - `id`: The identifier of the asset for the account holding a deposit.
1762		/// - `who`: The account to refund.
1763		///
1764		/// It will fail with either [`Error::ContainsHolds`] or [`Error::ContainsFreezes`] if
1765		/// the asset account contains holds or freezes in place.
1766		///
1767		/// Emits `Refunded` event when successful.
1768		#[pallet::call_index(30)]
1769		#[pallet::weight(T::WeightInfo::refund_other())]
1770		pub fn refund_other(
1771			origin: OriginFor<T>,
1772			id: T::AssetIdParameter,
1773			who: AccountIdLookupOf<T>,
1774		) -> DispatchResult {
1775			let origin = ensure_signed(origin)?;
1776			let who = T::Lookup::lookup(who)?;
1777			let id: T::AssetId = id.into();
1778			Self::do_refund_other(id, &who, Some(origin))
1779		}
1780
1781		/// Disallow further unprivileged transfers of an asset `id` to and from an account `who`.
1782		///
1783		/// Origin must be Signed and the sender should be the Freezer of the asset `id`.
1784		///
1785		/// - `id`: The identifier of the account's asset.
1786		/// - `who`: The account to be unblocked.
1787		///
1788		/// Emits `Blocked`.
1789		///
1790		/// Weight: `O(1)`
1791		#[pallet::call_index(31)]
1792		pub fn block(
1793			origin: OriginFor<T>,
1794			id: T::AssetIdParameter,
1795			who: AccountIdLookupOf<T>,
1796		) -> DispatchResult {
1797			let origin = ensure_signed(origin)?;
1798			let id: T::AssetId = id.into();
1799
1800			let d = Asset::<T, I>::get(&id).ok_or(Error::<T, I>::Unknown)?;
1801			ensure!(
1802				d.status == AssetStatus::Live || d.status == AssetStatus::Frozen,
1803				Error::<T, I>::IncorrectStatus
1804			);
1805			ensure!(origin == d.freezer, Error::<T, I>::NoPermission);
1806			let who = T::Lookup::lookup(who)?;
1807
1808			Account::<T, I>::try_mutate(&id, &who, |maybe_account| -> DispatchResult {
1809				maybe_account.as_mut().ok_or(Error::<T, I>::NoAccount)?.status =
1810					AccountStatus::Blocked;
1811				Ok(())
1812			})?;
1813
1814			Self::deposit_event(Event::<T, I>::Blocked { asset_id: id, who });
1815			Ok(())
1816		}
1817
1818		/// Transfer the entire transferable balance from the caller asset account.
1819		///
1820		/// NOTE: This function only attempts to transfer _transferable_ balances. This means that
1821		/// any held, frozen, or minimum balance (when `keep_alive` is `true`), will not be
1822		/// transferred by this function. To ensure that this function results in a killed account,
1823		/// you might need to prepare the account by removing any reference counters, storage
1824		/// deposits, etc...
1825		///
1826		/// The dispatch origin of this call must be Signed.
1827		///
1828		/// - `id`: The identifier of the asset for the account holding a deposit.
1829		/// - `dest`: The recipient of the transfer.
1830		/// - `keep_alive`: A boolean to determine if the `transfer_all` operation should send all
1831		///   of the funds the asset account has, causing the sender asset account to be killed
1832		///   (false), or transfer everything except at least the minimum balance, which will
1833		///   guarantee to keep the sender asset account alive (true).
1834		#[pallet::call_index(32)]
1835		#[pallet::weight(T::WeightInfo::transfer_all())]
1836		pub fn transfer_all(
1837			origin: OriginFor<T>,
1838			id: T::AssetIdParameter,
1839			dest: AccountIdLookupOf<T>,
1840			keep_alive: bool,
1841		) -> DispatchResult {
1842			let transactor = ensure_signed(origin)?;
1843			let keep_alive = if keep_alive { Preserve } else { Expendable };
1844			let reducible_balance = <Self as fungibles::Inspect<_>>::reducible_balance(
1845				id.clone().into(),
1846				&transactor,
1847				keep_alive,
1848				Fortitude::Polite,
1849			);
1850			let dest = T::Lookup::lookup(dest)?;
1851			<Self as fungibles::Mutate<_>>::transfer(
1852				id.into(),
1853				&transactor,
1854				&dest,
1855				reducible_balance,
1856				keep_alive,
1857			)?;
1858			Ok(())
1859		}
1860
1861		/// Sets the trusted reserve information of an asset.
1862		///
1863		/// Origin must be the Owner of the asset `id`. The origin must conform to the configured
1864		/// `CreateOrigin` or be the signed `owner` configured during asset creation.
1865		///
1866		/// - `id`: The identifier of the asset.
1867		/// - `reserves`: The full list of trusted reserves information.
1868		///
1869		/// Emits `AssetMinBalanceChanged` event when successful.
1870		#[pallet::call_index(33)]
1871		#[pallet::weight(T::WeightInfo::set_reserves())]
1872		pub fn set_reserves(
1873			origin: OriginFor<T>,
1874			id: T::AssetIdParameter,
1875			reserves: Vec<T::ReserveData>,
1876		) -> DispatchResult {
1877			let id: T::AssetId = id.into();
1878			let origin = ensure_signed(origin.clone())
1879				.or_else(|_| T::CreateOrigin::ensure_origin(origin, &id))?;
1880
1881			let details = Asset::<T, I>::get(&id).ok_or(Error::<T, I>::Unknown)?;
1882			ensure!(origin == details.owner, Error::<T, I>::NoPermission);
1883
1884			Self::unchecked_update_reserves(id, reserves)?;
1885			Ok(())
1886		}
1887	}
1888
1889	#[pallet::view_functions]
1890	impl<T: Config<I>, I: 'static> Pallet<T, I> {
1891		/// Provide the asset details for asset `id`.
1892		pub fn asset_details(
1893			id: T::AssetId,
1894		) -> Option<AssetDetails<T::Balance, T::AccountId, DepositBalanceOf<T, I>>> {
1895			Asset::<T, I>::get(id)
1896		}
1897
1898		/// Provide the balance of `who` for asset `id`.
1899		pub fn balance_of(who: T::AccountId, id: T::AssetId) -> Option<<T as Config<I>>::Balance> {
1900			Account::<T, I>::get(id, who).map(|account| account.balance)
1901		}
1902
1903		/// Provide the configured metadata for asset `id`.
1904		pub fn get_metadata(
1905			id: T::AssetId,
1906		) -> Option<AssetMetadata<DepositBalanceOf<T, I>, BoundedVec<u8, T::StringLimit>>> {
1907			Metadata::<T, I>::try_get(id).ok()
1908		}
1909
1910		/// Provide the configured reserves data for asset `id`.
1911		pub fn get_reserves_data(id: T::AssetId) -> Vec<T::ReserveData> {
1912			Self::reserves(&id)
1913		}
1914	}
1915
1916	/// Implements [`AccountTouch`] trait.
1917	/// Note that a depositor can be any account, without any specific privilege.
1918	impl<T: Config<I>, I: 'static> AccountTouch<T::AssetId, T::AccountId> for Pallet<T, I> {
1919		type Balance = DepositBalanceOf<T, I>;
1920
1921		fn deposit_required(_: T::AssetId) -> Self::Balance {
1922			T::AssetAccountDeposit::get()
1923		}
1924
1925		fn should_touch(asset: T::AssetId, who: &T::AccountId) -> bool {
1926			match Asset::<T, I>::get(&asset) {
1927				// refer to the [`Self::new_account`] function for more details.
1928				Some(info) if info.is_sufficient => false,
1929				Some(_) if frame_system::Pallet::<T>::can_accrue_consumers(who, 2) => false,
1930				Some(_) => !Account::<T, I>::contains_key(asset, who),
1931				_ => true,
1932			}
1933		}
1934
1935		fn touch(
1936			asset: T::AssetId,
1937			who: &T::AccountId,
1938			depositor: &T::AccountId,
1939		) -> DispatchResult {
1940			Self::do_touch(asset, who.clone(), depositor.clone())
1941		}
1942	}
1943
1944	/// Implements [`ContainsPair`] trait for a pair of asset and account IDs.
1945	impl<T: Config<I>, I: 'static> ContainsPair<T::AssetId, T::AccountId> for Pallet<T, I> {
1946		/// Check if an account with the given asset ID and account address exists.
1947		fn contains(asset: &T::AssetId, who: &T::AccountId) -> bool {
1948			Account::<T, I>::contains_key(asset, who)
1949		}
1950	}
1951
1952	/// Implements [`ProvideAssetReserves`] trait for getting the list of trusted reserves for a
1953	/// given asset.
1954	impl<T: Config<I>, I: 'static> ProvideAssetReserves<T::AssetId, T::ReserveData> for Pallet<T, I> {
1955		/// Provide the configured reserves for asset `id`.
1956		fn reserves(id: &T::AssetId) -> Vec<T::ReserveData> {
1957			Reserves::<T, I>::get(id).into_inner()
1958		}
1959	}
1960}
1961
1962sp_core::generate_feature_enabled_macro!(runtime_benchmarks_enabled, feature = "runtime-benchmarks", $);