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

difftreelog

feat add ApproveForAll to Eth and Sub

Grigoriy Simonov2022-12-06parent: #e7f81f3.patch.diff
in: master

39 files changed

modifiedclient/rpc/src/lib.rsdiffbeforeafterboth
--- a/client/rpc/src/lib.rs
+++ b/client/rpc/src/lib.rs
@@ -246,6 +246,16 @@
 		token_id: TokenId,
 		at: Option<BlockHash>,
 	) -> Result<Option<String>>;
+
+	/// Get whether an operator is approved by a given owner.
+	#[method(name = "unique_isApprovedForAll")]
+	fn is_approved_for_all(
+		&self,
+		collection: CollectionId,
+		owner: CrossAccountId,
+		operator: CrossAccountId,
+		at: Option<BlockHash>,
+	) -> Result<bool>;
 }
 
 mod app_promotion_unique_rpc {
@@ -569,6 +579,7 @@
 	pass_method!(effective_collection_limits(collection_id: CollectionId) -> Option<CollectionLimits>, unique_api);
 	pass_method!(total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<String> => |o| o.map(|number| number.to_string()) , unique_api);
 	pass_method!(token_owners(collection: CollectionId, token: TokenId) -> Vec<CrossAccountId>, unique_api);
+	pass_method!(is_approved_for_all(collection: CollectionId, owner: CrossAccountId, operator: CrossAccountId) -> bool, unique_api);
 }
 
 impl<C, Block, BlockNumber, CrossAccountId, AccountId>
