git.delta.rocks / unique-network / refs/commits / e2da42b8b024

difftreelog

feat xcm nft support

Daniel Shiposha2023-10-18parent: #5bde44b.patch.diff
in: master

5 files changed

modifiedpallets/common/src/lib.rsdiffbeforeafterboth
--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -2351,6 +2351,11 @@
 	/// Is the collection a foreign one?
 	fn is_foreign(&self) -> bool;
 
+	/// Does the token have children?
+	fn token_has_children(&self, _token: TokenId) -> bool {
+		false
+	}
+
 	/// Create a collection's item using a transaction.
 	///
 	/// This function performs additional XCM-related checks before the actual creation.
modifiedpallets/foreign-assets/src/lib.rsdiffbeforeafterboth
--- a/pallets/foreign-assets/src/lib.rs
+++ b/pallets/foreign-assets/src/lib.rs
@@ -364,7 +364,7 @@
 
 	fn check_out(_dest: &MultiLocation, _what: &MultiAsset, _context: &XcmContext) {}
 
-	fn deposit_asset(what: &MultiAsset, to: &MultiLocation, context: &XcmContext) -> XcmResult {
+	fn deposit_asset(what: &MultiAsset, to: &MultiLocation, _context: &XcmContext) -> XcmResult {
 		let collection_id = Self::multiasset_to_collection(what)?;
 		let dispatch =
 			T::CollectionDispatch::dispatch(collection_id).map_err(|_| XcmError::AssetNotFound)?;
@@ -397,7 +397,42 @@
 		from: &MultiLocation,
 		_maybe_context: Option<&XcmContext>,
 	) -> Result<staging_xcm_executor::Assets, XcmError> {
-		Err(XcmError::Unimplemented)
+		let from = T::LocationToAccountId::convert_location(from)
+			.ok_or(XcmExecutorError::AccountIdConversionFailed)?;
+
+		let collection_id = Self::multiasset_to_collection(what)?;
+		let dispatch =
+			T::CollectionDispatch::dispatch(collection_id).map_err(|_| XcmError::AssetNotFound)?;
+
+		let collection = dispatch.as_dyn();
+		let xcm_ext = collection.xcm_extensions().ok_or(XcmError::NoPermission)?;
+
+		match what.fun {
+			Fungibility::Fungible(amount) => xcm_ext
+				.burn_item(from, TokenId::default(), amount)
+				.map_err(|_| XcmError::FailedToTransactAsset("fungible item withdraw failed"))?,
+
+			Fungibility::NonFungible(asset_instance) => {
+				let token_id =
+					Self::asset_instance_to_token_id(xcm_ext, collection_id, &asset_instance)?
+						.ok_or(XcmError::AssetNotFound)?;
+
+				if xcm_ext.token_has_children(token_id) {
+					return Err(XcmError::Unimplemented);
+				}
+
+				let depositor = &from;
+				let to = Self::pallet_account();
+				let amount = 1;
+				xcm_ext
+					.transfer_item(depositor, &from, &to, token_id, amount, &ZeroBudget)
+					.map_err(|_| {
+						XcmError::FailedToTransactAsset("nonfungible item withdraw failed")
+					})?;
+			}
+		}
+
+		Ok(what.clone().into())
 	}
 
 	fn internal_transfer_asset(
@@ -406,7 +441,49 @@
 		to: &MultiLocation,
 		_context: &XcmContext,
 	) -> Result<staging_xcm_executor::Assets, XcmError> {
-		Err(XcmError::Unimplemented)
+		let collection_id = Self::multiasset_to_collection(what)?;
+
+		let dispatch =
+			T::CollectionDispatch::dispatch(collection_id).map_err(|_| XcmError::AssetNotFound)?;
+		let collection = dispatch.as_dyn();
+		let xcm_ext = collection.xcm_extensions().ok_or(XcmError::NoPermission)?;
+
+		let from = T::LocationToAccountId::convert_location(from)
+			.ok_or(XcmExecutorError::AccountIdConversionFailed)?;
+
+		let to = T::LocationToAccountId::convert_location(to)
+			.ok_or(XcmExecutorError::AccountIdConversionFailed)?;
+
+		let depositor = &from;
+
+		match what.fun {
+			Fungibility::Fungible(amount) => xcm_ext
+				.transfer_item(
+					depositor,
+					&from,
+					&to,
+					TokenId::default(),
+					amount,
+					&ZeroBudget,
+				)
+				.map_err(|_| XcmError::FailedToTransactAsset("fungible item transfer failed"))?,
+
+			Fungibility::NonFungible(asset_instance) => {
+				let token_id =
+					Self::asset_instance_to_token_id(xcm_ext, collection_id, &asset_instance)?
+						.ok_or(XcmError::AssetNotFound)?;
+
+				let amount = 1;
+
+				xcm_ext
+					.transfer_item(depositor, &from, &to, token_id, amount, &ZeroBudget)
+					.map_err(|_| {
+						XcmError::FailedToTransactAsset("nonfungible item transfer failed")
+					})?;
+			}
+		}
+
+		Ok(what.clone().into())
 	}
 }
 
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//! # 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): Trait for EVM support75//! - [`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;8283use evm_coder::ToLog;84use frame_support::{dispatch::PostDispatchInfo, ensure, pallet_prelude::*};85pub use pallet::*;86use pallet_common::{87	eth::collection_id_to_address, helpers::add_weight_to_post_info,88	weights::WeightInfo as CommonWeightInfo, Error as CommonError, Event as CommonEvent,89	Pallet as PalletCommon, SelfWeightOf as PalletCommonWeightOf,90};91use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};92use pallet_evm_coder_substrate::WithRecorder;93use pallet_structure::Pallet as PalletStructure;94use sp_core::H160;95use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};96use sp_std::{collections::btree_map::BTreeMap, vec::Vec};97use up_data_structs::{98	budget::{Budget, ZeroBudget},99	mapping::TokenAddressMapping,100	AccessMode, CollectionId, CreateCollectionData, Property, PropertyKey, TokenId,101};102use weights::WeightInfo;103104use crate::erc::ERC20Events;105#[cfg(feature = "runtime-benchmarks")]106pub mod benchmarking;107pub mod common;108pub mod erc;109pub mod weights;110111pub type CreateItemData<T> = (<T as pallet_evm::Config>::CrossAccountId, u128);112pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;113114#[frame_support::pallet]115pub mod pallet {116	use frame_support::{117		pallet_prelude::*, storage::Key, Blake2_128, Blake2_128Concat, Twox64Concat,118	};119	use up_data_structs::CollectionId;120121	use super::weights::WeightInfo;122123	#[pallet::error]124	pub enum Error<T> {125		/// Tried to set data for fungible item.126		FungibleItemsDontHaveData,127		/// Fungible token does not support nesting.128		FungibleDisallowsNesting,129		/// Setting item properties is not allowed.130		SettingPropertiesNotAllowed,131		/// Setting allowance for all is not allowed.132		SettingAllowanceForAllNotAllowed,133		/// Only a fungible collection could be possibly broken; any fungible token is valid.134		FungibleTokensAreAlwaysValid,135	}136137	#[pallet::config]138	pub trait Config:139		frame_system::Config + pallet_common::Config + pallet_structure::Config + pallet_evm::Config140	{141		type WeightInfo: WeightInfo;142	}143144	#[pallet::pallet]145	pub struct Pallet<T>(_);146147	/// Total amount of fungible tokens inside a collection.148	#[pallet::storage]149	pub type TotalSupply<T: Config> =150		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u128, QueryKind = ValueQuery>;151152	/// Amount of tokens owned by an account inside a collection.153	#[pallet::storage]154	pub type Balance<T: Config> = StorageNMap<155		Key = (156			Key<Twox64Concat, CollectionId>,157			Key<Blake2_128Concat, T::CrossAccountId>,158		),159		Value = u128,160		QueryKind = ValueQuery,161	>;162163	/// Storage for assets delegated to a limited extent to other users.164	#[pallet::storage]165	pub type Allowance<T: Config> = StorageNMap<166		Key = (167			Key<Twox64Concat, CollectionId>,168			Key<Blake2_128, T::CrossAccountId>,       // Owner169			Key<Blake2_128Concat, T::CrossAccountId>, // Spender170		),171		Value = u128,172		QueryKind = ValueQuery,173	>;174}175176/// Wrapper around untyped collection handle, asserting inner collection is of fungible type.177/// Required for interaction with Fungible collections, type safety and implementation [`solidity_interface`][`evm_coder::solidity_interface`].178pub struct FungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);179180/// Implementation of methods required for dispatching during runtime.181impl<T: Config> FungibleHandle<T> {182	/// Casts [`CollectionHandle`][`pallet_common::CollectionHandle`] into [`FungibleHandle`].183	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {184		Self(inner)185	}186187	/// Casts [`FungibleHandle`] into [`CollectionHandle`][`pallet_common::CollectionHandle`].188	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {189		self.0190	}191	/// Returns a mutable reference to the internal [`CollectionHandle`][`pallet_common::CollectionHandle`].192	pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {193		&mut self.0194	}195}196impl<T: Config> WithRecorder<T> for FungibleHandle<T> {197	fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {198		self.0.recorder()199	}200	fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {201		self.0.into_recorder()202	}203}204impl<T: Config> Deref for FungibleHandle<T> {205	type Target = pallet_common::CollectionHandle<T>;206207	fn deref(&self) -> &Self::Target {208		&self.0209	}210}211212/// Pallet implementation for fungible assets213impl<T: Config> Pallet<T> {214	/// 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		let _ = <Balance<T>>::clear_prefix((id,), u32::MAX, None);231		let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);232		Ok(())233	}234235	/// Add properties to the collection.236	pub fn set_collection_properties(237		collection: &FungibleHandle<T>,238		sender: &T::CrossAccountId,239		properties: Vec<Property>,240	) -> DispatchResult {241		<PalletCommon<T>>::set_collection_properties(collection, sender, properties.into_iter())242	}243244	/// Delete properties of the collection, associated with the provided keys.245	pub fn delete_collection_properties(246		collection: &FungibleHandle<T>,247		sender: &T::CrossAccountId,248		property_keys: Vec<PropertyKey>,249	) -> DispatchResult {250		<PalletCommon<T>>::delete_collection_properties(251			collection,252			sender,253			property_keys.into_iter(),254		)255	}256257	/// Checks if collection has tokens. Return `true` if it has.258	fn collection_has_tokens(collection_id: CollectionId) -> bool {259		<TotalSupply<T>>::get(collection_id) != 0260	}261262	/// Burns the specified amount of the token. If the token balance263	/// or total supply is less than the given value,264	/// it will return [DispatchError].265	pub fn burn(266		collection: &FungibleHandle<T>,267		owner: &T::CrossAccountId,268		amount: u128,269	) -> DispatchResult {270		let total_supply = <TotalSupply<T>>::get(collection.id)271			.checked_sub(amount)272			.ok_or(<CommonError<T>>::TokenValueTooLow)?;273274		let balance = <Balance<T>>::get((collection.id, owner))275			.checked_sub(amount)276			.ok_or(<CommonError<T>>::TokenValueTooLow)?;277278		if collection.permissions.access() == AccessMode::AllowList {279			collection.check_allowlist(owner)?;280		}281282		// =========283284		if balance == 0 {285			<Balance<T>>::remove((collection.id, owner));286			<PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());287		} else {288			<Balance<T>>::insert((collection.id, owner), balance);289		}290		<TotalSupply<T>>::insert(collection.id, total_supply);291292		<PalletEvm<T>>::deposit_log(293			ERC20Events::Transfer {294				from: *owner.as_eth(),295				to: H160::default(),296				value: amount.into(),297			}298			.to_log(collection_id_to_address(collection.id)),299		);300		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(301			collection.id,302			TokenId::default(),303			owner.clone(),304			amount,305		));306		Ok(())307	}308309	/// Transfers the specified amount of tokens. Will check that310	/// the transfer is allowed for the token.311	///312	/// - `from`: Owner of tokens to transfer.313	/// - `to`: Recepient of transfered tokens.314	/// - `amount`: Amount of tokens to transfer.315	/// - `collection`: Collection that contains the token316	pub fn transfer(317		collection: &FungibleHandle<T>,318		from: &T::CrossAccountId,319		to: &T::CrossAccountId,320		amount: u128,321		nesting_budget: &dyn Budget,322	) -> DispatchResultWithPostInfo {323		let depositor = from;324		Self::transfer_internal(collection, depositor, from, to, amount, nesting_budget)325	}326327	/// Transfers tokens from the `from` account to the `to` account.328	/// The `depositor` is the account who deposits the tokens.329	/// For instance, the nesting rules will be checked against the `depositor`'s permissions.330	fn transfer_internal(331		collection: &FungibleHandle<T>,332		depositor: &T::CrossAccountId,333		from: &T::CrossAccountId,334		to: &T::CrossAccountId,335		amount: u128,336		nesting_budget: &dyn Budget,337	) -> DispatchResultWithPostInfo {338		ensure!(339			collection.limits.transfers_enabled(),340			<CommonError<T>>::TransferNotAllowed,341		);342343		let mut actual_weight = <SelfWeightOf<T>>::transfer_raw();344345		if collection.permissions.access() == AccessMode::AllowList {346			collection.check_allowlist(from)?;347			collection.check_allowlist(to)?;348			actual_weight += <PalletCommonWeightOf<T>>::check_accesslist() * 2;349		}350		<PalletCommon<T>>::ensure_correct_receiver(to)?;351		let balance_from = <Balance<T>>::get((collection.id, from))352			.checked_sub(amount)353			.ok_or(<CommonError<T>>::TokenValueTooLow)?;354		let balance_to = if from != to && amount != 0 {355			Some(356				<Balance<T>>::get((collection.id, to))357					.checked_add(amount)358					.ok_or(ArithmeticError::Overflow)?,359			)360		} else {361			None362		};363364		// =========365366		if let Some(balance_to) = balance_to {367			// from != to && amount != 0368369			<PalletStructure<T>>::nest_if_sent_to_token(370				depositor,371				to,372				collection.id,373				TokenId::default(),374				nesting_budget,375			)?;376377			if balance_from == 0 {378				<Balance<T>>::remove((collection.id, from));379				<PalletStructure<T>>::unnest_if_nested(from, collection.id, TokenId::default());380			} else {381				<Balance<T>>::insert((collection.id, from), balance_from);382			}383			<Balance<T>>::insert((collection.id, to), balance_to);384		}385386		<PalletEvm<T>>::deposit_log(387			ERC20Events::Transfer {388				from: *from.as_eth(),389				to: *to.as_eth(),390				value: amount.into(),391			}392			.to_log(collection_id_to_address(collection.id)),393		);394		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(395			collection.id,396			TokenId::default(),397			from.clone(),398			to.clone(),399			amount,400		));401402		Ok(PostDispatchInfo {403			actual_weight: Some(actual_weight),404			pays_fee: Pays::Yes,405		})406	}407408	/// Minting tokens for multiple IDs.409	/// See [`create_item`][`Pallet::create_item`] for more details.410	pub fn create_multiple_items(411		collection: &FungibleHandle<T>,412		depositor: &T::CrossAccountId,413		data: BTreeMap<T::CrossAccountId, u128>,414		nesting_budget: &dyn Budget,415	) -> DispatchResult {416		if !collection.is_owner_or_admin(depositor) {417			ensure!(418				collection.permissions.mint_mode(),419				<CommonError<T>>::PublicMintingNotAllowed420			);421			collection.check_allowlist(depositor)?;422423			for (owner, _) in data.iter() {424				collection.check_allowlist(owner)?;425			}426		}427428		let total_supply = data429			.values()430			.copied()431			.try_fold(<TotalSupply<T>>::get(collection.id), |acc, v| {432				acc.checked_add(v)433			})434			.ok_or(ArithmeticError::Overflow)?;435436		for (to, _) in data.iter() {437			<PalletStructure<T>>::check_nesting(438				depositor,439				to,440				collection.id,441				TokenId::default(),442				nesting_budget,443			)?;444		}445446		let updated_balances = data447			.into_iter()448			.map(|(user, amount)| {449				let updated_balance = <Balance<T>>::get((collection.id, &user))450					.checked_add(amount)451					.ok_or(ArithmeticError::Overflow)?;452				Ok((user, amount, updated_balance))453			})454			.collect::<Result<Vec<_>, DispatchError>>()?;455456		// =========457458		<TotalSupply<T>>::insert(collection.id, total_supply);459		for (user, amount, updated_balance) in updated_balances {460			<Balance<T>>::insert((collection.id, &user), updated_balance);461			<PalletStructure<T>>::nest_if_sent_to_token_unchecked(462				&user,463				collection.id,464				TokenId::default(),465			);466			<PalletEvm<T>>::deposit_log(467				ERC20Events::Transfer {468					from: H160::default(),469					to: *user.as_eth(),470					value: amount.into(),471				}472				.to_log(collection_id_to_address(collection.id)),473			);474			<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(475				collection.id,476				TokenId::default(),477				user.clone(),478				amount,479			));480		}481482		Ok(())483	}484485	fn set_allowance_unchecked(486		collection: &FungibleHandle<T>,487		owner: &T::CrossAccountId,488		spender: &T::CrossAccountId,489		amount: u128,490	) {491		if amount == 0 {492			<Allowance<T>>::remove((collection.id, owner, spender));493		} else {494			<Allowance<T>>::insert((collection.id, owner, spender), amount);495		}496497		<PalletEvm<T>>::deposit_log(498			ERC20Events::Approval {499				owner: *owner.as_eth(),500				spender: *spender.as_eth(),501				value: amount.into(),502			}503			.to_log(collection_id_to_address(collection.id)),504		);505		<PalletCommon<T>>::deposit_event(CommonEvent::Approved(506			collection.id,507			TokenId(0),508			owner.clone(),509			spender.clone(),510			amount,511		));512	}513514	/// Set allowance for the spender to `transfer` or `burn` owner's tokens.515	///516	/// - `collection`: Collection that contains the token517	/// - `owner`: Owner of tokens that sets the allowance.518	/// - `spender`: Recipient of the allowance rights.519	/// - `amount`: Amount of tokens the spender is allowed to `transfer` or `burn`.520	pub fn set_allowance(521		collection: &FungibleHandle<T>,522		owner: &T::CrossAccountId,523		spender: &T::CrossAccountId,524		amount: u128,525	) -> DispatchResult {526		if collection.permissions.access() == AccessMode::AllowList {527			collection.check_allowlist(owner)?;528			collection.check_allowlist(spender)?;529		}530531		if <Balance<T>>::get((collection.id, owner)) < amount {532			ensure!(533				collection.ignores_owned_amount(owner),534				<CommonError<T>>::CantApproveMoreThanOwned535			);536		}537538		// =========539540		Self::set_allowance_unchecked(collection, owner, spender, amount);541		Ok(())542	}543544	/// Set allowance for the spender to `transfer` or `burn` owner's tokens from eth mirror.545	///546	/// - `collection`: Collection that contains the token547	/// - `sender`: Owner of tokens that sets the allowance.548	/// - `from`: Owner's eth mirror.549	/// - `to`: Recipient of the allowance rights.550	/// - `amount`: Amount of tokens the spender is allowed to `transfer` or `burn`.551	pub fn set_allowance_from(552		collection: &FungibleHandle<T>,553		sender: &T::CrossAccountId,554		from: &T::CrossAccountId,555		to: &T::CrossAccountId,556		amount: u128,557	) -> DispatchResult {558		if collection.permissions.access() == AccessMode::AllowList {559			collection.check_allowlist(sender)?;560			collection.check_allowlist(from)?;561			collection.check_allowlist(to)?;562		}563564		ensure!(565			sender.conv_eq(from),566			<CommonError<T>>::AddressIsNotEthMirror567		);568569		if <Balance<T>>::get((collection.id, from)) < amount {570			ensure!(571				collection.limits.owner_can_transfer()572					&& (collection.is_owner_or_admin(sender) || collection.is_owner_or_admin(from)),573				<CommonError<T>>::CantApproveMoreThanOwned574			);575		}576577		// =========578579		Self::set_allowance_unchecked(collection, from, to, amount);580		Ok(())581	}582583	/// Checks if a non-owner has (enough) allowance from the owner to perform operations on the tokens.584	/// Returns the expected remaining allowance - it should be set manually if the transaction proceeds.585	///586	/// - `collection`: Collection that contains the token.587	/// - `spender`: CrossAccountId who has the allowance rights.588	/// - `from`: The owner of the tokens who sets the allowance.589	/// - `amount`: Amount of tokens by which the allowance sholud be reduced.590	fn check_allowed(591		collection: &FungibleHandle<T>,592		spender: &T::CrossAccountId,593		from: &T::CrossAccountId,594		amount: u128,595		nesting_budget: &dyn Budget,596	) -> Result<Option<u128>, DispatchError> {597		if spender.conv_eq(from) {598			return Ok(None);599		}600		if collection.permissions.access() == AccessMode::AllowList {601			// `from`, `to` checked in [`transfer`]602			collection.check_allowlist(spender)?;603		}604605		if collection.ignores_token_restrictions(spender) {606			return Ok(Self::compute_allowance_decrease(607				collection, from, spender, amount,608			));609		}610611		if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {612			ensure!(613				<PalletStructure<T>>::check_indirectly_owned(614					spender.clone(),615					source.0,616					source.1,617					None,618					nesting_budget619				)?,620				<CommonError<T>>::ApprovedValueTooLow,621			);622			return Ok(None);623		}624625		let allowance = Self::compute_allowance_decrease(collection, from, spender, amount);626		ensure!(allowance.is_some(), <CommonError<T>>::ApprovedValueTooLow);627628		Ok(allowance)629	}630631	/// Returns `Some(amount)` if the `spender` have allowance to spend this amount.632	/// Otherwise, it returns `None`.633	fn compute_allowance_decrease(634		collection: &FungibleHandle<T>,635		from: &T::CrossAccountId,636		spender: &T::CrossAccountId,637		amount: u128,638	) -> Option<u128> {639		<Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount)640	}641642	/// Transfer fungible tokens from one account to another.643	/// Same as the [`transfer`][`Pallet::transfer`] but spender doesn't needs to be an owner of the token pieces.644	/// The owner should set allowance for the spender to transfer pieces.645	/// See [`set_allowance`][`Pallet::set_allowance`] for more details.646	pub fn transfer_from(647		collection: &FungibleHandle<T>,648		spender: &T::CrossAccountId,649		from: &T::CrossAccountId,650		to: &T::CrossAccountId,651		amount: u128,652		nesting_budget: &dyn Budget,653	) -> DispatchResultWithPostInfo {654		let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;655656		// =========657658		let mut result =659			Self::transfer_internal(collection, spender, from, to, amount, nesting_budget);660		add_weight_to_post_info(&mut result, <SelfWeightOf<T>>::check_allowed_raw());661		result?;662663		if let Some(allowance) = allowance {664			Self::set_allowance_unchecked(collection, from, spender, allowance);665			add_weight_to_post_info(666				&mut result,667				<SelfWeightOf<T>>::set_allowance_unchecked_raw(),668			)669		}670		result671	}672673	/// Burn fungible tokens from the account.674	///675	/// Same as the [`burn`][`Pallet::burn`] but spender doesn't need to be an owner of the tokens. The `from` should676	/// set allowance for the spender to burn tokens.677	/// See [`set_allowance`][`Pallet::set_allowance`] for more details.678	pub fn burn_from(679		collection: &FungibleHandle<T>,680		spender: &T::CrossAccountId,681		from: &T::CrossAccountId,682		amount: u128,683		nesting_budget: &dyn Budget,684	) -> DispatchResult {685		let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;686687		// =========688689		Self::burn(collection, from, amount)?;690		if let Some(allowance) = allowance {691			Self::set_allowance_unchecked(collection, from, spender, allowance);692		}693		Ok(())694	}695696	/// Creates fungible token.697	///698	/// The sender should be the owner/admin of the collection or collection should be configured699	/// to allow public minting.700	///701	/// - `data`: Contains user who will become the owners of the tokens and amount702	///   of tokens he will receive.703	pub fn create_item(704		collection: &FungibleHandle<T>,705		sender: &T::CrossAccountId,706		data: CreateItemData<T>,707		nesting_budget: &dyn Budget,708	) -> DispatchResult {709		Self::create_multiple_items(710			collection,711			sender,712			[(data.0, data.1)].into_iter().collect(),713			nesting_budget,714		)715	}716717	/// Returns 10 tokens owners in no particular order718	///719	/// There is no direct way to get token holders in ascending order,720	/// since `iter_prefix` returns values in no particular order.721	/// Therefore, getting the 10 largest holders with a large value of holders722	/// can lead to impact memory allocation + sorting with  `n * log (n)`.723	pub fn token_owners(724		collection: CollectionId,725		_token: TokenId,726	) -> Option<Vec<T::CrossAccountId>> {727		let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection,))728			.map(|(owner, _amount)| owner)729			.take(10)730			.collect();731732		if res.is_empty() {733			None734		} else {735			Some(res)736		}737	}738}
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): Trait for EVM support75//! - [`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;8283use evm_coder::ToLog;84use frame_support::{dispatch::PostDispatchInfo, ensure, pallet_prelude::*};85pub use pallet::*;86use pallet_common::{87	eth::collection_id_to_address, helpers::add_weight_to_post_info,88	weights::WeightInfo as CommonWeightInfo, Error as CommonError, Event as CommonEvent,89	Pallet as PalletCommon, SelfWeightOf as PalletCommonWeightOf,90};91use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};92use pallet_evm_coder_substrate::WithRecorder;93use pallet_structure::Pallet as PalletStructure;94use sp_core::H160;95use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};96use sp_std::{collections::btree_map::BTreeMap, vec::Vec};97use up_data_structs::{98	budget::Budget, mapping::TokenAddressMapping, AccessMode, CollectionId, Property, PropertyKey,99	TokenId,100};101use weights::WeightInfo;102103use crate::erc::ERC20Events;104#[cfg(feature = "runtime-benchmarks")]105pub mod benchmarking;106pub mod common;107pub mod erc;108pub mod weights;109110pub type CreateItemData<T> = (<T as pallet_evm::Config>::CrossAccountId, u128);111pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;112113#[frame_support::pallet]114pub mod pallet {115	use frame_support::{116		pallet_prelude::*, storage::Key, Blake2_128, Blake2_128Concat, Twox64Concat,117	};118	use up_data_structs::CollectionId;119120	use super::weights::WeightInfo;121122	#[pallet::error]123	pub enum Error<T> {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		/// Setting allowance for all is not allowed.131		SettingAllowanceForAllNotAllowed,132		/// Only a fungible collection could be possibly broken; any fungible token is valid.133		FungibleTokensAreAlwaysValid,134	}135136	#[pallet::config]137	pub trait Config:138		frame_system::Config + pallet_common::Config + pallet_structure::Config + pallet_evm::Config139	{140		type WeightInfo: WeightInfo;141	}142143	#[pallet::pallet]144	pub struct Pallet<T>(_);145146	/// Total amount of fungible tokens inside a collection.147	#[pallet::storage]148	pub type TotalSupply<T: Config> =149		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u128, QueryKind = ValueQuery>;150151	/// Amount of tokens owned by an account inside a collection.152	#[pallet::storage]153	pub type Balance<T: Config> = StorageNMap<154		Key = (155			Key<Twox64Concat, CollectionId>,156			Key<Blake2_128Concat, T::CrossAccountId>,157		),158		Value = u128,159		QueryKind = ValueQuery,160	>;161162	/// Storage for assets delegated to a limited extent to other users.163	#[pallet::storage]164	pub type Allowance<T: Config> = StorageNMap<165		Key = (166			Key<Twox64Concat, CollectionId>,167			Key<Blake2_128, T::CrossAccountId>,       // Owner168			Key<Blake2_128Concat, T::CrossAccountId>, // Spender169		),170		Value = u128,171		QueryKind = ValueQuery,172	>;173}174175/// Wrapper around untyped collection handle, asserting inner collection is of fungible type.176/// Required for interaction with Fungible collections, type safety and implementation [`solidity_interface`][`evm_coder::solidity_interface`].177pub struct FungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);178179/// Implementation of methods required for dispatching during runtime.180impl<T: Config> FungibleHandle<T> {181	/// Casts [`CollectionHandle`][`pallet_common::CollectionHandle`] into [`FungibleHandle`].182	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {183		Self(inner)184	}185186	/// Casts [`FungibleHandle`] into [`CollectionHandle`][`pallet_common::CollectionHandle`].187	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {188		self.0189	}190	/// Returns a mutable reference to the internal [`CollectionHandle`][`pallet_common::CollectionHandle`].191	pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {192		&mut self.0193	}194}195impl<T: Config> WithRecorder<T> for FungibleHandle<T> {196	fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {197		self.0.recorder()198	}199	fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {200		self.0.into_recorder()201	}202}203impl<T: Config> Deref for FungibleHandle<T> {204	type Target = pallet_common::CollectionHandle<T>;205206	fn deref(&self) -> &Self::Target {207		&self.0208	}209}210211/// Pallet implementation for fungible assets212impl<T: Config> Pallet<T> {213	/// Destroys a collection.214	pub fn destroy_collection(215		collection: FungibleHandle<T>,216		sender: &T::CrossAccountId,217	) -> DispatchResult {218		let id = collection.id;219220		if Self::collection_has_tokens(id) {221			return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());222		}223224		// =========225226		PalletCommon::destroy_collection(collection.0, sender)?;227228		<TotalSupply<T>>::remove(id);229		let _ = <Balance<T>>::clear_prefix((id,), u32::MAX, None);230		let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);231		Ok(())232	}233234	/// Add properties to the collection.235	pub fn set_collection_properties(236		collection: &FungibleHandle<T>,237		sender: &T::CrossAccountId,238		properties: Vec<Property>,239	) -> DispatchResult {240		<PalletCommon<T>>::set_collection_properties(collection, sender, properties.into_iter())241	}242243	/// Delete properties of the collection, associated with the provided keys.244	pub fn delete_collection_properties(245		collection: &FungibleHandle<T>,246		sender: &T::CrossAccountId,247		property_keys: Vec<PropertyKey>,248	) -> DispatchResult {249		<PalletCommon<T>>::delete_collection_properties(250			collection,251			sender,252			property_keys.into_iter(),253		)254	}255256	/// Checks if collection has tokens. Return `true` if it has.257	fn collection_has_tokens(collection_id: CollectionId) -> bool {258		<TotalSupply<T>>::get(collection_id) != 0259	}260261	/// Burns the specified amount of the token. If the token balance262	/// or total supply is less than the given value,263	/// it will return [DispatchError].264	pub fn burn(265		collection: &FungibleHandle<T>,266		owner: &T::CrossAccountId,267		amount: u128,268	) -> DispatchResult {269		let total_supply = <TotalSupply<T>>::get(collection.id)270			.checked_sub(amount)271			.ok_or(<CommonError<T>>::TokenValueTooLow)?;272273		let balance = <Balance<T>>::get((collection.id, owner))274			.checked_sub(amount)275			.ok_or(<CommonError<T>>::TokenValueTooLow)?;276277		if collection.permissions.access() == AccessMode::AllowList {278			collection.check_allowlist(owner)?;279		}280281		// =========282283		if balance == 0 {284			<Balance<T>>::remove((collection.id, owner));285			<PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());286		} else {287			<Balance<T>>::insert((collection.id, owner), balance);288		}289		<TotalSupply<T>>::insert(collection.id, total_supply);290291		<PalletEvm<T>>::deposit_log(292			ERC20Events::Transfer {293				from: *owner.as_eth(),294				to: H160::default(),295				value: amount.into(),296			}297			.to_log(collection_id_to_address(collection.id)),298		);299		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(300			collection.id,301			TokenId::default(),302			owner.clone(),303			amount,304		));305		Ok(())306	}307308	/// Transfers the specified amount of tokens. Will check that309	/// the transfer is allowed for the token.310	///311	/// - `from`: Owner of tokens to transfer.312	/// - `to`: Recepient of transfered tokens.313	/// - `amount`: Amount of tokens to transfer.314	/// - `collection`: Collection that contains the token315	pub fn transfer(316		collection: &FungibleHandle<T>,317		from: &T::CrossAccountId,318		to: &T::CrossAccountId,319		amount: u128,320		nesting_budget: &dyn Budget,321	) -> DispatchResultWithPostInfo {322		let depositor = from;323		Self::transfer_internal(collection, depositor, from, to, amount, nesting_budget)324	}325326	/// Transfers tokens from the `from` account to the `to` account.327	/// The `depositor` is the account who deposits the tokens.328	/// For instance, the nesting rules will be checked against the `depositor`'s permissions.329	fn transfer_internal(330		collection: &FungibleHandle<T>,331		depositor: &T::CrossAccountId,332		from: &T::CrossAccountId,333		to: &T::CrossAccountId,334		amount: u128,335		nesting_budget: &dyn Budget,336	) -> DispatchResultWithPostInfo {337		ensure!(338			collection.limits.transfers_enabled(),339			<CommonError<T>>::TransferNotAllowed,340		);341342		let mut actual_weight = <SelfWeightOf<T>>::transfer_raw();343344		if collection.permissions.access() == AccessMode::AllowList {345			collection.check_allowlist(from)?;346			collection.check_allowlist(to)?;347			actual_weight += <PalletCommonWeightOf<T>>::check_accesslist() * 2;348		}349		<PalletCommon<T>>::ensure_correct_receiver(to)?;350		let balance_from = <Balance<T>>::get((collection.id, from))351			.checked_sub(amount)352			.ok_or(<CommonError<T>>::TokenValueTooLow)?;353		let balance_to = if from != to && amount != 0 {354			Some(355				<Balance<T>>::get((collection.id, to))356					.checked_add(amount)357					.ok_or(ArithmeticError::Overflow)?,358			)359		} else {360			None361		};362363		// =========364365		if let Some(balance_to) = balance_to {366			// from != to && amount != 0367368			<PalletStructure<T>>::nest_if_sent_to_token(369				depositor,370				to,371				collection.id,372				TokenId::default(),373				nesting_budget,374			)?;375376			if balance_from == 0 {377				<Balance<T>>::remove((collection.id, from));378				<PalletStructure<T>>::unnest_if_nested(from, collection.id, TokenId::default());379			} else {380				<Balance<T>>::insert((collection.id, from), balance_from);381			}382			<Balance<T>>::insert((collection.id, to), balance_to);383		}384385		<PalletEvm<T>>::deposit_log(386			ERC20Events::Transfer {387				from: *from.as_eth(),388				to: *to.as_eth(),389				value: amount.into(),390			}391			.to_log(collection_id_to_address(collection.id)),392		);393		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(394			collection.id,395			TokenId::default(),396			from.clone(),397			to.clone(),398			amount,399		));400401		Ok(PostDispatchInfo {402			actual_weight: Some(actual_weight),403			pays_fee: Pays::Yes,404		})405	}406407	/// Minting tokens for multiple IDs.408	/// See [`create_item`][`Pallet::create_item`] for more details.409	pub fn create_multiple_items(410		collection: &FungibleHandle<T>,411		depositor: &T::CrossAccountId,412		data: BTreeMap<T::CrossAccountId, u128>,413		nesting_budget: &dyn Budget,414	) -> DispatchResult {415		if !collection.is_owner_or_admin(depositor) {416			ensure!(417				collection.permissions.mint_mode(),418				<CommonError<T>>::PublicMintingNotAllowed419			);420			collection.check_allowlist(depositor)?;421422			for (owner, _) in data.iter() {423				collection.check_allowlist(owner)?;424			}425		}426427		let total_supply = data428			.values()429			.copied()430			.try_fold(<TotalSupply<T>>::get(collection.id), |acc, v| {431				acc.checked_add(v)432			})433			.ok_or(ArithmeticError::Overflow)?;434435		for (to, _) in data.iter() {436			<PalletStructure<T>>::check_nesting(437				depositor,438				to,439				collection.id,440				TokenId::default(),441				nesting_budget,442			)?;443		}444445		let updated_balances = data446			.into_iter()447			.map(|(user, amount)| {448				let updated_balance = <Balance<T>>::get((collection.id, &user))449					.checked_add(amount)450					.ok_or(ArithmeticError::Overflow)?;451				Ok((user, amount, updated_balance))452			})453			.collect::<Result<Vec<_>, DispatchError>>()?;454455		// =========456457		<TotalSupply<T>>::insert(collection.id, total_supply);458		for (user, amount, updated_balance) in updated_balances {459			<Balance<T>>::insert((collection.id, &user), updated_balance);460			<PalletStructure<T>>::nest_if_sent_to_token_unchecked(461				&user,462				collection.id,463				TokenId::default(),464			);465			<PalletEvm<T>>::deposit_log(466				ERC20Events::Transfer {467					from: H160::default(),468					to: *user.as_eth(),469					value: amount.into(),470				}471				.to_log(collection_id_to_address(collection.id)),472			);473			<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(474				collection.id,475				TokenId::default(),476				user.clone(),477				amount,478			));479		}480481		Ok(())482	}483484	fn set_allowance_unchecked(485		collection: &FungibleHandle<T>,486		owner: &T::CrossAccountId,487		spender: &T::CrossAccountId,488		amount: u128,489	) {490		if amount == 0 {491			<Allowance<T>>::remove((collection.id, owner, spender));492		} else {493			<Allowance<T>>::insert((collection.id, owner, spender), amount);494		}495496		<PalletEvm<T>>::deposit_log(497			ERC20Events::Approval {498				owner: *owner.as_eth(),499				spender: *spender.as_eth(),500				value: amount.into(),501			}502			.to_log(collection_id_to_address(collection.id)),503		);504		<PalletCommon<T>>::deposit_event(CommonEvent::Approved(505			collection.id,506			TokenId(0),507			owner.clone(),508			spender.clone(),509			amount,510		));511	}512513	/// Set allowance for the spender to `transfer` or `burn` owner's tokens.514	///515	/// - `collection`: Collection that contains the token516	/// - `owner`: Owner of tokens that sets the allowance.517	/// - `spender`: Recipient of the allowance rights.518	/// - `amount`: Amount of tokens the spender is allowed to `transfer` or `burn`.519	pub fn set_allowance(520		collection: &FungibleHandle<T>,521		owner: &T::CrossAccountId,522		spender: &T::CrossAccountId,523		amount: u128,524	) -> DispatchResult {525		if collection.permissions.access() == AccessMode::AllowList {526			collection.check_allowlist(owner)?;527			collection.check_allowlist(spender)?;528		}529530		if <Balance<T>>::get((collection.id, owner)) < amount {531			ensure!(532				collection.ignores_owned_amount(owner),533				<CommonError<T>>::CantApproveMoreThanOwned534			);535		}536537		// =========538539		Self::set_allowance_unchecked(collection, owner, spender, amount);540		Ok(())541	}542543	/// Set allowance for the spender to `transfer` or `burn` owner's tokens from eth mirror.544	///545	/// - `collection`: Collection that contains the token546	/// - `sender`: Owner of tokens that sets the allowance.547	/// - `from`: Owner's eth mirror.548	/// - `to`: Recipient of the allowance rights.549	/// - `amount`: Amount of tokens the spender is allowed to `transfer` or `burn`.550	pub fn set_allowance_from(551		collection: &FungibleHandle<T>,552		sender: &T::CrossAccountId,553		from: &T::CrossAccountId,554		to: &T::CrossAccountId,555		amount: u128,556	) -> DispatchResult {557		if collection.permissions.access() == AccessMode::AllowList {558			collection.check_allowlist(sender)?;559			collection.check_allowlist(from)?;560			collection.check_allowlist(to)?;561		}562563		ensure!(564			sender.conv_eq(from),565			<CommonError<T>>::AddressIsNotEthMirror566		);567568		if <Balance<T>>::get((collection.id, from)) < amount {569			ensure!(570				collection.limits.owner_can_transfer()571					&& (collection.is_owner_or_admin(sender) || collection.is_owner_or_admin(from)),572				<CommonError<T>>::CantApproveMoreThanOwned573			);574		}575576		// =========577578		Self::set_allowance_unchecked(collection, from, to, amount);579		Ok(())580	}581582	/// Checks if a non-owner has (enough) allowance from the owner to perform operations on the tokens.583	/// Returns the expected remaining allowance - it should be set manually if the transaction proceeds.584	///585	/// - `collection`: Collection that contains the token.586	/// - `spender`: CrossAccountId who has the allowance rights.587	/// - `from`: The owner of the tokens who sets the allowance.588	/// - `amount`: Amount of tokens by which the allowance sholud be reduced.589	fn check_allowed(590		collection: &FungibleHandle<T>,591		spender: &T::CrossAccountId,592		from: &T::CrossAccountId,593		amount: u128,594		nesting_budget: &dyn Budget,595	) -> Result<Option<u128>, DispatchError> {596		if spender.conv_eq(from) {597			return Ok(None);598		}599		if collection.permissions.access() == AccessMode::AllowList {600			// `from`, `to` checked in [`transfer`]601			collection.check_allowlist(spender)?;602		}603604		if collection.ignores_token_restrictions(spender) {605			return Ok(Self::compute_allowance_decrease(606				collection, from, spender, amount,607			));608		}609610		if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {611			ensure!(612				<PalletStructure<T>>::check_indirectly_owned(613					spender.clone(),614					source.0,615					source.1,616					None,617					nesting_budget618				)?,619				<CommonError<T>>::ApprovedValueTooLow,620			);621			return Ok(None);622		}623624		let allowance = Self::compute_allowance_decrease(collection, from, spender, amount);625		ensure!(allowance.is_some(), <CommonError<T>>::ApprovedValueTooLow);626627		Ok(allowance)628	}629630	/// Returns `Some(amount)` if the `spender` have allowance to spend this amount.631	/// Otherwise, it returns `None`.632	fn compute_allowance_decrease(633		collection: &FungibleHandle<T>,634		from: &T::CrossAccountId,635		spender: &T::CrossAccountId,636		amount: u128,637	) -> Option<u128> {638		<Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount)639	}640641	/// Transfer fungible tokens from one account to another.642	/// Same as the [`transfer`][`Pallet::transfer`] but spender doesn't needs to be an owner of the token pieces.643	/// The owner should set allowance for the spender to transfer pieces.644	/// See [`set_allowance`][`Pallet::set_allowance`] for more details.645	pub fn transfer_from(646		collection: &FungibleHandle<T>,647		spender: &T::CrossAccountId,648		from: &T::CrossAccountId,649		to: &T::CrossAccountId,650		amount: u128,651		nesting_budget: &dyn Budget,652	) -> DispatchResultWithPostInfo {653		let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;654655		// =========656657		let mut result =658			Self::transfer_internal(collection, spender, from, to, amount, nesting_budget);659		add_weight_to_post_info(&mut result, <SelfWeightOf<T>>::check_allowed_raw());660		result?;661662		if let Some(allowance) = allowance {663			Self::set_allowance_unchecked(collection, from, spender, allowance);664			add_weight_to_post_info(665				&mut result,666				<SelfWeightOf<T>>::set_allowance_unchecked_raw(),667			)668		}669		result670	}671672	/// Burn fungible tokens from the account.673	///674	/// Same as the [`burn`][`Pallet::burn`] but spender doesn't need to be an owner of the tokens. The `from` should675	/// set allowance for the spender to burn tokens.676	/// See [`set_allowance`][`Pallet::set_allowance`] for more details.677	pub fn burn_from(678		collection: &FungibleHandle<T>,679		spender: &T::CrossAccountId,680		from: &T::CrossAccountId,681		amount: u128,682		nesting_budget: &dyn Budget,683	) -> DispatchResult {684		let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;685686		// =========687688		Self::burn(collection, from, amount)?;689		if let Some(allowance) = allowance {690			Self::set_allowance_unchecked(collection, from, spender, allowance);691		}692		Ok(())693	}694695	/// Creates fungible token.696	///697	/// The sender should be the owner/admin of the collection or collection should be configured698	/// to allow public minting.699	///700	/// - `data`: Contains user who will become the owners of the tokens and amount701	///   of tokens he will receive.702	pub fn create_item(703		collection: &FungibleHandle<T>,704		sender: &T::CrossAccountId,705		data: CreateItemData<T>,706		nesting_budget: &dyn Budget,707	) -> DispatchResult {708		Self::create_multiple_items(709			collection,710			sender,711			[(data.0, data.1)].into_iter().collect(),712			nesting_budget,713		)714	}715716	/// Returns 10 tokens owners in no particular order717	///718	/// There is no direct way to get token holders in ascending order,719	/// since `iter_prefix` returns values in no particular order.720	/// Therefore, getting the 10 largest holders with a large value of holders721	/// can lead to impact memory allocation + sorting with  `n * log (n)`.722	pub fn token_owners(723		collection: CollectionId,724		_token: TokenId,725	) -> Option<Vec<T::CrossAccountId>> {726		let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection,))727			.map(|(owner, _amount)| owner)728			.take(10)729			.collect();730731		if res.is_empty() {732			None733		} else {734			Some(res)735		}736	}737}
modifiedpallets/nonfungible/src/common.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -576,6 +576,10 @@
 		self.flags.foreign
 	}
 
+	fn token_has_children(&self, token: TokenId) -> bool {
+		<Pallet<T>>::token_has_children(self.id, token)
+	}
+
 	fn create_item_internal(
 		&self,
 		depositor: &<T>::CrossAccountId,
modifiedpallets/nonfungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -117,8 +117,8 @@
 use sp_std::{collections::btree_map::BTreeMap, vec, vec::Vec};
 use up_data_structs::{
 	budget::Budget, mapping::TokenAddressMapping, AccessMode, AuxPropertyValue, CollectionId,
-	CreateCollectionData, CreateNftExData, CustomDataLimit, PropertiesPermissionMap, Property,
-	PropertyKey, PropertyKeyPermission, PropertyScope, PropertyValue, TokenChild, TokenId,
+	CreateNftExData, CustomDataLimit, PropertiesPermissionMap, Property, PropertyKey,
+	PropertyKeyPermission, PropertyScope, PropertyValue, TokenChild, TokenId,
 	TokenProperties as TokenPropertiesT,
 };
 use weights::WeightInfo;