git.delta.rocks / unique-network / refs/commits / 20ac01d2fe7c

difftreelog

feat eth all-in-one create_collection (#971)

Gregory Simonov2023-08-16parent: #950d276.patch.diff
in: master
* feat: setNesting api change

* fix: change restricted collections to addresses instead of ids

* feat: all in one create collection method

* fix: code review requests

* feat: use struct for create_collection flags

* fix: update evm-coder dependency

* fix: code review requests

* fix: change pending_sponsor to optional cross address

* feat: forbid user from using flags

* refactor: deduplicate CollectionFlags struct

* fix: eth CollectionMode should be NFT

* style: fix clippy warning

* fix: disable eth create_collection

---------

67 files changed

modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2646,8 +2646,8 @@
 
 [[package]]
 name = "evm-coder"
-version = "0.3.1"
-source = "git+https://github.com/uniquenetwork/evm-coder?tag=v0.3.1#21e61c627f71337d6b8a03899fe8de14bfbf67aa"
+version = "0.3.6"
+source = "git+https://github.com/uniquenetwork/evm-coder?tag=v0.3.6#be59ae41a5d2ec9389bae22d54f81122b6ba55a4"
 dependencies = [
  "ethereum",
  "evm-coder-procedural",
@@ -2658,8 +2658,8 @@
 
 [[package]]
 name = "evm-coder-procedural"
-version = "0.3.1"
-source = "git+https://github.com/uniquenetwork/evm-coder?tag=v0.3.1#21e61c627f71337d6b8a03899fe8de14bfbf67aa"
+version = "0.3.6"
+source = "git+https://github.com/uniquenetwork/evm-coder?tag=v0.3.6#be59ae41a5d2ec9389bae22d54f81122b6ba55a4"
 dependencies = [
  "Inflector",
  "hex",
@@ -6489,6 +6489,7 @@
 name = "pallet-common"
 version = "0.1.14"
 dependencies = [
+ "bondrewd",
  "ethereum",
  "evm-coder",
  "frame-benchmarking",
@@ -7530,6 +7531,7 @@
  "frame-benchmarking",
  "frame-support",
  "frame-system",
+ "log",
  "pallet-balances-adapter",
  "pallet-common",
  "pallet-evm",
@@ -14097,6 +14099,7 @@
 dependencies = [
  "bondrewd",
  "derivative",
+ "evm-coder",
  "frame-support",
  "pallet-evm",
  "parity-scale-codec",
modifiedCargo.tomldiffbeforeafterboth
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -27,7 +27,7 @@
 [workspace.dependencies]
 # Unique
 app-promotion-rpc = { path = "primitives/app_promotion_rpc", default-features = false }
-evm-coder = { git = "https://github.com/uniquenetwork/evm-coder", tag = "v0.3.1", default-features = false }
+evm-coder = { git = "https://github.com/uniquenetwork/evm-coder", tag = "v0.3.6", default-features = false, features = ['bondrewd'] }
 pallet-app-promotion = { path = "pallets/app-promotion", default-features = false }
 pallet-balances-adapter = { default-features = false, path = "pallets/balances-adapter" }
 pallet-charge-transaction = { package = "pallet-template-transaction-payment", default-features = false, git = "https://github.com/uniquenetwork/pallet-sponsoring", branch = "polkadot-v0.9.43" }
modifiedpallets/common/Cargo.tomldiffbeforeafterboth
--- a/pallets/common/Cargo.toml
+++ b/pallets/common/Cargo.toml
@@ -10,6 +10,7 @@
 
 scale-info = { workspace = true }
 
+bondrewd = { version = "0.1.14", features = ["derive"], default-features = false }
 ethereum = { workspace = true }
 evm-coder = { workspace = true }
 frame-benchmarking = { workspace = true, optional = true }
modifiedpallets/common/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/common/src/benchmarking.rs
+++ b/pallets/common/src/benchmarking.rs
@@ -21,10 +21,9 @@
 use pallet_evm::account::CrossAccountId;
 use frame_benchmarking::{benchmarks, account};
 use up_data_structs::{
-	CollectionMode, CollectionFlags, CreateCollectionData, CollectionId, Property, PropertyKey,
-	PropertyValue, CollectionPermissions, NestingPermissions, AccessMode,
-	MAX_COLLECTION_NAME_LENGTH, MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH,
-	MAX_PROPERTIES_PER_ITEM,
+	CollectionMode, CreateCollectionData, CollectionId, Property, PropertyKey, PropertyValue,
+	CollectionPermissions, NestingPermissions, AccessMode, MAX_COLLECTION_NAME_LENGTH,
+	MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH, MAX_PROPERTIES_PER_ITEM,
 };
 use frame_support::{
 	traits::{Get, fungible::Balanced, Imbalance, tokens::Precision},
@@ -47,12 +46,7 @@
 		.unwrap()
 }
 pub fn create_var_data<const S: u32>(size: u32) -> BoundedVec<u8, ConstU32<S>> {
-	assert!(
-		size <= S,
-		"size ({}) should be less within bound ({})",
-		size,
-		S
-	);
+	assert!(size <= S, "size ({size}) should be less within bound ({S})",);
 	(0..size)
 		.map(|v| (v & 0xff) as u8)
 		.collect::<Vec<_>>()
@@ -81,7 +75,7 @@
 	mode: CollectionMode,
 	handler: impl FnOnce(
 		T::CrossAccountId,
-		CreateCollectionData<T::AccountId>,
+		CreateCollectionData<T::CrossAccountId>,
 	) -> Result<CollectionId, DispatchError>,
 	cast: impl FnOnce(CollectionHandle<T>) -> R,
 ) -> Result<R, DispatchError> {
@@ -124,9 +118,7 @@
 	create_collection_raw(
 		owner,
 		CollectionMode::NFT,
-		|owner: T::CrossAccountId, data| {
-			<Pallet<T>>::init_collection(owner.clone(), owner, data, CollectionFlags::default())
-		},
+		|owner: T::CrossAccountId, data| <Pallet<T>>::init_collection(owner.clone(), owner, data),
 		|h| h,
 	)
 }
modifiedpallets/common/src/dispatch.rsdiffbeforeafterboth
--- a/pallets/common/src/dispatch.rs
+++ b/pallets/common/src/dispatch.rs
@@ -9,7 +9,7 @@
 	traits::Get,
 };
 use sp_runtime::DispatchError;
-use up_data_structs::{CollectionId, CreateCollectionData, CollectionFlags};
+use up_data_structs::{CollectionId, CreateCollectionData};
 
 use crate::{pallet::Config, CommonCollectionOperations};
 
@@ -76,8 +76,7 @@
 	fn create(
 		sender: T::CrossAccountId,
 		payer: T::CrossAccountId,
-		data: CreateCollectionData<T::AccountId>,
-		flags: CollectionFlags,
+		data: CreateCollectionData<T::CrossAccountId>,
 	) -> Result<CollectionId, DispatchError>;
 
 	/// Delete the collection.
modifiedpallets/common/src/erc.rsdiffbeforeafterboth
--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -402,10 +402,44 @@
 		Ok(())
 	}
 
+	#[solidity(rename_selector = "setCollectionNesting")]
+	fn set_nesting(
+		&mut self,
+		caller: Caller,
+		collection_nesting_and_permissions: eth::CollectionNestingAndPermission,
+	) -> Result<()> {
+		self.consume_store_reads_and_writes(1, 1)?;
+
+		let caller = T::CrossAccountId::from_eth(caller);
+
+		let mut permissions = self.collection.permissions.clone();
+		let mut nesting = permissions.nesting().clone();
+
+		let bv = if !collection_nesting_and_permissions.restricted.is_empty() {
+			let mut bv = OwnerRestrictedSet::new();
+			for address in collection_nesting_and_permissions.restricted.iter() {
+				bv.try_insert(crate::eth::map_eth_to_id(address).ok_or_else(|| {
+					Error::Revert("Can't convert address into collection id".into())
+				})?)
+				.map_err(|_| "too many collections")?;
+			}
+			Some(bv)
+		} else {
+			None
+		};
+
+		nesting.token_owner = collection_nesting_and_permissions.token_owner;
+		nesting.collection_admin = collection_nesting_and_permissions.collection_admin;
+		nesting.restricted = bv;
+		permissions.nesting = Some(nesting);
+
+		<Pallet<T>>::update_permissions(&caller, self, permissions).map_err(dispatch_to_evm::<T>)
+	}
+
 	/// Toggle accessibility of collection nesting.
 	///
 	/// @param enable If "true" degenerates to nesting: 'Owner' else to nesting: 'Disabled'
-	#[solidity(rename_selector = "setCollectionNesting")]
+	#[solidity(hide, rename_selector = "setCollectionNesting")]
 	fn set_nesting_bool(&mut self, caller: Caller, enable: bool) -> Result<()> {
 		self.consume_store_reads_and_writes(1, 1)?;
 
@@ -424,8 +458,8 @@
 	///
 	/// @param enable If "true" degenerates to nesting: {OwnerRestricted: [1, 2, 3]} else to nesting: 'Disabled'
 	/// @param collections Addresses of collections that will be available for nesting.
-	#[solidity(rename_selector = "setCollectionNesting")]
-	fn set_nesting(
+	#[solidity(hide, rename_selector = "setCollectionNesting")]
+	fn set_nesting_collection_ids(
 		&mut self,
 		caller: Caller,
 		enable: bool,
@@ -464,8 +498,28 @@
 		<Pallet<T>>::update_permissions(&caller, self, permissions).map_err(dispatch_to_evm::<T>)
 	}
 
+	#[solidity(rename_selector = "collectionNesting")]
+	fn collection_nesting(&self) -> Result<eth::CollectionNestingAndPermission> {
+		let nesting = self.collection.permissions.nesting();
+
+		Ok(eth::CollectionNestingAndPermission::new(
+			nesting.token_owner,
+			nesting.collection_admin,
+			nesting
+				.restricted
+				.clone()
+				.map(|b| {
+					b.0.into_inner()
+						.iter()
+						.map(|id| crate::eth::collection_id_to_address(id.0.into()))
+						.collect()
+				})
+				.unwrap_or_default(),
+		))
+	}
+
 	/// Returns nesting for a collection
-	#[solidity(rename_selector = "collectionNestingRestrictedCollectionIds")]
+	#[solidity(hide, rename_selector = "collectionNestingRestrictedCollectionIds")]
 	fn collection_nesting_restricted_ids(&self) -> Result<eth::CollectionNesting> {
 		let nesting = self.collection.permissions.nesting();
 
@@ -480,6 +534,7 @@
 	}
 
 	/// Returns permissions for a collection
+	#[solidity(hide)]
 	fn collection_nesting_permissions(&self) -> Result<Vec<eth::CollectionNestingPermission>> {
 		let nesting = self.collection.permissions.nesting();
 		Ok(vec![
modifiedpallets/common/src/eth.rsdiffbeforeafterboth
--- a/pallets/common/src/eth.rs
+++ b/pallets/common/src/eth.rs
@@ -24,7 +24,8 @@
 };
 pub use pallet_evm::{Config, account::CrossAccountId};
 use sp_core::{H160, U256};
-use up_data_structs::CollectionId;
+use up_data_structs::{CollectionId, CollectionFlags};
+use pallet_evm_coder_substrate::execution::Error;
 
 // 0x17c4e6453Cc49AAAaEACA894e6D9683e00000001 - collection 1
 // TODO: Unhardcode prefix
@@ -104,10 +105,26 @@
 			sub: Default::default(),
 		}
 	}
+
+	/// Converts [`CrossAddress`] to `Option<CrossAccountId>`.
+	pub fn into_option_sub_cross_account<T>(&self) -> Result<Option<T::CrossAccountId>, Error>
+	where
+		T: pallet_evm::Config,
+		T::AccountId: From<[u8; 32]>,
+	{
+		if self.eth == Default::default() && self.sub == Default::default() {
+			Ok(None)
+		} else if self.eth == Default::default() {
+			Ok(Some(convert_uint256_to_cross_account::<T>(self.sub)))
+		} else if self.sub == Default::default() {
+			Ok(Some(T::CrossAccountId::from_eth(self.eth)))
+		} else {
+			Err(format!("All fields of cross account is non zeroed {:?}", self).into())
+		}
+	}
+
 	/// Converts [`CrossAddress`] to `CrossAccountId`.
-	pub fn into_sub_cross_account<T>(
-		&self,
-	) -> pallet_evm_coder_substrate::execution::Result<T::CrossAccountId>
+	pub fn into_sub_cross_account<T>(&self) -> Result<T::CrossAccountId, Error>
 	where
 		T: pallet_evm::Config,
 		T::AccountId: From<[u8; 32]>,
@@ -124,6 +141,19 @@
 	}
 }
 
+/// Type of tokens in collection
+#[derive(AbiCoder, Copy, Clone, Default, Debug, PartialEq)]
+#[repr(u8)]
+pub enum CollectionMode {
+	/// Nonfungible
+	#[default]
+	Nonfungible,
+	/// Fungible
+	Fungible,
+	/// Refungible
+	Refungible,
+}
+
 /// Ethereum representation of collection [`PropertyKey`](up_data_structs::PropertyKey) and [`PropertyValue`](up_data_structs::PropertyValue).
 #[derive(Debug, Default, AbiCoder)]
 pub struct Property {
@@ -144,7 +174,7 @@
 }
 
 impl TryFrom<up_data_structs::Property> for Property {
-	type Error = pallet_evm_coder_substrate::execution::Error;
+	type Error = Error;
 
 	fn try_from(from: up_data_structs::Property) -> Result<Self, Self::Error> {
 		let key = evm_coder::types::String::from_utf8(from.key.into())
@@ -155,7 +185,7 @@
 }
 
 impl TryInto<up_data_structs::Property> for Property {
-	type Error = pallet_evm_coder_substrate::execution::Error;
+	type Error = Error;
 
 	fn try_into(self) -> Result<up_data_structs::Property, Self::Error> {
 		let key = <Vec<u8>>::from(self.key)
@@ -220,17 +250,14 @@
 	pub fn has_value(&self) -> bool {
 		self.value.is_some()
 	}
-}
 
-impl TryInto<up_data_structs::CollectionLimits> for CollectionLimit {
-	type Error = pallet_evm_coder_substrate::execution::Error;
-
-	fn try_into(self) -> Result<up_data_structs::CollectionLimits, Self::Error> {
+	/// Set corresponding property in CollectionLimits struct
+	pub fn apply_limit(&self, limits: &mut up_data_structs::CollectionLimits) -> Result<(), Error> {
 		let value = self
 			.value
-			.ok_or::<Self::Error>("can't convert `None` value to boolean".into())?;
+			.ok_or::<Error>("can't convert `None` value to boolean".into())?;
 		let value = Some(value.try_into().map_err(|error| {
-			Self::Error::Revert(format!(
+			Error::Revert(format!(
 				"can't convert value to u32 \"{value}\" because: \"{error}\""
 			))
 		})?);
@@ -239,14 +266,13 @@
 			Some(value) => match value {
 				0 => Ok(Some(false)),
 				1 => Ok(Some(true)),
-				_ => Err(Self::Error::Revert(format!(
+				_ => Err(Error::Revert(format!(
 					"can't convert value to boolean \"{value}\""
 				))),
 			},
 			None => Ok(None),
 		};
 
-		let mut limits = up_data_structs::CollectionLimits::default();
 		match self.field {
 			CollectionLimitField::AccountTokenOwnership => {
 				limits.account_token_ownership_limit = value;
@@ -277,10 +303,99 @@
 				limits.transfers_enabled = convert_value_to_bool()?;
 			}
 		};
+		Ok(())
+	}
+}
+
+/// [`CollectionLimits`](up_data_structs::CollectionLimits) field representation for EVM.
+#[derive(Debug, Default, AbiCoder)]
+pub struct CollectionLimitValue {
+	field: CollectionLimitField,
+	value: U256,
+}
+
+impl CollectionLimitValue {
+	/// Create [`CollectionLimitValue`] from field and value.
+	pub fn new(field: CollectionLimitField, value: u32) -> Self {
+		Self {
+			field,
+			value: value.into(),
+		}
+	}
+
+	/// Set corresponding property in CollectionLimits struct
+	pub fn apply_limit(&self, limits: &mut up_data_structs::CollectionLimits) -> Result<(), Error> {
+		let value = self.value;
+		let value: u32 = value.try_into().map_err(|error| {
+			Error::Revert(format!(
+				"can't convert value to u32 \"{value}\" because: \"{error}\""
+			))
+		})?;
+
+		let convert_value_to_bool = || match value {
+			0 => Ok(Some(false)),
+			1 => Ok(Some(true)),
+			_ => Err(Error::Revert(format!(
+				"can't convert value to boolean \"{value}\""
+			))),
+		};
+
+		match self.field {
+			CollectionLimitField::AccountTokenOwnership => {
+				limits.account_token_ownership_limit = Some(value);
+			}
+			CollectionLimitField::SponsoredDataSize => {
+				limits.sponsored_data_size = Some(value);
+			}
+			CollectionLimitField::SponsoredDataRateLimit => {
+				limits.sponsored_data_rate_limit =
+					Some(up_data_structs::SponsoringRateLimit::Blocks(value));
+			}
+			CollectionLimitField::TokenLimit => {
+				limits.token_limit = Some(value);
+			}
+			CollectionLimitField::SponsorTransferTimeout => {
+				limits.sponsor_transfer_timeout = Some(value);
+			}
+			CollectionLimitField::SponsorApproveTimeout => {
+				limits.sponsor_approve_timeout = Some(value);
+			}
+			CollectionLimitField::OwnerCanTransfer => {
+				limits.owner_can_transfer = convert_value_to_bool()?;
+			}
+			CollectionLimitField::OwnerCanDestroy => {
+				limits.owner_can_destroy = convert_value_to_bool()?;
+			}
+			CollectionLimitField::TransferEnabled => {
+				limits.transfers_enabled = convert_value_to_bool()?;
+			}
+		};
+		Ok(())
+	}
+}
+
+impl TryInto<up_data_structs::CollectionLimits> for CollectionLimit {
+	type Error = Error;
+
+	fn try_into(self) -> Result<up_data_structs::CollectionLimits, Self::Error> {
+		let mut limits = up_data_structs::CollectionLimits::default();
+		self.apply_limit(&mut limits)?;
 		Ok(limits)
 	}
 }
 
+impl FromIterator<CollectionLimitValue> for Result<up_data_structs::CollectionLimits, Error> {
+	fn from_iter<T: IntoIterator<Item = CollectionLimitValue>>(
+		iter: T,
+	) -> Result<up_data_structs::CollectionLimits, Error> {
+		let mut limits = up_data_structs::CollectionLimits::default();
+		for value in iter.into_iter() {
+			value.apply_limit(&mut limits)?;
+		}
+		Ok(limits)
+	}
+}
+
 /// Ethereum representation of `NestingPermissions` (see [`up_data_structs::NestingPermissions`]) fields as an enumeration.
 #[derive(Default, Debug, Clone, Copy, AbiCoder)]
 #[repr(u8)]
@@ -384,8 +499,7 @@
 	/// Convert vector of [`TokenPropertyPermission`] into vector of [`up_data_structs::PropertyKeyPermission`].
 	pub fn into_property_key_permissions(
 		permissions: Vec<TokenPropertyPermission>,
-	) -> pallet_evm_coder_substrate::execution::Result<Vec<up_data_structs::PropertyKeyPermission>>
-	{
+	) -> Result<Vec<up_data_structs::PropertyKeyPermission>, Error> {
 		let mut perms = Vec::new();
 
 		for TokenPropertyPermission { key, permissions } in permissions {
@@ -410,6 +524,57 @@
 	pub uri: String,
 }
 
+/// Nested collections and permissions
+#[derive(Debug, Default, AbiCoder)]
+pub struct CollectionNestingAndPermission {
+	/// Owner of token can nest tokens under it.
+	pub token_owner: bool,
+	/// Admin of token collection can nest tokens under token.
+	pub collection_admin: bool,
+	/// If set - only tokens from specified collections can be nested.
+	pub restricted: Vec<Address>,
+}
+
+impl CollectionNestingAndPermission {
+	/// Create [`CollectionNesting`].
+	pub fn new(token_owner: bool, collection_admin: bool, restricted: Vec<Address>) -> Self {
+		Self {
+			token_owner,
+			collection_admin,
+			restricted,
+		}
+	}
+}
+
+/// Collection properties
+#[derive(Debug, Default, AbiCoder)]
+pub struct CreateCollectionData {
+	/// Collection sponsor
+	pub pending_sponsor: CrossAddress,
+	/// Collection name
+	pub name: String,
+	/// Collection description
+	pub description: String,
+	/// Token prefix
+	pub token_prefix: String,
+	/// Token type (NFT, FT or RFT)
+	pub mode: CollectionMode,
+	/// Fungible token precision
+	pub decimals: u8,
+	/// Custom Properties
+	pub properties: Vec<Property>,
+	/// Permissions for token properties
+	pub token_property_permissions: Vec<TokenPropertyPermission>,
+	/// Collection admins
+	pub admin_list: Vec<CrossAddress>,
+	/// Nesting settings
+	pub nesting_settings: CollectionNestingAndPermission,
+	/// Collection limits
+	pub limits: Vec<CollectionLimitValue>,
+	/// Extra collection flags
+	pub flags: CollectionFlags,
+}
+
 /// Nested collections.
 #[derive(Debug, Default, AbiCoder)]
 pub struct CollectionNesting {
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::{57	ops::{Deref, DerefMut},58	slice::from_ref,59};60use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};61use sp_std::vec::Vec;62use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};63use evm_coder::ToLog;64use frame_support::{65	dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},66	ensure,67	traits::{68		Get,69		fungible::{Balanced, Debt, Inspect},70		tokens::{Imbalance, Precision, Preservation},71	},72	dispatch::Pays,73	transactional, fail,74};75use up_data_structs::{76	AccessMode, COLLECTION_NUMBER_LIMIT, Collection, RpcCollection, CollectionFlags,77	RpcCollectionFlags, CollectionId, CreateItemData, MAX_TOKEN_PREFIX_LENGTH,78	COLLECTION_ADMINS_LIMIT, TokenId, TokenChild, CollectionStats, MAX_TOKEN_OWNERSHIP,79	CollectionMode, NFT_SPONSOR_TRANSFER_TIMEOUT, FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,80	REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, MAX_SPONSOR_TIMEOUT, CUSTOM_DATA_LIMIT, CollectionLimits,81	CreateCollectionData, SponsorshipState, CreateItemExData, SponsoringRateLimit, budget::Budget,82	PhantomType, Property, CollectionProperties as CollectionPropertiesT, TokenProperties,83	PropertiesPermissionMap, PropertyKey, PropertyValue, PropertyPermission, PropertiesError,84	TokenOwnerError, PropertyKeyPermission, TokenData, TrySetProperty, PropertyScope,85	CollectionPermissions,86};87use up_pov_estimate_rpc::PovInfo;8889pub use pallet::*;90use sp_core::H160;91use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, traits::Zero};9293#[cfg(feature = "runtime-benchmarks")]94pub mod benchmarking;95pub mod dispatch;96pub mod erc;97pub mod eth;98pub mod helpers;99#[allow(missing_docs)]100pub mod weights;101/// Weight info.102pub type SelfWeightOf<T> = <T as Config>::WeightInfo;103104/// Collection handle contains information about collection data and id.105/// Also provides functionality to count consumed gas.106///107/// CollectionHandle is used as a generic wrapper for collections of all types (except native fungible).108/// It allows to perform common operations and queries on any collection type,109/// both completely general for all, as well as their respective implementations of [`CommonCollectionOperations`].110#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]111pub struct CollectionHandle<T: Config> {112	/// Collection id113	pub id: CollectionId,114	collection: Collection<T::AccountId>,115	/// Substrate recorder for counting consumed gas116	pub recorder: SubstrateRecorder<T>,117}118119impl<T: Config> WithRecorder<T> for CollectionHandle<T> {120	fn recorder(&self) -> &SubstrateRecorder<T> {121		&self.recorder122	}123	fn into_recorder(self) -> SubstrateRecorder<T> {124		self.recorder125	}126}127128impl<T: Config> CollectionHandle<T> {129	/// Same as [CollectionHandle::new] but with an explicit gas limit.130	pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {131		Self::new_with_recorder(id, SubstrateRecorder::new(gas_limit))132	}133134	/// Same as [CollectionHandle::new] but with an existed [`SubstrateRecorder`].135	pub fn new_with_recorder(id: CollectionId, recorder: SubstrateRecorder<T>) -> Option<Self> {136		<CollectionById<T>>::get(id).map(|collection| Self {137			id,138			collection,139			recorder,140		})141	}142143	/// Retrives collection data from storage and creates collection handle with default parameters.144	/// If collection not found return `None`145	pub fn new(id: CollectionId) -> Option<Self> {146		Self::new_with_gas_limit(id, u64::MAX)147	}148149	/// Same as [`CollectionHandle::new`] but if collection not found [CollectionNotFound](Error::CollectionNotFound) returned.150	pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {151		Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)152	}153154	/// Consume gas for reading.155	pub fn consume_store_reads(156		&self,157		reads: u64,158	) -> pallet_evm_coder_substrate::execution::Result<()> {159		self.recorder().consume_store_reads(reads)160	}161162	/// Consume gas for writing.163	pub fn consume_store_writes(164		&self,165		writes: u64,166	) -> pallet_evm_coder_substrate::execution::Result<()> {167		self.recorder().consume_store_writes(writes)168	}169170	/// Consume gas for reading and writing.171	pub fn consume_store_reads_and_writes(172		&self,173		reads: u64,174		writes: u64,175	) -> pallet_evm_coder_substrate::execution::Result<()> {176		self.recorder()177			.consume_store_reads_and_writes(reads, writes)178	}179180	/// Save collection to storage.181	pub fn save(&self) -> DispatchResult {182		<CollectionById<T>>::insert(self.id, &self.collection);183		Ok(())184	}185186	/// Set collection sponsor.187	///188	/// Unique collections allows sponsoring for certain actions.189	/// This method allows you to set the sponsor of the collection.190	/// In order for sponsorship to become active, it must be confirmed through [`Self::confirm_sponsorship`].191	pub fn set_sponsor(192		&mut self,193		sender: &T::CrossAccountId,194		sponsor: T::AccountId,195	) -> DispatchResult {196		self.check_is_internal()?;197		self.check_is_owner_or_admin(sender)?;198199		self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor.clone());200201		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor));202		<PalletEvm<T>>::deposit_log(203			erc::CollectionHelpersEvents::CollectionChanged {204				collection_id: eth::collection_id_to_address(self.id),205			}206			.to_log(T::ContractAddress::get()),207		);208209		self.save()210	}211212	/// Force set `sponsor`.213	///214	/// Differs from [`set_sponsor`][`Self::set_sponsor`] in that confirmation215	/// from the `sponsor` is not required.216	///217	/// # Arguments218	///219	/// * `sponsor`: ID of the account of the sponsor-to-be.220	pub fn force_set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {221		self.check_is_internal()?;222223		self.collection.sponsorship = SponsorshipState::Confirmed(sponsor.clone());224225		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor.clone()));226		<Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sponsor));227		<PalletEvm<T>>::deposit_log(228			erc::CollectionHelpersEvents::CollectionChanged {229				collection_id: eth::collection_id_to_address(self.id),230			}231			.to_log(T::ContractAddress::get()),232		);233234		self.save()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) -> DispatchResult {242		self.check_is_internal()?;243		ensure!(244			self.collection.sponsorship.pending_sponsor() == Some(sender),245			Error::<T>::ConfirmSponsorshipFail246		);247248		self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());249250		<Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sender.clone()));251		<PalletEvm<T>>::deposit_log(252			erc::CollectionHelpersEvents::CollectionChanged {253				collection_id: eth::collection_id_to_address(self.id),254			}255			.to_log(T::ContractAddress::get()),256		);257258		self.save()259	}260261	/// Remove collection sponsor.262	pub fn remove_sponsor(&mut self, sender: &T::CrossAccountId) -> DispatchResult {263		self.check_is_internal()?;264		self.check_is_owner_or_admin(sender)?;265266		self.collection.sponsorship = SponsorshipState::Disabled;267268		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));269		<PalletEvm<T>>::deposit_log(270			erc::CollectionHelpersEvents::CollectionChanged {271				collection_id: eth::collection_id_to_address(self.id),272			}273			.to_log(T::ContractAddress::get()),274		);275		self.save()276	}277278	/// Force remove `sponsor`.279	///280	/// Differs from `remove_sponsor` in that281	/// it doesn't require consent from the `owner` of the collection.282	pub fn force_remove_sponsor(&mut self) -> DispatchResult {283		self.check_is_internal()?;284285		self.collection.sponsorship = SponsorshipState::Disabled;286287		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));288		<PalletEvm<T>>::deposit_log(289			erc::CollectionHelpersEvents::CollectionChanged {290				collection_id: eth::collection_id_to_address(self.id),291			}292			.to_log(T::ContractAddress::get()),293		);294		self.save()295	}296297	/// Checks that the collection was created with, and must be operated upon through **Unique API**.298	/// Now check only the `external` flag and if it's **true**, then return [`Error::CollectionIsExternal`] error.299	pub fn check_is_internal(&self) -> DispatchResult {300		if self.flags.external {301			return Err(<Error<T>>::CollectionIsExternal)?;302		}303304		Ok(())305	}306307	/// Checks that the collection was created with, and must be operated upon through an **assimilated API**.308	/// Now check only the `external` flag and if it's **false**, then return [`Error::CollectionIsInternal`] error.309	pub fn check_is_external(&self) -> DispatchResult {310		if !self.flags.external {311			return Err(<Error<T>>::CollectionIsInternal)?;312		}313314		Ok(())315	}316}317318impl<T: Config> Deref for CollectionHandle<T> {319	type Target = Collection<T::AccountId>;320321	fn deref(&self) -> &Self::Target {322		&self.collection323	}324}325326impl<T: Config> DerefMut for CollectionHandle<T> {327	fn deref_mut(&mut self) -> &mut Self::Target {328		&mut self.collection329	}330}331332impl<T: Config> CollectionHandle<T> {333	/// Checks if the `user` is the owner of the collection.334	pub fn check_is_owner(&self, user: &T::CrossAccountId) -> DispatchResult {335		ensure!(*user.as_sub() == self.owner, <Error<T>>::NoPermission);336		Ok(())337	}338339	/// Returns **true** if the `user` is the owner or administrator of the collection.340	pub fn is_owner_or_admin(&self, user: &T::CrossAccountId) -> bool {341		*user.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, user))342	}343344	/// Checks if the `user` is the owner or administrator of the collection.345	pub fn check_is_owner_or_admin(&self, user: &T::CrossAccountId) -> DispatchResult {346		ensure!(self.is_owner_or_admin(user), <Error<T>>::NoPermission);347		Ok(())348	}349350	/// Returns **true** if351	/// * the `user`is a collection owner or admin352	/// * the collection limits allow the owner/admins to transfer/burn any collection token353	pub fn ignores_token_restrictions(&self, user: &T::CrossAccountId) -> bool {354		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)355	}356357	/// Return **true** if `user` does not have enough token parts, and he can ignore such restrictions.358	pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {359		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)360	}361362	/// Checks if the user is in the allow list. If not [Error::AddressNotInAllowlist] returns.363	pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {364		ensure!(365			<Allowlist<T>>::get((self.id, user)),366			<Error<T>>::AddressNotInAllowlist367		);368		Ok(())369	}370371	/// Changes collection owner to another account372	/// #### Store read/writes373	/// 1 writes374	pub fn change_owner(375		&mut self,376		caller: T::CrossAccountId,377		new_owner: T::CrossAccountId,378	) -> DispatchResult {379		self.check_is_internal()?;380		self.check_is_owner(&caller)?;381		self.collection.owner = new_owner.as_sub().clone();382383		<Pallet<T>>::deposit_event(Event::<T>::CollectionOwnerChanged(384			self.id,385			new_owner.as_sub().clone(),386		));387		<PalletEvm<T>>::deposit_log(388			erc::CollectionHelpersEvents::CollectionChanged {389				collection_id: eth::collection_id_to_address(self.id),390			}391			.to_log(T::ContractAddress::get()),392		);393394		self.save()395	}396}397398#[frame_support::pallet]399pub mod pallet {400401	use super::*;402	use dispatch::CollectionDispatch;403	use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};404	use up_data_structs::{TokenId, mapping::TokenAddressMapping};405	use scale_info::TypeInfo;406	use weights::WeightInfo;407408	#[pallet::config]409	pub trait Config:410		frame_system::Config + pallet_evm_coder_substrate::Config + pallet_evm::Config + TypeInfo411	{412		/// Weight information for functions of this pallet.413		type WeightInfo: WeightInfo;414415		/// Events compatible with [`frame_system::Config::Event`].416		type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;417418		/// Handler of accounts and payment.419		type Currency: Balanced<Self::AccountId> + Inspect<Self::AccountId>;420421		/// Set price to create a collection.422		#[pallet::constant]423		type CollectionCreationPrice: Get<424			<<Self as Config>::Currency as Inspect<Self::AccountId>>::Balance,425		>;426427		/// Dispatcher of operations on collections.428		type CollectionDispatch: CollectionDispatch<Self>;429430		/// Account which holds the chain's treasury.431		type TreasuryAccountId: Get<Self::AccountId>;432433		/// Address under which the CollectionHelper contract would be available.434		#[pallet::constant]435		type ContractAddress: Get<H160>;436437		/// Mapper for token addresses to Ethereum addresses.438		type EvmTokenAddressMapping: TokenAddressMapping<H160>;439440		/// Mapper for token addresses to [`CrossAccountId`].441		type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;442	}443444	const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);445	/// Collection id for native fungible collction.446	pub const NATIVE_FUNGIBLE_COLLECTION_ID: CollectionId = CollectionId(0);447448	#[pallet::pallet]449	#[pallet::storage_version(STORAGE_VERSION)]450	pub struct Pallet<T>(_);451452	#[pallet::extra_constants]453	impl<T: Config> Pallet<T> {454		/// Maximum admins per collection.455		pub fn collection_admins_limit() -> u32 {456			COLLECTION_ADMINS_LIMIT457		}458	}459460	#[pallet::genesis_config]461	pub struct GenesisConfig<T>(PhantomData<T>);462463	#[cfg(feature = "std")]464	impl<T: Config> Default for GenesisConfig<T> {465		fn default() -> Self {466			Self(Default::default())467		}468	}469470	#[pallet::genesis_build]471	impl<T: Config> GenesisBuild<T> for GenesisConfig<T> {472		fn build(&self) {473			StorageVersion::new(1).put::<Pallet<T>>();474		}475	}476477	impl<T: Config> Pallet<T> {478		/// Helper function that handles deposit events479		pub fn deposit_event(event: Event<T>) {480			let event = <T as Config>::RuntimeEvent::from(event);481			let event = event.into();482			<frame_system::Pallet<T>>::deposit_event(event)483		}484	}485486	#[pallet::event]487	pub enum Event<T: Config> {488		/// New collection was created489		CollectionCreated(490			/// Globally unique identifier of newly created collection.491			CollectionId,492			/// [`CollectionMode`] converted into _u8_.493			u8,494			/// Collection owner.495			T::AccountId,496		),497498		/// New collection was destroyed499		CollectionDestroyed(500			/// Globally unique identifier of collection.501			CollectionId,502		),503504		/// New item was created.505		ItemCreated(506			/// Id of the collection where item was created.507			CollectionId,508			/// Id of an item. Unique within the collection.509			TokenId,510			/// Owner of newly created item511			T::CrossAccountId,512			/// Always 1 for NFT513			u128,514		),515516		/// Collection item was burned.517		ItemDestroyed(518			/// Id of the collection where item was destroyed.519			CollectionId,520			/// Identifier of burned NFT.521			TokenId,522			/// Which user has destroyed its tokens.523			T::CrossAccountId,524			/// Amount of token pieces destroed. Always 1 for NFT.525			u128,526		),527528		/// Item was transferred529		Transfer(530			/// Id of collection to which item is belong.531			CollectionId,532			/// Id of an item.533			TokenId,534			/// Original owner of item.535			T::CrossAccountId,536			/// New owner of item.537			T::CrossAccountId,538			/// Amount of token pieces transfered. Always 1 for NFT.539			u128,540		),541542		/// Amount pieces of token owned by `sender` was approved for `spender`.543		Approved(544			/// Id of collection to which item is belong.545			CollectionId,546			/// Id of an item.547			TokenId,548			/// Original owner of item.549			T::CrossAccountId,550			/// Id for which the approval was granted.551			T::CrossAccountId,552			/// Amount of token pieces transfered. Always 1 for NFT.553			u128,554		),555556		/// A `sender` approves operations on all owned tokens for `spender`.557		ApprovedForAll(558			/// Id of collection to which item is belong.559			CollectionId,560			/// Owner of a wallet.561			T::CrossAccountId,562			/// Id for which operator status was granted or rewoked.563			T::CrossAccountId,564			/// Is operator status granted or revoked?565			bool,566		),567568		/// The colletion property has been added or edited.569		CollectionPropertySet(570			/// Id of collection to which property has been set.571			CollectionId,572			/// The property that was set.573			PropertyKey,574		),575576		/// The property has been deleted.577		CollectionPropertyDeleted(578			/// Id of collection to which property has been deleted.579			CollectionId,580			/// The property that was deleted.581			PropertyKey,582		),583584		/// The token property has been added or edited.585		TokenPropertySet(586			/// Identifier of the collection whose token has the property set.587			CollectionId,588			/// The token for which the property was set.589			TokenId,590			/// The property that was set.591			PropertyKey,592		),593594		/// The token property has been deleted.595		TokenPropertyDeleted(596			/// Identifier of the collection whose token has the property deleted.597			CollectionId,598			/// The token for which the property was deleted.599			TokenId,600			/// The property that was deleted.601			PropertyKey,602		),603604		/// The token property permission of a collection has been set.605		PropertyPermissionSet(606			/// ID of collection to which property permission has been set.607			CollectionId,608			/// The property permission that was set.609			PropertyKey,610		),611612		/// Address was added to the allow list.613		AllowListAddressAdded(614			/// ID of the affected collection.615			CollectionId,616			/// Address of the added account.617			T::CrossAccountId,618		),619620		/// Address was removed from the allow list.621		AllowListAddressRemoved(622			/// ID of the affected collection.623			CollectionId,624			/// Address of the removed account.625			T::CrossAccountId,626		),627628		/// Collection admin was added.629		CollectionAdminAdded(630			/// ID of the affected collection.631			CollectionId,632			/// Admin address.633			T::CrossAccountId,634		),635636		/// Collection admin was removed.637		CollectionAdminRemoved(638			/// ID of the affected collection.639			CollectionId,640			/// Removed admin address.641			T::CrossAccountId,642		),643644		/// Collection limits were set.645		CollectionLimitSet(646			/// ID of the affected collection.647			CollectionId,648		),649650		/// Collection owned was changed.651		CollectionOwnerChanged(652			/// ID of the affected collection.653			CollectionId,654			/// New owner address.655			T::AccountId,656		),657658		/// Collection permissions were set.659		CollectionPermissionSet(660			/// ID of the affected collection.661			CollectionId,662		),663664		/// Collection sponsor was set.665		CollectionSponsorSet(666			/// ID of the affected collection.667			CollectionId,668			/// New sponsor address.669			T::AccountId,670		),671672		/// New sponsor was confirm.673		SponsorshipConfirmed(674			/// ID of the affected collection.675			CollectionId,676			/// New sponsor address.677			T::AccountId,678		),679680		/// Collection sponsor was removed.681		CollectionSponsorRemoved(682			/// ID of the affected collection.683			CollectionId,684		),685	}686687	#[pallet::error]688	pub enum Error<T> {689		/// This collection does not exist.690		CollectionNotFound,691		/// Sender parameter and item owner must be equal.692		MustBeTokenOwner,693		/// No permission to perform action694		NoPermission,695		/// Destroying only empty collections is allowed696		CantDestroyNotEmptyCollection,697		/// Collection is not in mint mode.698		PublicMintingNotAllowed,699		/// Address is not in allow list.700		AddressNotInAllowlist,701702		/// Collection name can not be longer than 63 char.703		CollectionNameLimitExceeded,704		/// Collection description can not be longer than 255 char.705		CollectionDescriptionLimitExceeded,706		/// Token prefix can not be longer than 15 char.707		CollectionTokenPrefixLimitExceeded,708		/// Total collections bound exceeded.709		TotalCollectionsLimitExceeded,710		/// Exceeded max admin count711		CollectionAdminCountExceeded,712		/// Collection limit bounds per collection exceeded713		CollectionLimitBoundsExceeded,714		/// Tried to enable permissions which are only permitted to be disabled715		OwnerPermissionsCantBeReverted,716		/// Collection settings not allowing items transferring717		TransferNotAllowed,718		/// Account token limit exceeded per collection719		AccountTokenLimitExceeded,720		/// Collection token limit exceeded721		CollectionTokenLimitExceeded,722		/// Metadata flag frozen723		MetadataFlagFrozen,724725		/// Item does not exist726		TokenNotFound,727		/// Item is balance not enough728		TokenValueTooLow,729		/// Requested value is more than the approved730		ApprovedValueTooLow,731		/// Tried to approve more than owned732		CantApproveMoreThanOwned,733		/// Only spending from eth mirror could be approved734		AddressIsNotEthMirror,735736		/// Can't transfer tokens to ethereum zero address737		AddressIsZero,738739		/// The operation is not supported740		UnsupportedOperation,741742		/// Insufficient funds to perform an action743		NotSufficientFounds,744745		/// User does not satisfy the nesting rule746		UserIsNotAllowedToNest,747		/// Only tokens from specific collections may nest tokens under this one748		SourceCollectionIsNotAllowedToNest,749750		/// Tried to store more data than allowed in collection field751		CollectionFieldSizeExceeded,752753		/// Tried to store more property data than allowed754		NoSpaceForProperty,755756		/// Tried to store more property keys than allowed757		PropertyLimitReached,758759		/// Property key is too long760		PropertyKeyIsTooLong,761762		/// Only ASCII letters, digits, and symbols `_`, `-`, and `.` are allowed763		InvalidCharacterInPropertyKey,764765		/// Empty property keys are forbidden766		EmptyPropertyKey,767768		/// Tried to access an external collection with an internal API769		CollectionIsExternal,770771		/// Tried to access an internal collection with an external API772		CollectionIsInternal,773774		/// This address is not set as sponsor, use setCollectionSponsor first.775		ConfirmSponsorshipFail,776777		/// The user is not an administrator.778		UserIsNotCollectionAdmin,779	}780781	/// Storage of the count of created collections. Essentially contains the last collection ID.782	#[pallet::storage]783	pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;784785	/// Storage of the count of deleted collections.786	#[pallet::storage]787	pub type DestroyedCollectionCount<T> =788		StorageValue<Value = CollectionId, QueryKind = ValueQuery>;789790	/// Storage of collection info.791	#[pallet::storage]792	pub type CollectionById<T> = StorageMap<793		Hasher = Blake2_128Concat,794		Key = CollectionId,795		Value = Collection<<T as frame_system::Config>::AccountId>,796		QueryKind = OptionQuery,797	>;798799	/// Storage of collection properties.800	#[pallet::storage]801	#[pallet::getter(fn collection_properties)]802	pub type CollectionProperties<T> = StorageMap<803		Hasher = Blake2_128Concat,804		Key = CollectionId,805		Value = CollectionPropertiesT,806		QueryKind = ValueQuery,807	>;808809	/// Storage of token property permissions of a collection.810	#[pallet::storage]811	#[pallet::getter(fn property_permissions)]812	pub type CollectionPropertyPermissions<T> = StorageMap<813		Hasher = Blake2_128Concat,814		Key = CollectionId,815		Value = PropertiesPermissionMap,816		QueryKind = ValueQuery,817	>;818819	/// Storage of the amount of collection admins.820	#[pallet::storage]821	pub type AdminAmount<T> = StorageMap<822		Hasher = Blake2_128Concat,823		Key = CollectionId,824		Value = u32,825		QueryKind = ValueQuery,826	>;827828	/// List of collection admins.829	#[pallet::storage]830	pub type IsAdmin<T: Config> = StorageNMap<831		Key = (832			Key<Blake2_128Concat, CollectionId>,833			Key<Blake2_128Concat, T::CrossAccountId>,834		),835		Value = bool,836		QueryKind = ValueQuery,837	>;838839	/// Allowlisted collection users.840	#[pallet::storage]841	pub type Allowlist<T: Config> = StorageNMap<842		Key = (843			Key<Blake2_128Concat, CollectionId>,844			Key<Blake2_128Concat, T::CrossAccountId>,845		),846		Value = bool,847		QueryKind = ValueQuery,848	>;849850	/// Not used by code, exists only to provide some types to metadata.851	#[pallet::storage]852	pub type DummyStorageValue<T: Config> = StorageValue<853		Value = (854			CollectionStats,855			CollectionId,856			TokenId,857			TokenChild,858			PhantomType<(859				TokenData<T::CrossAccountId>,860				RpcCollection<T::AccountId>,861				// PoV Estimate Info862				PovInfo,863			)>,864		),865		QueryKind = OptionQuery,866	>;867}868869/// Represents the change mode for the token property.870pub enum SetPropertyMode {871	/// The token already exists.872	ExistingToken,873874	/// New token.875	NewToken {876		/// The creator of the token is the recipient.877		mint_target_is_sender: bool,878	},879}880881/// Value representation with delayed initialization time.882pub struct LazyValue<T, F: FnOnce() -> T> {883	value: Option<T>,884	f: Option<F>,885}886887impl<T, F: FnOnce() -> T> LazyValue<T, F> {888	/// Create a new LazyValue.889	pub fn new(f: F) -> Self {890		Self {891			value: None,892			f: Some(f),893		}894	}895896	/// Get the value. If it call furst time the value will be initialized.897	pub fn value(&mut self) -> &T {898		if self.value.is_none() {899			self.value = Some(self.f.take().unwrap()())900		}901902		self.value.as_ref().unwrap()903	}904905	/// Is value initialized.906	pub fn has_value(&self) -> bool {907		self.value.is_some()908	}909}910911fn check_token_permissions<T, FCA, FTO, FTE>(912	collection_admin_permitted: bool,913	token_owner_permitted: bool,914	is_collection_admin: &mut LazyValue<bool, FCA>,915	is_token_owner: &mut LazyValue<Result<bool, DispatchError>, FTO>,916	is_token_exist: &mut LazyValue<bool, FTE>,917) -> DispatchResult918where919	T: Config,920	FCA: FnOnce() -> bool,921	FTO: FnOnce() -> Result<bool, DispatchError>,922	FTE: FnOnce() -> bool,923{924	if !(collection_admin_permitted && *is_collection_admin.value()925		|| token_owner_permitted && (*is_token_owner.value())?)926	{927		fail!(<Error<T>>::NoPermission);928	}929930	let token_certainly_exist = is_token_owner.has_value() && (*is_token_owner.value())?;931	if !token_certainly_exist && !is_token_exist.value() {932		fail!(<Error<T>>::TokenNotFound);933	}934	Ok(())935}936937impl<T: Config> Pallet<T> {938	/// Enshure that receiver address is correct.939	///940	/// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens.941	pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {942		ensure!(943			&T::CrossAccountId::from_eth(H160([0; 20])) != receiver,944			<Error<T>>::AddressIsZero945		);946		Ok(())947	}948949	/// Get a vector of collection admins.950	pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {951		<IsAdmin<T>>::iter_prefix((collection,))952			.map(|(a, _)| a)953			.collect()954	}955956	/// Get a vector of users allowed to mint tokens.957	pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {958		<Allowlist<T>>::iter_prefix((collection,))959			.map(|(a, _)| a)960			.collect()961	}962963	/// Is `user` allowed to mint token in `collection`.964	pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {965		<Allowlist<T>>::get((collection, user))966	}967968	/// Get statistics of collections.969	pub fn collection_stats() -> CollectionStats {970		let created = <CreatedCollectionCount<T>>::get();971		let destroyed = <DestroyedCollectionCount<T>>::get();972		CollectionStats {973			created: created.0,974			destroyed: destroyed.0,975			alive: created.0 - destroyed.0,976		}977	}978979	/// Get the effective limits for the collection.980	pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {981		let collection = <CollectionById<T>>::get(collection)?;982		let limits = collection.limits;983		let effective_limits = CollectionLimits {984			account_token_ownership_limit: Some(limits.account_token_ownership_limit()),985			sponsored_data_size: Some(limits.sponsored_data_size()),986			sponsored_data_rate_limit: Some(987				limits988					.sponsored_data_rate_limit989					.unwrap_or(SponsoringRateLimit::SponsoringDisabled),990			),991			token_limit: Some(limits.token_limit()),992			sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(993				match collection.mode {994					CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,995					CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,996					CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,997				},998			)),999			sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),1000			owner_can_transfer: Some(limits.owner_can_transfer()),1001			owner_can_destroy: Some(limits.owner_can_destroy()),1002			transfers_enabled: Some(limits.transfers_enabled()),1003		};10041005		Some(effective_limits)1006	}10071008	/// Returns information about the `collection` adapted for rpc.1009	pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {1010		let Collection {1011			name,1012			description,1013			owner,1014			mode,1015			token_prefix,1016			sponsorship,1017			limits,1018			permissions,1019			flags,1020		} = <CollectionById<T>>::get(collection)?;10211022		let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)1023			.into_iter()1024			.map(|(key, permission)| PropertyKeyPermission { key, permission })1025			.collect();10261027		let properties = <CollectionProperties<T>>::get(collection)1028			.into_iter()1029			.map(|(key, value)| Property { key, value })1030			.collect();10311032		let permissions = CollectionPermissions {1033			access: Some(permissions.access()),1034			mint_mode: Some(permissions.mint_mode()),1035			nesting: Some(permissions.nesting().clone()),1036		};10371038		Some(RpcCollection {1039			name: name.into_inner(),1040			description: description.into_inner(),1041			owner,1042			mode,1043			token_prefix: token_prefix.into_inner(),1044			sponsorship,1045			limits,1046			permissions,1047			token_property_permissions,1048			properties,1049			read_only: flags.external,10501051			flags: RpcCollectionFlags {1052				foreign: flags.foreign,1053				erc721metadata: flags.erc721metadata,1054			},1055		})1056	}1057}10581059macro_rules! limit_default {1060	($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1061		$(1062			if let Some($new) = $new.$field {1063				let $old = $old.$field($($arg)?);1064				let _ = $new;1065				let _ = $old;1066				$check1067			} else {1068				$new.$field = $old.$field1069			}1070		)*1071	}};1072}1073macro_rules! limit_default_clone {1074	($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1075		$(1076			if let Some($new) = $new.$field.clone() {1077				let $old = $old.$field($($arg)?);1078				let _ = $new;1079				let _ = $old;1080				$check1081			} else {1082				$new.$field = $old.$field.clone()1083			}1084		)*1085	}};1086}10871088impl<T: Config> Pallet<T> {1089	/// Create new collection.1090	///1091	/// * `owner` - The owner of the collection.1092	/// * `data` - Description of the created collection.1093	/// * `flags` - Extra flags to store.1094	pub fn init_collection(1095		owner: T::CrossAccountId,1096		payer: T::CrossAccountId,1097		data: CreateCollectionData<T::AccountId>,1098		flags: CollectionFlags,1099	) -> Result<CollectionId, DispatchError> {1100		{1101			ensure!(1102				data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,1103				Error::<T>::CollectionTokenPrefixLimitExceeded1104			);1105		}11061107		let created_count = <CreatedCollectionCount<T>>::get()1108			.01109			.checked_add(1)1110			.ok_or(ArithmeticError::Overflow)?;1111		let destroyed_count = <DestroyedCollectionCount<T>>::get().0;1112		let id = CollectionId(created_count);11131114		// bound Total number of collections1115		ensure!(1116			created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,1117			<Error<T>>::TotalCollectionsLimitExceeded1118		);11191120		// =========11211122		let collection = Collection {1123			owner: owner.as_sub().clone(),1124			name: data.name,1125			mode: data.mode.clone(),1126			description: data.description,1127			token_prefix: data.token_prefix,1128			sponsorship: data1129				.pending_sponsor1130				.map(SponsorshipState::Unconfirmed)1131				.unwrap_or_default(),1132			limits: data1133				.limits1134				.map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))1135				.unwrap_or_else(|| Ok(CollectionLimits::default()))?,1136			permissions: data1137				.permissions1138				.map(|permissions| {1139					Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)1140				})1141				.unwrap_or_else(|| Ok(CollectionPermissions::default()))?,1142			flags,1143		};11441145		let mut collection_properties = CollectionPropertiesT::new();1146		collection_properties1147			.try_set_from_iter(data.properties.into_iter())1148			.map_err(<Error<T>>::from)?;11491150		CollectionProperties::<T>::insert(id, collection_properties);11511152		let mut token_props_permissions = PropertiesPermissionMap::new();1153		token_props_permissions1154			.try_set_from_iter(data.token_property_permissions.into_iter())1155			.map_err(<Error<T>>::from)?;11561157		CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);11581159		// Take a (non-refundable) deposit of collection creation1160		{1161			let mut imbalance = <Debt<T::AccountId, <T as Config>::Currency>>::zero();1162			imbalance.subsume(<T as Config>::Currency::deposit(1163				&T::TreasuryAccountId::get(),1164				T::CollectionCreationPrice::get(),1165				Precision::Exact,1166			)?);1167			let credit =1168				<T as Config>::Currency::settle(payer.as_sub(), imbalance, Preservation::Preserve)1169					.map_err(|_| Error::<T>::NotSufficientFounds)?;11701171			debug_assert!(credit.peek().is_zero())1172		}11731174		<CreatedCollectionCount<T>>::put(created_count);1175		<Pallet<T>>::deposit_event(Event::CollectionCreated(1176			id,1177			data.mode.id(),1178			owner.as_sub().clone(),1179		));1180		<PalletEvm<T>>::deposit_log(1181			erc::CollectionHelpersEvents::CollectionCreated {1182				owner: *owner.as_eth(),1183				collection_id: eth::collection_id_to_address(id),1184			}1185			.to_log(T::ContractAddress::get()),1186		);1187		<CollectionById<T>>::insert(id, collection);1188		Ok(id)1189	}11901191	/// Destroy collection.1192	///1193	/// * `collection` - Collection handler.1194	/// * `sender` - The owner or administrator of the collection.1195	pub fn destroy_collection(1196		collection: CollectionHandle<T>,1197		sender: &T::CrossAccountId,1198	) -> DispatchResult {1199		ensure!(1200			collection.limits.owner_can_destroy(),1201			<Error<T>>::NoPermission,1202		);1203		collection.check_is_owner(sender)?;12041205		let destroyed_collections = <DestroyedCollectionCount<T>>::get()1206			.01207			.checked_add(1)1208			.ok_or(ArithmeticError::Overflow)?;12091210		// =========12111212		<DestroyedCollectionCount<T>>::put(destroyed_collections);1213		<CollectionById<T>>::remove(collection.id);1214		<AdminAmount<T>>::remove(collection.id);1215		let _ = <IsAdmin<T>>::clear_prefix((collection.id,), u32::MAX, None);1216		let _ = <Allowlist<T>>::clear_prefix((collection.id,), u32::MAX, None);1217		<CollectionProperties<T>>::remove(collection.id);12181219		<Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));12201221		<PalletEvm<T>>::deposit_log(1222			erc::CollectionHelpersEvents::CollectionDestroyed {1223				collection_id: eth::collection_id_to_address(collection.id),1224			}1225			.to_log(T::ContractAddress::get()),1226		);1227		Ok(())1228	}12291230	/// This function sets or removes a collection properties according to1231	/// `properties_updates` contents:1232	/// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`1233	/// * removes a property under the <key> if the value is `None` `(<key>, None)`.1234	///1235	/// This function fires an event for each property change.1236	/// In case of an error, all the changes (including the events) will be reverted1237	/// since the function is transactional.1238	#[transactional]1239	fn modify_collection_properties(1240		collection: &CollectionHandle<T>,1241		sender: &T::CrossAccountId,1242		properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,1243	) -> DispatchResult {1244		collection.check_is_owner_or_admin(sender)?;12451246		let mut stored_properties = <CollectionProperties<T>>::get(collection.id);12471248		for (key, value) in properties_updates {1249			match value {1250				Some(value) => {1251					stored_properties1252						.try_set(key.clone(), value)1253						.map_err(<Error<T>>::from)?;12541255					Self::deposit_event(Event::CollectionPropertySet(collection.id, key));1256					<PalletEvm<T>>::deposit_log(1257						erc::CollectionHelpersEvents::CollectionChanged {1258							collection_id: eth::collection_id_to_address(collection.id),1259						}1260						.to_log(T::ContractAddress::get()),1261					);1262				}1263				None => {1264					stored_properties.remove(&key).map_err(<Error<T>>::from)?;12651266					Self::deposit_event(Event::CollectionPropertyDeleted(collection.id, key));1267					<PalletEvm<T>>::deposit_log(1268						erc::CollectionHelpersEvents::CollectionChanged {1269							collection_id: eth::collection_id_to_address(collection.id),1270						}1271						.to_log(T::ContractAddress::get()),1272					);1273				}1274			}1275		}12761277		<CollectionProperties<T>>::set(collection.id, stored_properties);12781279		Ok(())1280	}12811282	/// A batch operation to add, edit or remove properties for a token.1283	/// It sets or removes a token's properties according to1284	/// `properties_updates` contents:1285	/// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`1286	/// * removes a property under the <key> if the value is `None` `(<key>, None)`.1287	///1288	/// All affected properties should have `mutable` permission1289	/// to be **deleted** or to be **set more than once**,1290	/// and the sender should have permission to edit those properties.1291	///1292	/// This function fires an event for each property change.1293	/// In case of an error, all the changes (including the events) will be reverted1294	/// since the function is transactional.1295	#[allow(clippy::too_many_arguments)]1296	pub fn modify_token_properties<FTO, FTE>(1297		collection: &CollectionHandle<T>,1298		sender: &T::CrossAccountId,1299		token_id: TokenId,1300		is_token_exist: &mut LazyValue<bool, FTE>,1301		properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,1302		mut stored_properties: TokenProperties,1303		is_token_owner: &mut LazyValue<Result<bool, DispatchError>, FTO>,1304		set_token_properties: impl FnOnce(TokenProperties),1305		log: evm_coder::ethereum::Log,1306	) -> DispatchResult1307	where1308		FTO: FnOnce() -> Result<bool, DispatchError>,1309		FTE: FnOnce() -> bool,1310	{1311		let mut is_collection_admin = LazyValue::new(|| collection.is_owner_or_admin(sender));1312		let permissions = Self::property_permissions(collection.id);13131314		let mut changed = false;1315		for (key, value) in properties_updates {1316			let permission = permissions1317				.get(&key)1318				.cloned()1319				.unwrap_or_else(PropertyPermission::none);13201321			let property_exists = stored_properties.get(&key).is_some();13221323			match permission {1324				PropertyPermission { mutable: false, .. } if property_exists => {1325					return Err(<Error<T>>::NoPermission.into());1326				}13271328				PropertyPermission {1329					collection_admin,1330					token_owner,1331					..1332				} => check_token_permissions::<T, _, FTO, FTE>(1333					collection_admin,1334					token_owner,1335					&mut is_collection_admin,1336					is_token_owner,1337					is_token_exist,1338				)?,1339			}13401341			match value {1342				Some(value) => {1343					stored_properties1344						.try_set(key.clone(), value)1345						.map_err(<Error<T>>::from)?;13461347					Self::deposit_event(Event::TokenPropertySet(collection.id, token_id, key));1348				}1349				None => {1350					stored_properties.remove(&key).map_err(<Error<T>>::from)?;13511352					Self::deposit_event(Event::TokenPropertyDeleted(collection.id, token_id, key));1353				}1354			}13551356			changed = true;1357		}13581359		if changed {1360			<PalletEvm<T>>::deposit_log(log);1361		}13621363		set_token_properties(stored_properties);13641365		Ok(())1366	}13671368	/// Sets or unsets the approval of a given operator.1369	///1370	/// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.1371	/// - `owner`: Token owner1372	/// - `operator`: Operator1373	/// - `approve`: Should operator status be granted or revoked?1374	pub fn set_allowance_for_all(1375		collection: &CollectionHandle<T>,1376		owner: &T::CrossAccountId,1377		operator: &T::CrossAccountId,1378		approve: bool,1379		set_allowance: impl FnOnce(),1380		log: evm_coder::ethereum::Log,1381	) -> DispatchResult {1382		if collection.permissions.access() == AccessMode::AllowList {1383			collection.check_allowlist(owner)?;1384			collection.check_allowlist(operator)?;1385		}13861387		Self::ensure_correct_receiver(operator)?;13881389		set_allowance();13901391		<PalletEvm<T>>::deposit_log(log);1392		Self::deposit_event(Event::ApprovedForAll(1393			collection.id,1394			owner.clone(),1395			operator.clone(),1396			approve,1397		));1398		Ok(())1399	}14001401	/// Set collection property.1402	///1403	/// * `collection` - Collection handler.1404	/// * `sender` - The owner or administrator of the collection.1405	/// * `property` - The property to set.1406	pub fn set_collection_property(1407		collection: &CollectionHandle<T>,1408		sender: &T::CrossAccountId,1409		property: Property,1410	) -> DispatchResult {1411		Self::set_collection_properties(collection, sender, [property].into_iter())1412	}14131414	/// Set a scoped collection property, where the scope is a special prefix1415	/// prohibiting a user access to change the property directly.1416	///1417	/// * `collection_id` - ID of the collection for which the property is being set.1418	/// * `scope` - Property scope.1419	/// * `property` - The property to set.1420	pub fn set_scoped_collection_property(1421		collection_id: CollectionId,1422		scope: PropertyScope,1423		property: Property,1424	) -> DispatchResult {1425		CollectionProperties::<T>::try_mutate(collection_id, |properties| {1426			properties.try_scoped_set(scope, property.key, property.value)1427		})1428		.map_err(<Error<T>>::from)?;14291430		Ok(())1431	}14321433	/// Set scoped collection properties, where the scope is a special prefix1434	/// prohibiting a user access to change the properties directly.1435	///1436	/// * `collection_id` - ID of the collection for which the properties is being set.1437	/// * `scope` - Property scope.1438	/// * `properties` - The properties to set.1439	pub fn set_scoped_collection_properties(1440		collection_id: CollectionId,1441		scope: PropertyScope,1442		properties: impl Iterator<Item = Property>,1443	) -> DispatchResult {1444		CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {1445			stored_properties.try_scoped_set_from_iter(scope, properties)1446		})1447		.map_err(<Error<T>>::from)?;14481449		Ok(())1450	}14511452	/// Set collection properties.1453	///1454	/// * `collection` - Collection handler.1455	/// * `sender` - The owner or administrator of the collection.1456	/// * `properties` - The properties to set.1457	pub fn set_collection_properties(1458		collection: &CollectionHandle<T>,1459		sender: &T::CrossAccountId,1460		properties: impl Iterator<Item = Property>,1461	) -> DispatchResult {1462		Self::modify_collection_properties(1463			collection,1464			sender,1465			properties.map(|property| (property.key, Some(property.value))),1466		)1467	}14681469	/// Delete collection property.1470	///1471	/// * `collection` - Collection handler.1472	/// * `sender` - The owner or administrator of the collection.1473	/// * `property` - The property to delete.1474	pub fn delete_collection_property(1475		collection: &CollectionHandle<T>,1476		sender: &T::CrossAccountId,1477		property_key: PropertyKey,1478	) -> DispatchResult {1479		Self::delete_collection_properties(collection, sender, [property_key].into_iter())1480	}14811482	/// Delete collection properties.1483	///1484	/// * `collection` - Collection handler.1485	/// * `sender` - The owner or administrator of the collection.1486	/// * `properties` - The properties to delete.1487	pub fn delete_collection_properties(1488		collection: &CollectionHandle<T>,1489		sender: &T::CrossAccountId,1490		property_keys: impl Iterator<Item = PropertyKey>,1491	) -> DispatchResult {1492		Self::modify_collection_properties(collection, sender, property_keys.map(|key| (key, None)))1493	}14941495	/// Set collection propetry permission without any checks.1496	///1497	/// Used for migrations.1498	///1499	/// * `collection` - Collection handler.1500	/// * `property_permissions` - Property permissions.1501	pub fn set_property_permission_unchecked(1502		collection: CollectionId,1503		property_permission: PropertyKeyPermission,1504	) -> DispatchResult {1505		<CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {1506			permissions.try_set(property_permission.key, property_permission.permission)1507		})1508		.map_err(<Error<T>>::from)?;1509		Ok(())1510	}15111512	/// Set collection property permission.1513	///1514	/// * `collection` - Collection handler.1515	/// * `sender` - The owner or administrator of the collection.1516	/// * `property_permission` - Property permission.1517	pub fn set_property_permission(1518		collection: &CollectionHandle<T>,1519		sender: &T::CrossAccountId,1520		property_permission: PropertyKeyPermission,1521	) -> DispatchResult {1522		Self::set_scoped_property_permission(1523			collection,1524			sender,1525			PropertyScope::None,1526			property_permission,1527		)1528	}15291530	/// Set collection property permission with scope.1531	///1532	/// * `collection` - Collection handler.1533	/// * `sender` - The owner or administrator of the collection.1534	/// * `scope` - Property scope.1535	/// * `property_permission` - Property permission.1536	pub fn set_scoped_property_permission(1537		collection: &CollectionHandle<T>,1538		sender: &T::CrossAccountId,1539		scope: PropertyScope,1540		property_permission: PropertyKeyPermission,1541	) -> DispatchResult {1542		collection.check_is_owner_or_admin(sender)?;15431544		let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);1545		let current_permission = all_permissions.get(&property_permission.key);1546		if matches![1547			current_permission,1548			Some(PropertyPermission { mutable: false, .. })1549		] {1550			return Err(<Error<T>>::NoPermission.into());1551		}15521553		CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {1554			let property_permission = property_permission.clone();1555			permissions.try_scoped_set(1556				scope,1557				property_permission.key,1558				property_permission.permission,1559			)1560		})1561		.map_err(<Error<T>>::from)?;15621563		Self::deposit_event(Event::PropertyPermissionSet(1564			collection.id,1565			property_permission.key,1566		));1567		<PalletEvm<T>>::deposit_log(1568			erc::CollectionHelpersEvents::CollectionChanged {1569				collection_id: eth::collection_id_to_address(collection.id),1570			}1571			.to_log(T::ContractAddress::get()),1572		);15731574		Ok(())1575	}15761577	/// Set token property permission.1578	///1579	/// * `collection` - Collection handler.1580	/// * `sender` - The owner or administrator of the collection.1581	/// * `property_permissions` - Property permissions.1582	#[transactional]1583	pub fn set_token_property_permissions(1584		collection: &CollectionHandle<T>,1585		sender: &T::CrossAccountId,1586		property_permissions: Vec<PropertyKeyPermission>,1587	) -> DispatchResult {1588		Self::set_scoped_token_property_permissions(1589			collection,1590			sender,1591			PropertyScope::None,1592			property_permissions,1593		)1594	}15951596	/// Set token property permission with scope.1597	///1598	/// * `collection` - Collection handler.1599	/// * `sender` - The owner or administrator of the collection.1600	/// * `scope` - Property scope.1601	/// * `property_permissions` - Property permissions.1602	#[transactional]1603	pub fn set_scoped_token_property_permissions(1604		collection: &CollectionHandle<T>,1605		sender: &T::CrossAccountId,1606		scope: PropertyScope,1607		property_permissions: Vec<PropertyKeyPermission>,1608	) -> DispatchResult {1609		for prop_pemission in property_permissions {1610			Self::set_scoped_property_permission(collection, sender, scope, prop_pemission)?;1611		}16121613		Ok(())1614	}16151616	/// Get collection property.1617	pub fn get_collection_property(1618		collection_id: CollectionId,1619		key: &PropertyKey,1620	) -> Option<PropertyValue> {1621		Self::collection_properties(collection_id).get(key).cloned()1622	}16231624	/// Convert byte vector to property key vector.1625	pub fn bytes_keys_to_property_keys(1626		keys: Vec<Vec<u8>>,1627	) -> Result<Vec<PropertyKey>, DispatchError> {1628		keys.into_iter()1629			.map(|key| -> Result<PropertyKey, DispatchError> {1630				key.try_into()1631					.map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())1632			})1633			.collect::<Result<Vec<PropertyKey>, DispatchError>>()1634	}16351636	/// Get properties according to given keys.1637	pub fn filter_collection_properties(1638		collection_id: CollectionId,1639		keys: Option<Vec<PropertyKey>>,1640	) -> Result<Vec<Property>, DispatchError> {1641		let properties = Self::collection_properties(collection_id);16421643		let properties = keys1644			.map(|keys| {1645				keys.into_iter()1646					.filter_map(|key| {1647						properties.get(&key).map(|value| Property {1648							key,1649							value: value.clone(),1650						})1651					})1652					.collect()1653			})1654			.unwrap_or_else(|| {1655				properties1656					.into_iter()1657					.map(|(key, value)| Property { key, value })1658					.collect()1659			});16601661		Ok(properties)1662	}16631664	/// Get property permissions according to given keys.1665	pub fn filter_property_permissions(1666		collection_id: CollectionId,1667		keys: Option<Vec<PropertyKey>>,1668	) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1669		let permissions = Self::property_permissions(collection_id);16701671		let key_permissions = keys1672			.map(|keys| {1673				keys.into_iter()1674					.filter_map(|key| {1675						permissions1676							.get(&key)1677							.map(|permission| PropertyKeyPermission {1678								key,1679								permission: permission.clone(),1680							})1681					})1682					.collect()1683			})1684			.unwrap_or_else(|| {1685				permissions1686					.into_iter()1687					.map(|(key, permission)| PropertyKeyPermission { key, permission })1688					.collect()1689			});16901691		Ok(key_permissions)1692	}16931694	/// Toggle `user` participation in the `collection`'s allow list.1695	/// #### Store read/writes1696	/// 1 writes1697	pub fn toggle_allowlist(1698		collection: &CollectionHandle<T>,1699		sender: &T::CrossAccountId,1700		user: &T::CrossAccountId,1701		allowed: bool,1702	) -> DispatchResult {1703		collection.check_is_owner_or_admin(sender)?;17041705		// =========17061707		if allowed {1708			<Allowlist<T>>::insert((collection.id, user), true);1709			Self::deposit_event(Event::<T>::AllowListAddressAdded(1710				collection.id,1711				user.clone(),1712			));1713		} else {1714			<Allowlist<T>>::remove((collection.id, user));1715			Self::deposit_event(Event::<T>::AllowListAddressRemoved(1716				collection.id,1717				user.clone(),1718			));1719		}17201721		<PalletEvm<T>>::deposit_log(1722			erc::CollectionHelpersEvents::CollectionChanged {1723				collection_id: eth::collection_id_to_address(collection.id),1724			}1725			.to_log(T::ContractAddress::get()),1726		);17271728		Ok(())1729	}17301731	/// Toggle `user` participation in the `collection`'s admin list.1732	/// #### Store read/writes1733	/// 2 reads, 2 writes1734	pub fn toggle_admin(1735		collection: &CollectionHandle<T>,1736		sender: &T::CrossAccountId,1737		user: &T::CrossAccountId,1738		admin: bool,1739	) -> DispatchResult {1740		collection.check_is_internal()?;1741		collection.check_is_owner(sender)?;17421743		let is_admin = <IsAdmin<T>>::get((collection.id, user));1744		if is_admin == admin {1745			if admin {1746				return Ok(());1747			} else {1748				return Err(Error::<T>::UserIsNotCollectionAdmin.into());1749			}1750		}1751		let amount = <AdminAmount<T>>::get(collection.id);17521753		// =========17541755		if admin {1756			let amount = amount1757				.checked_add(1)1758				.ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1759			ensure!(1760				amount <= Self::collection_admins_limit(),1761				<Error<T>>::CollectionAdminCountExceeded,1762			);17631764			<AdminAmount<T>>::insert(collection.id, amount);1765			<IsAdmin<T>>::insert((collection.id, user), true);17661767			Self::deposit_event(Event::<T>::CollectionAdminAdded(1768				collection.id,1769				user.clone(),1770			));1771		} else {1772			<AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1773			<IsAdmin<T>>::remove((collection.id, user));17741775			Self::deposit_event(Event::<T>::CollectionAdminRemoved(1776				collection.id,1777				user.clone(),1778			));1779		}17801781		<PalletEvm<T>>::deposit_log(1782			erc::CollectionHelpersEvents::CollectionChanged {1783				collection_id: eth::collection_id_to_address(collection.id),1784			}1785			.to_log(T::ContractAddress::get()),1786		);17871788		Ok(())1789	}17901791	/// Update collection limits.1792	pub fn update_limits(1793		user: &T::CrossAccountId,1794		collection: &mut CollectionHandle<T>,1795		new_limit: CollectionLimits,1796	) -> DispatchResult {1797		collection.check_is_internal()?;1798		collection.check_is_owner_or_admin(user)?;17991800		collection.limits =1801			Self::clamp_limits(collection.mode.clone(), &collection.limits, new_limit)?;18021803		Self::deposit_event(Event::<T>::CollectionLimitSet(collection.id));1804		<PalletEvm<T>>::deposit_log(1805			erc::CollectionHelpersEvents::CollectionChanged {1806				collection_id: eth::collection_id_to_address(collection.id),1807			}1808			.to_log(T::ContractAddress::get()),1809		);18101811		collection.save()1812	}18131814	/// Merge set fields from `new_limit` to `old_limit`.1815	fn clamp_limits(1816		mode: CollectionMode,1817		old_limit: &CollectionLimits,1818		mut new_limit: CollectionLimits,1819	) -> Result<CollectionLimits, DispatchError> {1820		let limits = old_limit;1821		limit_default!(old_limit, new_limit,1822			account_token_ownership_limit => ensure!(1823				new_limit <= MAX_TOKEN_OWNERSHIP,1824				<Error<T>>::CollectionLimitBoundsExceeded,1825			),1826			sponsored_data_size => ensure!(1827				new_limit <= CUSTOM_DATA_LIMIT,1828				<Error<T>>::CollectionLimitBoundsExceeded,1829			),18301831			sponsored_data_rate_limit => {},1832			token_limit => ensure!(1833				old_limit >= new_limit && new_limit > 0,1834				<Error<T>>::CollectionTokenLimitExceeded1835			),18361837			sponsor_transfer_timeout(match mode {1838				CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1839				CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1840				CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1841			}) => ensure!(1842				new_limit <= MAX_SPONSOR_TIMEOUT,1843				<Error<T>>::CollectionLimitBoundsExceeded,1844			),1845			sponsor_approve_timeout => {},1846			owner_can_transfer => ensure!(1847				!limits.owner_can_transfer_instaled() ||1848				old_limit || !new_limit,1849				<Error<T>>::OwnerPermissionsCantBeReverted,1850			),1851			owner_can_destroy => ensure!(1852				old_limit || !new_limit,1853				<Error<T>>::OwnerPermissionsCantBeReverted,1854			),1855			transfers_enabled => {},1856		);1857		Ok(new_limit)1858	}18591860	/// Update collection permissions.1861	pub fn update_permissions(1862		user: &T::CrossAccountId,1863		collection: &mut CollectionHandle<T>,1864		new_permission: CollectionPermissions,1865	) -> DispatchResult {1866		collection.check_is_internal()?;1867		collection.check_is_owner_or_admin(user)?;1868		collection.permissions = Self::clamp_permissions(1869			collection.mode.clone(),1870			&collection.permissions,1871			new_permission,1872		)?;18731874		Self::deposit_event(Event::<T>::CollectionPermissionSet(collection.id));1875		<PalletEvm<T>>::deposit_log(1876			erc::CollectionHelpersEvents::CollectionChanged {1877				collection_id: eth::collection_id_to_address(collection.id),1878			}1879			.to_log(T::ContractAddress::get()),1880		);18811882		collection.save()1883	}18841885	/// Merge set fields from `new_permission` to `old_permission`.1886	fn clamp_permissions(1887		_mode: CollectionMode,1888		old_permission: &CollectionPermissions,1889		mut new_permission: CollectionPermissions,1890	) -> Result<CollectionPermissions, DispatchError> {1891		limit_default_clone!(old_permission, new_permission,1892			access => {},1893			mint_mode => {},1894			nesting => { /* todo check for permissive, if only it gets out of benchmarks */ },1895		);1896		Ok(new_permission)1897	}18981899	/// Repair possibly broken properties of a collection.1900	pub fn repair_collection(collection_id: CollectionId) -> DispatchResult {1901		CollectionProperties::<T>::mutate(collection_id, |properties| {1902			properties.recompute_consumed_space();1903		});19041905		Ok(())1906	}1907}19081909/// Indicates unsupported methods by returning [Error::UnsupportedOperation].1910#[macro_export]1911macro_rules! unsupported {1912	($runtime:path) => {1913		Err($crate::Error::<$runtime>::UnsupportedOperation.into())1914	};1915}19161917/// Return weights for various worst-case operations.1918pub trait CommonWeightInfo<CrossAccountId> {1919	/// Weight of item creation.1920	fn create_item(data: &CreateItemData) -> Weight {1921		Self::create_multiple_items(from_ref(data))1922	}19231924	/// Weight of items creation.1925	fn create_multiple_items(amount: &[CreateItemData]) -> Weight;19261927	/// Weight of items creation.1928	fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;19291930	/// The weight of the burning item.1931	fn burn_item() -> Weight;19321933	/// Property setting weight.1934	///1935	/// * `amount`- The number of properties to set.1936	fn set_collection_properties(amount: u32) -> Weight;19371938	/// Collection property deletion weight.1939	///1940	/// * `amount`- The number of properties to set.1941	fn delete_collection_properties(amount: u32) -> Weight;19421943	/// Token property setting weight.1944	///1945	/// * `amount`- The number of properties to set.1946	fn set_token_properties(amount: u32) -> Weight;19471948	/// Token property deletion weight.1949	///1950	/// * `amount`- The number of properties to delete.1951	fn delete_token_properties(amount: u32) -> Weight;19521953	/// Token property permissions set weight.1954	///1955	/// * `amount`- The number of property permissions to set.1956	fn set_token_property_permissions(amount: u32) -> Weight;19571958	/// Transfer price of the token or its parts.1959	fn transfer() -> Weight;19601961	/// The price of setting the permission of the operation from another user.1962	fn approve() -> Weight;19631964	/// The price of setting the permission of the operation from another user for eth mirror.1965	fn approve_from() -> Weight;19661967	/// Transfer price from another user.1968	fn transfer_from() -> Weight;19691970	/// The price of burning a token from another user.1971	fn burn_from() -> Weight;19721973	/// Differs from burn_item in case of Fungible and Refungible, as it should burn1974	/// whole users's balance.1975	///1976	/// This method shouldn't be used directly, as it doesn't count breadth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1977	fn burn_recursively_self_raw() -> Weight;19781979	/// Cost of iterating over `amount` children while burning, without counting child burning itself.1980	///1981	/// This method shouldn't be used directly, as it doesn't count depth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1982	fn burn_recursively_breadth_raw(amount: u32) -> Weight;19831984	/// The price of recursive burning a token.1985	///1986	/// `max_selfs` - The maximum burning weight of the token itself.1987	/// `max_breadth` - The maximum number of nested tokens to burn.1988	fn burn_recursively(max_selfs: u32, max_breadth: u32) -> Weight {1989		Self::burn_recursively_self_raw()1990			.saturating_mul(max_selfs.max(1) as u64)1991			.saturating_add(Self::burn_recursively_breadth_raw(max_breadth))1992	}19931994	/// The price of retrieving token owner1995	fn token_owner() -> Weight;19961997	/// The price of setting approval for all1998	fn set_allowance_for_all() -> Weight;19992000	/// The price of repairing an item.2001	fn force_repair_item() -> Weight;2002}20032004/// Weight info extension trait for refungible pallet.2005pub trait RefungibleExtensionsWeightInfo {2006	/// Weight of token repartition.2007	fn repartition() -> Weight;2008}20092010/// Common collection operations.2011///2012/// It wraps methods in Fungible, Nonfungible and Refungible pallets2013/// and adds weight info.2014pub trait CommonCollectionOperations<T: Config> {2015	/// Create token.2016	///2017	/// * `sender` - The user who mint the token and pays for the transaction.2018	/// * `to` - The user who will own the token.2019	/// * `data` - Token data.2020	/// * `nesting_budget` - A budget that can be spent on nesting tokens.2021	fn create_item(2022		&self,2023		sender: T::CrossAccountId,2024		to: T::CrossAccountId,2025		data: CreateItemData,2026		nesting_budget: &dyn Budget,2027	) -> DispatchResultWithPostInfo;20282029	/// Create multiple tokens.2030	///2031	/// * `sender` - The user who mint the token and pays for the transaction.2032	/// * `to` - The user who will own the token.2033	/// * `data` - Token data.2034	/// * `nesting_budget` - A budget that can be spent on nesting tokens.2035	fn create_multiple_items(2036		&self,2037		sender: T::CrossAccountId,2038		to: T::CrossAccountId,2039		data: Vec<CreateItemData>,2040		nesting_budget: &dyn Budget,2041	) -> DispatchResultWithPostInfo;20422043	/// Create multiple tokens.2044	///2045	/// * `sender` - The user who mint the token and pays for the transaction.2046	/// * `to` - The user who will own the token.2047	/// * `data` - Token data.2048	/// * `nesting_budget` - A budget that can be spent on nesting tokens.2049	fn create_multiple_items_ex(2050		&self,2051		sender: T::CrossAccountId,2052		data: CreateItemExData<T::CrossAccountId>,2053		nesting_budget: &dyn Budget,2054	) -> DispatchResultWithPostInfo;20552056	/// Burn token.2057	///2058	/// * `sender` - The user who owns the token.2059	/// * `token` - Token id that will burned.2060	/// * `amount` - The number of parts of the token that will be burned.2061	fn burn_item(2062		&self,2063		sender: T::CrossAccountId,2064		token: TokenId,2065		amount: u128,2066	) -> DispatchResultWithPostInfo;20672068	/// Burn token and all nested tokens recursievly.2069	///2070	/// * `sender` - The user who owns the token.2071	/// * `token` - Token id that will burned.2072	/// * `self_budget` - The budget that can be spent on burning tokens.2073	/// * `breadth_budget` - The budget that can be spent on burning nested tokens.2074	fn burn_item_recursively(2075		&self,2076		sender: T::CrossAccountId,2077		token: TokenId,2078		self_budget: &dyn Budget,2079		breadth_budget: &dyn Budget,2080	) -> DispatchResultWithPostInfo;20812082	/// Set collection properties.2083	///2084	/// * `sender` - Must be either the owner of the collection or its admin.2085	/// * `properties` - Properties to be set.2086	fn set_collection_properties(2087		&self,2088		sender: T::CrossAccountId,2089		properties: Vec<Property>,2090	) -> DispatchResultWithPostInfo;20912092	/// Delete collection properties.2093	///2094	/// * `sender` - Must be either the owner of the collection or its admin.2095	/// * `properties` - The properties to be removed.2096	fn delete_collection_properties(2097		&self,2098		sender: &T::CrossAccountId,2099		property_keys: Vec<PropertyKey>,2100	) -> DispatchResultWithPostInfo;21012102	/// Set token properties.2103	///2104	/// The appropriate [`PropertyPermission`] for the token property2105	/// must be set with [`Self::set_token_property_permissions`].2106	///2107	/// * `sender` - Must be either the owner of the token or its admin.2108	/// * `token_id` - The token for which the properties are being set.2109	/// * `properties` - Properties to be set.2110	/// * `budget` - Budget for setting properties.2111	fn set_token_properties(2112		&self,2113		sender: T::CrossAccountId,2114		token_id: TokenId,2115		properties: Vec<Property>,2116		budget: &dyn Budget,2117	) -> DispatchResultWithPostInfo;21182119	/// Remove token properties.2120	///2121	/// The appropriate [`PropertyPermission`] for the token property2122	/// must be set with [`Self::set_token_property_permissions`].2123	///2124	/// * `sender` - Must be either the owner of the token or its admin.2125	/// * `token_id` - The token for which the properties are being remove.2126	/// * `property_keys` - Keys to remove corresponding properties.2127	/// * `budget` - Budget for removing properties.2128	fn delete_token_properties(2129		&self,2130		sender: T::CrossAccountId,2131		token_id: TokenId,2132		property_keys: Vec<PropertyKey>,2133		budget: &dyn Budget,2134	) -> DispatchResultWithPostInfo;21352136	/// Set token property permissions.2137	///2138	/// * `sender` - Must be either the owner of the token or its admin.2139	/// * `token_id` - The token for which the properties are being set.2140	/// * `property_permissions` - Property permissions to be set.2141	/// * `budget` - Budget for setting properties.2142	fn set_token_property_permissions(2143		&self,2144		sender: &T::CrossAccountId,2145		property_permissions: Vec<PropertyKeyPermission>,2146	) -> DispatchResultWithPostInfo;21472148	/// Transfer amount of token pieces.2149	///2150	/// * `sender` - Donor user.2151	/// * `to` - Recepient user.2152	/// * `token` - The token of which parts are being sent.2153	/// * `amount` - The number of parts of the token that will be transferred.2154	/// * `budget` - The maximum budget that can be spent on the transfer.2155	fn transfer(2156		&self,2157		sender: T::CrossAccountId,2158		to: T::CrossAccountId,2159		token: TokenId,2160		amount: u128,2161		budget: &dyn Budget,2162	) -> DispatchResultWithPostInfo;21632164	/// Grant access to another account to transfer parts of the token owned by the calling user via [Self::transfer_from].2165	///2166	/// * `sender` - The user who grants access to the token.2167	/// * `spender` - The user to whom the rights are granted.2168	/// * `token` - The token to which access is granted.2169	/// * `amount` - The amount of pieces that another user can dispose of.2170	fn approve(2171		&self,2172		sender: T::CrossAccountId,2173		spender: T::CrossAccountId,2174		token: TokenId,2175		amount: u128,2176	) -> DispatchResultWithPostInfo;21772178	/// Grant access to another account to transfer parts of the token owned by the calling user's eth mirror via [Self::transfer_from].2179	///2180	/// * `sender` - The user who grants access to the token.2181	/// * `from` - Spender's eth mirror.2182	/// * `to` - The user to whom the rights are granted.2183	/// * `token` - The token to which access is granted.2184	/// * `amount` - The amount of pieces that another user can dispose of.2185	fn approve_from(2186		&self,2187		sender: T::CrossAccountId,2188		from: T::CrossAccountId,2189		to: T::CrossAccountId,2190		token: TokenId,2191		amount: u128,2192	) -> DispatchResultWithPostInfo;21932194	/// Send parts of a token owned by another user.2195	///2196	/// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2197	///2198	/// * `sender` - The user who must have access to the token (see [`Self::approve`]).2199	/// * `from` - The user who owns the token.2200	/// * `to` - Recepient user.2201	/// * `token` - The token of which parts are being sent.2202	/// * `amount` - The number of parts of the token that will be transferred.2203	/// * `budget` - The maximum budget that can be spent on the transfer.2204	fn transfer_from(2205		&self,2206		sender: T::CrossAccountId,2207		from: T::CrossAccountId,2208		to: T::CrossAccountId,2209		token: TokenId,2210		amount: u128,2211		budget: &dyn Budget,2212	) -> DispatchResultWithPostInfo;22132214	/// Burn parts of a token owned by another user.2215	///2216	/// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2217	///2218	/// * `sender` - The user who must have access to the token (see [`Self::approve`]).2219	/// * `from` - The user who owns the token.2220	/// * `token` - The token of which parts are being sent.2221	/// * `amount` - The number of parts of the token that will be transferred.2222	/// * `budget` - The maximum budget that can be spent on the burn.2223	fn burn_from(2224		&self,2225		sender: T::CrossAccountId,2226		from: T::CrossAccountId,2227		token: TokenId,2228		amount: u128,2229		budget: &dyn Budget,2230	) -> DispatchResultWithPostInfo;22312232	/// Check permission to nest token.2233	///2234	/// * `sender` - The user who initiated the check.2235	/// * `from` - The token that is checked for embedding.2236	/// * `under` - Token under which to check.2237	/// * `budget` - The maximum budget that can be spent on the check.2238	fn check_nesting(2239		&self,2240		sender: T::CrossAccountId,2241		from: (CollectionId, TokenId),2242		under: TokenId,2243		budget: &dyn Budget,2244	) -> DispatchResult;22452246	/// Nest one token into another.2247	///2248	/// * `under` - Token holder.2249	/// * `to_nest` - Nested token.2250	fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));22512252	/// Unnest token.2253	///2254	/// * `under` - Token holder.2255	/// * `to_nest` - Token to unnest.2256	fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));22572258	/// Get all user tokens.2259	///2260	/// * `account` - Account for which you need to get tokens.2261	fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;22622263	/// Get all the tokens in the collection.2264	fn collection_tokens(&self) -> Vec<TokenId>;22652266	/// Check if the token exists.2267	///2268	/// * `token` - Id token to check.2269	fn token_exists(&self, token: TokenId) -> bool;22702271	/// Get the id of the last minted token.2272	fn last_token_id(&self) -> TokenId;22732274	/// Get the owner of the token.2275	///2276	/// * `token` - The token for which you need to find out the owner.2277	fn token_owner(&self, token: TokenId) -> Result<T::CrossAccountId, TokenOwnerError>;22782279	/// Returns 10 tokens owners in no particular order.2280	///2281	/// * `token` - The token for which you need to find out the owners.2282	fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId>;22832284	/// Get the value of the token property by key.2285	///2286	/// * `token` - Token with the property to get.2287	/// * `key` - Property name.2288	fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;22892290	/// Get a set of token properties by key vector.2291	///2292	/// * `token` - Token with the property to get.2293	/// * `keys` - Vector of property keys. If this parameter is [None](sp_std::result::Result),2294	/// then all properties are returned.2295	fn token_properties(&self, token: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;22962297	/// Amount of unique collection tokens2298	fn total_supply(&self) -> u32;22992300	/// Amount of different tokens account has.2301	///2302	/// * `account` - The account for which need to get the balance.2303	fn account_balance(&self, account: T::CrossAccountId) -> u32;23042305	/// Amount of specific token account have.2306	fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;23072308	/// Amount of token pieces2309	fn total_pieces(&self, token: TokenId) -> Option<u128>;23102311	/// Get the number of parts of the token that a trusted user can manage.2312	///2313	/// * `sender` - Trusted user.2314	/// * `spender` - Owner of the token.2315	/// * `token` - The token for which to get the value.2316	fn allowance(2317		&self,2318		sender: T::CrossAccountId,2319		spender: T::CrossAccountId,2320		token: TokenId,2321	) -> u128;23222323	/// Get extension for RFT collection.2324	fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>>;23252326	/// The `operator` is allowed to transfer all tokens of the `owner` on their behalf.2327	/// * `owner` - Token owner2328	/// * `operator` - Operator2329	/// * `approve` - Should operator status be granted or revoked?2330	fn set_allowance_for_all(2331		&self,2332		owner: T::CrossAccountId,2333		operator: T::CrossAccountId,2334		approve: bool,2335	) -> DispatchResultWithPostInfo;23362337	/// Tells whether the given `owner` approves the `operator`.2338	fn allowance_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool;23392340	/// Repairs a possibly broken item.2341	fn repair_item(&self, token: TokenId) -> DispatchResultWithPostInfo;2342}23432344/// Extension for RFT collection.2345pub trait RefungibleExtensions<T>2346where2347	T: Config,2348{2349	/// Change the number of parts of the token.2350	///2351	/// When the value changes down, this function is equivalent to burning parts of the token.2352	///2353	/// * `sender` - The user calling the repartition operation. Must be the owner of the token.2354	/// * `token` - The token for which you want to change the number of parts.2355	/// * `amount` - The new value of the parts of the token.2356	fn repartition(2357		&self,2358		sender: &T::CrossAccountId,2359		token: TokenId,2360		amount: u128,2361	) -> DispatchResultWithPostInfo;2362}23632364/// Merge [`DispatchResult`] with [`Weight`] into [`DispatchResultWithPostInfo`].2365///2366/// Used for [`CommonCollectionOperations`] implementations and flexible enough to do so.2367pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {2368	let post_info = PostDispatchInfo {2369		actual_weight: Some(weight),2370		pays_fee: Pays::Yes,2371	};2372	match res {2373		Ok(()) => Ok(post_info),2374		Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),2375	}2376}23772378impl<T: Config> From<PropertiesError> for Error<T> {2379	fn from(error: PropertiesError) -> Self {2380		match error {2381			PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,2382			PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,2383			PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,2384			PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,2385			PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,2386		}2387	}2388}23892390#[cfg(feature = "tests")]2391pub mod tests {2392	use crate::{DispatchResult, DispatchError, LazyValue, Config};23932394	const fn to_bool(u: u8) -> bool {2395		u != 02396	}23972398	#[derive(Debug)]2399	pub struct TestCase {2400		pub collection_admin: bool,2401		pub is_collection_admin: bool,2402		pub token_owner: bool,2403		pub is_token_owner: bool,2404		pub no_permission: bool,2405	}24062407	impl TestCase {2408		const fn new(2409			collection_admin: u8,2410			is_collection_admin: u8,2411			token_owner: u8,2412			is_token_owner: u8,2413			no_permission: u8,2414		) -> Self {2415			Self {2416				collection_admin: to_bool(collection_admin),2417				is_collection_admin: to_bool(is_collection_admin),2418				token_owner: to_bool(token_owner),2419				is_token_owner: to_bool(is_token_owner),2420				no_permission: to_bool(no_permission),2421			}2422		}2423	}24242425	#[rustfmt::skip]2426	pub const table: [TestCase; 16] = [2427		//                    ┌╴collection_admin2428		//                    │  ┌╴is_collection_admin2429		//                    │  │   ┌╴token_owner2430		//                    │  │   │  ┌╴is_token_ownership2431		//                    │  │   │  │   ┌╴no_permission2432		/*  0*/ TestCase::new(0, 0,  0, 0,  1),2433		/*  1*/ TestCase::new(0, 0,  0, 1,  1),2434		/*  2*/ TestCase::new(0, 0,  1, 0,  1),2435		/*  3*/ TestCase::new(0, 0,  1, 1,  0),2436		/*  4*/ TestCase::new(0, 1,  0, 0,  1),2437		/*  5*/ TestCase::new(0, 1,  0, 1,  1),2438		/*  6*/ TestCase::new(0, 1,  1, 0,  1),2439		/*  7*/ TestCase::new(0, 1,  1, 1,  0),2440		/*  8*/ TestCase::new(1, 0,  0, 0,  1),2441		/*  9*/ TestCase::new(1, 0,  0, 1,  1),2442		/* 10*/ TestCase::new(1, 0,  1, 0,  1),2443		/* 11*/ TestCase::new(1, 0,  1, 1,  0),2444		/* 12*/ TestCase::new(1, 1,  0, 0,  0),2445		/* 13*/ TestCase::new(1, 1,  0, 1,  0),2446		/* 14*/ TestCase::new(1, 1,  1, 0,  0),2447		/* 15*/ TestCase::new(1, 1,  1, 1,  0),2448	];24492450	pub fn check_token_permissions<T, FCA, FTO, FTE>(2451		collection_admin_permitted: bool,2452		token_owner_permitted: bool,2453		is_collection_admin: &mut LazyValue<bool, FCA>,2454		check_token_ownership: &mut LazyValue<Result<bool, DispatchError>, FTO>,2455		check_token_existence: &mut LazyValue<bool, FTE>,2456	) -> DispatchResult2457	where2458		T: Config,2459		FCA: FnOnce() -> bool,2460		FTO: FnOnce() -> Result<bool, DispatchError>,2461		FTE: FnOnce() -> bool,2462	{2463		crate::check_token_permissions::<T, FCA, FTO, FTE>(2464			collection_admin_permitted,2465			token_owner_permitted,2466			is_collection_admin,2467			check_token_ownership,2468			check_token_existence,2469		)2470	}2471}
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::{57	ops::{Deref, DerefMut},58	slice::from_ref,59};60use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};61use sp_std::vec::Vec;62use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};63use evm_coder::ToLog;64use frame_support::{65	dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},66	ensure,67	traits::{68		Get,69		fungible::{Balanced, Debt, Inspect},70		tokens::{Imbalance, Precision, Preservation},71	},72	dispatch::Pays,73	transactional, fail,74};75use up_data_structs::{76	AccessMode, COLLECTION_NUMBER_LIMIT, Collection, RpcCollection, RpcCollectionFlags,77	CollectionId, CreateItemData, MAX_TOKEN_PREFIX_LENGTH, COLLECTION_ADMINS_LIMIT, TokenId,78	TokenChild, CollectionStats, MAX_TOKEN_OWNERSHIP, CollectionMode, NFT_SPONSOR_TRANSFER_TIMEOUT,79	FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, MAX_SPONSOR_TIMEOUT,80	CUSTOM_DATA_LIMIT, CollectionLimits, CreateCollectionData, SponsorshipState, CreateItemExData,81	SponsoringRateLimit, budget::Budget, PhantomType, Property,82	CollectionProperties as CollectionPropertiesT, TokenProperties, PropertiesPermissionMap,83	PropertyKey, PropertyValue, PropertyPermission, PropertiesError, TokenOwnerError,84	PropertyKeyPermission, TokenData, TrySetProperty, PropertyScope, CollectionPermissions,85};86use up_pov_estimate_rpc::PovInfo;8788pub use pallet::*;89use sp_core::H160;90use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, traits::Zero};9192#[cfg(feature = "runtime-benchmarks")]93pub mod benchmarking;94pub mod dispatch;95pub mod erc;96pub mod eth;97pub mod helpers;98#[allow(missing_docs)]99pub mod weights;100/// Weight info.101pub type SelfWeightOf<T> = <T as Config>::WeightInfo;102103/// Collection handle contains information about collection data and id.104/// Also provides functionality to count consumed gas.105///106/// CollectionHandle is used as a generic wrapper for collections of all types (except native fungible).107/// It allows to perform common operations and queries on any collection type,108/// both completely general for all, as well as their respective implementations of [`CommonCollectionOperations`].109#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]110pub struct CollectionHandle<T: Config> {111	/// Collection id112	pub id: CollectionId,113	collection: Collection<T::AccountId>,114	/// Substrate recorder for counting consumed gas115	pub recorder: SubstrateRecorder<T>,116}117118impl<T: Config> WithRecorder<T> for CollectionHandle<T> {119	fn recorder(&self) -> &SubstrateRecorder<T> {120		&self.recorder121	}122	fn into_recorder(self) -> SubstrateRecorder<T> {123		self.recorder124	}125}126127impl<T: Config> CollectionHandle<T> {128	/// Same as [CollectionHandle::new] but with an explicit gas limit.129	pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {130		Self::new_with_recorder(id, SubstrateRecorder::new(gas_limit))131	}132133	/// Same as [CollectionHandle::new] but with an existed [`SubstrateRecorder`].134	pub fn new_with_recorder(id: CollectionId, recorder: SubstrateRecorder<T>) -> Option<Self> {135		<CollectionById<T>>::get(id).map(|collection| Self {136			id,137			collection,138			recorder,139		})140	}141142	/// Retrives collection data from storage and creates collection handle with default parameters.143	/// If collection not found return `None`144	pub fn new(id: CollectionId) -> Option<Self> {145		Self::new_with_gas_limit(id, u64::MAX)146	}147148	/// Same as [`CollectionHandle::new`] but if collection not found [CollectionNotFound](Error::CollectionNotFound) returned.149	pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {150		Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)151	}152153	/// Consume gas for reading.154	pub fn consume_store_reads(155		&self,156		reads: u64,157	) -> pallet_evm_coder_substrate::execution::Result<()> {158		self.recorder().consume_store_reads(reads)159	}160161	/// Consume gas for writing.162	pub fn consume_store_writes(163		&self,164		writes: u64,165	) -> pallet_evm_coder_substrate::execution::Result<()> {166		self.recorder().consume_store_writes(writes)167	}168169	/// Consume gas for reading and writing.170	pub fn consume_store_reads_and_writes(171		&self,172		reads: u64,173		writes: u64,174	) -> pallet_evm_coder_substrate::execution::Result<()> {175		self.recorder()176			.consume_store_reads_and_writes(reads, writes)177	}178179	/// Save collection to storage.180	pub fn save(&self) -> DispatchResult {181		<CollectionById<T>>::insert(self.id, &self.collection);182		Ok(())183	}184185	/// Set collection sponsor.186	///187	/// Unique collections allows sponsoring for certain actions.188	/// This method allows you to set the sponsor of the collection.189	/// In order for sponsorship to become active, it must be confirmed through [`Self::confirm_sponsorship`].190	pub fn set_sponsor(191		&mut self,192		sender: &T::CrossAccountId,193		sponsor: T::AccountId,194	) -> DispatchResult {195		self.check_is_internal()?;196		self.check_is_owner_or_admin(sender)?;197198		self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor.clone());199200		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor));201		<PalletEvm<T>>::deposit_log(202			erc::CollectionHelpersEvents::CollectionChanged {203				collection_id: eth::collection_id_to_address(self.id),204			}205			.to_log(T::ContractAddress::get()),206		);207208		self.save()209	}210211	/// Force set `sponsor`.212	///213	/// Differs from [`set_sponsor`][`Self::set_sponsor`] in that confirmation214	/// from the `sponsor` is not required.215	///216	/// # Arguments217	///218	/// * `sponsor`: ID of the account of the sponsor-to-be.219	pub fn force_set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {220		self.check_is_internal()?;221222		self.collection.sponsorship = SponsorshipState::Confirmed(sponsor.clone());223224		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor.clone()));225		<Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sponsor));226		<PalletEvm<T>>::deposit_log(227			erc::CollectionHelpersEvents::CollectionChanged {228				collection_id: eth::collection_id_to_address(self.id),229			}230			.to_log(T::ContractAddress::get()),231		);232233		self.save()234	}235236	/// Confirm sponsorship237	///238	/// In order for the sponsorship to become active, the user set as the sponsor must confirm their participation.239	/// Before confirming sponsorship, the user must be specified as the sponsor of the collection via [`Self::set_sponsor`].240	pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> DispatchResult {241		self.check_is_internal()?;242		ensure!(243			self.collection.sponsorship.pending_sponsor() == Some(sender),244			Error::<T>::ConfirmSponsorshipFail245		);246247		self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());248249		<Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sender.clone()));250		<PalletEvm<T>>::deposit_log(251			erc::CollectionHelpersEvents::CollectionChanged {252				collection_id: eth::collection_id_to_address(self.id),253			}254			.to_log(T::ContractAddress::get()),255		);256257		self.save()258	}259260	/// Remove collection sponsor.261	pub fn remove_sponsor(&mut self, sender: &T::CrossAccountId) -> DispatchResult {262		self.check_is_internal()?;263		self.check_is_owner_or_admin(sender)?;264265		self.collection.sponsorship = SponsorshipState::Disabled;266267		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));268		<PalletEvm<T>>::deposit_log(269			erc::CollectionHelpersEvents::CollectionChanged {270				collection_id: eth::collection_id_to_address(self.id),271			}272			.to_log(T::ContractAddress::get()),273		);274		self.save()275	}276277	/// Force remove `sponsor`.278	///279	/// Differs from `remove_sponsor` in that280	/// it doesn't require consent from the `owner` of the collection.281	pub fn force_remove_sponsor(&mut self) -> DispatchResult {282		self.check_is_internal()?;283284		self.collection.sponsorship = SponsorshipState::Disabled;285286		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));287		<PalletEvm<T>>::deposit_log(288			erc::CollectionHelpersEvents::CollectionChanged {289				collection_id: eth::collection_id_to_address(self.id),290			}291			.to_log(T::ContractAddress::get()),292		);293		self.save()294	}295296	/// Checks that the collection was created with, and must be operated upon through **Unique API**.297	/// Now check only the `external` flag and if it's **true**, then return [`Error::CollectionIsExternal`] error.298	pub fn check_is_internal(&self) -> DispatchResult {299		if self.flags.external {300			return Err(<Error<T>>::CollectionIsExternal)?;301		}302303		Ok(())304	}305306	/// Checks that the collection was created with, and must be operated upon through an **assimilated API**.307	/// Now check only the `external` flag and if it's **false**, then return [`Error::CollectionIsInternal`] error.308	pub fn check_is_external(&self) -> DispatchResult {309		if !self.flags.external {310			return Err(<Error<T>>::CollectionIsInternal)?;311		}312313		Ok(())314	}315}316317impl<T: Config> Deref for CollectionHandle<T> {318	type Target = Collection<T::AccountId>;319320	fn deref(&self) -> &Self::Target {321		&self.collection322	}323}324325impl<T: Config> DerefMut for CollectionHandle<T> {326	fn deref_mut(&mut self) -> &mut Self::Target {327		&mut self.collection328	}329}330331impl<T: Config> CollectionHandle<T> {332	/// Checks if the `user` is the owner of the collection.333	pub fn check_is_owner(&self, user: &T::CrossAccountId) -> DispatchResult {334		ensure!(*user.as_sub() == self.owner, <Error<T>>::NoPermission);335		Ok(())336	}337338	/// Returns **true** if the `user` is the owner or administrator of the collection.339	pub fn is_owner_or_admin(&self, user: &T::CrossAccountId) -> bool {340		*user.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, user))341	}342343	/// Checks if the `user` is the owner or administrator of the collection.344	pub fn check_is_owner_or_admin(&self, user: &T::CrossAccountId) -> DispatchResult {345		ensure!(self.is_owner_or_admin(user), <Error<T>>::NoPermission);346		Ok(())347	}348349	/// Returns **true** if350	/// * the `user`is a collection owner or admin351	/// * the collection limits allow the owner/admins to transfer/burn any collection token352	pub fn ignores_token_restrictions(&self, user: &T::CrossAccountId) -> bool {353		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)354	}355356	/// Return **true** if `user` does not have enough token parts, and he can ignore such restrictions.357	pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {358		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)359	}360361	/// Checks if the user is in the allow list. If not [Error::AddressNotInAllowlist] returns.362	pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {363		ensure!(364			<Allowlist<T>>::get((self.id, user)),365			<Error<T>>::AddressNotInAllowlist366		);367		Ok(())368	}369370	/// Changes collection owner to another account371	/// #### Store read/writes372	/// 1 writes373	pub fn change_owner(374		&mut self,375		caller: T::CrossAccountId,376		new_owner: T::CrossAccountId,377	) -> DispatchResult {378		self.check_is_internal()?;379		self.check_is_owner(&caller)?;380		self.collection.owner = new_owner.as_sub().clone();381382		<Pallet<T>>::deposit_event(Event::<T>::CollectionOwnerChanged(383			self.id,384			new_owner.as_sub().clone(),385		));386		<PalletEvm<T>>::deposit_log(387			erc::CollectionHelpersEvents::CollectionChanged {388				collection_id: eth::collection_id_to_address(self.id),389			}390			.to_log(T::ContractAddress::get()),391		);392393		self.save()394	}395}396397#[frame_support::pallet]398pub mod pallet {399400	use super::*;401	use dispatch::CollectionDispatch;402	use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};403	use up_data_structs::{TokenId, mapping::TokenAddressMapping};404	use scale_info::TypeInfo;405	use weights::WeightInfo;406407	#[pallet::config]408	pub trait Config:409		frame_system::Config + pallet_evm_coder_substrate::Config + pallet_evm::Config + TypeInfo410	{411		/// Weight information for functions of this pallet.412		type WeightInfo: WeightInfo;413414		/// Events compatible with [`frame_system::Config::Event`].415		type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;416417		/// Handler of accounts and payment.418		type Currency: Balanced<Self::AccountId> + Inspect<Self::AccountId>;419420		/// Set price to create a collection.421		#[pallet::constant]422		type CollectionCreationPrice: Get<423			<<Self as Config>::Currency as Inspect<Self::AccountId>>::Balance,424		>;425426		/// Dispatcher of operations on collections.427		type CollectionDispatch: CollectionDispatch<Self>;428429		/// Account which holds the chain's treasury.430		type TreasuryAccountId: Get<Self::AccountId>;431432		/// Address under which the CollectionHelper contract would be available.433		#[pallet::constant]434		type ContractAddress: Get<H160>;435436		/// Mapper for token addresses to Ethereum addresses.437		type EvmTokenAddressMapping: TokenAddressMapping<H160>;438439		/// Mapper for token addresses to [`CrossAccountId`].440		type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;441	}442443	const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);444	/// Collection id for native fungible collction.445	pub const NATIVE_FUNGIBLE_COLLECTION_ID: CollectionId = CollectionId(0);446447	#[pallet::pallet]448	#[pallet::storage_version(STORAGE_VERSION)]449	pub struct Pallet<T>(_);450451	#[pallet::extra_constants]452	impl<T: Config> Pallet<T> {453		/// Maximum admins per collection.454		pub fn collection_admins_limit() -> u32 {455			COLLECTION_ADMINS_LIMIT456		}457	}458459	#[pallet::genesis_config]460	pub struct GenesisConfig<T>(PhantomData<T>);461462	#[cfg(feature = "std")]463	impl<T: Config> Default for GenesisConfig<T> {464		fn default() -> Self {465			Self(Default::default())466		}467	}468469	#[pallet::genesis_build]470	impl<T: Config> GenesisBuild<T> for GenesisConfig<T> {471		fn build(&self) {472			StorageVersion::new(1).put::<Pallet<T>>();473		}474	}475476	impl<T: Config> Pallet<T> {477		/// Helper function that handles deposit events478		pub fn deposit_event(event: Event<T>) {479			let event = <T as Config>::RuntimeEvent::from(event);480			let event = event.into();481			<frame_system::Pallet<T>>::deposit_event(event)482		}483	}484485	#[pallet::event]486	pub enum Event<T: Config> {487		/// New collection was created488		CollectionCreated(489			/// Globally unique identifier of newly created collection.490			CollectionId,491			/// [`CollectionMode`] converted into _u8_.492			u8,493			/// Collection owner.494			T::AccountId,495		),496497		/// New collection was destroyed498		CollectionDestroyed(499			/// Globally unique identifier of collection.500			CollectionId,501		),502503		/// New item was created.504		ItemCreated(505			/// Id of the collection where item was created.506			CollectionId,507			/// Id of an item. Unique within the collection.508			TokenId,509			/// Owner of newly created item510			T::CrossAccountId,511			/// Always 1 for NFT512			u128,513		),514515		/// Collection item was burned.516		ItemDestroyed(517			/// Id of the collection where item was destroyed.518			CollectionId,519			/// Identifier of burned NFT.520			TokenId,521			/// Which user has destroyed its tokens.522			T::CrossAccountId,523			/// Amount of token pieces destroed. Always 1 for NFT.524			u128,525		),526527		/// Item was transferred528		Transfer(529			/// Id of collection to which item is belong.530			CollectionId,531			/// Id of an item.532			TokenId,533			/// Original owner of item.534			T::CrossAccountId,535			/// New owner of item.536			T::CrossAccountId,537			/// Amount of token pieces transfered. Always 1 for NFT.538			u128,539		),540541		/// Amount pieces of token owned by `sender` was approved for `spender`.542		Approved(543			/// Id of collection to which item is belong.544			CollectionId,545			/// Id of an item.546			TokenId,547			/// Original owner of item.548			T::CrossAccountId,549			/// Id for which the approval was granted.550			T::CrossAccountId,551			/// Amount of token pieces transfered. Always 1 for NFT.552			u128,553		),554555		/// A `sender` approves operations on all owned tokens for `spender`.556		ApprovedForAll(557			/// Id of collection to which item is belong.558			CollectionId,559			/// Owner of a wallet.560			T::CrossAccountId,561			/// Id for which operator status was granted or rewoked.562			T::CrossAccountId,563			/// Is operator status granted or revoked?564			bool,565		),566567		/// The colletion property has been added or edited.568		CollectionPropertySet(569			/// Id of collection to which property has been set.570			CollectionId,571			/// The property that was set.572			PropertyKey,573		),574575		/// The property has been deleted.576		CollectionPropertyDeleted(577			/// Id of collection to which property has been deleted.578			CollectionId,579			/// The property that was deleted.580			PropertyKey,581		),582583		/// The token property has been added or edited.584		TokenPropertySet(585			/// Identifier of the collection whose token has the property set.586			CollectionId,587			/// The token for which the property was set.588			TokenId,589			/// The property that was set.590			PropertyKey,591		),592593		/// The token property has been deleted.594		TokenPropertyDeleted(595			/// Identifier of the collection whose token has the property deleted.596			CollectionId,597			/// The token for which the property was deleted.598			TokenId,599			/// The property that was deleted.600			PropertyKey,601		),602603		/// The token property permission of a collection has been set.604		PropertyPermissionSet(605			/// ID of collection to which property permission has been set.606			CollectionId,607			/// The property permission that was set.608			PropertyKey,609		),610611		/// Address was added to the allow list.612		AllowListAddressAdded(613			/// ID of the affected collection.614			CollectionId,615			/// Address of the added account.616			T::CrossAccountId,617		),618619		/// Address was removed from the allow list.620		AllowListAddressRemoved(621			/// ID of the affected collection.622			CollectionId,623			/// Address of the removed account.624			T::CrossAccountId,625		),626627		/// Collection admin was added.628		CollectionAdminAdded(629			/// ID of the affected collection.630			CollectionId,631			/// Admin address.632			T::CrossAccountId,633		),634635		/// Collection admin was removed.636		CollectionAdminRemoved(637			/// ID of the affected collection.638			CollectionId,639			/// Removed admin address.640			T::CrossAccountId,641		),642643		/// Collection limits were set.644		CollectionLimitSet(645			/// ID of the affected collection.646			CollectionId,647		),648649		/// Collection owned was changed.650		CollectionOwnerChanged(651			/// ID of the affected collection.652			CollectionId,653			/// New owner address.654			T::AccountId,655		),656657		/// Collection permissions were set.658		CollectionPermissionSet(659			/// ID of the affected collection.660			CollectionId,661		),662663		/// Collection sponsor was set.664		CollectionSponsorSet(665			/// ID of the affected collection.666			CollectionId,667			/// New sponsor address.668			T::AccountId,669		),670671		/// New sponsor was confirm.672		SponsorshipConfirmed(673			/// ID of the affected collection.674			CollectionId,675			/// New sponsor address.676			T::AccountId,677		),678679		/// Collection sponsor was removed.680		CollectionSponsorRemoved(681			/// ID of the affected collection.682			CollectionId,683		),684	}685686	#[pallet::error]687	pub enum Error<T> {688		/// This collection does not exist.689		CollectionNotFound,690		/// Sender parameter and item owner must be equal.691		MustBeTokenOwner,692		/// No permission to perform action693		NoPermission,694		/// Destroying only empty collections is allowed695		CantDestroyNotEmptyCollection,696		/// Collection is not in mint mode.697		PublicMintingNotAllowed,698		/// Address is not in allow list.699		AddressNotInAllowlist,700701		/// Collection name can not be longer than 63 char.702		CollectionNameLimitExceeded,703		/// Collection description can not be longer than 255 char.704		CollectionDescriptionLimitExceeded,705		/// Token prefix can not be longer than 15 char.706		CollectionTokenPrefixLimitExceeded,707		/// Total collections bound exceeded.708		TotalCollectionsLimitExceeded,709		/// Exceeded max admin count710		CollectionAdminCountExceeded,711		/// Collection limit bounds per collection exceeded712		CollectionLimitBoundsExceeded,713		/// Tried to enable permissions which are only permitted to be disabled714		OwnerPermissionsCantBeReverted,715		/// Collection settings not allowing items transferring716		TransferNotAllowed,717		/// Account token limit exceeded per collection718		AccountTokenLimitExceeded,719		/// Collection token limit exceeded720		CollectionTokenLimitExceeded,721		/// Metadata flag frozen722		MetadataFlagFrozen,723724		/// Item does not exist725		TokenNotFound,726		/// Item is balance not enough727		TokenValueTooLow,728		/// Requested value is more than the approved729		ApprovedValueTooLow,730		/// Tried to approve more than owned731		CantApproveMoreThanOwned,732		/// Only spending from eth mirror could be approved733		AddressIsNotEthMirror,734735		/// Can't transfer tokens to ethereum zero address736		AddressIsZero,737738		/// The operation is not supported739		UnsupportedOperation,740741		/// Insufficient funds to perform an action742		NotSufficientFounds,743744		/// User does not satisfy the nesting rule745		UserIsNotAllowedToNest,746		/// Only tokens from specific collections may nest tokens under this one747		SourceCollectionIsNotAllowedToNest,748749		/// Tried to store more data than allowed in collection field750		CollectionFieldSizeExceeded,751752		/// Tried to store more property data than allowed753		NoSpaceForProperty,754755		/// Tried to store more property keys than allowed756		PropertyLimitReached,757758		/// Property key is too long759		PropertyKeyIsTooLong,760761		/// Only ASCII letters, digits, and symbols `_`, `-`, and `.` are allowed762		InvalidCharacterInPropertyKey,763764		/// Empty property keys are forbidden765		EmptyPropertyKey,766767		/// Tried to access an external collection with an internal API768		CollectionIsExternal,769770		/// Tried to access an internal collection with an external API771		CollectionIsInternal,772773		/// This address is not set as sponsor, use setCollectionSponsor first.774		ConfirmSponsorshipFail,775776		/// The user is not an administrator.777		UserIsNotCollectionAdmin,778	}779780	/// Storage of the count of created collections. Essentially contains the last collection ID.781	#[pallet::storage]782	pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;783784	/// Storage of the count of deleted collections.785	#[pallet::storage]786	pub type DestroyedCollectionCount<T> =787		StorageValue<Value = CollectionId, QueryKind = ValueQuery>;788789	/// Storage of collection info.790	#[pallet::storage]791	pub type CollectionById<T> = StorageMap<792		Hasher = Blake2_128Concat,793		Key = CollectionId,794		Value = Collection<<T as frame_system::Config>::AccountId>,795		QueryKind = OptionQuery,796	>;797798	/// Storage of collection properties.799	#[pallet::storage]800	#[pallet::getter(fn collection_properties)]801	pub type CollectionProperties<T> = StorageMap<802		Hasher = Blake2_128Concat,803		Key = CollectionId,804		Value = CollectionPropertiesT,805		QueryKind = ValueQuery,806	>;807808	/// Storage of token property permissions of a collection.809	#[pallet::storage]810	#[pallet::getter(fn property_permissions)]811	pub type CollectionPropertyPermissions<T> = StorageMap<812		Hasher = Blake2_128Concat,813		Key = CollectionId,814		Value = PropertiesPermissionMap,815		QueryKind = ValueQuery,816	>;817818	/// Storage of the amount of collection admins.819	#[pallet::storage]820	pub type AdminAmount<T> = StorageMap<821		Hasher = Blake2_128Concat,822		Key = CollectionId,823		Value = u32,824		QueryKind = ValueQuery,825	>;826827	/// List of collection admins.828	#[pallet::storage]829	pub type IsAdmin<T: Config> = StorageNMap<830		Key = (831			Key<Blake2_128Concat, CollectionId>,832			Key<Blake2_128Concat, T::CrossAccountId>,833		),834		Value = bool,835		QueryKind = ValueQuery,836	>;837838	/// Allowlisted collection users.839	#[pallet::storage]840	pub type Allowlist<T: Config> = StorageNMap<841		Key = (842			Key<Blake2_128Concat, CollectionId>,843			Key<Blake2_128Concat, T::CrossAccountId>,844		),845		Value = bool,846		QueryKind = ValueQuery,847	>;848849	/// Not used by code, exists only to provide some types to metadata.850	#[pallet::storage]851	pub type DummyStorageValue<T: Config> = StorageValue<852		Value = (853			CollectionStats,854			CollectionId,855			TokenId,856			TokenChild,857			PhantomType<(858				TokenData<T::CrossAccountId>,859				RpcCollection<T::AccountId>,860				// PoV Estimate Info861				PovInfo,862			)>,863		),864		QueryKind = OptionQuery,865	>;866}867868/// Represents the change mode for the token property.869pub enum SetPropertyMode {870	/// The token already exists.871	ExistingToken,872873	/// New token.874	NewToken {875		/// The creator of the token is the recipient.876		mint_target_is_sender: bool,877	},878}879880/// Value representation with delayed initialization time.881pub struct LazyValue<T, F: FnOnce() -> T> {882	value: Option<T>,883	f: Option<F>,884}885886impl<T, F: FnOnce() -> T> LazyValue<T, F> {887	/// Create a new LazyValue.888	pub fn new(f: F) -> Self {889		Self {890			value: None,891			f: Some(f),892		}893	}894895	/// Get the value. If it call furst time the value will be initialized.896	pub fn value(&mut self) -> &T {897		if self.value.is_none() {898			self.value = Some(self.f.take().unwrap()())899		}900901		self.value.as_ref().unwrap()902	}903904	/// Is value initialized.905	pub fn has_value(&self) -> bool {906		self.value.is_some()907	}908}909910fn check_token_permissions<T, FCA, FTO, FTE>(911	collection_admin_permitted: bool,912	token_owner_permitted: bool,913	is_collection_admin: &mut LazyValue<bool, FCA>,914	is_token_owner: &mut LazyValue<Result<bool, DispatchError>, FTO>,915	is_token_exist: &mut LazyValue<bool, FTE>,916) -> DispatchResult917where918	T: Config,919	FCA: FnOnce() -> bool,920	FTO: FnOnce() -> Result<bool, DispatchError>,921	FTE: FnOnce() -> bool,922{923	if !(collection_admin_permitted && *is_collection_admin.value()924		|| token_owner_permitted && (*is_token_owner.value())?)925	{926		fail!(<Error<T>>::NoPermission);927	}928929	let token_certainly_exist = is_token_owner.has_value() && (*is_token_owner.value())?;930	if !token_certainly_exist && !is_token_exist.value() {931		fail!(<Error<T>>::TokenNotFound);932	}933	Ok(())934}935936impl<T: Config> Pallet<T> {937	/// Enshure that receiver address is correct.938	///939	/// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens.940	pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {941		ensure!(942			&T::CrossAccountId::from_eth(H160([0; 20])) != receiver,943			<Error<T>>::AddressIsZero944		);945		Ok(())946	}947948	/// Get a vector of collection admins.949	pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {950		<IsAdmin<T>>::iter_prefix((collection,))951			.map(|(a, _)| a)952			.collect()953	}954955	/// Get a vector of users allowed to mint tokens.956	pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {957		<Allowlist<T>>::iter_prefix((collection,))958			.map(|(a, _)| a)959			.collect()960	}961962	/// Is `user` allowed to mint token in `collection`.963	pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {964		<Allowlist<T>>::get((collection, user))965	}966967	/// Get statistics of collections.968	pub fn collection_stats() -> CollectionStats {969		let created = <CreatedCollectionCount<T>>::get();970		let destroyed = <DestroyedCollectionCount<T>>::get();971		CollectionStats {972			created: created.0,973			destroyed: destroyed.0,974			alive: created.0 - destroyed.0,975		}976	}977978	/// Get the effective limits for the collection.979	pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {980		let collection = <CollectionById<T>>::get(collection)?;981		let limits = collection.limits;982		let effective_limits = CollectionLimits {983			account_token_ownership_limit: Some(limits.account_token_ownership_limit()),984			sponsored_data_size: Some(limits.sponsored_data_size()),985			sponsored_data_rate_limit: Some(986				limits987					.sponsored_data_rate_limit988					.unwrap_or(SponsoringRateLimit::SponsoringDisabled),989			),990			token_limit: Some(limits.token_limit()),991			sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(992				match collection.mode {993					CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,994					CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,995					CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,996				},997			)),998			sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),999			owner_can_transfer: Some(limits.owner_can_transfer()),1000			owner_can_destroy: Some(limits.owner_can_destroy()),1001			transfers_enabled: Some(limits.transfers_enabled()),1002		};10031004		Some(effective_limits)1005	}10061007	/// Returns information about the `collection` adapted for rpc.1008	pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {1009		let Collection {1010			name,1011			description,1012			owner,1013			mode,1014			token_prefix,1015			sponsorship,1016			limits,1017			permissions,1018			flags,1019		} = <CollectionById<T>>::get(collection)?;10201021		let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)1022			.into_iter()1023			.map(|(key, permission)| PropertyKeyPermission { key, permission })1024			.collect();10251026		let properties = <CollectionProperties<T>>::get(collection)1027			.into_iter()1028			.map(|(key, value)| Property { key, value })1029			.collect();10301031		let permissions = CollectionPermissions {1032			access: Some(permissions.access()),1033			mint_mode: Some(permissions.mint_mode()),1034			nesting: Some(permissions.nesting().clone()),1035		};10361037		Some(RpcCollection {1038			name: name.into_inner(),1039			description: description.into_inner(),1040			owner,1041			mode,1042			token_prefix: token_prefix.into_inner(),1043			sponsorship,1044			limits,1045			permissions,1046			token_property_permissions,1047			properties,1048			read_only: flags.external,10491050			flags: RpcCollectionFlags {1051				foreign: flags.foreign,1052				erc721metadata: flags.erc721metadata,1053			},1054		})1055	}1056}10571058macro_rules! limit_default {1059	($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1060		$(1061			if let Some($new) = $new.$field {1062				let $old = $old.$field($($arg)?);1063				let _ = $new;1064				let _ = $old;1065				$check1066			} else {1067				$new.$field = $old.$field1068			}1069		)*1070	}};1071}1072macro_rules! limit_default_clone {1073	($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1074		$(1075			if let Some($new) = $new.$field.clone() {1076				let $old = $old.$field($($arg)?);1077				let _ = $new;1078				let _ = $old;1079				$check1080			} else {1081				$new.$field = $old.$field.clone()1082			}1083		)*1084	}};1085}10861087impl<T: Config> Pallet<T> {1088	/// Create new collection.1089	///1090	/// * `owner` - The owner of the collection.1091	/// * `data` - Description of the created collection.1092	/// * `flags` - Extra flags to store.1093	pub fn init_collection(1094		owner: T::CrossAccountId,1095		payer: T::CrossAccountId,1096		data: CreateCollectionData<T::CrossAccountId>,1097	) -> Result<CollectionId, DispatchError> {1098		ensure!(data.flags.is_allowed_for_user(), <Error<T>>::NoPermission);1099		Self::init_collection_internal(owner, payer, data)1100	}11011102	/// Initializes the collection with ForeignCollection flag. Returns [CollectionId] on success, [DispatchError] otherwise.1103	pub fn init_foreign_collection(1104		owner: T::CrossAccountId,1105		payer: T::CrossAccountId,1106		mut data: CreateCollectionData<T::CrossAccountId>,1107	) -> Result<CollectionId, DispatchError> {1108		data.flags.foreign = true;1109		let id = Self::init_collection_internal(owner, payer, data)?;1110		Ok(id)1111	}11121113	fn init_collection_internal(1114		owner: T::CrossAccountId,1115		payer: T::CrossAccountId,1116		data: CreateCollectionData<T::CrossAccountId>,1117	) -> Result<CollectionId, DispatchError> {1118		{1119			ensure!(1120				data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,1121				Error::<T>::CollectionTokenPrefixLimitExceeded1122			);1123		}11241125		let created_count = <CreatedCollectionCount<T>>::get()1126			.01127			.checked_add(1)1128			.ok_or(ArithmeticError::Overflow)?;1129		let destroyed_count = <DestroyedCollectionCount<T>>::get().0;1130		let id = CollectionId(created_count);11311132		// bound Total number of collections1133		ensure!(1134			created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,1135			<Error<T>>::TotalCollectionsLimitExceeded1136		);11371138		// =========11391140		let collection = Collection {1141			owner: owner.as_sub().clone(),1142			name: data.name,1143			mode: data.mode.clone(),1144			description: data.description,1145			token_prefix: data.token_prefix,1146			sponsorship: data1147				.pending_sponsor1148				.map(|sponsor| SponsorshipState::Unconfirmed(sponsor.as_sub().clone()))1149				.unwrap_or_default(),1150			limits: data1151				.limits1152				.map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))1153				.unwrap_or_else(|| Ok(CollectionLimits::default()))?,1154			permissions: data1155				.permissions1156				.map(|permissions| {1157					Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)1158				})1159				.unwrap_or_else(|| Ok(CollectionPermissions::default()))?,1160			flags: data.flags,1161		};11621163		let mut collection_properties = CollectionPropertiesT::new();1164		collection_properties1165			.try_set_from_iter(data.properties.into_iter())1166			.map_err(<Error<T>>::from)?;11671168		CollectionProperties::<T>::insert(id, collection_properties);11691170		let mut token_props_permissions = PropertiesPermissionMap::new();1171		token_props_permissions1172			.try_set_from_iter(data.token_property_permissions.into_iter())1173			.map_err(<Error<T>>::from)?;11741175		CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);11761177		let mut admin_amount = 0u32;1178		for admin in data.admin_list.iter() {1179			if !<IsAdmin<T>>::get((id, admin)) {1180				<IsAdmin<T>>::insert((id, admin), true);1181				admin_amount = admin_amount1182					.checked_add(1)1183					.ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1184			}1185		}1186		ensure!(1187			admin_amount <= Self::collection_admins_limit(),1188			<Error<T>>::CollectionAdminCountExceeded,1189		);1190		<AdminAmount<T>>::insert(id, admin_amount);11911192		// Take a (non-refundable) deposit of collection creation1193		{1194			let mut imbalance = <Debt<T::AccountId, <T as Config>::Currency>>::zero();1195			imbalance.subsume(<T as Config>::Currency::deposit(1196				&T::TreasuryAccountId::get(),1197				T::CollectionCreationPrice::get(),1198				Precision::Exact,1199			)?);1200			let credit =1201				<T as Config>::Currency::settle(payer.as_sub(), imbalance, Preservation::Preserve)1202					.map_err(|_| Error::<T>::NotSufficientFounds)?;12031204			debug_assert!(credit.peek().is_zero())1205		}12061207		<CreatedCollectionCount<T>>::put(created_count);1208		<Pallet<T>>::deposit_event(Event::CollectionCreated(1209			id,1210			data.mode.id(),1211			owner.as_sub().clone(),1212		));1213		<PalletEvm<T>>::deposit_log(1214			erc::CollectionHelpersEvents::CollectionCreated {1215				owner: *owner.as_eth(),1216				collection_id: eth::collection_id_to_address(id),1217			}1218			.to_log(T::ContractAddress::get()),1219		);1220		<CollectionById<T>>::insert(id, collection);1221		Ok(id)1222	}12231224	/// Destroy collection.1225	///1226	/// * `collection` - Collection handler.1227	/// * `sender` - The owner or administrator of the collection.1228	pub fn destroy_collection(1229		collection: CollectionHandle<T>,1230		sender: &T::CrossAccountId,1231	) -> DispatchResult {1232		ensure!(1233			collection.limits.owner_can_destroy(),1234			<Error<T>>::NoPermission,1235		);1236		collection.check_is_owner(sender)?;12371238		let destroyed_collections = <DestroyedCollectionCount<T>>::get()1239			.01240			.checked_add(1)1241			.ok_or(ArithmeticError::Overflow)?;12421243		// =========12441245		<DestroyedCollectionCount<T>>::put(destroyed_collections);1246		<CollectionById<T>>::remove(collection.id);1247		<AdminAmount<T>>::remove(collection.id);1248		let _ = <IsAdmin<T>>::clear_prefix((collection.id,), u32::MAX, None);1249		let _ = <Allowlist<T>>::clear_prefix((collection.id,), u32::MAX, None);1250		<CollectionProperties<T>>::remove(collection.id);12511252		<Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));12531254		<PalletEvm<T>>::deposit_log(1255			erc::CollectionHelpersEvents::CollectionDestroyed {1256				collection_id: eth::collection_id_to_address(collection.id),1257			}1258			.to_log(T::ContractAddress::get()),1259		);1260		Ok(())1261	}12621263	/// This function sets or removes a collection properties according to1264	/// `properties_updates` contents:1265	/// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`1266	/// * removes a property under the <key> if the value is `None` `(<key>, None)`.1267	///1268	/// This function fires an event for each property change.1269	/// In case of an error, all the changes (including the events) will be reverted1270	/// since the function is transactional.1271	#[transactional]1272	fn modify_collection_properties(1273		collection: &CollectionHandle<T>,1274		sender: &T::CrossAccountId,1275		properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,1276	) -> DispatchResult {1277		collection.check_is_owner_or_admin(sender)?;12781279		let mut stored_properties = <CollectionProperties<T>>::get(collection.id);12801281		for (key, value) in properties_updates {1282			match value {1283				Some(value) => {1284					stored_properties1285						.try_set(key.clone(), value)1286						.map_err(<Error<T>>::from)?;12871288					Self::deposit_event(Event::CollectionPropertySet(collection.id, key));1289					<PalletEvm<T>>::deposit_log(1290						erc::CollectionHelpersEvents::CollectionChanged {1291							collection_id: eth::collection_id_to_address(collection.id),1292						}1293						.to_log(T::ContractAddress::get()),1294					);1295				}1296				None => {1297					stored_properties.remove(&key).map_err(<Error<T>>::from)?;12981299					Self::deposit_event(Event::CollectionPropertyDeleted(collection.id, key));1300					<PalletEvm<T>>::deposit_log(1301						erc::CollectionHelpersEvents::CollectionChanged {1302							collection_id: eth::collection_id_to_address(collection.id),1303						}1304						.to_log(T::ContractAddress::get()),1305					);1306				}1307			}1308		}13091310		<CollectionProperties<T>>::set(collection.id, stored_properties);13111312		Ok(())1313	}13141315	/// A batch operation to add, edit or remove properties for a token.1316	/// It sets or removes a token's properties according to1317	/// `properties_updates` contents:1318	/// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`1319	/// * removes a property under the <key> if the value is `None` `(<key>, None)`.1320	///1321	/// All affected properties should have `mutable` permission1322	/// to be **deleted** or to be **set more than once**,1323	/// and the sender should have permission to edit those properties.1324	///1325	/// This function fires an event for each property change.1326	/// In case of an error, all the changes (including the events) will be reverted1327	/// since the function is transactional.1328	#[allow(clippy::too_many_arguments)]1329	pub fn modify_token_properties<FTO, FTE>(1330		collection: &CollectionHandle<T>,1331		sender: &T::CrossAccountId,1332		token_id: TokenId,1333		is_token_exist: &mut LazyValue<bool, FTE>,1334		properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,1335		mut stored_properties: TokenProperties,1336		is_token_owner: &mut LazyValue<Result<bool, DispatchError>, FTO>,1337		set_token_properties: impl FnOnce(TokenProperties),1338		log: evm_coder::ethereum::Log,1339	) -> DispatchResult1340	where1341		FTO: FnOnce() -> Result<bool, DispatchError>,1342		FTE: FnOnce() -> bool,1343	{1344		let mut is_collection_admin = LazyValue::new(|| collection.is_owner_or_admin(sender));1345		let permissions = Self::property_permissions(collection.id);13461347		let mut changed = false;1348		for (key, value) in properties_updates {1349			let permission = permissions1350				.get(&key)1351				.cloned()1352				.unwrap_or_else(PropertyPermission::none);13531354			let property_exists = stored_properties.get(&key).is_some();13551356			match permission {1357				PropertyPermission { mutable: false, .. } if property_exists => {1358					return Err(<Error<T>>::NoPermission.into());1359				}13601361				PropertyPermission {1362					collection_admin,1363					token_owner,1364					..1365				} => check_token_permissions::<T, _, FTO, FTE>(1366					collection_admin,1367					token_owner,1368					&mut is_collection_admin,1369					is_token_owner,1370					is_token_exist,1371				)?,1372			}13731374			match value {1375				Some(value) => {1376					stored_properties1377						.try_set(key.clone(), value)1378						.map_err(<Error<T>>::from)?;13791380					Self::deposit_event(Event::TokenPropertySet(collection.id, token_id, key));1381				}1382				None => {1383					stored_properties.remove(&key).map_err(<Error<T>>::from)?;13841385					Self::deposit_event(Event::TokenPropertyDeleted(collection.id, token_id, key));1386				}1387			}13881389			changed = true;1390		}13911392		if changed {1393			<PalletEvm<T>>::deposit_log(log);1394		}13951396		set_token_properties(stored_properties);13971398		Ok(())1399	}14001401	/// Sets or unsets the approval of a given operator.1402	///1403	/// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.1404	/// - `owner`: Token owner1405	/// - `operator`: Operator1406	/// - `approve`: Should operator status be granted or revoked?1407	pub fn set_allowance_for_all(1408		collection: &CollectionHandle<T>,1409		owner: &T::CrossAccountId,1410		operator: &T::CrossAccountId,1411		approve: bool,1412		set_allowance: impl FnOnce(),1413		log: evm_coder::ethereum::Log,1414	) -> DispatchResult {1415		if collection.permissions.access() == AccessMode::AllowList {1416			collection.check_allowlist(owner)?;1417			collection.check_allowlist(operator)?;1418		}14191420		Self::ensure_correct_receiver(operator)?;14211422		set_allowance();14231424		<PalletEvm<T>>::deposit_log(log);1425		Self::deposit_event(Event::ApprovedForAll(1426			collection.id,1427			owner.clone(),1428			operator.clone(),1429			approve,1430		));1431		Ok(())1432	}14331434	/// Set collection property.1435	///1436	/// * `collection` - Collection handler.1437	/// * `sender` - The owner or administrator of the collection.1438	/// * `property` - The property to set.1439	pub fn set_collection_property(1440		collection: &CollectionHandle<T>,1441		sender: &T::CrossAccountId,1442		property: Property,1443	) -> DispatchResult {1444		Self::set_collection_properties(collection, sender, [property].into_iter())1445	}14461447	/// Set a scoped collection property, where the scope is a special prefix1448	/// prohibiting a user access to change the property directly.1449	///1450	/// * `collection_id` - ID of the collection for which the property is being set.1451	/// * `scope` - Property scope.1452	/// * `property` - The property to set.1453	pub fn set_scoped_collection_property(1454		collection_id: CollectionId,1455		scope: PropertyScope,1456		property: Property,1457	) -> DispatchResult {1458		CollectionProperties::<T>::try_mutate(collection_id, |properties| {1459			properties.try_scoped_set(scope, property.key, property.value)1460		})1461		.map_err(<Error<T>>::from)?;14621463		Ok(())1464	}14651466	/// Set scoped collection properties, where the scope is a special prefix1467	/// prohibiting a user access to change the properties directly.1468	///1469	/// * `collection_id` - ID of the collection for which the properties is being set.1470	/// * `scope` - Property scope.1471	/// * `properties` - The properties to set.1472	pub fn set_scoped_collection_properties(1473		collection_id: CollectionId,1474		scope: PropertyScope,1475		properties: impl Iterator<Item = Property>,1476	) -> DispatchResult {1477		CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {1478			stored_properties.try_scoped_set_from_iter(scope, properties)1479		})1480		.map_err(<Error<T>>::from)?;14811482		Ok(())1483	}14841485	/// Set collection properties.1486	///1487	/// * `collection` - Collection handler.1488	/// * `sender` - The owner or administrator of the collection.1489	/// * `properties` - The properties to set.1490	pub fn set_collection_properties(1491		collection: &CollectionHandle<T>,1492		sender: &T::CrossAccountId,1493		properties: impl Iterator<Item = Property>,1494	) -> DispatchResult {1495		Self::modify_collection_properties(1496			collection,1497			sender,1498			properties.map(|property| (property.key, Some(property.value))),1499		)1500	}15011502	/// Delete collection property.1503	///1504	/// * `collection` - Collection handler.1505	/// * `sender` - The owner or administrator of the collection.1506	/// * `property` - The property to delete.1507	pub fn delete_collection_property(1508		collection: &CollectionHandle<T>,1509		sender: &T::CrossAccountId,1510		property_key: PropertyKey,1511	) -> DispatchResult {1512		Self::delete_collection_properties(collection, sender, [property_key].into_iter())1513	}15141515	/// Delete collection properties.1516	///1517	/// * `collection` - Collection handler.1518	/// * `sender` - The owner or administrator of the collection.1519	/// * `properties` - The properties to delete.1520	pub fn delete_collection_properties(1521		collection: &CollectionHandle<T>,1522		sender: &T::CrossAccountId,1523		property_keys: impl Iterator<Item = PropertyKey>,1524	) -> DispatchResult {1525		Self::modify_collection_properties(collection, sender, property_keys.map(|key| (key, None)))1526	}15271528	/// Set collection propetry permission without any checks.1529	///1530	/// Used for migrations.1531	///1532	/// * `collection` - Collection handler.1533	/// * `property_permissions` - Property permissions.1534	pub fn set_property_permission_unchecked(1535		collection: CollectionId,1536		property_permission: PropertyKeyPermission,1537	) -> DispatchResult {1538		<CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {1539			permissions.try_set(property_permission.key, property_permission.permission)1540		})1541		.map_err(<Error<T>>::from)?;1542		Ok(())1543	}15441545	/// Set collection property permission.1546	///1547	/// * `collection` - Collection handler.1548	/// * `sender` - The owner or administrator of the collection.1549	/// * `property_permission` - Property permission.1550	pub fn set_property_permission(1551		collection: &CollectionHandle<T>,1552		sender: &T::CrossAccountId,1553		property_permission: PropertyKeyPermission,1554	) -> DispatchResult {1555		Self::set_scoped_property_permission(1556			collection,1557			sender,1558			PropertyScope::None,1559			property_permission,1560		)1561	}15621563	/// Set collection property permission with scope.1564	///1565	/// * `collection` - Collection handler.1566	/// * `sender` - The owner or administrator of the collection.1567	/// * `scope` - Property scope.1568	/// * `property_permission` - Property permission.1569	pub fn set_scoped_property_permission(1570		collection: &CollectionHandle<T>,1571		sender: &T::CrossAccountId,1572		scope: PropertyScope,1573		property_permission: PropertyKeyPermission,1574	) -> DispatchResult {1575		collection.check_is_owner_or_admin(sender)?;15761577		let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);1578		let current_permission = all_permissions.get(&property_permission.key);1579		if matches![1580			current_permission,1581			Some(PropertyPermission { mutable: false, .. })1582		] {1583			return Err(<Error<T>>::NoPermission.into());1584		}15851586		CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {1587			let property_permission = property_permission.clone();1588			permissions.try_scoped_set(1589				scope,1590				property_permission.key,1591				property_permission.permission,1592			)1593		})1594		.map_err(<Error<T>>::from)?;15951596		Self::deposit_event(Event::PropertyPermissionSet(1597			collection.id,1598			property_permission.key,1599		));1600		<PalletEvm<T>>::deposit_log(1601			erc::CollectionHelpersEvents::CollectionChanged {1602				collection_id: eth::collection_id_to_address(collection.id),1603			}1604			.to_log(T::ContractAddress::get()),1605		);16061607		Ok(())1608	}16091610	/// Set token property permission.1611	///1612	/// * `collection` - Collection handler.1613	/// * `sender` - The owner or administrator of the collection.1614	/// * `property_permissions` - Property permissions.1615	#[transactional]1616	pub fn set_token_property_permissions(1617		collection: &CollectionHandle<T>,1618		sender: &T::CrossAccountId,1619		property_permissions: Vec<PropertyKeyPermission>,1620	) -> DispatchResult {1621		Self::set_scoped_token_property_permissions(1622			collection,1623			sender,1624			PropertyScope::None,1625			property_permissions,1626		)1627	}16281629	/// Set token property permission with scope.1630	///1631	/// * `collection` - Collection handler.1632	/// * `sender` - The owner or administrator of the collection.1633	/// * `scope` - Property scope.1634	/// * `property_permissions` - Property permissions.1635	#[transactional]1636	pub fn set_scoped_token_property_permissions(1637		collection: &CollectionHandle<T>,1638		sender: &T::CrossAccountId,1639		scope: PropertyScope,1640		property_permissions: Vec<PropertyKeyPermission>,1641	) -> DispatchResult {1642		for prop_pemission in property_permissions {1643			Self::set_scoped_property_permission(collection, sender, scope, prop_pemission)?;1644		}16451646		Ok(())1647	}16481649	/// Get collection property.1650	pub fn get_collection_property(1651		collection_id: CollectionId,1652		key: &PropertyKey,1653	) -> Option<PropertyValue> {1654		Self::collection_properties(collection_id).get(key).cloned()1655	}16561657	/// Convert byte vector to property key vector.1658	pub fn bytes_keys_to_property_keys(1659		keys: Vec<Vec<u8>>,1660	) -> Result<Vec<PropertyKey>, DispatchError> {1661		keys.into_iter()1662			.map(|key| -> Result<PropertyKey, DispatchError> {1663				key.try_into()1664					.map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())1665			})1666			.collect::<Result<Vec<PropertyKey>, DispatchError>>()1667	}16681669	/// Get properties according to given keys.1670	pub fn filter_collection_properties(1671		collection_id: CollectionId,1672		keys: Option<Vec<PropertyKey>>,1673	) -> Result<Vec<Property>, DispatchError> {1674		let properties = Self::collection_properties(collection_id);16751676		let properties = keys1677			.map(|keys| {1678				keys.into_iter()1679					.filter_map(|key| {1680						properties.get(&key).map(|value| Property {1681							key,1682							value: value.clone(),1683						})1684					})1685					.collect()1686			})1687			.unwrap_or_else(|| {1688				properties1689					.into_iter()1690					.map(|(key, value)| Property { key, value })1691					.collect()1692			});16931694		Ok(properties)1695	}16961697	/// Get property permissions according to given keys.1698	pub fn filter_property_permissions(1699		collection_id: CollectionId,1700		keys: Option<Vec<PropertyKey>>,1701	) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1702		let permissions = Self::property_permissions(collection_id);17031704		let key_permissions = keys1705			.map(|keys| {1706				keys.into_iter()1707					.filter_map(|key| {1708						permissions1709							.get(&key)1710							.map(|permission| PropertyKeyPermission {1711								key,1712								permission: permission.clone(),1713							})1714					})1715					.collect()1716			})1717			.unwrap_or_else(|| {1718				permissions1719					.into_iter()1720					.map(|(key, permission)| PropertyKeyPermission { key, permission })1721					.collect()1722			});17231724		Ok(key_permissions)1725	}17261727	/// Toggle `user` participation in the `collection`'s allow list.1728	/// #### Store read/writes1729	/// 1 writes1730	pub fn toggle_allowlist(1731		collection: &CollectionHandle<T>,1732		sender: &T::CrossAccountId,1733		user: &T::CrossAccountId,1734		allowed: bool,1735	) -> DispatchResult {1736		collection.check_is_owner_or_admin(sender)?;17371738		// =========17391740		if allowed {1741			<Allowlist<T>>::insert((collection.id, user), true);1742			Self::deposit_event(Event::<T>::AllowListAddressAdded(1743				collection.id,1744				user.clone(),1745			));1746		} else {1747			<Allowlist<T>>::remove((collection.id, user));1748			Self::deposit_event(Event::<T>::AllowListAddressRemoved(1749				collection.id,1750				user.clone(),1751			));1752		}17531754		<PalletEvm<T>>::deposit_log(1755			erc::CollectionHelpersEvents::CollectionChanged {1756				collection_id: eth::collection_id_to_address(collection.id),1757			}1758			.to_log(T::ContractAddress::get()),1759		);17601761		Ok(())1762	}17631764	/// Toggle `user` participation in the `collection`'s admin list.1765	/// #### Store read/writes1766	/// 2 reads, 2 writes1767	pub fn toggle_admin(1768		collection: &CollectionHandle<T>,1769		sender: &T::CrossAccountId,1770		user: &T::CrossAccountId,1771		admin: bool,1772	) -> DispatchResult {1773		collection.check_is_internal()?;1774		collection.check_is_owner(sender)?;17751776		let is_admin = <IsAdmin<T>>::get((collection.id, user));1777		if is_admin == admin {1778			if admin {1779				return Ok(());1780			} else {1781				return Err(Error::<T>::UserIsNotCollectionAdmin.into());1782			}1783		}1784		let amount = <AdminAmount<T>>::get(collection.id);17851786		// =========17871788		if admin {1789			let amount = amount1790				.checked_add(1)1791				.ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1792			ensure!(1793				amount <= Self::collection_admins_limit(),1794				<Error<T>>::CollectionAdminCountExceeded,1795			);17961797			<AdminAmount<T>>::insert(collection.id, amount);1798			<IsAdmin<T>>::insert((collection.id, user), true);17991800			Self::deposit_event(Event::<T>::CollectionAdminAdded(1801				collection.id,1802				user.clone(),1803			));1804		} else {1805			<AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1806			<IsAdmin<T>>::remove((collection.id, user));18071808			Self::deposit_event(Event::<T>::CollectionAdminRemoved(1809				collection.id,1810				user.clone(),1811			));1812		}18131814		<PalletEvm<T>>::deposit_log(1815			erc::CollectionHelpersEvents::CollectionChanged {1816				collection_id: eth::collection_id_to_address(collection.id),1817			}1818			.to_log(T::ContractAddress::get()),1819		);18201821		Ok(())1822	}18231824	/// Update collection limits.1825	pub fn update_limits(1826		user: &T::CrossAccountId,1827		collection: &mut CollectionHandle<T>,1828		new_limit: CollectionLimits,1829	) -> DispatchResult {1830		collection.check_is_internal()?;1831		collection.check_is_owner_or_admin(user)?;18321833		collection.limits =1834			Self::clamp_limits(collection.mode.clone(), &collection.limits, new_limit)?;18351836		Self::deposit_event(Event::<T>::CollectionLimitSet(collection.id));1837		<PalletEvm<T>>::deposit_log(1838			erc::CollectionHelpersEvents::CollectionChanged {1839				collection_id: eth::collection_id_to_address(collection.id),1840			}1841			.to_log(T::ContractAddress::get()),1842		);18431844		collection.save()1845	}18461847	/// Merge set fields from `new_limit` to `old_limit`.1848	fn clamp_limits(1849		mode: CollectionMode,1850		old_limit: &CollectionLimits,1851		mut new_limit: CollectionLimits,1852	) -> Result<CollectionLimits, DispatchError> {1853		let limits = old_limit;1854		limit_default!(old_limit, new_limit,1855			account_token_ownership_limit => ensure!(1856				new_limit <= MAX_TOKEN_OWNERSHIP,1857				<Error<T>>::CollectionLimitBoundsExceeded,1858			),1859			sponsored_data_size => ensure!(1860				new_limit <= CUSTOM_DATA_LIMIT,1861				<Error<T>>::CollectionLimitBoundsExceeded,1862			),18631864			sponsored_data_rate_limit => {},1865			token_limit => ensure!(1866				old_limit >= new_limit && new_limit > 0,1867				<Error<T>>::CollectionTokenLimitExceeded1868			),18691870			sponsor_transfer_timeout(match mode {1871				CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1872				CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1873				CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1874			}) => ensure!(1875				new_limit <= MAX_SPONSOR_TIMEOUT,1876				<Error<T>>::CollectionLimitBoundsExceeded,1877			),1878			sponsor_approve_timeout => {},1879			owner_can_transfer => ensure!(1880				!limits.owner_can_transfer_instaled() ||1881				old_limit || !new_limit,1882				<Error<T>>::OwnerPermissionsCantBeReverted,1883			),1884			owner_can_destroy => ensure!(1885				old_limit || !new_limit,1886				<Error<T>>::OwnerPermissionsCantBeReverted,1887			),1888			transfers_enabled => {},1889		);1890		Ok(new_limit)1891	}18921893	/// Update collection permissions.1894	pub fn update_permissions(1895		user: &T::CrossAccountId,1896		collection: &mut CollectionHandle<T>,1897		new_permission: CollectionPermissions,1898	) -> DispatchResult {1899		collection.check_is_internal()?;1900		collection.check_is_owner_or_admin(user)?;1901		collection.permissions = Self::clamp_permissions(1902			collection.mode.clone(),1903			&collection.permissions,1904			new_permission,1905		)?;19061907		Self::deposit_event(Event::<T>::CollectionPermissionSet(collection.id));1908		<PalletEvm<T>>::deposit_log(1909			erc::CollectionHelpersEvents::CollectionChanged {1910				collection_id: eth::collection_id_to_address(collection.id),1911			}1912			.to_log(T::ContractAddress::get()),1913		);19141915		collection.save()1916	}19171918	/// Merge set fields from `new_permission` to `old_permission`.1919	fn clamp_permissions(1920		_mode: CollectionMode,1921		old_permission: &CollectionPermissions,1922		mut new_permission: CollectionPermissions,1923	) -> Result<CollectionPermissions, DispatchError> {1924		limit_default_clone!(old_permission, new_permission,1925			access => {},1926			mint_mode => {},1927			nesting => { /* todo check for permissive, if only it gets out of benchmarks */ },1928		);1929		Ok(new_permission)1930	}19311932	/// Repair possibly broken properties of a collection.1933	pub fn repair_collection(collection_id: CollectionId) -> DispatchResult {1934		CollectionProperties::<T>::mutate(collection_id, |properties| {1935			properties.recompute_consumed_space();1936		});19371938		Ok(())1939	}1940}19411942/// Indicates unsupported methods by returning [Error::UnsupportedOperation].1943#[macro_export]1944macro_rules! unsupported {1945	($runtime:path) => {1946		Err($crate::Error::<$runtime>::UnsupportedOperation.into())1947	};1948}19491950/// Return weights for various worst-case operations.1951pub trait CommonWeightInfo<CrossAccountId> {1952	/// Weight of item creation.1953	fn create_item(data: &CreateItemData) -> Weight {1954		Self::create_multiple_items(from_ref(data))1955	}19561957	/// Weight of items creation.1958	fn create_multiple_items(amount: &[CreateItemData]) -> Weight;19591960	/// Weight of items creation.1961	fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;19621963	/// The weight of the burning item.1964	fn burn_item() -> Weight;19651966	/// Property setting weight.1967	///1968	/// * `amount`- The number of properties to set.1969	fn set_collection_properties(amount: u32) -> Weight;19701971	/// Collection property deletion weight.1972	///1973	/// * `amount`- The number of properties to set.1974	fn delete_collection_properties(amount: u32) -> Weight;19751976	/// Token property setting weight.1977	///1978	/// * `amount`- The number of properties to set.1979	fn set_token_properties(amount: u32) -> Weight;19801981	/// Token property deletion weight.1982	///1983	/// * `amount`- The number of properties to delete.1984	fn delete_token_properties(amount: u32) -> Weight;19851986	/// Token property permissions set weight.1987	///1988	/// * `amount`- The number of property permissions to set.1989	fn set_token_property_permissions(amount: u32) -> Weight;19901991	/// Transfer price of the token or its parts.1992	fn transfer() -> Weight;19931994	/// The price of setting the permission of the operation from another user.1995	fn approve() -> Weight;19961997	/// The price of setting the permission of the operation from another user for eth mirror.1998	fn approve_from() -> Weight;19992000	/// Transfer price from another user.2001	fn transfer_from() -> Weight;20022003	/// The price of burning a token from another user.2004	fn burn_from() -> Weight;20052006	/// Differs from burn_item in case of Fungible and Refungible, as it should burn2007	/// whole users's balance.2008	///2009	/// This method shouldn't be used directly, as it doesn't count breadth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead2010	fn burn_recursively_self_raw() -> Weight;20112012	/// Cost of iterating over `amount` children while burning, without counting child burning itself.2013	///2014	/// This method shouldn't be used directly, as it doesn't count depth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead2015	fn burn_recursively_breadth_raw(amount: u32) -> Weight;20162017	/// The price of recursive burning a token.2018	///2019	/// `max_selfs` - The maximum burning weight of the token itself.2020	/// `max_breadth` - The maximum number of nested tokens to burn.2021	fn burn_recursively(max_selfs: u32, max_breadth: u32) -> Weight {2022		Self::burn_recursively_self_raw()2023			.saturating_mul(max_selfs.max(1) as u64)2024			.saturating_add(Self::burn_recursively_breadth_raw(max_breadth))2025	}20262027	/// The price of retrieving token owner2028	fn token_owner() -> Weight;20292030	/// The price of setting approval for all2031	fn set_allowance_for_all() -> Weight;20322033	/// The price of repairing an item.2034	fn force_repair_item() -> Weight;2035}20362037/// Weight info extension trait for refungible pallet.2038pub trait RefungibleExtensionsWeightInfo {2039	/// Weight of token repartition.2040	fn repartition() -> Weight;2041}20422043/// Common collection operations.2044///2045/// It wraps methods in Fungible, Nonfungible and Refungible pallets2046/// and adds weight info.2047pub trait CommonCollectionOperations<T: Config> {2048	/// Create token.2049	///2050	/// * `sender` - The user who mint the token and pays for the transaction.2051	/// * `to` - The user who will own the token.2052	/// * `data` - Token data.2053	/// * `nesting_budget` - A budget that can be spent on nesting tokens.2054	fn create_item(2055		&self,2056		sender: T::CrossAccountId,2057		to: T::CrossAccountId,2058		data: CreateItemData,2059		nesting_budget: &dyn Budget,2060	) -> DispatchResultWithPostInfo;20612062	/// Create multiple tokens.2063	///2064	/// * `sender` - The user who mint the token and pays for the transaction.2065	/// * `to` - The user who will own the token.2066	/// * `data` - Token data.2067	/// * `nesting_budget` - A budget that can be spent on nesting tokens.2068	fn create_multiple_items(2069		&self,2070		sender: T::CrossAccountId,2071		to: T::CrossAccountId,2072		data: Vec<CreateItemData>,2073		nesting_budget: &dyn Budget,2074	) -> DispatchResultWithPostInfo;20752076	/// Create multiple tokens.2077	///2078	/// * `sender` - The user who mint the token and pays for the transaction.2079	/// * `to` - The user who will own the token.2080	/// * `data` - Token data.2081	/// * `nesting_budget` - A budget that can be spent on nesting tokens.2082	fn create_multiple_items_ex(2083		&self,2084		sender: T::CrossAccountId,2085		data: CreateItemExData<T::CrossAccountId>,2086		nesting_budget: &dyn Budget,2087	) -> DispatchResultWithPostInfo;20882089	/// Burn token.2090	///2091	/// * `sender` - The user who owns the token.2092	/// * `token` - Token id that will burned.2093	/// * `amount` - The number of parts of the token that will be burned.2094	fn burn_item(2095		&self,2096		sender: T::CrossAccountId,2097		token: TokenId,2098		amount: u128,2099	) -> DispatchResultWithPostInfo;21002101	/// Burn token and all nested tokens recursievly.2102	///2103	/// * `sender` - The user who owns the token.2104	/// * `token` - Token id that will burned.2105	/// * `self_budget` - The budget that can be spent on burning tokens.2106	/// * `breadth_budget` - The budget that can be spent on burning nested tokens.2107	fn burn_item_recursively(2108		&self,2109		sender: T::CrossAccountId,2110		token: TokenId,2111		self_budget: &dyn Budget,2112		breadth_budget: &dyn Budget,2113	) -> DispatchResultWithPostInfo;21142115	/// Set collection properties.2116	///2117	/// * `sender` - Must be either the owner of the collection or its admin.2118	/// * `properties` - Properties to be set.2119	fn set_collection_properties(2120		&self,2121		sender: T::CrossAccountId,2122		properties: Vec<Property>,2123	) -> DispatchResultWithPostInfo;21242125	/// Delete collection properties.2126	///2127	/// * `sender` - Must be either the owner of the collection or its admin.2128	/// * `properties` - The properties to be removed.2129	fn delete_collection_properties(2130		&self,2131		sender: &T::CrossAccountId,2132		property_keys: Vec<PropertyKey>,2133	) -> DispatchResultWithPostInfo;21342135	/// Set token properties.2136	///2137	/// The appropriate [`PropertyPermission`] for the token property2138	/// must be set with [`Self::set_token_property_permissions`].2139	///2140	/// * `sender` - Must be either the owner of the token or its admin.2141	/// * `token_id` - The token for which the properties are being set.2142	/// * `properties` - Properties to be set.2143	/// * `budget` - Budget for setting properties.2144	fn set_token_properties(2145		&self,2146		sender: T::CrossAccountId,2147		token_id: TokenId,2148		properties: Vec<Property>,2149		budget: &dyn Budget,2150	) -> DispatchResultWithPostInfo;21512152	/// Remove token properties.2153	///2154	/// The appropriate [`PropertyPermission`] for the token property2155	/// must be set with [`Self::set_token_property_permissions`].2156	///2157	/// * `sender` - Must be either the owner of the token or its admin.2158	/// * `token_id` - The token for which the properties are being remove.2159	/// * `property_keys` - Keys to remove corresponding properties.2160	/// * `budget` - Budget for removing properties.2161	fn delete_token_properties(2162		&self,2163		sender: T::CrossAccountId,2164		token_id: TokenId,2165		property_keys: Vec<PropertyKey>,2166		budget: &dyn Budget,2167	) -> DispatchResultWithPostInfo;21682169	/// Set token property permissions.2170	///2171	/// * `sender` - Must be either the owner of the token or its admin.2172	/// * `token_id` - The token for which the properties are being set.2173	/// * `property_permissions` - Property permissions to be set.2174	/// * `budget` - Budget for setting properties.2175	fn set_token_property_permissions(2176		&self,2177		sender: &T::CrossAccountId,2178		property_permissions: Vec<PropertyKeyPermission>,2179	) -> DispatchResultWithPostInfo;21802181	/// Transfer amount of token pieces.2182	///2183	/// * `sender` - Donor user.2184	/// * `to` - Recepient user.2185	/// * `token` - The token of which parts are being sent.2186	/// * `amount` - The number of parts of the token that will be transferred.2187	/// * `budget` - The maximum budget that can be spent on the transfer.2188	fn transfer(2189		&self,2190		sender: T::CrossAccountId,2191		to: T::CrossAccountId,2192		token: TokenId,2193		amount: u128,2194		budget: &dyn Budget,2195	) -> DispatchResultWithPostInfo;21962197	/// Grant access to another account to transfer parts of the token owned by the calling user via [Self::transfer_from].2198	///2199	/// * `sender` - The user who grants access to the token.2200	/// * `spender` - The user to whom the rights are granted.2201	/// * `token` - The token to which access is granted.2202	/// * `amount` - The amount of pieces that another user can dispose of.2203	fn approve(2204		&self,2205		sender: T::CrossAccountId,2206		spender: T::CrossAccountId,2207		token: TokenId,2208		amount: u128,2209	) -> DispatchResultWithPostInfo;22102211	/// Grant access to another account to transfer parts of the token owned by the calling user's eth mirror via [Self::transfer_from].2212	///2213	/// * `sender` - The user who grants access to the token.2214	/// * `from` - Spender's eth mirror.2215	/// * `to` - The user to whom the rights are granted.2216	/// * `token` - The token to which access is granted.2217	/// * `amount` - The amount of pieces that another user can dispose of.2218	fn approve_from(2219		&self,2220		sender: T::CrossAccountId,2221		from: T::CrossAccountId,2222		to: T::CrossAccountId,2223		token: TokenId,2224		amount: u128,2225	) -> DispatchResultWithPostInfo;22262227	/// Send parts of a token owned by another user.2228	///2229	/// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2230	///2231	/// * `sender` - The user who must have access to the token (see [`Self::approve`]).2232	/// * `from` - The user who owns the token.2233	/// * `to` - Recepient user.2234	/// * `token` - The token of which parts are being sent.2235	/// * `amount` - The number of parts of the token that will be transferred.2236	/// * `budget` - The maximum budget that can be spent on the transfer.2237	fn transfer_from(2238		&self,2239		sender: T::CrossAccountId,2240		from: T::CrossAccountId,2241		to: T::CrossAccountId,2242		token: TokenId,2243		amount: u128,2244		budget: &dyn Budget,2245	) -> DispatchResultWithPostInfo;22462247	/// Burn parts of a token owned by another user.2248	///2249	/// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2250	///2251	/// * `sender` - The user who must have access to the token (see [`Self::approve`]).2252	/// * `from` - The user who owns the token.2253	/// * `token` - The token of which parts are being sent.2254	/// * `amount` - The number of parts of the token that will be transferred.2255	/// * `budget` - The maximum budget that can be spent on the burn.2256	fn burn_from(2257		&self,2258		sender: T::CrossAccountId,2259		from: T::CrossAccountId,2260		token: TokenId,2261		amount: u128,2262		budget: &dyn Budget,2263	) -> DispatchResultWithPostInfo;22642265	/// Check permission to nest token.2266	///2267	/// * `sender` - The user who initiated the check.2268	/// * `from` - The token that is checked for embedding.2269	/// * `under` - Token under which to check.2270	/// * `budget` - The maximum budget that can be spent on the check.2271	fn check_nesting(2272		&self,2273		sender: T::CrossAccountId,2274		from: (CollectionId, TokenId),2275		under: TokenId,2276		budget: &dyn Budget,2277	) -> DispatchResult;22782279	/// Nest one token into another.2280	///2281	/// * `under` - Token holder.2282	/// * `to_nest` - Nested token.2283	fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));22842285	/// Unnest token.2286	///2287	/// * `under` - Token holder.2288	/// * `to_nest` - Token to unnest.2289	fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));22902291	/// Get all user tokens.2292	///2293	/// * `account` - Account for which you need to get tokens.2294	fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;22952296	/// Get all the tokens in the collection.2297	fn collection_tokens(&self) -> Vec<TokenId>;22982299	/// Check if the token exists.2300	///2301	/// * `token` - Id token to check.2302	fn token_exists(&self, token: TokenId) -> bool;23032304	/// Get the id of the last minted token.2305	fn last_token_id(&self) -> TokenId;23062307	/// Get the owner of the token.2308	///2309	/// * `token` - The token for which you need to find out the owner.2310	fn token_owner(&self, token: TokenId) -> Result<T::CrossAccountId, TokenOwnerError>;23112312	/// Returns 10 tokens owners in no particular order.2313	///2314	/// * `token` - The token for which you need to find out the owners.2315	fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId>;23162317	/// Get the value of the token property by key.2318	///2319	/// * `token` - Token with the property to get.2320	/// * `key` - Property name.2321	fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;23222323	/// Get a set of token properties by key vector.2324	///2325	/// * `token` - Token with the property to get.2326	/// * `keys` - Vector of property keys. If this parameter is [None](sp_std::result::Result),2327	/// then all properties are returned.2328	fn token_properties(&self, token: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;23292330	/// Amount of unique collection tokens2331	fn total_supply(&self) -> u32;23322333	/// Amount of different tokens account has.2334	///2335	/// * `account` - The account for which need to get the balance.2336	fn account_balance(&self, account: T::CrossAccountId) -> u32;23372338	/// Amount of specific token account have.2339	fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;23402341	/// Amount of token pieces2342	fn total_pieces(&self, token: TokenId) -> Option<u128>;23432344	/// Get the number of parts of the token that a trusted user can manage.2345	///2346	/// * `sender` - Trusted user.2347	/// * `spender` - Owner of the token.2348	/// * `token` - The token for which to get the value.2349	fn allowance(2350		&self,2351		sender: T::CrossAccountId,2352		spender: T::CrossAccountId,2353		token: TokenId,2354	) -> u128;23552356	/// Get extension for RFT collection.2357	fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>>;23582359	/// The `operator` is allowed to transfer all tokens of the `owner` on their behalf.2360	/// * `owner` - Token owner2361	/// * `operator` - Operator2362	/// * `approve` - Should operator status be granted or revoked?2363	fn set_allowance_for_all(2364		&self,2365		owner: T::CrossAccountId,2366		operator: T::CrossAccountId,2367		approve: bool,2368	) -> DispatchResultWithPostInfo;23692370	/// Tells whether the given `owner` approves the `operator`.2371	fn allowance_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool;23722373	/// Repairs a possibly broken item.2374	fn repair_item(&self, token: TokenId) -> DispatchResultWithPostInfo;2375}23762377/// Extension for RFT collection.2378pub trait RefungibleExtensions<T>2379where2380	T: Config,2381{2382	/// Change the number of parts of the token.2383	///2384	/// When the value changes down, this function is equivalent to burning parts of the token.2385	///2386	/// * `sender` - The user calling the repartition operation. Must be the owner of the token.2387	/// * `token` - The token for which you want to change the number of parts.2388	/// * `amount` - The new value of the parts of the token.2389	fn repartition(2390		&self,2391		sender: &T::CrossAccountId,2392		token: TokenId,2393		amount: u128,2394	) -> DispatchResultWithPostInfo;2395}23962397/// Merge [`DispatchResult`] with [`Weight`] into [`DispatchResultWithPostInfo`].2398///2399/// Used for [`CommonCollectionOperations`] implementations and flexible enough to do so.2400pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {2401	let post_info = PostDispatchInfo {2402		actual_weight: Some(weight),2403		pays_fee: Pays::Yes,2404	};2405	match res {2406		Ok(()) => Ok(post_info),2407		Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),2408	}2409}24102411impl<T: Config> From<PropertiesError> for Error<T> {2412	fn from(error: PropertiesError) -> Self {2413		match error {2414			PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,2415			PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,2416			PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,2417			PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,2418			PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,2419		}2420	}2421}24222423#[cfg(feature = "tests")]2424pub mod tests {2425	use crate::{DispatchResult, DispatchError, LazyValue, Config};24262427	const fn to_bool(u: u8) -> bool {2428		u != 02429	}24302431	#[derive(Debug)]2432	pub struct TestCase {2433		pub collection_admin: bool,2434		pub is_collection_admin: bool,2435		pub token_owner: bool,2436		pub is_token_owner: bool,2437		pub no_permission: bool,2438	}24392440	impl TestCase {2441		const fn new(2442			collection_admin: u8,2443			is_collection_admin: u8,2444			token_owner: u8,2445			is_token_owner: u8,2446			no_permission: u8,2447		) -> Self {2448			Self {2449				collection_admin: to_bool(collection_admin),2450				is_collection_admin: to_bool(is_collection_admin),2451				token_owner: to_bool(token_owner),2452				is_token_owner: to_bool(is_token_owner),2453				no_permission: to_bool(no_permission),2454			}2455		}2456	}24572458	#[rustfmt::skip]2459	pub const table: [TestCase; 16] = [2460		//                    ┌╴collection_admin2461		//                    │  ┌╴is_collection_admin2462		//                    │  │   ┌╴token_owner2463		//                    │  │   │  ┌╴is_token_ownership2464		//                    │  │   │  │   ┌╴no_permission2465		/*  0*/ TestCase::new(0, 0,  0, 0,  1),2466		/*  1*/ TestCase::new(0, 0,  0, 1,  1),2467		/*  2*/ TestCase::new(0, 0,  1, 0,  1),2468		/*  3*/ TestCase::new(0, 0,  1, 1,  0),2469		/*  4*/ TestCase::new(0, 1,  0, 0,  1),2470		/*  5*/ TestCase::new(0, 1,  0, 1,  1),2471		/*  6*/ TestCase::new(0, 1,  1, 0,  1),2472		/*  7*/ TestCase::new(0, 1,  1, 1,  0),2473		/*  8*/ TestCase::new(1, 0,  0, 0,  1),2474		/*  9*/ TestCase::new(1, 0,  0, 1,  1),2475		/* 10*/ TestCase::new(1, 0,  1, 0,  1),2476		/* 11*/ TestCase::new(1, 0,  1, 1,  0),2477		/* 12*/ TestCase::new(1, 1,  0, 0,  0),2478		/* 13*/ TestCase::new(1, 1,  0, 1,  0),2479		/* 14*/ TestCase::new(1, 1,  1, 0,  0),2480		/* 15*/ TestCase::new(1, 1,  1, 1,  0),2481	];24822483	pub fn check_token_permissions<T, FCA, FTO, FTE>(2484		collection_admin_permitted: bool,2485		token_owner_permitted: bool,2486		is_collection_admin: &mut LazyValue<bool, FCA>,2487		check_token_ownership: &mut LazyValue<Result<bool, DispatchError>, FTO>,2488		check_token_existence: &mut LazyValue<bool, FTE>,2489	) -> DispatchResult2490	where2491		T: Config,2492		FCA: FnOnce() -> bool,2493		FTO: FnOnce() -> Result<bool, DispatchError>,2494		FTE: FnOnce() -> bool,2495	{2496		crate::check_token_permissions::<T, FCA, FTO, FTE>(2497			collection_admin_permitted,2498			token_owner_permitted,2499			is_collection_admin,2500			check_token_ownership,2501			check_token_existence,2502		)2503	}2504}
modifiedpallets/foreign-assets/src/lib.rsdiffbeforeafterboth
--- a/pallets/foreign-assets/src/lib.rs
+++ b/pallets/foreign-assets/src/lib.rs
@@ -42,9 +42,9 @@
 	RuntimeDebug,
 };
 use frame_system::pallet_prelude::*;
-use up_data_structs::{CollectionMode};
-use pallet_fungible::{Pallet as PalletFungible};
-use scale_info::{TypeInfo};
+use up_data_structs::CollectionMode;
+use pallet_fungible::Pallet as PalletFungible;
+use scale_info::TypeInfo;
 use sp_runtime::{
 	traits::{One, Zero},
 	ArithmeticError,
@@ -304,7 +304,7 @@
 				.collect::<Vec<u16>>();
 			description.append(&mut name.clone());
 
-			let data: CreateCollectionData<T::AccountId> = CreateCollectionData {
+			let data: CreateCollectionData<T::CrossAccountId> = CreateCollectionData {
 				name: name.try_into().unwrap(),
 				description: description.try_into().unwrap(),
 				mode: CollectionMode::Fungible(md.decimals),
modifiedpallets/fungible/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/fungible/src/benchmarking.rs
+++ b/pallets/fungible/src/benchmarking.rs
@@ -31,9 +31,7 @@
 	create_collection_raw(
 		owner,
 		CollectionMode::Fungible(0),
-		|owner: T::CrossAccountId, data| {
-			<Pallet<T>>::init_collection(owner.clone(), owner, data, Default::default())
-		},
+		|owner: T::CrossAccountId, data| <Pallet<T>>::init_collection(owner.clone(), owner, data),
 		FungibleHandle::cast,
 	)
 }
modifiedpallets/fungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -87,8 +87,8 @@
 };
 use pallet_evm::account::CrossAccountId;
 use up_data_structs::{
-	AccessMode, CollectionId, CollectionFlags, TokenId, CreateCollectionData,
-	mapping::TokenAddressMapping, budget::Budget, PropertyKey, Property,
+	AccessMode, CollectionId, TokenId, CreateCollectionData, mapping::TokenAddressMapping,
+	budget::Budget, PropertyKey, Property,
 };
 use pallet_common::{
 	Error as CommonError, Event as CommonEvent, Pallet as PalletCommon,
@@ -219,28 +219,18 @@
 	pub fn init_collection(
 		owner: T::CrossAccountId,
 		payer: T::CrossAccountId,
-		data: CreateCollectionData<T::AccountId>,
-		flags: CollectionFlags,
+		data: CreateCollectionData<T::CrossAccountId>,
 	) -> Result<CollectionId, DispatchError> {
-		<PalletCommon<T>>::init_collection(owner, payer, data, flags)
+		<PalletCommon<T>>::init_collection(owner, payer, data)
 	}
 
 	/// Initializes the collection with ForeignCollection flag. Returns [CollectionId] on success, [DispatchError] otherwise.
 	pub fn init_foreign_collection(
 		owner: T::CrossAccountId,
 		payer: T::CrossAccountId,
-		data: CreateCollectionData<T::AccountId>,
+		data: CreateCollectionData<T::CrossAccountId>,
 	) -> Result<CollectionId, DispatchError> {
-		let id = <PalletCommon<T>>::init_collection(
-			owner,
-			payer,
-			data,
-			CollectionFlags {
-				foreign: true,
-				..Default::default()
-			},
-		)?;
-		Ok(id)
+		<PalletCommon<T>>::init_foreign_collection(owner, payer, data)
 	}
 
 	/// Destroys a collection.
modifiedpallets/fungible/src/stubs/UniqueFungible.rawdiffbeforeafterboth

binary blob — no preview

modifiedpallets/fungible/src/stubs/UniqueFungible.soldiffbeforeafterboth
--- a/pallets/fungible/src/stubs/UniqueFungible.sol
+++ b/pallets/fungible/src/stubs/UniqueFungible.sol
@@ -18,7 +18,7 @@
 }
 
 /// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0x2a14cfd1
+/// @dev the ERC-165 identifier for this interface is 0xb34d97e9
 contract Collection is Dummy, ERC165 {
 	// /// Set collection property.
 	// ///
@@ -230,47 +230,63 @@
 	// 	dummy = 0;
 	// }
 
-	/// Toggle accessibility of collection nesting.
-	///
-	/// @param enable If "true" degenerates to nesting: 'Owner' else to nesting: 'Disabled'
-	/// @dev EVM selector for this function is: 0x112d4586,
-	///  or in textual repr: setCollectionNesting(bool)
-	function setCollectionNesting(bool enable) public {
+	/// @dev EVM selector for this function is: 0x0b9f3890,
+	///  or in textual repr: setCollectionNesting((bool,bool,address[]))
+	function setCollectionNesting(CollectionNestingAndPermission memory collectionNestingAndPermissions) public {
 		require(false, stub_error);
-		enable;
+		collectionNestingAndPermissions;
 		dummy = 0;
 	}
 
-	/// Toggle accessibility of collection nesting.
-	///
-	/// @param enable If "true" degenerates to nesting: {OwnerRestricted: [1, 2, 3]} else to nesting: 'Disabled'
-	/// @param collections Addresses of collections that will be available for nesting.
-	/// @dev EVM selector for this function is: 0x64872396,
-	///  or in textual repr: setCollectionNesting(bool,address[])
-	function setCollectionNesting(bool enable, address[] memory collections) public {
-		require(false, stub_error);
-		enable;
-		collections;
-		dummy = 0;
-	}
+	// /// Toggle accessibility of collection nesting.
+	// ///
+	// /// @param enable If "true" degenerates to nesting: 'Owner' else to nesting: 'Disabled'
+	// /// @dev EVM selector for this function is: 0x112d4586,
+	// ///  or in textual repr: setCollectionNesting(bool)
+	// function setCollectionNesting(bool enable) public {
+	// 	require(false, stub_error);
+	// 	enable;
+	// 	dummy = 0;
+	// }
+
+	// /// Toggle accessibility of collection nesting.
+	// ///
+	// /// @param enable If "true" degenerates to nesting: {OwnerRestricted: [1, 2, 3]} else to nesting: 'Disabled'
+	// /// @param collections Addresses of collections that will be available for nesting.
+	// /// @dev EVM selector for this function is: 0x64872396,
+	// ///  or in textual repr: setCollectionNesting(bool,address[])
+	// function setCollectionNesting(bool enable, address[] memory collections) public {
+	// 	require(false, stub_error);
+	// 	enable;
+	// 	collections;
+	// 	dummy = 0;
+	// }
 
-	/// Returns nesting for a collection
-	/// @dev EVM selector for this function is: 0x22d25bfe,
-	///  or in textual repr: collectionNestingRestrictedCollectionIds()
-	function collectionNestingRestrictedCollectionIds() public view returns (CollectionNesting memory) {
+	/// @dev EVM selector for this function is: 0x92c660a8,
+	///  or in textual repr: collectionNesting()
+	function collectionNesting() public view returns (CollectionNestingAndPermission memory) {
 		require(false, stub_error);
 		dummy;
-		return CollectionNesting(false, new uint256[](0));
+		return CollectionNestingAndPermission(false, false, new address[](0));
 	}
 
-	/// Returns permissions for a collection
-	/// @dev EVM selector for this function is: 0x5b2eaf4b,
-	///  or in textual repr: collectionNestingPermissions()
-	function collectionNestingPermissions() public view returns (CollectionNestingPermission[] memory) {
-		require(false, stub_error);
-		dummy;
-		return new CollectionNestingPermission[](0);
-	}
+	// /// Returns nesting for a collection
+	// /// @dev EVM selector for this function is: 0x22d25bfe,
+	// ///  or in textual repr: collectionNestingRestrictedCollectionIds()
+	// function collectionNestingRestrictedCollectionIds() public view returns (CollectionNesting memory) {
+	// 	require(false, stub_error);
+	// 	dummy;
+	// 	return CollectionNesting(false,new uint256[](0));
+	// }
+
+	// /// Returns permissions for a collection
+	// /// @dev EVM selector for this function is: 0x5b2eaf4b,
+	// ///  or in textual repr: collectionNestingPermissions()
+	// function collectionNestingPermissions() public view returns (CollectionNestingPermission[] memory) {
+	// 	require(false, stub_error);
+	// 	dummy;
+	// 	return new CollectionNestingPermission[](0);
+	// }
 
 	/// Set the collection access method.
 	/// @param mode Access mode
@@ -469,6 +485,16 @@
 	uint256[] ids;
 }
 
+/// Nested collections and permissions
+struct CollectionNestingAndPermission {
+	/// Owner of token can nest tokens under it.
+	bool token_owner;
+	/// Admin of token collection can nest tokens under token.
+	bool collection_admin;
+	/// If set - only tokens from specified collections can be nested.
+	address[] restricted;
+}
+
 /// [`CollectionLimits`](up_data_structs::CollectionLimits) field representation for EVM.
 struct CollectionLimit {
 	CollectionLimitField field;
modifiedpallets/nonfungible/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/benchmarking.rs
+++ b/pallets/nonfungible/src/benchmarking.rs
@@ -57,9 +57,7 @@
 	create_collection_raw(
 		owner,
 		CollectionMode::NFT,
-		|owner: T::CrossAccountId, data| {
-			<Pallet<T>>::init_collection(owner.clone(), owner, data, Default::default())
-		},
+		|owner: T::CrossAccountId, data| <Pallet<T>>::init_collection(owner.clone(), owner, data),
 		NonfungibleHandle::cast,
 	)
 }
modifiedpallets/nonfungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -100,10 +100,10 @@
 	dispatch::{PostDispatchInfo, Pays},
 };
 use up_data_structs::{
-	AccessMode, CollectionId, CollectionFlags, CustomDataLimit, TokenId, CreateCollectionData,
-	CreateNftExData, mapping::TokenAddressMapping, budget::Budget, Property, PropertyKey,
-	PropertyValue, PropertyKeyPermission, PropertyScope, TrySetProperty, TokenChild,
-	AuxPropertyValue, PropertiesPermissionMap, TokenProperties as TokenPropertiesT,
+	AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,
+	mapping::TokenAddressMapping, budget::Budget, Property, PropertyKey, PropertyValue,
+	PropertyKeyPermission, PropertyScope, TrySetProperty, TokenChild, AuxPropertyValue,
+	PropertiesPermissionMap, TokenProperties as TokenPropertiesT,
 };
 use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};
 use pallet_common::{
@@ -424,10 +424,9 @@
 	pub fn init_collection(
 		owner: T::CrossAccountId,
 		payer: T::CrossAccountId,
-		data: CreateCollectionData<T::AccountId>,
-		flags: CollectionFlags,
+		data: CreateCollectionData<T::CrossAccountId>,
 	) -> Result<CollectionId, DispatchError> {
-		<PalletCommon<T>>::init_collection(owner, payer, data, flags)
+		<PalletCommon<T>>::init_collection(owner, payer, data)
 	}
 
 	/// Destroy NFT collection
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
@@ -165,7 +165,7 @@
 }
 
 /// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0x2a14cfd1
+/// @dev the ERC-165 identifier for this interface is 0xb34d97e9
 contract Collection is Dummy, ERC165 {
 	// /// Set collection property.
 	// ///
@@ -377,47 +377,63 @@
 	// 	dummy = 0;
 	// }
 
-	/// Toggle accessibility of collection nesting.
-	///
-	/// @param enable If "true" degenerates to nesting: 'Owner' else to nesting: 'Disabled'
-	/// @dev EVM selector for this function is: 0x112d4586,
-	///  or in textual repr: setCollectionNesting(bool)
-	function setCollectionNesting(bool enable) public {
+	/// @dev EVM selector for this function is: 0x0b9f3890,
+	///  or in textual repr: setCollectionNesting((bool,bool,address[]))
+	function setCollectionNesting(CollectionNestingAndPermission memory collectionNestingAndPermissions) public {
 		require(false, stub_error);
-		enable;
+		collectionNestingAndPermissions;
 		dummy = 0;
 	}
 
-	/// Toggle accessibility of collection nesting.
-	///
-	/// @param enable If "true" degenerates to nesting: {OwnerRestricted: [1, 2, 3]} else to nesting: 'Disabled'
-	/// @param collections Addresses of collections that will be available for nesting.
-	/// @dev EVM selector for this function is: 0x64872396,
-	///  or in textual repr: setCollectionNesting(bool,address[])
-	function setCollectionNesting(bool enable, address[] memory collections) public {
-		require(false, stub_error);
-		enable;
-		collections;
-		dummy = 0;
-	}
+	// /// Toggle accessibility of collection nesting.
+	// ///
+	// /// @param enable If "true" degenerates to nesting: 'Owner' else to nesting: 'Disabled'
+	// /// @dev EVM selector for this function is: 0x112d4586,
+	// ///  or in textual repr: setCollectionNesting(bool)
+	// function setCollectionNesting(bool enable) public {
+	// 	require(false, stub_error);
+	// 	enable;
+	// 	dummy = 0;
+	// }
+
+	// /// Toggle accessibility of collection nesting.
+	// ///
+	// /// @param enable If "true" degenerates to nesting: {OwnerRestricted: [1, 2, 3]} else to nesting: 'Disabled'
+	// /// @param collections Addresses of collections that will be available for nesting.
+	// /// @dev EVM selector for this function is: 0x64872396,
+	// ///  or in textual repr: setCollectionNesting(bool,address[])
+	// function setCollectionNesting(bool enable, address[] memory collections) public {
+	// 	require(false, stub_error);
+	// 	enable;
+	// 	collections;
+	// 	dummy = 0;
+	// }
 
-	/// Returns nesting for a collection
-	/// @dev EVM selector for this function is: 0x22d25bfe,
-	///  or in textual repr: collectionNestingRestrictedCollectionIds()
-	function collectionNestingRestrictedCollectionIds() public view returns (CollectionNesting memory) {
+	/// @dev EVM selector for this function is: 0x92c660a8,
+	///  or in textual repr: collectionNesting()
+	function collectionNesting() public view returns (CollectionNestingAndPermission memory) {
 		require(false, stub_error);
 		dummy;
-		return CollectionNesting(false, new uint256[](0));
+		return CollectionNestingAndPermission(false, false, new address[](0));
 	}
 
-	/// Returns permissions for a collection
-	/// @dev EVM selector for this function is: 0x5b2eaf4b,
-	///  or in textual repr: collectionNestingPermissions()
-	function collectionNestingPermissions() public view returns (CollectionNestingPermission[] memory) {
-		require(false, stub_error);
-		dummy;
-		return new CollectionNestingPermission[](0);
-	}
+	// /// Returns nesting for a collection
+	// /// @dev EVM selector for this function is: 0x22d25bfe,
+	// ///  or in textual repr: collectionNestingRestrictedCollectionIds()
+	// function collectionNestingRestrictedCollectionIds() public view returns (CollectionNesting memory) {
+	// 	require(false, stub_error);
+	// 	dummy;
+	// 	return CollectionNesting(false,new uint256[](0));
+	// }
+
+	// /// Returns permissions for a collection
+	// /// @dev EVM selector for this function is: 0x5b2eaf4b,
+	// ///  or in textual repr: collectionNestingPermissions()
+	// function collectionNestingPermissions() public view returns (CollectionNestingPermission[] memory) {
+	// 	require(false, stub_error);
+	// 	dummy;
+	// 	return new CollectionNestingPermission[](0);
+	// }
 
 	/// Set the collection access method.
 	/// @param mode Access mode
@@ -616,6 +632,16 @@
 	uint256[] ids;
 }
 
+/// Nested collections and permissions
+struct CollectionNestingAndPermission {
+	/// Owner of token can nest tokens under it.
+	bool token_owner;
+	/// Admin of token collection can nest tokens under token.
+	bool collection_admin;
+	/// If set - only tokens from specified collections can be nested.
+	address[] restricted;
+}
+
 /// [`CollectionLimits`](up_data_structs::CollectionLimits) field representation for EVM.
 struct CollectionLimit {
 	CollectionLimitField field;
modifiedpallets/refungible/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/refungible/src/benchmarking.rs
+++ b/pallets/refungible/src/benchmarking.rs
@@ -61,9 +61,7 @@
 	create_collection_raw(
 		owner,
 		CollectionMode::ReFungible,
-		|owner: T::CrossAccountId, data| {
-			<Pallet<T>>::init_collection(owner.clone(), owner, data, Default::default())
-		},
+		|owner: T::CrossAccountId, data| <Pallet<T>>::init_collection(owner.clone(), owner, data),
 		RefungibleHandle::cast,
 	)
 }
modifiedpallets/refungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -104,11 +104,10 @@
 use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};
 use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};
 use up_data_structs::{
-	AccessMode, budget::Budget, CollectionId, CollectionFlags, CreateCollectionData,
-	mapping::TokenAddressMapping, MAX_REFUNGIBLE_PIECES, Property, PropertyKey,
-	PropertyKeyPermission, PropertyScope, PropertyValue, TokenId, TrySetProperty,
-	PropertiesPermissionMap, CreateRefungibleExMultipleOwners, TokenOwnerError,
-	TokenProperties as TokenPropertiesT,
+	AccessMode, budget::Budget, CollectionId, CreateCollectionData, mapping::TokenAddressMapping,
+	MAX_REFUNGIBLE_PIECES, Property, PropertyKey, PropertyKeyPermission, PropertyScope,
+	PropertyValue, TokenId, TrySetProperty, PropertiesPermissionMap,
+	CreateRefungibleExMultipleOwners, TokenOwnerError, TokenProperties as TokenPropertiesT,
 };
 
 pub use pallet::*;
@@ -334,10 +333,9 @@
 	pub fn init_collection(
 		owner: T::CrossAccountId,
 		payer: T::CrossAccountId,
-		data: CreateCollectionData<T::AccountId>,
-		flags: CollectionFlags,
+		data: CreateCollectionData<T::CrossAccountId>,
 	) -> Result<CollectionId, DispatchError> {
-		<PalletCommon<T>>::init_collection(owner, payer, data, flags)
+		<PalletCommon<T>>::init_collection(owner, payer, data)
 	}
 
 	/// Destroy RFT collection
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
@@ -165,7 +165,7 @@
 }
 
 /// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0x2a14cfd1
+/// @dev the ERC-165 identifier for this interface is 0xb34d97e9
 contract Collection is Dummy, ERC165 {
 	// /// Set collection property.
 	// ///
@@ -377,47 +377,63 @@
 	// 	dummy = 0;
 	// }
 
-	/// Toggle accessibility of collection nesting.
-	///
-	/// @param enable If "true" degenerates to nesting: 'Owner' else to nesting: 'Disabled'
-	/// @dev EVM selector for this function is: 0x112d4586,
-	///  or in textual repr: setCollectionNesting(bool)
-	function setCollectionNesting(bool enable) public {
+	/// @dev EVM selector for this function is: 0x0b9f3890,
+	///  or in textual repr: setCollectionNesting((bool,bool,address[]))
+	function setCollectionNesting(CollectionNestingAndPermission memory collectionNestingAndPermissions) public {
 		require(false, stub_error);
-		enable;
+		collectionNestingAndPermissions;
 		dummy = 0;
 	}
 
-	/// Toggle accessibility of collection nesting.
-	///
-	/// @param enable If "true" degenerates to nesting: {OwnerRestricted: [1, 2, 3]} else to nesting: 'Disabled'
-	/// @param collections Addresses of collections that will be available for nesting.
-	/// @dev EVM selector for this function is: 0x64872396,
-	///  or in textual repr: setCollectionNesting(bool,address[])
-	function setCollectionNesting(bool enable, address[] memory collections) public {
-		require(false, stub_error);
-		enable;
-		collections;
-		dummy = 0;
-	}
+	// /// Toggle accessibility of collection nesting.
+	// ///
+	// /// @param enable If "true" degenerates to nesting: 'Owner' else to nesting: 'Disabled'
+	// /// @dev EVM selector for this function is: 0x112d4586,
+	// ///  or in textual repr: setCollectionNesting(bool)
+	// function setCollectionNesting(bool enable) public {
+	// 	require(false, stub_error);
+	// 	enable;
+	// 	dummy = 0;
+	// }
+
+	// /// Toggle accessibility of collection nesting.
+	// ///
+	// /// @param enable If "true" degenerates to nesting: {OwnerRestricted: [1, 2, 3]} else to nesting: 'Disabled'
+	// /// @param collections Addresses of collections that will be available for nesting.
+	// /// @dev EVM selector for this function is: 0x64872396,
+	// ///  or in textual repr: setCollectionNesting(bool,address[])
+	// function setCollectionNesting(bool enable, address[] memory collections) public {
+	// 	require(false, stub_error);
+	// 	enable;
+	// 	collections;
+	// 	dummy = 0;
+	// }
 
-	/// Returns nesting for a collection
-	/// @dev EVM selector for this function is: 0x22d25bfe,
-	///  or in textual repr: collectionNestingRestrictedCollectionIds()
-	function collectionNestingRestrictedCollectionIds() public view returns (CollectionNesting memory) {
+	/// @dev EVM selector for this function is: 0x92c660a8,
+	///  or in textual repr: collectionNesting()
+	function collectionNesting() public view returns (CollectionNestingAndPermission memory) {
 		require(false, stub_error);
 		dummy;
-		return CollectionNesting(false, new uint256[](0));
+		return CollectionNestingAndPermission(false, false, new address[](0));
 	}
 
-	/// Returns permissions for a collection
-	/// @dev EVM selector for this function is: 0x5b2eaf4b,
-	///  or in textual repr: collectionNestingPermissions()
-	function collectionNestingPermissions() public view returns (CollectionNestingPermission[] memory) {
-		require(false, stub_error);
-		dummy;
-		return new CollectionNestingPermission[](0);
-	}
+	// /// Returns nesting for a collection
+	// /// @dev EVM selector for this function is: 0x22d25bfe,
+	// ///  or in textual repr: collectionNestingRestrictedCollectionIds()
+	// function collectionNestingRestrictedCollectionIds() public view returns (CollectionNesting memory) {
+	// 	require(false, stub_error);
+	// 	dummy;
+	// 	return CollectionNesting(false,new uint256[](0));
+	// }
+
+	// /// Returns permissions for a collection
+	// /// @dev EVM selector for this function is: 0x5b2eaf4b,
+	// ///  or in textual repr: collectionNestingPermissions()
+	// function collectionNestingPermissions() public view returns (CollectionNestingPermission[] memory) {
+	// 	require(false, stub_error);
+	// 	dummy;
+	// 	return new CollectionNestingPermission[](0);
+	// }
 
 	/// Set the collection access method.
 	/// @param mode Access mode
@@ -616,6 +632,16 @@
 	uint256[] ids;
 }
 
+/// Nested collections and permissions
+struct CollectionNestingAndPermission {
+	/// Owner of token can nest tokens under it.
+	bool token_owner;
+	/// Admin of token collection can nest tokens under token.
+	bool collection_admin;
+	/// If set - only tokens from specified collections can be nested.
+	address[] restricted;
+}
+
 /// [`CollectionLimits`](up_data_structs::CollectionLimits) field representation for EVM.
 struct CollectionLimit {
 	CollectionLimitField field;
modifiedpallets/structure/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/structure/src/benchmarking.rs
+++ b/pallets/structure/src/benchmarking.rs
@@ -40,7 +40,6 @@
 				mode: CollectionMode::NFT,
 				..Default::default()
 			},
-			CollectionFlags::default(),
 		)?;
 		let dispatch = T::CollectionDispatch::dispatch(CollectionId(1))?;
 		let dispatch = dispatch.as_dyn();
modifiedpallets/unique/Cargo.tomldiffbeforeafterboth
--- a/pallets/unique/Cargo.toml
+++ b/pallets/unique/Cargo.toml
@@ -47,6 +47,7 @@
 frame-benchmarking = { workspace = true, optional = true }
 frame-support = { workspace = true }
 frame-system = { workspace = true }
+log = { workspace = true }
 pallet-balances-adapter = { workspace = true }
 pallet-common = { workspace = true }
 pallet-evm = { workspace = true }
modifiedpallets/unique/src/eth/mod.rsdiffbeforeafterboth
--- a/pallets/unique/src/eth/mod.rs
+++ b/pallets/unique/src/eth/mod.rs
@@ -15,18 +15,16 @@
 // along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
 //! Implementation of CollectionHelpers contract.
-
+//!
 use core::marker::PhantomData;
 use ethereum as _;
 use evm_coder::{abi::AbiType, generate_stubgen, solidity_interface, types::*};
-use frame_support::traits::Get;
-use crate::Pallet;
-
+use frame_support::{BoundedVec, traits::Get};
 use pallet_common::{
 	CollectionById,
 	dispatch::CollectionDispatch,
 	erc::{CollectionHelpersEvents, static_property::key},
-	eth::{map_eth_to_id, collection_id_to_address},
+	eth::{self, map_eth_to_id, collection_id_to_address},
 	Pallet as PalletCommon, CollectionHandle,
 };
 use pallet_evm::{account::CrossAccountId, OnMethodCall, PrecompileHandle, PrecompileResult};
@@ -36,13 +34,13 @@
 	frontier_contract,
 };
 use up_data_structs::{
-	CollectionDescription, CollectionMode, CollectionName, CollectionTokenPrefix,
-	CreateCollectionData,
+	CollectionDescription, CollectionMode, CollectionName, CollectionPermissions,
+	CollectionTokenPrefix, CreateCollectionData, NestingPermissions,
 };
 
-use crate::{weights::WeightInfo, Config, SelfWeightOf};
+use crate::{weights::WeightInfo, Config, Pallet, SelfWeightOf};
 
-use alloc::format;
+use alloc::{format, collections::BTreeSet};
 use sp_std::vec::Vec;
 
 frontier_contract! {
@@ -113,9 +111,8 @@
 	let collection_helpers_address =
 		T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());
 
-	let collection_id =
-		T::CollectionDispatch::create(caller, collection_helpers_address, data, Default::default())
-			.map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
+	let collection_id = T::CollectionDispatch::create(caller, collection_helpers_address, data)
+		.map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
 	let address = pallet_common::eth::collection_id_to_address(collection_id);
 	Ok(address)
 }
@@ -140,7 +137,119 @@
 impl<T> EvmCollectionHelpers<T>
 where
 	T: Config + pallet_common::Config + pallet_nonfungible::Config + pallet_refungible::Config,
+	T::AccountId: From<[u8; 32]>,
 {
+/*
+	/// Create a collection
+	/// @return address Address of the newly created collection
+	#[weight(<SelfWeightOf<T>>::create_collection())]
+	#[solidity(rename_selector = "createCollection")]
+	fn create_collection(
+		&mut self,
+		caller: Caller,
+		value: Value,
+		data: eth::CreateCollectionData,
+	) -> Result<Address> {
+		let (caller, name, description, token_prefix) =
+			convert_data::<T>(caller, data.name, data.description, data.token_prefix)?;
+		if data.mode != eth::CollectionMode::Fungible && data.decimals != 0 {
+			return Err("decimals are only supported for NFT and RFT collections".into());
+		}
+		let mode = match data.mode {
+			eth::CollectionMode::Fungible => CollectionMode::Fungible(data.decimals),
+			eth::CollectionMode::Nonfungible => CollectionMode::NFT,
+			eth::CollectionMode::Refungible => CollectionMode::ReFungible,
+		};
+
+		let properties: BoundedVec<_, _> = data
+			.properties
+			.into_iter()
+			.map(eth::Property::try_into)
+			.collect::<Result<Vec<_>>>()?
+			.try_into()
+			.map_err(|_| "too many properties")?;
+
+		let token_property_permissions =
+			eth::TokenPropertyPermission::into_property_key_permissions(
+				data.token_property_permissions,
+			)?
+			.try_into()
+			.map_err(|_| "too many property permissions")?;
+
+		let limits = if !data.limits.is_empty() {
+			Some(
+				data.limits
+					.into_iter()
+					.collect::<Result<up_data_structs::CollectionLimits>>()?,
+			)
+		} else {
+			None
+		};
+
+		let pending_sponsor = data.pending_sponsor.into_option_sub_cross_account::<T>()?;
+
+		let restricted = if !data.nesting_settings.restricted.is_empty() {
+			Some(
+				data.nesting_settings
+					.restricted
+					.iter()
+					.map(map_eth_to_id)
+					.collect::<Option<BTreeSet<_>>>()
+					.ok_or("can't convert address into collection id")?
+					.try_into()
+					.map_err(|_| "too many collections")?,
+			)
+		} else {
+			None
+		};
+
+		let admin_list = data
+			.admin_list
+			.into_iter()
+			.map(|admin| admin.into_sub_cross_account::<T>())
+			.collect::<Result<Vec<_>>>()?;
+
+		let flags = data.flags;
+		if !flags.is_allowed_for_user() {
+			return Err("internal flags were used".into());
+		}
+
+		let data = CreateCollectionData {
+			name,
+			mode,
+			description,
+			token_prefix,
+			properties,
+			token_property_permissions,
+			limits,
+			pending_sponsor,
+			access: None,
+			permissions: Some(CollectionPermissions {
+				access: None,
+				mint_mode: None,
+				nesting: Some(NestingPermissions {
+					token_owner: data.nesting_settings.token_owner,
+					collection_admin: data.nesting_settings.collection_admin,
+					restricted,
+					#[cfg(feature = "runtime-benchmarks")]
+					permissive: true,
+				}),
+			}),
+			admin_list,
+			flags,
+		};
+		check_sent_amount_equals_collection_creation_price::<T>(value)?;
+		let collection_helpers_address =
+			T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());
+
+		let collection_id = T::CollectionDispatch::create(caller, collection_helpers_address, data)
+			.map_err(dispatch_to_evm::<T>)?;
+
+		let address = pallet_common::eth::collection_id_to_address(collection_id);
+		Ok(address)
+	}
+*/
+
 	/// Create an NFT collection
 	/// @param name Name of the collection
 	/// @param description Informative description of the collection
@@ -168,13 +277,8 @@
 		check_sent_amount_equals_collection_creation_price::<T>(value)?;
 		let collection_helpers_address =
 			T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());
-		let collection_id = T::CollectionDispatch::create(
-			caller,
-			collection_helpers_address,
-			data,
-			Default::default(),
-		)
-		.map_err(dispatch_to_evm::<T>)?;
+		let collection_id = T::CollectionDispatch::create(caller, collection_helpers_address, data)
+			.map_err(dispatch_to_evm::<T>)?;
 
 		let address = pallet_common::eth::collection_id_to_address(collection_id);
 		Ok(address)
@@ -387,6 +491,8 @@
 pub struct CollectionHelpersOnMethodCall<T: Config>(PhantomData<*const T>);
 impl<T: Config + pallet_nonfungible::Config + pallet_refungible::Config> OnMethodCall<T>
 	for CollectionHelpersOnMethodCall<T>
+where
+	T::AccountId: From<[u8; 32]>,
 {
 	fn is_reserved(contract: &sp_core::H160) -> bool {
 		contract == &T::ContractAddress::get()
modifiedpallets/unique/src/eth/stubs/CollectionHelpers.rawdiffbeforeafterboth

binary blob — no preview

modifiedpallets/unique/src/eth/stubs/CollectionHelpers.soldiffbeforeafterboth
--- a/pallets/unique/src/eth/stubs/CollectionHelpers.sol
+++ b/pallets/unique/src/eth/stubs/CollectionHelpers.sol
@@ -25,8 +25,19 @@
 }
 
 /// @title Contract, which allows users to operate with collections
-/// @dev the ERC-165 identifier for this interface is 0xe65011aa
+/// @dev the ERC-165 identifier for this interface is 0x4135fff1
 contract CollectionHelpers is Dummy, ERC165, CollectionHelpersEvents {
+	/// Create a collection
+	/// @return address Address of the newly created collection
+	/// @dev EVM selector for this function is: 0xa765ee5b,
+	///  or in textual repr: createCollection(((address,uint256),string,string,string,uint8,uint8,(string,bytes)[],(string,(uint8,bool)[])[],(address,uint256)[],(bool,bool,address[]),(uint8,uint256)[],uint8))
+	function createCollection(CreateCollectionData memory data) public payable returns (address) {
+		require(false, stub_error);
+		data;
+		dummy = 0;
+		return 0x0000000000000000000000000000000000000000;
+	}
+
 	/// Create an NFT collection
 	/// @param name Name of the collection
 	/// @param description Informative description of the collection
@@ -156,3 +167,135 @@
 		return 0;
 	}
 }
+
+/// Collection properties
+struct CreateCollectionData {
+	/// Collection sponsor
+	CrossAddress pending_sponsor;
+	/// Collection name
+	string name;
+	/// Collection description
+	string description;
+	/// Token prefix
+	string token_prefix;
+	/// Token type (NFT, FT or RFT)
+	CollectionMode mode;
+	/// Fungible token precision
+	uint8 decimals;
+	/// Custom Properties
+	Property[] properties;
+	/// Permissions for token properties
+	TokenPropertyPermission[] token_property_permissions;
+	/// Collection admins
+	CrossAddress[] admin_list;
+	/// Nesting settings
+	CollectionNestingAndPermission nesting_settings;
+	/// Collection limits
+	CollectionLimitValue[] limits;
+	/// Extra collection flags
+	CollectionFlags flags;
+}
+
+/// Cross account struct
+type CollectionFlags is uint8;
+
+library CollectionFlagsLib {
+	/// Tokens in foreign collections can be transferred, but not burnt
+	CollectionFlags constant foreignField = CollectionFlags.wrap(128);
+	/// Supports ERC721Metadata
+	CollectionFlags constant erc721metadataField = CollectionFlags.wrap(64);
+	/// External collections can't be managed using `unique` api
+	CollectionFlags constant externalField = CollectionFlags.wrap(1);
+
+	/// Reserved bits
+	function reservedField(uint8 value) public pure returns (CollectionFlags) {
+		require(value < 1 << 5, "out of bound value");
+		return CollectionFlags.wrap(value << 1);
+	}
+}
+
+/// [`CollectionLimits`](up_data_structs::CollectionLimits) field representation for EVM.
+struct CollectionLimitValue {
+	CollectionLimitField field;
+	uint256 value;
+}
+
+/// [`CollectionLimits`](up_data_structs::CollectionLimits) fields representation for EVM.
+enum CollectionLimitField {
+	/// How many tokens can a user have on one account.
+	AccountTokenOwnership,
+	/// How many bytes of data are available for sponsorship.
+	SponsoredDataSize,
+	/// In any case, chain default: [`SponsoringRateLimit::SponsoringDisabled`]
+	SponsoredDataRateLimit,
+	/// How many tokens can be mined into this collection.
+	TokenLimit,
+	/// Timeouts for transfer sponsoring.
+	SponsorTransferTimeout,
+	/// Timeout for sponsoring an approval in passed blocks.
+	SponsorApproveTimeout,
+	/// Whether the collection owner of the collection can send tokens (which belong to other users).
+	OwnerCanTransfer,
+	/// Can the collection owner burn other people's tokens.
+	OwnerCanDestroy,
+	/// Is it possible to send tokens from this collection between users.
+	TransferEnabled
+}
+
+/// Nested collections and permissions
+struct CollectionNestingAndPermission {
+	/// Owner of token can nest tokens under it.
+	bool token_owner;
+	/// Admin of token collection can nest tokens under token.
+	bool collection_admin;
+	/// If set - only tokens from specified collections can be nested.
+	address[] restricted;
+}
+
+/// Cross account struct
+struct CrossAddress {
+	address eth;
+	uint256 sub;
+}
+
+/// Ethereum representation of Token Property Permissions.
+struct TokenPropertyPermission {
+	/// Token property key.
+	string key;
+	/// Token property permissions.
+	PropertyPermission[] permissions;
+}
+
+/// Ethereum representation of TokenPermissions (see [`up_data_structs::PropertyPermission`]) as an key and value.
+struct PropertyPermission {
+	/// TokenPermission field.
+	TokenPermissionField code;
+	/// TokenPermission value.
+	bool value;
+}
+
+/// Ethereum representation of TokenPermissions (see [`up_data_structs::PropertyPermission`]) fields as an enumeration.
+enum TokenPermissionField {
+	/// Permission to change the property and property permission. See [`up_data_structs::PropertyPermission::mutable`]
+	Mutable,
+	/// Change permission for the collection administrator. See [`up_data_structs::PropertyPermission::token_owner`]
+	TokenOwner,
+	/// Permission to change the property for the owner of the token. See [`up_data_structs::PropertyPermission::collection_admin`]
+	CollectionAdmin
+}
+
+/// Ethereum representation of collection [`PropertyKey`](up_data_structs::PropertyKey) and [`PropertyValue`](up_data_structs::PropertyValue).
+struct Property {
+	string key;
+	bytes value;
+}
+
+/// Type of tokens in collection
+enum CollectionMode {
+	/// Fungible
+	Fungible,
+	/// Nonfungible
+	Nonfungible,
+	/// Refungible
+	Refungible
+}
modifiedpallets/unique/src/lib.rsdiffbeforeafterboth
--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -365,7 +365,7 @@
 			token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,
 			mode: CollectionMode,
 		) -> DispatchResult {
-			let data: CreateCollectionData<T::AccountId> = CreateCollectionData {
+			let data: CreateCollectionData<T::CrossAccountId> = CreateCollectionData {
 				name: collection_name,
 				description: collection_description,
 				token_prefix,
@@ -390,14 +390,13 @@
 		#[pallet::weight(<SelfWeightOf<T>>::create_collection())]
 		pub fn create_collection_ex(
 			origin: OriginFor<T>,
-			data: CreateCollectionData<T::AccountId>,
+			data: CreateCollectionData<T::CrossAccountId>,
 		) -> DispatchResult {
 			let sender = ensure_signed(origin)?;
 
 			// =========
 			let sender = T::CrossAccountId::from_sub(sender);
-			let _id =
-				T::CollectionDispatch::create(sender.clone(), sender, data, Default::default())?;
+			let _id = T::CollectionDispatch::create(sender.clone(), sender, data)?;
 
 			Ok(())
 		}
modifiedprimitives/data-structs/Cargo.tomldiffbeforeafterboth
--- a/primitives/data-structs/Cargo.toml
+++ b/primitives/data-structs/Cargo.toml
@@ -22,6 +22,7 @@
 sp-std = { workspace = true }
 bondrewd = { version = "0.1.14", features = ["derive"], default-features = false }
 struct-versioning = { workspace = true }
+evm-coder = { workspace = true }
 
 [features]
 default = ["std"]
modifiedprimitives/data-structs/src/lib.rsdiffbeforeafterboth
--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -32,11 +32,13 @@
 
 use sp_core::U256;
 use sp_runtime::{ArithmeticError, sp_std::prelude::Vec};
+use sp_std::collections::btree_set::BTreeSet;
 use codec::{Decode, Encode, EncodeLike, MaxEncodedLen};
-use bondrewd::Bitfields;
 use frame_support::{BoundedVec, traits::ConstU32};
 use derivative::Derivative;
 use scale_info::TypeInfo;
+use evm_coder::AbiCoderFlags;
+use bondrewd::Bitfields;
 
 mod bondrewd_codec;
 mod bounded;
@@ -163,6 +165,14 @@
 	}
 }
 
+impl Deref for CollectionId {
+	type Target = u32;
+
+	fn deref(&self) -> &Self::Target {
+		&self.0
+	}
+}
+
 /// Token id.
 #[derive(
 	Encode,
@@ -350,7 +360,7 @@
 pub type CollectionDescription = BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>;
 pub type CollectionTokenPrefix = BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>;
 
-#[derive(Bitfields, Clone, Copy, PartialEq, Eq, Debug, Default)]
+#[derive(AbiCoderFlags, Bitfields, Clone, Copy, PartialEq, Eq, Debug, Default)]
 #[bondrewd(enforce_bytes = 1)]
 pub struct CollectionFlags {
 	/// Tokens in foreign collections can be transferred, but not burnt
@@ -362,12 +372,18 @@
 	/// External collections can't be managed using `unique` api
 	#[bondrewd(bits = "7..8")]
 	pub external: bool,
-
-	#[bondrewd(reserve, bits = "2..7")]
+	/// Reserved flags
+	#[bondrewd(bits = "2..7")]
 	pub reserved: u8,
 }
 bondrewd_codec!(CollectionFlags);
 
+impl CollectionFlags {
+	pub fn is_allowed_for_user(self) -> bool {
+		!self.foreign && !self.external && self.reserved == 0
+	}
+}
+
 /// Base structure for represent collection.
 ///
 /// Used to provide basic functionality for all types of collections.
@@ -545,7 +561,7 @@
 /// All fields are wrapped in [`Option`], where `None` means chain default.
 #[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Derivative, MaxEncodedLen)]
 #[derivative(Debug, Default(bound = ""))]
-pub struct CreateCollectionData<AccountId> {
+pub struct CreateCollectionData<CrossAccountId> {
 	/// Collection mode.
 	#[derivative(Default(value = "CollectionMode::NFT"))]
 	pub mode: CollectionMode,
@@ -562,9 +578,6 @@
 	/// Token prefix.
 	pub token_prefix: CollectionTokenPrefix,
 
-	/// Pending collection sponsor.
-	pub pending_sponsor: Option<AccountId>,
-
 	/// Collection limits.
 	pub limits: Option<CollectionLimits>,
 
@@ -576,6 +589,13 @@
 
 	/// Collection properties.
 	pub properties: CollectionPropertiesVec,
+
+	pub admin_list: Vec<CrossAccountId>,
+
+	/// Pending collection sponsor.
+	pub pending_sponsor: Option<CrossAccountId>,
+
+	pub flags: CollectionFlags,
 }
 
 /// Bounded vector of properties permissions. Max length is [`MAX_PROPERTIES_PER_ITEM`].
@@ -833,6 +853,14 @@
 	}
 }
 
+impl TryFrom<BTreeSet<CollectionId>> for OwnerRestrictedSet {
+	type Error = ();
+
+	fn try_from(value: BTreeSet<CollectionId>) -> Result<Self, Self::Error> {
+		Ok(Self(value.try_into()?))
+	}
+}
+
 /// Part of collection permissions, if set, defines who is able to nest tokens into other tokens.
 #[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative)]
 #[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
modifiedruntime/common/dispatch.rsdiffbeforeafterboth
--- a/runtime/common/dispatch.rs
+++ b/runtime/common/dispatch.rs
@@ -25,14 +25,14 @@
 };
 pub use pallet_common::dispatch::CollectionDispatch;
 use pallet_fungible::{Pallet as PalletFungible, FungibleHandle};
-use pallet_balances_adapter::{NativeFungibleHandle};
+use pallet_balances_adapter::NativeFungibleHandle;
 use pallet_nonfungible::{Pallet as PalletNonfungible, NonfungibleHandle};
 use pallet_refungible::{
 	Pallet as PalletRefungible, RefungibleHandle, erc_token::RefungibleTokenHandle,
 };
 use up_data_structs::{
 	CollectionMode, CreateCollectionData, MAX_DECIMAL_POINTS, mapping::TokenAddressMapping,
-	CollectionId, CollectionFlags,
+	CollectionId,
 };
 
 #[cfg(not(feature = "refungible"))]
@@ -72,26 +72,21 @@
 	fn create(
 		sender: T::CrossAccountId,
 		payer: T::CrossAccountId,
-		data: CreateCollectionData<T::AccountId>,
-		flags: CollectionFlags,
+		data: CreateCollectionData<T::CrossAccountId>,
 	) -> Result<CollectionId, DispatchError> {
 		let id = match data.mode {
-			CollectionMode::NFT => {
-				<PalletNonfungible<T>>::init_collection(sender, payer, data, flags)?
-			}
+			CollectionMode::NFT => <PalletNonfungible<T>>::init_collection(sender, payer, data)?,
 			CollectionMode::Fungible(decimal_points) => {
 				// check params
 				ensure!(
 					decimal_points <= MAX_DECIMAL_POINTS,
 					pallet_unique::Error::<T>::CollectionDecimalPointLimitExceeded
 				);
-				<PalletFungible<T>>::init_collection(sender, payer, data, flags)?
+				<PalletFungible<T>>::init_collection(sender, payer, data)?
 			}
 
 			#[cfg(feature = "refungible")]
-			CollectionMode::ReFungible => {
-				<PalletRefungible<T>>::init_collection(sender, payer, data, flags)?
-			}
+			CollectionMode::ReFungible => <PalletRefungible<T>>::init_collection(sender, payer, data)?,
 
 			#[cfg(not(feature = "refungible"))]
 			CollectionMode::ReFungible => return unsupported!(T),
modifiedruntime/common/ethereum/sponsoring.rsdiffbeforeafterboth
--- a/runtime/common/ethereum/sponsoring.rs
+++ b/runtime/common/ethereum/sponsoring.rs
@@ -234,6 +234,7 @@
 			| CollectionOwner
 			| CollectionAdmins
 			| CollectionLimits
+			| CollectionNesting
 			| CollectionNestingRestrictedIds
 			| CollectionNestingPermissions
 			| UniqueCollectionType => None,
@@ -249,6 +250,7 @@
 			| RemoveCollectionAdmin { .. }
 			| SetNestingBool { .. }
 			| SetNesting { .. }
+			| SetNestingCollectionIds { .. }
 			| SetCollectionAccess { .. }
 			| SetCollectionMintMode { .. }
 			| SetOwner { .. }
modifiedtests/src/benchmarks/opsFee/index.tsdiffbeforeafterboth
--- a/tests/src/benchmarks/opsFee/index.ts
+++ b/tests/src/benchmarks/opsFee/index.ts
@@ -1,6 +1,6 @@
 import {EthUniqueHelper, usingEthPlaygrounds} from '../../eth/util';
 import {readFile} from 'fs/promises';
-import {CollectionLimitField,  TokenPermissionField} from '../../eth/util/playgrounds/types';
+import {CollectionLimitField,  CreateCollectionData,  TokenPermissionField} from '../../eth/util/playgrounds/types';
 import {IKeyringPair} from '@polkadot/types/types';
 import {UniqueFTCollection, UniqueNFTCollection} from '../../util/playgrounds/unique';
 import {Contract} from 'web3-eth-contract';
@@ -399,7 +399,7 @@
     () => collection.setLimits(donor, {accountTokenOwnershipLimit: 1000}),
   )));
 
-  const {collectionAddress} = await helper.eth.createCollection('nft', ethSigner, 'A', 'B', 'C');
+  const {collectionAddress} = await helper.eth.createCollection(ethSigner, new CreateCollectionData('A', 'B', 'C', 'nft')).send();
   const collectionWithEthOwner = await helper.ethNativeContract.collection(collectionAddress, 'nft', ethSigner, true);
 
 
@@ -775,7 +775,7 @@
     () => collection.setLimits(donor, {accountTokenOwnershipLimit: 1000}),
   )));
 
-  const {collectionAddress} = await helper.eth.createCollection('nft', ethSigner, 'A', 'B', 'C');
+  const {collectionAddress} = await helper.eth.createCollection(ethSigner, new CreateCollectionData('A', 'B', 'C', 'nft')).send();
   const collectionWithEthOwner = await helper.ethNativeContract.collection(collectionAddress, 'nft', ethSigner, true);
 
 
modifiedtests/src/createCollection.test.tsdiffbeforeafterboth
--- a/tests/src/createCollection.test.ts
+++ b/tests/src/createCollection.test.ts
@@ -16,7 +16,7 @@
 
 import {IKeyringPair} from '@polkadot/types/types';
 import {usingPlaygrounds, expect, itSub, Pallets} from './util';
-import {ICollectionCreationOptions, IProperty} from './util/playgrounds/types';
+import {CollectionFlag, ICollectionCreationOptions, IProperty} from './util/playgrounds/types';
 import {UniqueHelper} from './util/playgrounds/unique';
 
 async function mintCollectionHelper(helper: UniqueHelper, signer: IKeyringPair, options: ICollectionCreationOptions, type?: 'nft' | 'fungible' | 'refungible') {
@@ -36,6 +36,16 @@
   if(options.properties) {
     expect(data?.raw.properties).to.be.deep.equal(options.properties);
   }
+  if(options.adminList) {
+    expect(data?.admins).to.be.deep.equal(options.adminList);
+  }
+
+  if(options.flags) {
+    if((options.flags[0] & 64) != 0)
+      expect(data?.raw.flags.erc721metadata).to.be.true;
+    if((options.flags[0] & 128) != 0)
+      expect(data?.raw.flags.foreign).to.be.false;
+  }
 
   if(options.tokenPropertyPermissions) {
     expect(data?.raw.tokenPropertyPermissions).to.be.deep.equal(options.tokenPropertyPermissions);
@@ -46,11 +56,12 @@
 
 describe('integration test: ext. createCollection():', () => {
   let alice: IKeyringPair;
+  let bob: IKeyringPair;
 
   before(async () => {
     await usingPlaygrounds(async (helper, privateKey) => {
       const donor = await privateKey({url: import.meta.url});
-      [alice] = await helper.arrange.createAccounts([100n], donor);
+      [alice, bob] = await helper.arrange.createAccounts([100n, 100n], donor);
     });
   });
   itSub('Create new NFT collection', async ({helper}) => {
@@ -82,6 +93,30 @@
     }, 'nft');
   });
 
+  itSub('create new collection with admin', async ({helper}) => {
+    await mintCollectionHelper(helper, alice, {
+      name: 'name', description: 'descr', tokenPrefix: 'COL',
+      adminList: [{Substrate: bob.address}],
+    }, 'nft');
+  });
+
+  itSub('create new collection with flags', async ({helper}) => {
+    await mintCollectionHelper(helper, alice, {
+      name: 'name', description: 'descr', tokenPrefix: 'COL',
+      flags: [CollectionFlag.Erc721metadata],
+    }, 'nft');
+
+    await mintCollectionHelper(helper, alice, {
+      name: 'name', description: 'descr', tokenPrefix: 'COL',
+      flags: [CollectionFlag.Foreign],
+    }, 'nft');
+
+    await mintCollectionHelper(helper, alice, {
+      name: 'name', description: 'descr', tokenPrefix: 'COL',
+      flags: [CollectionFlag.Erc721metadata, CollectionFlag.Foreign],
+    }, 'nft');
+  });
+
   itSub('Create new collection with extra fields', async ({helper}) => {
     const collection = await mintCollectionHelper(helper, alice, {name: 'name', description: 'descr', tokenPrefix: 'COL'}, 'fungible');
     await collection.setPermissions(alice, {access: 'AllowList'});
modifiedtests/src/eth/abi/collectionHelpers.jsondiffbeforeafterboth
--- a/tests/src/eth/abi/collectionHelpers.json
+++ b/tests/src/eth/abi/collectionHelpers.json
@@ -75,6 +75,118 @@
   },
   {
     "inputs": [
+      {
+        "components": [
+          {
+            "components": [
+              { "internalType": "address", "name": "eth", "type": "address" },
+              { "internalType": "uint256", "name": "sub", "type": "uint256" }
+            ],
+            "internalType": "struct CrossAddress",
+            "name": "pending_sponsor",
+            "type": "tuple"
+          },
+          { "internalType": "string", "name": "name", "type": "string" },
+          { "internalType": "string", "name": "description", "type": "string" },
+          {
+            "internalType": "string",
+            "name": "token_prefix",
+            "type": "string"
+          },
+          {
+            "internalType": "enum CollectionMode",
+            "name": "mode",
+            "type": "uint8"
+          },
+          { "internalType": "uint8", "name": "decimals", "type": "uint8" },
+          {
+            "components": [
+              { "internalType": "string", "name": "key", "type": "string" },
+              { "internalType": "bytes", "name": "value", "type": "bytes" }
+            ],
+            "internalType": "struct Property[]",
+            "name": "properties",
+            "type": "tuple[]"
+          },
+          {
+            "components": [
+              { "internalType": "string", "name": "key", "type": "string" },
+              {
+                "components": [
+                  {
+                    "internalType": "enum TokenPermissionField",
+                    "name": "code",
+                    "type": "uint8"
+                  },
+                  { "internalType": "bool", "name": "value", "type": "bool" }
+                ],
+                "internalType": "struct PropertyPermission[]",
+                "name": "permissions",
+                "type": "tuple[]"
+              }
+            ],
+            "internalType": "struct TokenPropertyPermission[]",
+            "name": "token_property_permissions",
+            "type": "tuple[]"
+          },
+          {
+            "components": [
+              { "internalType": "address", "name": "eth", "type": "address" },
+              { "internalType": "uint256", "name": "sub", "type": "uint256" }
+            ],
+            "internalType": "struct CrossAddress[]",
+            "name": "admin_list",
+            "type": "tuple[]"
+          },
+          {
+            "components": [
+              { "internalType": "bool", "name": "token_owner", "type": "bool" },
+              {
+                "internalType": "bool",
+                "name": "collection_admin",
+                "type": "bool"
+              },
+              {
+                "internalType": "address[]",
+                "name": "restricted",
+                "type": "address[]"
+              }
+            ],
+            "internalType": "struct CollectionNestingAndPermission",
+            "name": "nesting_settings",
+            "type": "tuple"
+          },
+          {
+            "components": [
+              {
+                "internalType": "enum CollectionLimitField",
+                "name": "field",
+                "type": "uint8"
+              },
+              { "internalType": "uint256", "name": "value", "type": "uint256" }
+            ],
+            "internalType": "struct CollectionLimitValue[]",
+            "name": "limits",
+            "type": "tuple[]"
+          },
+          {
+            "internalType": "CollectionFlags",
+            "name": "flags",
+            "type": "uint8"
+          }
+        ],
+        "internalType": "struct CreateCollectionData",
+        "name": "data",
+        "type": "tuple"
+      }
+    ],
+    "name": "createCollection",
+    "outputs": [{ "internalType": "address", "name": "", "type": "address" }],
+    "stateMutability": "payable",
+    "type": "function"
+  },
+  {
+    "inputs": [
       { "internalType": "string", "name": "name", "type": "string" },
       { "internalType": "uint8", "name": "decimals", "type": "uint8" },
       { "internalType": "string", "name": "description", "type": "string" },
modifiedtests/src/eth/abi/fungible.jsondiffbeforeafterboth
--- a/tests/src/eth/abi/fungible.json
+++ b/tests/src/eth/abi/fungible.json
@@ -280,35 +280,23 @@
   },
   {
     "inputs": [],
-    "name": "collectionNestingPermissions",
+    "name": "collectionNesting",
     "outputs": [
       {
         "components": [
+          { "internalType": "bool", "name": "token_owner", "type": "bool" },
           {
-            "internalType": "enum CollectionPermissionField",
-            "name": "field",
-            "type": "uint8"
+            "internalType": "bool",
+            "name": "collection_admin",
+            "type": "bool"
           },
-          { "internalType": "bool", "name": "value", "type": "bool" }
-        ],
-        "internalType": "struct CollectionNestingPermission[]",
-        "name": "",
-        "type": "tuple[]"
-      }
-    ],
-    "stateMutability": "view",
-    "type": "function"
-  },
-  {
-    "inputs": [],
-    "name": "collectionNestingRestrictedCollectionIds",
-    "outputs": [
-      {
-        "components": [
-          { "internalType": "bool", "name": "token_owner", "type": "bool" },
-          { "internalType": "uint256[]", "name": "ids", "type": "uint256[]" }
+          {
+            "internalType": "address[]",
+            "name": "restricted",
+            "type": "address[]"
+          }
         ],
-        "internalType": "struct CollectionNesting",
+        "internalType": "struct CollectionNestingAndPermission",
         "name": "",
         "type": "tuple"
       }
@@ -576,19 +564,24 @@
     "type": "function"
   },
   {
-    "inputs": [{ "internalType": "bool", "name": "enable", "type": "bool" }],
-    "name": "setCollectionNesting",
-    "outputs": [],
-    "stateMutability": "nonpayable",
-    "type": "function"
-  },
-  {
     "inputs": [
-      { "internalType": "bool", "name": "enable", "type": "bool" },
       {
-        "internalType": "address[]",
-        "name": "collections",
-        "type": "address[]"
+        "components": [
+          { "internalType": "bool", "name": "token_owner", "type": "bool" },
+          {
+            "internalType": "bool",
+            "name": "collection_admin",
+            "type": "bool"
+          },
+          {
+            "internalType": "address[]",
+            "name": "restricted",
+            "type": "address[]"
+          }
+        ],
+        "internalType": "struct CollectionNestingAndPermission",
+        "name": "collectionNestingAndPermissions",
+        "type": "tuple"
       }
     ],
     "name": "setCollectionNesting",
modifiedtests/src/eth/abi/fungibleDeprecated.jsondiffbeforeafterboth
--- a/tests/src/eth/abi/fungibleDeprecated.json
+++ b/tests/src/eth/abi/fungibleDeprecated.json
@@ -88,5 +88,64 @@
     "outputs": [],
     "stateMutability": "nonpayable",
     "type": "function"
+  },
+  {
+    "inputs": [],
+    "name": "collectionNestingPermissions",
+    "outputs": [
+      {
+        "components": [
+          {
+            "internalType": "enum CollectionPermissionField",
+            "name": "field",
+            "type": "uint8"
+          },
+          { "internalType": "bool", "name": "value", "type": "bool" }
+        ],
+        "internalType": "struct CollectionNestingPermission[]",
+        "name": "",
+        "type": "tuple[]"
+      }
+    ],
+    "stateMutability": "view",
+    "type": "function"
+  },
+  {
+    "inputs": [],
+    "name": "collectionNestingRestrictedCollectionIds",
+    "outputs": [
+      {
+        "components": [
+          { "internalType": "bool", "name": "token_owner", "type": "bool" },
+          { "internalType": "uint256[]", "name": "ids", "type": "uint256[]" }
+        ],
+        "internalType": "struct CollectionNesting",
+        "name": "",
+        "type": "tuple"
+      }
+    ],
+    "stateMutability": "view",
+    "type": "function"
+  },
+  {
+    "inputs": [{ "internalType": "bool", "name": "enable", "type": "bool" }],
+    "name": "setCollectionNesting",
+    "outputs": [],
+    "stateMutability": "nonpayable",
+    "type": "function"
+  },
+  {
+    "inputs": [
+      { "internalType": "bool", "name": "enable", "type": "bool" },
+      {
+        "internalType": "address[]",
+        "name": "collections",
+        "type": "address[]"
+      }
+    ],
+    "name": "setCollectionNesting",
+    "outputs": [],
+    "stateMutability": "nonpayable",
+    "type": "function"
   }
 ]
modifiedtests/src/eth/abi/nonFungible.jsondiffbeforeafterboth
--- a/tests/src/eth/abi/nonFungible.json
+++ b/tests/src/eth/abi/nonFungible.json
@@ -291,35 +291,23 @@
   },
   {
     "inputs": [],
-    "name": "collectionNestingPermissions",
+    "name": "collectionNesting",
     "outputs": [
       {
         "components": [
+          { "internalType": "bool", "name": "token_owner", "type": "bool" },
           {
-            "internalType": "enum CollectionPermissionField",
-            "name": "field",
-            "type": "uint8"
+            "internalType": "bool",
+            "name": "collection_admin",
+            "type": "bool"
           },
-          { "internalType": "bool", "name": "value", "type": "bool" }
-        ],
-        "internalType": "struct CollectionNestingPermission[]",
-        "name": "",
-        "type": "tuple[]"
-      }
-    ],
-    "stateMutability": "view",
-    "type": "function"
-  },
-  {
-    "inputs": [],
-    "name": "collectionNestingRestrictedCollectionIds",
-    "outputs": [
-      {
-        "components": [
-          { "internalType": "bool", "name": "token_owner", "type": "bool" },
-          { "internalType": "uint256[]", "name": "ids", "type": "uint256[]" }
+          {
+            "internalType": "address[]",
+            "name": "restricted",
+            "type": "address[]"
+          }
         ],
-        "internalType": "struct CollectionNesting",
+        "internalType": "struct CollectionNestingAndPermission",
         "name": "",
         "type": "tuple"
       }
@@ -705,19 +693,24 @@
     "type": "function"
   },
   {
-    "inputs": [{ "internalType": "bool", "name": "enable", "type": "bool" }],
-    "name": "setCollectionNesting",
-    "outputs": [],
-    "stateMutability": "nonpayable",
-    "type": "function"
-  },
-  {
     "inputs": [
-      { "internalType": "bool", "name": "enable", "type": "bool" },
       {
-        "internalType": "address[]",
-        "name": "collections",
-        "type": "address[]"
+        "components": [
+          { "internalType": "bool", "name": "token_owner", "type": "bool" },
+          {
+            "internalType": "bool",
+            "name": "collection_admin",
+            "type": "bool"
+          },
+          {
+            "internalType": "address[]",
+            "name": "restricted",
+            "type": "address[]"
+          }
+        ],
+        "internalType": "struct CollectionNestingAndPermission",
+        "name": "collectionNestingAndPermissions",
+        "type": "tuple"
       }
     ],
     "name": "setCollectionNesting",
modifiedtests/src/eth/abi/nonFungibleDeprecated.jsondiffbeforeafterboth
--- a/tests/src/eth/abi/nonFungibleDeprecated.json
+++ b/tests/src/eth/abi/nonFungibleDeprecated.json
@@ -109,5 +109,64 @@
     "outputs": [],
     "stateMutability": "nonpayable",
     "type": "function"
+  },
+  {
+    "inputs": [],
+    "name": "collectionNestingPermissions",
+    "outputs": [
+      {
+        "components": [
+          {
+            "internalType": "enum CollectionPermissionField",
+            "name": "field",
+            "type": "uint8"
+          },
+          { "internalType": "bool", "name": "value", "type": "bool" }
+        ],
+        "internalType": "struct CollectionNestingPermission[]",
+        "name": "",
+        "type": "tuple[]"
+      }
+    ],
+    "stateMutability": "view",
+    "type": "function"
+  },
+  {
+    "inputs": [],
+    "name": "collectionNestingRestrictedCollectionIds",
+    "outputs": [
+      {
+        "components": [
+          { "internalType": "bool", "name": "token_owner", "type": "bool" },
+          { "internalType": "uint256[]", "name": "ids", "type": "uint256[]" }
+        ],
+        "internalType": "struct CollectionNesting",
+        "name": "",
+        "type": "tuple"
+      }
+    ],
+    "stateMutability": "view",
+    "type": "function"
+  },
+  {
+    "inputs": [{ "internalType": "bool", "name": "enable", "type": "bool" }],
+    "name": "setCollectionNesting",
+    "outputs": [],
+    "stateMutability": "nonpayable",
+    "type": "function"
+  },
+  {
+    "inputs": [
+      { "internalType": "bool", "name": "enable", "type": "bool" },
+      {
+        "internalType": "address[]",
+        "name": "collections",
+        "type": "address[]"
+      }
+    ],
+    "name": "setCollectionNesting",
+    "outputs": [],
+    "stateMutability": "nonpayable",
+    "type": "function"
   }
 ]
modifiedtests/src/eth/abi/reFungible.jsondiffbeforeafterboth
--- a/tests/src/eth/abi/reFungible.json
+++ b/tests/src/eth/abi/reFungible.json
@@ -273,35 +273,23 @@
   },
   {
     "inputs": [],
-    "name": "collectionNestingPermissions",
+    "name": "collectionNesting",
     "outputs": [
       {
         "components": [
+          { "internalType": "bool", "name": "token_owner", "type": "bool" },
           {
-            "internalType": "enum CollectionPermissionField",
-            "name": "field",
-            "type": "uint8"
+            "internalType": "bool",
+            "name": "collection_admin",
+            "type": "bool"
           },
-          { "internalType": "bool", "name": "value", "type": "bool" }
-        ],
-        "internalType": "struct CollectionNestingPermission[]",
-        "name": "",
-        "type": "tuple[]"
-      }
-    ],
-    "stateMutability": "view",
-    "type": "function"
-  },
-  {
-    "inputs": [],
-    "name": "collectionNestingRestrictedCollectionIds",
-    "outputs": [
-      {
-        "components": [
-          { "internalType": "bool", "name": "token_owner", "type": "bool" },
-          { "internalType": "uint256[]", "name": "ids", "type": "uint256[]" }
+          {
+            "internalType": "address[]",
+            "name": "restricted",
+            "type": "address[]"
+          }
         ],
-        "internalType": "struct CollectionNesting",
+        "internalType": "struct CollectionNestingAndPermission",
         "name": "",
         "type": "tuple"
       }
@@ -687,19 +675,24 @@
     "type": "function"
   },
   {
-    "inputs": [{ "internalType": "bool", "name": "enable", "type": "bool" }],
-    "name": "setCollectionNesting",
-    "outputs": [],
-    "stateMutability": "nonpayable",
-    "type": "function"
-  },
-  {
     "inputs": [
-      { "internalType": "bool", "name": "enable", "type": "bool" },
       {
-        "internalType": "address[]",
-        "name": "collections",
-        "type": "address[]"
+        "components": [
+          { "internalType": "bool", "name": "token_owner", "type": "bool" },
+          {
+            "internalType": "bool",
+            "name": "collection_admin",
+            "type": "bool"
+          },
+          {
+            "internalType": "address[]",
+            "name": "restricted",
+            "type": "address[]"
+          }
+        ],
+        "internalType": "struct CollectionNestingAndPermission",
+        "name": "collectionNestingAndPermissions",
+        "type": "tuple"
       }
     ],
     "name": "setCollectionNesting",
modifiedtests/src/eth/abi/reFungibleDeprecated.jsondiffbeforeafterboth
--- a/tests/src/eth/abi/reFungibleDeprecated.json
+++ b/tests/src/eth/abi/reFungibleDeprecated.json
@@ -137,5 +137,64 @@
     "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
     "stateMutability": "nonpayable",
     "type": "function"
+  },
+  {
+    "inputs": [],
+    "name": "collectionNestingPermissions",
+    "outputs": [
+      {
+        "components": [
+          {
+            "internalType": "enum CollectionPermissionField",
+            "name": "field",
+            "type": "uint8"
+          },
+          { "internalType": "bool", "name": "value", "type": "bool" }
+        ],
+        "internalType": "struct CollectionNestingPermission[]",
+        "name": "",
+        "type": "tuple[]"
+      }
+    ],
+    "stateMutability": "view",
+    "type": "function"
+  },
+  {
+    "inputs": [],
+    "name": "collectionNestingRestrictedCollectionIds",
+    "outputs": [
+      {
+        "components": [
+          { "internalType": "bool", "name": "token_owner", "type": "bool" },
+          { "internalType": "uint256[]", "name": "ids", "type": "uint256[]" }
+        ],
+        "internalType": "struct CollectionNesting",
+        "name": "",
+        "type": "tuple"
+      }
+    ],
+    "stateMutability": "view",
+    "type": "function"
+  },
+  {
+    "inputs": [{ "internalType": "bool", "name": "enable", "type": "bool" }],
+    "name": "setCollectionNesting",
+    "outputs": [],
+    "stateMutability": "nonpayable",
+    "type": "function"
+  },
+  {
+    "inputs": [
+      { "internalType": "bool", "name": "enable", "type": "bool" },
+      {
+        "internalType": "address[]",
+        "name": "collections",
+        "type": "address[]"
+      }
+    ],
+    "name": "setCollectionNesting",
+    "outputs": [],
+    "stateMutability": "nonpayable",
+    "type": "function"
   }
 ]
modifiedtests/src/eth/allowlist.test.tsdiffbeforeafterboth
--- a/tests/src/eth/allowlist.test.ts
+++ b/tests/src/eth/allowlist.test.ts
@@ -17,6 +17,7 @@
 import {IKeyringPair} from '@polkadot/types/types';
 import {Pallets} from '../util';
 import {itEth, usingEthPlaygrounds, expect, SponsoringMode} from './util';
+import {CreateCollectionData} from './util/playgrounds/types';
 
 describe('EVM contract allowlist', () => {
   let donor: IKeyringPair;
@@ -104,7 +105,7 @@
       const userEth = await helper.eth.createAccountWithBalance(donor);
       const mintParams = testCase.mode === 'ft' ? [userEth, 100] : [userEth];
 
-      const {collectionAddress, collectionId} = await helper.eth.createCollection(testCase.mode, owner, 'A', 'B', 'C');
+      const {collectionAddress, collectionId} = await helper.eth.createCollection(owner, new CreateCollectionData('A', 'B', 'C', testCase.mode)).send();
       const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, owner);
       const userCrossSub = helper.ethCrossAccount.fromKeyringPair(userSub);
       const userCrossEth = helper.ethCrossAccount.fromAddress(userEth);
@@ -178,7 +179,7 @@
       const userEth = helper.eth.createAccount();
       const userCrossEth = helper.ethCrossAccount.fromAddress(userEth);
 
-      const {collectionAddress, collectionId} = await helper.eth.createCollection(testCase.mode, owner, 'A', 'B', 'C');
+      const {collectionAddress, collectionId} = await helper.eth.createCollection(owner, new CreateCollectionData('A', 'B', 'C', testCase.mode)).send();
       const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, owner, !testCase.cross);
 
       expect(await helper.collection.allowed(collectionId, {Substrate: userSub.address})).to.be.false;
modifiedtests/src/eth/api/CollectionHelpers.soldiffbeforeafterboth
--- a/tests/src/eth/api/CollectionHelpers.sol
+++ b/tests/src/eth/api/CollectionHelpers.sol
@@ -20,8 +20,14 @@
 }
 
 /// @title Contract, which allows users to operate with collections
-/// @dev the ERC-165 identifier for this interface is 0xe65011aa
+/// @dev the ERC-165 identifier for this interface is 0x4135fff1
 interface CollectionHelpers is Dummy, ERC165, CollectionHelpersEvents {
+	/// Create a collection
+	/// @return address Address of the newly created collection
+	/// @dev EVM selector for this function is: 0xa765ee5b,
+	///  or in textual repr: createCollection(((address,uint256),string,string,string,uint8,uint8,(string,bytes)[],(string,(uint8,bool)[])[],(address,uint256)[],(bool,bool,address[]),(uint8,uint256)[],uint8))
+	function createCollection(CreateCollectionData memory data) external payable returns (address);
+
 	/// Create an NFT collection
 	/// @param name Name of the collection
 	/// @param description Informative description of the collection
@@ -94,3 +100,135 @@
 	///  or in textual repr: collectionId(address)
 	function collectionId(address collectionAddress) external view returns (uint32);
 }
+
+/// Collection properties
+struct CreateCollectionData {
+	/// Collection sponsor
+	CrossAddress pending_sponsor;
+	/// Collection name
+	string name;
+	/// Collection description
+	string description;
+	/// Token prefix
+	string token_prefix;
+	/// Token type (NFT, FT or RFT)
+	CollectionMode mode;
+	/// Fungible token precision
+	uint8 decimals;
+	/// Custom Properties
+	Property[] properties;
+	/// Permissions for token properties
+	TokenPropertyPermission[] token_property_permissions;
+	/// Collection admins
+	CrossAddress[] admin_list;
+	/// Nesting settings
+	CollectionNestingAndPermission nesting_settings;
+	/// Collection limits
+	CollectionLimitValue[] limits;
+	/// Extra collection flags
+	CollectionFlags flags;
+}
+
+/// Cross account struct
+type CollectionFlags is uint8;
+
+library CollectionFlagsLib {
+	/// Tokens in foreign collections can be transferred, but not burnt
+	CollectionFlags constant foreignField = CollectionFlags.wrap(128);
+	/// Supports ERC721Metadata
+	CollectionFlags constant erc721metadataField = CollectionFlags.wrap(64);
+	/// External collections can't be managed using `unique` api
+	CollectionFlags constant externalField = CollectionFlags.wrap(1);
+
+	/// Reserved bits
+	function reservedField(uint8 value) public pure returns (CollectionFlags) {
+		require(value < 1 << 5, "out of bound value");
+		return CollectionFlags.wrap(value << 1);
+	}
+}
+
+/// [`CollectionLimits`](up_data_structs::CollectionLimits) field representation for EVM.
+struct CollectionLimitValue {
+	CollectionLimitField field;
+	uint256 value;
+}
+
+/// [`CollectionLimits`](up_data_structs::CollectionLimits) fields representation for EVM.
+enum CollectionLimitField {
+	/// How many tokens can a user have on one account.
+	AccountTokenOwnership,
+	/// How many bytes of data are available for sponsorship.
+	SponsoredDataSize,
+	/// In any case, chain default: [`SponsoringRateLimit::SponsoringDisabled`]
+	SponsoredDataRateLimit,
+	/// How many tokens can be mined into this collection.
+	TokenLimit,
+	/// Timeouts for transfer sponsoring.
+	SponsorTransferTimeout,
+	/// Timeout for sponsoring an approval in passed blocks.
+	SponsorApproveTimeout,
+	/// Whether the collection owner of the collection can send tokens (which belong to other users).
+	OwnerCanTransfer,
+	/// Can the collection owner burn other people's tokens.
+	OwnerCanDestroy,
+	/// Is it possible to send tokens from this collection between users.
+	TransferEnabled
+}
+
+/// Nested collections and permissions
+struct CollectionNestingAndPermission {
+	/// Owner of token can nest tokens under it.
+	bool token_owner;
+	/// Admin of token collection can nest tokens under token.
+	bool collection_admin;
+	/// If set - only tokens from specified collections can be nested.
+	address[] restricted;
+}
+
+/// Cross account struct
+struct CrossAddress {
+	address eth;
+	uint256 sub;
+}
+
+/// Ethereum representation of Token Property Permissions.
+struct TokenPropertyPermission {
+	/// Token property key.
+	string key;
+	/// Token property permissions.
+	PropertyPermission[] permissions;
+}
+
+/// Ethereum representation of TokenPermissions (see [`up_data_structs::PropertyPermission`]) as an key and value.
+struct PropertyPermission {
+	/// TokenPermission field.
+	TokenPermissionField code;
+	/// TokenPermission value.
+	bool value;
+}
+
+/// Ethereum representation of TokenPermissions (see [`up_data_structs::PropertyPermission`]) fields as an enumeration.
+enum TokenPermissionField {
+	/// Permission to change the property and property permission. See [`up_data_structs::PropertyPermission::mutable`]
+	Mutable,
+	/// Change permission for the collection administrator. See [`up_data_structs::PropertyPermission::token_owner`]
+	TokenOwner,
+	/// Permission to change the property for the owner of the token. See [`up_data_structs::PropertyPermission::collection_admin`]
+	CollectionAdmin
+}
+
+/// Ethereum representation of collection [`PropertyKey`](up_data_structs::PropertyKey) and [`PropertyValue`](up_data_structs::PropertyValue).
+struct Property {
+	string key;
+	bytes value;
+}
+
+/// Type of tokens in collection
+enum CollectionMode {
+	/// Fungible
+	Fungible,
+	/// Nonfungible
+	Nonfungible,
+	/// Refungible
+	Refungible
+}
modifiedtests/src/eth/api/UniqueFungible.soldiffbeforeafterboth
--- a/tests/src/eth/api/UniqueFungible.sol
+++ b/tests/src/eth/api/UniqueFungible.sol
@@ -13,7 +13,7 @@
 }
 
 /// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0x2a14cfd1
+/// @dev the ERC-165 identifier for this interface is 0xb34d97e9
 interface Collection is Dummy, ERC165 {
 	// /// Set collection property.
 	// ///
@@ -148,30 +148,38 @@
 	// ///  or in textual repr: removeCollectionAdmin(address)
 	// function removeCollectionAdmin(address admin) external;
 
-	/// Toggle accessibility of collection nesting.
-	///
-	/// @param enable If "true" degenerates to nesting: 'Owner' else to nesting: 'Disabled'
-	/// @dev EVM selector for this function is: 0x112d4586,
-	///  or in textual repr: setCollectionNesting(bool)
-	function setCollectionNesting(bool enable) external;
+	/// @dev EVM selector for this function is: 0x0b9f3890,
+	///  or in textual repr: setCollectionNesting((bool,bool,address[]))
+	function setCollectionNesting(CollectionNestingAndPermission memory collectionNestingAndPermissions) external;
 
-	/// Toggle accessibility of collection nesting.
-	///
-	/// @param enable If "true" degenerates to nesting: {OwnerRestricted: [1, 2, 3]} else to nesting: 'Disabled'
-	/// @param collections Addresses of collections that will be available for nesting.
-	/// @dev EVM selector for this function is: 0x64872396,
-	///  or in textual repr: setCollectionNesting(bool,address[])
-	function setCollectionNesting(bool enable, address[] memory collections) external;
+	// /// Toggle accessibility of collection nesting.
+	// ///
+	// /// @param enable If "true" degenerates to nesting: 'Owner' else to nesting: 'Disabled'
+	// /// @dev EVM selector for this function is: 0x112d4586,
+	// ///  or in textual repr: setCollectionNesting(bool)
+	// function setCollectionNesting(bool enable) external;
+
+	// /// Toggle accessibility of collection nesting.
+	// ///
+	// /// @param enable If "true" degenerates to nesting: {OwnerRestricted: [1, 2, 3]} else to nesting: 'Disabled'
+	// /// @param collections Addresses of collections that will be available for nesting.
+	// /// @dev EVM selector for this function is: 0x64872396,
+	// ///  or in textual repr: setCollectionNesting(bool,address[])
+	// function setCollectionNesting(bool enable, address[] memory collections) external;
+
+	/// @dev EVM selector for this function is: 0x92c660a8,
+	///  or in textual repr: collectionNesting()
+	function collectionNesting() external view returns (CollectionNestingAndPermission memory);
 
-	/// Returns nesting for a collection
-	/// @dev EVM selector for this function is: 0x22d25bfe,
-	///  or in textual repr: collectionNestingRestrictedCollectionIds()
-	function collectionNestingRestrictedCollectionIds() external view returns (CollectionNesting memory);
+	// /// Returns nesting for a collection
+	// /// @dev EVM selector for this function is: 0x22d25bfe,
+	// ///  or in textual repr: collectionNestingRestrictedCollectionIds()
+	// function collectionNestingRestrictedCollectionIds() external view returns (CollectionNesting memory);
 
-	/// Returns permissions for a collection
-	/// @dev EVM selector for this function is: 0x5b2eaf4b,
-	///  or in textual repr: collectionNestingPermissions()
-	function collectionNestingPermissions() external view returns (CollectionNestingPermission[] memory);
+	// /// Returns permissions for a collection
+	// /// @dev EVM selector for this function is: 0x5b2eaf4b,
+	// ///  or in textual repr: collectionNestingPermissions()
+	// function collectionNestingPermissions() external view returns (CollectionNestingPermission[] memory);
 
 	/// Set the collection access method.
 	/// @param mode Access mode
@@ -311,6 +319,16 @@
 	uint256[] ids;
 }
 
+/// Nested collections and permissions
+struct CollectionNestingAndPermission {
+	/// Owner of token can nest tokens under it.
+	bool token_owner;
+	/// Admin of token collection can nest tokens under token.
+	bool collection_admin;
+	/// If set - only tokens from specified collections can be nested.
+	address[] restricted;
+}
+
 /// [`CollectionLimits`](up_data_structs::CollectionLimits) field representation for EVM.
 struct CollectionLimit {
 	CollectionLimitField field;
modifiedtests/src/eth/api/UniqueNFT.soldiffbeforeafterboth
--- a/tests/src/eth/api/UniqueNFT.sol
+++ b/tests/src/eth/api/UniqueNFT.sol
@@ -118,7 +118,7 @@
 }
 
 /// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0x2a14cfd1
+/// @dev the ERC-165 identifier for this interface is 0xb34d97e9
 interface Collection is Dummy, ERC165 {
 	// /// Set collection property.
 	// ///
@@ -253,30 +253,38 @@
 	// ///  or in textual repr: removeCollectionAdmin(address)
 	// function removeCollectionAdmin(address admin) external;
 
-	/// Toggle accessibility of collection nesting.
-	///
-	/// @param enable If "true" degenerates to nesting: 'Owner' else to nesting: 'Disabled'
-	/// @dev EVM selector for this function is: 0x112d4586,
-	///  or in textual repr: setCollectionNesting(bool)
-	function setCollectionNesting(bool enable) external;
+	/// @dev EVM selector for this function is: 0x0b9f3890,
+	///  or in textual repr: setCollectionNesting((bool,bool,address[]))
+	function setCollectionNesting(CollectionNestingAndPermission memory collectionNestingAndPermissions) external;
 
-	/// Toggle accessibility of collection nesting.
-	///
-	/// @param enable If "true" degenerates to nesting: {OwnerRestricted: [1, 2, 3]} else to nesting: 'Disabled'
-	/// @param collections Addresses of collections that will be available for nesting.
-	/// @dev EVM selector for this function is: 0x64872396,
-	///  or in textual repr: setCollectionNesting(bool,address[])
-	function setCollectionNesting(bool enable, address[] memory collections) external;
+	// /// Toggle accessibility of collection nesting.
+	// ///
+	// /// @param enable If "true" degenerates to nesting: 'Owner' else to nesting: 'Disabled'
+	// /// @dev EVM selector for this function is: 0x112d4586,
+	// ///  or in textual repr: setCollectionNesting(bool)
+	// function setCollectionNesting(bool enable) external;
+
+	// /// Toggle accessibility of collection nesting.
+	// ///
+	// /// @param enable If "true" degenerates to nesting: {OwnerRestricted: [1, 2, 3]} else to nesting: 'Disabled'
+	// /// @param collections Addresses of collections that will be available for nesting.
+	// /// @dev EVM selector for this function is: 0x64872396,
+	// ///  or in textual repr: setCollectionNesting(bool,address[])
+	// function setCollectionNesting(bool enable, address[] memory collections) external;
+
+	/// @dev EVM selector for this function is: 0x92c660a8,
+	///  or in textual repr: collectionNesting()
+	function collectionNesting() external view returns (CollectionNestingAndPermission memory);
 
-	/// Returns nesting for a collection
-	/// @dev EVM selector for this function is: 0x22d25bfe,
-	///  or in textual repr: collectionNestingRestrictedCollectionIds()
-	function collectionNestingRestrictedCollectionIds() external view returns (CollectionNesting memory);
+	// /// Returns nesting for a collection
+	// /// @dev EVM selector for this function is: 0x22d25bfe,
+	// ///  or in textual repr: collectionNestingRestrictedCollectionIds()
+	// function collectionNestingRestrictedCollectionIds() external view returns (CollectionNesting memory);
 
-	/// Returns permissions for a collection
-	/// @dev EVM selector for this function is: 0x5b2eaf4b,
-	///  or in textual repr: collectionNestingPermissions()
-	function collectionNestingPermissions() external view returns (CollectionNestingPermission[] memory);
+	// /// Returns permissions for a collection
+	// /// @dev EVM selector for this function is: 0x5b2eaf4b,
+	// ///  or in textual repr: collectionNestingPermissions()
+	// function collectionNestingPermissions() external view returns (CollectionNestingPermission[] memory);
 
 	/// Set the collection access method.
 	/// @param mode Access mode
@@ -416,6 +424,16 @@
 	uint256[] ids;
 }
 
+/// Nested collections and permissions
+struct CollectionNestingAndPermission {
+	/// Owner of token can nest tokens under it.
+	bool token_owner;
+	/// Admin of token collection can nest tokens under token.
+	bool collection_admin;
+	/// If set - only tokens from specified collections can be nested.
+	address[] restricted;
+}
+
 /// [`CollectionLimits`](up_data_structs::CollectionLimits) field representation for EVM.
 struct CollectionLimit {
 	CollectionLimitField field;
modifiedtests/src/eth/api/UniqueRefungible.soldiffbeforeafterboth
--- a/tests/src/eth/api/UniqueRefungible.sol
+++ b/tests/src/eth/api/UniqueRefungible.sol
@@ -118,7 +118,7 @@
 }
 
 /// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0x2a14cfd1
+/// @dev the ERC-165 identifier for this interface is 0xb34d97e9
 interface Collection is Dummy, ERC165 {
 	// /// Set collection property.
 	// ///
@@ -253,30 +253,38 @@
 	// ///  or in textual repr: removeCollectionAdmin(address)
 	// function removeCollectionAdmin(address admin) external;
 
-	/// Toggle accessibility of collection nesting.
-	///
-	/// @param enable If "true" degenerates to nesting: 'Owner' else to nesting: 'Disabled'
-	/// @dev EVM selector for this function is: 0x112d4586,
-	///  or in textual repr: setCollectionNesting(bool)
-	function setCollectionNesting(bool enable) external;
+	/// @dev EVM selector for this function is: 0x0b9f3890,
+	///  or in textual repr: setCollectionNesting((bool,bool,address[]))
+	function setCollectionNesting(CollectionNestingAndPermission memory collectionNestingAndPermissions) external;
 
-	/// Toggle accessibility of collection nesting.
-	///
-	/// @param enable If "true" degenerates to nesting: {OwnerRestricted: [1, 2, 3]} else to nesting: 'Disabled'
-	/// @param collections Addresses of collections that will be available for nesting.
-	/// @dev EVM selector for this function is: 0x64872396,
-	///  or in textual repr: setCollectionNesting(bool,address[])
-	function setCollectionNesting(bool enable, address[] memory collections) external;
+	// /// Toggle accessibility of collection nesting.
+	// ///
+	// /// @param enable If "true" degenerates to nesting: 'Owner' else to nesting: 'Disabled'
+	// /// @dev EVM selector for this function is: 0x112d4586,
+	// ///  or in textual repr: setCollectionNesting(bool)
+	// function setCollectionNesting(bool enable) external;
+
+	// /// Toggle accessibility of collection nesting.
+	// ///
+	// /// @param enable If "true" degenerates to nesting: {OwnerRestricted: [1, 2, 3]} else to nesting: 'Disabled'
+	// /// @param collections Addresses of collections that will be available for nesting.
+	// /// @dev EVM selector for this function is: 0x64872396,
+	// ///  or in textual repr: setCollectionNesting(bool,address[])
+	// function setCollectionNesting(bool enable, address[] memory collections) external;
+
+	/// @dev EVM selector for this function is: 0x92c660a8,
+	///  or in textual repr: collectionNesting()
+	function collectionNesting() external view returns (CollectionNestingAndPermission memory);
 
-	/// Returns nesting for a collection
-	/// @dev EVM selector for this function is: 0x22d25bfe,
-	///  or in textual repr: collectionNestingRestrictedCollectionIds()
-	function collectionNestingRestrictedCollectionIds() external view returns (CollectionNesting memory);
+	// /// Returns nesting for a collection
+	// /// @dev EVM selector for this function is: 0x22d25bfe,
+	// ///  or in textual repr: collectionNestingRestrictedCollectionIds()
+	// function collectionNestingRestrictedCollectionIds() external view returns (CollectionNesting memory);
 
-	/// Returns permissions for a collection
-	/// @dev EVM selector for this function is: 0x5b2eaf4b,
-	///  or in textual repr: collectionNestingPermissions()
-	function collectionNestingPermissions() external view returns (CollectionNestingPermission[] memory);
+	// /// Returns permissions for a collection
+	// /// @dev EVM selector for this function is: 0x5b2eaf4b,
+	// ///  or in textual repr: collectionNestingPermissions()
+	// function collectionNestingPermissions() external view returns (CollectionNestingPermission[] memory);
 
 	/// Set the collection access method.
 	/// @param mode Access mode
@@ -416,6 +424,16 @@
 	uint256[] ids;
 }
 
+/// Nested collections and permissions
+struct CollectionNestingAndPermission {
+	/// Owner of token can nest tokens under it.
+	bool token_owner;
+	/// Admin of token collection can nest tokens under token.
+	bool collection_admin;
+	/// If set - only tokens from specified collections can be nested.
+	address[] restricted;
+}
+
 /// [`CollectionLimits`](up_data_structs::CollectionLimits) field representation for EVM.
 struct CollectionLimit {
 	CollectionLimitField field;
modifiedtests/src/eth/collectionAdmin.test.tsdiffbeforeafterboth
--- a/tests/src/eth/collectionAdmin.test.ts
+++ b/tests/src/eth/collectionAdmin.test.ts
@@ -19,6 +19,7 @@
 import {IEthCrossAccountId} from '../util/playgrounds/types';
 import {usingEthPlaygrounds, itEth} from './util';
 import {EthUniqueHelper} from './util/playgrounds/unique.dev';
+import {CreateCollectionData} from './util/playgrounds/types';
 
 async function recordEthFee(helper: EthUniqueHelper, userAddress: string, call: () => Promise<any>) {
   const before = await helper.balance.getSubstrate(helper.address.ethToSubstrate(userAddress));
@@ -55,7 +56,7 @@
       const adminCrossSub = helper.ethCrossAccount.fromKeyringPair(adminSub);
       const adminCrossEth = helper.ethCrossAccount.fromAddress(adminEth);
 
-      const {collectionAddress, collectionId} = await helper.eth.createCollection(testCase.mode, owner, 'A', 'B', 'C');
+      const {collectionAddress, collectionId} = await helper.eth.createCollection(owner, new CreateCollectionData('A', 'B', 'C', testCase.mode)).send();
       const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, owner, true);
 
       // Check isOwnerOrAdminCross returns false:
modifiedtests/src/eth/collectionLimits.test.tsdiffbeforeafterboth
--- a/tests/src/eth/collectionLimits.test.ts
+++ b/tests/src/eth/collectionLimits.test.ts
@@ -1,7 +1,7 @@
 import {IKeyringPair} from '@polkadot/types/types';
 import {Pallets} from '../util';
 import {expect, itEth, usingEthPlaygrounds} from './util';
-import {CollectionLimitField} from './util/playgrounds/types';
+import {CollectionLimitField, CreateCollectionData} from './util/playgrounds/types';
 
 
 describe('Can set collection limits', () => {
@@ -20,7 +20,7 @@
   ].map(testCase =>
     itEth.ifWithPallets(`for ${testCase.case}`, testCase.requiredPallets || [], async ({helper}) => {
       const owner = await helper.eth.createAccountWithBalance(donor);
-      const {collectionId, collectionAddress} = await helper.eth.createCollection(testCase.case, owner, 'Limits', 'absolutely anything', 'FLO', 18);
+      const {collectionId, collectionAddress} = await helper.eth.createCollection(owner, new CreateCollectionData('Limits', 'absolutely anything', 'FLO', testCase.case, 18)).send();
       const limits = {
         accountTokenOwnershipLimit: 1000,
         sponsoredDataSize: 1024,
@@ -96,13 +96,13 @@
       };
 
       const owner = await helper.eth.createAccountWithBalance(donor);
-      const {collectionAddress} = await helper.eth.createCollection(testCase.case, owner, 'Limits', 'absolutely anything', 'ISNI', 18);
+      const {collectionAddress} = await helper.eth.createCollection(owner, new CreateCollectionData('Limits', 'absolutely anything', 'ISNI', testCase.case, 18)).send();
       const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, testCase.case, owner);
 
       // Cannot set non-existing limit
       await expect(collectionEvm.methods
         .setCollectionLimit({field: 9, value: {status: true, value: 1}})
-        .call()).to.be.rejectedWith('Returned error: VM Exception while processing transaction: revert Value not convertible into enum "CollectionLimitField"');
+        .call()).to.be.rejectedWith('Returned error: VM Exception while processing transaction: revert value not convertible into enum "CollectionLimitField"');
 
       // Cannot disable limits
       await expect(collectionEvm.methods
@@ -129,7 +129,7 @@
     itEth.ifWithPallets(`Non-owner and non-admin cannot set collection limits for ${testCase.case}`, testCase.requiredPallets || [], async ({helper}) => {
       const owner = await helper.eth.createAccountWithBalance(donor);
       const nonOwner = await helper.eth.createAccountWithBalance(donor);
-      const {collectionAddress} = await helper.eth.createCollection(testCase.case, owner, 'Limits', 'absolutely anything', 'FLO', 18);
+      const {collectionAddress} = await helper.eth.createCollection(owner, new CreateCollectionData('Limits', 'absolutely anything', 'FLO', testCase.case, 18)).send();
 
       const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, testCase.case, owner);
       await expect(collectionEvm.methods
addedtests/src/eth/createCollection.test.tsdiffbeforeafterboth
--- /dev/null
+++ b/tests/src/eth/createCollection.test.ts
@@ -0,0 +1,1459 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+import {IKeyringPair} from '@polkadot/types/types';
+import {evmToAddress} from '@polkadot/util-crypto';
+import {Pallets, requirePalletsOrSkip} from '../util';
+import {expect, itEth, usingEthPlaygrounds} from './util';
+import {CREATE_COLLECTION_DATA_DEFAULTS, CollectionLimitField, CollectionMode, CreateCollectionData, TokenPermissionField, emptyAddress} from './util/playgrounds/types';
+import {CollectionFlag, IEthCrossAccountId, TCollectionMode} from '../util/playgrounds/types';
+
+const DECIMALS = 18;
+const CREATE_COLLECTION_DATA_DEFAULTS_ARRAY = [
+  [],
+  [],
+  [],
+  [false, false, []],
+  [],
+  [0],
+];
+
+type ElementOf<A> = A extends readonly (infer T)[] ? T : never;
+function* cartesian<T extends Array<Array<any>>, R extends Array<any>>(internalRest: [...R], ...args: [...T]): Generator<[...R, ...{[K in keyof T]: ElementOf<T[K]>}]> {
+  if(args.length === 0) {
+    yield internalRest as any;
+    return;
+  }
+  for(const value of args[0]) {
+    yield* cartesian([...internalRest, value], ...args.slice(1)) as any;
+  }
+}
+
+describe('Create collection from EVM', () => {
+  let donor: IKeyringPair;
+  let nominal: bigint;
+
+  before(async function() {
+    await usingEthPlaygrounds(async (helper, privateKey) => {
+      donor = await privateKey({url: import.meta.url});
+      nominal = helper.balance.getOneTokenNominal();
+    });
+  });
+
+  describe('Fungible collection', () => {
+    before(async function() {
+      await usingEthPlaygrounds((helper) => {
+        requirePalletsOrSkip(this, helper, [Pallets.Fungible]);
+        return Promise.resolve();
+      });
+    });
+
+    itEth('Collection address exist', async ({helper}) => {
+      const owner = await helper.eth.createAccountWithBalance(donor);
+      const collectionAddressForNonexistentCollection = '0x17C4E6453CC49AAAAEACA894E6D9683E00112233';
+      const collectionHelpers = await helper.ethNativeContract.collectionHelpers(owner);
+
+      expect(await collectionHelpers
+        .methods.isCollectionExist(collectionAddressForNonexistentCollection).call())
+        .to.be.false;
+
+      const {collectionAddress} = await helper.eth.createCollection(owner, new CreateCollectionData('Exister', 'absolutely anything', 'WIWT', 'ft', DECIMALS)).send();
+      expect(await collectionHelpers
+        .methods.isCollectionExist(collectionAddress).call())
+        .to.be.true;
+
+      // check collectionOwner:
+      const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner, true);
+      const collectionOwner = await collectionEvm.methods.collectionOwner().call();
+      expect(helper.address.restoreCrossAccountFromBigInt(BigInt(collectionOwner.sub))).to.eq(helper.address.ethToSubstrate(owner, true));
+    });
+
+    itEth('destroyCollection', async ({helper}) => {
+      const owner = await helper.eth.createAccountWithBalance(donor);
+      const {collectionAddress, collectionId} = await helper.eth.createCollection(owner, new CreateCollectionData('Exister', 'absolutely anything', 'WIWT', 'ft', DECIMALS)).send();
+      const collectionHelper = await helper.ethNativeContract.collectionHelpers(owner);
+
+      const result = await collectionHelper.methods
+        .destroyCollection(collectionAddress)
+        .send({from: owner});
+
+      const events = helper.eth.normalizeEvents(result.events);
+
+      expect(events).to.be.deep.equal([
+        {
+          address: collectionHelper.options.address,
+          event: 'CollectionDestroyed',
+          args: {
+            collectionId: collectionAddress,
+          },
+        },
+      ]);
+
+      expect(await collectionHelper.methods
+        .isCollectionExist(collectionAddress)
+        .call()).to.be.false;
+      expect(await helper.collection.getData(collectionId)).to.be.null;
+    });
+
+    itEth('(!negative test!) Create collection (bad lengths)', async ({helper}) => {
+      const owner = await helper.eth.createAccountWithBalance(donor);
+      const collectionHelper = await helper.ethNativeContract.collectionHelpers(owner);
+      {
+        const MAX_NAME_LENGTH = 64;
+        const collectionName = 'A'.repeat(MAX_NAME_LENGTH + 1);
+        const description = 'A';
+        const tokenPrefix = 'A';
+
+        await expect(collectionHelper.methods
+          .createCollection([
+            emptyAddress,
+            collectionName,
+            description,
+            tokenPrefix,
+            CollectionMode.Fungible,
+            DECIMALS,
+            ...CREATE_COLLECTION_DATA_DEFAULTS_ARRAY,
+          ])
+          .call({value: Number(2n * nominal)})).to.be.rejectedWith('name is too long. Max length is ' + MAX_NAME_LENGTH);
+      }
+      {
+        const MAX_DESCRIPTION_LENGTH = 256;
+        const collectionName = 'A';
+        const description = 'A'.repeat(MAX_DESCRIPTION_LENGTH + 1);
+        const tokenPrefix = 'A';
+        await expect(collectionHelper.methods
+          .createCollection([
+            emptyAddress,
+            collectionName,
+            description,
+            tokenPrefix,
+            CollectionMode.Fungible,
+            DECIMALS,
+            ...CREATE_COLLECTION_DATA_DEFAULTS_ARRAY,
+          ])
+          .call({value: Number(2n * nominal)})).to.be.rejectedWith('description is too long. Max length is ' + MAX_DESCRIPTION_LENGTH);
+      }
+      {
+        const MAX_TOKEN_PREFIX_LENGTH = 16;
+        const collectionName = 'A';
+        const description = 'A';
+        const tokenPrefix = 'A'.repeat(MAX_TOKEN_PREFIX_LENGTH + 1);
+        await expect(collectionHelper.methods
+          .createCollection([
+            emptyAddress,
+            collectionName,
+            description,
+            tokenPrefix,
+            CollectionMode.Fungible,
+            DECIMALS,
+            ...CREATE_COLLECTION_DATA_DEFAULTS_ARRAY,
+          ])
+          .call({value: Number(2n * nominal)})).to.be.rejectedWith('token_prefix is too long. Max length is ' + MAX_TOKEN_PREFIX_LENGTH);
+      }
+    });
+
+    itEth('(!negative test!) cannot create collection if value !== 2', async ({helper}) => {
+      const owner = await helper.eth.createAccountWithBalance(donor);
+      const collectionHelper = await helper.ethNativeContract.collectionHelpers(owner);
+      const expects = [0n, 1n, 30n].map(async value => {
+        await expect(collectionHelper.methods
+          .createCollection([
+            emptyAddress,
+            'Peasantry',
+            'absolutely anything',
+            'TWIW',
+            CollectionMode.Fungible,
+            DECIMALS,
+            ...CREATE_COLLECTION_DATA_DEFAULTS_ARRAY,
+          ])
+          .call({value: Number(value * nominal)})).to.be.rejectedWith('Sent amount not equals to collection creation price (2000000000000000000)');
+      });
+      await Promise.all(expects);
+    });
+  });
+
+  describe('Nonfungible collection', () => {
+    before(async function() {
+      await usingEthPlaygrounds((helper) => {
+        requirePalletsOrSkip(this, helper, [Pallets.NFT]);
+        return Promise.resolve();
+      });
+    });
+
+    itEth('Create collection', async ({helper}) => {
+      const owner = await helper.eth.createAccountWithBalance(donor);
+
+      const name = 'CollectionEVM';
+      const description = 'Some description';
+      const prefix = 'token prefix';
+
+      // todo:playgrounds this might fail when in async environment.
+      const collectionCountBefore = +(await helper.callRpc('api.rpc.unique.collectionStats')).created;
+      const {collectionId, collectionAddress, events} = await helper.eth.createCollection(owner, new CreateCollectionData(name, description, prefix, 'nft')).send();
+
+      expect(events).to.be.deep.equal([
+        {
+          address: '0x6C4E9fE1AE37a41E93CEE429e8E1881aBdcbb54F',
+          event: 'CollectionCreated',
+          args: {
+            owner: owner,
+            collectionId: collectionAddress,
+          },
+        },
+      ]);
+
+      const collectionCountAfter = +(await helper.callRpc('api.rpc.unique.collectionStats')).created;
+
+      const collection = helper.nft.getCollectionObject(collectionId);
+      const data = (await collection.getData())!;
+
+      expect(collectionCountAfter - collectionCountBefore).to.be.eq(1);
+      expect(collectionId).to.be.eq(collectionCountAfter);
+      expect(data.name).to.be.eq(name);
+      expect(data.description).to.be.eq(description);
+      expect(data.raw.tokenPrefix).to.be.eq(prefix);
+      expect(data.raw.mode).to.be.eq('NFT');
+
+      const options = await collection.getOptions();
+
+      expect(options.tokenPropertyPermissions).to.be.empty;
+    });
+
+    // this test will occasionally fail when in async environment.
+    itEth('Check collection address exist', async ({helper}) => {
+      const owner = await helper.eth.createAccountWithBalance(donor);
+
+      const expectedCollectionId = +(await helper.callRpc('api.rpc.unique.collectionStats')).created + 1;
+      const expectedCollectionAddress = helper.ethAddress.fromCollectionId(expectedCollectionId);
+      const collectionHelpers = await helper.ethNativeContract.collectionHelpers(owner);
+
+      expect(await collectionHelpers.methods
+        .isCollectionExist(expectedCollectionAddress)
+        .call()).to.be.false;
+
+      await collectionHelpers.methods
+        .createCollection([
+          emptyAddress,
+          'A',
+          'A',
+          'A',
+          CollectionMode.Nonfungible,
+          0,
+          ...CREATE_COLLECTION_DATA_DEFAULTS_ARRAY,
+        ])
+        .send({value: Number(2n * helper.balance.getOneTokenNominal())});
+
+      expect(await collectionHelpers.methods
+        .isCollectionExist(expectedCollectionAddress)
+        .call()).to.be.true;
+    });
+  });
+
+  describe('Create RFT collection from EVM', () => {
+    before(async function() {
+      await usingEthPlaygrounds((helper) => {
+        requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);
+        return Promise.resolve();
+      });
+    });
+
+    itEth('Create collection', async ({helper}) => {
+      const owner = await helper.eth.createAccountWithBalance(donor);
+
+      const name = 'CollectionEVM';
+      const description = 'Some description';
+      const prefix = 'token prefix';
+
+      const {collectionId} = await helper.eth.createCollection(owner, new CreateCollectionData(name, description, prefix, 'rft')).send();
+      const data = (await helper.rft.getData(collectionId))!;
+      const collection = helper.rft.getCollectionObject(collectionId);
+
+      expect(data.name).to.be.eq(name);
+      expect(data.description).to.be.eq(description);
+      expect(data.raw.tokenPrefix).to.be.eq(prefix);
+      expect(data.raw.mode).to.be.eq('ReFungible');
+
+      const options = await collection.getOptions();
+
+      expect(options.tokenPropertyPermissions).to.be.empty;
+    });
+
+    itEth('Create collection with properties & get description', async ({helper}) => {
+      const owner = await helper.eth.createAccountWithBalance(donor);
+
+      const name = 'CollectionEVM';
+      const description = 'Some description';
+      const prefix = 'token prefix';
+      const baseUri = 'BaseURI';
+
+      const {collectionId, collectionAddress} = await helper.eth.createERC721MetadataCompatibleRFTCollection(owner, name, description, prefix, baseUri);
+      const contract = helper.ethNativeContract.collection(collectionAddress, 'nft');
+
+      const collection = helper.rft.getCollectionObject(collectionId);
+      const data = (await collection.getData())!;
+
+      expect(data.name).to.be.eq(name);
+      expect(data.description).to.be.eq(description);
+      expect(data.raw.tokenPrefix).to.be.eq(prefix);
+      expect(data.raw.mode).to.be.eq('ReFungible');
+
+      expect(await contract.methods.description().call()).to.deep.equal(description);
+
+      const options = await collection.getOptions();
+      expect(options.tokenPropertyPermissions).to.be.deep.equal([
+        {
+          key: 'URI',
+          permission: {mutable: true, collectionAdmin: true, tokenOwner: false},
+        },
+        {
+          key: 'URISuffix',
+          permission: {mutable: true, collectionAdmin: true, tokenOwner: false},
+        },
+      ]);
+    });
+
+    itEth('Set sponsorship', async ({helper}) => {
+      const owner = await helper.eth.createAccountWithBalance(donor);
+      const sponsor = await helper.eth.createAccountWithBalance(donor);
+      const ss58Format = helper.chain.getChainProperties().ss58Format;
+      const {collectionId, collectionAddress} = await helper.eth.createCollection(owner, new CreateCollectionData('Sponsor', 'absolutely anything', 'ENVY', 'rft')).send();
+
+      const collection = await helper.ethNativeContract.collection(collectionAddress, 'rft', owner);
+      const sponsorCross = helper.ethCrossAccount.fromAddress(sponsor);
+      await collection.methods.setCollectionSponsorCross(sponsorCross).send();
+
+      let data = (await helper.rft.getData(collectionId))!;
+      expect(data.raw.sponsorship.Unconfirmed).to.be.equal(evmToAddress(sponsor, Number(ss58Format)));
+
+      await expect(collection.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('ConfirmSponsorshipFail');
+
+      const sponsorCollection = await helper.ethNativeContract.collection(collectionAddress, 'rft', sponsor);
+      await sponsorCollection.methods.confirmCollectionSponsorship().send();
+
+      data = (await helper.rft.getData(collectionId))!;
+      expect(data.raw.sponsorship.Confirmed).to.be.equal(evmToAddress(sponsor, Number(ss58Format)));
+    });
+
+    itEth('Collection address exist', async ({helper}) => {
+      const owner = await helper.eth.createAccountWithBalance(donor);
+      const collectionAddressForNonexistentCollection = '0x17C4E6453CC49AAAAEACA894E6D9683E00112233';
+      const collectionHelpers = await helper.ethNativeContract.collectionHelpers(owner);
+
+      expect(await collectionHelpers
+        .methods.isCollectionExist(collectionAddressForNonexistentCollection).call())
+        .to.be.false;
+
+      const {collectionAddress} = await helper.eth.createCollection(owner, new CreateCollectionData('Exister', 'absolutely anything', 'WIWT', 'rft')).send();
+      expect(await collectionHelpers
+        .methods.isCollectionExist(collectionAddress).call())
+        .to.be.true;
+
+      // check collectionOwner:
+      const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner, true);
+      const collectionOwner = await collectionEvm.methods.collectionOwner().call();
+      expect(helper.address.restoreCrossAccountFromBigInt(BigInt(collectionOwner.sub))).to.eq(helper.address.ethToSubstrate(owner, true));
+    });
+
+    itEth('destroyCollection', async ({helper}) => {
+      const owner = await helper.eth.createAccountWithBalance(donor);
+      const {collectionAddress, collectionId} = await helper.eth.createCollection(owner, new CreateCollectionData('Limits', 'absolutely anything', 'OLF', 'rft')).send();
+      const collectionHelper = await helper.ethNativeContract.collectionHelpers(owner);
+
+      await expect(collectionHelper.methods
+        .destroyCollection(collectionAddress)
+        .send({from: owner})).to.be.fulfilled;
+
+      expect(await collectionHelper.methods
+        .isCollectionExist(collectionAddress)
+        .call()).to.be.false;
+      expect(await helper.collection.getData(collectionId)).to.be.null;
+    });
+
+    itEth('(!negative test!) Create collection (bad lengths)', async ({helper}) => {
+      const owner = await helper.eth.createAccountWithBalance(donor);
+      const collectionHelper = await helper.ethNativeContract.collectionHelpers(owner);
+      {
+        const MAX_NAME_LENGTH = 64;
+        const collectionName = 'A'.repeat(MAX_NAME_LENGTH + 1);
+        const description = 'A';
+        const tokenPrefix = 'A';
+
+        await expect(collectionHelper.methods
+          .createCollection([
+            emptyAddress,
+            collectionName,
+            description,
+            tokenPrefix,
+            CollectionMode.Refungible,
+            DECIMALS,
+            ...CREATE_COLLECTION_DATA_DEFAULTS_ARRAY,
+          ])
+          .call({value: Number(2n * nominal)})).to.be.rejectedWith('name is too long. Max length is ' + MAX_NAME_LENGTH);
+      }
+      {
+        const MAX_DESCRIPTION_LENGTH = 256;
+        const collectionName = 'A';
+        const description = 'A'.repeat(MAX_DESCRIPTION_LENGTH + 1);
+        const tokenPrefix = 'A';
+        await expect(collectionHelper.methods
+          .createCollection([
+            emptyAddress,
+            collectionName,
+            description,
+            tokenPrefix,
+            CollectionMode.Refungible,
+            DECIMALS,
+            ...CREATE_COLLECTION_DATA_DEFAULTS_ARRAY,
+          ])
+          .call({value: Number(2n * nominal)})).to.be.rejectedWith('description is too long. Max length is ' + MAX_DESCRIPTION_LENGTH);
+      }
+      {
+        const MAX_TOKEN_PREFIX_LENGTH = 16;
+        const collectionName = 'A';
+        const description = 'A';
+        const tokenPrefix = 'A'.repeat(MAX_TOKEN_PREFIX_LENGTH + 1);
+        await expect(collectionHelper.methods
+          .createCollection([
+            emptyAddress,
+            collectionName,
+            description,
+            tokenPrefix,
+            CollectionMode.Refungible,
+            DECIMALS,
+            ...CREATE_COLLECTION_DATA_DEFAULTS_ARRAY,
+          ])
+          .call({value: Number(2n * nominal)})).to.be.rejectedWith('token_prefix is too long. Max length is ' + MAX_TOKEN_PREFIX_LENGTH);
+      }
+    });
+
+    itEth('(!negative test!) Create collection (no funds)', async ({helper}) => {
+      const owner = await helper.eth.createAccountWithBalance(donor);
+      const collectionHelper = await helper.ethNativeContract.collectionHelpers(owner);
+      await expect(collectionHelper.methods
+        .createCollection([
+          emptyAddress,
+          'Peasantry',
+          'absolutely anything',
+          'TWIW',
+          CollectionMode.Refungible,
+          0,
+          ...CREATE_COLLECTION_DATA_DEFAULTS_ARRAY,
+        ])
+        .call({value: Number(1n * nominal)})).to.be.rejectedWith('Sent amount not equals to collection creation price (2000000000000000000)');
+    });
+  });
+
+  describe('Sponsoring', () => {
+    itEth('Сan remove collection sponsor', async ({helper}) => {
+      const owner = await helper.eth.createAccountWithBalance(donor);
+      const sponsor = await helper.eth.createAccountWithBalance(donor);
+      const sponsorCross = helper.ethCrossAccount.fromAddr(sponsor);
+
+      const {collectionAddress} = await helper.eth.createCollection(
+        owner,
+        {
+          ...CREATE_COLLECTION_DATA_DEFAULTS,
+          name: 'Sponsor collection',
+          description: '1',
+          tokenPrefix: '1',
+          collectionMode: 'nft',
+          pendingSponsor: sponsorCross,
+        },
+      ).send();
+      const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
+
+      expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.true;
+
+      await collectionEvm.methods.confirmCollectionSponsorship().send({from: sponsor});
+      let sponsorStruct = await collectionEvm.methods.collectionSponsor().call({from: owner});
+      expect(helper.address.restoreCrossAccountFromBigInt(BigInt(sponsorStruct.sub))).to.be.eq(helper.address.ethToSubstrate(sponsor, true));
+      expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.false;
+
+      await collectionEvm.methods.removeCollectionSponsor().send({from: owner});
+
+      sponsorStruct = await collectionEvm.methods.collectionSponsor().call({from: owner});
+      expect(sponsorStruct.eth).to.be.eq('0x0000000000000000000000000000000000000000');
+    });
+
+    itEth('Can sponsor from evm address via access list', async ({helper}) => {
+      const owner = await helper.eth.createAccountWithBalance(donor);
+      const sponsorEth = await helper.eth.createAccountWithBalance(donor);
+      const sponsorCross = helper.ethCrossAccount.fromAddr(sponsorEth);
+
+      const {collectionId, collectionAddress} = await helper.eth.createERC721MetadataCompatibleCollection(
+        owner,
+        {
+          ...CREATE_COLLECTION_DATA_DEFAULTS,
+          name: 'Sponsor collection',
+          description: '1',
+          tokenPrefix: '1',
+          collectionMode: 'nft',
+          pendingSponsor: sponsorCross,
+          limits: [{field: CollectionLimitField.SponsoredDataRateLimit, value: 30n}],
+          tokenPropertyPermissions: [{key: 'key', permissions: [{code: TokenPermissionField.TokenOwner, value: true}]}],
+        },
+        '',
+      );
+
+      const collectionSub = helper.nft.getCollectionObject(collectionId);
+      const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
+
+      let sponsorship = (await collectionSub.getData())!.raw.sponsorship;
+      expect(sponsorship.Unconfirmed).to.be.eq(helper.address.ethToSubstrate(sponsorEth, true));
+      // Account cannot confirm sponsorship if it is not set as a sponsor
+      await expect(collectionEvm.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('ConfirmSponsorshipFail');
+
+      // Sponsor can confirm sponsorship:
+      await collectionEvm.methods.confirmCollectionSponsorship().send({from: sponsorEth});
+      sponsorship = (await collectionSub.getData())!.raw.sponsorship;
+      expect(sponsorship.Confirmed).to.be.eq(helper.address.ethToSubstrate(sponsorEth, true));
+
+      // Create user with no balance:
+      const user = helper.ethCrossAccount.createAccount();
+      const nextTokenId = await collectionEvm.methods.nextTokenId().call();
+      expect(nextTokenId).to.be.equal('1');
+
+      // Set collection permissions:
+      const oldPermissions = (await collectionSub.getData())!.raw.permissions;
+      expect(oldPermissions.mintMode).to.be.false;
+      expect(oldPermissions.access).to.be.equal('Normal');
+
+      await collectionEvm.methods.setCollectionAccess(1 /*'AllowList'*/).send({from: owner});
+      await collectionEvm.methods.addToCollectionAllowListCross(user).send({from: owner});
+      await collectionEvm.methods.setCollectionMintMode(true).send({from: owner});
+
+      const newPermissions = (await collectionSub.getData())!.raw.permissions;
+      expect(newPermissions.mintMode).to.be.true;
+      expect(newPermissions.access).to.be.equal('AllowList');
+
+      const ownerBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));
+      const sponsorBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsorEth));
+      const userBalanceBefore =  await helper.balance.getSubstrate(helper.address.ethToSubstrate(user.eth));
+
+      // User can mint token without balance:
+      {
+        const result = await collectionEvm.methods.mintCross(user, [{key: 'key', value: Buffer.from('Value')}]).send({from: user.eth});
+        const event = helper.eth.normalizeEvents(result.events)
+          .find(event => event.event === 'Transfer');
+
+        expect(event).to.be.deep.equal({
+          address: collectionAddress,
+          event: 'Transfer',
+          args: {
+            from: '0x0000000000000000000000000000000000000000',
+            to: user.eth,
+            tokenId: '1',
+          },
+        });
+
+        // await collectionEvm.methods.setProperties(1, [{key: 'key', value: Buffer.from('Value1')}]).send({from: user.eth});
+
+        const ownerBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));
+        const sponsorBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsorEth));
+        const userBalanceAfter =  await helper.balance.getSubstrate(helper.address.ethToSubstrate(user.eth));
+
+        expect(await collectionEvm.methods.properties(nextTokenId, []).call())
+          .to.be.like([
+            [
+              'key',
+              '0x' + Buffer.from('Value').toString('hex'),
+            ],
+          ]);
+        expect(ownerBalanceBefore).to.be.eq(ownerBalanceAfter);
+        expect(userBalanceAfter).to.be.eq(userBalanceBefore);
+        expect(sponsorBalanceBefore > sponsorBalanceAfter).to.be.true;
+      }
+    });
+
+    itEth('Check that transaction via EVM spend money from sponsor address', async ({helper}) => {
+      const owner = await helper.eth.createAccountWithBalance(donor);
+      const sponsor = await helper.eth.createAccountWithBalance(donor);
+      const sponsorCross = helper.ethCrossAccount.fromAddr(sponsor);
+      const user = helper.eth.createAccount();
+      const userCross = helper.ethCrossAccount.fromAddress(user);
+
+      const {collectionAddress, collectionId} = await helper.eth.createERC721MetadataCompatibleCollection(
+        owner,
+        {
+          ...CREATE_COLLECTION_DATA_DEFAULTS,
+          name: 'Sponsor collection',
+          description: '1',
+          tokenPrefix: '1',
+          collectionMode: 'nft',
+          pendingSponsor: sponsorCross,
+          adminList: [userCross],
+        },
+        '',
+      );
+
+      const collectionSub = helper.nft.getCollectionObject(collectionId);
+      const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
+      // Set collection sponsor:
+      let collectionData = (await collectionSub.getData())!;
+      expect(collectionData.raw.sponsorship.Unconfirmed).to.be.eq(helper.address.ethToSubstrate(sponsor, true));
+      await expect(collectionEvm.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('ConfirmSponsorshipFail');
+
+      await collectionEvm.methods.confirmCollectionSponsorship().send({from: sponsor});
+      collectionData = (await collectionSub.getData())!;
+      expect(collectionData.raw.sponsorship.Confirmed).to.be.eq(helper.address.ethToSubstrate(sponsor, true));
+
+      const ownerBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));
+      const sponsorBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsor));
+
+      const mintingResult = await collectionEvm.methods.mintWithTokenURI(user, 'Test URI').send({from: user});
+      const tokenId = mintingResult.events.Transfer.returnValues.tokenId;
+
+      const event = helper.eth.normalizeEvents(mintingResult.events)
+        .find(event => event.event === 'Transfer');
+      const address = helper.ethAddress.fromCollectionId(collectionId);
+
+      expect(event).to.be.deep.equal({
+        address,
+        event: 'Transfer',
+        args: {
+          from: '0x0000000000000000000000000000000000000000',
+          to: user,
+          tokenId: '1',
+        },
+      });
+      expect(await collectionEvm.methods.tokenURI(tokenId).call({from: user})).to.be.equal('Test URI');
+
+      const ownerBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));
+      expect(ownerBalanceAfter).to.be.eq(ownerBalanceBefore);
+      const sponsorBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsor));
+      expect(sponsorBalanceAfter < sponsorBalanceBefore).to.be.true;
+    });
+
+    itEth('Can reassign collection sponsor', async ({helper}) => {
+      const owner = await helper.eth.createAccountWithBalance(donor);
+      const sponsorEth = await helper.eth.createAccountWithBalance(donor);
+      const sponsorCrossEth = helper.ethCrossAccount.fromAddr(sponsorEth);
+      const [sponsorSub] = await helper.arrange.createAccounts([100n], donor);
+      const sponsorCrossSub = helper.ethCrossAccount.fromKeyringPair(sponsorSub);
+
+      const {collectionAddress, collectionId} = await helper.eth.createERC721MetadataCompatibleCollection(
+        owner,
+        {
+          ...CREATE_COLLECTION_DATA_DEFAULTS,
+          name: 'Sponsor collection',
+          description: '1',
+          tokenPrefix: '1',
+          collectionMode: 'nft',
+          pendingSponsor: sponsorCrossEth,
+        },
+        '',
+      );
+      const collectionSub = helper.nft.getCollectionObject(collectionId);
+      const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
+
+      // Set and confirm sponsor:
+      await collectionEvm.methods.confirmCollectionSponsorship().send({from: sponsorEth});
+
+      // Can reassign sponsor:
+      await collectionEvm.methods.setCollectionSponsorCross(sponsorCrossSub).send({from: owner});
+      const collectionSponsor = (await collectionSub.getData())?.raw.sponsorship;
+      expect(collectionSponsor).to.deep.eq({Unconfirmed: sponsorSub.address});
+    });
+
+    [
+      'transfer',
+      'transferCross',
+      'transferFrom',
+      'transferFromCross',
+    ].map(testCase =>
+      itEth(`[${testCase}] Check that transfer via EVM spend money from sponsor address`, async ({helper}) => {
+        const owner = await helper.eth.createAccountWithBalance(donor);
+        const sponsor = await helper.eth.createAccountWithBalance(donor);
+        const sponsorCross = helper.ethCrossAccount.fromAddr(sponsor);
+        const user = await helper.eth.createAccountWithBalance(donor);
+        const userCross = helper.ethCrossAccount.fromAddress(user);
+
+        const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleCollection(
+          owner,
+          {
+            ...CREATE_COLLECTION_DATA_DEFAULTS,
+            name: 'Sponsor collection',
+            description: '1',
+            tokenPrefix: '1',
+            collectionMode: 'rft',
+            pendingSponsor: sponsorCross,
+            adminList: [userCross],
+          },
+          '',
+        );
+        const receiver = await helper.eth.createAccountWithBalance(donor);
+        const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'rft', owner);
+
+        await collectionEvm.methods.confirmCollectionSponsorship().send({from: sponsor});
+
+        const result = await collectionEvm.methods.mintWithTokenURI(user, 'Test URI').send({from: user});
+        const tokenId = result.events.Transfer.returnValues.tokenId;
+
+        const ownerBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));
+        const sponsorBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsor));
+        const userBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(user));
+
+        switch (testCase) {
+          case 'transfer':
+            await collectionEvm.methods.transfer(receiver, tokenId).send({from: user});
+            break;
+          case 'transferCross':
+            await collectionEvm.methods.transferCross(helper.ethCrossAccount.fromAddress(receiver), tokenId).send({from: user});
+            break;
+          case 'transferFrom':
+            await collectionEvm.methods.transferFrom(user, receiver, tokenId).send({from: user});
+            break;
+          case 'transferFromCross':
+            await collectionEvm.methods.transferFromCross(helper.ethCrossAccount.fromAddress(user), helper.ethCrossAccount.fromAddress(receiver), tokenId).send({from: user});
+            break;
+        }
+
+        const ownerBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));
+        expect(ownerBalanceAfter).to.be.eq(ownerBalanceBefore);
+        const sponsorBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsor));
+        expect(sponsorBalanceAfter < sponsorBalanceBefore).to.be.true;
+        const userBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(user));
+        expect(userBalanceAfter).to.be.eq(userBalanceBefore);
+      }));
+  });
+
+  describe('Collection admins', () => {
+    let donor: IKeyringPair;
+
+    before(async function() {
+      await usingEthPlaygrounds(async (_helper, privateKey) => {
+        donor = await privateKey({url: import.meta.url});
+      });
+    });
+
+    [
+      {mode: 'nft' as const, requiredPallets: []},
+      {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
+      {mode: 'ft' as const, requiredPallets: []},
+    ].map(testCase => {
+      itEth.ifWithPallets(`can add account admin by owner for ${testCase.mode}`, testCase.requiredPallets, async ({helper, privateKey}) => {
+        // arrange
+        const owner = await helper.eth.createAccountWithBalance(donor);
+        const adminSub = await privateKey('//admin2');
+        const adminEth = helper.eth.createAccount().toLowerCase();
+
+        const adminCrossSub = helper.ethCrossAccount.fromKeyringPair(adminSub);
+        const adminCrossEth = helper.ethCrossAccount.fromAddress(adminEth);
+
+        const {collectionAddress, collectionId} = await helper.eth.createCollection(
+          owner,
+          {
+            ...CREATE_COLLECTION_DATA_DEFAULTS,
+            name: 'Mint collection',
+            description: 'a',
+            tokenPrefix: 'b',
+            collectionMode: testCase.mode,
+            adminList: [adminCrossSub, adminCrossEth],
+          },
+        ).send();
+        const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, owner, true);
+
+        // 1. Expect api.rpc.unique.adminlist returns admins:
+        const adminListRpc = await helper.collection.getAdmins(collectionId);
+        expect(adminListRpc).to.has.length(2);
+        expect(adminListRpc).to.be.deep.contain.members([{Substrate: adminSub.address}, {Ethereum: adminEth}]);
+
+        // 2. Expect methods.collectionAdmins == api.rpc.unique.adminlist
+        let adminListEth = await collectionEvm.methods.collectionAdmins().call();
+        adminListEth = adminListEth.map((element: IEthCrossAccountId) => helper.address.convertCrossAccountFromEthCrossAccount(element));
+        expect(adminListRpc).to.be.like(adminListEth);
+
+        // 3. check isOwnerOrAdminCross returns true:
+        expect(await collectionEvm.methods.isOwnerOrAdminCross(adminCrossSub).call()).to.be.true;
+        expect(await collectionEvm.methods.isOwnerOrAdminCross(adminCrossEth).call()).to.be.true;
+      });
+    });
+
+    itEth('cross account admin can mint', async ({helper}) => {
+      // arrange: create collection and accounts
+      const owner = await helper.eth.createAccountWithBalance(donor);
+      const adminEth = (await helper.eth.createAccountWithBalance(donor)).toLowerCase();
+      const adminCrossEth = helper.ethCrossAccount.fromAddress(adminEth);
+      const [adminSub] = await helper.arrange.createAccounts([100n], donor);
+      const adminCrossSub = helper.ethCrossAccount.fromKeyringPair(adminSub);
+      const {collectionAddress, collectionId} = await helper.eth.createERC721MetadataCompatibleCollection(
+        owner,
+        {
+          ...CREATE_COLLECTION_DATA_DEFAULTS,
+          name: 'Mint collection',
+          description: 'a',
+          tokenPrefix: 'b',
+          collectionMode: 'nft',
+          adminList: [adminCrossSub, adminCrossEth],
+        },
+        'uri',
+      );
+      const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner, true);
+
+      // admin (sub and eth) can mint token:
+      await collectionEvm.methods.mint(owner).send({from: adminEth});
+      await helper.nft.mintToken(adminSub, {collectionId, owner: {Ethereum: owner}});
+
+      expect(await helper.collection.getLastTokenId(collectionId)).to.eq(2);
+    });
+
+    itEth('cannot add invalid cross account admin', async ({helper}) => {
+      const owner = await helper.eth.createAccountWithBalance(donor);
+      const [admin] = await helper.arrange.createAccounts([100n, 100n], donor);
+
+      const adminCross = {
+        eth: helper.address.substrateToEth(admin.address),
+        sub: admin.addressRaw,
+      };
+
+      await expect(helper.eth.createCollection(
+        owner,
+        {
+          ...CREATE_COLLECTION_DATA_DEFAULTS,
+          name: 'A',
+          description: 'B',
+          tokenPrefix: 'C',
+          collectionMode: 'nft',
+          adminList: [adminCross],
+        },
+      ).call()).to.be.rejected;
+    });
+
+    itEth('Remove [cross] admin by owner', async ({helper}) => {
+      const owner = await helper.eth.createAccountWithBalance(donor);
+
+      const [adminSub] = await helper.arrange.createAccounts([10n], donor);
+      const adminEth = (await helper.eth.createAccountWithBalance(donor)).toLowerCase();
+      const adminCrossSub = helper.ethCrossAccount.fromKeyringPair(adminSub);
+      const adminCrossEth = helper.ethCrossAccount.fromAddress(adminEth);
+
+      const {collectionAddress, collectionId} = await helper.eth.createCollection(
+        owner,
+        {
+          ...CREATE_COLLECTION_DATA_DEFAULTS,
+          name: 'A',
+          description: 'B',
+          tokenPrefix: 'C',
+          collectionMode: 'nft',
+          adminList: [adminCrossSub, adminCrossEth],
+        },
+      ).send();
+
+      const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
+
+      {
+        const adminList = await helper.collection.getAdmins(collectionId);
+        expect(adminList).to.deep.include({Substrate: adminSub.address});
+        expect(adminList).to.deep.include({Ethereum: adminEth});
+      }
+
+      await collectionEvm.methods.removeCollectionAdminCross(adminCrossSub).send();
+      await collectionEvm.methods.removeCollectionAdminCross(adminCrossEth).send();
+      const adminList = await helper.collection.getAdmins(collectionId);
+      expect(adminList.length).to.be.eq(0);
+
+      // Non admin cannot mint:
+      await expect(helper.nft.mintToken(adminSub, {collectionId, owner: {Substrate: adminSub.address}})).to.be.rejectedWith(/common.PublicMintingNotAllowed/);
+      await expect(collectionEvm.methods.mint(adminEth).send({from: adminEth})).to.be.rejected;
+    });
+  });
+
+  describe('Collection limits', () => {
+    describe('Can set collection limits', () => {
+      [
+        {case: 'nft' as const},
+        {case: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
+        {case: 'ft' as const},
+      ].map(testCase =>
+        itEth.ifWithPallets(`for ${testCase.case}`, testCase.requiredPallets || [], async ({helper}) => {
+          const owner = await helper.eth.createAccountWithBalance(donor);
+
+          const limits = {
+            accountTokenOwnershipLimit: 1000n,
+            sponsoredDataSize: 1024n,
+            sponsoredDataRateLimit: 30n,
+            tokenLimit: 1000000n,
+            sponsorTransferTimeout: 6n,
+            sponsorApproveTimeout: 6n,
+            ownerCanTransfer: 1n,
+            ownerCanDestroy: 0n,
+            transfersEnabled: 0n,
+          };
+
+          const {collectionId, collectionAddress} = await helper.eth.createCollection(
+            owner,
+            {
+              ...CREATE_COLLECTION_DATA_DEFAULTS,
+              name: 'Limits',
+              description: 'absolutely anything',
+              tokenPrefix: 'FLO',
+              collectionMode: testCase.case,
+              limits: [
+                {field: CollectionLimitField.AccountTokenOwnership, value: limits.accountTokenOwnershipLimit},
+                {field: CollectionLimitField.SponsoredDataSize, value: limits.sponsoredDataSize},
+                {field: CollectionLimitField.SponsoredDataRateLimit, value: limits.sponsoredDataRateLimit},
+                {field: CollectionLimitField.TokenLimit, value: limits.tokenLimit},
+                {field: CollectionLimitField.SponsorTransferTimeout, value: limits.sponsorTransferTimeout},
+                {field: CollectionLimitField.SponsorApproveTimeout, value: limits.sponsorApproveTimeout},
+                {field: CollectionLimitField.OwnerCanTransfer, value: limits.ownerCanTransfer},
+                {field: CollectionLimitField.OwnerCanDestroy, value: limits.ownerCanDestroy},
+                {field: CollectionLimitField.TransferEnabled, value: limits.transfersEnabled},
+              ],
+            },
+          ).send();
+
+          const expectedLimits = {
+            accountTokenOwnershipLimit: 1000,
+            sponsoredDataSize: 1024,
+            sponsoredDataRateLimit: {blocks: 30},
+            tokenLimit: 1000000,
+            sponsorTransferTimeout: 6,
+            sponsorApproveTimeout: 6,
+            ownerCanTransfer: true,
+            ownerCanDestroy: false,
+            transfersEnabled: false,
+          };
+
+          const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, testCase.case, owner);
+
+          // Check limits from sub:
+          const data = (await helper.rft.getData(collectionId))!;
+          expect(data.raw.limits).to.deep.eq(expectedLimits);
+          expect(await helper.collection.getEffectiveLimits(collectionId)).to.deep.eq(expectedLimits);
+          // Check limits from eth:
+          const limitsEvm = await collectionEvm.methods.collectionLimits().call({from: owner});
+          expect(limitsEvm).to.have.length(9);
+          expect(limitsEvm[0]).to.deep.eq([CollectionLimitField.AccountTokenOwnership.toString(), [true, limits.accountTokenOwnershipLimit.toString()]]);
+          expect(limitsEvm[1]).to.deep.eq([CollectionLimitField.SponsoredDataSize.toString(), [true, limits.sponsoredDataSize.toString()]]);
+          expect(limitsEvm[2]).to.deep.eq([CollectionLimitField.SponsoredDataRateLimit.toString(), [true, limits.sponsoredDataRateLimit.toString()]]);
+          expect(limitsEvm[3]).to.deep.eq([CollectionLimitField.TokenLimit.toString(), [true, limits.tokenLimit.toString()]]);
+          expect(limitsEvm[4]).to.deep.eq([CollectionLimitField.SponsorTransferTimeout.toString(), [true, limits.sponsorTransferTimeout.toString()]]);
+          expect(limitsEvm[5]).to.deep.eq([CollectionLimitField.SponsorApproveTimeout.toString(), [true, limits.sponsorApproveTimeout.toString()]]);
+          expect(limitsEvm[6]).to.deep.eq([CollectionLimitField.OwnerCanTransfer.toString(), [true, limits.ownerCanTransfer.toString()]]);
+          expect(limitsEvm[7]).to.deep.eq([CollectionLimitField.OwnerCanDestroy.toString(), [true, limits.ownerCanDestroy.toString()]]);
+          expect(limitsEvm[8]).to.deep.eq([CollectionLimitField.TransferEnabled.toString(), [true, limits.transfersEnabled.toString()]]);
+        }));
+    });
+
+    describe('(!negative test!) Cannot set invalid collection limits', () => {
+      [
+        {case: 'nft' as const},
+        {case: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
+        {case: 'ft' as const},
+      ].map(testCase =>
+        itEth.ifWithPallets(`for ${testCase.case}`, testCase.requiredPallets || [], async ({helper}) => {
+          const invalidLimits = {
+            accountTokenOwnershipLimit: BigInt(Number.MAX_SAFE_INTEGER),
+            transfersEnabled: 3,
+          };
+
+          const createCollectionData = {
+            ...CREATE_COLLECTION_DATA_DEFAULTS,
+            name: 'Limits',
+            description: 'absolutely anything',
+            tokenPrefix: 'ISNI',
+            collectionMode: testCase.case,
+          };
+
+          const owner = await helper.eth.createAccountWithBalance(donor);
+          await expect(helper.eth.createCollection(
+            owner,
+            {
+              ...createCollectionData,
+              limits: [{field: 9 as CollectionLimitField, value: 1n}],
+            },
+          ).call()).to.be.rejectedWith('value not convertible into enum "CollectionLimitField"');
+
+          await expect(helper.eth.createCollection(
+            owner,
+            {
+              ...createCollectionData,
+              limits: [{field: CollectionLimitField.AccountTokenOwnership, value: invalidLimits.accountTokenOwnershipLimit}],
+            },
+          ).call()).to.be.rejectedWith(`can't convert value to u32 "${invalidLimits.accountTokenOwnershipLimit}"`);
+
+          await expect(helper.eth.createCollection(
+            owner,
+            {
+              ...createCollectionData,
+              limits: [{field: CollectionLimitField.TransferEnabled, value: 3n}],
+            },
+          ).call()).to.be.rejectedWith(`can't convert value to boolean "${invalidLimits.transfersEnabled}"`);
+
+          await expect(helper.eth.createCollection(
+            owner,
+            {
+              ...createCollectionData,
+              limits: [{field: CollectionLimitField.SponsoredDataSize, value: -1n}],
+            },
+          ).call()).to.be.rejectedWith('value out-of-bounds');
+        }));
+    });
+  });
+
+  describe('Collection properties', () => {
+
+    [
+      {mode: 'nft' as const, methodParams: [{key: 'testKey1', value: Buffer.from('testValue1')}, {key: 'testKey2', value: Buffer.from('testValue2')}], expectedProps: [{key: 'testKey1', value: 'testValue1'}, {key: 'testKey2', value: 'testValue2'}]},
+      {mode: 'rft' as const, methodParams: [{key: 'testKey1', value: Buffer.from('testValue1')}, {key: 'testKey2', value: Buffer.from('testValue2')}], expectedProps: [{key: 'testKey1', value: 'testValue1'}, {key: 'testKey2', value: 'testValue2'}]},
+      {mode: 'ft' as const, methodParams: [{key: 'testKey1', value: Buffer.from('testValue1')}, {key: 'testKey2', value: Buffer.from('testValue2')}], expectedProps: [{key: 'testKey1', value: 'testValue1'}, {key: 'testKey2', value: 'testValue2'}]},
+    ].map(testCase =>
+      itEth.ifWithPallets(`Collection properties can be set for ${testCase.mode}`, testCase.mode === 'rft' ? [Pallets.ReFungible] : [], async({helper}) => {
+        const caller = await helper.eth.createAccountWithBalance(donor);
+        const callerCross = helper.ethCrossAccount.fromAddress(caller);
+        const owner = await helper.eth.createAccountWithBalance(donor);
+        const {collectionId, collectionAddress} = await helper.eth.createCollection(
+          owner,
+          {
+            ...CREATE_COLLECTION_DATA_DEFAULTS,
+            name: 'name',
+            description: 'test',
+            tokenPrefix: 'test',
+            collectionMode: testCase.mode,
+            adminList: [callerCross],
+            properties: testCase.methodParams,
+          },
+        ).send();
+
+        const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, caller);
+
+        const raw = (await helper[testCase.mode].getData(collectionId))?.raw;
+        expect(raw.properties).to.deep.equal(testCase.expectedProps);
+
+        // collectionProperties returns properties:
+        expect(await collectionEvm.methods.collectionProperties([]).call()).to.be.like(testCase.expectedProps.map(prop => helper.ethProperty.property(prop.key, prop.value)));
+      }));
+
+    [
+      {mode: 'nft' as const},
+      {mode: 'rft' as const},
+      {mode: 'ft' as const},
+    ].map(testCase =>
+      itEth.ifWithPallets(`Collection properties can be deleted for ${testCase.mode}`, testCase.mode === 'rft' ? [Pallets.ReFungible] : [], async({helper}) => {
+        const caller = await helper.eth.createAccountWithBalance(donor);
+        const callerCross = helper.ethCrossAccount.fromAddress(caller);
+        const owner = await helper.eth.createAccountWithBalance(donor);
+        const {collectionId, collectionAddress} = await helper.eth.createCollection(
+          owner,
+          {
+            ...CREATE_COLLECTION_DATA_DEFAULTS,
+            name: 'name',
+            description: 'test',
+            tokenPrefix: 'test',
+            collectionMode: testCase.mode,
+            adminList: [callerCross],
+            properties:[
+              {key: 'testKey1', value: Buffer.from('testValue1')},
+              {key: 'testKey2', value: Buffer.from('testValue2')},
+              {key: 'testKey3', value: Buffer.from('testValue3')}],
+          },
+        ).send();
+
+        const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, caller);
+
+        await collectionEvm.methods.deleteCollectionProperties(['testKey1', 'testKey2']).send({from: caller});
+
+        const raw = (await helper[testCase.mode].getData(collectionId))?.raw;
+
+        expect(raw.properties.length).to.equal(1);
+        expect(raw.properties).to.deep.equal([{key: 'testKey3', value: 'testValue3'}]);
+      }));
+
+    itEth('(!negative test!) Cannot set invalid properties', async({helper}) => {
+      const caller = await helper.eth.createAccountWithBalance(donor);
+      const callerCross = helper.ethCrossAccount.fromAddress(caller);
+      const owner = await helper.eth.createAccountWithBalance(donor);
+      const createCollectionData = {
+        ...CREATE_COLLECTION_DATA_DEFAULTS,
+        name: 'name',
+        description: 'test',
+        tokenPrefix: 'test',
+        collectionMode: 'nft' as TCollectionMode,
+        adminList: [callerCross],
+      };
+      await expect(helper.eth.createCollection(
+        owner,
+        {
+          ...createCollectionData,
+          properties: [{key: '', value: Buffer.from('val1')}],
+        },
+      ).call()).to.be.rejected;
+
+      await expect(helper.eth.createCollection(
+        owner,
+        {
+          ...createCollectionData,
+          properties: [{key: 'déjà vu', value: Buffer.from('hmm...')}],
+        },
+      ).call()).to.be.rejected;
+
+      await expect(helper.eth.createCollection(
+        owner,
+        {
+          ...createCollectionData,
+          properties: [{key: 'a'.repeat(257), value: Buffer.from('val3')}],
+        },
+      ).call()).to.be.rejected;
+    });
+
+    itEth('(!negative test!) cannot delete properties of non-owned collections', async ({helper}) => {
+      const caller = await helper.eth.createAccountWithBalance(donor);
+      const owner = await helper.eth.createAccountWithBalance(donor);
+      const {collectionAddress} = await helper.eth.createCollection(
+        owner,
+        {
+          ...CREATE_COLLECTION_DATA_DEFAULTS,
+          name: 'name',
+          description: 'test',
+          tokenPrefix: 'test',
+          collectionMode: 'nft',
+          properties:[
+            {key: 'testKey1', value: Buffer.from('testValue1')},
+            {key: 'testKey2', value: Buffer.from('testValue2')}],
+        },
+      ).send();
+
+      const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'nft', caller);
+
+      await expect(collectionEvm.methods.deleteCollectionProperties(['testKey2']).send({from: caller})).to.be.rejected;
+    });
+  });
+
+  describe('Token property permissions', () => {
+    [
+      {mode: 'nft' as const, requiredPallets: []},
+      {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
+    ].map(testCase =>
+      itEth.ifWithPallets(`[${testCase.mode}] Can set all possible token property permissions`, testCase.requiredPallets, async({helper}) => {
+        const owner = await helper.eth.createAccountWithBalance(donor);
+        const caller = await helper.ethCrossAccount.createAccountWithBalance(donor);
+        for(const [mutable,collectionAdmin, tokenOwner] of cartesian([], [false, true], [false, true], [false, true])) {
+          const {collectionId, collectionAddress} = await helper.eth.createCollection(
+            owner,
+            {
+              ...CREATE_COLLECTION_DATA_DEFAULTS,
+              name: 'A',
+              description: 'B',
+              tokenPrefix: 'C',
+              collectionMode: testCase.mode,
+              adminList: [caller],
+              tokenPropertyPermissions: [
+                {
+                  key: 'testKey',
+                  permissions: [
+                    {code: TokenPermissionField.Mutable, value: mutable},
+                    {code: TokenPermissionField.TokenOwner, value: tokenOwner},
+                    {code: TokenPermissionField.CollectionAdmin, value: collectionAdmin},
+                  ],
+                },
+              ],
+            },
+          ).send();
+          const collection = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, owner);
+
+          expect(await helper[testCase.mode].getPropertyPermissions(collectionId)).to.be.deep.equal([{
+            key: 'testKey',
+            permission: {mutable, collectionAdmin, tokenOwner},
+          }]);
+
+          expect(await collection.methods.tokenPropertyPermissions().call({from: caller.eth})).to.be.like([
+            ['testKey', [
+              [TokenPermissionField.Mutable.toString(), mutable],
+              [TokenPermissionField.TokenOwner.toString(), tokenOwner],
+              [TokenPermissionField.CollectionAdmin.toString(), collectionAdmin]],
+            ],
+          ]);
+        }
+      }));
+
+    [
+      {mode: 'nft' as const, requiredPallets: []},
+      {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
+    ].map(testCase =>
+      itEth.ifWithPallets(`[${testCase.mode}] Can set multiple token property permissions`, testCase.requiredPallets, async({helper}) => {
+        const owner = await helper.eth.createAccountWithBalance(donor);
+        const {collectionId, collectionAddress} = await helper.eth.createCollection(
+          owner,
+          {
+            ...CREATE_COLLECTION_DATA_DEFAULTS,
+            name: 'A',
+            description: 'B',
+            tokenPrefix: 'C',
+            collectionMode: testCase.mode,
+            tokenPropertyPermissions: [
+              {
+                key: 'testKey_0',
+                permissions: [
+                  {code: TokenPermissionField.Mutable, value: true},
+                  {code: TokenPermissionField.TokenOwner, value: true},
+                  {code: TokenPermissionField.CollectionAdmin, value: true}],
+              },
+              {
+                key: 'testKey_1',
+                permissions: [
+                  {code: TokenPermissionField.Mutable, value: true},
+                  {code: TokenPermissionField.TokenOwner, value: false},
+                  {code: TokenPermissionField.CollectionAdmin, value: true}],
+              },
+              {
+                key: 'testKey_2',
+                permissions: [
+                  {code: TokenPermissionField.Mutable, value: false},
+                  {code: TokenPermissionField.TokenOwner, value: true},
+                  {code: TokenPermissionField.CollectionAdmin, value: false}],
+              },
+            ],
+          },
+        ).send();
+        const collection = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, owner);
+
+        expect(await helper[testCase.mode].getPropertyPermissions(collectionId)).to.be.deep.equal([
+          {
+            key: 'testKey_0',
+            permission: {mutable: true, tokenOwner: true, collectionAdmin: true},
+          },
+          {
+            key: 'testKey_1',
+            permission: {mutable: true, tokenOwner: false, collectionAdmin: true},
+          },
+          {
+            key: 'testKey_2',
+            permission: {mutable: false, tokenOwner: true, collectionAdmin: false},
+          },
+        ]);
+
+        expect(await collection.methods.tokenPropertyPermissions().call({from: owner})).to.be.like([
+          ['testKey_0', [
+            [TokenPermissionField.Mutable.toString(), true],
+            [TokenPermissionField.TokenOwner.toString(), true],
+            [TokenPermissionField.CollectionAdmin.toString(), true]],
+          ],
+          ['testKey_1', [
+            [TokenPermissionField.Mutable.toString(), true],
+            [TokenPermissionField.TokenOwner.toString(), false],
+            [TokenPermissionField.CollectionAdmin.toString(), true]],
+          ],
+          ['testKey_2', [
+            [TokenPermissionField.Mutable.toString(), false],
+            [TokenPermissionField.TokenOwner.toString(), true],
+            [TokenPermissionField.CollectionAdmin.toString(), false]],
+          ],
+        ]);
+      }));
+
+    [
+      {mode: 'nft' as const, requiredPallets: []},
+      {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
+    ].map(testCase =>
+      itEth.ifWithPallets(`Can be deleted for ${testCase.mode}`, testCase.requiredPallets, async({helper}) => {
+        const caller = await helper.eth.createAccountWithBalance(donor);
+        const receiver = await helper.ethCrossAccount.createAccountWithBalance(donor);
+        const {collectionAddress} = await helper.eth.createCollection(
+          caller,
+          {
+            ...CREATE_COLLECTION_DATA_DEFAULTS,
+            name: 'A',
+            description: 'B',
+            tokenPrefix: 'C',
+            collectionMode: testCase.mode,
+            adminList: [receiver],
+            tokenPropertyPermissions: [
+              {
+                key: 'testKey',
+                permissions: [
+                  {code: TokenPermissionField.Mutable, value: true},
+                  {code: TokenPermissionField.CollectionAdmin, value: true}],
+              },
+              {
+                key: 'testKey_1',
+                permissions: [
+                  {code: TokenPermissionField.Mutable, value: true},
+                  {code: TokenPermissionField.CollectionAdmin, value: true}],
+              },
+            ],
+          },
+        ).send();
+
+        const collection = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, caller);
+        const tokenId = (await collection.methods.mintCross(receiver, [{key: 'testKey', value: Buffer.from('testValue')}, {key: 'testKey_1', value: Buffer.from('testValue_1')}]).send()).events.Transfer.returnValues.tokenId;
+        expect(await collection.methods.properties(tokenId, ['testKey', 'testKey_1']).call()).to.has.length(2);
+
+        await collection.methods.deleteProperties(tokenId, ['testKey', 'testKey_1']).send({from: caller});
+        expect(await collection.methods.properties(tokenId, ['testKey', 'testKey_1']).call()).to.has.length(0);
+      }));
+  });
+
+  describe('Nesting', () => {
+    itEth('NFT: allows an Owner to nest/unnest their token', async ({helper}) => {
+      const owner = await helper.eth.createAccountWithBalance(donor);
+      const {collectionAddress, collectionId} = await helper.eth.createCollection(
+        owner,
+        {
+          ...CREATE_COLLECTION_DATA_DEFAULTS,
+          name: 'A',
+          description: 'B',
+          tokenPrefix: 'C',
+          collectionMode: 'nft',
+          nestingSettings: {token_owner: true, collection_admin: false, restricted: []},
+        },
+      ).send();
+
+      const contract = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
+
+      // Create a token to be nested to
+      const mintingTargetNFTTokenIdResult = await contract.methods.mint(owner).send({from: owner});
+      const targetNFTTokenId = mintingTargetNFTTokenIdResult.events.Transfer.returnValues.tokenId;
+      const targetNftTokenAddress = helper.ethAddress.fromTokenId(collectionId, targetNFTTokenId);
+
+      // Create a nested token
+      const mintingFirstTokenIdResult = await contract.methods.mint(targetNftTokenAddress).send({from: owner});
+      const firstTokenId = mintingFirstTokenIdResult.events.Transfer.returnValues.tokenId;
+      expect(await contract.methods.ownerOf(firstTokenId).call()).to.be.equal(targetNftTokenAddress);
+
+      // Create a token to be nested and nest
+      const mintingSecondTokenIdResult = await contract.methods.mint(owner).send({from: owner});
+      const secondTokenId = mintingSecondTokenIdResult.events.Transfer.returnValues.tokenId;
+
+      await contract.methods.transfer(targetNftTokenAddress, secondTokenId).send({from: owner});
+      expect(await contract.methods.ownerOf(secondTokenId).call()).to.be.equal(targetNftTokenAddress);
+
+      // Unnest token back
+      await contract.methods.transferFrom(targetNftTokenAddress, owner, secondTokenId).send({from: owner});
+      expect(await contract.methods.ownerOf(secondTokenId).call()).to.be.equal(owner);
+    });
+
+    itEth('NFT: collectionNesting()', async ({helper}) => {
+      const owner = await helper.eth.createAccountWithBalance(donor);
+      const {collectionAddress: unnestedCollectionAddress} = await helper.eth.createCollection(
+        owner,
+        new CreateCollectionData('A', 'B', 'C', 'nft'),
+      ).send();
+
+      const unnestedContract = await helper.ethNativeContract.collection(unnestedCollectionAddress, 'nft', owner);
+      expect(await unnestedContract.methods.collectionNesting().call({from: owner})).to.be.like([false, false, []]);
+
+      const {collectionAddress} = await helper.eth.createCollection(
+        owner,
+        {
+          ...CREATE_COLLECTION_DATA_DEFAULTS,
+          name: 'A',
+          description: 'B',
+          tokenPrefix: 'C',
+          collectionMode: 'nft',
+          nestingSettings: {token_owner: true, collection_admin: false, restricted: [unnestedCollectionAddress.toString()]},
+        },
+      ).send();
+
+      const contract = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
+      expect(await contract.methods.collectionNesting().call({from: owner})).to.be.like([true, false, [unnestedCollectionAddress.toString()]]);
+      await contract.methods.setCollectionNesting([false, false, []]).send({from: owner});
+      expect(await contract.methods.collectionNesting().call({from: owner})).to.be.like([false, false, []]);
+    });
+
+    itEth('NFT: disallows to nest token if nesting is disabled', async ({helper}) => {
+      const owner = await helper.eth.createAccountWithBalance(donor);
+
+      const {collectionId, collectionAddress} = await helper.eth.createCollection(
+        owner,
+        {
+          ...CREATE_COLLECTION_DATA_DEFAULTS,
+          name: 'A',
+          description: 'B',
+          tokenPrefix: 'C',
+          collectionMode: 'nft',
+          nestingSettings: {token_owner: false, collection_admin: false, restricted: []},
+        },
+      ).send();
+
+      const contract = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
+
+      // Create a token to nest into
+      const mintingTargetTokenIdResult = await contract.methods.mint(owner).send({from: owner});
+      const targetTokenId = mintingTargetTokenIdResult.events.Transfer.returnValues.tokenId;
+      const targetNftTokenAddress = helper.ethAddress.fromTokenId(collectionId, targetTokenId);
+
+      // Create a token to nest
+      const mintingNftTokenIdResult = await contract.methods.mint(owner).send({from: owner});
+      const nftTokenId = mintingNftTokenIdResult.events.Transfer.returnValues.tokenId;
+
+      // Try to nest
+      await expect(contract.methods
+        .transfer(targetNftTokenAddress, nftTokenId)
+        .call({from: owner})).to.be.rejectedWith('UserIsNotAllowedToNest');
+    });
+  });
+
+  describe('Flags', () => {
+    const createCollectionData = {
+      ...CREATE_COLLECTION_DATA_DEFAULTS,
+      name: 'A',
+      description: 'B',
+      tokenPrefix: 'C',
+      collectionMode: 'nft' as TCollectionMode,
+    };
+
+    itEth('NFT: use numbers for flags', async ({helper}) => {
+      const owner = await helper.eth.createAccountWithBalance(donor);
+
+      {
+        const {collectionId} = await helper.eth.createCollection(owner, {...createCollectionData, flags: 0}).send();
+        expect((await helper.nft.getData(collectionId))?.raw.flags).to.be.deep.equal({foreign: false, erc721metadata: false});
+      }
+
+      {
+        const {collectionId} = await helper.eth.createCollection(owner, {...createCollectionData, flags: 64}).send();
+        expect((await helper.nft.getData(collectionId))?.raw.flags).to.be.deep.equal({foreign: false, erc721metadata: true});
+      }
+    });
+
+    itEth('NFT: foreign flag number is ignored', async ({helper}) => {
+      const owner = await helper.eth.createAccountWithBalance(donor);
+
+      {
+        const {collectionId} = await helper.eth.createCollection(owner, {...createCollectionData, flags: 128}).send();
+        expect((await helper.nft.getData(collectionId))?.raw.flags).to.be.deep.equal({foreign: false, erc721metadata: false});
+      }
+
+      {
+        const {collectionId} = await helper.eth.createCollection(owner, {...createCollectionData, flags: 192}).send();
+        expect((await helper.nft.getData(collectionId))?.raw.flags).to.be.deep.equal({foreign: false, erc721metadata: true});
+      }
+    });
+
+    itEth('NFT: use enum for flags', async ({helper}) => {
+      const owner = await helper.eth.createAccountWithBalance(donor);
+
+      {
+        const {collectionId} = await helper.eth.createCollection(owner, {...createCollectionData, flags: [CollectionFlag.Erc721metadata]}).send();
+        expect((await helper.nft.getData(collectionId))?.raw.flags).to.be.deep.equal({foreign: false, erc721metadata: true});
+      }
+    });
+
+    itEth('NFT: foreign flag enum is ignored', async ({helper}) => {
+      const owner = await helper.eth.createAccountWithBalance(donor);
+
+      {
+        const {collectionId} = await helper.eth.createCollection(owner, {...createCollectionData, flags: [CollectionFlag.Foreign]}).send();
+        expect((await helper.nft.getData(collectionId))?.raw.flags).to.be.deep.equal({foreign: false, erc721metadata: false});
+      }
+
+      {
+        const {collectionId} = await helper.eth.createCollection(owner, {...createCollectionData, flags: [CollectionFlag.Erc721metadata | CollectionFlag.Foreign]}).send();
+        expect((await helper.nft.getData(collectionId))?.raw.flags).to.be.deep.equal({foreign: false, erc721metadata: true});
+      }
+    });
+  });
+});
modifiedtests/src/eth/destroyCollection.test.tsdiffbeforeafterboth
--- a/tests/src/eth/destroyCollection.test.ts
+++ b/tests/src/eth/destroyCollection.test.ts
@@ -17,13 +17,15 @@
 import {IKeyringPair} from '@polkadot/types/types';
 import {Pallets} from '../util';
 import {expect, itEth, usingEthPlaygrounds} from './util';
+import {TCollectionMode} from '../util/playgrounds/types';
+import {CreateCollectionData} from './util/playgrounds/types';
 
 describe('Destroy Collection from EVM', function() {
   let donor: IKeyringPair;
   const testCases = [
-    {case: 'rft' as const, params: ['Limits', 'absolutely anything', 'OLF'], requiredPallets: [Pallets.ReFungible]},
-    {case: 'nft' as const, params: ['Limits', 'absolutely anything', 'OLF'], requiredPallets: [Pallets.NFT]},
-    {case: 'ft' as const, params: ['Limits', 'absolutely anything', 'OLF', 18], requiredPallets: [Pallets.Fungible]},
+    {case: 'rft' as const, params: ['Limits', 'absolutely anything', 'OLF', 'rft'], requiredPallets: [Pallets.ReFungible]},
+    {case: 'nft' as const, params: ['Limits', 'absolutely anything', 'OLF', 'nft'], requiredPallets: [Pallets.NFT]},
+    {case: 'ft' as const, params: ['Limits', 'absolutely anything', 'OLF', 'ft', 18], requiredPallets: [Pallets.Fungible]},
   ];
 
   before(async function() {
@@ -40,8 +42,7 @@
       const unexistedCollection = helper.ethAddress.fromCollectionId(1000000);
 
       const collectionHelpers = await helper.ethNativeContract.collectionHelpers(signer);
-      const {collectionAddress} = await helper.eth.createCollection(testCase.case, owner, ...testCase.params as [string, string, string, number?]);
-
+      const {collectionAddress} = await helper.eth.createCollection(owner, new CreateCollectionData(...testCase.params as [string, string, string, TCollectionMode, number?])).send();
       // cannot burn collec
       await expect(collectionHelpers.methods
         .destroyCollection(collectionAddress)
modifiedtests/src/eth/events.test.tsdiffbeforeafterboth
--- a/tests/src/eth/events.test.ts
+++ b/tests/src/eth/events.test.ts
@@ -19,7 +19,7 @@
 import {EthUniqueHelper, itEth, usingEthPlaygrounds} from './util';
 import {IEvent, TCollectionMode} from '../util/playgrounds/types';
 import {Pallets, requirePalletsOrSkip} from '../util';
-import {CollectionLimitField, TokenPermissionField, NormalizedEvent} from './util/playgrounds/types';
+import {CollectionLimitField, TokenPermissionField, NormalizedEvent, CreateCollectionData} from './util/playgrounds/types';
 
 let donor: IKeyringPair;
 
@@ -39,7 +39,8 @@
 async function testCollectionCreatedAndDestroy(helper: EthUniqueHelper, mode: TCollectionMode) {
   const owner = await helper.eth.createAccountWithBalance(donor);
   const {unsubscribe, collectedEvents: subEvents} = await helper.subscribeEvents([{section: 'common', names: ['CollectionCreated', 'CollectionDestroyed']}]);
-  const {collectionAddress, events: ethEvents} = await helper.eth.createCollection(mode, owner, 'A', 'B', 'C');
+  const {collectionAddress, events: ethEvents} = await helper.eth.createCollection(owner, new CreateCollectionData('A', 'B', 'C', mode, 18)).send();
+
   await helper.wait.newBlocks(1);
   {
     expect(ethEvents).to.containSubset([
@@ -72,7 +73,7 @@
 
 async function testCollectionPropertySetAndDeleted(helper: EthUniqueHelper, mode: TCollectionMode) {
   const owner = await helper.eth.createAccountWithBalance(donor);
-  const {collectionAddress} = await helper.eth.createCollection(mode, owner, 'A', 'B', 'C');
+  const {collectionAddress} = await helper.eth.createCollection(owner, new CreateCollectionData('A', 'B', 'C', mode, 18)).send();
   const collection = await helper.ethNativeContract.collection(collectionAddress, mode, owner);
   const collectionHelper = await helper.ethNativeContract.collectionHelpers(owner);
 
@@ -113,7 +114,7 @@
 
 async function testPropertyPermissionSet(helper: EthUniqueHelper, mode: TCollectionMode) {
   const owner = await helper.eth.createAccountWithBalance(donor);
-  const {collectionAddress} = await helper.eth.createCollection(mode, owner, 'A', 'B', 'C');
+  const {collectionAddress} = await helper.eth.createCollection(owner, new CreateCollectionData('A', 'B', 'C', mode, 18)).send();
   const collection = await helper.ethNativeContract.collection(collectionAddress, mode, owner);
   const collectionHelper = await helper.ethNativeContract.collectionHelpers(owner);
   const ethEvents: any = [];
@@ -144,7 +145,7 @@
 async function testAllowListAddressAddedAndRemoved(helper: EthUniqueHelper, mode: TCollectionMode) {
   const owner = await helper.eth.createAccountWithBalance(donor);
   const user = helper.ethCrossAccount.createAccount();
-  const {collectionAddress} = await helper.eth.createCollection(mode, owner, 'A', 'B', 'C');
+  const {collectionAddress} = await helper.eth.createCollection(owner, new CreateCollectionData('A', 'B', 'C', mode, 18)).send();
   const collection = await helper.ethNativeContract.collection(collectionAddress, mode, owner);
   const collectionHelper = await helper.ethNativeContract.collectionHelpers(owner);
   const ethEvents: any[] = [];
@@ -186,7 +187,7 @@
 async function testCollectionAdminAddedAndRemoved(helper: EthUniqueHelper, mode: TCollectionMode) {
   const owner = await helper.eth.createAccountWithBalance(donor);
   const user = helper.ethCrossAccount.createAccount();
-  const {collectionAddress} = await helper.eth.createCollection(mode, owner, 'A', 'B', 'C');
+  const {collectionAddress} = await helper.eth.createCollection(owner, new CreateCollectionData('A', 'B', 'C', mode, 18)).send();
   const collection = await helper.ethNativeContract.collection(collectionAddress, mode, owner);
   const collectionHelper = await helper.ethNativeContract.collectionHelpers(owner);
   const ethEvents: any = [];
@@ -226,7 +227,7 @@
 
 async function testCollectionLimitSet(helper: EthUniqueHelper, mode: TCollectionMode) {
   const owner = await helper.eth.createAccountWithBalance(donor);
-  const {collectionAddress} = await helper.eth.createCollection(mode, owner, 'A', 'B', 'C');
+  const {collectionAddress} = await helper.eth.createCollection(owner, new CreateCollectionData('A', 'B', 'C', mode, 18)).send();
   const collection = await helper.ethNativeContract.collection(collectionAddress, mode, owner);
   const collectionHelper = await helper.ethNativeContract.collectionHelpers(owner);
   const ethEvents: any = [];
@@ -253,7 +254,7 @@
 async function testCollectionOwnerChanged(helper: EthUniqueHelper, mode: TCollectionMode) {
   const owner = await helper.eth.createAccountWithBalance(donor);
   const newOwner = helper.ethCrossAccount.createAccount();
-  const {collectionAddress} = await helper.eth.createCollection(mode, owner, 'A', 'B', 'C');
+  const {collectionAddress} = await helper.eth.createCollection(owner, new CreateCollectionData('A', 'B', 'C', mode, 18)).send();
   const collection = await helper.ethNativeContract.collection(collectionAddress, mode, owner);
   const collectionHelper = await helper.ethNativeContract.collectionHelpers(owner);
   const ethEvents: any = [];
@@ -279,7 +280,7 @@
 
 async function testCollectionPermissionSet(helper: EthUniqueHelper, mode: TCollectionMode) {
   const owner = await helper.eth.createAccountWithBalance(donor);
-  const {collectionAddress} = await helper.eth.createCollection(mode, owner, 'A', 'B', 'C');
+  const {collectionAddress} = await helper.eth.createCollection(owner, new CreateCollectionData('A', 'B', 'C', mode, 18)).send();
   const collection = await helper.ethNativeContract.collection(collectionAddress, mode, owner);
   const collectionHelper = await helper.ethNativeContract.collectionHelpers(owner);
   const ethEvents: any = [];
@@ -320,7 +321,7 @@
 async function testCollectionSponsorSetAndConfirmedAndThenRemoved(helper: EthUniqueHelper, mode: TCollectionMode) {
   const owner = await helper.eth.createAccountWithBalance(donor);
   const sponsor = await helper.ethCrossAccount.createAccountWithBalance(donor);
-  const {collectionAddress} = await helper.eth.createCollection(mode, owner, 'A', 'B', 'C');
+  const {collectionAddress} = await helper.eth.createCollection(owner, new CreateCollectionData('A', 'B', 'C', mode, 18)).send();
   const collection = await helper.ethNativeContract.collection(collectionAddress, mode, owner);
   const collectionHelper = await helper.ethNativeContract.collectionHelpers(owner);
   const ethEvents: any = [];
@@ -374,7 +375,7 @@
 
 async function testTokenPropertySetAndDeleted(helper: EthUniqueHelper, mode: TCollectionMode) {
   const owner = await helper.eth.createAccountWithBalance(donor);
-  const {collectionAddress} = await helper.eth.createCollection(mode, owner, 'A', 'B', 'C');
+  const {collectionAddress} = await helper.eth.createCollection(owner, new CreateCollectionData('A', 'B', 'C', mode, 18)).send();
   const collection = await helper.ethNativeContract.collection(collectionAddress, mode, owner);
   const result = await collection.methods.mint(owner).send({from: owner});
   const tokenId = result.events.Transfer.returnValues.tokenId;
modifiedtests/src/eth/marketplace-v2/Market.soldiffbeforeafterboth
--- a/tests/src/eth/marketplace-v2/Market.sol
+++ b/tests/src/eth/marketplace-v2/Market.sol
@@ -7,7 +7,7 @@
 import "@openzeppelin/contracts/access/Ownable.sol";
 import { UniqueNFT, CrossAddress } from "@unique-nft/solidity-interfaces/contracts/UniqueNFT.sol";
 import { UniqueFungible, CrossAddress as CrossAddressF } from "@unique-nft/solidity-interfaces/contracts/UniqueFungible.sol";
-import "@unique-nft/solidity-interfaces/contracts/CollectionHelpers.sol";
+import { CollectionHelpers } from "@unique-nft/solidity-interfaces/contracts/CollectionHelpers.sol";
 import "./royalty/UniqueRoyaltyHelper.sol";
 
 contract Market is Ownable, ReentrancyGuard {
modifiedtests/src/eth/marketplace/marketplace.test.tsdiffbeforeafterboth
--- a/tests/src/eth/marketplace/marketplace.test.ts
+++ b/tests/src/eth/marketplace/marketplace.test.ts
@@ -60,7 +60,7 @@
     await helpers.methods.setSponsor(matcher.options.address, sponsor).send({from: matcherOwner});
     await helpers.methods.confirmSponsorship(matcher.options.address).send({from: sponsor});
 
-    const collection = await helper.nft.mintCollection(alice, {limits: {sponsorApproveTimeout: 1}, pendingSponsor: alice.address});
+    const collection = await helper.nft.mintCollection(alice, {limits: {sponsorApproveTimeout: 1}, pendingSponsor: {Substrate: alice.address}});
     await collection.confirmSponsorship(alice);
     await collection.addToAllowList(alice, {Substrate: aliceDoubleMirror});
     const evmCollection = await helper.ethNativeContract.collection(helper.ethAddress.fromCollectionId(collection.collectionId), 'nft');
@@ -114,7 +114,7 @@
     await helpers.methods.setSponsor(matcher.options.address, sponsor).send({from: matcherOwner});
     await helpers.methods.confirmSponsorship(matcher.options.address).send({from: sponsor});
 
-    const collection = await helper.nft.mintCollection(alice, {limits: {sponsorApproveTimeout: 1}, pendingSponsor: alice.address});
+    const collection = await helper.nft.mintCollection(alice, {limits: {sponsorApproveTimeout: 1}, pendingSponsor: {Substrate: alice.address}});
     await collection.confirmSponsorship(alice);
     await collection.addToAllowList(alice, {Substrate: aliceDoubleMirror});
     const evmCollection = await helper.ethNativeContract.collection(helper.ethAddress.fromCollectionId(collection.collectionId), 'nft');
modifiedtests/src/eth/nesting/nest.test.tsdiffbeforeafterboth
--- a/tests/src/eth/nesting/nest.test.ts
+++ b/tests/src/eth/nesting/nest.test.ts
@@ -6,11 +6,12 @@
 const createNestingCollection = async (
   helper: EthUniqueHelper,
   owner: string,
+  mergeDeprecated = false,
 ): Promise<{ collectionId: number, collectionAddress: string, contract: Contract }> => {
   const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
 
-  const contract = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
-  await contract.methods.setCollectionNesting(true).send({from: owner});
+  const contract = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner, mergeDeprecated);
+  await contract.methods.setCollectionNesting([true, false, []]).send({from: owner});
 
   return {collectionId, collectionAddress, contract};
 };
@@ -52,27 +53,44 @@
       expect(await contract.methods.ownerOf(secondTokenId).call()).to.be.equal(owner);
     });
 
+    itEth('NFT: collectionNesting()', async ({helper}) => {
+      const owner = await helper.eth.createAccountWithBalance(donor);
+      const {collectionAddress: unnestedCollectionAddress} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
+      const unnestedContract = await helper.ethNativeContract.collection(unnestedCollectionAddress, 'nft', owner);
+      expect(await unnestedContract.methods.collectionNesting().call({from: owner})).to.be.like([false, false, []]);
+
+      const {contract} = await createNestingCollection(helper, owner);
+      expect(await contract.methods.collectionNesting().call({from: owner})).to.be.like([true, false, []]);
+      await contract.methods.setCollectionNesting([true, false, [unnestedCollectionAddress]]).send({from: owner});
+      expect(await contract.methods.collectionNesting().call({from: owner})).to.be.like([true, false, [unnestedCollectionAddress]]);
+      await contract.methods.setCollectionNesting([false, true, [unnestedCollectionAddress]]).send({from: owner});
+      expect(await contract.methods.collectionNesting().call({from: owner})).to.be.like([false, true, [unnestedCollectionAddress]]);
+      await contract.methods.setCollectionNesting([false, false, []]).send({from: owner});
+      expect(await contract.methods.collectionNesting().call({from: owner})).to.be.like([false, false, []]);
+    });
+
+    // Sof-deprecated
     itEth('NFT: collectionNestingRestrictedCollectionIds() & collectionNestingPermissions', async ({helper}) => {
       const owner = await helper.eth.createAccountWithBalance(donor);
       const {collectionId: unnestedCollsectionId, collectionAddress: unnsetedCollectionAddress} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
-      const unnestedContract = await helper.ethNativeContract.collection(unnsetedCollectionAddress, 'nft', owner);
+      const unnestedContract = await helper.ethNativeContract.collection(unnsetedCollectionAddress, 'nft', owner, true);
       expect(await unnestedContract.methods.collectionNestingRestrictedCollectionIds().call({from: owner})).to.be.like([false, []]);
 
-      const {contract} = await createNestingCollection(helper, owner);
+      const {contract} = await createNestingCollection(helper, owner, true);
       expect(await contract.methods.collectionNestingRestrictedCollectionIds().call({from: owner})).to.be.like([true, []]);
-      await contract.methods.setCollectionNesting(true, [unnsetedCollectionAddress]).send({from: owner});
+      await contract.methods['setCollectionNesting(bool,address[])'](true, [unnsetedCollectionAddress]).send({from: owner});
       expect(await contract.methods.collectionNestingRestrictedCollectionIds().call({from: owner})).to.be.like([true, [unnestedCollsectionId.toString()]]);
       expect(await contract.methods.collectionNestingPermissions().call({from: owner})).to.be.like([['1', false], ['0', true]]);
-      await contract.methods.setCollectionNesting(false).send({from: owner});
+      await contract.methods['setCollectionNesting(bool)'](false).send({from: owner});
       expect(await contract.methods.collectionNestingPermissions().call({from: owner})).to.be.like([['1', false], ['0', false]]);
     });
 
     itEth('NFT: allows an Owner to nest/unnest their token (Restricted nesting)', async ({helper}) => {
       const owner = await helper.eth.createAccountWithBalance(donor);
 
-      const {collectionId: collectionIdA, collectionAddress: collectionAddressA, contract: contractA} = await createNestingCollection(helper, owner);
-      const {collectionAddress: collectionAddressB, contract: contractB} = await createNestingCollection(helper, owner);
-      await contractA.methods.setCollectionNesting(true, [collectionAddressA, collectionAddressB]).send({from: owner});
+      const {collectionId: collectionIdA, contract: contractA} = await createNestingCollection(helper, owner);
+      const {contract: contractB} = await createNestingCollection(helper, owner);
+      await contractA.methods.setCollectionNesting([true, false, [contractA.options.address, contractB.options.address]]).send({from: owner});
 
       // Create a token to nest into
       const mintingtargetNftTokenIdResult = await contractA.methods.mint(owner).send({from: owner});
@@ -101,7 +119,7 @@
       const owner = await helper.eth.createAccountWithBalance(donor);
 
       const {collectionId, contract} = await createNestingCollection(helper, owner);
-      await contract.methods.setCollectionNesting(false).send({from: owner});
+      await contract.methods.setCollectionNesting([false, false, []]).send({from: owner});
 
       // Create a token to nest into
       const mintingTargetTokenIdResult = await contract.methods.mint(owner).send({from: owner});
@@ -143,10 +161,10 @@
       const owner = await helper.eth.createAccountWithBalance(donor);
       const malignant = await helper.eth.createAccountWithBalance(donor);
 
-      const {collectionId: collectionIdA, collectionAddress: collectionAddressA, contract: contractA} = await createNestingCollection(helper, owner);
-      const {collectionAddress: collectionAddressB, contract: contractB} = await createNestingCollection(helper, owner);
+      const {collectionId: collectionIdA, contract: contractA} = await createNestingCollection(helper, owner);
+      const {collectionId: collectionIdB, contract: contractB} = await createNestingCollection(helper, owner);
 
-      await contractA.methods.setCollectionNesting(true, [collectionAddressA, collectionAddressB]).send({from: owner});
+      await contractA.methods.setCollectionNesting([true, false, [contractA.options.address, contractB.options.address]]).send({from: owner});
 
       // Create a token in one collection
       const mintingTokenIdAResult = await contractA.methods.mint(owner).send({from: owner});
@@ -166,10 +184,10 @@
     itEth('NFT: disallows to nest token in an unlisted collection', async ({helper}) => {
       const owner = await helper.eth.createAccountWithBalance(donor);
 
-      const {collectionId: collectionIdA, collectionAddress: collectionAddressA, contract: contractA} = await createNestingCollection(helper, owner);
+      const {collectionId: collectionIdA, contract: contractA} = await createNestingCollection(helper, owner);
       const {contract: contractB} = await createNestingCollection(helper, owner);
 
-      await contractA.methods.setCollectionNesting(true, [collectionAddressA]).send({from: owner});
+      await contractA.methods.setCollectionNesting([true, false, [contractA.options.address]]).send({from: owner});
 
       // Create a token in one collection
       const mintingTokenIdAResult = await contractA.methods.mint(owner).send({from: owner});
@@ -251,7 +269,7 @@
       itEth(`Disallow nest into collection without nesting permission [${testCase.mode}] (except for native fungible collection)`, async ({helper}) => {
         const owner = await helper.eth.createAccountWithBalance(donor);
         const {collectionId: targetCollectionId, contract: targetContract} = await createNestingCollection(helper, owner);
-        await targetContract.methods.setCollectionNesting(false).send({from: owner});
+        await targetContract.methods.setCollectionNesting([false, false, []]).send({from: owner});
 
         const {contract: ftContract} = await createFungibleCollection(helper, owner, testCase.mode);
 
modifiedtests/src/eth/tokenProperties.test.tsdiffbeforeafterboth
--- a/tests/src/eth/tokenProperties.test.ts
+++ b/tests/src/eth/tokenProperties.test.ts
@@ -20,7 +20,7 @@
 import {ITokenPropertyPermission} from '../util/playgrounds/types';
 import {Pallets} from '../util';
 import {UniqueNFTCollection, UniqueNFToken, UniqueRFTCollection} from '../util/playgrounds/unique';
-import {TokenPermissionField} from './util/playgrounds/types';
+import {CreateCollectionData, TokenPermissionField} from './util/playgrounds/types';
 
 describe('EVM token properties', () => {
   let donor: IKeyringPair;
@@ -41,7 +41,7 @@
       const owner = await helper.eth.createAccountWithBalance(donor);
       const caller = await helper.ethCrossAccount.createAccountWithBalance(donor);
       for(const [mutable,collectionAdmin, tokenOwner] of cartesian([], [false, true], [false, true], [false, true])) {
-        const {collectionId, collectionAddress} = await helper.eth.createCollection(testCase.mode, owner, 'A', 'B', 'C');
+        const {collectionId, collectionAddress} = await helper.eth.createCollection(owner, new CreateCollectionData('A', 'B', 'C', testCase.mode)).send();
         const collection = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, owner);
         await collection.methods.addCollectionAdminCross(caller).send({from: owner});
 
@@ -75,7 +75,7 @@
     itEth.ifWithPallets(`[${testCase.mode}] Can set multiple token property permissions as owner`, testCase.requiredPallets, async({helper}) => {
       const owner = await helper.eth.createAccountWithBalance(donor);
 
-      const {collectionId, collectionAddress} = await helper.eth.createCollection(testCase.mode, owner, 'A', 'B', 'C');
+      const {collectionId, collectionAddress} = await helper.eth.createCollection(owner, new CreateCollectionData('A', 'B', 'C', testCase.mode)).send();
       const collection = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, owner);
 
       await collection.methods.setTokenPropertyPermissions([
@@ -138,7 +138,7 @@
       const owner = await helper.eth.createAccountWithBalance(donor);
       const caller = await helper.ethCrossAccount.createAccountWithBalance(donor);
 
-      const {collectionId, collectionAddress} = await helper.eth.createCollection(testCase.mode, owner, 'A', 'B', 'C');
+      const {collectionId, collectionAddress} = await helper.eth.createCollection(owner, new CreateCollectionData('A', 'B', 'C', testCase.mode)).send();
       const collection = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, owner);
       await collection.methods.addCollectionAdminCross(caller).send({from: owner});
 
@@ -455,7 +455,7 @@
       const owner = await helper.eth.createAccountWithBalance(donor);
       const caller = await helper.eth.createAccountWithBalance(donor);
 
-      const {collectionAddress} = await helper.eth.createCollection(testCase.mode, owner, 'A', 'B', 'C');
+      const {collectionAddress} = await helper.eth.createCollection(owner, new CreateCollectionData('A', 'B', 'C', testCase.mode)).send();
       const collection = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, owner);
 
       await expect(collection.methods.setTokenPropertyPermissions([
@@ -474,7 +474,7 @@
     itEth.ifWithPallets(`[${testCase.mode}] Cannot set token property permissions with invalid character`, testCase.requiredPallets, async({helper}) => {
       const owner = await helper.eth.createAccountWithBalance(donor);
 
-      const {collectionAddress} = await helper.eth.createCollection(testCase.mode, owner, 'A', 'B', 'C');
+      const {collectionAddress} = await helper.eth.createCollection(owner, new CreateCollectionData('A', 'B', 'C', testCase.mode)).send();
       const collection = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, owner);
 
       await expect(collection.methods.setTokenPropertyPermissions([
@@ -494,7 +494,7 @@
     itEth.ifWithPallets(`[${testCase.mode}] Can reconfigure token property permissions to stricter ones`, testCase.requiredPallets, async({helper}) => {
       const owner = await helper.eth.createAccountWithBalance(donor);
 
-      const {collectionAddress, collectionId} = await helper.eth.createCollection(testCase.mode, owner, 'A', 'B', 'C');
+      const {collectionAddress, collectionId} = await helper.eth.createCollection(owner, new CreateCollectionData('A', 'B', 'C', testCase.mode)).send();
       const collection = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, owner);
 
       // 1. Owner sets strict property-permissions:
@@ -530,7 +530,7 @@
     itEth.ifWithPallets(`[${testCase.mode}] Cannot reconfigure token property permissions to less strict ones`, testCase.requiredPallets, async({helper}) => {
       const owner = await helper.eth.createAccountWithBalance(donor);
 
-      const {collectionAddress} = await helper.eth.createCollection(testCase.mode, owner, 'A', 'B', 'C');
+      const {collectionAddress} = await helper.eth.createCollection(owner, new CreateCollectionData('A', 'B', 'C', testCase.mode)).send();
       const collection = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, owner);
 
       // 1. Owner sets strict property-permissions:
modifiedtests/src/eth/tokens/callMethodsERC20.test.tsdiffbeforeafterboth
--- a/tests/src/eth/tokens/callMethodsERC20.test.ts
+++ b/tests/src/eth/tokens/callMethodsERC20.test.ts
@@ -17,6 +17,7 @@
 import {Pallets, requirePalletsOrSkip} from '../../util';
 import {expect, itEth, usingEthPlaygrounds} from '../util';
 import {IKeyringPair} from '@polkadot/types/types';
+import {CreateCollectionData} from '../util/playgrounds/types';
 
 [
   {mode: 'ft' as const, requiredPallets: []},
@@ -36,7 +37,7 @@
       const caller = await helper.eth.createAccountWithBalance(donor);
       const mintingParams = testCase.mode === 'ft' ? [caller, 200n] : [caller];
 
-      const {collection, collectionId} = await helper.eth.createCollection(testCase.mode, caller, 'TotalSupply', '6', '6');
+      const {collection, collectionId} = await helper.eth.createCollection(caller, new CreateCollectionData('TotalSupply', '6', '6', testCase.mode)).send();
       if(testCase.mode === 'rft') await collection.methods.mint(caller).send({from: caller});
 
       // Use collection contract for FT or token contract for RFT:
@@ -57,7 +58,7 @@
       const caller = await helper.eth.createAccountWithBalance(donor);
       const mintingParams = testCase.mode === 'ft' ? [caller, 200n] : [caller];
 
-      const {collection, collectionId} = await helper.eth.createCollection(testCase.mode, caller, 'BalanceOf', 'Descroption', 'Prefix');
+      const {collection, collectionId} = await helper.eth.createCollection(caller, new CreateCollectionData('BalanceOf', 'Descroption', 'Prefix', testCase.mode)).send();
       if(testCase.mode === 'rft') await collection.methods.mint(caller).send({from: caller});
 
       // Use collection contract for FT or token contract for RFT:
@@ -76,7 +77,7 @@
 
     itEth('decimals', async ({helper}) => {
       const caller = await helper.eth.createAccountWithBalance(donor);
-      const {collection, collectionId} = await helper.eth.createCollection(testCase.mode, caller, 'BalanceOf', 'Descroption', 'Prefix');
+      const {collection, collectionId} = await helper.eth.createCollection(caller, new CreateCollectionData('BalanceOf', 'Descroption', 'Prefix', testCase.mode)).send();
       if(testCase.mode === 'rft') await collection.methods.mint(caller).send({from: caller});
 
       // Use collection contract for FT or token contract for RFT:
modifiedtests/src/eth/tokens/callMethodsERC721.test.tsdiffbeforeafterboth
--- a/tests/src/eth/tokens/callMethodsERC721.test.ts
+++ b/tests/src/eth/tokens/callMethodsERC721.test.ts
@@ -17,6 +17,7 @@
 import {Pallets} from '../../util';
 import {expect, itEth, usingEthPlaygrounds} from '../util';
 import {IKeyringPair} from '@polkadot/types/types';
+import {CreateCollectionData} from '../util/playgrounds/types';
 
 
 describe('ERC-721 call methods', () => {
@@ -37,7 +38,7 @@
       const [callerSub] = await helper.arrange.createAccounts([100n], donor);
       const [name, description, tokenPrefix] = ['Name', 'Description', 'Symbol'];
 
-      const {collection: collectionEth} = await helper.eth.createCollection(testCase.mode, callerEth, name, description, tokenPrefix);
+      const {collection: collectionEth} = await helper.eth.createCollection(callerEth, new CreateCollectionData(name, description, tokenPrefix, testCase.mode)).send();
       await collectionEth.methods.mint(callerEth).send({from: callerEth});
       const {collectionId} = await helper[testCase.mode].mintCollection(callerSub, {name, description, tokenPrefix});
       const collectionSub = await helper.ethNativeContract.collectionById(collectionId, testCase.mode, callerEth);
@@ -60,7 +61,7 @@
     itEth.ifWithPallets(`${testCase.mode.toUpperCase()}: totalSupply`, testCase.requiredPallets, async ({helper}) => {
       const caller = await helper.eth.createAccountWithBalance(donor);
 
-      const {collection} = await helper.eth.createCollection(testCase.mode, caller, 'TotalSupply', '6', '6');
+      const {collection} = await helper.eth.createCollection(caller, new CreateCollectionData('TotalSupply', '6', '6', testCase.mode)).send();
       await collection.methods.mint(caller).send({from: caller});
 
       const totalSupply = await collection.methods.totalSupply().call();
@@ -75,7 +76,7 @@
     itEth.ifWithPallets(`${testCase.mode.toUpperCase()}: balanceOf`, testCase.requiredPallets, async ({helper}) => {
       const caller = await helper.eth.createAccountWithBalance(donor);
 
-      const {collection} = await helper.eth.createCollection(testCase.mode, caller, 'BalanceOf', 'Descroption', 'Prefix');
+      const {collection} = await helper.eth.createCollection(caller, new CreateCollectionData('BalanceOf', 'Descroption', 'Prefix', testCase.mode)).send();
       await collection.methods.mint(caller).send({from: caller});
       await collection.methods.mint(caller).send({from: caller});
       await collection.methods.mint(caller).send({from: caller});
@@ -91,7 +92,7 @@
   ].map(testCase => {
     itEth.ifWithPallets(`${testCase.mode.toUpperCase()}: ownerOf`, testCase.requiredPallets, async ({helper}) => {
       const caller = await helper.eth.createAccountWithBalance(donor);
-      const {collection} = await helper.eth.createCollection(testCase.mode, caller, 'OwnerOf', '6', '6');
+      const {collection} = await helper.eth.createCollection(caller, new CreateCollectionData('OwnerOf', '6', '6', testCase.mode)).send();
 
       const result = await collection.methods.mint(caller).send();
       const tokenId = result.events.Transfer.returnValues.tokenId;
@@ -108,7 +109,7 @@
     itEth.ifWithPallets(`${testCase.mode.toUpperCase()}: ownerOf after burn`, testCase.requiredPallets, async ({helper}) => {
       const caller = await helper.eth.createAccountWithBalance(donor);
       const receiver = helper.eth.createAccount();
-      const {collection, collectionId} = await helper.eth.createCollection(testCase.mode, caller, 'OwnerOf-AfterBurn', '6', '6');
+      const {collection, collectionId} = await helper.eth.createCollection(caller, new CreateCollectionData('OwnerOf-AfterBurn', '6', '6', testCase.mode)).send();
 
       const result = await collection.methods.mint(caller).send();
       const tokenId = result.events.Transfer.returnValues.tokenId;
modifiedtests/src/eth/tokens/minting.test.tsdiffbeforeafterboth
--- a/tests/src/eth/tokens/minting.test.ts
+++ b/tests/src/eth/tokens/minting.test.ts
@@ -17,6 +17,7 @@
 import {IKeyringPair} from '@polkadot/types/types';
 import {Pallets} from '../../util';
 import {expect, itEth, usingEthPlaygrounds} from '../util';
+import {CreateCollectionData} from '../util/playgrounds/types';
 
 
 describe('Minting tokens', () => {
@@ -78,7 +79,7 @@
       const receiver = helper.eth.createAccount();
       const mintingParams = testCase.mode === 'ft' ? [receiver, 100] : [receiver];
 
-      const {collection, collectionAddress, collectionId} = await helper.eth.createCollection(testCase.mode, owner, 'Name', 'Desc', 'Prefix');
+      const {collection, collectionAddress, collectionId} = await helper.eth.createCollection(owner, new CreateCollectionData('Name', 'Desc', 'Prefix', testCase.mode)).send();
 
       const result = await collection.methods.mint(...mintingParams).send({from: owner});
 
@@ -112,7 +113,7 @@
       const receiver = helper.eth.createAccount();
       const mintingParams = testCase.mode === 'ft' ? [receiver, 100] : [receiver];
 
-      const {collection, collectionAddress, collectionId} = await helper.eth.createCollection(testCase.mode, owner, 'Name', 'Desc', 'Prefix');
+      const {collection, collectionAddress, collectionId} = await helper.eth.createCollection(owner, new CreateCollectionData('Name', 'Desc', 'Prefix', testCase.mode)).send();
 
       const result = await collection.methods.mint(...mintingParams).send({from: owner});
 
modifiedtests/src/eth/util/playgrounds/types.tsdiffbeforeafterboth
--- a/tests/src/eth/util/playgrounds/types.ts
+++ b/tests/src/eth/util/playgrounds/types.ts
@@ -1,3 +1,5 @@
+import {CollectionFlag, TCollectionMode} from '../../../util/playgrounds/types';
+
 export interface ContractImports {
   solPath: string;
   fsPath: string;
@@ -19,8 +21,10 @@
   value: bigint,
 }
 
+export type EthAddress = string;
+
 export interface CrossAddress {
-  readonly eth: string,
+  readonly eth: EthAddress,
   readonly sub: string | Uint8Array,
 }
 
@@ -48,3 +52,81 @@
   field: CollectionLimitField,
   value: OptionUint,
 }
+
+export interface CollectionLimitValue {
+  field: CollectionLimitField,
+  value: bigint,
+}
+
+export enum CollectionMode {
+	Fungible,
+	Nonfungible,
+	Refungible,
+}
+
+export interface PropertyPermission {
+  code: TokenPermissionField,
+  value: boolean,
+}
+export interface TokenPropertyPermission {
+  key: string,
+  permissions: PropertyPermission[],
+}
+export interface CollectionNestingAndPermission {
+  token_owner: boolean,
+  collection_admin: boolean,
+  restricted: string[],
+}
+
+export const emptyAddress: [string, string] = [
+  '0x0000000000000000000000000000000000000000',
+  '0',
+];
+
+export const CREATE_COLLECTION_DATA_DEFAULTS = {
+  decimals: 0,
+  properties: [],
+  tokenPropertyPermissions: [],
+  adminList: [],
+  nestingSettings: {token_owner: false, collection_admin: false, restricted: []},
+  limits: [],
+  pendingSponsor: emptyAddress,
+  flags: 0,
+};
+
+export interface Property {
+  key: string;
+  value: Buffer;
+}
+
+export class CreateCollectionData {
+  name: string;
+  description: string;
+  tokenPrefix: string;
+  collectionMode: TCollectionMode;
+  decimals? = 0;
+  properties?: Property[] = [];
+  tokenPropertyPermissions?: TokenPropertyPermission[] = [];
+  adminList?: CrossAddress[] = [];
+  nestingSettings?: CollectionNestingAndPermission = {token_owner: false, collection_admin: false, restricted: []};
+  limits?: CollectionLimitValue[] = [];
+  pendingSponsor?: [string, string] = emptyAddress;
+  flags?: number | CollectionFlag[] = [0];
+
+  constructor(
+    name: string,
+    description: string,
+    tokenPrefix: string,
+    collectionMode: TCollectionMode,
+    decimals = 18,
+  ) {
+    this.name = name;
+    this.description = description;
+    this.tokenPrefix = tokenPrefix;
+    this.collectionMode = collectionMode;
+    if(collectionMode == 'ft')
+      this.decimals = decimals;
+    else
+      this.decimals = 0;
+  }
+}
\ No newline at end of file
modifiedtests/src/eth/util/playgrounds/unique.dev.tsdiffbeforeafterboth
--- a/tests/src/eth/util/playgrounds/unique.dev.ts
+++ b/tests/src/eth/util/playgrounds/unique.dev.ts
@@ -18,7 +18,7 @@
 
 import {ArrangeGroup, DevUniqueHelper} from '../../../util/playgrounds/unique.dev';
 
-import {ContractImports, CompiledContract, CrossAddress, NormalizedEvent, EthProperty} from './types';
+import {ContractImports, CompiledContract, CrossAddress, NormalizedEvent, EthProperty, CollectionMode, CreateCollectionData} from './types';
 
 // Native contracts ABI
 import collectionHelpersAbi from '../../abi/collectionHelpers.json' assert {type: 'json'};
@@ -50,7 +50,6 @@
   }
 }
 
-
 class ContractGroup extends EthGroupBase {
   async findImports(imports?: ContractImports[]) {
     if(!imports) return function(path: string) {
@@ -181,7 +180,84 @@
   }
 }
 
+class CreateCollectionTransaction {
+  signer: string;
+  data: CreateCollectionData;
+  mergeDeprecated: boolean;
+  helper: EthUniqueHelper;
+
+  constructor(helper: EthUniqueHelper, signer: string, data: CreateCollectionData, mergeDeprecated = false) {
+    this.helper = helper;
+    this.signer = signer;
+
+    let flags = 0;
+    // convert CollectionFlags to number and join them in one number
+    if(!data.flags || typeof data.flags == 'number') {
+      flags = data.flags ?? 0;
+    } else {
+      for(let i = 0; i < data.flags.length; i++){
+        const flag = data.flags[i];
+        flags = flags | flag;
+      }
+    }
+    data.flags = flags;
+
+    this.data = data;
+    this.mergeDeprecated = mergeDeprecated;
+  }
+
+  private async createTransaction() {
+    const collectionHelper = await this.helper.ethNativeContract.collectionHelpers(this.signer);
+    let collectionMode;
+    switch (this.data.collectionMode) {
+      case 'nft': collectionMode = CollectionMode.Nonfungible; break;
+      case 'rft': collectionMode = CollectionMode.Refungible; break;
+      case 'ft': collectionMode = CollectionMode.Fungible; break;
+    }
+
+    const tx = collectionHelper.methods.createCollection([
+      this.data.pendingSponsor,
+      this.data.name,
+      this.data.description,
+      this.data.tokenPrefix,
+      collectionMode,
+      this.data.decimals,
+      this.data.properties,
+      this.data.tokenPropertyPermissions,
+      this.data.adminList,
+      this.data.nestingSettings,
+      this.data.limits,
+      this.data.flags,
+    ]);
+    return tx;
+  }
+
+  async send(options?: any): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[], collection: Contract }> {
+    const collectionCreationPrice = {
+      value: Number(this.helper.balance.getCollectionCreationPrice()),
+    };
+    const tx = await this.createTransaction();
+    const result = await tx.send({...options, ...collectionCreationPrice});
 
+    const collectionAddress = this.helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
+    const collectionId = this.helper.ethAddress.extractCollectionId(collectionAddress);
+    const events = this.helper.eth.normalizeEvents(result.events);
+    const collection = await this.helper.ethNativeContract.collectionById(collectionId, this.data.collectionMode, this.signer, this.mergeDeprecated);
+
+    return {collectionId, collectionAddress, events, collection};
+  }
+
+  async call(options?: any) {
+    const collectionCreationPrice = {
+      value: Number(this.helper.balance.getCollectionCreationPrice()),
+    };
+    const tx = await this.createTransaction();
+
+    return await tx.call({...options, ...collectionCreationPrice});
+  }
+}
+
+
 class EthGroup extends EthGroupBase {
   DEFAULT_GAS = 2_500_000;
 
@@ -236,30 +312,28 @@
     }
   }
 
-  async createCollection(mode: TCollectionMode, signer: string, name: string, description: string, tokenPrefix: string, decimals = 18, mergeDeprecated = false): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[], collection: Contract }> {
-    const collectionCreationPrice = this.helper.balance.getCollectionCreationPrice();
+  createCollection(signer: string, data: CreateCollectionData, mergeDeprecated = false): CreateCollectionTransaction {
+    return new CreateCollectionTransaction(this.helper, signer, data, mergeDeprecated);
+  }
+
+  createNFTCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {
+    return this.createCollection(signer, new CreateCollectionData(name, description, tokenPrefix, 'nft')).send();
+  }
+
+  async createERC721MetadataCompatibleCollection(signer: string, data: CreateCollectionData, baseUri: string): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {
     const collectionHelper = await this.helper.ethNativeContract.collectionHelpers(signer);
-    const functionName: string = this.createCollectionMethodName(mode);
-
-    const functionParams = mode === 'ft' ? [name, decimals, description, tokenPrefix] : [name, description, tokenPrefix];
-    const result = await collectionHelper.methods[functionName](...functionParams).send({value: Number(collectionCreationPrice)});
 
-    const collectionAddress = this.helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
-    const collectionId = this.helper.ethAddress.extractCollectionId(collectionAddress);
-    const events = this.helper.eth.normalizeEvents(result.events);
-    const collection = await this.helper.ethNativeContract.collectionById(collectionId, mode, signer, mergeDeprecated);
+    const {collectionId, collectionAddress, events} = await this.createCollection(signer, data).send();
 
-    return {collectionId, collectionAddress, events, collection};
-  }
+    await collectionHelper.methods.makeCollectionERC721MetadataCompatible(collectionAddress, baseUri).send();
 
-  createNFTCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {
-    return this.createCollection('nft', signer, name, description, tokenPrefix);
+    return {collectionId, collectionAddress, events};
   }
 
   async createERC721MetadataCompatibleNFTCollection(signer: string, name: string, description: string, tokenPrefix: string, baseUri: string): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {
     const collectionHelper = await this.helper.ethNativeContract.collectionHelpers(signer);
 
-    const {collectionId, collectionAddress, events} = await this.createCollection('nft', signer, name, description, tokenPrefix);
+    const {collectionId, collectionAddress, events} = await this.createCollection(signer, new CreateCollectionData(name, description, tokenPrefix, 'nft')).send();
 
     await collectionHelper.methods.makeCollectionERC721MetadataCompatible(collectionAddress, baseUri).send();
 
@@ -267,17 +341,17 @@
   }
 
   createRFTCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {
-    return this.createCollection('rft', signer, name, description, tokenPrefix);
+    return this.createCollection(signer, new CreateCollectionData(name, description, tokenPrefix, 'rft')).send();
   }
 
   createFungibleCollection(signer: string, name: string, decimals: number, description: string, tokenPrefix: string): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {
-    return this.createCollection('ft', signer, name, description, tokenPrefix, decimals);
+    return this.createCollection(signer, new CreateCollectionData(name, description, tokenPrefix, 'ft')).send();
   }
 
   async createERC721MetadataCompatibleRFTCollection(signer: string, name: string, description: string, tokenPrefix: string, baseUri: string): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {
     const collectionHelper = await this.helper.ethNativeContract.collectionHelpers(signer);
 
-    const {collectionId, collectionAddress, events} = await this.createCollection('rft', signer, name, description, tokenPrefix);
+    const {collectionId, collectionAddress, events} = await this.createCollection(signer, new CreateCollectionData(name, description, tokenPrefix, 'rft')).send();
 
     await collectionHelper.methods.makeCollectionERC721MetadataCompatible(collectionAddress, baseUri).send();
 
@@ -432,6 +506,13 @@
     };
   }
 
+  fromAddr(address: TEthereumAccount): [string, string] {
+    return [
+      address,
+      '0',
+    ];
+  }
+
   fromKeyringPair(keyring: IKeyringPair): CrossAddress {
     return {
       eth: '0x0000000000000000000000000000000000000000',
modifiedtests/src/interfaces/augment-api-tx.tsdiffbeforeafterboth
--- a/tests/src/interfaces/augment-api-tx.ts
+++ b/tests/src/interfaces/augment-api-tx.ts
@@ -1499,7 +1499,7 @@
        * 
        * * `data`: Explicit data of a collection used for its creation.
        **/
-      createCollectionEx: AugmentedSubmittable<(data: UpDataStructsCreateCollectionData | { mode?: any; access?: any; name?: any; description?: any; tokenPrefix?: any; pendingSponsor?: any; limits?: any; permissions?: any; tokenPropertyPermissions?: any; properties?: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [UpDataStructsCreateCollectionData]>;
+      createCollectionEx: AugmentedSubmittable<(data: UpDataStructsCreateCollectionData | { mode?: any; access?: any; name?: any; description?: any; tokenPrefix?: any; limits?: any; permissions?: any; tokenPropertyPermissions?: any; properties?: any; adminList?: any; pendingSponsor?: any; flags?: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [UpDataStructsCreateCollectionData]>;
       /**
        * Mint an item within a collection.
        * 
modifiedtests/src/interfaces/augment-types.tsdiffbeforeafterboth
--- a/tests/src/interfaces/augment-types.ts
+++ b/tests/src/interfaces/augment-types.ts
@@ -25,7 +25,7 @@
 import type { CollectiveOrigin, MemberCount, ProposalIndex, Votes, VotesTo230 } from '@polkadot/types/interfaces/collective';
 import type { AuthorityId, RawVRFOutput } from '@polkadot/types/interfaces/consensus';
 import type { AliveContractInfo, CodeHash, CodeSource, CodeUploadRequest, CodeUploadResult, CodeUploadResultValue, ContractCallFlags, ContractCallRequest, ContractExecResult, ContractExecResultOk, ContractExecResultResult, ContractExecResultSuccessTo255, ContractExecResultSuccessTo260, ContractExecResultTo255, ContractExecResultTo260, ContractExecResultTo267, ContractExecResultU64, ContractInfo, ContractInstantiateResult, ContractInstantiateResultTo267, ContractInstantiateResultTo299, ContractInstantiateResultU64, ContractReturnFlags, ContractStorageKey, DeletedContract, ExecReturnValue, Gas, HostFnWeights, HostFnWeightsTo264, InstantiateRequest, InstantiateRequestV1, InstantiateRequestV2, InstantiateReturnValue, InstantiateReturnValueOk, InstantiateReturnValueTo267, InstructionWeights, Limits, LimitsTo264, PrefabWasmModule, RentProjection, Schedule, ScheduleTo212, ScheduleTo258, ScheduleTo264, SeedOf, StorageDeposit, TombstoneContractInfo, TrieId } from '@polkadot/types/interfaces/contracts';
-import type { ContractConstructorSpecLatest, ContractConstructorSpecV0, ContractConstructorSpecV1, ContractConstructorSpecV2, ContractConstructorSpecV3, ContractConstructorSpecV4, ContractContractSpecV0, ContractContractSpecV1, ContractContractSpecV2, ContractContractSpecV3, ContractContractSpecV4, ContractCryptoHasher, ContractDiscriminant, ContractDisplayName, ContractEnvironmentV4, ContractEventParamSpecLatest, ContractEventParamSpecV0, ContractEventParamSpecV2, ContractEventSpecLatest, ContractEventSpecV0, ContractEventSpecV1, ContractEventSpecV2, ContractLayoutArray, ContractLayoutCell, ContractLayoutEnum, ContractLayoutHash, ContractLayoutHashingStrategy, ContractLayoutKey, ContractLayoutStruct, ContractLayoutStructField, ContractMessageParamSpecLatest, ContractMessageParamSpecV0, ContractMessageParamSpecV2, ContractMessageSpecLatest, ContractMessageSpecV0, ContractMessageSpecV1, ContractMessageSpecV2, ContractMessageSpecV3, ContractMetadata, ContractMetadataLatest, ContractMetadataV0, ContractMetadataV1, ContractMetadataV2, ContractMetadataV3, ContractMetadataV4, ContractProject, ContractProjectContract, ContractProjectInfo, ContractProjectSource, ContractProjectV0, ContractSelector, ContractStorageLayout, ContractTypeSpec } from '@polkadot/types/interfaces/contractsAbi';
+import type { ContractConstructorSpecLatest, ContractConstructorSpecV0, ContractConstructorSpecV1, ContractConstructorSpecV2, ContractConstructorSpecV3, ContractContractSpecV0, ContractContractSpecV1, ContractContractSpecV2, ContractContractSpecV3, ContractContractSpecV4, ContractCryptoHasher, ContractDiscriminant, ContractDisplayName, ContractEventParamSpecLatest, ContractEventParamSpecV0, ContractEventParamSpecV2, ContractEventSpecLatest, ContractEventSpecV0, ContractEventSpecV1, ContractEventSpecV2, ContractLayoutArray, ContractLayoutCell, ContractLayoutEnum, ContractLayoutHash, ContractLayoutHashingStrategy, ContractLayoutKey, ContractLayoutStruct, ContractLayoutStructField, ContractMessageParamSpecLatest, ContractMessageParamSpecV0, ContractMessageParamSpecV2, ContractMessageSpecLatest, ContractMessageSpecV0, ContractMessageSpecV1, ContractMessageSpecV2, ContractMetadata, ContractMetadataLatest, ContractMetadataV0, ContractMetadataV1, ContractMetadataV2, ContractMetadataV3, ContractMetadataV4, ContractProject, ContractProjectContract, ContractProjectInfo, ContractProjectSource, ContractProjectV0, ContractSelector, ContractStorageLayout, ContractTypeSpec } from '@polkadot/types/interfaces/contractsAbi';
 import type { FundIndex, FundInfo, LastContribution, TrieIndex } from '@polkadot/types/interfaces/crowdloan';
 import type { CollationInfo, CollationInfoV1, ConfigData, MessageId, OverweightIndex, PageCounter, PageIndexData } from '@polkadot/types/interfaces/cumulus';
 import type { AccountVote, AccountVoteSplit, AccountVoteStandard, Conviction, Delegations, PreimageStatus, PreimageStatusAvailable, PriorLock, PropIndex, Proposal, ProxyState, ReferendumIndex, ReferendumInfo, ReferendumInfoFinished, ReferendumInfoTo239, ReferendumStatus, Tally, Voting, VotingDelegating, VotingDirect, VotingDirectVote } from '@polkadot/types/interfaces/democracy';
@@ -254,7 +254,6 @@
     ContractConstructorSpecV1: ContractConstructorSpecV1;
     ContractConstructorSpecV2: ContractConstructorSpecV2;
     ContractConstructorSpecV3: ContractConstructorSpecV3;
-    ContractConstructorSpecV4: ContractConstructorSpecV4;
     ContractContractSpecV0: ContractContractSpecV0;
     ContractContractSpecV1: ContractContractSpecV1;
     ContractContractSpecV2: ContractContractSpecV2;
@@ -263,7 +262,6 @@
     ContractCryptoHasher: ContractCryptoHasher;
     ContractDiscriminant: ContractDiscriminant;
     ContractDisplayName: ContractDisplayName;
-    ContractEnvironmentV4: ContractEnvironmentV4;
     ContractEventParamSpecLatest: ContractEventParamSpecLatest;
     ContractEventParamSpecV0: ContractEventParamSpecV0;
     ContractEventParamSpecV2: ContractEventParamSpecV2;
@@ -300,7 +298,6 @@
     ContractMessageSpecV0: ContractMessageSpecV0;
     ContractMessageSpecV1: ContractMessageSpecV1;
     ContractMessageSpecV2: ContractMessageSpecV2;
-    ContractMessageSpecV3: ContractMessageSpecV3;
     ContractMetadata: ContractMetadata;
     ContractMetadataLatest: ContractMetadataLatest;
     ContractMetadataV0: ContractMetadataV0;
modifiedtests/src/interfaces/default/types.tsdiffbeforeafterboth
--- a/tests/src/interfaces/default/types.ts
+++ b/tests/src/interfaces/default/types.ts
@@ -3221,11 +3221,13 @@
   readonly name: Vec<u16>;
   readonly description: Vec<u16>;
   readonly tokenPrefix: Bytes;
-  readonly pendingSponsor: Option<AccountId32>;
   readonly limits: Option<UpDataStructsCollectionLimits>;
   readonly permissions: Option<UpDataStructsCollectionPermissions>;
   readonly tokenPropertyPermissions: Vec<UpDataStructsPropertyKeyPermission>;
   readonly properties: Vec<UpDataStructsProperty>;
+  readonly adminList: Vec<PalletEvmAccountBasicCrossAccountIdRepr>;
+  readonly pendingSponsor: Option<PalletEvmAccountBasicCrossAccountIdRepr>;
+  readonly flags: U8aFixed;
 }
 
 /** @name UpDataStructsCreateFungibleData */
modifiedtests/src/interfaces/lookup.tsdiffbeforeafterboth
--- a/tests/src/interfaces/lookup.ts
+++ b/tests/src/interfaces/lookup.ts
@@ -2904,7 +2904,7 @@
     }
   },
   /**
-   * Lookup335: up_data_structs::CreateCollectionData<sp_core::crypto::AccountId32>
+   * Lookup335: up_data_structs::CreateCollectionData<pallet_evm::account::BasicCrossAccountIdRepr<sp_core::crypto::AccountId32>>
    **/
   UpDataStructsCreateCollectionData: {
     mode: 'UpDataStructsCollectionMode',
@@ -2912,11 +2912,13 @@
     name: 'Vec<u16>',
     description: 'Vec<u16>',
     tokenPrefix: 'Bytes',
-    pendingSponsor: 'Option<AccountId32>',
     limits: 'Option<UpDataStructsCollectionLimits>',
     permissions: 'Option<UpDataStructsCollectionPermissions>',
     tokenPropertyPermissions: 'Vec<UpDataStructsPropertyKeyPermission>',
-    properties: 'Vec<UpDataStructsProperty>'
+    properties: 'Vec<UpDataStructsProperty>',
+    adminList: 'Vec<PalletEvmAccountBasicCrossAccountIdRepr>',
+    pendingSponsor: 'Option<PalletEvmAccountBasicCrossAccountIdRepr>',
+    flags: '[u8;1]'
   },
   /**
    * Lookup337: up_data_structs::AccessMode
@@ -2990,7 +2992,7 @@
     value: 'Bytes'
   },
   /**
-   * Lookup360: up_data_structs::CreateItemData
+   * Lookup362: up_data_structs::CreateItemData
    **/
   UpDataStructsCreateItemData: {
     _enum: {
@@ -3000,26 +3002,26 @@
     }
   },
   /**
-   * Lookup361: up_data_structs::CreateNftData
+   * Lookup363: up_data_structs::CreateNftData
    **/
   UpDataStructsCreateNftData: {
     properties: 'Vec<UpDataStructsProperty>'
   },
   /**
-   * Lookup362: up_data_structs::CreateFungibleData
+   * Lookup364: up_data_structs::CreateFungibleData
    **/
   UpDataStructsCreateFungibleData: {
     value: 'u128'
   },
   /**
-   * Lookup363: up_data_structs::CreateReFungibleData
+   * Lookup365: up_data_structs::CreateReFungibleData
    **/
   UpDataStructsCreateReFungibleData: {
     pieces: 'u128',
     properties: 'Vec<UpDataStructsProperty>'
   },
   /**
-   * Lookup366: up_data_structs::CreateItemExData<pallet_evm::account::BasicCrossAccountIdRepr<sp_core::crypto::AccountId32>>
+   * Lookup368: up_data_structs::CreateItemExData<pallet_evm::account::BasicCrossAccountIdRepr<sp_core::crypto::AccountId32>>
    **/
   UpDataStructsCreateItemExData: {
     _enum: {
@@ -3030,14 +3032,14 @@
     }
   },
   /**
-   * Lookup368: up_data_structs::CreateNftExData<pallet_evm::account::BasicCrossAccountIdRepr<sp_core::crypto::AccountId32>>
+   * Lookup370: up_data_structs::CreateNftExData<pallet_evm::account::BasicCrossAccountIdRepr<sp_core::crypto::AccountId32>>
    **/
   UpDataStructsCreateNftExData: {
     properties: 'Vec<UpDataStructsProperty>',
     owner: 'PalletEvmAccountBasicCrossAccountIdRepr'
   },
   /**
-   * Lookup375: up_data_structs::CreateRefungibleExSingleOwner<pallet_evm::account::BasicCrossAccountIdRepr<sp_core::crypto::AccountId32>>
+   * Lookup377: up_data_structs::CreateRefungibleExSingleOwner<pallet_evm::account::BasicCrossAccountIdRepr<sp_core::crypto::AccountId32>>
    **/
   UpDataStructsCreateRefungibleExSingleOwner: {
     user: 'PalletEvmAccountBasicCrossAccountIdRepr',
@@ -3045,14 +3047,14 @@
     properties: 'Vec<UpDataStructsProperty>'
   },
   /**
-   * Lookup377: up_data_structs::CreateRefungibleExMultipleOwners<pallet_evm::account::BasicCrossAccountIdRepr<sp_core::crypto::AccountId32>>
+   * Lookup379: up_data_structs::CreateRefungibleExMultipleOwners<pallet_evm::account::BasicCrossAccountIdRepr<sp_core::crypto::AccountId32>>
    **/
   UpDataStructsCreateRefungibleExMultipleOwners: {
     users: 'BTreeMap<PalletEvmAccountBasicCrossAccountIdRepr, u128>',
     properties: 'Vec<UpDataStructsProperty>'
   },
   /**
-   * Lookup378: pallet_configuration::pallet::Call<T>
+   * Lookup380: pallet_configuration::pallet::Call<T>
    **/
   PalletConfigurationCall: {
     _enum: {
@@ -3078,7 +3080,7 @@
     }
   },
   /**
-   * Lookup380: pallet_configuration::AppPromotionConfiguration<BlockNumber>
+   * Lookup382: pallet_configuration::AppPromotionConfiguration<BlockNumber>
    **/
   PalletConfigurationAppPromotionConfiguration: {
     recalculationInterval: 'Option<u32>',
@@ -3087,11 +3089,11 @@
     maxStakersPerCalculation: 'Option<u8>'
   },
   /**
-   * Lookup384: pallet_structure::pallet::Call<T>
+   * Lookup386: pallet_structure::pallet::Call<T>
    **/
   PalletStructureCall: 'Null',
   /**
-   * Lookup385: pallet_app_promotion::pallet::Call<T>
+   * Lookup387: pallet_app_promotion::pallet::Call<T>
    **/
   PalletAppPromotionCall: {
     _enum: {
@@ -3126,7 +3128,7 @@
     }
   },
   /**
-   * Lookup386: pallet_foreign_assets::module::Call<T>
+   * Lookup388: pallet_foreign_assets::module::Call<T>
    **/
   PalletForeignAssetsModuleCall: {
     _enum: {
@@ -3143,7 +3145,7 @@
     }
   },
   /**
-   * Lookup387: pallet_evm::pallet::Call<T>
+   * Lookup389: pallet_evm::pallet::Call<T>
    **/
   PalletEvmCall: {
     _enum: {
@@ -3186,7 +3188,7 @@
     }
   },
   /**
-   * Lookup393: pallet_ethereum::pallet::Call<T>
+   * Lookup395: pallet_ethereum::pallet::Call<T>
    **/
   PalletEthereumCall: {
     _enum: {
@@ -3196,7 +3198,7 @@
     }
   },
   /**
-   * Lookup394: ethereum::transaction::TransactionV2
+   * Lookup396: ethereum::transaction::TransactionV2
    **/
   EthereumTransactionTransactionV2: {
     _enum: {
@@ -3206,7 +3208,7 @@
     }
   },
   /**
-   * Lookup395: ethereum::transaction::LegacyTransaction
+   * Lookup397: ethereum::transaction::LegacyTransaction
    **/
   EthereumTransactionLegacyTransaction: {
     nonce: 'U256',
@@ -3218,7 +3220,7 @@
     signature: 'EthereumTransactionTransactionSignature'
   },
   /**
-   * Lookup396: ethereum::transaction::TransactionAction
+   * Lookup398: ethereum::transaction::TransactionAction
    **/
   EthereumTransactionTransactionAction: {
     _enum: {
@@ -3227,7 +3229,7 @@
     }
   },
   /**
-   * Lookup397: ethereum::transaction::TransactionSignature
+   * Lookup399: ethereum::transaction::TransactionSignature
    **/
   EthereumTransactionTransactionSignature: {
     v: 'u64',
@@ -3235,7 +3237,7 @@
     s: 'H256'
   },
   /**
-   * Lookup399: ethereum::transaction::EIP2930Transaction
+   * Lookup401: ethereum::transaction::EIP2930Transaction
    **/
   EthereumTransactionEip2930Transaction: {
     chainId: 'u64',
@@ -3251,14 +3253,14 @@
     s: 'H256'
   },
   /**
-   * Lookup401: ethereum::transaction::AccessListItem
+   * Lookup403: ethereum::transaction::AccessListItem
    **/
   EthereumTransactionAccessListItem: {
     address: 'H160',
     storageKeys: 'Vec<H256>'
   },
   /**
-   * Lookup402: ethereum::transaction::EIP1559Transaction
+   * Lookup404: ethereum::transaction::EIP1559Transaction
    **/
   EthereumTransactionEip1559Transaction: {
     chainId: 'u64',
@@ -3275,7 +3277,7 @@
     s: 'H256'
   },
   /**
-   * Lookup403: pallet_evm_contract_helpers::pallet::Call<T>
+   * Lookup405: pallet_evm_contract_helpers::pallet::Call<T>
    **/
   PalletEvmContractHelpersCall: {
     _enum: {
@@ -3285,7 +3287,7 @@
     }
   },
   /**
-   * Lookup405: pallet_evm_migration::pallet::Call<T>
+   * Lookup407: pallet_evm_migration::pallet::Call<T>
    **/
   PalletEvmMigrationCall: {
     _enum: {
@@ -3310,7 +3312,7 @@
     }
   },
   /**
-   * Lookup409: pallet_maintenance::pallet::Call<T>
+   * Lookup411: pallet_maintenance::pallet::Call<T>
    **/
   PalletMaintenanceCall: {
     _enum: {
@@ -3326,7 +3328,7 @@
     }
   },
   /**
-   * Lookup410: pallet_test_utils::pallet::Call<T>
+   * Lookup412: pallet_test_utils::pallet::Call<T>
    **/
   PalletTestUtilsCall: {
     _enum: {
@@ -3345,32 +3347,32 @@
     }
   },
   /**
-   * Lookup412: pallet_sudo::pallet::Error<T>
+   * Lookup414: pallet_sudo::pallet::Error<T>
    **/
   PalletSudoError: {
     _enum: ['RequireSudo']
   },
   /**
-   * Lookup414: orml_vesting::module::Error<T>
+   * Lookup416: orml_vesting::module::Error<T>
    **/
   OrmlVestingModuleError: {
     _enum: ['ZeroVestingPeriod', 'ZeroVestingPeriodCount', 'InsufficientBalanceToLock', 'TooManyVestingSchedules', 'AmountLow', 'MaxVestingSchedulesExceeded']
   },
   /**
-   * Lookup415: orml_xtokens::module::Error<T>
+   * Lookup417: orml_xtokens::module::Error<T>
    **/
   OrmlXtokensModuleError: {
     _enum: ['AssetHasNoReserve', 'NotCrossChainTransfer', 'InvalidDest', 'NotCrossChainTransferableCurrency', 'UnweighableMessage', 'XcmExecutionFailed', 'CannotReanchor', 'InvalidAncestry', 'InvalidAsset', 'DestinationNotInvertible', 'BadVersion', 'DistinctReserveForAssetAndFee', 'ZeroFee', 'ZeroAmount', 'TooManyAssetsBeingSent', 'AssetIndexNonExistent', 'FeeNotEnough', 'NotSupportedMultiLocation', 'MinXcmFeeNotDefined']
   },
   /**
-   * Lookup418: orml_tokens::BalanceLock<Balance>
+   * Lookup420: orml_tokens::BalanceLock<Balance>
    **/
   OrmlTokensBalanceLock: {
     id: '[u8;8]',
     amount: 'u128'
   },
   /**
-   * Lookup420: orml_tokens::AccountData<Balance>
+   * Lookup422: orml_tokens::AccountData<Balance>
    **/
   OrmlTokensAccountData: {
     free: 'u128',
@@ -3378,20 +3380,20 @@
     frozen: 'u128'
   },
   /**
-   * Lookup422: orml_tokens::ReserveData<ReserveIdentifier, Balance>
+   * Lookup424: orml_tokens::ReserveData<ReserveIdentifier, Balance>
    **/
   OrmlTokensReserveData: {
     id: 'Null',
     amount: 'u128'
   },
   /**
-   * Lookup424: orml_tokens::module::Error<T>
+   * Lookup426: orml_tokens::module::Error<T>
    **/
   OrmlTokensModuleError: {
     _enum: ['BalanceTooLow', 'AmountIntoBalanceFailed', 'LiquidityRestrictions', 'MaxLocksExceeded', 'KeepAlive', 'ExistentialDeposit', 'DeadAccount', 'TooManyReserves']
   },
   /**
-   * Lookup429: pallet_identity::types::RegistrarInfo<Balance, sp_core::crypto::AccountId32>
+   * Lookup431: pallet_identity::types::RegistrarInfo<Balance, sp_core::crypto::AccountId32>
    **/
   PalletIdentityRegistrarInfo: {
     account: 'AccountId32',
@@ -3399,13 +3401,13 @@
     fields: 'PalletIdentityBitFlags'
   },
   /**
-   * Lookup431: pallet_identity::pallet::Error<T>
+   * Lookup433: pallet_identity::pallet::Error<T>
    **/
   PalletIdentityError: {
     _enum: ['TooManySubAccounts', 'NotFound', 'NotNamed', 'EmptyIndex', 'FeeChanged', 'NoIdentity', 'StickyJudgement', 'JudgementGiven', 'InvalidJudgement', 'InvalidIndex', 'InvalidTarget', 'TooManyFields', 'TooManyRegistrars', 'AlreadyClaimed', 'NotSub', 'NotOwned', 'JudgementForDifferentIdentity', 'JudgementPaymentFailed']
   },
   /**
-   * Lookup432: pallet_preimage::RequestStatus<sp_core::crypto::AccountId32, Balance>
+   * Lookup434: pallet_preimage::RequestStatus<sp_core::crypto::AccountId32, Balance>
    **/
   PalletPreimageRequestStatus: {
     _enum: {
@@ -3421,13 +3423,13 @@
     }
   },
   /**
-   * Lookup437: pallet_preimage::pallet::Error<T>
+   * Lookup439: pallet_preimage::pallet::Error<T>
    **/
   PalletPreimageError: {
     _enum: ['TooBig', 'AlreadyNoted', 'NotAuthorized', 'NotNoted', 'Requested', 'NotRequested']
   },
   /**
-   * Lookup439: cumulus_pallet_xcmp_queue::InboundChannelDetails
+   * Lookup441: cumulus_pallet_xcmp_queue::InboundChannelDetails
    **/
   CumulusPalletXcmpQueueInboundChannelDetails: {
     sender: 'u32',
@@ -3435,19 +3437,19 @@
     messageMetadata: 'Vec<(u32,PolkadotParachainPrimitivesXcmpMessageFormat)>'
   },
   /**
-   * Lookup440: cumulus_pallet_xcmp_queue::InboundState
+   * Lookup442: cumulus_pallet_xcmp_queue::InboundState
    **/
   CumulusPalletXcmpQueueInboundState: {
     _enum: ['Ok', 'Suspended']
   },
   /**
-   * Lookup443: polkadot_parachain::primitives::XcmpMessageFormat
+   * Lookup445: polkadot_parachain::primitives::XcmpMessageFormat
    **/
   PolkadotParachainPrimitivesXcmpMessageFormat: {
     _enum: ['ConcatenatedVersionedXcm', 'ConcatenatedEncodedBlob', 'Signals']
   },
   /**
-   * Lookup446: cumulus_pallet_xcmp_queue::OutboundChannelDetails
+   * Lookup448: cumulus_pallet_xcmp_queue::OutboundChannelDetails
    **/
   CumulusPalletXcmpQueueOutboundChannelDetails: {
     recipient: 'u32',
@@ -3457,13 +3459,13 @@
     lastIndex: 'u16'
   },
   /**
-   * Lookup447: cumulus_pallet_xcmp_queue::OutboundState
+   * Lookup449: cumulus_pallet_xcmp_queue::OutboundState
    **/
   CumulusPalletXcmpQueueOutboundState: {
     _enum: ['Ok', 'Suspended']
   },
   /**
-   * Lookup449: cumulus_pallet_xcmp_queue::QueueConfigData
+   * Lookup451: cumulus_pallet_xcmp_queue::QueueConfigData
    **/
   CumulusPalletXcmpQueueQueueConfigData: {
     suspendThreshold: 'u32',
@@ -3474,13 +3476,13 @@
     xcmpMaxIndividualWeight: 'SpWeightsWeightV2Weight'
   },
   /**
-   * Lookup451: cumulus_pallet_xcmp_queue::pallet::Error<T>
+   * Lookup453: cumulus_pallet_xcmp_queue::pallet::Error<T>
    **/
   CumulusPalletXcmpQueueError: {
     _enum: ['FailedToSend', 'BadXcmOrigin', 'BadXcm', 'BadOverweightIndex', 'WeightOverLimit']
   },
   /**
-   * Lookup452: pallet_xcm::pallet::QueryStatus<BlockNumber>
+   * Lookup454: pallet_xcm::pallet::QueryStatus<BlockNumber>
    **/
   PalletXcmQueryStatus: {
     _enum: {
@@ -3501,7 +3503,7 @@
     }
   },
   /**
-   * Lookup456: xcm::VersionedResponse
+   * Lookup458: xcm::VersionedResponse
    **/
   XcmVersionedResponse: {
     _enum: {
@@ -3512,7 +3514,7 @@
     }
   },
   /**
-   * Lookup462: pallet_xcm::pallet::VersionMigrationStage
+   * Lookup464: pallet_xcm::pallet::VersionMigrationStage
    **/
   PalletXcmVersionMigrationStage: {
     _enum: {
@@ -3523,7 +3525,7 @@
     }
   },
   /**
-   * Lookup465: xcm::VersionedAssetId
+   * Lookup467: xcm::VersionedAssetId
    **/
   XcmVersionedAssetId: {
     _enum: {
@@ -3534,7 +3536,7 @@
     }
   },
   /**
-   * Lookup466: pallet_xcm::pallet::RemoteLockedFungibleRecord<ConsumerIdentifier, MaxConsumers>
+   * Lookup468: pallet_xcm::pallet::RemoteLockedFungibleRecord<ConsumerIdentifier, MaxConsumers>
    **/
   PalletXcmRemoteLockedFungibleRecord: {
     amount: 'u128',
@@ -3543,23 +3545,23 @@
     consumers: 'Vec<(Null,u128)>'
   },
   /**
-   * Lookup473: pallet_xcm::pallet::Error<T>
+   * Lookup475: pallet_xcm::pallet::Error<T>
    **/
   PalletXcmError: {
     _enum: ['Unreachable', 'SendFailure', 'Filtered', 'UnweighableMessage', 'DestinationNotInvertible', 'Empty', 'CannotReanchor', 'TooManyAssets', 'InvalidOrigin', 'BadVersion', 'BadLocation', 'NoSubscription', 'AlreadySubscribed', 'InvalidAsset', 'LowBalance', 'TooManyLocks', 'AccountNotSovereign', 'FeesNotMet', 'LockNotFound', 'InUse']
   },
   /**
-   * Lookup474: cumulus_pallet_xcm::pallet::Error<T>
+   * Lookup476: cumulus_pallet_xcm::pallet::Error<T>
    **/
   CumulusPalletXcmError: 'Null',
   /**
-   * Lookup475: cumulus_pallet_dmp_queue::ConfigData
+   * Lookup477: cumulus_pallet_dmp_queue::ConfigData
    **/
   CumulusPalletDmpQueueConfigData: {
     maxIndividual: 'SpWeightsWeightV2Weight'
   },
   /**
-   * Lookup476: cumulus_pallet_dmp_queue::PageIndexData
+   * Lookup478: cumulus_pallet_dmp_queue::PageIndexData
    **/
   CumulusPalletDmpQueuePageIndexData: {
     beginUsed: 'u32',
@@ -3567,25 +3569,25 @@
     overweightCount: 'u64'
   },
   /**
-   * Lookup479: cumulus_pallet_dmp_queue::pallet::Error<T>
+   * Lookup481: cumulus_pallet_dmp_queue::pallet::Error<T>
    **/
   CumulusPalletDmpQueueError: {
     _enum: ['Unknown', 'OverLimit']
   },
   /**
-   * Lookup483: pallet_unique::pallet::Error<T>
+   * Lookup485: pallet_unique::pallet::Error<T>
    **/
   PalletUniqueError: {
     _enum: ['CollectionDecimalPointLimitExceeded', 'EmptyArgument', 'RepartitionCalledOnNonRefungibleCollection']
   },
   /**
-   * Lookup484: pallet_configuration::pallet::Error<T>
+   * Lookup486: pallet_configuration::pallet::Error<T>
    **/
   PalletConfigurationError: {
     _enum: ['InconsistentConfiguration']
   },
   /**
-   * Lookup485: up_data_structs::Collection<sp_core::crypto::AccountId32>
+   * Lookup487: up_data_structs::Collection<sp_core::crypto::AccountId32>
    **/
   UpDataStructsCollection: {
     owner: 'AccountId32',
@@ -3599,7 +3601,7 @@
     flags: '[u8;1]'
   },
   /**
-   * Lookup486: up_data_structs::SponsorshipState<sp_core::crypto::AccountId32>
+   * Lookup488: up_data_structs::SponsorshipState<sp_core::crypto::AccountId32>
    **/
   UpDataStructsSponsorshipStateAccountId32: {
     _enum: {
@@ -3609,7 +3611,7 @@
     }
   },
   /**
-   * Lookup487: up_data_structs::Properties
+   * Lookup489: up_data_structs::Properties
    **/
   UpDataStructsProperties: {
     map: 'UpDataStructsPropertiesMapBoundedVec',
@@ -3617,15 +3619,15 @@
     reserved: 'u32'
   },
   /**
-   * Lookup488: up_data_structs::PropertiesMap<bounded_collections::bounded_vec::BoundedVec<T, S>>
+   * Lookup490: up_data_structs::PropertiesMap<bounded_collections::bounded_vec::BoundedVec<T, S>>
    **/
   UpDataStructsPropertiesMapBoundedVec: 'BTreeMap<Bytes, Bytes>',
   /**
-   * Lookup493: up_data_structs::PropertiesMap<up_data_structs::PropertyPermission>
+   * Lookup495: up_data_structs::PropertiesMap<up_data_structs::PropertyPermission>
    **/
   UpDataStructsPropertiesMapPropertyPermission: 'BTreeMap<Bytes, UpDataStructsPropertyPermission>',
   /**
-   * Lookup500: up_data_structs::CollectionStats
+   * Lookup502: up_data_structs::CollectionStats
    **/
   UpDataStructsCollectionStats: {
     created: 'u32',
@@ -3633,18 +3635,18 @@
     alive: 'u32'
   },
   /**
-   * Lookup501: up_data_structs::TokenChild
+   * Lookup503: up_data_structs::TokenChild
    **/
   UpDataStructsTokenChild: {
     token: 'u32',
     collection: 'u32'
   },
   /**
-   * Lookup502: PhantomType::up_data_structs<T>
+   * Lookup504: PhantomType::up_data_structs<T>
    **/
   PhantomTypeUpDataStructs: '[(UpDataStructsTokenData,UpDataStructsRpcCollection,UpPovEstimateRpcPovInfo);0]',
   /**
-   * Lookup504: up_data_structs::TokenData<pallet_evm::account::BasicCrossAccountIdRepr<sp_core::crypto::AccountId32>>
+   * Lookup506: up_data_structs::TokenData<pallet_evm::account::BasicCrossAccountIdRepr<sp_core::crypto::AccountId32>>
    **/
   UpDataStructsTokenData: {
     properties: 'Vec<UpDataStructsProperty>',
@@ -3652,7 +3654,7 @@
     pieces: 'u128'
   },
   /**
-   * Lookup506: up_data_structs::RpcCollection<sp_core::crypto::AccountId32>
+   * Lookup507: up_data_structs::RpcCollection<sp_core::crypto::AccountId32>
    **/
   UpDataStructsRpcCollection: {
     owner: 'AccountId32',
@@ -3669,14 +3671,14 @@
     flags: 'UpDataStructsRpcCollectionFlags'
   },
   /**
-   * Lookup507: up_data_structs::RpcCollectionFlags
+   * Lookup508: up_data_structs::RpcCollectionFlags
    **/
   UpDataStructsRpcCollectionFlags: {
     foreign: 'bool',
     erc721metadata: 'bool'
   },
   /**
-   * Lookup508: up_pov_estimate_rpc::PovInfo
+   * Lookup509: up_pov_estimate_rpc::PovInfo
    **/
   UpPovEstimateRpcPovInfo: {
     proofSize: 'u64',
@@ -3686,7 +3688,7 @@
     keyValues: 'Vec<UpPovEstimateRpcTrieKeyValue>'
   },
   /**
-   * Lookup511: sp_runtime::transaction_validity::TransactionValidityError
+   * Lookup512: sp_runtime::transaction_validity::TransactionValidityError
    **/
   SpRuntimeTransactionValidityTransactionValidityError: {
     _enum: {
@@ -3695,7 +3697,7 @@
     }
   },
   /**
-   * Lookup512: sp_runtime::transaction_validity::InvalidTransaction
+   * Lookup513: sp_runtime::transaction_validity::InvalidTransaction
    **/
   SpRuntimeTransactionValidityInvalidTransaction: {
     _enum: {
@@ -3713,7 +3715,7 @@
     }
   },
   /**
-   * Lookup513: sp_runtime::transaction_validity::UnknownTransaction
+   * Lookup514: sp_runtime::transaction_validity::UnknownTransaction
    **/
   SpRuntimeTransactionValidityUnknownTransaction: {
     _enum: {
@@ -3723,68 +3725,68 @@
     }
   },
   /**
-   * Lookup515: up_pov_estimate_rpc::TrieKeyValue
+   * Lookup516: up_pov_estimate_rpc::TrieKeyValue
    **/
   UpPovEstimateRpcTrieKeyValue: {
     key: 'Bytes',
     value: 'Bytes'
   },
   /**
-   * Lookup517: pallet_common::pallet::Error<T>
+   * Lookup518: pallet_common::pallet::Error<T>
    **/
   PalletCommonError: {
     _enum: ['CollectionNotFound', 'MustBeTokenOwner', 'NoPermission', 'CantDestroyNotEmptyCollection', 'PublicMintingNotAllowed', 'AddressNotInAllowlist', 'CollectionNameLimitExceeded', 'CollectionDescriptionLimitExceeded', 'CollectionTokenPrefixLimitExceeded', 'TotalCollectionsLimitExceeded', 'CollectionAdminCountExceeded', 'CollectionLimitBoundsExceeded', 'OwnerPermissionsCantBeReverted', 'TransferNotAllowed', 'AccountTokenLimitExceeded', 'CollectionTokenLimitExceeded', 'MetadataFlagFrozen', 'TokenNotFound', 'TokenValueTooLow', 'ApprovedValueTooLow', 'CantApproveMoreThanOwned', 'AddressIsNotEthMirror', 'AddressIsZero', 'UnsupportedOperation', 'NotSufficientFounds', 'UserIsNotAllowedToNest', 'SourceCollectionIsNotAllowedToNest', 'CollectionFieldSizeExceeded', 'NoSpaceForProperty', 'PropertyLimitReached', 'PropertyKeyIsTooLong', 'InvalidCharacterInPropertyKey', 'EmptyPropertyKey', 'CollectionIsExternal', 'CollectionIsInternal', 'ConfirmSponsorshipFail', 'UserIsNotCollectionAdmin']
   },
   /**
-   * Lookup519: pallet_fungible::pallet::Error<T>
+   * Lookup520: pallet_fungible::pallet::Error<T>
    **/
   PalletFungibleError: {
     _enum: ['NotFungibleDataUsedToMintFungibleCollectionToken', 'FungibleItemsHaveNoId', 'FungibleItemsDontHaveData', 'FungibleDisallowsNesting', 'SettingPropertiesNotAllowed', 'SettingAllowanceForAllNotAllowed', 'FungibleTokensAreAlwaysValid']
   },
   /**
-   * Lookup524: pallet_refungible::pallet::Error<T>
+   * Lookup525: pallet_refungible::pallet::Error<T>
    **/
   PalletRefungibleError: {
     _enum: ['NotRefungibleDataUsedToMintFungibleCollectionToken', 'WrongRefungiblePieces', 'RepartitionWhileNotOwningAllPieces', 'RefungibleDisallowsNesting', 'SettingPropertiesNotAllowed']
   },
   /**
-   * Lookup525: pallet_nonfungible::ItemData<pallet_evm::account::BasicCrossAccountIdRepr<sp_core::crypto::AccountId32>>
+   * Lookup526: pallet_nonfungible::ItemData<pallet_evm::account::BasicCrossAccountIdRepr<sp_core::crypto::AccountId32>>
    **/
   PalletNonfungibleItemData: {
     owner: 'PalletEvmAccountBasicCrossAccountIdRepr'
   },
   /**
-   * Lookup527: up_data_structs::PropertyScope
+   * Lookup528: up_data_structs::PropertyScope
    **/
   UpDataStructsPropertyScope: {
     _enum: ['None', 'Rmrk']
   },
   /**
-   * Lookup530: pallet_nonfungible::pallet::Error<T>
+   * Lookup531: pallet_nonfungible::pallet::Error<T>
    **/
   PalletNonfungibleError: {
     _enum: ['NotNonfungibleDataUsedToMintFungibleCollectionToken', 'NonfungibleItemsHaveNoAmount', 'CantBurnNftWithChildren']
   },
   /**
-   * Lookup531: pallet_structure::pallet::Error<T>
+   * Lookup532: pallet_structure::pallet::Error<T>
    **/
   PalletStructureError: {
     _enum: ['OuroborosDetected', 'DepthLimit', 'BreadthLimit', 'TokenNotFound', 'CantNestTokenUnderCollection']
   },
   /**
-   * Lookup536: pallet_app_promotion::pallet::Error<T>
+   * Lookup537: pallet_app_promotion::pallet::Error<T>
    **/
   PalletAppPromotionError: {
     _enum: ['AdminNotSet', 'NoPermission', 'NotSufficientFunds', 'PendingForBlockOverflow', 'SponsorNotSet', 'InsufficientStakedBalance', 'InconsistencyState']
   },
   /**
-   * Lookup537: pallet_foreign_assets::module::Error<T>
+   * Lookup538: pallet_foreign_assets::module::Error<T>
    **/
   PalletForeignAssetsModuleError: {
     _enum: ['BadLocation', 'MultiLocationExisted', 'AssetIdNotExists', 'AssetIdExisted']
   },
   /**
-   * Lookup538: pallet_evm::CodeMetadata
+   * Lookup539: pallet_evm::CodeMetadata
    **/
   PalletEvmCodeMetadata: {
     _alias: {
@@ -3795,13 +3797,13 @@
     hash_: 'H256'
   },
   /**
-   * Lookup540: pallet_evm::pallet::Error<T>
+   * Lookup541: pallet_evm::pallet::Error<T>
    **/
   PalletEvmError: {
     _enum: ['BalanceLow', 'FeeOverflow', 'PaymentOverflow', 'WithdrawFailed', 'GasPriceTooLow', 'InvalidNonce', 'GasLimitTooLow', 'GasLimitTooHigh', 'Undefined', 'Reentrancy', 'TransactionMustComeFromEOA']
   },
   /**
-   * Lookup543: fp_rpc::TransactionStatus
+   * Lookup544: fp_rpc::TransactionStatus
    **/
   FpRpcTransactionStatus: {
     transactionHash: 'H256',
@@ -3813,11 +3815,11 @@
     logsBloom: 'EthbloomBloom'
   },
   /**
-   * Lookup545: ethbloom::Bloom
+   * Lookup546: ethbloom::Bloom
    **/
   EthbloomBloom: '[u8;256]',
   /**
-   * Lookup547: ethereum::receipt::ReceiptV3
+   * Lookup548: ethereum::receipt::ReceiptV3
    **/
   EthereumReceiptReceiptV3: {
     _enum: {
@@ -3827,7 +3829,7 @@
     }
   },
   /**
-   * Lookup548: ethereum::receipt::EIP658ReceiptData
+   * Lookup549: ethereum::receipt::EIP658ReceiptData
    **/
   EthereumReceiptEip658ReceiptData: {
     statusCode: 'u8',
@@ -3836,7 +3838,7 @@
     logs: 'Vec<EthereumLog>'
   },
   /**
-   * Lookup549: ethereum::block::Block<ethereum::transaction::TransactionV2>
+   * Lookup550: ethereum::block::Block<ethereum::transaction::TransactionV2>
    **/
   EthereumBlock: {
     header: 'EthereumHeader',
@@ -3844,7 +3846,7 @@
     ommers: 'Vec<EthereumHeader>'
   },
   /**
-   * Lookup550: ethereum::header::Header
+   * Lookup551: ethereum::header::Header
    **/
   EthereumHeader: {
     parentHash: 'H256',
@@ -3864,23 +3866,23 @@
     nonce: 'EthereumTypesHashH64'
   },
   /**
-   * Lookup551: ethereum_types::hash::H64
+   * Lookup552: ethereum_types::hash::H64
    **/
   EthereumTypesHashH64: '[u8;8]',
   /**
-   * Lookup556: pallet_ethereum::pallet::Error<T>
+   * Lookup557: pallet_ethereum::pallet::Error<T>
    **/
   PalletEthereumError: {
     _enum: ['InvalidSignature', 'PreLogExists']
   },
   /**
-   * Lookup557: pallet_evm_coder_substrate::pallet::Error<T>
+   * Lookup558: pallet_evm_coder_substrate::pallet::Error<T>
    **/
   PalletEvmCoderSubstrateError: {
     _enum: ['OutOfGas', 'OutOfFund']
   },
   /**
-   * Lookup558: up_data_structs::SponsorshipState<pallet_evm::account::BasicCrossAccountIdRepr<sp_core::crypto::AccountId32>>
+   * Lookup559: up_data_structs::SponsorshipState<pallet_evm::account::BasicCrossAccountIdRepr<sp_core::crypto::AccountId32>>
    **/
   UpDataStructsSponsorshipStateBasicCrossAccountIdRepr: {
     _enum: {
@@ -3890,35 +3892,35 @@
     }
   },
   /**
-   * Lookup559: pallet_evm_contract_helpers::SponsoringModeT
+   * Lookup560: pallet_evm_contract_helpers::SponsoringModeT
    **/
   PalletEvmContractHelpersSponsoringModeT: {
     _enum: ['Disabled', 'Allowlisted', 'Generous']
   },
   /**
-   * Lookup565: pallet_evm_contract_helpers::pallet::Error<T>
+   * Lookup566: pallet_evm_contract_helpers::pallet::Error<T>
    **/
   PalletEvmContractHelpersError: {
     _enum: ['NoPermission', 'NoPendingSponsor', 'TooManyMethodsHaveSponsoredLimit']
   },
   /**
-   * Lookup566: pallet_evm_migration::pallet::Error<T>
+   * Lookup567: pallet_evm_migration::pallet::Error<T>
    **/
   PalletEvmMigrationError: {
     _enum: ['AccountNotEmpty', 'AccountIsNotMigrating', 'BadEvent']
   },
   /**
-   * Lookup567: pallet_maintenance::pallet::Error<T>
+   * Lookup568: pallet_maintenance::pallet::Error<T>
    **/
   PalletMaintenanceError: 'Null',
   /**
-   * Lookup568: pallet_test_utils::pallet::Error<T>
+   * Lookup569: pallet_test_utils::pallet::Error<T>
    **/
   PalletTestUtilsError: {
     _enum: ['TestPalletDisabled', 'TriggerRollback']
   },
   /**
-   * Lookup570: sp_runtime::MultiSignature
+   * Lookup571: sp_runtime::MultiSignature
    **/
   SpRuntimeMultiSignature: {
     _enum: {
@@ -3928,55 +3930,55 @@
     }
   },
   /**
-   * Lookup571: sp_core::ed25519::Signature
+   * Lookup572: sp_core::ed25519::Signature
    **/
   SpCoreEd25519Signature: '[u8;64]',
   /**
-   * Lookup573: sp_core::sr25519::Signature
+   * Lookup574: sp_core::sr25519::Signature
    **/
   SpCoreSr25519Signature: '[u8;64]',
   /**
-   * Lookup574: sp_core::ecdsa::Signature
+   * Lookup575: sp_core::ecdsa::Signature
    **/
   SpCoreEcdsaSignature: '[u8;65]',
   /**
-   * Lookup577: frame_system::extensions::check_spec_version::CheckSpecVersion<T>
+   * Lookup578: frame_system::extensions::check_spec_version::CheckSpecVersion<T>
    **/
   FrameSystemExtensionsCheckSpecVersion: 'Null',
   /**
-   * Lookup578: frame_system::extensions::check_tx_version::CheckTxVersion<T>
+   * Lookup579: frame_system::extensions::check_tx_version::CheckTxVersion<T>
    **/
   FrameSystemExtensionsCheckTxVersion: 'Null',
   /**
-   * Lookup579: frame_system::extensions::check_genesis::CheckGenesis<T>
+   * Lookup580: frame_system::extensions::check_genesis::CheckGenesis<T>
    **/
   FrameSystemExtensionsCheckGenesis: 'Null',
   /**
-   * Lookup582: frame_system::extensions::check_nonce::CheckNonce<T>
+   * Lookup583: frame_system::extensions::check_nonce::CheckNonce<T>
    **/
   FrameSystemExtensionsCheckNonce: 'Compact<u32>',
   /**
-   * Lookup583: frame_system::extensions::check_weight::CheckWeight<T>
+   * Lookup584: frame_system::extensions::check_weight::CheckWeight<T>
    **/
   FrameSystemExtensionsCheckWeight: 'Null',
   /**
-   * Lookup584: opal_runtime::runtime_common::maintenance::CheckMaintenance
+   * Lookup585: opal_runtime::runtime_common::maintenance::CheckMaintenance
    **/
   OpalRuntimeRuntimeCommonMaintenanceCheckMaintenance: 'Null',
   /**
-   * Lookup585: opal_runtime::runtime_common::identity::DisableIdentityCalls
+   * Lookup586: opal_runtime::runtime_common::identity::DisableIdentityCalls
    **/
   OpalRuntimeRuntimeCommonIdentityDisableIdentityCalls: 'Null',
   /**
-   * Lookup586: pallet_template_transaction_payment::ChargeTransactionPayment<opal_runtime::Runtime>
+   * Lookup587: pallet_template_transaction_payment::ChargeTransactionPayment<opal_runtime::Runtime>
    **/
   PalletTemplateTransactionPaymentChargeTransactionPayment: 'Compact<u128>',
   /**
-   * Lookup587: opal_runtime::Runtime
+   * Lookup588: opal_runtime::Runtime
    **/
   OpalRuntimeRuntime: 'Null',
   /**
-   * Lookup588: pallet_ethereum::FakeTransactionFinalizer<opal_runtime::Runtime>
+   * Lookup589: pallet_ethereum::FakeTransactionFinalizer<opal_runtime::Runtime>
    **/
   PalletEthereumFakeTransactionFinalizer: 'Null'
 };
modifiedtests/src/interfaces/types-lookup.tsdiffbeforeafterboth
--- a/tests/src/interfaces/types-lookup.ts
+++ b/tests/src/interfaces/types-lookup.ts
@@ -3181,11 +3181,13 @@
     readonly name: Vec<u16>;
     readonly description: Vec<u16>;
     readonly tokenPrefix: Bytes;
-    readonly pendingSponsor: Option<AccountId32>;
     readonly limits: Option<UpDataStructsCollectionLimits>;
     readonly permissions: Option<UpDataStructsCollectionPermissions>;
     readonly tokenPropertyPermissions: Vec<UpDataStructsPropertyKeyPermission>;
     readonly properties: Vec<UpDataStructsProperty>;
+    readonly adminList: Vec<PalletEvmAccountBasicCrossAccountIdRepr>;
+    readonly pendingSponsor: Option<PalletEvmAccountBasicCrossAccountIdRepr>;
+    readonly flags: U8aFixed;
   }
 
   /** @name UpDataStructsAccessMode (337) */
@@ -3252,7 +3254,7 @@
     readonly value: Bytes;
   }
 
-  /** @name UpDataStructsCreateItemData (360) */
+  /** @name UpDataStructsCreateItemData (362) */
   interface UpDataStructsCreateItemData extends Enum {
     readonly isNft: boolean;
     readonly asNft: UpDataStructsCreateNftData;
@@ -3263,23 +3265,23 @@
     readonly type: 'Nft' | 'Fungible' | 'ReFungible';
   }
 
-  /** @name UpDataStructsCreateNftData (361) */
+  /** @name UpDataStructsCreateNftData (363) */
   interface UpDataStructsCreateNftData extends Struct {
     readonly properties: Vec<UpDataStructsProperty>;
   }
 
-  /** @name UpDataStructsCreateFungibleData (362) */
+  /** @name UpDataStructsCreateFungibleData (364) */
   interface UpDataStructsCreateFungibleData extends Struct {
     readonly value: u128;
   }
 
-  /** @name UpDataStructsCreateReFungibleData (363) */
+  /** @name UpDataStructsCreateReFungibleData (365) */
   interface UpDataStructsCreateReFungibleData extends Struct {
     readonly pieces: u128;
     readonly properties: Vec<UpDataStructsProperty>;
   }
 
-  /** @name UpDataStructsCreateItemExData (366) */
+  /** @name UpDataStructsCreateItemExData (368) */
   interface UpDataStructsCreateItemExData extends Enum {
     readonly isNft: boolean;
     readonly asNft: Vec<UpDataStructsCreateNftExData>;
@@ -3292,26 +3294,26 @@
     readonly type: 'Nft' | 'Fungible' | 'RefungibleMultipleItems' | 'RefungibleMultipleOwners';
   }
 
-  /** @name UpDataStructsCreateNftExData (368) */
+  /** @name UpDataStructsCreateNftExData (370) */
   interface UpDataStructsCreateNftExData extends Struct {
     readonly properties: Vec<UpDataStructsProperty>;
     readonly owner: PalletEvmAccountBasicCrossAccountIdRepr;
   }
 
-  /** @name UpDataStructsCreateRefungibleExSingleOwner (375) */
+  /** @name UpDataStructsCreateRefungibleExSingleOwner (377) */
   interface UpDataStructsCreateRefungibleExSingleOwner extends Struct {
     readonly user: PalletEvmAccountBasicCrossAccountIdRepr;
     readonly pieces: u128;
     readonly properties: Vec<UpDataStructsProperty>;
   }
 
-  /** @name UpDataStructsCreateRefungibleExMultipleOwners (377) */
+  /** @name UpDataStructsCreateRefungibleExMultipleOwners (379) */
   interface UpDataStructsCreateRefungibleExMultipleOwners extends Struct {
     readonly users: BTreeMap<PalletEvmAccountBasicCrossAccountIdRepr, u128>;
     readonly properties: Vec<UpDataStructsProperty>;
   }
 
-  /** @name PalletConfigurationCall (378) */
+  /** @name PalletConfigurationCall (380) */
   interface PalletConfigurationCall extends Enum {
     readonly isSetWeightToFeeCoefficientOverride: boolean;
     readonly asSetWeightToFeeCoefficientOverride: {
@@ -3340,7 +3342,7 @@
     readonly type: 'SetWeightToFeeCoefficientOverride' | 'SetMinGasPriceOverride' | 'SetAppPromotionConfigurationOverride' | 'SetCollatorSelectionDesiredCollators' | 'SetCollatorSelectionLicenseBond' | 'SetCollatorSelectionKickThreshold';
   }
 
-  /** @name PalletConfigurationAppPromotionConfiguration (380) */
+  /** @name PalletConfigurationAppPromotionConfiguration (382) */
   interface PalletConfigurationAppPromotionConfiguration extends Struct {
     readonly recalculationInterval: Option<u32>;
     readonly pendingInterval: Option<u32>;
@@ -3348,10 +3350,10 @@
     readonly maxStakersPerCalculation: Option<u8>;
   }
 
-  /** @name PalletStructureCall (384) */
+  /** @name PalletStructureCall (386) */
   type PalletStructureCall = Null;
 
-  /** @name PalletAppPromotionCall (385) */
+  /** @name PalletAppPromotionCall (387) */
   interface PalletAppPromotionCall extends Enum {
     readonly isSetAdminAddress: boolean;
     readonly asSetAdminAddress: {
@@ -3393,7 +3395,7 @@
     readonly type: 'SetAdminAddress' | 'Stake' | 'UnstakeAll' | 'SponsorCollection' | 'StopSponsoringCollection' | 'SponsorContract' | 'StopSponsoringContract' | 'PayoutStakers' | 'UnstakePartial' | 'ForceUnstake';
   }
 
-  /** @name PalletForeignAssetsModuleCall (386) */
+  /** @name PalletForeignAssetsModuleCall (388) */
   interface PalletForeignAssetsModuleCall extends Enum {
     readonly isRegisterForeignAsset: boolean;
     readonly asRegisterForeignAsset: {
@@ -3410,7 +3412,7 @@
     readonly type: 'RegisterForeignAsset' | 'UpdateForeignAsset';
   }
 
-  /** @name PalletEvmCall (387) */
+  /** @name PalletEvmCall (389) */
   interface PalletEvmCall extends Enum {
     readonly isWithdraw: boolean;
     readonly asWithdraw: {
@@ -3455,7 +3457,7 @@
     readonly type: 'Withdraw' | 'Call' | 'Create' | 'Create2';
   }
 
-  /** @name PalletEthereumCall (393) */
+  /** @name PalletEthereumCall (395) */
   interface PalletEthereumCall extends Enum {
     readonly isTransact: boolean;
     readonly asTransact: {
@@ -3464,7 +3466,7 @@
     readonly type: 'Transact';
   }
 
-  /** @name EthereumTransactionTransactionV2 (394) */
+  /** @name EthereumTransactionTransactionV2 (396) */
   interface EthereumTransactionTransactionV2 extends Enum {
     readonly isLegacy: boolean;
     readonly asLegacy: EthereumTransactionLegacyTransaction;
@@ -3475,7 +3477,7 @@
     readonly type: 'Legacy' | 'Eip2930' | 'Eip1559';
   }
 
-  /** @name EthereumTransactionLegacyTransaction (395) */
+  /** @name EthereumTransactionLegacyTransaction (397) */
   interface EthereumTransactionLegacyTransaction extends Struct {
     readonly nonce: U256;
     readonly gasPrice: U256;
@@ -3486,7 +3488,7 @@
     readonly signature: EthereumTransactionTransactionSignature;
   }
 
-  /** @name EthereumTransactionTransactionAction (396) */
+  /** @name EthereumTransactionTransactionAction (398) */
   interface EthereumTransactionTransactionAction extends Enum {
     readonly isCall: boolean;
     readonly asCall: H160;
@@ -3494,14 +3496,14 @@
     readonly type: 'Call' | 'Create';
   }
 
-  /** @name EthereumTransactionTransactionSignature (397) */
+  /** @name EthereumTransactionTransactionSignature (399) */
   interface EthereumTransactionTransactionSignature extends Struct {
     readonly v: u64;
     readonly r: H256;
     readonly s: H256;
   }
 
-  /** @name EthereumTransactionEip2930Transaction (399) */
+  /** @name EthereumTransactionEip2930Transaction (401) */
   interface EthereumTransactionEip2930Transaction extends Struct {
     readonly chainId: u64;
     readonly nonce: U256;
@@ -3516,13 +3518,13 @@
     readonly s: H256;
   }
 
-  /** @name EthereumTransactionAccessListItem (401) */
+  /** @name EthereumTransactionAccessListItem (403) */
   interface EthereumTransactionAccessListItem extends Struct {
     readonly address: H160;
     readonly storageKeys: Vec<H256>;
   }
 
-  /** @name EthereumTransactionEip1559Transaction (402) */
+  /** @name EthereumTransactionEip1559Transaction (404) */
   interface EthereumTransactionEip1559Transaction extends Struct {
     readonly chainId: u64;
     readonly nonce: U256;
@@ -3538,7 +3540,7 @@
     readonly s: H256;
   }
 
-  /** @name PalletEvmContractHelpersCall (403) */
+  /** @name PalletEvmContractHelpersCall (405) */
   interface PalletEvmContractHelpersCall extends Enum {
     readonly isMigrateFromSelfSponsoring: boolean;
     readonly asMigrateFromSelfSponsoring: {
@@ -3547,7 +3549,7 @@
     readonly type: 'MigrateFromSelfSponsoring';
   }
 
-  /** @name PalletEvmMigrationCall (405) */
+  /** @name PalletEvmMigrationCall (407) */
   interface PalletEvmMigrationCall extends Enum {
     readonly isBegin: boolean;
     readonly asBegin: {
@@ -3575,7 +3577,7 @@
     readonly type: 'Begin' | 'SetData' | 'Finish' | 'InsertEthLogs' | 'InsertEvents' | 'RemoveRmrkData';
   }
 
-  /** @name PalletMaintenanceCall (409) */
+  /** @name PalletMaintenanceCall (411) */
   interface PalletMaintenanceCall extends Enum {
     readonly isEnable: boolean;
     readonly isDisable: boolean;
@@ -3587,7 +3589,7 @@
     readonly type: 'Enable' | 'Disable' | 'ExecutePreimage';
   }
 
-  /** @name PalletTestUtilsCall (410) */
+  /** @name PalletTestUtilsCall (412) */
   interface PalletTestUtilsCall extends Enum {
     readonly isEnable: boolean;
     readonly isSetTestValue: boolean;
@@ -3607,13 +3609,13 @@
     readonly type: 'Enable' | 'SetTestValue' | 'SetTestValueAndRollback' | 'IncTestValue' | 'JustTakeFee' | 'BatchAll';
   }
 
-  /** @name PalletSudoError (412) */
+  /** @name PalletSudoError (414) */
   interface PalletSudoError extends Enum {
     readonly isRequireSudo: boolean;
     readonly type: 'RequireSudo';
   }
 
-  /** @name OrmlVestingModuleError (414) */
+  /** @name OrmlVestingModuleError (416) */
   interface OrmlVestingModuleError extends Enum {
     readonly isZeroVestingPeriod: boolean;
     readonly isZeroVestingPeriodCount: boolean;
@@ -3624,7 +3626,7 @@
     readonly type: 'ZeroVestingPeriod' | 'ZeroVestingPeriodCount' | 'InsufficientBalanceToLock' | 'TooManyVestingSchedules' | 'AmountLow' | 'MaxVestingSchedulesExceeded';
   }
 
-  /** @name OrmlXtokensModuleError (415) */
+  /** @name OrmlXtokensModuleError (417) */
   interface OrmlXtokensModuleError extends Enum {
     readonly isAssetHasNoReserve: boolean;
     readonly isNotCrossChainTransfer: boolean;
@@ -3648,26 +3650,26 @@
     readonly type: 'AssetHasNoReserve' | 'NotCrossChainTransfer' | 'InvalidDest' | 'NotCrossChainTransferableCurrency' | 'UnweighableMessage' | 'XcmExecutionFailed' | 'CannotReanchor' | 'InvalidAncestry' | 'InvalidAsset' | 'DestinationNotInvertible' | 'BadVersion' | 'DistinctReserveForAssetAndFee' | 'ZeroFee' | 'ZeroAmount' | 'TooManyAssetsBeingSent' | 'AssetIndexNonExistent' | 'FeeNotEnough' | 'NotSupportedMultiLocation' | 'MinXcmFeeNotDefined';
   }
 
-  /** @name OrmlTokensBalanceLock (418) */
+  /** @name OrmlTokensBalanceLock (420) */
   interface OrmlTokensBalanceLock extends Struct {
     readonly id: U8aFixed;
     readonly amount: u128;
   }
 
-  /** @name OrmlTokensAccountData (420) */
+  /** @name OrmlTokensAccountData (422) */
   interface OrmlTokensAccountData extends Struct {
     readonly free: u128;
     readonly reserved: u128;
     readonly frozen: u128;
   }
 
-  /** @name OrmlTokensReserveData (422) */
+  /** @name OrmlTokensReserveData (424) */
   interface OrmlTokensReserveData extends Struct {
     readonly id: Null;
     readonly amount: u128;
   }
 
-  /** @name OrmlTokensModuleError (424) */
+  /** @name OrmlTokensModuleError (426) */
   interface OrmlTokensModuleError extends Enum {
     readonly isBalanceTooLow: boolean;
     readonly isAmountIntoBalanceFailed: boolean;
@@ -3680,14 +3682,14 @@
     readonly type: 'BalanceTooLow' | 'AmountIntoBalanceFailed' | 'LiquidityRestrictions' | 'MaxLocksExceeded' | 'KeepAlive' | 'ExistentialDeposit' | 'DeadAccount' | 'TooManyReserves';
   }
 
-  /** @name PalletIdentityRegistrarInfo (429) */
+  /** @name PalletIdentityRegistrarInfo (431) */
   interface PalletIdentityRegistrarInfo extends Struct {
     readonly account: AccountId32;
     readonly fee: u128;
     readonly fields: PalletIdentityBitFlags;
   }
 
-  /** @name PalletIdentityError (431) */
+  /** @name PalletIdentityError (433) */
   interface PalletIdentityError extends Enum {
     readonly isTooManySubAccounts: boolean;
     readonly isNotFound: boolean;
@@ -3710,7 +3712,7 @@
     readonly type: 'TooManySubAccounts' | 'NotFound' | 'NotNamed' | 'EmptyIndex' | 'FeeChanged' | 'NoIdentity' | 'StickyJudgement' | 'JudgementGiven' | 'InvalidJudgement' | 'InvalidIndex' | 'InvalidTarget' | 'TooManyFields' | 'TooManyRegistrars' | 'AlreadyClaimed' | 'NotSub' | 'NotOwned' | 'JudgementForDifferentIdentity' | 'JudgementPaymentFailed';
   }
 
-  /** @name PalletPreimageRequestStatus (432) */
+  /** @name PalletPreimageRequestStatus (434) */
   interface PalletPreimageRequestStatus extends Enum {
     readonly isUnrequested: boolean;
     readonly asUnrequested: {
@@ -3726,7 +3728,7 @@
     readonly type: 'Unrequested' | 'Requested';
   }
 
-  /** @name PalletPreimageError (437) */
+  /** @name PalletPreimageError (439) */
   interface PalletPreimageError extends Enum {
     readonly isTooBig: boolean;
     readonly isAlreadyNoted: boolean;
@@ -3737,21 +3739,21 @@
     readonly type: 'TooBig' | 'AlreadyNoted' | 'NotAuthorized' | 'NotNoted' | 'Requested' | 'NotRequested';
   }
 
-  /** @name CumulusPalletXcmpQueueInboundChannelDetails (439) */
+  /** @name CumulusPalletXcmpQueueInboundChannelDetails (441) */
   interface CumulusPalletXcmpQueueInboundChannelDetails extends Struct {
     readonly sender: u32;
     readonly state: CumulusPalletXcmpQueueInboundState;
     readonly messageMetadata: Vec<ITuple<[u32, PolkadotParachainPrimitivesXcmpMessageFormat]>>;
   }
 
-  /** @name CumulusPalletXcmpQueueInboundState (440) */
+  /** @name CumulusPalletXcmpQueueInboundState (442) */
   interface CumulusPalletXcmpQueueInboundState extends Enum {
     readonly isOk: boolean;
     readonly isSuspended: boolean;
     readonly type: 'Ok' | 'Suspended';
   }
 
-  /** @name PolkadotParachainPrimitivesXcmpMessageFormat (443) */
+  /** @name PolkadotParachainPrimitivesXcmpMessageFormat (445) */
   interface PolkadotParachainPrimitivesXcmpMessageFormat extends Enum {
     readonly isConcatenatedVersionedXcm: boolean;
     readonly isConcatenatedEncodedBlob: boolean;
@@ -3759,7 +3761,7 @@
     readonly type: 'ConcatenatedVersionedXcm' | 'ConcatenatedEncodedBlob' | 'Signals';
   }
 
-  /** @name CumulusPalletXcmpQueueOutboundChannelDetails (446) */
+  /** @name CumulusPalletXcmpQueueOutboundChannelDetails (448) */
   interface CumulusPalletXcmpQueueOutboundChannelDetails extends Struct {
     readonly recipient: u32;
     readonly state: CumulusPalletXcmpQueueOutboundState;
@@ -3768,14 +3770,14 @@
     readonly lastIndex: u16;
   }
 
-  /** @name CumulusPalletXcmpQueueOutboundState (447) */
+  /** @name CumulusPalletXcmpQueueOutboundState (449) */
   interface CumulusPalletXcmpQueueOutboundState extends Enum {
     readonly isOk: boolean;
     readonly isSuspended: boolean;
     readonly type: 'Ok' | 'Suspended';
   }
 
-  /** @name CumulusPalletXcmpQueueQueueConfigData (449) */
+  /** @name CumulusPalletXcmpQueueQueueConfigData (451) */
   interface CumulusPalletXcmpQueueQueueConfigData extends Struct {
     readonly suspendThreshold: u32;
     readonly dropThreshold: u32;
@@ -3785,7 +3787,7 @@
     readonly xcmpMaxIndividualWeight: SpWeightsWeightV2Weight;
   }
 
-  /** @name CumulusPalletXcmpQueueError (451) */
+  /** @name CumulusPalletXcmpQueueError (453) */
   interface CumulusPalletXcmpQueueError extends Enum {
     readonly isFailedToSend: boolean;
     readonly isBadXcmOrigin: boolean;
@@ -3795,7 +3797,7 @@
     readonly type: 'FailedToSend' | 'BadXcmOrigin' | 'BadXcm' | 'BadOverweightIndex' | 'WeightOverLimit';
   }
 
-  /** @name PalletXcmQueryStatus (452) */
+  /** @name PalletXcmQueryStatus (454) */
   interface PalletXcmQueryStatus extends Enum {
     readonly isPending: boolean;
     readonly asPending: {
@@ -3817,7 +3819,7 @@
     readonly type: 'Pending' | 'VersionNotifier' | 'Ready';
   }
 
-  /** @name XcmVersionedResponse (456) */
+  /** @name XcmVersionedResponse (458) */
   interface XcmVersionedResponse extends Enum {
     readonly isV2: boolean;
     readonly asV2: XcmV2Response;
@@ -3826,7 +3828,7 @@
     readonly type: 'V2' | 'V3';
   }
 
-  /** @name PalletXcmVersionMigrationStage (462) */
+  /** @name PalletXcmVersionMigrationStage (464) */
   interface PalletXcmVersionMigrationStage extends Enum {
     readonly isMigrateSupportedVersion: boolean;
     readonly isMigrateVersionNotifiers: boolean;
@@ -3836,14 +3838,14 @@
     readonly type: 'MigrateSupportedVersion' | 'MigrateVersionNotifiers' | 'NotifyCurrentTargets' | 'MigrateAndNotifyOldTargets';
   }
 
-  /** @name XcmVersionedAssetId (465) */
+  /** @name XcmVersionedAssetId (467) */
   interface XcmVersionedAssetId extends Enum {
     readonly isV3: boolean;
     readonly asV3: XcmV3MultiassetAssetId;
     readonly type: 'V3';
   }
 
-  /** @name PalletXcmRemoteLockedFungibleRecord (466) */
+  /** @name PalletXcmRemoteLockedFungibleRecord (468) */
   interface PalletXcmRemoteLockedFungibleRecord extends Struct {
     readonly amount: u128;
     readonly owner: XcmVersionedMultiLocation;
@@ -3851,7 +3853,7 @@
     readonly consumers: Vec<ITuple<[Null, u128]>>;
   }
 
-  /** @name PalletXcmError (473) */
+  /** @name PalletXcmError (475) */
   interface PalletXcmError extends Enum {
     readonly isUnreachable: boolean;
     readonly isSendFailure: boolean;
@@ -3876,29 +3878,29 @@
     readonly type: 'Unreachable' | 'SendFailure' | 'Filtered' | 'UnweighableMessage' | 'DestinationNotInvertible' | 'Empty' | 'CannotReanchor' | 'TooManyAssets' | 'InvalidOrigin' | 'BadVersion' | 'BadLocation' | 'NoSubscription' | 'AlreadySubscribed' | 'InvalidAsset' | 'LowBalance' | 'TooManyLocks' | 'AccountNotSovereign' | 'FeesNotMet' | 'LockNotFound' | 'InUse';
   }
 
-  /** @name CumulusPalletXcmError (474) */
+  /** @name CumulusPalletXcmError (476) */
   type CumulusPalletXcmError = Null;
 
-  /** @name CumulusPalletDmpQueueConfigData (475) */
+  /** @name CumulusPalletDmpQueueConfigData (477) */
   interface CumulusPalletDmpQueueConfigData extends Struct {
     readonly maxIndividual: SpWeightsWeightV2Weight;
   }
 
-  /** @name CumulusPalletDmpQueuePageIndexData (476) */
+  /** @name CumulusPalletDmpQueuePageIndexData (478) */
   interface CumulusPalletDmpQueuePageIndexData extends Struct {
     readonly beginUsed: u32;
     readonly endUsed: u32;
     readonly overweightCount: u64;
   }
 
-  /** @name CumulusPalletDmpQueueError (479) */
+  /** @name CumulusPalletDmpQueueError (481) */
   interface CumulusPalletDmpQueueError extends Enum {
     readonly isUnknown: boolean;
     readonly isOverLimit: boolean;
     readonly type: 'Unknown' | 'OverLimit';
   }
 
-  /** @name PalletUniqueError (483) */
+  /** @name PalletUniqueError (485) */
   interface PalletUniqueError extends Enum {
     readonly isCollectionDecimalPointLimitExceeded: boolean;
     readonly isEmptyArgument: boolean;
@@ -3906,13 +3908,13 @@
     readonly type: 'CollectionDecimalPointLimitExceeded' | 'EmptyArgument' | 'RepartitionCalledOnNonRefungibleCollection';
   }
 
-  /** @name PalletConfigurationError (484) */
+  /** @name PalletConfigurationError (486) */
   interface PalletConfigurationError extends Enum {
     readonly isInconsistentConfiguration: boolean;
     readonly type: 'InconsistentConfiguration';
   }
 
-  /** @name UpDataStructsCollection (485) */
+  /** @name UpDataStructsCollection (487) */
   interface UpDataStructsCollection extends Struct {
     readonly owner: AccountId32;
     readonly mode: UpDataStructsCollectionMode;
@@ -3925,7 +3927,7 @@
     readonly flags: U8aFixed;
   }
 
-  /** @name UpDataStructsSponsorshipStateAccountId32 (486) */
+  /** @name UpDataStructsSponsorshipStateAccountId32 (488) */
   interface UpDataStructsSponsorshipStateAccountId32 extends Enum {
     readonly isDisabled: boolean;
     readonly isUnconfirmed: boolean;
@@ -3935,43 +3937,43 @@
     readonly type: 'Disabled' | 'Unconfirmed' | 'Confirmed';
   }
 
-  /** @name UpDataStructsProperties (487) */
+  /** @name UpDataStructsProperties (489) */
   interface UpDataStructsProperties extends Struct {
     readonly map: UpDataStructsPropertiesMapBoundedVec;
     readonly consumedSpace: u32;
     readonly reserved: u32;
   }
 
-  /** @name UpDataStructsPropertiesMapBoundedVec (488) */
+  /** @name UpDataStructsPropertiesMapBoundedVec (490) */
   interface UpDataStructsPropertiesMapBoundedVec extends BTreeMap<Bytes, Bytes> {}
 
-  /** @name UpDataStructsPropertiesMapPropertyPermission (493) */
+  /** @name UpDataStructsPropertiesMapPropertyPermission (495) */
   interface UpDataStructsPropertiesMapPropertyPermission extends BTreeMap<Bytes, UpDataStructsPropertyPermission> {}
 
-  /** @name UpDataStructsCollectionStats (500) */
+  /** @name UpDataStructsCollectionStats (502) */
   interface UpDataStructsCollectionStats extends Struct {
     readonly created: u32;
     readonly destroyed: u32;
     readonly alive: u32;
   }
 
-  /** @name UpDataStructsTokenChild (501) */
+  /** @name UpDataStructsTokenChild (503) */
   interface UpDataStructsTokenChild extends Struct {
     readonly token: u32;
     readonly collection: u32;
   }
 
-  /** @name PhantomTypeUpDataStructs (502) */
+  /** @name PhantomTypeUpDataStructs (504) */
   interface PhantomTypeUpDataStructs extends Vec<ITuple<[UpDataStructsTokenData, UpDataStructsRpcCollection, UpPovEstimateRpcPovInfo]>> {}
 
-  /** @name UpDataStructsTokenData (504) */
+  /** @name UpDataStructsTokenData (506) */
   interface UpDataStructsTokenData extends Struct {
     readonly properties: Vec<UpDataStructsProperty>;
     readonly owner: Option<PalletEvmAccountBasicCrossAccountIdRepr>;
     readonly pieces: u128;
   }
 
-  /** @name UpDataStructsRpcCollection (506) */
+  /** @name UpDataStructsRpcCollection (507) */
   interface UpDataStructsRpcCollection extends Struct {
     readonly owner: AccountId32;
     readonly mode: UpDataStructsCollectionMode;
@@ -3987,13 +3989,13 @@
     readonly flags: UpDataStructsRpcCollectionFlags;
   }
 
-  /** @name UpDataStructsRpcCollectionFlags (507) */
+  /** @name UpDataStructsRpcCollectionFlags (508) */
   interface UpDataStructsRpcCollectionFlags extends Struct {
     readonly foreign: bool;
     readonly erc721metadata: bool;
   }
 
-  /** @name UpPovEstimateRpcPovInfo (508) */
+  /** @name UpPovEstimateRpcPovInfo (509) */
   interface UpPovEstimateRpcPovInfo extends Struct {
     readonly proofSize: u64;
     readonly compactProofSize: u64;
@@ -4002,7 +4004,7 @@
     readonly keyValues: Vec<UpPovEstimateRpcTrieKeyValue>;
   }
 
-  /** @name SpRuntimeTransactionValidityTransactionValidityError (511) */
+  /** @name SpRuntimeTransactionValidityTransactionValidityError (512) */
   interface SpRuntimeTransactionValidityTransactionValidityError extends Enum {
     readonly isInvalid: boolean;
     readonly asInvalid: SpRuntimeTransactionValidityInvalidTransaction;
@@ -4011,7 +4013,7 @@
     readonly type: 'Invalid' | 'Unknown';
   }
 
-  /** @name SpRuntimeTransactionValidityInvalidTransaction (512) */
+  /** @name SpRuntimeTransactionValidityInvalidTransaction (513) */
   interface SpRuntimeTransactionValidityInvalidTransaction extends Enum {
     readonly isCall: boolean;
     readonly isPayment: boolean;
@@ -4028,7 +4030,7 @@
     readonly type: 'Call' | 'Payment' | 'Future' | 'Stale' | 'BadProof' | 'AncientBirthBlock' | 'ExhaustsResources' | 'Custom' | 'BadMandatory' | 'MandatoryValidation' | 'BadSigner';
   }
 
-  /** @name SpRuntimeTransactionValidityUnknownTransaction (513) */
+  /** @name SpRuntimeTransactionValidityUnknownTransaction (514) */
   interface SpRuntimeTransactionValidityUnknownTransaction extends Enum {
     readonly isCannotLookup: boolean;
     readonly isNoUnsignedValidator: boolean;
@@ -4037,13 +4039,13 @@
     readonly type: 'CannotLookup' | 'NoUnsignedValidator' | 'Custom';
   }
 
-  /** @name UpPovEstimateRpcTrieKeyValue (515) */
+  /** @name UpPovEstimateRpcTrieKeyValue (516) */
   interface UpPovEstimateRpcTrieKeyValue extends Struct {
     readonly key: Bytes;
     readonly value: Bytes;
   }
 
-  /** @name PalletCommonError (517) */
+  /** @name PalletCommonError (518) */
   interface PalletCommonError extends Enum {
     readonly isCollectionNotFound: boolean;
     readonly isMustBeTokenOwner: boolean;
@@ -4085,7 +4087,7 @@
     readonly type: 'CollectionNotFound' | 'MustBeTokenOwner' | 'NoPermission' | 'CantDestroyNotEmptyCollection' | 'PublicMintingNotAllowed' | 'AddressNotInAllowlist' | 'CollectionNameLimitExceeded' | 'CollectionDescriptionLimitExceeded' | 'CollectionTokenPrefixLimitExceeded' | 'TotalCollectionsLimitExceeded' | 'CollectionAdminCountExceeded' | 'CollectionLimitBoundsExceeded' | 'OwnerPermissionsCantBeReverted' | 'TransferNotAllowed' | 'AccountTokenLimitExceeded' | 'CollectionTokenLimitExceeded' | 'MetadataFlagFrozen' | 'TokenNotFound' | 'TokenValueTooLow' | 'ApprovedValueTooLow' | 'CantApproveMoreThanOwned' | 'AddressIsNotEthMirror' | 'AddressIsZero' | 'UnsupportedOperation' | 'NotSufficientFounds' | 'UserIsNotAllowedToNest' | 'SourceCollectionIsNotAllowedToNest' | 'CollectionFieldSizeExceeded' | 'NoSpaceForProperty' | 'PropertyLimitReached' | 'PropertyKeyIsTooLong' | 'InvalidCharacterInPropertyKey' | 'EmptyPropertyKey' | 'CollectionIsExternal' | 'CollectionIsInternal' | 'ConfirmSponsorshipFail' | 'UserIsNotCollectionAdmin';
   }
 
-  /** @name PalletFungibleError (519) */
+  /** @name PalletFungibleError (520) */
   interface PalletFungibleError extends Enum {
     readonly isNotFungibleDataUsedToMintFungibleCollectionToken: boolean;
     readonly isFungibleItemsHaveNoId: boolean;
@@ -4097,7 +4099,7 @@
     readonly type: 'NotFungibleDataUsedToMintFungibleCollectionToken' | 'FungibleItemsHaveNoId' | 'FungibleItemsDontHaveData' | 'FungibleDisallowsNesting' | 'SettingPropertiesNotAllowed' | 'SettingAllowanceForAllNotAllowed' | 'FungibleTokensAreAlwaysValid';
   }
 
-  /** @name PalletRefungibleError (524) */
+  /** @name PalletRefungibleError (525) */
   interface PalletRefungibleError extends Enum {
     readonly isNotRefungibleDataUsedToMintFungibleCollectionToken: boolean;
     readonly isWrongRefungiblePieces: boolean;
@@ -4107,19 +4109,19 @@
     readonly type: 'NotRefungibleDataUsedToMintFungibleCollectionToken' | 'WrongRefungiblePieces' | 'RepartitionWhileNotOwningAllPieces' | 'RefungibleDisallowsNesting' | 'SettingPropertiesNotAllowed';
   }
 
-  /** @name PalletNonfungibleItemData (525) */
+  /** @name PalletNonfungibleItemData (526) */
   interface PalletNonfungibleItemData extends Struct {
     readonly owner: PalletEvmAccountBasicCrossAccountIdRepr;
   }
 
-  /** @name UpDataStructsPropertyScope (527) */
+  /** @name UpDataStructsPropertyScope (528) */
   interface UpDataStructsPropertyScope extends Enum {
     readonly isNone: boolean;
     readonly isRmrk: boolean;
     readonly type: 'None' | 'Rmrk';
   }
 
-  /** @name PalletNonfungibleError (530) */
+  /** @name PalletNonfungibleError (531) */
   interface PalletNonfungibleError extends Enum {
     readonly isNotNonfungibleDataUsedToMintFungibleCollectionToken: boolean;
     readonly isNonfungibleItemsHaveNoAmount: boolean;
@@ -4127,7 +4129,7 @@
     readonly type: 'NotNonfungibleDataUsedToMintFungibleCollectionToken' | 'NonfungibleItemsHaveNoAmount' | 'CantBurnNftWithChildren';
   }
 
-  /** @name PalletStructureError (531) */
+  /** @name PalletStructureError (532) */
   interface PalletStructureError extends Enum {
     readonly isOuroborosDetected: boolean;
     readonly isDepthLimit: boolean;
@@ -4137,7 +4139,7 @@
     readonly type: 'OuroborosDetected' | 'DepthLimit' | 'BreadthLimit' | 'TokenNotFound' | 'CantNestTokenUnderCollection';
   }
 
-  /** @name PalletAppPromotionError (536) */
+  /** @name PalletAppPromotionError (537) */
   interface PalletAppPromotionError extends Enum {
     readonly isAdminNotSet: boolean;
     readonly isNoPermission: boolean;
@@ -4149,7 +4151,7 @@
     readonly type: 'AdminNotSet' | 'NoPermission' | 'NotSufficientFunds' | 'PendingForBlockOverflow' | 'SponsorNotSet' | 'InsufficientStakedBalance' | 'InconsistencyState';
   }
 
-  /** @name PalletForeignAssetsModuleError (537) */
+  /** @name PalletForeignAssetsModuleError (538) */
   interface PalletForeignAssetsModuleError extends Enum {
     readonly isBadLocation: boolean;
     readonly isMultiLocationExisted: boolean;
@@ -4158,13 +4160,13 @@
     readonly type: 'BadLocation' | 'MultiLocationExisted' | 'AssetIdNotExists' | 'AssetIdExisted';
   }
 
-  /** @name PalletEvmCodeMetadata (538) */
+  /** @name PalletEvmCodeMetadata (539) */
   interface PalletEvmCodeMetadata extends Struct {
     readonly size_: u64;
     readonly hash_: H256;
   }
 
-  /** @name PalletEvmError (540) */
+  /** @name PalletEvmError (541) */
   interface PalletEvmError extends Enum {
     readonly isBalanceLow: boolean;
     readonly isFeeOverflow: boolean;
@@ -4180,7 +4182,7 @@
     readonly type: 'BalanceLow' | 'FeeOverflow' | 'PaymentOverflow' | 'WithdrawFailed' | 'GasPriceTooLow' | 'InvalidNonce' | 'GasLimitTooLow' | 'GasLimitTooHigh' | 'Undefined' | 'Reentrancy' | 'TransactionMustComeFromEOA';
   }
 
-  /** @name FpRpcTransactionStatus (543) */
+  /** @name FpRpcTransactionStatus (544) */
   interface FpRpcTransactionStatus extends Struct {
     readonly transactionHash: H256;
     readonly transactionIndex: u32;
@@ -4191,10 +4193,10 @@
     readonly logsBloom: EthbloomBloom;
   }
 
-  /** @name EthbloomBloom (545) */
+  /** @name EthbloomBloom (546) */
   interface EthbloomBloom extends U8aFixed {}
 
-  /** @name EthereumReceiptReceiptV3 (547) */
+  /** @name EthereumReceiptReceiptV3 (548) */
   interface EthereumReceiptReceiptV3 extends Enum {
     readonly isLegacy: boolean;
     readonly asLegacy: EthereumReceiptEip658ReceiptData;
@@ -4205,7 +4207,7 @@
     readonly type: 'Legacy' | 'Eip2930' | 'Eip1559';
   }
 
-  /** @name EthereumReceiptEip658ReceiptData (548) */
+  /** @name EthereumReceiptEip658ReceiptData (549) */
   interface EthereumReceiptEip658ReceiptData extends Struct {
     readonly statusCode: u8;
     readonly usedGas: U256;
@@ -4213,14 +4215,14 @@
     readonly logs: Vec<EthereumLog>;
   }
 
-  /** @name EthereumBlock (549) */
+  /** @name EthereumBlock (550) */
   interface EthereumBlock extends Struct {
     readonly header: EthereumHeader;
     readonly transactions: Vec<EthereumTransactionTransactionV2>;
     readonly ommers: Vec<EthereumHeader>;
   }
 
-  /** @name EthereumHeader (550) */
+  /** @name EthereumHeader (551) */
   interface EthereumHeader extends Struct {
     readonly parentHash: H256;
     readonly ommersHash: H256;
@@ -4239,24 +4241,24 @@
     readonly nonce: EthereumTypesHashH64;
   }
 
-  /** @name EthereumTypesHashH64 (551) */
+  /** @name EthereumTypesHashH64 (552) */
   interface EthereumTypesHashH64 extends U8aFixed {}
 
-  /** @name PalletEthereumError (556) */
+  /** @name PalletEthereumError (557) */
   interface PalletEthereumError extends Enum {
     readonly isInvalidSignature: boolean;
     readonly isPreLogExists: boolean;
     readonly type: 'InvalidSignature' | 'PreLogExists';
   }
 
-  /** @name PalletEvmCoderSubstrateError (557) */
+  /** @name PalletEvmCoderSubstrateError (558) */
   interface PalletEvmCoderSubstrateError extends Enum {
     readonly isOutOfGas: boolean;
     readonly isOutOfFund: boolean;
     readonly type: 'OutOfGas' | 'OutOfFund';
   }
 
-  /** @name UpDataStructsSponsorshipStateBasicCrossAccountIdRepr (558) */
+  /** @name UpDataStructsSponsorshipStateBasicCrossAccountIdRepr (559) */
   interface UpDataStructsSponsorshipStateBasicCrossAccountIdRepr extends Enum {
     readonly isDisabled: boolean;
     readonly isUnconfirmed: boolean;
@@ -4266,7 +4268,7 @@
     readonly type: 'Disabled' | 'Unconfirmed' | 'Confirmed';
   }
 
-  /** @name PalletEvmContractHelpersSponsoringModeT (559) */
+  /** @name PalletEvmContractHelpersSponsoringModeT (560) */
   interface PalletEvmContractHelpersSponsoringModeT extends Enum {
     readonly isDisabled: boolean;
     readonly isAllowlisted: boolean;
@@ -4274,7 +4276,7 @@
     readonly type: 'Disabled' | 'Allowlisted' | 'Generous';
   }
 
-  /** @name PalletEvmContractHelpersError (565) */
+  /** @name PalletEvmContractHelpersError (566) */
   interface PalletEvmContractHelpersError extends Enum {
     readonly isNoPermission: boolean;
     readonly isNoPendingSponsor: boolean;
@@ -4282,7 +4284,7 @@
     readonly type: 'NoPermission' | 'NoPendingSponsor' | 'TooManyMethodsHaveSponsoredLimit';
   }
 
-  /** @name PalletEvmMigrationError (566) */
+  /** @name PalletEvmMigrationError (567) */
   interface PalletEvmMigrationError extends Enum {
     readonly isAccountNotEmpty: boolean;
     readonly isAccountIsNotMigrating: boolean;
@@ -4290,17 +4292,17 @@
     readonly type: 'AccountNotEmpty' | 'AccountIsNotMigrating' | 'BadEvent';
   }
 
-  /** @name PalletMaintenanceError (567) */
+  /** @name PalletMaintenanceError (568) */
   type PalletMaintenanceError = Null;
 
-  /** @name PalletTestUtilsError (568) */
+  /** @name PalletTestUtilsError (569) */
   interface PalletTestUtilsError extends Enum {
     readonly isTestPalletDisabled: boolean;
     readonly isTriggerRollback: boolean;
     readonly type: 'TestPalletDisabled' | 'TriggerRollback';
   }
 
-  /** @name SpRuntimeMultiSignature (570) */
+  /** @name SpRuntimeMultiSignature (571) */
   interface SpRuntimeMultiSignature extends Enum {
     readonly isEd25519: boolean;
     readonly asEd25519: SpCoreEd25519Signature;
@@ -4311,43 +4313,43 @@
     readonly type: 'Ed25519' | 'Sr25519' | 'Ecdsa';
   }
 
-  /** @name SpCoreEd25519Signature (571) */
+  /** @name SpCoreEd25519Signature (572) */
   interface SpCoreEd25519Signature extends U8aFixed {}
 
-  /** @name SpCoreSr25519Signature (573) */
+  /** @name SpCoreSr25519Signature (574) */
   interface SpCoreSr25519Signature extends U8aFixed {}
 
-  /** @name SpCoreEcdsaSignature (574) */
+  /** @name SpCoreEcdsaSignature (575) */
   interface SpCoreEcdsaSignature extends U8aFixed {}
 
-  /** @name FrameSystemExtensionsCheckSpecVersion (577) */
+  /** @name FrameSystemExtensionsCheckSpecVersion (578) */
   type FrameSystemExtensionsCheckSpecVersion = Null;
 
-  /** @name FrameSystemExtensionsCheckTxVersion (578) */
+  /** @name FrameSystemExtensionsCheckTxVersion (579) */
   type FrameSystemExtensionsCheckTxVersion = Null;
 
-  /** @name FrameSystemExtensionsCheckGenesis (579) */
+  /** @name FrameSystemExtensionsCheckGenesis (580) */
   type FrameSystemExtensionsCheckGenesis = Null;
 
-  /** @name FrameSystemExtensionsCheckNonce (582) */
+  /** @name FrameSystemExtensionsCheckNonce (583) */
   interface FrameSystemExtensionsCheckNonce extends Compact<u32> {}
 
-  /** @name FrameSystemExtensionsCheckWeight (583) */
+  /** @name FrameSystemExtensionsCheckWeight (584) */
   type FrameSystemExtensionsCheckWeight = Null;
 
-  /** @name OpalRuntimeRuntimeCommonMaintenanceCheckMaintenance (584) */
+  /** @name OpalRuntimeRuntimeCommonMaintenanceCheckMaintenance (585) */
   type OpalRuntimeRuntimeCommonMaintenanceCheckMaintenance = Null;
 
-  /** @name OpalRuntimeRuntimeCommonIdentityDisableIdentityCalls (585) */
+  /** @name OpalRuntimeRuntimeCommonIdentityDisableIdentityCalls (586) */
   type OpalRuntimeRuntimeCommonIdentityDisableIdentityCalls = Null;
 
-  /** @name PalletTemplateTransactionPaymentChargeTransactionPayment (586) */
+  /** @name PalletTemplateTransactionPaymentChargeTransactionPayment (587) */
   interface PalletTemplateTransactionPaymentChargeTransactionPayment extends Compact<u128> {}
 
-  /** @name OpalRuntimeRuntime (587) */
+  /** @name OpalRuntimeRuntime (588) */
   type OpalRuntimeRuntime = Null;
 
-  /** @name PalletEthereumFakeTransactionFinalizer (588) */
+  /** @name PalletEthereumFakeTransactionFinalizer (589) */
   type PalletEthereumFakeTransactionFinalizer = Null;
 
 } // declare module
modifiedtests/src/sub/appPromotion/appPromotion.test.tsdiffbeforeafterboth
--- a/tests/src/sub/appPromotion/appPromotion.test.ts
+++ b/tests/src/sub/appPromotion/appPromotion.test.ts
@@ -51,6 +51,7 @@
       donor = await privateKey({url: import.meta.url});
       palletAddress = helper.arrange.calculatePalletAddress('appstake');
       palletAdmin = await privateKey('//PromotionAdmin');
+
       nominal = helper.balance.getOneTokenNominal();
 
       const accountBalances = new Array(200).fill(1000n);
@@ -96,7 +97,6 @@
       expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);
       // it is potentially flaky test. Promotion can credited some tokens. Maybe we need to use closeTo?
       expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedBefore + 100n * nominal); // total tokens amount staked in app-promotion increased
-
 
       await helper.staking.stake(staker, 200n * nominal);
       expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(300n * nominal);
@@ -497,13 +497,13 @@
       expect((await collectionWithoutSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});
 
       // Can set sponsoring for collection with unconfirmed sponsor
-      const collectionWithUnconfirmedSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'Unconfirmed', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: oldSponsor.address});
+      const collectionWithUnconfirmedSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'Unconfirmed', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: {Substrate: oldSponsor.address}});
       expect((await collectionWithUnconfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Unconfirmed: oldSponsor.address});
       await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionWithUnconfirmedSponsor.collectionId))).to.be.fulfilled;
       expect((await collectionWithUnconfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});
 
       // Can set sponsoring for collection with confirmed sponsor
-      const collectionWithConfirmedSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'Confirmed', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: oldSponsor.address});
+      const collectionWithConfirmedSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'Confirmed', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: {Substrate: oldSponsor.address}});
       await collectionWithConfirmedSponsor.confirmSponsorship(oldSponsor);
       await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionWithConfirmedSponsor.collectionId))).to.be.fulfilled;
       expect((await collectionWithConfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});
@@ -584,7 +584,7 @@
     itSub('should not affect collection which is not sponsored by pallete', async ({helper}) => {
       const api = helper.getApi();
       const [collectionOwner] = await getAccounts(1);
-      const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: collectionOwner.address});
+      const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: {Substrate: collectionOwner.address}});
       await collection.confirmSponsorship(collectionOwner);
 
       await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.rejected;
modifiedtests/src/util/playgrounds/types.tsdiffbeforeafterboth
--- a/tests/src/util/playgrounds/types.ts
+++ b/tests/src/util/playgrounds/types.ts
@@ -142,6 +142,21 @@
   }
 }
 
+export interface ICollectionFlags {
+  foreign: boolean,
+  erc721metadata: boolean,
+}
+
+export enum CollectionFlag {
+  None = 0,
+  /// External collections can't be managed using `unique` api
+  External = 1,
+  /// Supports ERC721Metadata
+  Erc721metadata = 64,
+  /// Tokens in foreign collections can be transferred, but not burnt
+  Foreign = 128,
+}
+
 export interface ICollectionCreationOptions {
   name?: string | number[];
   description?: string | number[];
@@ -155,7 +170,9 @@
   properties?: IProperty[];
   tokenPropertyPermissions?: ITokenPropertyPermission[];
   limits?: ICollectionLimits;
-  pendingSponsor?: TSubstrateAccount;
+  pendingSponsor?: ICrossAccountId;
+  adminList?: ICrossAccountId[];
+  flags?: number[] | CollectionFlag[] ,
 }
 
 export interface IChainProperties {
modifiedtests/src/util/playgrounds/unique.tsdiffbeforeafterboth
--- a/tests/src/util/playgrounds/unique.ts
+++ b/tests/src/util/playgrounds/unique.ts
@@ -44,10 +44,12 @@
   MoonbeamAssetInfo,
   DemocracyStandardAccountVote,
   IEthCrossAccountId,
+  CollectionFlag,
 } from './types';
 import {RuntimeDispatchInfo} from '@polkadot/types/interfaces';
 import type {Vec} from '@polkadot/types-codec';
 import {FrameSystemEventRecord, PalletBalancesIdAmount} from '@polkadot/types/lookup';
+import {arrayUnzip} from '@polkadot/util';
 
 export class CrossAccountId {
   Substrate!: TSubstrateAccount;
@@ -1624,6 +1626,17 @@
     for(const key of ['name', 'description', 'tokenPrefix']) {
       if(typeof collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] === 'string') collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] = this.helper.util.str2vec(collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] as string);
     }
+
+    let flags = 0;
+    // convert CollectionFlags to number and join them in one number
+    if(collectionOptions.flags) {
+      for(let i = 0; i < collectionOptions.flags.length; i++){
+        const flag = collectionOptions.flags[i];
+        flags = flags | flag;
+      }
+    }
+    collectionOptions.flags = [flags];
+
     const creationResult = await this.helper.executeExtrinsic(
       signer,
       'api.tx.unique.createCollectionEx', [collectionOptions],