modifiedpallets/common/src/lib.rsdiffbeforeafterboth
before · pallets/common/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//! # Common pallet18//!19//! The Common pallet provides functionality for handling collections.20//!21//! ## Overview22//!23//! The Common pallet provides an interface for common collection operations for different collection types24//! (see [CommonCollectionOperations]), as well as a generic dispatcher for these, see [dispatch] module.25//! It also provides this functionality to EVM, see [erc] and [eth] modules.26//!27//! The Common pallet provides functions for:28//!29//! - Setting and approving collection sponsor.30//! - Get\set\delete allow list.31//! - Get\set\delete collection properties.32//! - Get\set\delete collection property permissions.33//! - Get\set\delete token property permissions.34//! - Get\set\delete collection administrators.35//! - Checking access permissions.36//!37//! ### Terminology38//! **Collection sponsor** - For the collection, you can set a sponsor, at whose expense it will39//! be possible to mint tokens.40//!41//! **Allow list** - List of users who have the right to minting tokens.42//!43//! **Collection properties** - Collection properties are simply key-value stores where various44//! metadata can be placed.45//!46//! **Permissions on token properties** - For each property in the token can be set permission47//! to change, see [`PropertyPermission`].48//!49//! **Collection administrator** - For a collection, you can set administrators who have the right50//! to most actions on the collection.5152#![warn(missing_docs)]53#![cfg_attr(not(feature = "std"), no_std)]54extern crate alloc;5556use core::ops::{Deref, DerefMut};57use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};58use sp_std::vec::Vec;59use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};60use evm_coder::ToLog;61use frame_support::{62	dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},63	ensure,64	traits::{Imbalance, Get, Currency, WithdrawReasons, ExistenceRequirement},65	dispatch::Pays,66	transactional,67};68use pallet_evm::GasWeightMapping;69use up_data_structs::{70	COLLECTION_NUMBER_LIMIT,71	Collection,72	RpcCollection,73	CollectionFlags,74	RpcCollectionFlags,75	CollectionId,76	CreateItemData,77	MAX_TOKEN_PREFIX_LENGTH,78	COLLECTION_ADMINS_LIMIT,79	TokenId,80	TokenChild,81	CollectionStats,82	MAX_TOKEN_OWNERSHIP,83	CollectionMode,84	NFT_SPONSOR_TRANSFER_TIMEOUT,85	FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,86	REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,87	MAX_SPONSOR_TIMEOUT,88	CUSTOM_DATA_LIMIT,89	CollectionLimits,90	CreateCollectionData,91	SponsorshipState,92	CreateItemExData,93	SponsoringRateLimit,94	budget::Budget,95	PhantomType,96	Property,97	Properties,98	PropertiesPermissionMap,99	PropertyKey,100	PropertyValue,101	PropertyPermission,102	PropertiesError,103	PropertyKeyPermission,104	TokenData,105	TrySetProperty,106	PropertyScope,107	// RMRK108	RmrkCollectionInfo,109	RmrkInstanceInfo,110	RmrkResourceInfo,111	RmrkPropertyInfo,112	RmrkBaseInfo,113	RmrkPartType,114	RmrkBoundedTheme,115	RmrkNftChild,116	CollectionPermissions,117};118119pub use pallet::*;120use sp_core::H160;121use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};122#[cfg(feature = "runtime-benchmarks")]123pub mod benchmarking;124pub mod dispatch;125pub mod erc;126pub mod eth;127pub mod weights;128129/// Weight info.130pub type SelfWeightOf<T> = <T as Config>::WeightInfo;131132/// Collection handle contains information about collection data and id.133/// Also provides functionality to count consumed gas.134///135/// CollectionHandle is used as a generic wrapper for collections of all types.136/// It allows to perform common operations and queries on any collection type,137/// both completely general for all, as well as their respective implementations of [`CommonCollectionOperations`].138#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]139pub struct CollectionHandle<T: Config> {140	/// Collection id141	pub id: CollectionId,142	collection: Collection<T::AccountId>,143	/// Substrate recorder for counting consumed gas144	pub recorder: SubstrateRecorder<T>,145}146147impl<T: Config> WithRecorder<T> for CollectionHandle<T> {148	fn recorder(&self) -> &SubstrateRecorder<T> {149		&self.recorder150	}151	fn into_recorder(self) -> SubstrateRecorder<T> {152		self.recorder153	}154}155156impl<T: Config> CollectionHandle<T> {157	/// Same as [CollectionHandle::new] but with an explicit gas limit.158	pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {159		<CollectionById<T>>::get(id).map(|collection| Self {160			id,161			collection,162			recorder: SubstrateRecorder::new(gas_limit),163		})164	}165166	/// Same as [CollectionHandle::new] but with an existed [`SubstrateRecorder`].167	pub fn new_with_recorder(id: CollectionId, recorder: SubstrateRecorder<T>) -> Option<Self> {168		<CollectionById<T>>::get(id).map(|collection| Self {169			id,170			collection,171			recorder,172		})173	}174175	/// Retrives collection data from storage and creates collection handle with default parameters.176	/// If collection not found return `None`177	pub fn new(id: CollectionId) -> Option<Self> {178		Self::new_with_gas_limit(id, u64::MAX)179	}180181	/// Same as [`CollectionHandle::new`] but if collection not found [CollectionNotFound](Error::CollectionNotFound) returned.182	pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {183		Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)184	}185186	/// Consume gas for reading.187	pub fn consume_store_reads(&self, reads: u64) -> evm_coder::execution::Result<()> {188		self.recorder189			.consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(190				<T as frame_system::Config>::DbWeight::get()191					.read192					.saturating_mul(reads),193			)))194	}195196	/// Consume gas for writing.197	pub fn consume_store_writes(&self, writes: u64) -> evm_coder::execution::Result<()> {198		self.recorder199			.consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(200				<T as frame_system::Config>::DbWeight::get()201					.write202					.saturating_mul(writes),203			)))204	}205206	/// Consume gas for reading and writing.207	pub fn consume_store_reads_and_writes(208		&self,209		reads: u64,210		writes: u64,211	) -> evm_coder::execution::Result<()> {212		let weight = <T as frame_system::Config>::DbWeight::get();213		let reads = weight.read.saturating_mul(reads);214		let writes = weight.read.saturating_mul(writes);215		self.recorder216			.consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(217				reads.saturating_add(writes),218			)))219	}220221	/// Save collection to storage.222	pub fn save(&self) -> DispatchResult {223		<CollectionById<T>>::insert(self.id, &self.collection);224		Ok(())225	}226227	/// Set collection sponsor.228	///229	/// Unique collections allows sponsoring for certain actions.230	/// This method allows you to set the sponsor of the collection.231	/// In order for sponsorship to become active, it must be confirmed through [`Self::confirm_sponsorship`].232	pub fn set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {233		self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor);234		Ok(())235	}236237	/// Confirm sponsorship238	///239	/// In order for the sponsorship to become active, the user set as the sponsor must confirm their participation.240	/// Before confirming sponsorship, the user must be specified as the sponsor of the collection via [`Self::set_sponsor`].241	pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> Result<bool, DispatchError> {242		if self.collection.sponsorship.pending_sponsor() != Some(sender) {243			return Ok(false);244		}245246		self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());247		Ok(true)248	}249250	/// Remove collection sponsor.251	pub fn remove_sponsor(&mut self) -> DispatchResult {252		self.collection.sponsorship = SponsorshipState::Disabled;253		Ok(())254	}255256	/// Checks that the collection was created with, and must be operated upon through **Unique API**.257	/// Now check only the `external` flag and if it's **true**, then return [`Error::CollectionIsExternal`] error.258	pub fn check_is_internal(&self) -> DispatchResult {259		if self.flags.external {260			return Err(<Error<T>>::CollectionIsExternal)?;261		}262263		Ok(())264	}265266	/// Checks that the collection was created with, and must be operated upon through an **assimilated API**.267	/// Now check only the `external` flag and if it's **false**, then return [`Error::CollectionIsInternal`] error.268	pub fn check_is_external(&self) -> DispatchResult {269		if !self.flags.external {270			return Err(<Error<T>>::CollectionIsInternal)?;271		}272273		Ok(())274	}275}276277impl<T: Config> Deref for CollectionHandle<T> {278	type Target = Collection<T::AccountId>;279280	fn deref(&self) -> &Self::Target {281		&self.collection282	}283}284285impl<T: Config> DerefMut for CollectionHandle<T> {286	fn deref_mut(&mut self) -> &mut Self::Target {287		&mut self.collection288	}289}290291impl<T: Config> CollectionHandle<T> {292	/// Checks if the `user` is the owner of the collection.293	pub fn check_is_owner(&self, user: &T::CrossAccountId) -> DispatchResult {294		ensure!(*user.as_sub() == self.owner, <Error<T>>::NoPermission);295		Ok(())296	}297298	/// Returns **true** if the `user` is the owner or administrator of the collection.299	pub fn is_owner_or_admin(&self, user: &T::CrossAccountId) -> bool {300		*user.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, user))301	}302303	/// Checks if the `user` is the owner or administrator of the collection.304	pub fn check_is_owner_or_admin(&self, user: &T::CrossAccountId) -> DispatchResult {305		ensure!(self.is_owner_or_admin(user), <Error<T>>::NoPermission);306		Ok(())307	}308309	/// Return **true** if `user` was not allowed to have tokens, and he can ignore such restrictions.310	pub fn ignores_allowance(&self, user: &T::CrossAccountId) -> bool {311		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)312	}313314	/// Return **true** if `user` does not have enough token parts, and he can ignore such restrictions.315	pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {316		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)317	}318319	/// Checks if the user is in the allow list. If not [Error::AddressNotInAllowlist] returns.320	pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {321		ensure!(322			<Allowlist<T>>::get((self.id, user)),323			<Error<T>>::AddressNotInAllowlist324		);325		Ok(())326	}327328	/// Changes collection owner to another account329	/// #### Store read/writes330	/// 1 writes331	fn set_owner_internal(332		&mut self,333		caller: T::CrossAccountId,334		new_owner: T::CrossAccountId,335	) -> DispatchResult {336		self.check_is_owner(&caller)?;337		self.collection.owner = new_owner.as_sub().clone();338		self.save()339	}340}341342#[frame_support::pallet]343pub mod pallet {344	use super::*;345	use dispatch::CollectionDispatch;346	use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};347	use frame_system::pallet_prelude::*;348	use frame_support::traits::Currency;349	use up_data_structs::{TokenId, mapping::TokenAddressMapping};350	use scale_info::TypeInfo;351	use weights::WeightInfo;352353	#[pallet::config]354	pub trait Config:355		frame_system::Config + pallet_evm_coder_substrate::Config + pallet_evm::Config + TypeInfo356	{357		/// Weight information for functions of this pallet.358		type WeightInfo: WeightInfo;359360		/// Events compatible with [`frame_system::Config::Event`].361		type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;362363		/// Handler of accounts and payment.364		type Currency: Currency<Self::AccountId>;365366		/// Set price to create a collection.367		#[pallet::constant]368		type CollectionCreationPrice: Get<369			<<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,370		>;371372		/// Dispatcher of operations on collections.373		type CollectionDispatch: CollectionDispatch<Self>;374375		/// Account which holds the chain's treasury.376		type TreasuryAccountId: Get<Self::AccountId>;377378		/// Address under which the CollectionHelper contract would be available.379		#[pallet::constant]380		type ContractAddress: Get<H160>;381382		/// Mapper for token addresses to Ethereum addresses.383		type EvmTokenAddressMapping: TokenAddressMapping<H160>;384385		/// Mapper for token addresses to [`CrossAccountId`].386		type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;387	}388389	const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);390391	#[pallet::pallet]392	#[pallet::storage_version(STORAGE_VERSION)]393	#[pallet::generate_store(pub(super) trait Store)]394	pub struct Pallet<T>(_);395396	#[pallet::extra_constants]397	impl<T: Config> Pallet<T> {398		/// Maximum admins per collection.399		pub fn collection_admins_limit() -> u32 {400			COLLECTION_ADMINS_LIMIT401		}402	}403404	#[pallet::event]405	#[pallet::generate_deposit(pub fn deposit_event)]406	pub enum Event<T: Config> {407		/// New collection was created408		CollectionCreated(409			/// Globally unique identifier of newly created collection.410			CollectionId,411			/// [`CollectionMode`] converted into _u8_.412			u8,413			/// Collection owner.414			T::AccountId,415		),416417		/// New collection was destroyed418		CollectionDestroyed(419			/// Globally unique identifier of collection.420			CollectionId,421		),422423		/// New item was created.424		ItemCreated(425			/// Id of the collection where item was created.426			CollectionId,427			/// Id of an item. Unique within the collection.428			TokenId,429			/// Owner of newly created item430			T::CrossAccountId,431			/// Always 1 for NFT432			u128,433		),434435		/// Collection item was burned.436		ItemDestroyed(437			/// Id of the collection where item was destroyed.438			CollectionId,439			/// Identifier of burned NFT.440			TokenId,441			/// Which user has destroyed its tokens.442			T::CrossAccountId,443			/// Amount of token pieces destroed. Always 1 for NFT.444			u128,445		),446447		/// Item was transferred448		Transfer(449			/// Id of collection to which item is belong.450			CollectionId,451			/// Id of an item.452			TokenId,453			/// Original owner of item.454			T::CrossAccountId,455			/// New owner of item.456			T::CrossAccountId,457			/// Amount of token pieces transfered. Always 1 for NFT.458			u128,459		),460461		/// Amount pieces of token owned by `sender` was approved for `spender`.462		Approved(463			/// Id of collection to which item is belong.464			CollectionId,465			/// Id of an item.466			TokenId,467			/// Original owner of item.468			T::CrossAccountId,469			/// Id for which the approval was granted.470			T::CrossAccountId,471			/// Amount of token pieces transfered. Always 1 for NFT.472			u128,473		),474475		/// The colletion property has been added or edited.476		CollectionPropertySet(477			/// Id of collection to which property has been set.478			CollectionId,479			/// The property that was set.480			PropertyKey,481		),482483		/// The property has been deleted.484		CollectionPropertyDeleted(485			/// Id of collection to which property has been deleted.486			CollectionId,487			/// The property that was deleted.488			PropertyKey,489		),490491		/// The token property has been added or edited.492		TokenPropertySet(493			/// Identifier of the collection whose token has the property set.494			CollectionId,495			/// The token for which the property was set.496			TokenId,497			/// The property that was set.498			PropertyKey,499		),500501		/// The token property has been deleted.502		TokenPropertyDeleted(503			/// Identifier of the collection whose token has the property deleted.504			CollectionId,505			/// The token for which the property was deleted.506			TokenId,507			/// The property that was deleted.508			PropertyKey,509		),510511		/// The token property permission of a collection has been set.512		PropertyPermissionSet(513			/// ID of collection to which property permission has been set.514			CollectionId,515			/// The property permission that was set.516			PropertyKey,517		),518	}519520	#[pallet::error]521	pub enum Error<T> {522		/// This collection does not exist.523		CollectionNotFound,524		/// Sender parameter and item owner must be equal.525		MustBeTokenOwner,526		/// No permission to perform action527		NoPermission,528		/// Destroying only empty collections is allowed529		CantDestroyNotEmptyCollection,530		/// Collection is not in mint mode.531		PublicMintingNotAllowed,532		/// Address is not in allow list.533		AddressNotInAllowlist,534535		/// Collection name can not be longer than 63 char.536		CollectionNameLimitExceeded,537		/// Collection description can not be longer than 255 char.538		CollectionDescriptionLimitExceeded,539		/// Token prefix can not be longer than 15 char.540		CollectionTokenPrefixLimitExceeded,541		/// Total collections bound exceeded.542		TotalCollectionsLimitExceeded,543		/// Exceeded max admin count544		CollectionAdminCountExceeded,545		/// Collection limit bounds per collection exceeded546		CollectionLimitBoundsExceeded,547		/// Tried to enable permissions which are only permitted to be disabled548		OwnerPermissionsCantBeReverted,549		/// Collection settings not allowing items transferring550		TransferNotAllowed,551		/// Account token limit exceeded per collection552		AccountTokenLimitExceeded,553		/// Collection token limit exceeded554		CollectionTokenLimitExceeded,555		/// Metadata flag frozen556		MetadataFlagFrozen,557558		/// Item does not exist559		TokenNotFound,560		/// Item is balance not enough561		TokenValueTooLow,562		/// Requested value is more than the approved563		ApprovedValueTooLow,564		/// Tried to approve more than owned565		CantApproveMoreThanOwned,566567		/// Can't transfer tokens to ethereum zero address568		AddressIsZero,569570		/// The operation is not supported571		UnsupportedOperation,572573		/// Insufficient funds to perform an action574		NotSufficientFounds,575576		/// User does not satisfy the nesting rule577		UserIsNotAllowedToNest,578		/// Only tokens from specific collections may nest tokens under this one579		SourceCollectionIsNotAllowedToNest,580581		/// Tried to store more data than allowed in collection field582		CollectionFieldSizeExceeded,583584		/// Tried to store more property data than allowed585		NoSpaceForProperty,586587		/// Tried to store more property keys than allowed588		PropertyLimitReached,589590		/// Property key is too long591		PropertyKeyIsTooLong,592593		/// Only ASCII letters, digits, and symbols `_`, `-`, and `.` are allowed594		InvalidCharacterInPropertyKey,595596		/// Empty property keys are forbidden597		EmptyPropertyKey,598599		/// Tried to access an external collection with an internal API600		CollectionIsExternal,601602		/// Tried to access an internal collection with an external API603		CollectionIsInternal,604	}605606	/// Storage of the count of created collections. Essentially contains the last collection ID.607	#[pallet::storage]608	pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;609610	/// Storage of the count of deleted collections.611	#[pallet::storage]612	pub type DestroyedCollectionCount<T> =613		StorageValue<Value = CollectionId, QueryKind = ValueQuery>;614615	/// Storage of collection info.616	#[pallet::storage]617	pub type CollectionById<T> = StorageMap<618		Hasher = Blake2_128Concat,619		Key = CollectionId,620		Value = Collection<<T as frame_system::Config>::AccountId>,621		QueryKind = OptionQuery,622	>;623624	/// Storage of collection properties.625	#[pallet::storage]626	#[pallet::getter(fn collection_properties)]627	pub type CollectionProperties<T> = StorageMap<628		Hasher = Blake2_128Concat,629		Key = CollectionId,630		Value = Properties,631		QueryKind = ValueQuery,632		OnEmpty = up_data_structs::CollectionProperties,633	>;634635	/// Storage of token property permissions of a collection.636	#[pallet::storage]637	#[pallet::getter(fn property_permissions)]638	pub type CollectionPropertyPermissions<T> = StorageMap<639		Hasher = Blake2_128Concat,640		Key = CollectionId,641		Value = PropertiesPermissionMap,642		QueryKind = ValueQuery,643	>;644645	/// Storage of the amount of collection admins.646	#[pallet::storage]647	pub type AdminAmount<T> = StorageMap<648		Hasher = Blake2_128Concat,649		Key = CollectionId,650		Value = u32,651		QueryKind = ValueQuery,652	>;653654	/// List of collection admins.655	#[pallet::storage]656	pub type IsAdmin<T: Config> = StorageNMap<657		Key = (658			Key<Blake2_128Concat, CollectionId>,659			Key<Blake2_128Concat, T::CrossAccountId>,660		),661		Value = bool,662		QueryKind = ValueQuery,663	>;664665	/// Allowlisted collection users.666	#[pallet::storage]667	pub type Allowlist<T: Config> = StorageNMap<668		Key = (669			Key<Blake2_128Concat, CollectionId>,670			Key<Blake2_128Concat, T::CrossAccountId>,671		),672		Value = bool,673		QueryKind = ValueQuery,674	>;675676	/// Not used by code, exists only to provide some types to metadata.677	#[pallet::storage]678	pub type DummyStorageValue<T: Config> = StorageValue<679		Value = (680			CollectionStats,681			CollectionId,682			TokenId,683			TokenChild,684			PhantomType<(685				TokenData<T::CrossAccountId>,686				RpcCollection<T::AccountId>,687				// RMRK688				RmrkCollectionInfo<T::AccountId>,689				RmrkInstanceInfo<T::AccountId>,690				RmrkResourceInfo,691				RmrkPropertyInfo,692				RmrkBaseInfo<T::AccountId>,693				RmrkPartType,694				RmrkBoundedTheme,695				RmrkNftChild,696			)>,697		),698		QueryKind = OptionQuery,699	>;700701	#[pallet::hooks]702	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {703		fn on_runtime_upgrade() -> Weight {704			StorageVersion::new(1).put::<Pallet<T>>();705706			Weight::zero()707		}708	}709}710711impl<T: Config> Pallet<T> {712	/// Enshure that receiver address is correct.713	///714	/// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens.715	pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {716		ensure!(717			&T::CrossAccountId::from_eth(H160([0; 20])) != receiver,718			<Error<T>>::AddressIsZero719		);720		Ok(())721	}722723	/// Get a vector of collection admins.724	pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {725		<IsAdmin<T>>::iter_prefix((collection,))726			.map(|(a, _)| a)727			.collect()728	}729730	/// Get a vector of users allowed to mint tokens.731	pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {732		<Allowlist<T>>::iter_prefix((collection,))733			.map(|(a, _)| a)734			.collect()735	}736737	/// Is `user` allowed to mint token in `collection`.738	pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {739		<Allowlist<T>>::get((collection, user))740	}741742	/// Get statistics of collections.743	pub fn collection_stats() -> CollectionStats {744		let created = <CreatedCollectionCount<T>>::get();745		let destroyed = <DestroyedCollectionCount<T>>::get();746		CollectionStats {747			created: created.0,748			destroyed: destroyed.0,749			alive: created.0 - destroyed.0,750		}751	}752753	/// Get the effective limits for the collection.754	pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {755		let collection = <CollectionById<T>>::get(collection)?;756		let limits = collection.limits;757		let effective_limits = CollectionLimits {758			account_token_ownership_limit: Some(limits.account_token_ownership_limit()),759			sponsored_data_size: Some(limits.sponsored_data_size()),760			sponsored_data_rate_limit: Some(761				limits762					.sponsored_data_rate_limit763					.unwrap_or(SponsoringRateLimit::SponsoringDisabled),764			),765			token_limit: Some(limits.token_limit()),766			sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(767				match collection.mode {768					CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,769					CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,770					CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,771				},772			)),773			sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),774			owner_can_transfer: Some(limits.owner_can_transfer()),775			owner_can_destroy: Some(limits.owner_can_destroy()),776			transfers_enabled: Some(limits.transfers_enabled()),777		};778779		Some(effective_limits)780	}781782	/// Returns information about the `collection` adapted for rpc.783	pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {784		let Collection {785			name,786			description,787			owner,788			mode,789			token_prefix,790			sponsorship,791			limits,792			permissions,793			flags,794		} = <CollectionById<T>>::get(collection)?;795796		let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)797			.into_iter()798			.map(|(key, permission)| PropertyKeyPermission { key, permission })799			.collect();800801		let properties = <CollectionProperties<T>>::get(collection)802			.into_iter()803			.map(|(key, value)| Property { key, value })804			.collect();805806		let permissions = CollectionPermissions {807			access: Some(permissions.access()),808			mint_mode: Some(permissions.mint_mode()),809			nesting: Some(permissions.nesting().clone()),810		};811812		Some(RpcCollection {813			name: name.into_inner(),814			description: description.into_inner(),815			owner,816			mode,817			token_prefix: token_prefix.into_inner(),818			sponsorship,819			limits,820			permissions,821			token_property_permissions,822			properties,823			read_only: flags.external,824825			flags: RpcCollectionFlags {826				foreign: flags.foreign,827				erc721metadata: flags.erc721metadata,828			},829		})830	}831}832833macro_rules! limit_default {834	($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{835		$(836			if let Some($new) = $new.$field {837				let $old = $old.$field($($arg)?);838				let _ = $new;839				let _ = $old;840				$check841			} else {842				$new.$field = $old.$field843			}844		)*845	}};846}847macro_rules! limit_default_clone {848	($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{849		$(850			if let Some($new) = $new.$field.clone() {851				let $old = $old.$field($($arg)?);852				let _ = $new;853				let _ = $old;854				$check855			} else {856				$new.$field = $old.$field.clone()857			}858		)*859	}};860}861862impl<T: Config> Pallet<T> {863	/// Create new collection.864	///865	/// * `owner` - The owner of the collection.866	/// * `data` - Description of the created collection.867	/// * `flags` - Extra flags to store.868	pub fn init_collection(869		owner: T::CrossAccountId,870		payer: T::CrossAccountId,871		data: CreateCollectionData<T::AccountId>,872		flags: CollectionFlags,873	) -> Result<CollectionId, DispatchError> {874		{875			ensure!(876				data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,877				Error::<T>::CollectionTokenPrefixLimitExceeded878			);879		}880881		let created_count = <CreatedCollectionCount<T>>::get()882			.0883			.checked_add(1)884			.ok_or(ArithmeticError::Overflow)?;885		let destroyed_count = <DestroyedCollectionCount<T>>::get().0;886		let id = CollectionId(created_count);887888		// bound Total number of collections889		ensure!(890			created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,891			<Error<T>>::TotalCollectionsLimitExceeded892		);893894		// =========895896		let collection = Collection {897			owner: owner.as_sub().clone(),898			name: data.name,899			mode: data.mode.clone(),900			description: data.description,901			token_prefix: data.token_prefix,902			sponsorship: data903				.pending_sponsor904				.map(SponsorshipState::Unconfirmed)905				.unwrap_or_default(),906			limits: data907				.limits908				.map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))909				.unwrap_or_else(|| Ok(CollectionLimits::default()))?,910			permissions: data911				.permissions912				.map(|permissions| {913					Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)914				})915				.unwrap_or_else(|| Ok(CollectionPermissions::default()))?,916			flags,917		};918919		let mut collection_properties = up_data_structs::CollectionProperties::get();920		collection_properties921			.try_set_from_iter(data.properties.into_iter())922			.map_err(<Error<T>>::from)?;923924		CollectionProperties::<T>::insert(id, collection_properties);925926		let mut token_props_permissions = PropertiesPermissionMap::new();927		token_props_permissions928			.try_set_from_iter(data.token_property_permissions.into_iter())929			.map_err(<Error<T>>::from)?;930931		CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);932933		// Take a (non-refundable) deposit of collection creation934		{935			let mut imbalance =936				<<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();937			imbalance.subsume(938				<<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(939					&T::TreasuryAccountId::get(),940					T::CollectionCreationPrice::get(),941				),942			);943			<T as Config>::Currency::settle(944				payer.as_sub(),945				imbalance,946				WithdrawReasons::TRANSFER,947				ExistenceRequirement::KeepAlive,948			)949			.map_err(|_| Error::<T>::NotSufficientFounds)?;950		}951952		<CreatedCollectionCount<T>>::put(created_count);953		<Pallet<T>>::deposit_event(Event::CollectionCreated(954			id,955			data.mode.id(),956			owner.as_sub().clone(),957		));958		<PalletEvm<T>>::deposit_log(959			erc::CollectionHelpersEvents::CollectionCreated {960				owner: *owner.as_eth(),961				collection_id: eth::collection_id_to_address(id),962			}963			.to_log(T::ContractAddress::get()),964		);965		<CollectionById<T>>::insert(id, collection);966		Ok(id)967	}968969	/// Destroy collection.970	///971	/// * `collection` - Collection handler.972	/// * `sender` - The owner or administrator of the collection.973	pub fn destroy_collection(974		collection: CollectionHandle<T>,975		sender: &T::CrossAccountId,976	) -> DispatchResult {977		ensure!(978			collection.limits.owner_can_destroy(),979			<Error<T>>::NoPermission,980		);981		collection.check_is_owner(sender)?;982983		let destroyed_collections = <DestroyedCollectionCount<T>>::get()984			.0985			.checked_add(1)986			.ok_or(ArithmeticError::Overflow)?;987988		// =========989990		<DestroyedCollectionCount<T>>::put(destroyed_collections);991		<CollectionById<T>>::remove(collection.id);992		<AdminAmount<T>>::remove(collection.id);993		let _ = <IsAdmin<T>>::clear_prefix((collection.id,), u32::MAX, None);994		let _ = <Allowlist<T>>::clear_prefix((collection.id,), u32::MAX, None);995		<CollectionProperties<T>>::remove(collection.id);996997		<Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));998999		<PalletEvm<T>>::deposit_log(1000			erc::CollectionHelpersEvents::CollectionDestroyed {1001				collection_id: eth::collection_id_to_address(collection.id),1002			}1003			.to_log(T::ContractAddress::get()),1004		);1005		Ok(())1006	}10071008	/// Set collection property.1009	///1010	/// * `collection` - Collection handler.1011	/// * `sender` - The owner or administrator of the collection.1012	/// * `property` - The property to set.1013	pub fn set_collection_property(1014		collection: &CollectionHandle<T>,1015		sender: &T::CrossAccountId,1016		property: Property,1017	) -> DispatchResult {1018		collection.check_is_owner_or_admin(sender)?;10191020		CollectionProperties::<T>::try_mutate(collection.id, |properties| {1021			let property = property.clone();1022			properties.try_set(property.key, property.value)1023		})1024		.map_err(<Error<T>>::from)?;10251026		Self::deposit_event(Event::CollectionPropertySet(collection.id, property.key));10271028		Ok(())1029	}10301031	/// Set scouped collection property.1032	///1033	/// * `collection_id` - ID of the collection for which the property is being set.1034	/// * `scope` - Property scope.1035	/// * `property` - The property to set.1036	pub fn set_scoped_collection_property(1037		collection_id: CollectionId,1038		scope: PropertyScope,1039		property: Property,1040	) -> DispatchResult {1041		CollectionProperties::<T>::try_mutate(collection_id, |properties| {1042			properties.try_scoped_set(scope, property.key, property.value)1043		})1044		.map_err(<Error<T>>::from)?;10451046		Ok(())1047	}10481049	/// Set scouped collection properties.1050	///1051	/// * `collection_id` - ID of the collection for which the properties is being set.1052	/// * `scope` - Property scope.1053	/// * `properties` - The properties to set.1054	pub fn set_scoped_collection_properties(1055		collection_id: CollectionId,1056		scope: PropertyScope,1057		properties: impl Iterator<Item = Property>,1058	) -> DispatchResult {1059		CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {1060			stored_properties.try_scoped_set_from_iter(scope, properties)1061		})1062		.map_err(<Error<T>>::from)?;10631064		Ok(())1065	}10661067	/// Set collection properties.1068	///1069	/// * `collection` - Collection handler.1070	/// * `sender` - The owner or administrator of the collection.1071	/// * `properties` - The properties to set.1072	#[transactional]1073	pub fn set_collection_properties(1074		collection: &CollectionHandle<T>,1075		sender: &T::CrossAccountId,1076		properties: Vec<Property>,1077	) -> DispatchResult {1078		for property in properties {1079			Self::set_collection_property(collection, sender, property)?;1080		}10811082		Ok(())1083	}10841085	/// Delete collection property.1086	///1087	/// * `collection` - Collection handler.1088	/// * `sender` - The owner or administrator of the collection.1089	/// * `property` - The property to delete.1090	pub fn delete_collection_property(1091		collection: &CollectionHandle<T>,1092		sender: &T::CrossAccountId,1093		property_key: PropertyKey,1094	) -> DispatchResult {1095		collection.check_is_owner_or_admin(sender)?;10961097		CollectionProperties::<T>::try_mutate(collection.id, |properties| {1098			properties.remove(&property_key)1099		})1100		.map_err(<Error<T>>::from)?;11011102		Self::deposit_event(Event::CollectionPropertyDeleted(1103			collection.id,1104			property_key,1105		));11061107		Ok(())1108	}11091110	/// Delete collection properties.1111	///1112	/// * `collection` - Collection handler.1113	/// * `sender` - The owner or administrator of the collection.1114	/// * `properties` - The properties to delete.1115	#[transactional]1116	pub fn delete_collection_properties(1117		collection: &CollectionHandle<T>,1118		sender: &T::CrossAccountId,1119		property_keys: Vec<PropertyKey>,1120	) -> DispatchResult {1121		for key in property_keys {1122			Self::delete_collection_property(collection, sender, key)?;1123		}11241125		Ok(())1126	}11271128	/// Set collection propetry permission without any checks.1129	///1130	/// Used for migrations.1131	///1132	/// * `collection` - Collection handler.1133	/// * `property_permissions` - Property permissions.1134	pub fn set_property_permission_unchecked(1135		collection: CollectionId,1136		property_permission: PropertyKeyPermission,1137	) -> DispatchResult {1138		<CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {1139			permissions.try_set(property_permission.key, property_permission.permission)1140		})1141		.map_err(<Error<T>>::from)?;1142		Ok(())1143	}11441145	/// Set collection property permission.1146	///1147	/// * `collection` - Collection handler.1148	/// * `sender` - The owner or administrator of the collection.1149	/// * `property_permission` - Property permission.1150	pub fn set_property_permission(1151		collection: &CollectionHandle<T>,1152		sender: &T::CrossAccountId,1153		property_permission: PropertyKeyPermission,1154	) -> DispatchResult {1155		Self::set_scoped_property_permission(1156			collection,1157			sender,1158			PropertyScope::None,1159			property_permission,1160		)1161	}11621163	/// Set collection property permission with scope.1164	///1165	/// * `collection` - Collection handler.1166	/// * `sender` - The owner or administrator of the collection.1167	/// * `scope` - Property scope.1168	/// * `property_permission` - Property permission.1169	pub fn set_scoped_property_permission(1170		collection: &CollectionHandle<T>,1171		sender: &T::CrossAccountId,1172		scope: PropertyScope,1173		property_permission: PropertyKeyPermission,1174	) -> DispatchResult {1175		collection.check_is_owner_or_admin(sender)?;11761177		let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);1178		let current_permission = all_permissions.get(&property_permission.key);1179		if matches![1180			current_permission,1181			Some(PropertyPermission { mutable: false, .. })1182		] {1183			return Err(<Error<T>>::NoPermission.into());1184		}11851186		CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {1187			let property_permission = property_permission.clone();1188			permissions.try_scoped_set(1189				scope,1190				property_permission.key,1191				property_permission.permission,1192			)1193		})1194		.map_err(<Error<T>>::from)?;11951196		Self::deposit_event(Event::PropertyPermissionSet(1197			collection.id,1198			property_permission.key,1199		));12001201		Ok(())1202	}12031204	/// Set token property permission.1205	///1206	/// * `collection` - Collection handler.1207	/// * `sender` - The owner or administrator of the collection.1208	/// * `property_permissions` - Property permissions.1209	#[transactional]1210	pub fn set_token_property_permissions(1211		collection: &CollectionHandle<T>,1212		sender: &T::CrossAccountId,1213		property_permissions: Vec<PropertyKeyPermission>,1214	) -> DispatchResult {1215		Self::set_scoped_token_property_permissions(1216			collection,1217			sender,1218			PropertyScope::None,1219			property_permissions,1220		)1221	}12221223	/// Set token property permission with scope.1224	///1225	/// * `collection` - Collection handler.1226	/// * `sender` - The owner or administrator of the collection.1227	/// * `scope` - Property scope.1228	/// * `property_permissions` - Property permissions.1229	#[transactional]1230	pub fn set_scoped_token_property_permissions(1231		collection: &CollectionHandle<T>,1232		sender: &T::CrossAccountId,1233		scope: PropertyScope,1234		property_permissions: Vec<PropertyKeyPermission>,1235	) -> DispatchResult {1236		for prop_pemission in property_permissions {1237			Self::set_scoped_property_permission(collection, sender, scope, prop_pemission)?;1238		}12391240		Ok(())1241	}12421243	/// Get collection property.1244	pub fn get_collection_property(1245		collection_id: CollectionId,1246		key: &PropertyKey,1247	) -> Option<PropertyValue> {1248		Self::collection_properties(collection_id).get(key).cloned()1249	}12501251	/// Convert byte vector to property key vector.1252	pub fn bytes_keys_to_property_keys(1253		keys: Vec<Vec<u8>>,1254	) -> Result<Vec<PropertyKey>, DispatchError> {1255		keys.into_iter()1256			.map(|key| -> Result<PropertyKey, DispatchError> {1257				key.try_into()1258					.map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())1259			})1260			.collect::<Result<Vec<PropertyKey>, DispatchError>>()1261	}12621263	/// Get properties according to given keys.1264	pub fn filter_collection_properties(1265		collection_id: CollectionId,1266		keys: Option<Vec<PropertyKey>>,1267	) -> Result<Vec<Property>, DispatchError> {1268		let properties = Self::collection_properties(collection_id);12691270		let properties = keys1271			.map(|keys| {1272				keys.into_iter()1273					.filter_map(|key| {1274						properties.get(&key).map(|value| Property {1275							key,1276							value: value.clone(),1277						})1278					})1279					.collect()1280			})1281			.unwrap_or_else(|| {1282				properties1283					.into_iter()1284					.map(|(key, value)| Property { key, value })1285					.collect()1286			});12871288		Ok(properties)1289	}12901291	/// Get property permissions according to given keys.1292	pub fn filter_property_permissions(1293		collection_id: CollectionId,1294		keys: Option<Vec<PropertyKey>>,1295	) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1296		let permissions = Self::property_permissions(collection_id);12971298		let key_permissions = keys1299			.map(|keys| {1300				keys.into_iter()1301					.filter_map(|key| {1302						permissions1303							.get(&key)1304							.map(|permission| PropertyKeyPermission {1305								key,1306								permission: permission.clone(),1307							})1308					})1309					.collect()1310			})1311			.unwrap_or_else(|| {1312				permissions1313					.into_iter()1314					.map(|(key, permission)| PropertyKeyPermission { key, permission })1315					.collect()1316			});13171318		Ok(key_permissions)1319	}13201321	/// Toggle `user` participation in the `collection`'s allow list.1322	/// #### Store read/writes1323	/// 1 writes1324	pub fn toggle_allowlist(1325		collection: &CollectionHandle<T>,1326		sender: &T::CrossAccountId,1327		user: &T::CrossAccountId,1328		allowed: bool,1329	) -> DispatchResult {1330		collection.check_is_owner_or_admin(sender)?;13311332		// =========13331334		if allowed {1335			<Allowlist<T>>::insert((collection.id, user), true);1336		} else {1337			<Allowlist<T>>::remove((collection.id, user));1338		}13391340		Ok(())1341	}13421343	/// Toggle `user` participation in the `collection`'s admin list.1344	/// #### Store read/writes1345	/// 2 writes1346	pub fn toggle_admin(1347		collection: &CollectionHandle<T>,1348		sender: &T::CrossAccountId,1349		user: &T::CrossAccountId,1350		admin: bool,1351	) -> DispatchResult {1352		collection.check_is_owner(sender)?;13531354		let was_admin = <IsAdmin<T>>::get((collection.id, user));1355		if was_admin == admin {1356			return Ok(());1357		}1358		let amount = <AdminAmount<T>>::get(collection.id);13591360		if admin {1361			let amount = amount1362				.checked_add(1)1363				.ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1364			ensure!(1365				amount <= Self::collection_admins_limit(),1366				<Error<T>>::CollectionAdminCountExceeded,1367			);13681369			// =========13701371			<AdminAmount<T>>::insert(collection.id, amount);1372			<IsAdmin<T>>::insert((collection.id, user), true);1373		} else {1374			<AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1375			<IsAdmin<T>>::remove((collection.id, user));1376		}13771378		Ok(())1379	}13801381	/// Merge set fields from `new_limit` to `old_limit`.1382	pub fn clamp_limits(1383		mode: CollectionMode,1384		old_limit: &CollectionLimits,1385		mut new_limit: CollectionLimits,1386	) -> Result<CollectionLimits, DispatchError> {1387		let limits = old_limit;1388		limit_default!(old_limit, new_limit,1389			account_token_ownership_limit => ensure!(1390				new_limit <= MAX_TOKEN_OWNERSHIP,1391				<Error<T>>::CollectionLimitBoundsExceeded,1392			),1393			sponsored_data_size => ensure!(1394				new_limit <= CUSTOM_DATA_LIMIT,1395				<Error<T>>::CollectionLimitBoundsExceeded,1396			),13971398			sponsored_data_rate_limit => {},1399			token_limit => ensure!(1400				old_limit >= new_limit && new_limit > 0,1401				<Error<T>>::CollectionTokenLimitExceeded1402			),14031404			sponsor_transfer_timeout(match mode {1405				CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1406				CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1407				CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1408			}) => ensure!(1409				new_limit <= MAX_SPONSOR_TIMEOUT,1410				<Error<T>>::CollectionLimitBoundsExceeded,1411			),1412			sponsor_approve_timeout => {},1413			owner_can_transfer => ensure!(1414				!limits.owner_can_transfer_instaled() ||1415				old_limit || !new_limit,1416				<Error<T>>::OwnerPermissionsCantBeReverted,1417			),1418			owner_can_destroy => ensure!(1419				old_limit || !new_limit,1420				<Error<T>>::OwnerPermissionsCantBeReverted,1421			),1422			transfers_enabled => {},1423		);1424		Ok(new_limit)1425	}14261427	/// Merge set fields from `new_permission` to `old_permission`.1428	pub fn clamp_permissions(1429		_mode: CollectionMode,1430		old_permission: &CollectionPermissions,1431		mut new_permission: CollectionPermissions,1432	) -> Result<CollectionPermissions, DispatchError> {1433		limit_default_clone!(old_permission, new_permission,1434			access => {},1435			mint_mode => {},1436			nesting => { /* todo check for permissive, if only it gets out of benchmarks */ },1437		);1438		Ok(new_permission)1439	}1440}14411442/// Indicates unsupported methods by returning [Error::UnsupportedOperation].1443#[macro_export]1444macro_rules! unsupported {1445	($runtime:path) => {1446		Err($crate::Error::<$runtime>::UnsupportedOperation.into())1447	};1448}14491450/// Return weights for various worst-case operations.1451pub trait CommonWeightInfo<CrossAccountId> {1452	/// Weight of item creation.1453	fn create_item() -> Weight;14541455	/// Weight of items creation.1456	fn create_multiple_items(amount: &[CreateItemData]) -> Weight;14571458	/// Weight of items creation.1459	fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;14601461	/// The weight of the burning item.1462	fn burn_item() -> Weight;14631464	/// Property setting weight.1465	///1466	/// * `amount`- The number of properties to set.1467	fn set_collection_properties(amount: u32) -> Weight;14681469	/// Collection property deletion weight.1470	///1471	/// * `amount`- The number of properties to set.1472	fn delete_collection_properties(amount: u32) -> Weight;14731474	/// Token property setting weight.1475	///1476	/// * `amount`- The number of properties to set.1477	fn set_token_properties(amount: u32) -> Weight;14781479	/// Token property deletion weight.1480	///1481	/// * `amount`- The number of properties to delete.1482	fn delete_token_properties(amount: u32) -> Weight;14831484	/// Token property permissions set weight.1485	///1486	/// * `amount`- The number of property permissions to set.1487	fn set_token_property_permissions(amount: u32) -> Weight;14881489	/// Transfer price of the token or its parts.1490	fn transfer() -> Weight;14911492	/// The price of setting the permission of the operation from another user.1493	fn approve() -> Weight;14941495	/// Transfer price from another user.1496	fn transfer_from() -> Weight;14971498	/// The price of burning a token from another user.1499	fn burn_from() -> Weight;15001501	/// Differs from burn_item in case of Fungible and Refungible, as it should burn1502	/// whole users's balance.1503	///1504	/// This method shouldn't be used directly, as it doesn't count breadth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1505	fn burn_recursively_self_raw() -> Weight;15061507	/// Cost of iterating over `amount` children while burning, without counting child burning itself.1508	///1509	/// This method shouldn't be used directly, as it doesn't count depth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1510	fn burn_recursively_breadth_raw(amount: u32) -> Weight;15111512	/// The price of recursive burning a token.1513	///1514	/// `max_selfs` - The maximum burning weight of the token itself.1515	/// `max_breadth` - The maximum number of nested tokens to burn.1516	fn burn_recursively(max_selfs: u32, max_breadth: u32) -> Weight {1517		Self::burn_recursively_self_raw()1518			.saturating_mul(max_selfs.max(1) as u64)1519			.saturating_add(Self::burn_recursively_breadth_raw(max_breadth))1520	}15211522	/// The price of retrieving token owner1523	fn token_owner() -> Weight;1524}15251526/// Weight info extension trait for refungible pallet.1527pub trait RefungibleExtensionsWeightInfo {1528	/// Weight of token repartition.1529	fn repartition() -> Weight;1530}15311532/// Common collection operations.1533///1534/// It wraps methods in Fungible, Nonfungible and Refungible pallets1535/// and adds weight info.1536pub trait CommonCollectionOperations<T: Config> {1537	/// Create token.1538	///1539	/// * `sender` - The user who mint the token and pays for the transaction.1540	/// * `to` - The user who will own the token.1541	/// * `data` - Token data.1542	/// * `nesting_budget` - A budget that can be spent on nesting tokens.1543	fn create_item(1544		&self,1545		sender: T::CrossAccountId,1546		to: T::CrossAccountId,1547		data: CreateItemData,1548		nesting_budget: &dyn Budget,1549	) -> DispatchResultWithPostInfo;15501551	/// Create multiple tokens.1552	///1553	/// * `sender` - The user who mint the token and pays for the transaction.1554	/// * `to` - The user who will own the token.1555	/// * `data` - Token data.1556	/// * `nesting_budget` - A budget that can be spent on nesting tokens.1557	fn create_multiple_items(1558		&self,1559		sender: T::CrossAccountId,1560		to: T::CrossAccountId,1561		data: Vec<CreateItemData>,1562		nesting_budget: &dyn Budget,1563	) -> DispatchResultWithPostInfo;15641565	/// Create multiple tokens.1566	///1567	/// * `sender` - The user who mint the token and pays for the transaction.1568	/// * `to` - The user who will own the token.1569	/// * `data` - Token data.1570	/// * `nesting_budget` - A budget that can be spent on nesting tokens.1571	fn create_multiple_items_ex(1572		&self,1573		sender: T::CrossAccountId,1574		data: CreateItemExData<T::CrossAccountId>,1575		nesting_budget: &dyn Budget,1576	) -> DispatchResultWithPostInfo;15771578	/// Burn token.1579	///1580	/// * `sender` - The user who owns the token.1581	/// * `token` - Token id that will burned.1582	/// * `amount` - The number of parts of the token that will be burned.1583	fn burn_item(1584		&self,1585		sender: T::CrossAccountId,1586		token: TokenId,1587		amount: u128,1588	) -> DispatchResultWithPostInfo;15891590	/// Burn token and all nested tokens recursievly.1591	///1592	/// * `sender` - The user who owns the token.1593	/// * `token` - Token id that will burned.1594	/// * `self_budget` - The budget that can be spent on burning tokens.1595	/// * `breadth_budget` - The budget that can be spent on burning nested tokens.1596	fn burn_item_recursively(1597		&self,1598		sender: T::CrossAccountId,1599		token: TokenId,1600		self_budget: &dyn Budget,1601		breadth_budget: &dyn Budget,1602	) -> DispatchResultWithPostInfo;16031604	/// Set collection properties.1605	///1606	/// * `sender` - Must be either the owner of the collection or its admin.1607	/// * `properties` - Properties to be set.1608	fn set_collection_properties(1609		&self,1610		sender: T::CrossAccountId,1611		properties: Vec<Property>,1612	) -> DispatchResultWithPostInfo;16131614	/// Delete collection properties.1615	///1616	/// * `sender` - Must be either the owner of the collection or its admin.1617	/// * `properties` - The properties to be removed.1618	fn delete_collection_properties(1619		&self,1620		sender: &T::CrossAccountId,1621		property_keys: Vec<PropertyKey>,1622	) -> DispatchResultWithPostInfo;16231624	/// Set token properties.1625	///1626	/// The appropriate [`PropertyPermission`] for the token property1627	/// must be set with [`Self::set_token_property_permissions`].1628	///1629	/// * `sender` - Must be either the owner of the token or its admin.1630	/// * `token_id` - The token for which the properties are being set.1631	/// * `properties` - Properties to be set.1632	/// * `budget` - Budget for setting properties.1633	fn set_token_properties(1634		&self,1635		sender: T::CrossAccountId,1636		token_id: TokenId,1637		properties: Vec<Property>,1638		budget: &dyn Budget,1639	) -> DispatchResultWithPostInfo;16401641	/// Remove token properties.1642	///1643	/// The appropriate [`PropertyPermission`] for the token property1644	/// must be set with [`Self::set_token_property_permissions`].1645	///1646	/// * `sender` - Must be either the owner of the token or its admin.1647	/// * `token_id` - The token for which the properties are being remove.1648	/// * `property_keys` - Keys to remove corresponding properties.1649	/// * `budget` - Budget for removing properties.1650	fn delete_token_properties(1651		&self,1652		sender: T::CrossAccountId,1653		token_id: TokenId,1654		property_keys: Vec<PropertyKey>,1655		budget: &dyn Budget,1656	) -> DispatchResultWithPostInfo;16571658	/// Set token property permissions.1659	///1660	/// * `sender` - Must be either the owner of the token or its admin.1661	/// * `token_id` - The token for which the properties are being set.1662	/// * `property_permissions` - Property permissions to be set.1663	/// * `budget` - Budget for setting properties.1664	fn set_token_property_permissions(1665		&self,1666		sender: &T::CrossAccountId,1667		property_permissions: Vec<PropertyKeyPermission>,1668	) -> DispatchResultWithPostInfo;16691670	/// Transfer amount of token pieces.1671	///1672	/// * `sender` - Donor user.1673	/// * `to` - Recepient user.1674	/// * `token` - The token of which parts are being sent.1675	/// * `amount` - The number of parts of the token that will be transferred.1676	/// * `budget` - The maximum budget that can be spent on the transfer.1677	fn transfer(1678		&self,1679		sender: T::CrossAccountId,1680		to: T::CrossAccountId,1681		token: TokenId,1682		amount: u128,1683		budget: &dyn Budget,1684	) -> DispatchResultWithPostInfo;16851686	/// Grant access to another account to transfer parts of the token owned by the calling user via [Self::transfer_from].1687	///1688	/// * `sender` - The user who grants access to the token.1689	/// * `spender` - The user to whom the rights are granted.1690	/// * `token` - The token to which access is granted.1691	/// * `amount` - The amount of pieces that another user can dispose of.1692	fn approve(1693		&self,1694		sender: T::CrossAccountId,1695		spender: T::CrossAccountId,1696		token: TokenId,1697		amount: u128,1698	) -> DispatchResultWithPostInfo;16991700	/// Send parts of a token owned by another user.1701	///1702	/// Before calling this method, you must grant rights to the calling user via [`Self::approve`].1703	///1704	/// * `sender` - The user who must have access to the token (see [`Self::approve`]).1705	/// * `from` - The user who owns the token.1706	/// * `to` - Recepient user.1707	/// * `token` - The token of which parts are being sent.1708	/// * `amount` - The number of parts of the token that will be transferred.1709	/// * `budget` - The maximum budget that can be spent on the transfer.1710	fn transfer_from(1711		&self,1712		sender: T::CrossAccountId,1713		from: T::CrossAccountId,1714		to: T::CrossAccountId,1715		token: TokenId,1716		amount: u128,1717		budget: &dyn Budget,1718	) -> DispatchResultWithPostInfo;17191720	/// Burn parts of a token owned by another user.1721	///1722	/// Before calling this method, you must grant rights to the calling user via [`Self::approve`].1723	///1724	/// * `sender` - The user who must have access to the token (see [`Self::approve`]).1725	/// * `from` - The user who owns the token.1726	/// * `token` - The token of which parts are being sent.1727	/// * `amount` - The number of parts of the token that will be transferred.1728	/// * `budget` - The maximum budget that can be spent on the burn.1729	fn burn_from(1730		&self,1731		sender: T::CrossAccountId,1732		from: T::CrossAccountId,1733		token: TokenId,1734		amount: u128,1735		budget: &dyn Budget,1736	) -> DispatchResultWithPostInfo;17371738	/// Check permission to nest token.1739	///1740	/// * `sender` - The user who initiated the check.1741	/// * `from` - The token that is checked for embedding.1742	/// * `under` - Token under which to check.1743	/// * `budget` - The maximum budget that can be spent on the check.1744	fn check_nesting(1745		&self,1746		sender: T::CrossAccountId,1747		from: (CollectionId, TokenId),1748		under: TokenId,1749		budget: &dyn Budget,1750	) -> DispatchResult;17511752	/// Nest one token into another.1753	///1754	/// * `under` - Token holder.1755	/// * `to_nest` - Nested token.1756	fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));17571758	/// Unnest token.1759	///1760	/// * `under` - Token holder.1761	/// * `to_nest` - Token to unnest.1762	fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));17631764	/// Get all user tokens.1765	///1766	/// * `account` - Account for which you need to get tokens.1767	fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;17681769	/// Get all the tokens in the collection.1770	fn collection_tokens(&self) -> Vec<TokenId>;17711772	/// Check if the token exists.1773	///1774	/// * `token` - Id token to check.1775	fn token_exists(&self, token: TokenId) -> bool;17761777	/// Get the id of the last minted token.1778	fn last_token_id(&self) -> TokenId;17791780	/// Get the owner of the token.1781	///1782	/// * `token` - The token for which you need to find out the owner.1783	fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId>;17841785	/// Returns 10 tokens owners in no particular order.1786	///1787	/// * `token` - The token for which you need to find out the owners.1788	fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId>;17891790	/// Get the value of the token property by key.1791	///1792	/// * `token` - Token with the property to get.1793	/// * `key` - Property name.1794	fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;17951796	/// Get a set of token properties by key vector.1797	///1798	/// * `token` - Token with the property to get.1799	/// * `keys` - Vector of property keys. If this parameter is [None](sp_std::result::Result),1800	/// then all properties are returned.1801	fn token_properties(&self, token: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;18021803	/// Amount of unique collection tokens1804	fn total_supply(&self) -> u32;18051806	/// Amount of different tokens account has.1807	///1808	/// * `account` - The account for which need to get the balance.1809	fn account_balance(&self, account: T::CrossAccountId) -> u32;18101811	/// Amount of specific token account have.1812	fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;18131814	/// Amount of token pieces1815	fn total_pieces(&self, token: TokenId) -> Option<u128>;18161817	/// Get the number of parts of the token that a trusted user can manage.1818	///1819	/// * `sender` - Trusted user.1820	/// * `spender` - Owner of the token.1821	/// * `token` - The token for which to get the value.1822	fn allowance(1823		&self,1824		sender: T::CrossAccountId,1825		spender: T::CrossAccountId,1826		token: TokenId,1827	) -> u128;18281829	/// Get extension for RFT collection.1830	fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>>;1831}18321833/// Extension for RFT collection.1834pub trait RefungibleExtensions<T>1835where1836	T: Config,1837{1838	/// Change the number of parts of the token.1839	///1840	/// When the value changes down, this function is equivalent to burning parts of the token.1841	///1842	/// * `sender` - The user calling the repartition operation. Must be the owner of the token.1843	/// * `token` - The token for which you want to change the number of parts.1844	/// * `amount` - The new value of the parts of the token.1845	fn repartition(1846		&self,1847		sender: &T::CrossAccountId,1848		token: TokenId,1849		amount: u128,1850	) -> DispatchResultWithPostInfo;1851}18521853/// Merge [`DispatchResult`] with [`Weight`] into [`DispatchResultWithPostInfo`].1854///1855/// Used for [`CommonCollectionOperations`] implementations and flexible enough to do so.1856pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {1857	let post_info = PostDispatchInfo {1858		actual_weight: Some(weight),1859		pays_fee: Pays::Yes,1860	};1861	match res {1862		Ok(()) => Ok(post_info),1863		Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),1864	}1865}18661867impl<T: Config> From<PropertiesError> for Error<T> {1868	fn from(error: PropertiesError) -> Self {1869		match error {1870			PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,1871			PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,1872			PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,1873			PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,1874			PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,1875		}1876	}1877}
after · pallets/common/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//! # Common pallet18//!19//! The Common pallet provides functionality for handling collections.20//!21//! ## Overview22//!23//! The Common pallet provides an interface for common collection operations for different collection types24//! (see [CommonCollectionOperations]), as well as a generic dispatcher for these, see [dispatch] module.25//! It also provides this functionality to EVM, see [erc] and [eth] modules.26//!27//! The Common pallet provides functions for:28//!29//! - Setting and approving collection sponsor.30//! - Get\set\delete allow list.31//! - Get\set\delete collection properties.32//! - Get\set\delete collection property permissions.33//! - Get\set\delete token property permissions.34//! - Get\set\delete collection administrators.35//! - Checking access permissions.36//!37//! ### Terminology38//! **Collection sponsor** - For the collection, you can set a sponsor, at whose expense it will39//! be possible to mint tokens.40//!41//! **Allow list** - List of users who have the right to minting tokens.42//!43//! **Collection properties** - Collection properties are simply key-value stores where various44//! metadata can be placed.45//!46//! **Permissions on token properties** - For each property in the token can be set permission47//! to change, see [`PropertyPermission`].48//!49//! **Collection administrator** - For a collection, you can set administrators who have the right50//! to most actions on the collection.5152#![warn(missing_docs)]53#![cfg_attr(not(feature = "std"), no_std)]54extern crate alloc;5556use core::ops::{Deref, DerefMut};57use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};58use sp_std::vec::Vec;59use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};60use evm_coder::ToLog;61use frame_support::{62	dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},63	ensure,64	traits::{Imbalance, Get, Currency, WithdrawReasons, ExistenceRequirement},65	dispatch::Pays,66	transactional,67};68use pallet_evm::GasWeightMapping;69use up_data_structs::{70	COLLECTION_NUMBER_LIMIT,71	Collection,72	RpcCollection,73	CollectionFlags,74	RpcCollectionFlags,75	CollectionId,76	CreateItemData,77	MAX_TOKEN_PREFIX_LENGTH,78	COLLECTION_ADMINS_LIMIT,79	TokenId,80	TokenChild,81	CollectionStats,82	MAX_TOKEN_OWNERSHIP,83	CollectionMode,84	NFT_SPONSOR_TRANSFER_TIMEOUT,85	FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,86	REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,87	MAX_SPONSOR_TIMEOUT,88	CUSTOM_DATA_LIMIT,89	CollectionLimits,90	CreateCollectionData,91	SponsorshipState,92	CreateItemExData,93	SponsoringRateLimit,94	budget::Budget,95	PhantomType,96	Property,97	Properties,98	PropertiesPermissionMap,99	PropertyKey,100	PropertyValue,101	PropertyPermission,102	PropertiesError,103	PropertyKeyPermission,104	TokenData,105	TrySetProperty,106	PropertyScope,107	// RMRK108	RmrkCollectionInfo,109	RmrkInstanceInfo,110	RmrkResourceInfo,111	RmrkPropertyInfo,112	RmrkBaseInfo,113	RmrkPartType,114	RmrkBoundedTheme,115	RmrkNftChild,116	CollectionPermissions,117};118119pub use pallet::*;120use sp_core::H160;121use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};122#[cfg(feature = "runtime-benchmarks")]123pub mod benchmarking;124pub mod dispatch;125pub mod erc;126pub mod eth;127pub mod weights;128129/// Weight info.130pub type SelfWeightOf<T> = <T as Config>::WeightInfo;131132/// Collection handle contains information about collection data and id.133/// Also provides functionality to count consumed gas.134///135/// CollectionHandle is used as a generic wrapper for collections of all types.136/// It allows to perform common operations and queries on any collection type,137/// both completely general for all, as well as their respective implementations of [`CommonCollectionOperations`].138#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]139pub struct CollectionHandle<T: Config> {140	/// Collection id141	pub id: CollectionId,142	collection: Collection<T::AccountId>,143	/// Substrate recorder for counting consumed gas144	pub recorder: SubstrateRecorder<T>,145}146147impl<T: Config> WithRecorder<T> for CollectionHandle<T> {148	fn recorder(&self) -> &SubstrateRecorder<T> {149		&self.recorder150	}151	fn into_recorder(self) -> SubstrateRecorder<T> {152		self.recorder153	}154}155156impl<T: Config> CollectionHandle<T> {157	/// Same as [CollectionHandle::new] but with an explicit gas limit.158	pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {159		<CollectionById<T>>::get(id).map(|collection| Self {160			id,161			collection,162			recorder: SubstrateRecorder::new(gas_limit),163		})164	}165166	/// Same as [CollectionHandle::new] but with an existed [`SubstrateRecorder`].167	pub fn new_with_recorder(id: CollectionId, recorder: SubstrateRecorder<T>) -> Option<Self> {168		<CollectionById<T>>::get(id).map(|collection| Self {169			id,170			collection,171			recorder,172		})173	}174175	/// Retrives collection data from storage and creates collection handle with default parameters.176	/// If collection not found return `None`177	pub fn new(id: CollectionId) -> Option<Self> {178		Self::new_with_gas_limit(id, u64::MAX)179	}180181	/// Same as [`CollectionHandle::new`] but if collection not found [CollectionNotFound](Error::CollectionNotFound) returned.182	pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {183		Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)184	}185186	/// Consume gas for reading.187	pub fn consume_store_reads(&self, reads: u64) -> evm_coder::execution::Result<()> {188		self.recorder189			.consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(190				<T as frame_system::Config>::DbWeight::get()191					.read192					.saturating_mul(reads),193			)))194	}195196	/// Consume gas for writing.197	pub fn consume_store_writes(&self, writes: u64) -> evm_coder::execution::Result<()> {198		self.recorder199			.consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(200				<T as frame_system::Config>::DbWeight::get()201					.write202					.saturating_mul(writes),203			)))204	}205206	/// Consume gas for reading and writing.207	pub fn consume_store_reads_and_writes(208		&self,209		reads: u64,210		writes: u64,211	) -> evm_coder::execution::Result<()> {212		let weight = <T as frame_system::Config>::DbWeight::get();213		let reads = weight.read.saturating_mul(reads);214		let writes = weight.read.saturating_mul(writes);215		self.recorder216			.consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(217				reads.saturating_add(writes),218			)))219	}220221	/// Save collection to storage.222	pub fn save(&self) -> DispatchResult {223		<CollectionById<T>>::insert(self.id, &self.collection);224		Ok(())225	}226227	/// Set collection sponsor.228	///229	/// Unique collections allows sponsoring for certain actions.230	/// This method allows you to set the sponsor of the collection.231	/// In order for sponsorship to become active, it must be confirmed through [`Self::confirm_sponsorship`].232	pub fn set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {233		self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor);234		Ok(())235	}236237	/// Confirm sponsorship238	///239	/// In order for the sponsorship to become active, the user set as the sponsor must confirm their participation.240	/// Before confirming sponsorship, the user must be specified as the sponsor of the collection via [`Self::set_sponsor`].241	pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> Result<bool, DispatchError> {242		if self.collection.sponsorship.pending_sponsor() != Some(sender) {243			return Ok(false);244		}245246		self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());247		Ok(true)248	}249250	/// Remove collection sponsor.251	pub fn remove_sponsor(&mut self) -> DispatchResult {252		self.collection.sponsorship = SponsorshipState::Disabled;253		Ok(())254	}255256	/// Checks that the collection was created with, and must be operated upon through **Unique API**.257	/// Now check only the `external` flag and if it's **true**, then return [`Error::CollectionIsExternal`] error.258	pub fn check_is_internal(&self) -> DispatchResult {259		if self.flags.external {260			return Err(<Error<T>>::CollectionIsExternal)?;261		}262263		Ok(())264	}265266	/// Checks that the collection was created with, and must be operated upon through an **assimilated API**.267	/// Now check only the `external` flag and if it's **false**, then return [`Error::CollectionIsInternal`] error.268	pub fn check_is_external(&self) -> DispatchResult {269		if !self.flags.external {270			return Err(<Error<T>>::CollectionIsInternal)?;271		}272273		Ok(())274	}275}276277impl<T: Config> Deref for CollectionHandle<T> {278	type Target = Collection<T::AccountId>;279280	fn deref(&self) -> &Self::Target {281		&self.collection282	}283}284285impl<T: Config> DerefMut for CollectionHandle<T> {286	fn deref_mut(&mut self) -> &mut Self::Target {287		&mut self.collection288	}289}290291impl<T: Config> CollectionHandle<T> {292	/// Checks if the `user` is the owner of the collection.293	pub fn check_is_owner(&self, user: &T::CrossAccountId) -> DispatchResult {294		ensure!(*user.as_sub() == self.owner, <Error<T>>::NoPermission);295		Ok(())296	}297298	/// Returns **true** if the `user` is the owner or administrator of the collection.299	pub fn is_owner_or_admin(&self, user: &T::CrossAccountId) -> bool {300		*user.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, user))301	}302303	/// Checks if the `user` is the owner or administrator of the collection.304	pub fn check_is_owner_or_admin(&self, user: &T::CrossAccountId) -> DispatchResult {305		ensure!(self.is_owner_or_admin(user), <Error<T>>::NoPermission);306		Ok(())307	}308309	/// Return **true** if `user` was not allowed to have tokens, and he can ignore such restrictions.310	pub fn ignores_allowance(&self, user: &T::CrossAccountId) -> bool {311		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)312	}313314	/// Return **true** if `user` does not have enough token parts, and he can ignore such restrictions.315	pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {316		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)317	}318319	/// Checks if the user is in the allow list. If not [Error::AddressNotInAllowlist] returns.320	pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {321		ensure!(322			<Allowlist<T>>::get((self.id, user)),323			<Error<T>>::AddressNotInAllowlist324		);325		Ok(())326	}327328	/// Changes collection owner to another account329	/// #### Store read/writes330	/// 1 writes331	fn set_owner_internal(332		&mut self,333		caller: T::CrossAccountId,334		new_owner: T::CrossAccountId,335	) -> DispatchResult {336		self.check_is_owner(&caller)?;337		self.collection.owner = new_owner.as_sub().clone();338		self.save()339	}340}341342#[frame_support::pallet]343pub mod pallet {344	use super::*;345	use dispatch::CollectionDispatch;346	use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};347	use frame_system::pallet_prelude::*;348	use frame_support::traits::Currency;349	use up_data_structs::{TokenId, mapping::TokenAddressMapping};350	use scale_info::TypeInfo;351	use weights::WeightInfo;352353	#[pallet::config]354	pub trait Config:355		frame_system::Config + pallet_evm_coder_substrate::Config + pallet_evm::Config + TypeInfo356	{357		/// Weight information for functions of this pallet.358		type WeightInfo: WeightInfo;359360		/// Events compatible with [`frame_system::Config::Event`].361		type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;362363		/// Handler of accounts and payment.364		type Currency: Currency<Self::AccountId>;365366		/// Set price to create a collection.367		#[pallet::constant]368		type CollectionCreationPrice: Get<369			<<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,370		>;371372		/// Dispatcher of operations on collections.373		type CollectionDispatch: CollectionDispatch<Self>;374375		/// Account which holds the chain's treasury.376		type TreasuryAccountId: Get<Self::AccountId>;377378		/// Address under which the CollectionHelper contract would be available.379		#[pallet::constant]380		type ContractAddress: Get<H160>;381382		/// Mapper for token addresses to Ethereum addresses.383		type EvmTokenAddressMapping: TokenAddressMapping<H160>;384385		/// Mapper for token addresses to [`CrossAccountId`].386		type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;387	}388389	const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);390391	#[pallet::pallet]392	#[pallet::storage_version(STORAGE_VERSION)]393	#[pallet::generate_store(pub(super) trait Store)]394	pub struct Pallet<T>(_);395396	#[pallet::extra_constants]397	impl<T: Config> Pallet<T> {398		/// Maximum admins per collection.399		pub fn collection_admins_limit() -> u32 {400			COLLECTION_ADMINS_LIMIT401		}402	}403404	#[pallet::event]405	#[pallet::generate_deposit(pub fn deposit_event)]406	pub enum Event<T: Config> {407		/// New collection was created408		CollectionCreated(409			/// Globally unique identifier of newly created collection.410			CollectionId,411			/// [`CollectionMode`] converted into _u8_.412			u8,413			/// Collection owner.414			T::AccountId,415		),416417		/// New collection was destroyed418		CollectionDestroyed(419			/// Globally unique identifier of collection.420			CollectionId,421		),422423		/// New item was created.424		ItemCreated(425			/// Id of the collection where item was created.426			CollectionId,427			/// Id of an item. Unique within the collection.428			TokenId,429			/// Owner of newly created item430			T::CrossAccountId,431			/// Always 1 for NFT432			u128,433		),434435		/// Collection item was burned.436		ItemDestroyed(437			/// Id of the collection where item was destroyed.438			CollectionId,439			/// Identifier of burned NFT.440			TokenId,441			/// Which user has destroyed its tokens.442			T::CrossAccountId,443			/// Amount of token pieces destroed. Always 1 for NFT.444			u128,445		),446447		/// Item was transferred448		Transfer(449			/// Id of collection to which item is belong.450			CollectionId,451			/// Id of an item.452			TokenId,453			/// Original owner of item.454			T::CrossAccountId,455			/// New owner of item.456			T::CrossAccountId,457			/// Amount of token pieces transfered. Always 1 for NFT.458			u128,459		),460461		/// Amount pieces of token owned by `sender` was approved for `spender`.462		Approved(463			/// Id of collection to which item is belong.464			CollectionId,465			/// Id of an item.466			TokenId,467			/// Original owner of item.468			T::CrossAccountId,469			/// Id for which the approval was granted.470			T::CrossAccountId,471			/// Amount of token pieces transfered. Always 1 for NFT.472			u128,473		),474475		/// Amount pieces of token owned by `sender` was approved for `spender`.476		ApprovedForAll(477			/// Id of collection to which item is belong.478			CollectionId,479			/// Owner of a wallet.480			T::CrossAccountId,481			/// Id for which operator status was granted or rewoked.482			T::CrossAccountId,483			/// Is operator status was granted or rewoked.484			bool,485		),486487		/// The colletion property has been added or edited.488		CollectionPropertySet(489			/// Id of collection to which property has been set.490			CollectionId,491			/// The property that was set.492			PropertyKey,493		),494495		/// The property has been deleted.496		CollectionPropertyDeleted(497			/// Id of collection to which property has been deleted.498			CollectionId,499			/// The property that was deleted.500			PropertyKey,501		),502503		/// The token property has been added or edited.504		TokenPropertySet(505			/// Identifier of the collection whose token has the property set.506			CollectionId,507			/// The token for which the property was set.508			TokenId,509			/// The property that was set.510			PropertyKey,511		),512513		/// The token property has been deleted.514		TokenPropertyDeleted(515			/// Identifier of the collection whose token has the property deleted.516			CollectionId,517			/// The token for which the property was deleted.518			TokenId,519			/// The property that was deleted.520			PropertyKey,521		),522523		/// The token property permission of a collection has been set.524		PropertyPermissionSet(525			/// ID of collection to which property permission has been set.526			CollectionId,527			/// The property permission that was set.528			PropertyKey,529		),530	}531532	#[pallet::error]533	pub enum Error<T> {534		/// This collection does not exist.535		CollectionNotFound,536		/// Sender parameter and item owner must be equal.537		MustBeTokenOwner,538		/// No permission to perform action539		NoPermission,540		/// Destroying only empty collections is allowed541		CantDestroyNotEmptyCollection,542		/// Collection is not in mint mode.543		PublicMintingNotAllowed,544		/// Address is not in allow list.545		AddressNotInAllowlist,546547		/// Collection name can not be longer than 63 char.548		CollectionNameLimitExceeded,549		/// Collection description can not be longer than 255 char.550		CollectionDescriptionLimitExceeded,551		/// Token prefix can not be longer than 15 char.552		CollectionTokenPrefixLimitExceeded,553		/// Total collections bound exceeded.554		TotalCollectionsLimitExceeded,555		/// Exceeded max admin count556		CollectionAdminCountExceeded,557		/// Collection limit bounds per collection exceeded558		CollectionLimitBoundsExceeded,559		/// Tried to enable permissions which are only permitted to be disabled560		OwnerPermissionsCantBeReverted,561		/// Collection settings not allowing items transferring562		TransferNotAllowed,563		/// Account token limit exceeded per collection564		AccountTokenLimitExceeded,565		/// Collection token limit exceeded566		CollectionTokenLimitExceeded,567		/// Metadata flag frozen568		MetadataFlagFrozen,569570		/// Item does not exist571		TokenNotFound,572		/// Item is balance not enough573		TokenValueTooLow,574		/// Requested value is more than the approved575		ApprovedValueTooLow,576		/// Tried to approve more than owned577		CantApproveMoreThanOwned,578579		/// Can't transfer tokens to ethereum zero address580		AddressIsZero,581582		/// The operation is not supported583		UnsupportedOperation,584585		/// Insufficient funds to perform an action586		NotSufficientFounds,587588		/// User does not satisfy the nesting rule589		UserIsNotAllowedToNest,590		/// Only tokens from specific collections may nest tokens under this one591		SourceCollectionIsNotAllowedToNest,592593		/// Tried to store more data than allowed in collection field594		CollectionFieldSizeExceeded,595596		/// Tried to store more property data than allowed597		NoSpaceForProperty,598599		/// Tried to store more property keys than allowed600		PropertyLimitReached,601602		/// Property key is too long603		PropertyKeyIsTooLong,604605		/// Only ASCII letters, digits, and symbols `_`, `-`, and `.` are allowed606		InvalidCharacterInPropertyKey,607608		/// Empty property keys are forbidden609		EmptyPropertyKey,610611		/// Tried to access an external collection with an internal API612		CollectionIsExternal,613614		/// Tried to access an internal collection with an external API615		CollectionIsInternal,616	}617618	/// Storage of the count of created collections. Essentially contains the last collection ID.619	#[pallet::storage]620	pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;621622	/// Storage of the count of deleted collections.623	#[pallet::storage]624	pub type DestroyedCollectionCount<T> =625		StorageValue<Value = CollectionId, QueryKind = ValueQuery>;626627	/// Storage of collection info.628	#[pallet::storage]629	pub type CollectionById<T> = StorageMap<630		Hasher = Blake2_128Concat,631		Key = CollectionId,632		Value = Collection<<T as frame_system::Config>::AccountId>,633		QueryKind = OptionQuery,634	>;635636	/// Storage of collection properties.637	#[pallet::storage]638	#[pallet::getter(fn collection_properties)]639	pub type CollectionProperties<T> = StorageMap<640		Hasher = Blake2_128Concat,641		Key = CollectionId,642		Value = Properties,643		QueryKind = ValueQuery,644		OnEmpty = up_data_structs::CollectionProperties,645	>;646647	/// Storage of token property permissions of a collection.648	#[pallet::storage]649	#[pallet::getter(fn property_permissions)]650	pub type CollectionPropertyPermissions<T> = StorageMap<651		Hasher = Blake2_128Concat,652		Key = CollectionId,653		Value = PropertiesPermissionMap,654		QueryKind = ValueQuery,655	>;656657	/// Storage of the amount of collection admins.658	#[pallet::storage]659	pub type AdminAmount<T> = StorageMap<660		Hasher = Blake2_128Concat,661		Key = CollectionId,662		Value = u32,663		QueryKind = ValueQuery,664	>;665666	/// List of collection admins.667	#[pallet::storage]668	pub type IsAdmin<T: Config> = StorageNMap<669		Key = (670			Key<Blake2_128Concat, CollectionId>,671			Key<Blake2_128Concat, T::CrossAccountId>,672		),673		Value = bool,674		QueryKind = ValueQuery,675	>;676677	/// Allowlisted collection users.678	#[pallet::storage]679	pub type Allowlist<T: Config> = StorageNMap<680		Key = (681			Key<Blake2_128Concat, CollectionId>,682			Key<Blake2_128Concat, T::CrossAccountId>,683		),684		Value = bool,685		QueryKind = ValueQuery,686	>;687688	/// Not used by code, exists only to provide some types to metadata.689	#[pallet::storage]690	pub type DummyStorageValue<T: Config> = StorageValue<691		Value = (692			CollectionStats,693			CollectionId,694			TokenId,695			TokenChild,696			PhantomType<(697				TokenData<T::CrossAccountId>,698				RpcCollection<T::AccountId>,699				// RMRK700				RmrkCollectionInfo<T::AccountId>,701				RmrkInstanceInfo<T::AccountId>,702				RmrkResourceInfo,703				RmrkPropertyInfo,704				RmrkBaseInfo<T::AccountId>,705				RmrkPartType,706				RmrkBoundedTheme,707				RmrkNftChild,708			)>,709		),710		QueryKind = OptionQuery,711	>;712713	#[pallet::hooks]714	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {715		fn on_runtime_upgrade() -> Weight {716			StorageVersion::new(1).put::<Pallet<T>>();717718			Weight::zero()719		}720	}721}722723impl<T: Config> Pallet<T> {724	/// Enshure that receiver address is correct.725	///726	/// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens.727	pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {728		ensure!(729			&T::CrossAccountId::from_eth(H160([0; 20])) != receiver,730			<Error<T>>::AddressIsZero731		);732		Ok(())733	}734735	/// Get a vector of collection admins.736	pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {737		<IsAdmin<T>>::iter_prefix((collection,))738			.map(|(a, _)| a)739			.collect()740	}741742	/// Get a vector of users allowed to mint tokens.743	pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {744		<Allowlist<T>>::iter_prefix((collection,))745			.map(|(a, _)| a)746			.collect()747	}748749	/// Is `user` allowed to mint token in `collection`.750	pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {751		<Allowlist<T>>::get((collection, user))752	}753754	/// Get statistics of collections.755	pub fn collection_stats() -> CollectionStats {756		let created = <CreatedCollectionCount<T>>::get();757		let destroyed = <DestroyedCollectionCount<T>>::get();758		CollectionStats {759			created: created.0,760			destroyed: destroyed.0,761			alive: created.0 - destroyed.0,762		}763	}764765	/// Get the effective limits for the collection.766	pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {767		let collection = <CollectionById<T>>::get(collection)?;768		let limits = collection.limits;769		let effective_limits = CollectionLimits {770			account_token_ownership_limit: Some(limits.account_token_ownership_limit()),771			sponsored_data_size: Some(limits.sponsored_data_size()),772			sponsored_data_rate_limit: Some(773				limits774					.sponsored_data_rate_limit775					.unwrap_or(SponsoringRateLimit::SponsoringDisabled),776			),777			token_limit: Some(limits.token_limit()),778			sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(779				match collection.mode {780					CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,781					CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,782					CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,783				},784			)),785			sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),786			owner_can_transfer: Some(limits.owner_can_transfer()),787			owner_can_destroy: Some(limits.owner_can_destroy()),788			transfers_enabled: Some(limits.transfers_enabled()),789		};790791		Some(effective_limits)792	}793794	/// Returns information about the `collection` adapted for rpc.795	pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {796		let Collection {797			name,798			description,799			owner,800			mode,801			token_prefix,802			sponsorship,803			limits,804			permissions,805			flags,806		} = <CollectionById<T>>::get(collection)?;807808		let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)809			.into_iter()810			.map(|(key, permission)| PropertyKeyPermission { key, permission })811			.collect();812813		let properties = <CollectionProperties<T>>::get(collection)814			.into_iter()815			.map(|(key, value)| Property { key, value })816			.collect();817818		let permissions = CollectionPermissions {819			access: Some(permissions.access()),820			mint_mode: Some(permissions.mint_mode()),821			nesting: Some(permissions.nesting().clone()),822		};823824		Some(RpcCollection {825			name: name.into_inner(),826			description: description.into_inner(),827			owner,828			mode,829			token_prefix: token_prefix.into_inner(),830			sponsorship,831			limits,832			permissions,833			token_property_permissions,834			properties,835			read_only: flags.external,836837			flags: RpcCollectionFlags {838				foreign: flags.foreign,839				erc721metadata: flags.erc721metadata,840			},841		})842	}843}844845macro_rules! limit_default {846	($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{847		$(848			if let Some($new) = $new.$field {849				let $old = $old.$field($($arg)?);850				let _ = $new;851				let _ = $old;852				$check853			} else {854				$new.$field = $old.$field855			}856		)*857	}};858}859macro_rules! limit_default_clone {860	($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{861		$(862			if let Some($new) = $new.$field.clone() {863				let $old = $old.$field($($arg)?);864				let _ = $new;865				let _ = $old;866				$check867			} else {868				$new.$field = $old.$field.clone()869			}870		)*871	}};872}873874impl<T: Config> Pallet<T> {875	/// Create new collection.876	///877	/// * `owner` - The owner of the collection.878	/// * `data` - Description of the created collection.879	/// * `flags` - Extra flags to store.880	pub fn init_collection(881		owner: T::CrossAccountId,882		payer: T::CrossAccountId,883		data: CreateCollectionData<T::AccountId>,884		flags: CollectionFlags,885	) -> Result<CollectionId, DispatchError> {886		{887			ensure!(888				data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,889				Error::<T>::CollectionTokenPrefixLimitExceeded890			);891		}892893		let created_count = <CreatedCollectionCount<T>>::get()894			.0895			.checked_add(1)896			.ok_or(ArithmeticError::Overflow)?;897		let destroyed_count = <DestroyedCollectionCount<T>>::get().0;898		let id = CollectionId(created_count);899900		// bound Total number of collections901		ensure!(902			created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,903			<Error<T>>::TotalCollectionsLimitExceeded904		);905906		// =========907908		let collection = Collection {909			owner: owner.as_sub().clone(),910			name: data.name,911			mode: data.mode.clone(),912			description: data.description,913			token_prefix: data.token_prefix,914			sponsorship: data915				.pending_sponsor916				.map(SponsorshipState::Unconfirmed)917				.unwrap_or_default(),918			limits: data919				.limits920				.map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))921				.unwrap_or_else(|| Ok(CollectionLimits::default()))?,922			permissions: data923				.permissions924				.map(|permissions| {925					Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)926				})927				.unwrap_or_else(|| Ok(CollectionPermissions::default()))?,928			flags,929		};930931		let mut collection_properties = up_data_structs::CollectionProperties::get();932		collection_properties933			.try_set_from_iter(data.properties.into_iter())934			.map_err(<Error<T>>::from)?;935936		CollectionProperties::<T>::insert(id, collection_properties);937938		let mut token_props_permissions = PropertiesPermissionMap::new();939		token_props_permissions940			.try_set_from_iter(data.token_property_permissions.into_iter())941			.map_err(<Error<T>>::from)?;942943		CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);944945		// Take a (non-refundable) deposit of collection creation946		{947			let mut imbalance =948				<<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();949			imbalance.subsume(950				<<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(951					&T::TreasuryAccountId::get(),952					T::CollectionCreationPrice::get(),953				),954			);955			<T as Config>::Currency::settle(956				payer.as_sub(),957				imbalance,958				WithdrawReasons::TRANSFER,959				ExistenceRequirement::KeepAlive,960			)961			.map_err(|_| Error::<T>::NotSufficientFounds)?;962		}963964		<CreatedCollectionCount<T>>::put(created_count);965		<Pallet<T>>::deposit_event(Event::CollectionCreated(966			id,967			data.mode.id(),968			owner.as_sub().clone(),969		));970		<PalletEvm<T>>::deposit_log(971			erc::CollectionHelpersEvents::CollectionCreated {972				owner: *owner.as_eth(),973				collection_id: eth::collection_id_to_address(id),974			}975			.to_log(T::ContractAddress::get()),976		);977		<CollectionById<T>>::insert(id, collection);978		Ok(id)979	}980981	/// Destroy collection.982	///983	/// * `collection` - Collection handler.984	/// * `sender` - The owner or administrator of the collection.985	pub fn destroy_collection(986		collection: CollectionHandle<T>,987		sender: &T::CrossAccountId,988	) -> DispatchResult {989		ensure!(990			collection.limits.owner_can_destroy(),991			<Error<T>>::NoPermission,992		);993		collection.check_is_owner(sender)?;994995		let destroyed_collections = <DestroyedCollectionCount<T>>::get()996			.0997			.checked_add(1)998			.ok_or(ArithmeticError::Overflow)?;9991000		// =========10011002		<DestroyedCollectionCount<T>>::put(destroyed_collections);1003		<CollectionById<T>>::remove(collection.id);1004		<AdminAmount<T>>::remove(collection.id);1005		let _ = <IsAdmin<T>>::clear_prefix((collection.id,), u32::MAX, None);1006		let _ = <Allowlist<T>>::clear_prefix((collection.id,), u32::MAX, None);1007		<CollectionProperties<T>>::remove(collection.id);10081009		<Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));10101011		<PalletEvm<T>>::deposit_log(1012			erc::CollectionHelpersEvents::CollectionDestroyed {1013				collection_id: eth::collection_id_to_address(collection.id),1014			}1015			.to_log(T::ContractAddress::get()),1016		);1017		Ok(())1018	}10191020	/// Set collection property.1021	///1022	/// * `collection` - Collection handler.1023	/// * `sender` - The owner or administrator of the collection.1024	/// * `property` - The property to set.1025	pub fn set_collection_property(1026		collection: &CollectionHandle<T>,1027		sender: &T::CrossAccountId,1028		property: Property,1029	) -> DispatchResult {1030		collection.check_is_owner_or_admin(sender)?;10311032		CollectionProperties::<T>::try_mutate(collection.id, |properties| {1033			let property = property.clone();1034			properties.try_set(property.key, property.value)1035		})1036		.map_err(<Error<T>>::from)?;10371038		Self::deposit_event(Event::CollectionPropertySet(collection.id, property.key));10391040		Ok(())1041	}10421043	/// Set scouped collection property.1044	///1045	/// * `collection_id` - ID of the collection for which the property is being set.1046	/// * `scope` - Property scope.1047	/// * `property` - The property to set.1048	pub fn set_scoped_collection_property(1049		collection_id: CollectionId,1050		scope: PropertyScope,1051		property: Property,1052	) -> DispatchResult {1053		CollectionProperties::<T>::try_mutate(collection_id, |properties| {1054			properties.try_scoped_set(scope, property.key, property.value)1055		})1056		.map_err(<Error<T>>::from)?;10571058		Ok(())1059	}10601061	/// Set scouped collection properties.1062	///1063	/// * `collection_id` - ID of the collection for which the properties is being set.1064	/// * `scope` - Property scope.1065	/// * `properties` - The properties to set.1066	pub fn set_scoped_collection_properties(1067		collection_id: CollectionId,1068		scope: PropertyScope,1069		properties: impl Iterator<Item = Property>,1070	) -> DispatchResult {1071		CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {1072			stored_properties.try_scoped_set_from_iter(scope, properties)1073		})1074		.map_err(<Error<T>>::from)?;10751076		Ok(())1077	}10781079	/// Set collection properties.1080	///1081	/// * `collection` - Collection handler.1082	/// * `sender` - The owner or administrator of the collection.1083	/// * `properties` - The properties to set.1084	#[transactional]1085	pub fn set_collection_properties(1086		collection: &CollectionHandle<T>,1087		sender: &T::CrossAccountId,1088		properties: Vec<Property>,1089	) -> DispatchResult {1090		for property in properties {1091			Self::set_collection_property(collection, sender, property)?;1092		}10931094		Ok(())1095	}10961097	/// Delete collection property.1098	///1099	/// * `collection` - Collection handler.1100	/// * `sender` - The owner or administrator of the collection.1101	/// * `property` - The property to delete.1102	pub fn delete_collection_property(1103		collection: &CollectionHandle<T>,1104		sender: &T::CrossAccountId,1105		property_key: PropertyKey,1106	) -> DispatchResult {1107		collection.check_is_owner_or_admin(sender)?;11081109		CollectionProperties::<T>::try_mutate(collection.id, |properties| {1110			properties.remove(&property_key)1111		})1112		.map_err(<Error<T>>::from)?;11131114		Self::deposit_event(Event::CollectionPropertyDeleted(1115			collection.id,1116			property_key,1117		));11181119		Ok(())1120	}11211122	/// Delete collection properties.1123	///1124	/// * `collection` - Collection handler.1125	/// * `sender` - The owner or administrator of the collection.1126	/// * `properties` - The properties to delete.1127	#[transactional]1128	pub fn delete_collection_properties(1129		collection: &CollectionHandle<T>,1130		sender: &T::CrossAccountId,1131		property_keys: Vec<PropertyKey>,1132	) -> DispatchResult {1133		for key in property_keys {1134			Self::delete_collection_property(collection, sender, key)?;1135		}11361137		Ok(())1138	}11391140	/// Set collection propetry permission without any checks.1141	///1142	/// Used for migrations.1143	///1144	/// * `collection` - Collection handler.1145	/// * `property_permissions` - Property permissions.1146	pub fn set_property_permission_unchecked(1147		collection: CollectionId,1148		property_permission: PropertyKeyPermission,1149	) -> DispatchResult {1150		<CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {1151			permissions.try_set(property_permission.key, property_permission.permission)1152		})1153		.map_err(<Error<T>>::from)?;1154		Ok(())1155	}11561157	/// Set collection property permission.1158	///1159	/// * `collection` - Collection handler.1160	/// * `sender` - The owner or administrator of the collection.1161	/// * `property_permission` - Property permission.1162	pub fn set_property_permission(1163		collection: &CollectionHandle<T>,1164		sender: &T::CrossAccountId,1165		property_permission: PropertyKeyPermission,1166	) -> DispatchResult {1167		Self::set_scoped_property_permission(1168			collection,1169			sender,1170			PropertyScope::None,1171			property_permission,1172		)1173	}11741175	/// Set collection property permission with scope.1176	///1177	/// * `collection` - Collection handler.1178	/// * `sender` - The owner or administrator of the collection.1179	/// * `scope` - Property scope.1180	/// * `property_permission` - Property permission.1181	pub fn set_scoped_property_permission(1182		collection: &CollectionHandle<T>,1183		sender: &T::CrossAccountId,1184		scope: PropertyScope,1185		property_permission: PropertyKeyPermission,1186	) -> DispatchResult {1187		collection.check_is_owner_or_admin(sender)?;11881189		let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);1190		let current_permission = all_permissions.get(&property_permission.key);1191		if matches![1192			current_permission,1193			Some(PropertyPermission { mutable: false, .. })1194		] {1195			return Err(<Error<T>>::NoPermission.into());1196		}11971198		CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {1199			let property_permission = property_permission.clone();1200			permissions.try_scoped_set(1201				scope,1202				property_permission.key,1203				property_permission.permission,1204			)1205		})1206		.map_err(<Error<T>>::from)?;12071208		Self::deposit_event(Event::PropertyPermissionSet(1209			collection.id,1210			property_permission.key,1211		));12121213		Ok(())1214	}12151216	/// Set token property permission.1217	///1218	/// * `collection` - Collection handler.1219	/// * `sender` - The owner or administrator of the collection.1220	/// * `property_permissions` - Property permissions.1221	#[transactional]1222	pub fn set_token_property_permissions(1223		collection: &CollectionHandle<T>,1224		sender: &T::CrossAccountId,1225		property_permissions: Vec<PropertyKeyPermission>,1226	) -> DispatchResult {1227		Self::set_scoped_token_property_permissions(1228			collection,1229			sender,1230			PropertyScope::None,1231			property_permissions,1232		)1233	}12341235	/// Set token property permission with scope.1236	///1237	/// * `collection` - Collection handler.1238	/// * `sender` - The owner or administrator of the collection.1239	/// * `scope` - Property scope.1240	/// * `property_permissions` - Property permissions.1241	#[transactional]1242	pub fn set_scoped_token_property_permissions(1243		collection: &CollectionHandle<T>,1244		sender: &T::CrossAccountId,1245		scope: PropertyScope,1246		property_permissions: Vec<PropertyKeyPermission>,1247	) -> DispatchResult {1248		for prop_pemission in property_permissions {1249			Self::set_scoped_property_permission(collection, sender, scope, prop_pemission)?;1250		}12511252		Ok(())1253	}12541255	/// Get collection property.1256	pub fn get_collection_property(1257		collection_id: CollectionId,1258		key: &PropertyKey,1259	) -> Option<PropertyValue> {1260		Self::collection_properties(collection_id).get(key).cloned()1261	}12621263	/// Convert byte vector to property key vector.1264	pub fn bytes_keys_to_property_keys(1265		keys: Vec<Vec<u8>>,1266	) -> Result<Vec<PropertyKey>, DispatchError> {1267		keys.into_iter()1268			.map(|key| -> Result<PropertyKey, DispatchError> {1269				key.try_into()1270					.map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())1271			})1272			.collect::<Result<Vec<PropertyKey>, DispatchError>>()1273	}12741275	/// Get properties according to given keys.1276	pub fn filter_collection_properties(1277		collection_id: CollectionId,1278		keys: Option<Vec<PropertyKey>>,1279	) -> Result<Vec<Property>, DispatchError> {1280		let properties = Self::collection_properties(collection_id);12811282		let properties = keys1283			.map(|keys| {1284				keys.into_iter()1285					.filter_map(|key| {1286						properties.get(&key).map(|value| Property {1287							key,1288							value: value.clone(),1289						})1290					})1291					.collect()1292			})1293			.unwrap_or_else(|| {1294				properties1295					.into_iter()1296					.map(|(key, value)| Property { key, value })1297					.collect()1298			});12991300		Ok(properties)1301	}13021303	/// Get property permissions according to given keys.1304	pub fn filter_property_permissions(1305		collection_id: CollectionId,1306		keys: Option<Vec<PropertyKey>>,1307	) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1308		let permissions = Self::property_permissions(collection_id);13091310		let key_permissions = keys1311			.map(|keys| {1312				keys.into_iter()1313					.filter_map(|key| {1314						permissions1315							.get(&key)1316							.map(|permission| PropertyKeyPermission {1317								key,1318								permission: permission.clone(),1319							})1320					})1321					.collect()1322			})1323			.unwrap_or_else(|| {1324				permissions1325					.into_iter()1326					.map(|(key, permission)| PropertyKeyPermission { key, permission })1327					.collect()1328			});13291330		Ok(key_permissions)1331	}13321333	/// Toggle `user` participation in the `collection`'s allow list.1334	/// #### Store read/writes1335	/// 1 writes1336	pub fn toggle_allowlist(1337		collection: &CollectionHandle<T>,1338		sender: &T::CrossAccountId,1339		user: &T::CrossAccountId,1340		allowed: bool,1341	) -> DispatchResult {1342		collection.check_is_owner_or_admin(sender)?;13431344		// =========13451346		if allowed {1347			<Allowlist<T>>::insert((collection.id, user), true);1348		} else {1349			<Allowlist<T>>::remove((collection.id, user));1350		}13511352		Ok(())1353	}13541355	/// Toggle `user` participation in the `collection`'s admin list.1356	/// #### Store read/writes1357	/// 2 writes1358	pub fn toggle_admin(1359		collection: &CollectionHandle<T>,1360		sender: &T::CrossAccountId,1361		user: &T::CrossAccountId,1362		admin: bool,1363	) -> DispatchResult {1364		collection.check_is_owner(sender)?;13651366		let was_admin = <IsAdmin<T>>::get((collection.id, user));1367		if was_admin == admin {1368			return Ok(());1369		}1370		let amount = <AdminAmount<T>>::get(collection.id);13711372		if admin {1373			let amount = amount1374				.checked_add(1)1375				.ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1376			ensure!(1377				amount <= Self::collection_admins_limit(),1378				<Error<T>>::CollectionAdminCountExceeded,1379			);13801381			// =========13821383			<AdminAmount<T>>::insert(collection.id, amount);1384			<IsAdmin<T>>::insert((collection.id, user), true);1385		} else {1386			<AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1387			<IsAdmin<T>>::remove((collection.id, user));1388		}13891390		Ok(())1391	}13921393	/// Merge set fields from `new_limit` to `old_limit`.1394	pub fn clamp_limits(1395		mode: CollectionMode,1396		old_limit: &CollectionLimits,1397		mut new_limit: CollectionLimits,1398	) -> Result<CollectionLimits, DispatchError> {1399		let limits = old_limit;1400		limit_default!(old_limit, new_limit,1401			account_token_ownership_limit => ensure!(1402				new_limit <= MAX_TOKEN_OWNERSHIP,1403				<Error<T>>::CollectionLimitBoundsExceeded,1404			),1405			sponsored_data_size => ensure!(1406				new_limit <= CUSTOM_DATA_LIMIT,1407				<Error<T>>::CollectionLimitBoundsExceeded,1408			),14091410			sponsored_data_rate_limit => {},1411			token_limit => ensure!(1412				old_limit >= new_limit && new_limit > 0,1413				<Error<T>>::CollectionTokenLimitExceeded1414			),14151416			sponsor_transfer_timeout(match mode {1417				CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1418				CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1419				CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1420			}) => ensure!(1421				new_limit <= MAX_SPONSOR_TIMEOUT,1422				<Error<T>>::CollectionLimitBoundsExceeded,1423			),1424			sponsor_approve_timeout => {},1425			owner_can_transfer => ensure!(1426				!limits.owner_can_transfer_instaled() ||1427				old_limit || !new_limit,1428				<Error<T>>::OwnerPermissionsCantBeReverted,1429			),1430			owner_can_destroy => ensure!(1431				old_limit || !new_limit,1432				<Error<T>>::OwnerPermissionsCantBeReverted,1433			),1434			transfers_enabled => {},1435		);1436		Ok(new_limit)1437	}14381439	/// Merge set fields from `new_permission` to `old_permission`.1440	pub fn clamp_permissions(1441		_mode: CollectionMode,1442		old_permission: &CollectionPermissions,1443		mut new_permission: CollectionPermissions,1444	) -> Result<CollectionPermissions, DispatchError> {1445		limit_default_clone!(old_permission, new_permission,1446			access => {},1447			mint_mode => {},1448			nesting => { /* todo check for permissive, if only it gets out of benchmarks */ },1449		);1450		Ok(new_permission)1451	}1452}14531454/// Indicates unsupported methods by returning [Error::UnsupportedOperation].1455#[macro_export]1456macro_rules! unsupported {1457	($runtime:path) => {1458		Err($crate::Error::<$runtime>::UnsupportedOperation.into())1459	};1460}14611462/// Return weights for various worst-case operations.1463pub trait CommonWeightInfo<CrossAccountId> {1464	/// Weight of item creation.1465	fn create_item() -> Weight;14661467	/// Weight of items creation.1468	fn create_multiple_items(amount: &[CreateItemData]) -> Weight;14691470	/// Weight of items creation.1471	fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;14721473	/// The weight of the burning item.1474	fn burn_item() -> Weight;14751476	/// Property setting weight.1477	///1478	/// * `amount`- The number of properties to set.1479	fn set_collection_properties(amount: u32) -> Weight;14801481	/// Collection property deletion weight.1482	///1483	/// * `amount`- The number of properties to set.1484	fn delete_collection_properties(amount: u32) -> Weight;14851486	/// Token property setting weight.1487	///1488	/// * `amount`- The number of properties to set.1489	fn set_token_properties(amount: u32) -> Weight;14901491	/// Token property deletion weight.1492	///1493	/// * `amount`- The number of properties to delete.1494	fn delete_token_properties(amount: u32) -> Weight;14951496	/// Token property permissions set weight.1497	///1498	/// * `amount`- The number of property permissions to set.1499	fn set_token_property_permissions(amount: u32) -> Weight;15001501	/// Transfer price of the token or its parts.1502	fn transfer() -> Weight;15031504	/// The price of setting the permission of the operation from another user.1505	fn approve() -> Weight;15061507	/// Transfer price from another user.1508	fn transfer_from() -> Weight;15091510	/// The price of burning a token from another user.1511	fn burn_from() -> Weight;15121513	/// Differs from burn_item in case of Fungible and Refungible, as it should burn1514	/// whole users's balance.1515	///1516	/// This method shouldn't be used directly, as it doesn't count breadth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1517	fn burn_recursively_self_raw() -> Weight;15181519	/// Cost of iterating over `amount` children while burning, without counting child burning itself.1520	///1521	/// This method shouldn't be used directly, as it doesn't count depth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1522	fn burn_recursively_breadth_raw(amount: u32) -> Weight;15231524	/// The price of recursive burning a token.1525	///1526	/// `max_selfs` - The maximum burning weight of the token itself.1527	/// `max_breadth` - The maximum number of nested tokens to burn.1528	fn burn_recursively(max_selfs: u32, max_breadth: u32) -> Weight {1529		Self::burn_recursively_self_raw()1530			.saturating_mul(max_selfs.max(1) as u64)1531			.saturating_add(Self::burn_recursively_breadth_raw(max_breadth))1532	}15331534	/// The price of retrieving token owner1535	fn token_owner() -> Weight;15361537	/// The price of setting approval for all1538	fn set_approval_for_all() -> Weight;1539}15401541/// Weight info extension trait for refungible pallet.1542pub trait RefungibleExtensionsWeightInfo {1543	/// Weight of token repartition.1544	fn repartition() -> Weight;1545}15461547/// Common collection operations.1548///1549/// It wraps methods in Fungible, Nonfungible and Refungible pallets1550/// and adds weight info.1551pub trait CommonCollectionOperations<T: Config> {1552	/// Create token.1553	///1554	/// * `sender` - The user who mint the token and pays for the transaction.1555	/// * `to` - The user who will own the token.1556	/// * `data` - Token data.1557	/// * `nesting_budget` - A budget that can be spent on nesting tokens.1558	fn create_item(1559		&self,1560		sender: T::CrossAccountId,1561		to: T::CrossAccountId,1562		data: CreateItemData,1563		nesting_budget: &dyn Budget,1564	) -> DispatchResultWithPostInfo;15651566	/// Create multiple tokens.1567	///1568	/// * `sender` - The user who mint the token and pays for the transaction.1569	/// * `to` - The user who will own the token.1570	/// * `data` - Token data.1571	/// * `nesting_budget` - A budget that can be spent on nesting tokens.1572	fn create_multiple_items(1573		&self,1574		sender: T::CrossAccountId,1575		to: T::CrossAccountId,1576		data: Vec<CreateItemData>,1577		nesting_budget: &dyn Budget,1578	) -> DispatchResultWithPostInfo;15791580	/// Create multiple tokens.1581	///1582	/// * `sender` - The user who mint the token and pays for the transaction.1583	/// * `to` - The user who will own the token.1584	/// * `data` - Token data.1585	/// * `nesting_budget` - A budget that can be spent on nesting tokens.1586	fn create_multiple_items_ex(1587		&self,1588		sender: T::CrossAccountId,1589		data: CreateItemExData<T::CrossAccountId>,1590		nesting_budget: &dyn Budget,1591	) -> DispatchResultWithPostInfo;15921593	/// Burn token.1594	///1595	/// * `sender` - The user who owns the token.1596	/// * `token` - Token id that will burned.1597	/// * `amount` - The number of parts of the token that will be burned.1598	fn burn_item(1599		&self,1600		sender: T::CrossAccountId,1601		token: TokenId,1602		amount: u128,1603	) -> DispatchResultWithPostInfo;16041605	/// Burn token and all nested tokens recursievly.1606	///1607	/// * `sender` - The user who owns the token.1608	/// * `token` - Token id that will burned.1609	/// * `self_budget` - The budget that can be spent on burning tokens.1610	/// * `breadth_budget` - The budget that can be spent on burning nested tokens.1611	fn burn_item_recursively(1612		&self,1613		sender: T::CrossAccountId,1614		token: TokenId,1615		self_budget: &dyn Budget,1616		breadth_budget: &dyn Budget,1617	) -> DispatchResultWithPostInfo;16181619	/// Set collection properties.1620	///1621	/// * `sender` - Must be either the owner of the collection or its admin.1622	/// * `properties` - Properties to be set.1623	fn set_collection_properties(1624		&self,1625		sender: T::CrossAccountId,1626		properties: Vec<Property>,1627	) -> DispatchResultWithPostInfo;16281629	/// Delete collection properties.1630	///1631	/// * `sender` - Must be either the owner of the collection or its admin.1632	/// * `properties` - The properties to be removed.1633	fn delete_collection_properties(1634		&self,1635		sender: &T::CrossAccountId,1636		property_keys: Vec<PropertyKey>,1637	) -> DispatchResultWithPostInfo;16381639	/// Set token properties.1640	///1641	/// The appropriate [`PropertyPermission`] for the token property1642	/// must be set with [`Self::set_token_property_permissions`].1643	///1644	/// * `sender` - Must be either the owner of the token or its admin.1645	/// * `token_id` - The token for which the properties are being set.1646	/// * `properties` - Properties to be set.1647	/// * `budget` - Budget for setting properties.1648	fn set_token_properties(1649		&self,1650		sender: T::CrossAccountId,1651		token_id: TokenId,1652		properties: Vec<Property>,1653		budget: &dyn Budget,1654	) -> DispatchResultWithPostInfo;16551656	/// Remove token properties.1657	///1658	/// The appropriate [`PropertyPermission`] for the token property1659	/// must be set with [`Self::set_token_property_permissions`].1660	///1661	/// * `sender` - Must be either the owner of the token or its admin.1662	/// * `token_id` - The token for which the properties are being remove.1663	/// * `property_keys` - Keys to remove corresponding properties.1664	/// * `budget` - Budget for removing properties.1665	fn delete_token_properties(1666		&self,1667		sender: T::CrossAccountId,1668		token_id: TokenId,1669		property_keys: Vec<PropertyKey>,1670		budget: &dyn Budget,1671	) -> DispatchResultWithPostInfo;16721673	/// Set token property permissions.1674	///1675	/// * `sender` - Must be either the owner of the token or its admin.1676	/// * `token_id` - The token for which the properties are being set.1677	/// * `property_permissions` - Property permissions to be set.1678	/// * `budget` - Budget for setting properties.1679	fn set_token_property_permissions(1680		&self,1681		sender: &T::CrossAccountId,1682		property_permissions: Vec<PropertyKeyPermission>,1683	) -> DispatchResultWithPostInfo;16841685	/// Transfer amount of token pieces.1686	///1687	/// * `sender` - Donor user.1688	/// * `to` - Recepient user.1689	/// * `token` - The token of which parts are being sent.1690	/// * `amount` - The number of parts of the token that will be transferred.1691	/// * `budget` - The maximum budget that can be spent on the transfer.1692	fn transfer(1693		&self,1694		sender: T::CrossAccountId,1695		to: T::CrossAccountId,1696		token: TokenId,1697		amount: u128,1698		budget: &dyn Budget,1699	) -> DispatchResultWithPostInfo;17001701	/// Grant access to another account to transfer parts of the token owned by the calling user via [Self::transfer_from].1702	///1703	/// * `sender` - The user who grants access to the token.1704	/// * `spender` - The user to whom the rights are granted.1705	/// * `token` - The token to which access is granted.1706	/// * `amount` - The amount of pieces that another user can dispose of.1707	fn approve(1708		&self,1709		sender: T::CrossAccountId,1710		spender: T::CrossAccountId,1711		token: TokenId,1712		amount: u128,1713	) -> DispatchResultWithPostInfo;17141715	/// Send parts of a token owned by another user.1716	///1717	/// Before calling this method, you must grant rights to the calling user via [`Self::approve`].1718	///1719	/// * `sender` - The user who must have access to the token (see [`Self::approve`]).1720	/// * `from` - The user who owns the token.1721	/// * `to` - Recepient user.1722	/// * `token` - The token of which parts are being sent.1723	/// * `amount` - The number of parts of the token that will be transferred.1724	/// * `budget` - The maximum budget that can be spent on the transfer.1725	fn transfer_from(1726		&self,1727		sender: T::CrossAccountId,1728		from: T::CrossAccountId,1729		to: T::CrossAccountId,1730		token: TokenId,1731		amount: u128,1732		budget: &dyn Budget,1733	) -> DispatchResultWithPostInfo;17341735	/// Burn parts of a token owned by another user.1736	///1737	/// Before calling this method, you must grant rights to the calling user via [`Self::approve`].1738	///1739	/// * `sender` - The user who must have access to the token (see [`Self::approve`]).1740	/// * `from` - The user who owns the token.1741	/// * `token` - The token of which parts are being sent.1742	/// * `amount` - The number of parts of the token that will be transferred.1743	/// * `budget` - The maximum budget that can be spent on the burn.1744	fn burn_from(1745		&self,1746		sender: T::CrossAccountId,1747		from: T::CrossAccountId,1748		token: TokenId,1749		amount: u128,1750		budget: &dyn Budget,1751	) -> DispatchResultWithPostInfo;17521753	/// Check permission to nest token.1754	///1755	/// * `sender` - The user who initiated the check.1756	/// * `from` - The token that is checked for embedding.1757	/// * `under` - Token under which to check.1758	/// * `budget` - The maximum budget that can be spent on the check.1759	fn check_nesting(1760		&self,1761		sender: T::CrossAccountId,1762		from: (CollectionId, TokenId),1763		under: TokenId,1764		budget: &dyn Budget,1765	) -> DispatchResult;17661767	/// Nest one token into another.1768	///1769	/// * `under` - Token holder.1770	/// * `to_nest` - Nested token.1771	fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));17721773	/// Unnest token.1774	///1775	/// * `under` - Token holder.1776	/// * `to_nest` - Token to unnest.1777	fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));17781779	/// Get all user tokens.1780	///1781	/// * `account` - Account for which you need to get tokens.1782	fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;17831784	/// Get all the tokens in the collection.1785	fn collection_tokens(&self) -> Vec<TokenId>;17861787	/// Check if the token exists.1788	///1789	/// * `token` - Id token to check.1790	fn token_exists(&self, token: TokenId) -> bool;17911792	/// Get the id of the last minted token.1793	fn last_token_id(&self) -> TokenId;17941795	/// Get the owner of the token.1796	///1797	/// * `token` - The token for which you need to find out the owner.1798	fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId>;17991800	/// Returns 10 tokens owners in no particular order.1801	///1802	/// * `token` - The token for which you need to find out the owners.1803	fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId>;18041805	/// Get the value of the token property by key.1806	///1807	/// * `token` - Token with the property to get.1808	/// * `key` - Property name.1809	fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;18101811	/// Get a set of token properties by key vector.1812	///1813	/// * `token` - Token with the property to get.1814	/// * `keys` - Vector of property keys. If this parameter is [None](sp_std::result::Result),1815	/// then all properties are returned.1816	fn token_properties(&self, token: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;18171818	/// Amount of unique collection tokens1819	fn total_supply(&self) -> u32;18201821	/// Amount of different tokens account has.1822	///1823	/// * `account` - The account for which need to get the balance.1824	fn account_balance(&self, account: T::CrossAccountId) -> u32;18251826	/// Amount of specific token account have.1827	fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;18281829	/// Amount of token pieces1830	fn total_pieces(&self, token: TokenId) -> Option<u128>;18311832	/// Get the number of parts of the token that a trusted user can manage.1833	///1834	/// * `sender` - Trusted user.1835	/// * `spender` - Owner of the token.1836	/// * `token` - The token for which to get the value.1837	fn allowance(1838		&self,1839		sender: T::CrossAccountId,1840		spender: T::CrossAccountId,1841		token: TokenId,1842	) -> u128;18431844	/// Get extension for RFT collection.1845	fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>>;18461847	/// An operator is allowed to transfer all tokens of the sender on their behalf.1848	/// * `owner` - Token owner1849	/// * `operator` - Operator1850	/// * `approve` - Is operator enabled or disabled1851	fn set_approval_for_all(1852		&self,1853		owner: T::CrossAccountId,1854		operator: T::CrossAccountId,1855		approve: bool,1856	) -> DispatchResultWithPostInfo;18571858	/// Tells whether an operator is approved by a given owner.1859	fn is_approved_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool;1860}18611862/// Extension for RFT collection.1863pub trait RefungibleExtensions<T>1864where1865	T: Config,1866{1867	/// Change the number of parts of the token.1868	///1869	/// When the value changes down, this function is equivalent to burning parts of the token.1870	///1871	/// * `sender` - The user calling the repartition operation. Must be the owner of the token.1872	/// * `token` - The token for which you want to change the number of parts.1873	/// * `amount` - The new value of the parts of the token.1874	fn repartition(1875		&self,1876		sender: &T::CrossAccountId,1877		token: TokenId,1878		amount: u128,1879	) -> DispatchResultWithPostInfo;1880}18811882/// Merge [`DispatchResult`] with [`Weight`] into [`DispatchResultWithPostInfo`].1883///1884/// Used for [`CommonCollectionOperations`] implementations and flexible enough to do so.1885pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {1886	let post_info = PostDispatchInfo {1887		actual_weight: Some(weight),1888		pays_fee: Pays::Yes,1889	};1890	match res {1891		Ok(()) => Ok(post_info),1892		Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),1893	}1894}18951896impl<T: Config> From<PropertiesError> for Error<T> {1897	fn from(error: PropertiesError) -> Self {1898		match error {1899			PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,1900			PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,1901			PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,1902			PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,1903			PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,1904		}1905	}1906}
modifiedpallets/fungible/src/common.rsdiffbeforeafterboth
--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -107,6 +107,10 @@
 	fn token_owner() -> Weight {
 		Weight::zero()
 	}
