git.delta.rocks / unique-network / refs/commits / 0766e08cb8d3

difftreelog

doc(pallet-fungible): document public api

PraetorP2022-07-13parent: #956ec6e.patch.diff
in: master

3 files changed

modifiedpallets/fungible/src/common.rsdiffbeforeafterboth
--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -104,6 +104,8 @@
 	}
 }
 
+/// Implementation of `CommonCollectionOperations` for `FungibleHandle`. It wraps FungibleHandle Pallete
+/// methods and adds weight info.
 impl<T: Config> CommonCollectionOperations<T> for FungibleHandle<T> {
 	fn create_item(
 		&self,
modifiedpallets/fungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/fungible/src/erc.rs
+++ b/pallets/fungible/src/erc.rs
@@ -14,6 +14,8 @@
 // You should have received a copy of the GNU General Public License
 // along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
+//! ERC-20 standart support implementation.
+
 use core::char::{REPLACEMENT_CHARACTER, decode_utf16};
 use core::convert::TryInto;
 use evm_coder::{ToLog, execution::*, generate_stubgen, solidity_interface, types::*, weight};
modifiedpallets/fungible/src/lib.rsdiffbeforeafterboth
before · pallets/fungible/src/lib.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617#![cfg_attr(not(feature = "std"), no_std)]1819use core::ops::Deref;20use evm_coder::ToLog;21use frame_support::{ensure};22use pallet_evm::account::CrossAccountId;23use up_data_structs::{24	AccessMode, CollectionId, TokenId, CreateCollectionData, mapping::TokenAddressMapping,25	budget::Budget,26};27use pallet_common::{28	Error as CommonError, Event as CommonEvent, Pallet as PalletCommon,29	eth::collection_id_to_address,30};31use pallet_evm::Pallet as PalletEvm;32use pallet_structure::Pallet as PalletStructure;33use pallet_evm_coder_substrate::WithRecorder;34use sp_core::H160;35use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};36use sp_std::{collections::btree_map::BTreeMap};3738pub use pallet::*;3940use crate::erc::ERC20Events;41#[cfg(feature = "runtime-benchmarks")]42pub mod benchmarking;43pub mod common;44pub mod erc;45pub mod weights;4647pub type CreateItemData<T> = (<T as pallet_evm::account::Config>::CrossAccountId, u128);48pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;4950#[frame_support::pallet]51pub mod pallet {52	use frame_support::{Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};53	use up_data_structs::CollectionId;54	use super::weights::WeightInfo;5556	#[pallet::error]57	pub enum Error<T> {58		/// Not Fungible item data used to mint in Fungible collection.59		NotFungibleDataUsedToMintFungibleCollectionToken,60		/// Not default id passed as TokenId argument61		FungibleItemsHaveNoId,62		/// Tried to set data for fungible item63		FungibleItemsDontHaveData,64		/// Fungible token does not support nested65		FungibleDisallowsNesting,66		/// Setting item properties is not allowed67		SettingPropertiesNotAllowed,68	}6970	#[pallet::config]71	pub trait Config:72		frame_system::Config + pallet_common::Config + pallet_structure::Config + pallet_evm::Config73	{74		type WeightInfo: WeightInfo;75	}7677	#[pallet::pallet]78	#[pallet::generate_store(pub(super) trait Store)]79	pub struct Pallet<T>(_);8081	#[pallet::storage]82	pub type TotalSupply<T: Config> =83		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u128, QueryKind = ValueQuery>;8485	#[pallet::storage]86	pub type Balance<T: Config> = StorageNMap<87		Key = (88			Key<Twox64Concat, CollectionId>,89			Key<Blake2_128Concat, T::CrossAccountId>,90		),91		Value = u128,92		QueryKind = ValueQuery,93	>;9495	#[pallet::storage]96	pub type Allowance<T: Config> = StorageNMap<97		Key = (98			Key<Twox64Concat, CollectionId>,99			Key<Blake2_128, T::CrossAccountId>,100			Key<Blake2_128Concat, T::CrossAccountId>,101		),102		Value = u128,103		QueryKind = ValueQuery,104	>;105}106107pub struct FungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);108impl<T: Config> FungibleHandle<T> {109	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {110		Self(inner)111	}112	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {113		self.0114	}115	pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {116		&mut self.0117	}118}119impl<T: Config> WithRecorder<T> for FungibleHandle<T> {120	fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {121		self.0.recorder()122	}123	fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {124		self.0.into_recorder()125	}126}127impl<T: Config> Deref for FungibleHandle<T> {128	type Target = pallet_common::CollectionHandle<T>;129130	fn deref(&self) -> &Self::Target {131		&self.0132	}133}134135impl<T: Config> Pallet<T> {136	pub fn init_collection(137		owner: T::CrossAccountId,138		data: CreateCollectionData<T::AccountId>,139	) -> Result<CollectionId, DispatchError> {140		<PalletCommon<T>>::init_collection(owner, data, false)141	}142	pub fn destroy_collection(143		collection: FungibleHandle<T>,144		sender: &T::CrossAccountId,145	) -> DispatchResult {146		let id = collection.id;147148		if Self::collection_has_tokens(id) {149			return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());150		}151152		// =========153154		PalletCommon::destroy_collection(collection.0, sender)?;155156		<TotalSupply<T>>::remove(id);157		<Balance<T>>::remove_prefix((id,), None);158		<Allowance<T>>::remove_prefix((id,), None);159		Ok(())160	}161162	fn collection_has_tokens(collection_id: CollectionId) -> bool {163		<TotalSupply<T>>::get(collection_id) != 0164	}165166	pub fn burn(167		collection: &FungibleHandle<T>,168		owner: &T::CrossAccountId,169		amount: u128,170	) -> DispatchResult {171		let total_supply = <TotalSupply<T>>::get(collection.id)172			.checked_sub(amount)173			.ok_or(<CommonError<T>>::TokenValueTooLow)?;174175		let balance = <Balance<T>>::get((collection.id, owner))176			.checked_sub(amount)177			.ok_or(<CommonError<T>>::TokenValueTooLow)?;178179		if collection.permissions.access() == AccessMode::AllowList {180			collection.check_allowlist(owner)?;181		}182183		// =========184185		if balance == 0 {186			<Balance<T>>::remove((collection.id, owner));187			<PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());188		} else {189			<Balance<T>>::insert((collection.id, owner), balance);190		}191		<TotalSupply<T>>::insert(collection.id, total_supply);192193		<PalletEvm<T>>::deposit_log(194			ERC20Events::Transfer {195				from: *owner.as_eth(),196				to: H160::default(),197				value: amount.into(),198			}199			.to_log(collection_id_to_address(collection.id)),200		);201		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(202			collection.id,203			TokenId::default(),204			owner.clone(),205			amount,206		));207		Ok(())208	}209210	pub fn transfer(211		collection: &FungibleHandle<T>,212		from: &T::CrossAccountId,213		to: &T::CrossAccountId,214		amount: u128,215		nesting_budget: &dyn Budget,216	) -> DispatchResult {217		ensure!(218			collection.limits.transfers_enabled(),219			<CommonError<T>>::TransferNotAllowed,220		);221222		if collection.permissions.access() == AccessMode::AllowList {223			collection.check_allowlist(from)?;224			collection.check_allowlist(to)?;225		}226		<PalletCommon<T>>::ensure_correct_receiver(to)?;227228		let balance_from = <Balance<T>>::get((collection.id, from))229			.checked_sub(amount)230			.ok_or(<CommonError<T>>::TokenValueTooLow)?;231		let balance_to = if from != to {232			Some(233				<Balance<T>>::get((collection.id, to))234					.checked_add(amount)235					.ok_or(ArithmeticError::Overflow)?,236			)237		} else {238			None239		};240241		// =========242243		<PalletStructure<T>>::nest_if_sent_to_token(244			from.clone(),245			to,246			collection.id,247			TokenId::default(),248			nesting_budget,249		)?;250251		if let Some(balance_to) = balance_to {252			// from != to253			if balance_from == 0 {254				<Balance<T>>::remove((collection.id, from));255				<PalletStructure<T>>::unnest_if_nested(from, collection.id, TokenId::default());256			} else {257				<Balance<T>>::insert((collection.id, from), balance_from);258			}259			<Balance<T>>::insert((collection.id, to), balance_to);260		}261262		<PalletEvm<T>>::deposit_log(263			ERC20Events::Transfer {264				from: *from.as_eth(),265				to: *to.as_eth(),266				value: amount.into(),267			}268			.to_log(collection_id_to_address(collection.id)),269		);270		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(271			collection.id,272			TokenId::default(),273			from.clone(),274			to.clone(),275			amount,276		));277		Ok(())278	}279280	pub fn create_multiple_items(281		collection: &FungibleHandle<T>,282		sender: &T::CrossAccountId,283		data: BTreeMap<T::CrossAccountId, u128>,284		nesting_budget: &dyn Budget,285	) -> DispatchResult {286		if !collection.is_owner_or_admin(sender) {287			ensure!(288				collection.permissions.mint_mode(),289				<CommonError<T>>::PublicMintingNotAllowed290			);291			collection.check_allowlist(sender)?;292293			for (owner, _) in data.iter() {294				collection.check_allowlist(owner)?;295			}296		}297298		let total_supply = data299			.iter()300			.map(|(_, v)| *v)301			.try_fold(<TotalSupply<T>>::get(collection.id), |acc, v| {302				acc.checked_add(v)303			})304			.ok_or(ArithmeticError::Overflow)?;305306		let mut balances = data;307		for (k, v) in balances.iter_mut() {308			*v = <Balance<T>>::get((collection.id, &k))309				.checked_add(*v)310				.ok_or(ArithmeticError::Overflow)?;311		}312313		for (to, _) in balances.iter() {314			<PalletStructure<T>>::check_nesting(315				sender.clone(),316				to,317				collection.id,318				TokenId::default(),319				nesting_budget,320			)?;321		}322323		// =========324325		<TotalSupply<T>>::insert(collection.id, total_supply);326		for (user, amount) in balances {327			<Balance<T>>::insert((collection.id, &user), amount);328			<PalletStructure<T>>::nest_if_sent_to_token_unchecked(329				&user,330				collection.id,331				TokenId::default(),332			);333			<PalletEvm<T>>::deposit_log(334				ERC20Events::Transfer {335					from: H160::default(),336					to: *user.as_eth(),337					value: amount.into(),338				}339				.to_log(collection_id_to_address(collection.id)),340			);341			<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(342				collection.id,343				TokenId::default(),344				user.clone(),345				amount,346			));347		}348349		Ok(())350	}351352	fn set_allowance_unchecked(353		collection: &FungibleHandle<T>,354		owner: &T::CrossAccountId,355		spender: &T::CrossAccountId,356		amount: u128,357	) {358		if amount == 0 {359			<Allowance<T>>::remove((collection.id, owner, spender));360		} else {361			<Allowance<T>>::insert((collection.id, owner, spender), amount);362		}363364		<PalletEvm<T>>::deposit_log(365			ERC20Events::Approval {366				owner: *owner.as_eth(),367				spender: *spender.as_eth(),368				value: amount.into(),369			}370			.to_log(collection_id_to_address(collection.id)),371		);372		<PalletCommon<T>>::deposit_event(CommonEvent::Approved(373			collection.id,374			TokenId(0),375			owner.clone(),376			spender.clone(),377			amount,378		));379	}380381	pub fn set_allowance(382		collection: &FungibleHandle<T>,383		owner: &T::CrossAccountId,384		spender: &T::CrossAccountId,385		amount: u128,386	) -> DispatchResult {387		if collection.permissions.access() == AccessMode::AllowList {388			collection.check_allowlist(owner)?;389			collection.check_allowlist(spender)?;390		}391392		if <Balance<T>>::get((collection.id, owner)) < amount {393			ensure!(394				collection.ignores_owned_amount(owner),395				<CommonError<T>>::CantApproveMoreThanOwned396			);397		}398399		// =========400401		Self::set_allowance_unchecked(collection, owner, spender, amount);402		Ok(())403	}404405	fn check_allowed(406		collection: &FungibleHandle<T>,407		spender: &T::CrossAccountId,408		from: &T::CrossAccountId,409		amount: u128,410		nesting_budget: &dyn Budget,411	) -> Result<Option<u128>, DispatchError> {412		if spender.conv_eq(from) {413			return Ok(None);414		}415		if collection.permissions.access() == AccessMode::AllowList {416			// `from`, `to` checked in [`transfer`]417			collection.check_allowlist(spender)?;418		}419		if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {420			// TODO: should collection owner be allowed to perform this transfer?421			ensure!(422				<PalletStructure<T>>::check_indirectly_owned(423					spender.clone(),424					source.0,425					source.1,426					None,427					nesting_budget428				)?,429				<CommonError<T>>::ApprovedValueTooLow,430			);431			return Ok(None);432		}433		let allowance = <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount);434		if allowance.is_none() {435			ensure!(436				collection.ignores_allowance(spender),437				<CommonError<T>>::ApprovedValueTooLow438			);439		}440441		Ok(allowance)442	}443444	pub fn transfer_from(445		collection: &FungibleHandle<T>,446		spender: &T::CrossAccountId,447		from: &T::CrossAccountId,448		to: &T::CrossAccountId,449		amount: u128,450		nesting_budget: &dyn Budget,451	) -> DispatchResult {452		let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;453454		// =========455456		Self::transfer(collection, from, to, amount, nesting_budget)?;457		if let Some(allowance) = allowance {458			Self::set_allowance_unchecked(collection, from, spender, allowance);459		}460		Ok(())461	}462463	pub fn burn_from(464		collection: &FungibleHandle<T>,465		spender: &T::CrossAccountId,466		from: &T::CrossAccountId,467		amount: u128,468		nesting_budget: &dyn Budget,469	) -> DispatchResult {470		let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;471472		// =========473474		Self::burn(collection, from, amount)?;475		if let Some(allowance) = allowance {476			Self::set_allowance_unchecked(collection, from, spender, allowance);477		}478		Ok(())479	}480481	/// Delegated to `create_multiple_items`482	pub fn create_item(483		collection: &FungibleHandle<T>,484		sender: &T::CrossAccountId,485		data: CreateItemData<T>,486		nesting_budget: &dyn Budget,487	) -> DispatchResult {488		Self::create_multiple_items(489			collection,490			sender,491			[(data.0, data.1)].into_iter().collect(),492			nesting_budget,493		)494	}495}
after · pallets/fungible/src/lib.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # Fungible Pallet18//!19//! The Fungible pallet provides functionality for dealing with fungible assets.20//!21//! - [`CreateItemData`]22//! - [`Config`]23//! - [`FungibleHandle`]24//! - [`Pallet`]25//! - [`TotalSupply`]26//! - [`Balance`]27//! - [`Allowance`]28//! - [`Error`]29//!30//! ## Fungible tokens31//!32//! Fungible tokens or assets are divisible and non-unique. For instance,33//! fiat currencies like the dollar are fungible: A $1 bill34//! in New York City has the same value as a $1 bill in Miami.35//! A fungible token can also be a cryptocurrency like Bitcoin: 1 BTC is worth 1 BTC,36//! no matter where it is issued. Thus, the fungibility refers to a specific currency’s37//! ability to maintain one standard value. As well, it needs to have uniform acceptance.38//! This means that a currency’s history should not be able to affect its value,39//! and this is due to the fact that each piece that is a part of the currency is equal40//! in value when compared to every other piece of that exact same currency.41//! In the world of cryptocurrencies, this is essentially a coin or a token42//! that can be replaced by another identical coin or token, and they are43//! both mutually interchangeable. A popular implementation of fungible tokens is44//! the ERC-20 token standard.45//!46//! ### ERC-2047//!48//! The [ERC-20](https://ethereum.org/en/developers/docs/standards/tokens/erc-20/) (Ethereum Request for Comments 20), proposed by Fabian Vogelsteller in November 2015,49//! is a Token Standard that implements an API for tokens within Smart Contracts.50//!51//! Example functionalities ERC-20 provides:52//!53//! * transfer tokens from one account to another54//! * get the current token balance of an account55//! * get the total supply of the token available on the network56//! * approve whether an amount of token from an account can be spent by a third-party account57//!58//! ## Overview59//!60//! The module provides functionality for asset management of fungible asset, supports ERC-20 standart, includes:61//!62//! * Asset Issuance63//! * Asset Transferal64//! * Asset Destruction65//! * Delegated Asset Transfers66//!67//! **NOTE:** The created fungible asset always has `token_id` = 0.68//! So `tokenA` and `tokenB` will have different `collection_id`.69//!70//! ### Implementations71//!72//! The Fungible pallet provides implementations for the following traits.73//!74//! - [`WithRecorder`](pallet_evm_coder_substrate::WithRecorder):75//! - [`CommonCollectionOperations`](pallet_common::CommonCollectionOperations): Functions for dealing with collections76//!	- [`CommonWeightInfo`](pallet_common::CommonWeightInfo): Functions for retrieval of transaction weight77//! - [`CommonEvmHandler`](pallet_common::erc::CommonEvmHandler): Function for handling EVM runtime calls7879#![cfg_attr(not(feature = "std"), no_std)]8081use core::ops::Deref;82use evm_coder::ToLog;83use frame_support::{ensure};84use pallet_evm::account::CrossAccountId;85use up_data_structs::{86	AccessMode, CollectionId, TokenId, CreateCollectionData, mapping::TokenAddressMapping,87	budget::Budget,88};89use pallet_common::{90	Error as CommonError, Event as CommonEvent, Pallet as PalletCommon,91	eth::collection_id_to_address,92};93use pallet_evm::Pallet as PalletEvm;94use pallet_structure::Pallet as PalletStructure;95use pallet_evm_coder_substrate::WithRecorder;96use sp_core::H160;97use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};98use sp_std::{collections::btree_map::BTreeMap};99100pub use pallet::*;101102use crate::erc::ERC20Events;103#[cfg(feature = "runtime-benchmarks")]104pub mod benchmarking;105pub mod common;106pub mod erc;107pub mod weights;108109pub type CreateItemData<T> = (<T as pallet_evm::account::Config>::CrossAccountId, u128);110pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;111112#[frame_support::pallet]113pub mod pallet {114	use frame_support::{Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};115	use up_data_structs::CollectionId;116	use super::weights::WeightInfo;117118	#[pallet::error]119	pub enum Error<T> {120		/// Not Fungible item data used to mint in Fungible collection.121		NotFungibleDataUsedToMintFungibleCollectionToken,122		/// Not default id passed as TokenId argument.123		FungibleItemsHaveNoId,124		/// Tried to set data for fungible item.125		FungibleItemsDontHaveData,126		/// Fungible token does not support nesting.127		FungibleDisallowsNesting,128		/// Setting item properties is not allowed.129		SettingPropertiesNotAllowed,130	}131132	#[pallet::config]133	pub trait Config:134		frame_system::Config + pallet_common::Config + pallet_structure::Config + pallet_evm::Config135	{136		type WeightInfo: WeightInfo;137	}138139	#[pallet::pallet]140	#[pallet::generate_store(pub(super) trait Store)]141	pub struct Pallet<T>(_);142143	/// Total amount of fungible tokens inside a collection.144	#[pallet::storage]145	pub type TotalSupply<T: Config> =146		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u128, QueryKind = ValueQuery>;147148	/// Amount of tokens owned by an account inside a collection.149	#[pallet::storage]150	pub type Balance<T: Config> = StorageNMap<151		Key = (152			Key<Twox64Concat, CollectionId>,153			Key<Blake2_128Concat, T::CrossAccountId>,154		),155		Value = u128,156		QueryKind = ValueQuery,157	>;158159	/// Storage for delegated assets.160	#[pallet::storage]161	pub type Allowance<T: Config> = StorageNMap<162		Key = (163			Key<Twox64Concat, CollectionId>,164			Key<Blake2_128, T::CrossAccountId>,165			Key<Blake2_128Concat, T::CrossAccountId>,166		),167		Value = u128,168		QueryKind = ValueQuery,169	>;170}171/// Handler for fungible assets.172pub struct FungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);173impl<T: Config> FungibleHandle<T> {174	/// Casts [pallet_common::CollectionHandle] into [FungibleHandle].175	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {176		Self(inner)177	}178179	/// Casts [FungibleHandle] into [pallet_common::CollectionHandle].180	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {181		self.0182	}183	/// Returns a mutable reference to the internal [pallet_common::CollectionHandle].184	pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {185		&mut self.0186	}187}188impl<T: Config> WithRecorder<T> for FungibleHandle<T> {189	fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {190		self.0.recorder()191	}192	fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {193		self.0.into_recorder()194	}195}196impl<T: Config> Deref for FungibleHandle<T> {197	type Target = pallet_common::CollectionHandle<T>;198199	fn deref(&self) -> &Self::Target {200		&self.0201	}202}203204/// Pallet implementation for fungible assets205impl<T: Config> Pallet<T> {206	/// Initializes the collection. Returns [CollectionId] on success, [DispatchError] otherwise.207	pub fn init_collection(208		owner: T::CrossAccountId,209		data: CreateCollectionData<T::AccountId>,210	) -> Result<CollectionId, DispatchError> {211		<PalletCommon<T>>::init_collection(owner, data, false)212	}213214	/// Destroys a collection.215	pub fn destroy_collection(216		collection: FungibleHandle<T>,217		sender: &T::CrossAccountId,218	) -> DispatchResult {219		let id = collection.id;220221		if Self::collection_has_tokens(id) {222			return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());223		}224225		// =========226227		PalletCommon::destroy_collection(collection.0, sender)?;228229		<TotalSupply<T>>::remove(id);230		<Balance<T>>::remove_prefix((id,), None);231		<Allowance<T>>::remove_prefix((id,), None);232		Ok(())233	}234235	///Checks if collection has tokens. Return `true` if it has.236	fn collection_has_tokens(collection_id: CollectionId) -> bool {237		<TotalSupply<T>>::get(collection_id) != 0238	}239240	/// Burns the specified amount of the token. If the token balance241	/// or total supply is less than the given value,242	/// it will return [DispatchError].243	pub fn burn(244		collection: &FungibleHandle<T>,245		owner: &T::CrossAccountId,246		amount: u128,247	) -> DispatchResult {248		let total_supply = <TotalSupply<T>>::get(collection.id)249			.checked_sub(amount)250			.ok_or(<CommonError<T>>::TokenValueTooLow)?;251252		let balance = <Balance<T>>::get((collection.id, owner))253			.checked_sub(amount)254			.ok_or(<CommonError<T>>::TokenValueTooLow)?;255256		if collection.permissions.access() == AccessMode::AllowList {257			collection.check_allowlist(owner)?;258		}259260		// =========261262		if balance == 0 {263			<Balance<T>>::remove((collection.id, owner));264			<PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());265		} else {266			<Balance<T>>::insert((collection.id, owner), balance);267		}268		<TotalSupply<T>>::insert(collection.id, total_supply);269270		<PalletEvm<T>>::deposit_log(271			ERC20Events::Transfer {272				from: *owner.as_eth(),273				to: H160::default(),274				value: amount.into(),275			}276			.to_log(collection_id_to_address(collection.id)),277		);278		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(279			collection.id,280			TokenId::default(),281			owner.clone(),282			amount,283		));284		Ok(())285	}286287	/// Transfers the specified amount of tokens. Will check that288	/// the transfer is allowed for the token.289	pub fn transfer(290		collection: &FungibleHandle<T>,291		from: &T::CrossAccountId,292		to: &T::CrossAccountId,293		amount: u128,294		nesting_budget: &dyn Budget,295	) -> DispatchResult {296		ensure!(297			collection.limits.transfers_enabled(),298			<CommonError<T>>::TransferNotAllowed,299		);300301		if collection.permissions.access() == AccessMode::AllowList {302			collection.check_allowlist(from)?;303			collection.check_allowlist(to)?;304		}305		<PalletCommon<T>>::ensure_correct_receiver(to)?;306307		let balance_from = <Balance<T>>::get((collection.id, from))308			.checked_sub(amount)309			.ok_or(<CommonError<T>>::TokenValueTooLow)?;310		let balance_to = if from != to {311			Some(312				<Balance<T>>::get((collection.id, to))313					.checked_add(amount)314					.ok_or(ArithmeticError::Overflow)?,315			)316		} else {317			None318		};319320		// =========321322		<PalletStructure<T>>::nest_if_sent_to_token(323			from.clone(),324			to,325			collection.id,326			TokenId::default(),327			nesting_budget,328		)?;329330		if let Some(balance_to) = balance_to {331			// from != to332			if balance_from == 0 {333				<Balance<T>>::remove((collection.id, from));334				<PalletStructure<T>>::unnest_if_nested(from, collection.id, TokenId::default());335			} else {336				<Balance<T>>::insert((collection.id, from), balance_from);337			}338			<Balance<T>>::insert((collection.id, to), balance_to);339		}340341		<PalletEvm<T>>::deposit_log(342			ERC20Events::Transfer {343				from: *from.as_eth(),344				to: *to.as_eth(),345				value: amount.into(),346			}347			.to_log(collection_id_to_address(collection.id)),348		);349		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(350			collection.id,351			TokenId::default(),352			from.clone(),353			to.clone(),354			amount,355		));356		Ok(())357	}358359	/// Minting tokens for multiple IDs.360	pub fn create_multiple_items(361		collection: &FungibleHandle<T>,362		sender: &T::CrossAccountId,363		data: BTreeMap<T::CrossAccountId, u128>,364		nesting_budget: &dyn Budget,365	) -> DispatchResult {366		if !collection.is_owner_or_admin(sender) {367			ensure!(368				collection.permissions.mint_mode(),369				<CommonError<T>>::PublicMintingNotAllowed370			);371			collection.check_allowlist(sender)?;372373			for (owner, _) in data.iter() {374				collection.check_allowlist(owner)?;375			}376		}377378		let total_supply = data379			.iter()380			.map(|(_, v)| *v)381			.try_fold(<TotalSupply<T>>::get(collection.id), |acc, v| {382				acc.checked_add(v)383			})384			.ok_or(ArithmeticError::Overflow)?;385386		let mut balances = data;387		for (k, v) in balances.iter_mut() {388			*v = <Balance<T>>::get((collection.id, &k))389				.checked_add(*v)390				.ok_or(ArithmeticError::Overflow)?;391		}392393		for (to, _) in balances.iter() {394			<PalletStructure<T>>::check_nesting(395				sender.clone(),396				to,397				collection.id,398				TokenId::default(),399				nesting_budget,400			)?;401		}402403		// =========404405		<TotalSupply<T>>::insert(collection.id, total_supply);406		for (user, amount) in balances {407			<Balance<T>>::insert((collection.id, &user), amount);408			<PalletStructure<T>>::nest_if_sent_to_token_unchecked(409				&user,410				collection.id,411				TokenId::default(),412			);413			<PalletEvm<T>>::deposit_log(414				ERC20Events::Transfer {415					from: H160::default(),416					to: *user.as_eth(),417					value: amount.into(),418				}419				.to_log(collection_id_to_address(collection.id)),420			);421			<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(422				collection.id,423				TokenId::default(),424				user.clone(),425				amount,426			));427		}428429		Ok(())430	}431432	fn set_allowance_unchecked(433		collection: &FungibleHandle<T>,434		owner: &T::CrossAccountId,435		spender: &T::CrossAccountId,436		amount: u128,437	) {438		if amount == 0 {439			<Allowance<T>>::remove((collection.id, owner, spender));440		} else {441			<Allowance<T>>::insert((collection.id, owner, spender), amount);442		}443444		<PalletEvm<T>>::deposit_log(445			ERC20Events::Approval {446				owner: *owner.as_eth(),447				spender: *spender.as_eth(),448				value: amount.into(),449			}450			.to_log(collection_id_to_address(collection.id)),451		);452		<PalletCommon<T>>::deposit_event(CommonEvent::Approved(453			collection.id,454			TokenId(0),455			owner.clone(),456			spender.clone(),457			amount,458		));459	}460461	/// Sets the amount of owner tokens that the spender can manage.462	pub fn set_allowance(463		collection: &FungibleHandle<T>,464		owner: &T::CrossAccountId,465		spender: &T::CrossAccountId,466		amount: u128,467	) -> DispatchResult {468		if collection.permissions.access() == AccessMode::AllowList {469			collection.check_allowlist(owner)?;470			collection.check_allowlist(spender)?;471		}472473		if <Balance<T>>::get((collection.id, owner)) < amount {474			ensure!(475				collection.ignores_owned_amount(owner),476				<CommonError<T>>::CantApproveMoreThanOwned477			);478		}479480		// =========481482		Self::set_allowance_unchecked(collection, owner, spender, amount);483		Ok(())484	}485486	fn check_allowed(487		collection: &FungibleHandle<T>,488		spender: &T::CrossAccountId,489		from: &T::CrossAccountId,490		amount: u128,491		nesting_budget: &dyn Budget,492	) -> Result<Option<u128>, DispatchError> {493		if spender.conv_eq(from) {494			return Ok(None);495		}496		if collection.permissions.access() == AccessMode::AllowList {497			// `from`, `to` checked in [`transfer`]498			collection.check_allowlist(spender)?;499		}500		if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {501			// TODO: should collection owner be allowed to perform this transfer?502			ensure!(503				<PalletStructure<T>>::check_indirectly_owned(504					spender.clone(),505					source.0,506					source.1,507					None,508					nesting_budget509				)?,510				<CommonError<T>>::ApprovedValueTooLow,511			);512			return Ok(None);513		}514		let allowance = <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount);515		if allowance.is_none() {516			ensure!(517				collection.ignores_allowance(spender),518				<CommonError<T>>::ApprovedValueTooLow519			);520		}521522		Ok(allowance)523	}524525	/// Transfers of tokens that `from` gave to `spender` to manage, to `to` ID.526	pub fn transfer_from(527		collection: &FungibleHandle<T>,528		spender: &T::CrossAccountId,529		from: &T::CrossAccountId,530		to: &T::CrossAccountId,531		amount: u128,532		nesting_budget: &dyn Budget,533	) -> DispatchResult {534		let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;535536		// =========537538		Self::transfer(collection, from, to, amount, nesting_budget)?;539		if let Some(allowance) = allowance {540			Self::set_allowance_unchecked(collection, from, spender, allowance);541		}542		Ok(())543	}544545	/// Burns managed tokens.546	pub fn burn_from(547		collection: &FungibleHandle<T>,548		spender: &T::CrossAccountId,549		from: &T::CrossAccountId,550		amount: u128,551		nesting_budget: &dyn Budget,552	) -> DispatchResult {553		let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;554555		// =========556557		Self::burn(collection, from, amount)?;558		if let Some(allowance) = allowance {559			Self::set_allowance_unchecked(collection, from, spender, allowance);560		}561		Ok(())562	}563564	/// Delegated to `create_multiple_items`565	pub fn create_item(566		collection: &FungibleHandle<T>,567		sender: &T::CrossAccountId,568		data: CreateItemData<T>,569		nesting_budget: &dyn Budget,570	) -> DispatchResult {571		Self::create_multiple_items(572			collection,573			sender,574			[(data.0, data.1)].into_iter().collect(),575			nesting_budget,576		)577	}578}