+
+	fn set_approval_for_all() -> Weight {
+		Weight::zero()
+	}
 }
 
 /// Implementation of `CommonCollectionOperations` for `FungibleHandle`. It wraps FungibleHandle Pallete
@@ -424,4 +428,17 @@
 		}
 		<TotalSupply<T>>::try_get(self.id).ok()
 	}
+
+	fn set_approval_for_all(
+		&self,
+		_owner: T::CrossAccountId,
+		_operator: T::CrossAccountId,
+		_approve: bool,
+	) -> DispatchResultWithPostInfo {
+		fail!(<Error<T>>::SettingApprovalForAllNotAllowed)
+	}
+
+	fn is_approved_for_all(&self, _owner: T::CrossAccountId, _operator: T::CrossAccountId) -> bool {
+		false
+	}
 }
modifiedpallets/fungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -127,6 +127,8 @@
 		FungibleDisallowsNesting,
 		/// Setting item properties is not allowed.
 		SettingPropertiesNotAllowed,
+		/// Setting approval for all is not allowed.
+		SettingApprovalForAllNotAllowed,
 	}
 
 	#[pallet::config]
modifiedpallets/nonfungible/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/benchmarking.rs
+++ b/pallets/nonfungible/src/benchmarking.rs
@@ -222,4 +222,18 @@
 		let item = create_max_item(&collection, &owner, owner.clone())?;
 
 	}: {collection.token_owner(item)}
+
+	set_approval_for_all {
+		bench_init!{
+			owner: sub; collection: collection(owner);
+			operator: cross_from_sub(owner); owner: cross_sub;
+		};
+	}: {<Pallet<T>>::set_approval_for_all(&collection, &owner, &operator, true)}
+
+	is_approved_for_all {
+		bench_init!{
+			owner: sub; collection: collection(owner);
+			operator: cross_from_sub(owner); owner: cross_sub;
+		};
+	}: {<Pallet<T>>::is_approved_for_all(&collection, &owner, &operator)}
 }
modifiedpallets/nonfungible/src/common.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -122,6 +122,10 @@
 	fn token_owner() -> Weight {
 		<SelfWeightOf<T>>::token_owner()
 	}
+
+	fn set_approval_for_all() -> Weight {
+		<SelfWeightOf<T>>::set_approval_for_all()
+	}
 }
 
 fn map_create_data<T: Config>(
@@ -512,4 +516,20 @@
 			None
 		}
 	}
+
+	fn set_approval_for_all(
+		&self,
+		owner: T::CrossAccountId,
+		operator: T::CrossAccountId,
+		approve: bool,
+	) -> DispatchResultWithPostInfo {
+		with_weight(
+			<Pallet<T>>::set_approval_for_all(self, &owner, &operator, approve),
+			<CommonWeights<T>>::set_approval_for_all(),
+		)
+	}
+
+	fn is_approved_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool {
+		<Pallet<T>>::is_approved_for_all(self, &owner, &operator)
+	}
 }
modifiedpallets/nonfungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -469,15 +469,23 @@
 		Ok(())
 	}
 
-	/// @dev Not implemented
+	/// @notice Sets or unsets the approval of a given operator.
+	///  An operator is allowed to transfer all tokens of the sender on their behalf.
+	/// @param operator Operator
+	/// @param approved Is operator enabled or disabled
+	#[weight(<SelfWeightOf<T>>::set_approval_for_all())]
 	fn set_approval_for_all(
 		&mut self,
-		_caller: caller,
-		_operator: address,
-		_approved: bool,
+		caller: caller,
+		operator: address,
+		approved: bool,
 	) -> Result<void> {
-		// TODO: Not implemetable
-		Err("not implemented".into())
+		let caller = T::CrossAccountId::from_eth(caller);
+		let operator = T::CrossAccountId::from_eth(operator);
+
+		<Pallet<T>>::set_approval_for_all(self, &caller, &operator, approved)
+			.map_err(dispatch_to_evm::<T>)?;
+		Ok(())
 	}
 
 	/// @dev Not implemented
@@ -486,10 +494,13 @@
 		Err("not implemented".into())
 	}
 
-	/// @dev Not implemented
-	fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {
-		// TODO: Not implemetable
-		Err("not implemented".into())
+	/// @notice Tells whether an operator is approved by a given owner.
+	#[weight(<SelfWeightOf<T>>::is_approved_for_all())]
+	fn is_approved_for_all(&self, owner: address, operator: address) -> Result<bool> {
+		let owner = T::CrossAccountId::from_eth(owner);
+		let operator = T::CrossAccountId::from_eth(operator);
+
+		Ok(<Pallet<T>>::is_approved_for_all(self, &owner, &operator))
 	}
 
 	/// @notice Returns collection helper contract address
modifiedpallets/nonfungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -272,6 +272,18 @@
 		QueryKind = OptionQuery,
 	>;
 
+	/// Operator set by a wallet owner that could perform certain transactions on all tokens in the wallet.
+	#[pallet::storage]
+	pub type WalletOperator<T: Config> = StorageNMap<
+		Key = (
+			Key<Twox64Concat, CollectionId>,
+			Key<Blake2_128Concat, T::CrossAccountId>,
+			Key<Blake2_128Concat, T::CrossAccountId>,
+		),
+		Value = bool,
+		QueryKind = OptionQuery,
+	>;
+
 	/// Upgrade from the old schema to properties.
 	#[pallet::hooks]
 	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
@@ -438,6 +450,7 @@
 		<TokensBurnt<T>>::remove(id);
 		let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);
 		let _ = <AccountBalance<T>>::clear_prefix((id,), u32::MAX, None);
+		let _ = <WalletOperator<T>>::clear_prefix((id,), u32::MAX, None);
 		Ok(())
 	}
 
@@ -1193,6 +1206,9 @@
 		if <Allowance<T>>::get((collection.id, token)).as_ref() == Some(spender) {
 			return Ok(());
 		}
+		if <WalletOperator<T>>::get((collection.id, from, spender)) == Some(true) {
+			return Ok(());
+		}
 		ensure!(
 			collection.ignores_allowance(spender),
 			<CommonError<T>>::ApprovedValueTooLow
@@ -1326,4 +1342,52 @@
 	) -> DispatchResult {
 		Self::create_multiple_items(collection, sender, vec![data], nesting_budget)
 	}
+
+	/// Sets or unsets the approval of a given operator.
+	///
+	/// An operator is allowed to transfer all token pieces of the sender on their behalf.
+	/// - `owner`: Token owner
+	/// - `operator`: Operator
+	/// - `approve`: Is operator enabled or disabled
+	pub fn set_approval_for_all(
+		collection: &NonfungibleHandle<T>,
+		owner: &T::CrossAccountId,
+		operator: &T::CrossAccountId,
+		approve: bool,
+	) -> DispatchResult {
+		if collection.permissions.access() == AccessMode::AllowList {
+			collection.check_allowlist(owner)?;
+			collection.check_allowlist(operator)?;
+		}
+
+		<PalletCommon<T>>::ensure_correct_receiver(operator)?;
+
+		// =========
+
+		<WalletOperator<T>>::insert((collection.id, owner, operator), approve);
+		<PalletEvm<T>>::deposit_log(
+			ERC721Events::ApprovalForAll {
+				owner: *owner.as_eth(),
+				operator: *operator.as_eth(),
+				approved: approve,
+			}
+			.to_log(collection_id_to_address(collection.id)),
+		);
+		<PalletCommon<T>>::deposit_event(CommonEvent::ApprovedForAll(
+			collection.id,
+			owner.clone(),
+			operator.clone(),
+			approve,
+		));
+		Ok(())
+	}
+
+	/// Tells whether an operator is approved by a given owner.
+	pub fn is_approved_for_all(
+		collection: &NonfungibleHandle<T>,
+		owner: &T::CrossAccountId,
+		operator: &T::CrossAccountId,
+	) -> bool {
+		<WalletOperator<T>>::get((collection.id, owner, operator)).unwrap_or(false)
+	}
 }
modifiedpallets/nonfungible/src/stubs/UniqueNFT.rawdiffbeforeafterboth

binary blob — no preview

modifiedpallets/nonfungible/src/stubs/UniqueNFT.soldiffbeforeafterboth
--- a/pallets/nonfungible/src/stubs/UniqueNFT.sol
+++ b/pallets/nonfungible/src/stubs/UniqueNFT.sol
@@ -1020,7 +1020,10 @@
 		dummy = 0;
 	}
 
-	/// @dev Not implemented
+	/// @notice Sets or unsets the approval of a given operator.
+	///  An operator is allowed to transfer all tokens of the sender on their behalf.
+	/// @param operator Operator
+	/// @param approved Is operator enabled or disabled
 	/// @dev EVM selector for this function is: 0xa22cb465,
 	///  or in textual repr: setApprovalForAll(address,bool)
 	function setApprovalForAll(address operator, bool approved) public {
@@ -1040,15 +1043,15 @@
 		return 0x0000000000000000000000000000000000000000;
 	}
 
-	/// @dev Not implemented
+	/// @notice Tells whether an operator is approved by a given owner.
 	/// @dev EVM selector for this function is: 0xe985e9c5,
 	///  or in textual repr: isApprovedForAll(address,address)
-	function isApprovedForAll(address owner, address operator) public view returns (address) {
+	function isApprovedForAll(address owner, address operator) public view returns (bool) {
 		require(false, stub_error);
 		owner;
 		operator;
 		dummy;
-		return 0x0000000000000000000000000000000000000000;
+		return false;
 	}
 
 	/// @notice Returns collection helper contract address
modifiedpallets/nonfungible/src/weights.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/weights.rs
+++ b/pallets/nonfungible/src/weights.rs
@@ -26,6 +26,7 @@
 #![cfg_attr(rustfmt, rustfmt_skip)]
 #![allow(unused_parens)]
 #![allow(unused_imports)]
+#![allow(missing_docs)]
 #![allow(clippy::unnecessary_cast)]
 
 use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}};
@@ -47,6 +48,8 @@
 	fn set_token_properties(b: u32, ) -> Weight;
 	fn delete_token_properties(b: u32, ) -> Weight;
 	fn token_owner() -> Weight;
+	fn set_approval_for_all() -> Weight;
+	fn is_approved_for_all() -> Weight;
 }
 
 /// Weights for pallet_nonfungible using the Substrate node and recommended hardware.
@@ -195,6 +198,16 @@
 		Weight::from_ref_time(4_366_000)
 			.saturating_add(T::DbWeight::get().reads(1 as u64))
 	}
+	// Storage: Nonfungible WalletOperator (r:0 w:1)
+	fn set_approval_for_all() -> Weight {
+		Weight::from_ref_time(16_231_000 as u64)
+			.saturating_add(T::DbWeight::get().writes(1 as u64))
+	}
+	// Storage: Nonfungible WalletOperator (r:1 w:0)
+	fn is_approved_for_all() -> Weight {
+		Weight::from_ref_time(6_161_000 as u64)
+			.saturating_add(T::DbWeight::get().reads(1 as u64))
+	}
 }
 
 // For backwards compatibility and tests
@@ -342,4 +355,14 @@
 		Weight::from_ref_time(4_366_000)
 			.saturating_add(RocksDbWeight::get().reads(1 as u64))
 	}
+	// Storage: Nonfungible WalletOperator (r:0 w:1)
+	fn set_approval_for_all() -> Weight {
+		Weight::from_ref_time(16_231_000 as u64)
+			.saturating_add(RocksDbWeight::get().writes(1 as u64))
+	}
+	// Storage: Nonfungible WalletOperator (r:1 w:0)
+	fn is_approved_for_all() -> Weight {
+		Weight::from_ref_time(6_161_000 as u64)
+			.saturating_add(RocksDbWeight::get().reads(1 as u64))
+	}
 }
modifiedpallets/refungible/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/refungible/src/benchmarking.rs
+++ b/pallets/refungible/src/benchmarking.rs
@@ -290,4 +290,18 @@
 		};
 		let item = create_max_item(&collection, &sender, [(owner.clone(), 100)])?;
 	}: {<Pallet<T>>::token_owner(collection.id, item)}
+
+	set_approval_for_all {
+		bench_init!{
+			owner: sub; collection: collection(owner);
+			operator: cross_from_sub(owner); owner: cross_sub;
+		};
+	}: {<Pallet<T>>::set_approval_for_all(&collection, &owner, &operator, true)}
+
+	is_approved_for_all {
+		bench_init!{
+			owner: sub; collection: collection(owner);
+			operator: cross_from_sub(owner); owner: cross_sub;
+		};
+	}: {<Pallet<T>>::is_approved_for_all(&collection, &owner, &operator)}
 }
modifiedpallets/refungible/src/common.rsdiffbeforeafterboth
--- a/pallets/refungible/src/common.rs
+++ b/pallets/refungible/src/common.rs
@@ -152,6 +152,10 @@
 	fn token_owner() -> Weight {
 		<SelfWeightOf<T>>::token_owner()
 	}
+
+	fn set_approval_for_all() -> Weight {
+		<SelfWeightOf<T>>::set_approval_for_all()
+	}
 }
 
 fn map_create_data<T: Config>(
@@ -516,6 +520,22 @@
 	fn total_pieces(&self, token: TokenId) -> Option<u128> {
 		<Pallet<T>>::total_pieces(self.id, token)
 	}
+
+	fn set_approval_for_all(
+		&self,
+		owner: T::CrossAccountId,
+		operator: T::CrossAccountId,
+		approve: bool,
+	) -> DispatchResultWithPostInfo {
+		with_weight(
+			<Pallet<T>>::set_approval_for_all(self, &owner, &operator, approve),
+			<CommonWeights<T>>::set_approval_for_all(),
+		)
+	}
+
+	fn is_approved_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool {
+		<Pallet<T>>::is_approved_for_all(self, &owner, &operator)
+	}
 }
 
 impl<T: Config> RefungibleExtensions<T> for RefungibleHandle<T> {
modifiedpallets/refungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/refungible/src/erc.rs
+++ b/pallets/refungible/src/erc.rs
@@ -461,15 +461,23 @@
 		Err("not implemented".into())
 	}
 
-	/// @dev Not implemented
+	/// @notice Sets or unsets the approval of a given operator.
+	///  An operator is allowed to transfer all tokens of the sender on their behalf.
+	/// @param operator Operator
+	/// @param approved Is operator enabled or disabled
+	#[weight(<SelfWeightOf<T>>::set_approval_for_all())]
 	fn set_approval_for_all(
 		&mut self,
-		_caller: caller,
-		_operator: address,
-		_approved: bool,
+		caller: caller,
+		operator: address,
+		approved: bool,
 	) -> Result<void> {
-		// TODO: Not implemetable
-		Err("not implemented".into())
+		let caller = T::CrossAccountId::from_eth(caller);
+		let operator = T::CrossAccountId::from_eth(operator);
+
+		<Pallet<T>>::set_approval_for_all(self, &caller, &operator, approved)
+			.map_err(dispatch_to_evm::<T>)?;
+		Ok(())
 	}
 
 	/// @dev Not implemented
@@ -478,10 +486,13 @@
 		Err("not implemented".into())
 	}
 
-	/// @dev Not implemented
-	fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {
-		// TODO: Not implemetable
-		Err("not implemented".into())
+	/// @notice Tells whether an operator is approved by a given owner.
+	#[weight(<SelfWeightOf<T>>::is_approved_for_all())]
+	fn is_approved_for_all(&self, owner: address, operator: address) -> Result<bool> {
+		let owner = T::CrossAccountId::from_eth(owner);
+		let operator = T::CrossAccountId::from_eth(operator);
+
+		Ok(<Pallet<T>>::is_approved_for_all(self, &owner, &operator))
 	}
 
 	/// @notice Returns collection helper contract address
modifiedpallets/refungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -273,6 +273,18 @@
 		QueryKind = ValueQuery,
 	>;
 
+	/// Operator set by a wallet owner that could perform certain transactions on all tokens in the wallet.
+	#[pallet::storage]
+	pub type WalletOperator<T: Config> = StorageNMap<
+		Key = (
+			Key<Twox64Concat, CollectionId>,
+			Key<Blake2_128Concat, T::CrossAccountId>,
+			Key<Blake2_128Concat, T::CrossAccountId>,
+		),
+		Value = bool,
+		QueryKind = OptionQuery,
+	>;
+
 	#[pallet::hooks]
 	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
 		fn on_runtime_upgrade() -> Weight {
@@ -1161,6 +1173,12 @@
 		}
 		let allowance =
 			<Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);
+
+		// Allowance if any would be reduced if spender is also wallet operator
+		if <WalletOperator<T>>::get((collection.id, from, spender)) == Some(true) {
+			return Ok(allowance);
+		}
+
 		if allowance.is_none() {
 			ensure!(
 				collection.ignores_allowance(spender),
@@ -1387,4 +1405,52 @@
 			Some(res)
 		}
 	}
+
+	/// Sets or unsets the approval of a given operator.
+	///
+	/// An operator is allowed to transfer all tokens of the sender on their behalf.
+	/// - `owner`: Token owner
+	/// - `operator`: Operator
+	/// - `approve`: Is operator enabled or disabled
+	pub fn set_approval_for_all(
+		collection: &RefungibleHandle<T>,
+		owner: &T::CrossAccountId,
+		operator: &T::CrossAccountId,
+		approve: bool,
+	) -> DispatchResult {
+		if collection.permissions.access() == AccessMode::AllowList {
+			collection.check_allowlist(owner)?;
+			collection.check_allowlist(operator)?;
+		}
+
+		<PalletCommon<T>>::ensure_correct_receiver(operator)?;
+
+		// =========
+
+		<WalletOperator<T>>::insert((collection.id, owner, operator), approve);
+		<PalletEvm<T>>::deposit_log(
+			ERC721Events::ApprovalForAll {
+				owner: *owner.as_eth(),
+				operator: *operator.as_eth(),
+				approved: approve,
+			}
+			.to_log(collection_id_to_address(collection.id)),
+		);
+		<PalletCommon<T>>::deposit_event(CommonEvent::ApprovedForAll(
+			collection.id,
+			owner.clone(),
+			operator.clone(),
+			approve,
+		));
+		Ok(())
+	}
+
+	/// Tells whether an operator is approved by a given owner.
+	pub fn is_approved_for_all(
+		collection: &RefungibleHandle<T>,
+		owner: &T::CrossAccountId,
+		operator: &T::CrossAccountId,
+	) -> bool {
+		<WalletOperator<T>>::get((collection.id, owner, operator)).unwrap_or(false)
+	}
 }
modifiedpallets/refungible/src/stubs/UniqueRefungible.rawdiffbeforeafterboth

binary blob — no preview

modifiedpallets/refungible/src/stubs/UniqueRefungible.soldiffbeforeafterboth
--- a/pallets/refungible/src/stubs/UniqueRefungible.sol
+++ b/pallets/refungible/src/stubs/UniqueRefungible.sol
@@ -1017,7 +1017,10 @@
 		dummy = 0;
 	}
 
-	/// @dev Not implemented
+	/// @notice Sets or unsets the approval of a given operator.
+	///  An operator is allowed to transfer all tokens of the sender on their behalf.
+	/// @param operator Operator
+	/// @param approved Is operator enabled or disabled
 	/// @dev EVM selector for this function is: 0xa22cb465,
 	///  or in textual repr: setApprovalForAll(address,bool)
 	function setApprovalForAll(address operator, bool approved) public {
@@ -1037,15 +1040,15 @@
 		return 0x0000000000000000000000000000000000000000;
 	}
 
-	/// @dev Not implemented
+	/// @notice Tells whether an operator is approved by a given owner.
 	/// @dev EVM selector for this function is: 0xe985e9c5,
 	///  or in textual repr: isApprovedForAll(address,address)
-	function isApprovedForAll(address owner, address operator) public view returns (address) {
+	function isApprovedForAll(address owner, address operator) public view returns (bool) {
 		require(false, stub_error);
 		owner;
 		operator;
 		dummy;
-		return 0x0000000000000000000000000000000000000000;
+		return false;
 	}
 
 	/// @notice Returns collection helper contract address
modifiedpallets/refungible/src/weights.rsdiffbeforeafterboth
--- a/pallets/refungible/src/weights.rs
+++ b/pallets/refungible/src/weights.rs
@@ -3,7 +3,7 @@
 //! Autogenerated weights for pallet_refungible
 //!
 //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev
-//! DATE: 2022-08-15, STEPS: `50`, REPEAT: 80, LOW RANGE: `[]`, HIGH RANGE: `[]`
+//! DATE: 2022-11-25, STEPS: `50`, REPEAT: 80, LOW RANGE: `[]`, HIGH RANGE: `[]`
 //! EXECUTION: None, WASM-EXECUTION: Compiled, CHAIN: None, DB CACHE: 1024
 
 // Executed Command:
@@ -26,6 +26,7 @@
 #![cfg_attr(rustfmt, rustfmt_skip)]
 #![allow(unused_parens)]
 #![allow(unused_imports)]
+#![allow(missing_docs)]
 #![allow(clippy::unnecessary_cast)]
 
 use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}};
@@ -54,6 +55,8 @@
 	fn delete_token_properties(b: u32, ) -> Weight;
 	fn repartition_item() -> Weight;
 	fn token_owner() -> Weight;
+	fn set_approval_for_all() -> Weight;
+	fn is_approved_for_all() -> Weight;
 }
 
 /// Weights for pallet_refungible using the Substrate node and recommended hardware.
@@ -259,6 +262,16 @@
 		Weight::from_ref_time(9_431_000)
 			.saturating_add(T::DbWeight::get().reads(2 as u64))
 	}
+	// Storage: Refungible WalletOperator (r:0 w:1)
+	fn set_approval_for_all() -> Weight {
+		Weight::from_ref_time(16_150_000 as u64)
+			.saturating_add(T::DbWeight::get().writes(1 as u64))
+	}
+	// Storage: Refungible WalletOperator (r:1 w:0)
+	fn is_approved_for_all() -> Weight {
+		Weight::from_ref_time(5_901_000 as u64)
+			.saturating_add(T::DbWeight::get().reads(1 as u64))
+	}
 }
 
 // For backwards compatibility and tests
@@ -463,4 +476,14 @@
 		Weight::from_ref_time(9_431_000)
 			.saturating_add(RocksDbWeight::get().reads(2 as u64))
 	}
+	// Storage: Refungible WalletOperator (r:0 w:1)
+	fn set_approval_for_all() -> Weight {
+		Weight::from_ref_time(16_150_000 as u64)
+			.saturating_add(RocksDbWeight::get().writes(1 as u64))
+	}
+	// Storage: Refungible WalletOperator (r:1 w:0)
+	fn is_approved_for_all() -> Weight {
+		Weight::from_ref_time(5_901_000 as u64)
+			.saturating_add(RocksDbWeight::get().reads(1 as u64))
+	}
 }
modifiedpallets/unique/src/lib.rsdiffbeforeafterboth
--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -1126,6 +1126,28 @@
 				}
 			})
 		}
+
+		/// Sets or unsets the approval of a given operator.
+		///
+		/// An operator is allowed to transfer all tokens of the sender on their behalf.
+		///
+		/// # Arguments
+		///
+		/// * `owner`: Token owner
+		/// * `operator`: Operator
+		/// * `approve`: Is operator enabled or disabled
+		#[weight = T::CommonWeightInfo::set_approval_for_all()]
+		pub fn set_approval_for_all(
+			origin,
+			collection_id: CollectionId,
+			operator: T::CrossAccountId,
+			approve: bool,
+		) -> DispatchResultWithPostInfo {
+			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
+			dispatch_tx::<T, _>(collection_id, |d| {
+				d.set_approval_for_all(sender, operator, approve)
+			})
+		}
 	}
 }
 
modifiedprimitives/rpc/src/lib.rsdiffbeforeafterboth
--- a/primitives/rpc/src/lib.rs
+++ b/primitives/rpc/src/lib.rs
@@ -132,5 +132,8 @@
 		fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Result<Option<u128>>;
 
 		fn token_owners(collection: CollectionId, token: TokenId) -> Result<Vec<CrossAccountId>>;
+
+		/// Get whether an operator is approved by a given owner.
+		fn is_approved_for_all(collection: CollectionId, owner: CrossAccountId, operator: CrossAccountId) -> Result<bool>;
 	}
 }
modifiedruntime/common/runtime_apis.rsdiffbeforeafterboth
--- a/runtime/common/runtime_apis.rs
+++ b/runtime/common/runtime_apis.rs
@@ -187,6 +187,10 @@
                 fn total_pieces(collection: CollectionId, token_id: TokenId) -> Result<Option<u128>, DispatchError> {
                     dispatch_unique_runtime!(collection.total_pieces(token_id))
                 }
+
+		        fn is_approved_for_all(collection: CollectionId, owner: CrossAccountId, operator: CrossAccountId) -> Result<bool, DispatchError> {
+                    dispatch_unique_runtime!(collection.is_approved_for_all(owner, operator))
+                }
             }
 
             impl app_promotion_rpc::AppPromotionApi<Block, BlockNumber, CrossAccountId, AccountId> for Runtime {
modifiedruntime/common/weights.rsdiffbeforeafterboth
--- a/runtime/common/weights.rs
+++ b/runtime/common/weights.rs
@@ -120,6 +120,10 @@
 	fn token_owner() -> Weight {
 		max_weight_of!(token_owner())
 	}
+
+	fn set_approval_for_all() -> Weight {
+		max_weight_of!(set_approval_for_all())
+	}
 }
 
 #[cfg(feature = "refungible")]
modifiedtests/src/approve.test.tsdiffbeforeafterboth
--- a/tests/src/approve.test.ts
+++ b/tests/src/approve.test.ts
@@ -603,3 +603,40 @@
     await expect(approveTx()).to.be.rejected;
   });
 });
+
+describe('Normal user can approve other users to be wallet operator:', () => {
+  let alice: IKeyringPair;
+  let bob: IKeyringPair;
+
+  before(async () => {
+    await usingPlaygrounds(async (helper, privateKey) => {
+      const donor = await privateKey({filename: __filename});
+      [alice, bob] = await helper.arrange.createAccounts([100n, 100n], donor);
+    });
+  });
+
+  itSub('[nft] Enable and disable approval', async ({helper}) => {
+    const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+    await helper.nft.mintToken(alice, {collectionId: collectionId, owner: alice.address});
+    const checkBeforeApprovalTx = () => helper.nft.isApprovedForAll(collectionId, {Substrate: alice.address}, {Substrate: bob.address});
+    expect(await checkBeforeApprovalTx()).to.be.false;
+    await helper.nft.setApprovalForAll(alice, collectionId, {Substrate: bob.address}, true);
+    const checkAfterApprovalTx = () => helper.nft.isApprovedForAll(collectionId, {Substrate: alice.address}, {Substrate: bob.address});
+    expect(await checkAfterApprovalTx()).to.be.true;
+    await helper.nft.setApprovalForAll(alice, collectionId, {Substrate: bob.address}, false);
+    const checkAfterDisapprovalTx = () => helper.nft.isApprovedForAll(collectionId, {Substrate: alice.address}, {Substrate: bob.address});
+    expect(await checkAfterDisapprovalTx()).to.be.false;
+  });
+
+  itSub.ifWithPallets('[rft] Enable and disable approval', [Pallets.ReFungible], async ({helper}) => {
+    const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+    const checkBeforeApprovalTx = () => helper.rft.isApprovedForAll(collectionId, {Substrate: alice.address}, {Substrate: bob.address});
+    expect(await checkBeforeApprovalTx()).to.be.false;
+    await helper.rft.setApprovalForAll(alice, collectionId, {Substrate: bob.address}, true);
+    const checkAfterApprovalTx = () => helper.rft.isApprovedForAll(collectionId, {Substrate: alice.address}, {Substrate: bob.address});
+    expect(await checkAfterApprovalTx()).to.be.true;
+    await helper.rft.setApprovalForAll(alice, collectionId, {Substrate: bob.address}, false);
+    const checkAfterDisapprovalTx = () => helper.rft.isApprovedForAll(collectionId, {Substrate: alice.address}, {Substrate: bob.address});
+    expect(await checkAfterDisapprovalTx()).to.be.false;
+  });
+});
modifiedtests/src/eth/abi/nonFungible.jsondiffbeforeafterboth
--- a/tests/src/eth/abi/nonFungible.json
+++ b/tests/src/eth/abi/nonFungible.json
@@ -384,7 +384,7 @@
       { "internalType": "address", "name": "operator", "type": "address" }
     ],
     "name": "isApprovedForAll",
-    "outputs": [{ "internalType": "address", "name": "", "type": "address" }],
+    "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
     "stateMutability": "view",
     "type": "function"
   },
modifiedtests/src/eth/abi/reFungible.jsondiffbeforeafterboth
--- a/tests/src/eth/abi/reFungible.json
+++ b/tests/src/eth/abi/reFungible.json
@@ -366,7 +366,7 @@
       { "internalType": "address", "name": "operator", "type": "address" }
     ],
     "name": "isApprovedForAll",
-    "outputs": [{ "internalType": "address", "name": "", "type": "address" }],
+    "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
     "stateMutability": "view",
     "type": "function"
   },
modifiedtests/src/eth/api/UniqueNFT.soldiffbeforeafterboth
--- a/tests/src/eth/api/UniqueNFT.sol
+++ b/tests/src/eth/api/UniqueNFT.sol
@@ -671,7 +671,10 @@
 	///  or in textual repr: approve(address,uint256)
 	function approve(address approved, uint256 tokenId) external;
 
-	/// @dev Not implemented
+	/// @notice Sets or unsets the approval of a given operator.
+	///  An operator is allowed to transfer all tokens of the sender on their behalf.
+	/// @param operator Operator
+	/// @param approved Is operator enabled or disabled
 	/// @dev EVM selector for this function is: 0xa22cb465,
 	///  or in textual repr: setApprovalForAll(address,bool)
 	function setApprovalForAll(address operator, bool approved) external;
@@ -681,10 +684,10 @@
 	///  or in textual repr: getApproved(uint256)
 	function getApproved(uint256 tokenId) external view returns (address);
 
-	/// @dev Not implemented
+	/// @notice Tells whether an operator is approved by a given owner.
 	/// @dev EVM selector for this function is: 0xe985e9c5,
 	///  or in textual repr: isApprovedForAll(address,address)
-	function isApprovedForAll(address owner, address operator) external view returns (address);
+	function isApprovedForAll(address owner, address operator) external view returns (bool);
 
 	/// @notice Returns collection helper contract address
 	/// @dev EVM selector for this function is: 0x1896cce6,
modifiedtests/src/eth/api/UniqueRefungible.soldiffbeforeafterboth
--- a/tests/src/eth/api/UniqueRefungible.sol
+++ b/tests/src/eth/api/UniqueRefungible.sol
@@ -668,7 +668,10 @@
 	///  or in textual repr: approve(address,uint256)
 	function approve(address approved, uint256 tokenId) external;
 
-	/// @dev Not implemented
+	/// @notice Sets or unsets the approval of a given operator.
+	///  An operator is allowed to transfer all tokens of the sender on their behalf.
+	/// @param operator Operator
+	/// @param approved Is operator enabled or disabled
 	/// @dev EVM selector for this function is: 0xa22cb465,
 	///  or in textual repr: setApprovalForAll(address,bool)
 	function setApprovalForAll(address operator, bool approved) external;
@@ -678,10 +681,10 @@
 	///  or in textual repr: getApproved(uint256)
 	function getApproved(uint256 tokenId) external view returns (address);
 
-	/// @dev Not implemented
+	/// @notice Tells whether an operator is approved by a given owner.
 	/// @dev EVM selector for this function is: 0xe985e9c5,
 	///  or in textual repr: isApprovedForAll(address,address)
-	function isApprovedForAll(address owner, address operator) external view returns (address);
+	function isApprovedForAll(address owner, address operator) external view returns (bool);
 
 	/// @notice Returns collection helper contract address
 	/// @dev EVM selector for this function is: 0x1896cce6,
modifiedtests/src/eth/nonFungible.test.tsdiffbeforeafterboth
--- a/tests/src/eth/nonFungible.test.ts
+++ b/tests/src/eth/nonFungible.test.ts
@@ -249,6 +249,114 @@
     }
   });
 
+  itEth('Can perform setApprovalForAll()', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const operator = helper.eth.createAccount();
+
+    const collection = await helper.nft.mintCollection(minter, {});
+
+    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
+    const contract = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
+
+    const approvedBefore = await contract.methods.isApprovedForAll(owner, operator).call();
+    expect(approvedBefore).to.be.equal(false);
+
+    {
+      const result = await contract.methods.setApprovalForAll(operator, true).send({from: owner});
+
+      expect(result.events.ApprovalForAll).to.be.like({
+        address: collectionAddress,
+        event: 'ApprovalForAll',
+        returnValues: {
+          owner,
+          operator,
+          approved: true,
+        },
+      });
+
+      const approvedAfter = await contract.methods.isApprovedForAll(owner, operator).call();
+      expect(approvedAfter).to.be.equal(true);
+    }
+
+    {
+      const result = await contract.methods.setApprovalForAll(operator, false).send({from: owner});
+
+      expect(result.events.ApprovalForAll).to.be.like({
+        address: collectionAddress,
+        event: 'ApprovalForAll',
+        returnValues: {
+          owner,
+          operator,
+          approved: false,
+        },
+      });
+
+      const approvedAfter = await contract.methods.isApprovedForAll(owner, operator).call();
+      expect(approvedAfter).to.be.equal(false);
+    }
+  });
+
+  itEth('Can perform burn with ApprovalForAll', async ({helper}) => {
+    const collection = await helper.nft.mintCollection(minter, {name: 'A', description: 'B', tokenPrefix: 'C'});
+
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const operator = await helper.eth.createAccountWithBalance(donor, 100n);
+
+    const token = await collection.mintToken(minter, {Ethereum: owner});
+
+    const address = helper.ethAddress.fromCollectionId(collection.collectionId);
+    const contract = helper.ethNativeContract.collection(address, 'nft');
+
+    {
+      await contract.methods.setApprovalForAll(operator, true).send({from: owner});
+      const ownerCross = helper.ethCrossAccount.fromAddress(owner);
+      const result = await contract.methods.burnFromCross(ownerCross, token.tokenId).send({from: operator});
+      const events = result.events.Transfer;
+
+      expect(events).to.be.like({
+        address,
+        event: 'Transfer',
+        returnValues: {
+          from: owner,
+          to: '0x0000000000000000000000000000000000000000',
+          tokenId: token.tokenId.toString(),
+        },
+      });
+    }
+  });
+  
+  itEth('Can perform transfer with ApprovalForAll', async ({helper}) => {
+    const collection = await helper.nft.mintCollection(minter, {name: 'A', description: 'B', tokenPrefix: 'C'});
+
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const operator = await helper.eth.createAccountWithBalance(donor);
+    const receiver = charlie;
+
+    const token = await collection.mintToken(minter, {Ethereum: owner});
+
+    const address = helper.ethAddress.fromCollectionId(collection.collectionId);
+    const contract = helper.ethNativeContract.collection(address, 'nft');
+
+    {
+      await contract.methods.setApprovalForAll(operator, true).send({from: owner});
+      const ownerCross = helper.ethCrossAccount.fromAddress(owner);
+      const recieverCross = helper.ethCrossAccount.fromKeyringPair(receiver);
+      const result = await contract.methods.transferFromCross(ownerCross, recieverCross, token.tokenId).send({from: operator});
+      const event = result.events.Transfer;
+      expect(event).to.be.like({
+        address: helper.ethAddress.fromCollectionId(collection.collectionId),
+        event: 'Transfer',
+        returnValues: {
+          from: owner,
+          to: helper.address.substrateToEth(receiver.address),
+          tokenId: token.tokenId.toString(),
+        },
+      });
+    }
+
+    expect(await token.getOwner()).to.be.like({Substrate: receiver.address});
+  });
+
   itEth('Can perform burnFromCross()', async ({helper}) => {
     const collection = await helper.nft.mintCollection(minter, {name: 'A', description: 'B', tokenPrefix: 'C'});
     const ownerSub = bob;
@@ -822,3 +930,53 @@
     expect(symbol).to.equal('CHANGE');
   });
 });
+
+describe('Negative tests', () => {
+  let donor: IKeyringPair;
+  let minter: IKeyringPair;
+  let alice: IKeyringPair;
+  let bob: IKeyringPair;
+
+  before(async function() {
+    await usingEthPlaygrounds(async (helper, privateKey) => {
+      donor = await privateKey({filename: __filename});
+      [minter, alice, bob] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+    });
+  });
+
+  itEth('[negative] Cant perform burn without approval', async ({helper}) => {
+    const collection = await helper.nft.mintCollection(minter, {name: 'A', description: 'B', tokenPrefix: 'C'});
+
+    const owner = bob;
+    const spender = await helper.eth.createAccountWithBalance(donor, 100n);
+
+    const token = await collection.mintToken(minter, {Substrate: owner.address});
+
+    const address = helper.ethAddress.fromCollectionId(collection.collectionId);
+    const contract = helper.ethNativeContract.collection(address, 'nft');
+
+    {
+      const ownerCross = helper.ethCrossAccount.fromKeyringPair(owner);
+      await expect(contract.methods.burnFromCross(ownerCross, token.tokenId).send({from: spender})).to.be.rejected;
+    }
+  });
+
+  itEth('[negative] Cant perform transfer without approval', async ({helper}) => {
+    const collection = await helper.nft.mintCollection(minter, {name: 'A', description: 'B', tokenPrefix: 'C'});
+    const owner = bob;
+    const receiver = alice;
+
+    const spender = await helper.eth.createAccountWithBalance(donor, 100n);
+
+    const token = await collection.mintToken(minter, {Substrate: owner.address});
+
+    const address = helper.ethAddress.fromCollectionId(collection.collectionId);
+    const contract = helper.ethNativeContract.collection(address, 'nft');
+
+    {
+      const ownerCross = helper.ethCrossAccount.fromKeyringPair(owner);
+      const recieverCross = helper.ethCrossAccount.fromKeyringPair(receiver);
+      await expect(contract.methods.transferFromCross(ownerCross, recieverCross, token.tokenId).send({from: spender})).to.be.rejected;
+    }
+  });
+});
modifiedtests/src/eth/reFungible.test.tsdiffbeforeafterboth
--- a/tests/src/eth/reFungible.test.ts
+++ b/tests/src/eth/reFungible.test.ts
@@ -169,6 +169,136 @@
     }
   });
 
+  itEth('Can perform setApprovalForAll()', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const operator = helper.eth.createAccount();
+
+    const collection = await helper.rft.mintCollection(minter, {});
+
+    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
+    const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', owner);
+
+    const approvedBefore = await contract.methods.isApprovedForAll(owner, operator).call();
+    expect(approvedBefore).to.be.equal(false);
+
+    {
+      const result = await contract.methods.setApprovalForAll(operator, true).send({from: owner});
+
+      expect(result.events.ApprovalForAll).to.be.like({
+        address: collectionAddress,
+        event: 'ApprovalForAll',
+        returnValues: {
+          owner,
+          operator,
+          approved: true,
+        },
+      });
+
+      const approvedAfter = await contract.methods.isApprovedForAll(owner, operator).call();
+      expect(approvedAfter).to.be.equal(true);
+    }
+
+    {
+      const result = await contract.methods.setApprovalForAll(operator, false).send({from: owner});
+
+      expect(result.events.ApprovalForAll).to.be.like({
+        address: collectionAddress,
+        event: 'ApprovalForAll',
+        returnValues: {
+          owner,
+          operator,
+          approved: false,
+        },
+      });
+
+      const approvedAfter = await contract.methods.isApprovedForAll(owner, operator).call();
+      expect(approvedAfter).to.be.equal(false);
+    }
+  });
+
+  itEth('Can perform burn with ApprovalForAll', async ({helper}) => {
+    const collection = await helper.rft.mintCollection(minter, {name: 'A', description: 'B', tokenPrefix: 'C'});
+
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const operator = await helper.eth.createAccountWithBalance(donor, 100n);
+
+    const token = await collection.mintToken(minter, 100n, {Ethereum: owner});
+
+    const address = helper.ethAddress.fromCollectionId(collection.collectionId);
+    const contract = helper.ethNativeContract.collection(address, 'rft');
+
+    {
+      await contract.methods.setApprovalForAll(operator, true).send({from: owner});
+      const ownerCross = helper.ethCrossAccount.fromAddress(owner);
+      const result = await contract.methods.burnFromCross(ownerCross, token.tokenId).send({from: operator});
+      const events = result.events.Transfer;
+
+      expect(events).to.be.like({
+        address,
+        event: 'Transfer',
+        returnValues: {
+          from: owner,
+          to: '0x0000000000000000000000000000000000000000',
+          tokenId: token.tokenId.toString(),
+        },
+      });
+    }
+  });
+
+  itEth('Can perform burn with approve and approvalForAll', async ({helper}) => {
+    const collection = await helper.rft.mintCollection(minter, {name: 'A', description: 'B', tokenPrefix: 'C'});
+
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const operator = await helper.eth.createAccountWithBalance(donor, 100n);
+
+    const token = await collection.mintToken(minter, 100n, {Ethereum: owner});
+
+    const address = helper.ethAddress.fromCollectionId(collection.collectionId);
+    const contract = helper.ethNativeContract.collection(address, 'rft');
+
+    const rftToken = helper.ethNativeContract.rftTokenById(token.collectionId, token.tokenId, owner);
+
+    {
+      await rftToken.methods.approve(operator, 15n).send({from: owner});
+      await contract.methods.setApprovalForAll(operator, true).send({from: owner});
+      await rftToken.methods.burnFrom(owner, 10n).send({from: operator});
+      const allowance = await rftToken.methods.allowance(owner, operator).call();
+      expect(allowance).to.be.equal('5');
+    }
+  });
+  
+  itEth('Can perform transfer with ApprovalForAll', async ({helper}) => {
+    const collection = await helper.rft.mintCollection(minter, {name: 'A', description: 'B', tokenPrefix: 'C'});
+
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const operator = await helper.eth.createAccountWithBalance(donor);
+    const receiver = charlie;
+
+    const token = await collection.mintToken(minter, 100n, {Ethereum: owner});
+
+    const address = helper.ethAddress.fromCollectionId(collection.collectionId);
+    const contract = helper.ethNativeContract.collection(address, 'rft');
+
+    {
+      await contract.methods.setApprovalForAll(operator, true).send({from: owner});
+      const ownerCross = helper.ethCrossAccount.fromAddress(owner);
+      const recieverCross = helper.ethCrossAccount.fromKeyringPair(receiver);
+      const result = await contract.methods.transferFromCross(ownerCross, recieverCross, token.tokenId).send({from: operator});
+      const event = result.events.Transfer;
+      expect(event).to.be.like({
+        address: helper.ethAddress.fromCollectionId(collection.collectionId),
+        event: 'Transfer',
+        returnValues: {
+          from: owner,
+          to: helper.address.substrateToEth(receiver.address),
+          tokenId: token.tokenId.toString(),
+        },
+      });
+    }
+
+    expect(await token.getTop10Owners()).to.be.like([{Substrate: receiver.address}]);
+  });
+
   itEth('Can perform burn()', async ({helper}) => {
     const caller = await helper.eth.createAccountWithBalance(donor);
     const {collectionAddress} = await helper.eth.createRFTCollection(caller, 'Burny', '6', '6');
@@ -594,3 +724,52 @@
     expect(symbol).to.equal('12');
   });
 });
+
+describe('Negative tests', () => {
+  let donor: IKeyringPair;
+  let minter: IKeyringPair;
+  let alice: IKeyringPair;
+
+  before(async function() {
+    await usingEthPlaygrounds(async (helper, privateKey) => {
+      donor = await privateKey({filename: __filename});
+      [minter, alice] = await helper.arrange.createAccounts([100n, 100n], donor);
+    });
+  });
+
+  itEth('[negative] Cant perform burn without approval', async ({helper}) => {
+    const collection = await helper.rft.mintCollection(minter, {name: 'A', description: 'B', tokenPrefix: 'C'});
+
+    const owner = await helper.eth.createAccountWithBalance(donor, 100n);
+    const spender = await helper.eth.createAccountWithBalance(donor, 100n);
+
+    const token = await collection.mintToken(minter, 100n, {Ethereum: owner});
+
+    const address = helper.ethAddress.fromCollectionId(collection.collectionId);
+    const contract = helper.ethNativeContract.collection(address, 'rft');
+
+    {
+      const ownerCross = helper.ethCrossAccount.fromAddress(owner);
+      await expect(contract.methods.burnFromCross(ownerCross, token.tokenId).send({from: spender})).to.be.rejected;
+    }
+  });
+
+  itEth('[negative] Cant perform transfer without approval', async ({helper}) => {
+    const collection = await helper.rft.mintCollection(minter, {name: 'A', description: 'B', tokenPrefix: 'C'});
+    const owner = await helper.eth.createAccountWithBalance(donor, 100n);
+    const receiver = alice;
+
+    const spender = await helper.eth.createAccountWithBalance(donor, 100n);
+
+    const token = await collection.mintToken(minter, 100n, {Ethereum: owner});
+
+    const address = helper.ethAddress.fromCollectionId(collection.collectionId);
+    const contract = helper.ethNativeContract.collection(address, 'rft');
+
+    {
+      const ownerCross = helper.ethCrossAccount.fromAddress(owner);
+      const recieverCross = helper.ethCrossAccount.fromKeyringPair(receiver);
+      await expect(contract.methods.transferFromCross(ownerCross, recieverCross, token.tokenId).send({from: spender})).to.be.rejected;
+    }
+  });
+});
modifiedtests/src/interfaces/augment-api-errors.tsdiffbeforeafterboth
--- a/tests/src/interfaces/augment-api-errors.ts
+++ b/tests/src/interfaces/augment-api-errors.ts
@@ -386,6 +386,10 @@
        **/
       NotFungibleDataUsedToMintFungibleCollectionToken: AugmentedError<ApiType>;
       /**
+       * Setting approval for all is not allowed.
+       **/
+      SettingApprovalForAllNotAllowed: AugmentedError<ApiType>;
+      /**
        * Setting item properties is not allowed.
        **/
       SettingPropertiesNotAllowed: AugmentedError<ApiType>;
modifiedtests/src/interfaces/augment-api-events.tsdiffbeforeafterboth
--- a/tests/src/interfaces/augment-api-events.ts
+++ b/tests/src/interfaces/augment-api-events.ts
@@ -107,6 +107,10 @@
        **/
       Approved: AugmentedEvent<ApiType, [u32, u32, PalletEvmAccountBasicCrossAccountIdRepr, PalletEvmAccountBasicCrossAccountIdRepr, u128]>;
       /**
+       * Amount pieces of token owned by `sender` was approved for `spender`.
+       **/
+      ApprovedForAll: AugmentedEvent<ApiType, [u32, PalletEvmAccountBasicCrossAccountIdRepr, PalletEvmAccountBasicCrossAccountIdRepr, bool]>;
+      /**
        * New collection was created
        **/
       CollectionCreated: AugmentedEvent<ApiType, [u32, u8, AccountId32]>;
modifiedtests/src/interfaces/augment-api-query.tsdiffbeforeafterboth
--- a/tests/src/interfaces/augment-api-query.ts
+++ b/tests/src/interfaces/augment-api-query.ts
@@ -442,6 +442,10 @@
        **/
       tokensMinted: AugmentedQuery<ApiType, (arg: u32 | AnyNumber | Uint8Array) => Observable<u32>, [u32]> & QueryableStorageEntry<ApiType, [u32]>;
       /**
+       * Operator set by a wallet owner that could perform certain transactions on all tokens in the wallet.
+       **/
+      walletOperator: AugmentedQuery<ApiType, (arg1: u32 | AnyNumber | Uint8Array, arg2: PalletEvmAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, arg3: PalletEvmAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array) => Observable<Option<bool>>, [u32, PalletEvmAccountBasicCrossAccountIdRepr, PalletEvmAccountBasicCrossAccountIdRepr]> & QueryableStorageEntry<ApiType, [u32, PalletEvmAccountBasicCrossAccountIdRepr, PalletEvmAccountBasicCrossAccountIdRepr]>;
+      /**
        * Generic query
        **/
       [key: string]: QueryableStorageEntry<ApiType>;
@@ -645,6 +649,10 @@
        **/
       totalSupply: AugmentedQuery<ApiType, (arg1: u32 | AnyNumber | Uint8Array, arg2: u32 | AnyNumber | Uint8Array) => Observable<u128>, [u32, u32]> & QueryableStorageEntry<ApiType, [u32, u32]>;
       /**
+       * Operator set by a wallet owner that could perform certain transactions on all tokens in the wallet.
+       **/
+      walletOperator: AugmentedQuery<ApiType, (arg1: u32 | AnyNumber | Uint8Array, arg2: PalletEvmAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, arg3: PalletEvmAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array) => Observable<Option<bool>>, [u32, PalletEvmAccountBasicCrossAccountIdRepr, PalletEvmAccountBasicCrossAccountIdRepr]> & QueryableStorageEntry<ApiType, [u32, PalletEvmAccountBasicCrossAccountIdRepr, PalletEvmAccountBasicCrossAccountIdRepr]>;
+      /**
        * Generic query
        **/
       [key: string]: QueryableStorageEntry<ApiType>;
modifiedtests/src/interfaces/augment-api-rpc.tsdiffbeforeafterboth
--- a/tests/src/interfaces/augment-api-rpc.ts
+++ b/tests/src/interfaces/augment-api-rpc.ts
@@ -720,6 +720,10 @@
        **/
       effectiveCollectionLimits: AugmentedRpc<(collection: u32 | AnyNumber | Uint8Array, at?: Hash | string | Uint8Array) => Observable<Option<UpDataStructsCollectionLimits>>>;
       /**
+       * Tells whether an operator is approved by a given owner.
+       **/
+      isApprovedForAll: AugmentedRpc<(collection: u32 | AnyNumber | Uint8Array, owner: PalletEvmAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, operator: PalletEvmAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, at?: Hash | string | Uint8Array) => Observable<Option<bool>>>;
+      /**
        * Get the last token ID created in a collection
        **/
       lastTokenId: AugmentedRpc<(collection: u32 | AnyNumber | Uint8Array, at?: Hash | string | Uint8Array) => Observable<u32>>;
modifiedtests/src/interfaces/augment-api-tx.tsdiffbeforeafterboth
--- a/tests/src/interfaces/augment-api-tx.ts
+++ b/tests/src/interfaces/augment-api-tx.ts
@@ -1545,6 +1545,18 @@
        **/
       repartition: AugmentedSubmittable<(collectionId: u32 | AnyNumber | Uint8Array, tokenId: u32 | AnyNumber | Uint8Array, amount: u128 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32, u32, u128]>;
       /**
+       * Sets or unsets the approval of a given operator.
+       * 
+       * An operator is allowed to transfer all tokens of the sender on their behalf.
+       * 
+       * # Arguments
+       * 
+       * * `owner`: Token owner
+       * * `operator`: Operator
+       * * `approve`: Is operator enabled or disabled
+       **/
+      setApprovalForAll: AugmentedSubmittable<(collectionId: u32 | AnyNumber | Uint8Array, operator: PalletEvmAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, approve: bool | boolean | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32, PalletEvmAccountBasicCrossAccountIdRepr, bool]>;
+      /**
        * Set specific limits of a collection. Empty, or None fields mean chain default.
        * 
        * # Permissions
modifiedtests/src/interfaces/default/types.tsdiffbeforeafterboth
--- a/tests/src/interfaces/default/types.ts
+++ b/tests/src/interfaces/default/types.ts
@@ -1286,6 +1286,8 @@
   readonly asTransfer: ITuple<[u32, u32, PalletEvmAccountBasicCrossAccountIdRepr, PalletEvmAccountBasicCrossAccountIdRepr, u128]>;
   readonly isApproved: boolean;
   readonly asApproved: ITuple<[u32, u32, PalletEvmAccountBasicCrossAccountIdRepr, PalletEvmAccountBasicCrossAccountIdRepr, u128]>;
+  readonly isApprovedForAll: boolean;
+  readonly asApprovedForAll: ITuple<[u32, PalletEvmAccountBasicCrossAccountIdRepr, PalletEvmAccountBasicCrossAccountIdRepr, bool]>;
   readonly isCollectionPropertySet: boolean;
   readonly asCollectionPropertySet: ITuple<[u32, Bytes]>;
   readonly isCollectionPropertyDeleted: boolean;
@@ -1296,7 +1298,7 @@
   readonly asTokenPropertyDeleted: ITuple<[u32, u32, Bytes]>;
   readonly isPropertyPermissionSet: boolean;
   readonly asPropertyPermissionSet: ITuple<[u32, Bytes]>;
-  readonly type: 'CollectionCreated' | 'CollectionDestroyed' | 'ItemCreated' | 'ItemDestroyed' | 'Transfer' | 'Approved' | 'CollectionPropertySet' | 'CollectionPropertyDeleted' | 'TokenPropertySet' | 'TokenPropertyDeleted' | 'PropertyPermissionSet';
+  readonly type: 'CollectionCreated' | 'CollectionDestroyed' | 'ItemCreated' | 'ItemDestroyed' | 'Transfer' | 'Approved' | 'ApprovedForAll' | 'CollectionPropertySet' | 'CollectionPropertyDeleted' | 'TokenPropertySet' | 'TokenPropertyDeleted' | 'PropertyPermissionSet';
 }
 
 /** @name PalletConfigurationCall */
@@ -1603,7 +1605,8 @@
   readonly isFungibleItemsDontHaveData: boolean;
   readonly isFungibleDisallowsNesting: boolean;
   readonly isSettingPropertiesNotAllowed: boolean;
-  readonly type: 'NotFungibleDataUsedToMintFungibleCollectionToken' | 'FungibleItemsHaveNoId' | 'FungibleItemsDontHaveData' | 'FungibleDisallowsNesting' | 'SettingPropertiesNotAllowed';
+  readonly isSettingApprovalForAllNotAllowed: boolean;
+  readonly type: 'NotFungibleDataUsedToMintFungibleCollectionToken' | 'FungibleItemsHaveNoId' | 'FungibleItemsDontHaveData' | 'FungibleDisallowsNesting' | 'SettingPropertiesNotAllowed' | 'SettingApprovalForAllNotAllowed';
 }
 
 /** @name PalletInflationCall */
@@ -2309,7 +2312,13 @@
     readonly tokenId: u32;
     readonly amount: u128;
   } & Struct;
-  readonly type: 'CreateCollection' | 'CreateCollectionEx' | 'DestroyCollection' | 'AddToAllowList' | 'RemoveFromAllowList' | 'ChangeCollectionOwner' | 'AddCollectionAdmin' | 'RemoveCollectionAdmin' | 'SetCollectionSponsor' | 'ConfirmSponsorship' | 'RemoveCollectionSponsor' | 'CreateItem' | 'CreateMultipleItems' | 'SetCollectionProperties' | 'DeleteCollectionProperties' | 'SetTokenProperties' | 'DeleteTokenProperties' | 'SetTokenPropertyPermissions' | 'CreateMultipleItemsEx' | 'SetTransfersEnabledFlag' | 'BurnItem' | 'BurnFrom' | 'Transfer' | 'Approve' | 'TransferFrom' | 'SetCollectionLimits' | 'SetCollectionPermissions' | 'Repartition';
+  readonly isSetApprovalForAll: boolean;
+  readonly asSetApprovalForAll: {
+    readonly collectionId: u32;
+    readonly operator: PalletEvmAccountBasicCrossAccountIdRepr;
+    readonly approve: bool;
+  } & Struct;
+  readonly type: 'CreateCollection' | 'CreateCollectionEx' | 'DestroyCollection' | 'AddToAllowList' | 'RemoveFromAllowList' | 'ChangeCollectionOwner' | 'AddCollectionAdmin' | 'RemoveCollectionAdmin' | 'SetCollectionSponsor' | 'ConfirmSponsorship' | 'RemoveCollectionSponsor' | 'CreateItem' | 'CreateMultipleItems' | 'SetCollectionProperties' | 'DeleteCollectionProperties' | 'SetTokenProperties' | 'DeleteTokenProperties' | 'SetTokenPropertyPermissions' | 'CreateMultipleItemsEx' | 'SetTransfersEnabledFlag' | 'BurnItem' | 'BurnFrom' | 'Transfer' | 'Approve' | 'TransferFrom' | 'SetCollectionLimits' | 'SetCollectionPermissions' | 'Repartition' | 'SetApprovalForAll';
 }
 
 /** @name PalletUniqueError */
modifiedtests/src/interfaces/lookup.tsdiffbeforeafterboth
--- a/tests/src/interfaces/lookup.ts
+++ b/tests/src/interfaces/lookup.ts
@@ -1046,6 +1046,7 @@
       ItemDestroyed: '(u32,u32,PalletEvmAccountBasicCrossAccountIdRepr,u128)',
       Transfer: '(u32,u32,PalletEvmAccountBasicCrossAccountIdRepr,PalletEvmAccountBasicCrossAccountIdRepr,u128)',
       Approved: '(u32,u32,PalletEvmAccountBasicCrossAccountIdRepr,PalletEvmAccountBasicCrossAccountIdRepr,u128)',
+      ApprovedForAll: '(u32,PalletEvmAccountBasicCrossAccountIdRepr,PalletEvmAccountBasicCrossAccountIdRepr,bool)',
       CollectionPropertySet: '(u32,Bytes)',
       CollectionPropertyDeleted: '(u32,Bytes)',
       TokenPropertySet: '(u32,u32,Bytes)',
@@ -1054,7 +1055,7 @@
     }
   },
   /**
-   * Lookup99: pallet_structure::pallet::Event<T>
+   * Lookup100: pallet_structure::pallet::Event<T>
    **/
   PalletStructureEvent: {
     _enum: {
@@ -1062,7 +1063,7 @@
     }
   },
   /**
-   * Lookup100: pallet_rmrk_core::pallet::Event<T>
+   * Lookup101: pallet_rmrk_core::pallet::Event<T>
    **/
   PalletRmrkCoreEvent: {
     _enum: {
@@ -1139,7 +1140,7 @@
     }
   },
   /**
-   * Lookup101: rmrk_traits::nft::AccountIdOrCollectionNftTuple<sp_core::crypto::AccountId32>
+   * Lookup102: rmrk_traits::nft::AccountIdOrCollectionNftTuple<sp_core::crypto::AccountId32>
    **/
   RmrkTraitsNftAccountIdOrCollectionNftTuple: {
     _enum: {
@@ -2302,7 +2303,12 @@
       repartition: {
         collectionId: 'u32',
         tokenId: 'u32',
-        amount: 'u128'
+        amount: 'u128',
+      },
+      set_approval_for_all: {
+        collectionId: 'u32',
+        operator: 'PalletEvmAccountBasicCrossAccountIdRepr',
+        approve: 'bool'
       }
     }
   },
@@ -3445,7 +3451,7 @@
    * Lookup430: pallet_fungible::pallet::Error<T>
    **/
   PalletFungibleError: {
-    _enum: ['NotFungibleDataUsedToMintFungibleCollectionToken', 'FungibleItemsHaveNoId', 'FungibleItemsDontHaveData', 'FungibleDisallowsNesting', 'SettingPropertiesNotAllowed']
+    _enum: ['NotFungibleDataUsedToMintFungibleCollectionToken', 'FungibleItemsHaveNoId', 'FungibleItemsDontHaveData', 'FungibleDisallowsNesting', 'SettingPropertiesNotAllowed', 'SettingApprovalForAllNotAllowed']
   },
   /**
    * Lookup431: pallet_refungible::ItemData
modifiedtests/src/interfaces/types-lookup.tsdiffbeforeafterboth
--- a/tests/src/interfaces/types-lookup.ts
+++ b/tests/src/interfaces/types-lookup.ts
@@ -1182,6 +1182,8 @@
     readonly asTransfer: ITuple<[u32, u32, PalletEvmAccountBasicCrossAccountIdRepr, PalletEvmAccountBasicCrossAccountIdRepr, u128]>;
     readonly isApproved: boolean;
     readonly asApproved: ITuple<[u32, u32, PalletEvmAccountBasicCrossAccountIdRepr, PalletEvmAccountBasicCrossAccountIdRepr, u128]>;
+    readonly isApprovedForAll: boolean;
+    readonly asApprovedForAll: ITuple<[u32, PalletEvmAccountBasicCrossAccountIdRepr, PalletEvmAccountBasicCrossAccountIdRepr, bool]>;
     readonly isCollectionPropertySet: boolean;
     readonly asCollectionPropertySet: ITuple<[u32, Bytes]>;
     readonly isCollectionPropertyDeleted: boolean;
@@ -1192,17 +1194,17 @@
     readonly asTokenPropertyDeleted: ITuple<[u32, u32, Bytes]>;
     readonly isPropertyPermissionSet: boolean;
     readonly asPropertyPermissionSet: ITuple<[u32, Bytes]>;
-    readonly type: 'CollectionCreated' | 'CollectionDestroyed' | 'ItemCreated' | 'ItemDestroyed' | 'Transfer' | 'Approved' | 'CollectionPropertySet' | 'CollectionPropertyDeleted' | 'TokenPropertySet' | 'TokenPropertyDeleted' | 'PropertyPermissionSet';
+    readonly type: 'CollectionCreated' | 'CollectionDestroyed' | 'ItemCreated' | 'ItemDestroyed' | 'Transfer' | 'Approved' | 'ApprovedForAll' | 'CollectionPropertySet' | 'CollectionPropertyDeleted' | 'TokenPropertySet' | 'TokenPropertyDeleted' | 'PropertyPermissionSet';
   }
 
-  /** @name PalletStructureEvent (99) */
+  /** @name PalletStructureEvent (100) */
   interface PalletStructureEvent extends Enum {
     readonly isExecuted: boolean;
     readonly asExecuted: Result<Null, SpRuntimeDispatchError>;
     readonly type: 'Executed';
   }
 
-  /** @name PalletRmrkCoreEvent (100) */
+  /** @name PalletRmrkCoreEvent (101) */
   interface PalletRmrkCoreEvent extends Enum {
     readonly isCollectionCreated: boolean;
     readonly asCollectionCreated: {
@@ -1292,7 +1294,7 @@
     readonly type: 'CollectionCreated' | 'CollectionDestroyed' | 'IssuerChanged' | 'CollectionLocked' | 'NftMinted' | 'NftBurned' | 'NftSent' | 'NftAccepted' | 'NftRejected' | 'PropertySet' | 'ResourceAdded' | 'ResourceRemoval' | 'ResourceAccepted' | 'ResourceRemovalAccepted' | 'PrioritySet';
   }
 
-  /** @name RmrkTraitsNftAccountIdOrCollectionNftTuple (101) */
+  /** @name RmrkTraitsNftAccountIdOrCollectionNftTuple (102) */
   interface RmrkTraitsNftAccountIdOrCollectionNftTuple extends Enum {
     readonly isAccountId: boolean;
     readonly asAccountId: AccountId32;
@@ -2539,7 +2541,13 @@
       readonly tokenId: u32;
       readonly amount: u128;
     } & Struct;
-    readonly type: 'CreateCollection' | 'CreateCollectionEx' | 'DestroyCollection' | 'AddToAllowList' | 'RemoveFromAllowList' | 'ChangeCollectionOwner' | 'AddCollectionAdmin' | 'RemoveCollectionAdmin' | 'SetCollectionSponsor' | 'ConfirmSponsorship' | 'RemoveCollectionSponsor' | 'CreateItem' | 'CreateMultipleItems' | 'SetCollectionProperties' | 'DeleteCollectionProperties' | 'SetTokenProperties' | 'DeleteTokenProperties' | 'SetTokenPropertyPermissions' | 'CreateMultipleItemsEx' | 'SetTransfersEnabledFlag' | 'BurnItem' | 'BurnFrom' | 'Transfer' | 'Approve' | 'TransferFrom' | 'SetCollectionLimits' | 'SetCollectionPermissions' | 'Repartition';
+    readonly isSetApprovalForAll: boolean;
+    readonly asSetApprovalForAll: {
+      readonly collectionId: u32;
+      readonly operator: PalletEvmAccountBasicCrossAccountIdRepr;
+      readonly approve: bool;
+    } & Struct;
+    readonly type: 'CreateCollection' | 'CreateCollectionEx' | 'DestroyCollection' | 'AddToAllowList' | 'RemoveFromAllowList' | 'ChangeCollectionOwner' | 'AddCollectionAdmin' | 'RemoveCollectionAdmin' | 'SetCollectionSponsor' | 'ConfirmSponsorship' | 'RemoveCollectionSponsor' | 'CreateItem' | 'CreateMultipleItems' | 'SetCollectionProperties' | 'DeleteCollectionProperties' | 'SetTokenProperties' | 'DeleteTokenProperties' | 'SetTokenPropertyPermissions' | 'CreateMultipleItemsEx' | 'SetTransfersEnabledFlag' | 'BurnItem' | 'BurnFrom' | 'Transfer' | 'Approve' | 'TransferFrom' | 'SetCollectionLimits' | 'SetCollectionPermissions' | 'Repartition' | 'SetApprovalForAll';
   }
 
   /** @name UpDataStructsCollectionMode (240) */
@@ -3655,7 +3663,8 @@
     readonly isFungibleItemsDontHaveData: boolean;
     readonly isFungibleDisallowsNesting: boolean;
     readonly isSettingPropertiesNotAllowed: boolean;
-    readonly type: 'NotFungibleDataUsedToMintFungibleCollectionToken' | 'FungibleItemsHaveNoId' | 'FungibleItemsDontHaveData' | 'FungibleDisallowsNesting' | 'SettingPropertiesNotAllowed';
+    readonly isSettingApprovalForAllNotAllowed: boolean;
+    readonly type: 'NotFungibleDataUsedToMintFungibleCollectionToken' | 'FungibleItemsHaveNoId' | 'FungibleItemsDontHaveData' | 'FungibleDisallowsNesting' | 'SettingPropertiesNotAllowed' | 'SettingApprovalForAllNotAllowed';
   }
 
   /** @name PalletRefungibleItemData (431) */
modifiedtests/src/interfaces/unique/definitions.tsdiffbeforeafterboth
--- a/tests/src/interfaces/unique/definitions.ts
+++ b/tests/src/interfaces/unique/definitions.ts
@@ -175,5 +175,10 @@
       [collectionParam, tokenParam], 
       'Option<u128>',
     ),
+    isApprovedForAll: fun(
+      'Tells whether an operator is approved by a given owner.', 
+      [collectionParam, crossAccountParam('owner'), crossAccountParam('operator')], 
+      'Option<bool>',
+    ),
   },
 };
modifiedtests/src/util/playgrounds/unique.tsdiffbeforeafterboth
--- a/tests/src/util/playgrounds/unique.ts
+++ b/tests/src/util/playgrounds/unique.ts
@@ -1413,6 +1413,32 @@
   getTokenObject(_collectionId: number, _tokenId: number): any {
     return null;
   }
+
+  /**
+   * Tells whether an operator is approved by a given owner.
+   * @param collectionId ID of collection
+   * @param owner owner address
+	 * @param operator operator addrees
+   * @returns true if operator is enabled
+   */
+  async isApprovedForAll(collectionId: number, owner: ICrossAccountId, operator: ICrossAccountId): Promise<boolean> {
+    return (await this.helper.callRpc('api.rpc.unique.isApprovedForAll', [collectionId, owner, operator])).toJSON();
+  }
+
+  /** Sets or unsets the approval of a given operator.
+	 *  An operator is allowed to transfer all tokens of the sender on their behalf.
+	 *  @param operator Operator
+	 *  @param approved Is operator enabled or disabled
+   *  @returns ```true``` if extrinsic success, otherwise ```false```
+   */
+  async setApprovalForAll(signer: TSigner, collectionId: number, operator: ICrossAccountId, approved: boolean): Promise<boolean> {
+    const result = await this.helper.executeExtrinsic(
+      signer,
+      'api.tx.unique.setApprovalForAll', [collectionId, operator, approved],
+      true,
+    );
+    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'ApprovedForAll');
+  }
 }