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

difftreelog

Add first draft of Properties

Daniel Shiposha2022-04-29parent: #c01b00c.patch.diff
in: master

14 files changed

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#![cfg_attr(not(feature = "std"), no_std)]1819use core::ops::{Deref, DerefMut};20use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};21use sp_std::vec::Vec;22use pallet_evm::account::CrossAccountId;23use frame_support::{24	dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},25	ensure, fail,26	traits::{Imbalance, Get, Currency, WithdrawReasons, ExistenceRequirement},27	BoundedVec,28	weights::Pays,29};30use pallet_evm::GasWeightMapping;31use up_data_structs::{32	COLLECTION_NUMBER_LIMIT, Collection, RpcCollection, CollectionId, CreateItemData,33	MAX_TOKEN_PREFIX_LENGTH, COLLECTION_ADMINS_LIMIT, MetaUpdatePermission, TokenId,34	CollectionStats, MAX_TOKEN_OWNERSHIP, CollectionMode, NFT_SPONSOR_TRANSFER_TIMEOUT,35	FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, MAX_SPONSOR_TIMEOUT,36	CUSTOM_DATA_LIMIT, CollectionLimits, CustomDataLimit, CreateCollectionData, SponsorshipState,37	CreateItemExData, SponsoringRateLimit, budget::Budget, COLLECTION_FIELD_LIMIT, CollectionField,38	PhantomType,39};40pub use pallet::*;41use sp_core::H160;42use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};43#[cfg(feature = "runtime-benchmarks")]44pub mod benchmarking;45pub mod dispatch;46pub mod erc;47pub mod eth;4849#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]50pub struct CollectionHandle<T: Config> {51	pub id: CollectionId,52	collection: Collection<T::AccountId>,53	pub recorder: SubstrateRecorder<T>,54}55impl<T: Config> WithRecorder<T> for CollectionHandle<T> {56	fn recorder(&self) -> &SubstrateRecorder<T> {57		&self.recorder58	}59	fn into_recorder(self) -> SubstrateRecorder<T> {60		self.recorder61	}62}63impl<T: Config> CollectionHandle<T> {64	pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {65		<CollectionById<T>>::get(id).map(|collection| Self {66			id,67			collection,68			recorder: SubstrateRecorder::new(eth::collection_id_to_address(id), gas_limit),69		})70	}71	pub fn new(id: CollectionId) -> Option<Self> {72		Self::new_with_gas_limit(id, u64::MAX)73	}74	pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {75		Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)76	}77	pub fn log_mirrored(&self, log: impl evm_coder::ToLog) {78		self.recorder.log_mirrored(log)79	}80	pub fn log_direct(&self, log: impl evm_coder::ToLog) {81		self.recorder.log_direct(log)82	}83	pub fn consume_store_reads(&self, reads: u64) -> evm_coder::execution::Result<()> {84		self.recorder85			.consume_gas(T::GasWeightMapping::weight_to_gas(86				<T as frame_system::Config>::DbWeight::get()87					.read88					.saturating_mul(reads),89			))90	}91	pub fn consume_store_writes(&self, writes: u64) -> evm_coder::execution::Result<()> {92		self.recorder93			.consume_gas(T::GasWeightMapping::weight_to_gas(94				<T as frame_system::Config>::DbWeight::get()95					.write96					.saturating_mul(writes),97			))98	}99	pub fn submit_logs(self) {100		self.recorder.submit_logs()101	}102	pub fn save(self) -> DispatchResult {103		self.recorder.submit_logs();104		<CollectionById<T>>::insert(self.id, self.collection);105		Ok(())106	}107}108impl<T: Config> Deref for CollectionHandle<T> {109	type Target = Collection<T::AccountId>;110111	fn deref(&self) -> &Self::Target {112		&self.collection113	}114}115116impl<T: Config> DerefMut for CollectionHandle<T> {117	fn deref_mut(&mut self) -> &mut Self::Target {118		&mut self.collection119	}120}121122impl<T: Config> CollectionHandle<T> {123	pub fn check_is_owner(&self, subject: &T::CrossAccountId) -> DispatchResult {124		ensure!(*subject.as_sub() == self.owner, <Error<T>>::NoPermission);125		Ok(())126	}127	pub fn is_owner_or_admin(&self, subject: &T::CrossAccountId) -> bool {128		*subject.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, subject))129	}130	pub fn check_is_owner_or_admin(&self, subject: &T::CrossAccountId) -> DispatchResult {131		ensure!(self.is_owner_or_admin(subject), <Error<T>>::NoPermission);132		Ok(())133	}134	pub fn ignores_allowance(&self, user: &T::CrossAccountId) -> bool {135		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)136	}137	pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {138		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)139	}140	pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {141		ensure!(142			<Allowlist<T>>::get((self.id, user)),143			<Error<T>>::AddressNotInAllowlist144		);145		Ok(())146	}147148	pub fn check_can_update_meta(149		&self,150		subject: &T::CrossAccountId,151		item_owner: &T::CrossAccountId,152	) -> DispatchResult {153		match self.meta_update_permission {154			MetaUpdatePermission::ItemOwner => {155				ensure!(subject == item_owner, <Error<T>>::NoPermission);156				Ok(())157			}158			MetaUpdatePermission::Admin => self.check_is_owner_or_admin(subject),159			MetaUpdatePermission::None => fail!(<Error<T>>::NoPermission),160		}161	}162}163164#[frame_support::pallet]165pub mod pallet {166	use super::*;167	use pallet_evm::account;168	use dispatch::CollectionDispatch;169	use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};170	use frame_system::pallet_prelude::*;171	use frame_support::traits::Currency;172	use up_data_structs::{TokenId, mapping::TokenAddressMapping};173	use scale_info::TypeInfo;174175	#[pallet::config]176	pub trait Config:177		frame_system::Config + pallet_evm_coder_substrate::Config + TypeInfo + account::Config178	{179		type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>;180181		type Currency: Currency<Self::AccountId>;182183		#[pallet::constant]184		type CollectionCreationPrice: Get<185			<<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,186		>;187		type CollectionDispatch: CollectionDispatch<Self>;188189		type TreasuryAccountId: Get<Self::AccountId>;190191		type EvmTokenAddressMapping: TokenAddressMapping<H160>;192		type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;193	}194195	const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);196197	#[pallet::pallet]198	#[pallet::storage_version(STORAGE_VERSION)]199	#[pallet::generate_store(pub(super) trait Store)]200	pub struct Pallet<T>(_);201202	#[pallet::extra_constants]203	impl<T: Config> Pallet<T> {204		pub fn collection_admins_limit() -> u32 {205			COLLECTION_ADMINS_LIMIT206		}207	}208209	#[pallet::event]210	#[pallet::generate_deposit(pub fn deposit_event)]211	pub enum Event<T: Config> {212		/// New collection was created213		///214		/// # Arguments215		///216		/// * collection_id: Globally unique identifier of newly created collection.217		///218		/// * mode: [CollectionMode] converted into u8.219		///220		/// * account_id: Collection owner.221		CollectionCreated(CollectionId, u8, T::AccountId),222223		/// New collection was destroyed224		///225		/// # Arguments226		///227		/// * collection_id: Globally unique identifier of collection.228		CollectionDestroyed(CollectionId),229230		/// New item was created.231		///232		/// # Arguments233		///234		/// * collection_id: Id of the collection where item was created.235		///236		/// * item_id: Id of an item. Unique within the collection.237		///238		/// * recipient: Owner of newly created item239		///240		/// * amount: Always 1 for NFT241		ItemCreated(CollectionId, TokenId, T::CrossAccountId, u128),242243		/// Collection item was burned.244		///245		/// # Arguments246		///247		/// * collection_id.248		///249		/// * item_id: Identifier of burned NFT.250		///251		/// * owner: which user has destroyed its tokens252		///253		/// * amount: Always 1 for NFT254		ItemDestroyed(CollectionId, TokenId, T::CrossAccountId, u128),255256		/// Item was transferred257		///258		/// * collection_id: Id of collection to which item is belong259		///260		/// * item_id: Id of an item261		///262		/// * sender: Original owner of item263		///264		/// * recipient: New owner of item265		///266		/// * amount: Always 1 for NFT267		Transfer(268			CollectionId,269			TokenId,270			T::CrossAccountId,271			T::CrossAccountId,272			u128,273		),274275		/// * collection_id276		///277		/// * item_id278		///279		/// * sender280		///281		/// * spender282		///283		/// * amount284		Approved(285			CollectionId,286			TokenId,287			T::CrossAccountId,288			T::CrossAccountId,289			u128,290		),291	}292293	#[pallet::error]294	pub enum Error<T> {295		/// This collection does not exist.296		CollectionNotFound,297		/// Sender parameter and item owner must be equal.298		MustBeTokenOwner,299		/// No permission to perform action300		NoPermission,301		/// Collection is not in mint mode.302		PublicMintingNotAllowed,303		/// Address is not in allow list.304		AddressNotInAllowlist,305306		/// Collection name can not be longer than 63 char.307		CollectionNameLimitExceeded,308		/// Collection description can not be longer than 255 char.309		CollectionDescriptionLimitExceeded,310		/// Token prefix can not be longer than 15 char.311		CollectionTokenPrefixLimitExceeded,312		/// Total collections bound exceeded.313		TotalCollectionsLimitExceeded,314		/// variable_data exceeded data limit.315		TokenVariableDataLimitExceeded,316		/// Exceeded max admin count317		CollectionAdminCountExceeded,318		/// Collection limit bounds per collection exceeded319		CollectionLimitBoundsExceeded,320		/// Tried to enable permissions which are only permitted to be disabled321		OwnerPermissionsCantBeReverted,322323		/// Collection settings not allowing items transferring324		TransferNotAllowed,325		/// Account token limit exceeded per collection326		AccountTokenLimitExceeded,327		/// Collection token limit exceeded328		CollectionTokenLimitExceeded,329		/// Metadata flag frozen330		MetadataFlagFrozen,331332		/// Item not exists.333		TokenNotFound,334		/// Item balance not enough.335		TokenValueTooLow,336		/// Requested value more than approved.337		ApprovedValueTooLow,338		/// Tried to approve more than owned339		CantApproveMoreThanOwned,340341		/// Can't transfer tokens to ethereum zero address342		AddressIsZero,343		/// Target collection doesn't supports this operation344		UnsupportedOperation,345346		/// Not sufficient founds to perform action347		NotSufficientFounds,348349		/// Collection has nesting disabled350		NestingIsDisabled,351		/// Only owner may nest tokens under this collection352		OnlyOwnerAllowedToNest,353		/// Only tokens from specific collections may nest tokens under this354		SourceCollectionIsNotAllowedToNest,355356		/// Tried to store more data than allowed in collection field357		CollectionFieldSizeExceeded,358	}359360	#[pallet::storage]361	pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;362	#[pallet::storage]363	pub type DestroyedCollectionCount<T> =364		StorageValue<Value = CollectionId, QueryKind = ValueQuery>;365366	/// Collection info367	#[pallet::storage]368	pub type CollectionById<T> = StorageMap<369		Hasher = Blake2_128Concat,370		Key = CollectionId,371		Value = Collection<<T as frame_system::Config>::AccountId>,372		QueryKind = OptionQuery,373	>;374375	/// Large variable-size collection fields are extracted here376	#[pallet::storage]377	pub type CollectionData<T> = StorageNMap<378		Key = (379			Key<Twox64Concat, CollectionId>,380			Key<Twox64Concat, CollectionField>,381		),382		Value = BoundedVec<u8, ConstU32<COLLECTION_FIELD_LIMIT>>,383		QueryKind = ValueQuery,384	>;385386	#[pallet::storage]387	pub type AdminAmount<T> = StorageMap<388		Hasher = Blake2_128Concat,389		Key = CollectionId,390		Value = u32,391		QueryKind = ValueQuery,392	>;393394	/// List of collection admins395	#[pallet::storage]396	pub type IsAdmin<T: Config> = StorageNMap<397		Key = (398			Key<Blake2_128Concat, CollectionId>,399			Key<Blake2_128Concat, T::CrossAccountId>,400		),401		Value = bool,402		QueryKind = ValueQuery,403	>;404405	/// Allowlisted collection users406	#[pallet::storage]407	pub type Allowlist<T: Config> = StorageNMap<408		Key = (409			Key<Blake2_128Concat, CollectionId>,410			Key<Blake2_128Concat, T::CrossAccountId>,411		),412		Value = bool,413		QueryKind = ValueQuery,414	>;415416	/// Not used by code, exists only to provide some types to metadata417	#[pallet::storage]418	pub type DummyStorageValue<T: Config> = StorageValue<419		Value = (420			CollectionStats,421			CollectionId,422			TokenId,423			PhantomType<RpcCollection<T::AccountId>>,424		),425		QueryKind = OptionQuery,426	>;427428	#[pallet::hooks]429	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {430		fn on_runtime_upgrade() -> Weight {431			if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {432				use up_data_structs::{CollectionVersion1, CollectionVersion2};433				<CollectionById<T>>::translate::<CollectionVersion1<T::AccountId>, _>(|id, v| {434					Self::set_field_raw(435						id,436						CollectionField::OffchainSchema,437						v.offchain_schema.clone().into_inner(),438					)439					.expect("data has lower bounds than field");440					Self::set_field_raw(441						id,442						CollectionField::VariableOnChainSchema,443						v.variable_on_chain_schema.clone().into_inner(),444					)445					.expect("data has lower bounds than field");446					Self::set_field_raw(447						id,448						CollectionField::ConstOnChainSchema,449						v.const_on_chain_schema.clone().into_inner(),450					)451					.expect("data has lower bounds than field");452453					Some(CollectionVersion2::from(v))454				});455			}456457			0458		}459	}460}461462impl<T: Config> Pallet<T> {463	/// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens464	pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {465		ensure!(466			&T::CrossAccountId::from_eth(H160([0; 20])) != receiver,467			<Error<T>>::AddressIsZero468		);469		Ok(())470	}471	pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {472		<IsAdmin<T>>::iter_prefix((collection,))473			.map(|(a, _)| a)474			.collect()475	}476	pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {477		<Allowlist<T>>::iter_prefix((collection,))478			.map(|(a, _)| a)479			.collect()480	}481	pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {482		<Allowlist<T>>::get((collection, user))483	}484	pub fn collection_stats() -> CollectionStats {485		let created = <CreatedCollectionCount<T>>::get();486		let destroyed = <DestroyedCollectionCount<T>>::get();487		CollectionStats {488			created: created.0,489			destroyed: destroyed.0,490			alive: created.0 - destroyed.0,491		}492	}493494	pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {495		let collection = <CollectionById<T>>::get(collection);496		if collection.is_none() {497			return None;498		}499500		let collection = collection.unwrap();501		let limits = collection.limits;502		let effective_limits = CollectionLimits {503			account_token_ownership_limit: Some(limits.account_token_ownership_limit()),504			sponsored_data_size: Some(limits.sponsored_data_size()),505			sponsored_data_rate_limit: Some(506				limits507					.sponsored_data_rate_limit508					.unwrap_or(SponsoringRateLimit::SponsoringDisabled),509			),510			token_limit: Some(limits.token_limit()),511			sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(512				match collection.mode {513					CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,514					CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,515					CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,516				},517			)),518			sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),519			owner_can_transfer: Some(limits.owner_can_transfer()),520			owner_can_destroy: Some(limits.owner_can_destroy()),521			transfers_enabled: Some(limits.transfers_enabled()),522			nesting_rule: Some(limits.nesting_rule().clone()),523		};524525		Some(effective_limits)526	}527528	pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {529		let Collection {530			name,531			description,532			owner,533			mode,534			access,535			token_prefix,536			mint_mode,537			schema_version,538			sponsorship,539			limits,540			meta_update_permission,541		} = <CollectionById<T>>::get(collection)?;542		Some(RpcCollection {543			name: name.into_inner(),544			description: description.into_inner(),545			owner,546			mode,547			access,548			token_prefix: token_prefix.into_inner(),549			mint_mode,550			schema_version,551			sponsorship,552			limits,553			meta_update_permission,554			offchain_schema: <CollectionData<T>>::get((555				collection,556				CollectionField::OffchainSchema,557			))558			.into_inner(),559			const_on_chain_schema: <CollectionData<T>>::get((560				collection,561				CollectionField::ConstOnChainSchema,562			))563			.into_inner(),564			variable_on_chain_schema: <CollectionData<T>>::get((565				collection,566				CollectionField::VariableOnChainSchema,567			))568			.into_inner(),569		})570	}571}572573impl<T: Config> Pallet<T> {574	pub fn init_collection(575		owner: T::AccountId,576		data: CreateCollectionData<T::AccountId>,577	) -> Result<CollectionId, DispatchError> {578		{579			ensure!(580				data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,581				Error::<T>::CollectionTokenPrefixLimitExceeded582			);583		}584585		let created_count = <CreatedCollectionCount<T>>::get()586			.0587			.checked_add(1)588			.ok_or(ArithmeticError::Overflow)?;589		let destroyed_count = <DestroyedCollectionCount<T>>::get().0;590		let id = CollectionId(created_count);591592		// bound Total number of collections593		ensure!(594			created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,595			<Error<T>>::TotalCollectionsLimitExceeded596		);597598		// =========599600		let collection = Collection {601			owner: owner.clone(),602			name: data.name,603			mode: data.mode.clone(),604			mint_mode: false,605			access: data.access.unwrap_or_default(),606			description: data.description,607			token_prefix: data.token_prefix,608			schema_version: data.schema_version.unwrap_or_default(),609			sponsorship: data610				.pending_sponsor611				.map(SponsorshipState::Unconfirmed)612				.unwrap_or_default(),613			limits: data614				.limits615				.map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))616				.unwrap_or_else(|| Ok(CollectionLimits::default()))?,617			meta_update_permission: data.meta_update_permission.unwrap_or_default(),618		};619620		// Take a (non-refundable) deposit of collection creation621		{622			let mut imbalance =623				<<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();624			imbalance.subsume(625				<<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(626					&T::TreasuryAccountId::get(),627					T::CollectionCreationPrice::get(),628				),629			);630			<T as Config>::Currency::settle(631				&owner,632				imbalance,633				WithdrawReasons::TRANSFER,634				ExistenceRequirement::KeepAlive,635			)636			.map_err(|_| Error::<T>::NotSufficientFounds)?;637		}638639		<CreatedCollectionCount<T>>::put(created_count);640		<Pallet<T>>::deposit_event(Event::CollectionCreated(id, data.mode.id(), owner.clone()));641		<CollectionById<T>>::insert(id, collection);642		Self::set_field_raw(643			id,644			CollectionField::OffchainSchema,645			data.offchain_schema.into_inner(),646		)647		.expect("data has lower bounds than field");648		Self::set_field_raw(649			id,650			CollectionField::VariableOnChainSchema,651			data.variable_on_chain_schema.into_inner(),652		)653		.expect("data has lower bounds than field");654		Self::set_field_raw(655			id,656			CollectionField::ConstOnChainSchema,657			data.const_on_chain_schema.into_inner(),658		)659		.expect("data has lower bounds than field");660		Ok(id)661	}662663	pub fn destroy_collection(664		collection: CollectionHandle<T>,665		sender: &T::CrossAccountId,666	) -> DispatchResult {667		ensure!(668			collection.limits.owner_can_destroy(),669			<Error<T>>::NoPermission,670		);671		collection.check_is_owner(sender)?;672673		let destroyed_collections = <DestroyedCollectionCount<T>>::get()674			.0675			.checked_add(1)676			.ok_or(ArithmeticError::Overflow)?;677678		// =========679680		<DestroyedCollectionCount<T>>::put(destroyed_collections);681		<CollectionById<T>>::remove(collection.id);682		<CollectionData<T>>::remove_prefix((collection.id,), None);683		<AdminAmount<T>>::remove(collection.id);684		<IsAdmin<T>>::remove_prefix((collection.id,), None);685		<Allowlist<T>>::remove_prefix((collection.id,), None);686687		<Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));688		Ok(())689	}690691	fn set_field_raw(692		collection_id: CollectionId,693		field: CollectionField,694		value: Vec<u8>,695	) -> DispatchResult {696		if !value.is_empty() {697			<CollectionData<T>>::insert(698				(collection_id, field),699				BoundedVec::try_from(value).map_err(|_| <Error<T>>::CollectionFieldSizeExceeded)?,700			)701		} else {702			<CollectionData<T>>::remove((collection_id, field));703		}704		Ok(())705	}706707	pub fn set_field(708		collection: &CollectionHandle<T>,709		sender: &T::CrossAccountId,710		field: CollectionField,711		value: Vec<u8>,712	) -> DispatchResult {713		collection.check_is_owner_or_admin(sender)?;714715		// =========716717		Self::set_field_raw(collection.id, field, value)718	}719720	pub fn toggle_allowlist(721		collection: &CollectionHandle<T>,722		sender: &T::CrossAccountId,723		user: &T::CrossAccountId,724		allowed: bool,725	) -> DispatchResult {726		collection.check_is_owner_or_admin(sender)?;727728		// =========729730		if allowed {731			<Allowlist<T>>::insert((collection.id, user), true);732		} else {733			<Allowlist<T>>::remove((collection.id, user));734		}735736		Ok(())737	}738739	pub fn toggle_admin(740		collection: &CollectionHandle<T>,741		sender: &T::CrossAccountId,742		user: &T::CrossAccountId,743		admin: bool,744	) -> DispatchResult {745		collection.check_is_owner_or_admin(sender)?;746747		let was_admin = <IsAdmin<T>>::get((collection.id, user));748		if was_admin == admin {749			return Ok(());750		}751		let amount = <AdminAmount<T>>::get(collection.id);752753		if admin {754			let amount = amount755				.checked_add(1)756				.ok_or(<Error<T>>::CollectionAdminCountExceeded)?;757			ensure!(758				amount <= Self::collection_admins_limit(),759				<Error<T>>::CollectionAdminCountExceeded,760			);761762			// =========763764			<AdminAmount<T>>::insert(collection.id, amount);765			<IsAdmin<T>>::insert((collection.id, user), true);766		} else {767			<AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));768			<IsAdmin<T>>::remove((collection.id, user));769		}770771		Ok(())772	}773774	pub fn clamp_limits(775		mode: CollectionMode,776		old_limit: &CollectionLimits,777		mut new_limit: CollectionLimits,778	) -> Result<CollectionLimits, DispatchError> {779		macro_rules! limit_default {780				($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{781					$(782						if let Some($new) = $new.$field {783							let $old = $old.$field($($arg)?);784							let _ = $new;785							let _ = $old;786							$check787						} else {788							$new.$field = $old.$field789						}790					)*791				}};792			}793794		limit_default!(old_limit, new_limit,795			account_token_ownership_limit => ensure!(796				new_limit <= MAX_TOKEN_OWNERSHIP,797				<Error<T>>::CollectionLimitBoundsExceeded,798			),799			sponsor_transfer_timeout(match mode {800				CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,801				CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,802				CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,803			}) => ensure!(804				new_limit <= MAX_SPONSOR_TIMEOUT,805				<Error<T>>::CollectionLimitBoundsExceeded,806			),807			sponsored_data_size => ensure!(808				new_limit <= CUSTOM_DATA_LIMIT,809				<Error<T>>::CollectionLimitBoundsExceeded,810			),811			token_limit => ensure!(812				old_limit >= new_limit && new_limit > 0,813				<Error<T>>::CollectionTokenLimitExceeded814			),815			owner_can_transfer => ensure!(816				old_limit || !new_limit,817				<Error<T>>::OwnerPermissionsCantBeReverted,818			),819			owner_can_destroy => ensure!(820				old_limit || !new_limit,821				<Error<T>>::OwnerPermissionsCantBeReverted,822			),823			sponsored_data_rate_limit => {},824			transfers_enabled => {},825		);826		Ok(new_limit)827	}828}829830#[macro_export]831macro_rules! unsupported {832	() => {833		Err(<Error<T>>::UnsupportedOperation.into())834	};835}836837/// Worst cases838pub trait CommonWeightInfo<CrossAccountId> {839	fn create_item() -> Weight;840	fn create_multiple_items(amount: u32) -> Weight;841	fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;842	fn burn_item() -> Weight;843	fn transfer() -> Weight;844	fn approve() -> Weight;845	fn transfer_from() -> Weight;846	fn burn_from() -> Weight;847	fn set_variable_metadata(bytes: u32) -> Weight;848}849850pub trait CommonCollectionOperations<T: Config> {851	fn create_item(852		&self,853		sender: T::CrossAccountId,854		to: T::CrossAccountId,855		data: CreateItemData,856		nesting_budget: &dyn Budget,857	) -> DispatchResultWithPostInfo;858	fn create_multiple_items(859		&self,860		sender: T::CrossAccountId,861		to: T::CrossAccountId,862		data: Vec<CreateItemData>,863		nesting_budget: &dyn Budget,864	) -> DispatchResultWithPostInfo;865	fn create_multiple_items_ex(866		&self,867		sender: T::CrossAccountId,868		data: CreateItemExData<T::CrossAccountId>,869		nesting_budget: &dyn Budget,870	) -> DispatchResultWithPostInfo;871	fn burn_item(872		&self,873		sender: T::CrossAccountId,874		token: TokenId,875		amount: u128,876	) -> DispatchResultWithPostInfo;877878	fn transfer(879		&self,880		sender: T::CrossAccountId,881		to: T::CrossAccountId,882		token: TokenId,883		amount: u128,884		nesting_budget: &dyn Budget,885	) -> DispatchResultWithPostInfo;886	fn approve(887		&self,888		sender: T::CrossAccountId,889		spender: T::CrossAccountId,890		token: TokenId,891		amount: u128,892	) -> DispatchResultWithPostInfo;893	fn transfer_from(894		&self,895		sender: T::CrossAccountId,896		from: T::CrossAccountId,897		to: T::CrossAccountId,898		token: TokenId,899		amount: u128,900		nesting_budget: &dyn Budget,901	) -> DispatchResultWithPostInfo;902	fn burn_from(903		&self,904		sender: T::CrossAccountId,905		from: T::CrossAccountId,906		token: TokenId,907		amount: u128,908		nesting_budget: &dyn Budget,909	) -> DispatchResultWithPostInfo;910911	fn set_variable_metadata(912		&self,913		sender: T::CrossAccountId,914		token: TokenId,915		data: BoundedVec<u8, CustomDataLimit>,916	) -> DispatchResultWithPostInfo;917918	fn check_nesting(919		&self,920		sender: T::CrossAccountId,921		from: (CollectionId, TokenId),922		under: TokenId,923		budget: &dyn Budget,924	) -> DispatchResult;925926	fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;927	fn collection_tokens(&self) -> Vec<TokenId>;928	fn token_exists(&self, token: TokenId) -> bool;929	fn last_token_id(&self) -> TokenId;930931	fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId>;932	fn const_metadata(&self, token: TokenId) -> Vec<u8>;933	fn variable_metadata(&self, token: TokenId) -> Vec<u8>;934935	/// Amount of unique collection tokens936	fn total_supply(&self) -> u32;937	/// Amount of different tokens account has (Applicable to nonfungible/refungible)938	fn account_balance(&self, account: T::CrossAccountId) -> u32;939	/// Amount of specific token account have (Applicable to fungible/refungible)940	fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;941	fn allowance(942		&self,943		sender: T::CrossAccountId,944		spender: T::CrossAccountId,945		token: TokenId,946	) -> u128;947}948949// Flexible enough for implementing CommonCollectionOperations950pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {951	let post_info = PostDispatchInfo {952		actual_weight: Some(weight),953		pays_fee: Pays::Yes,954	};955	match res {956		Ok(()) => Ok(post_info),957		Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),958	}959}
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#![cfg_attr(not(feature = "std"), no_std)]1819use core::ops::{Deref, DerefMut};20use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};21use sp_std::{vec::Vec, collections::btree_map::BTreeMap};22use pallet_evm::account::CrossAccountId;23use frame_support::{24	dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},25	ensure, fail,26	traits::{Imbalance, Get, Currency, WithdrawReasons, ExistenceRequirement},27	BoundedVec,28	weights::Pays,29};30use pallet_evm::GasWeightMapping;31use up_data_structs::{32	COLLECTION_NUMBER_LIMIT, Collection, RpcCollection, CollectionId, CreateItemData,33	MAX_TOKEN_PREFIX_LENGTH, COLLECTION_ADMINS_LIMIT, MetaUpdatePermission, TokenId,34	CollectionStats, MAX_TOKEN_OWNERSHIP, CollectionMode, NFT_SPONSOR_TRANSFER_TIMEOUT,35	FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, MAX_SPONSOR_TIMEOUT,36	CUSTOM_DATA_LIMIT, CollectionLimits, CustomDataLimit, CreateCollectionData, SponsorshipState,37	CreateItemExData, SponsoringRateLimit, budget::Budget, COLLECTION_FIELD_LIMIT, CollectionField,38	PhantomType, Property, Properties, PropertiesPermissionMap, PropertyKey, PropertyPermission,39	PropertiesError,40};41pub use pallet::*;42use sp_core::H160;43use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};44#[cfg(feature = "runtime-benchmarks")]45pub mod benchmarking;46pub mod dispatch;47pub mod erc;48pub mod eth;4950#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]51pub struct CollectionHandle<T: Config> {52	pub id: CollectionId,53	collection: Collection<T::AccountId>,54	pub recorder: SubstrateRecorder<T>,55}56impl<T: Config> WithRecorder<T> for CollectionHandle<T> {57	fn recorder(&self) -> &SubstrateRecorder<T> {58		&self.recorder59	}60	fn into_recorder(self) -> SubstrateRecorder<T> {61		self.recorder62	}63}64impl<T: Config> CollectionHandle<T> {65	pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {66		<CollectionById<T>>::get(id).map(|collection| Self {67			id,68			collection,69			recorder: SubstrateRecorder::new(eth::collection_id_to_address(id), gas_limit),70		})71	}72	pub fn new(id: CollectionId) -> Option<Self> {73		Self::new_with_gas_limit(id, u64::MAX)74	}75	pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {76		Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)77	}78	pub fn log_mirrored(&self, log: impl evm_coder::ToLog) {79		self.recorder.log_mirrored(log)80	}81	pub fn log_direct(&self, log: impl evm_coder::ToLog) {82		self.recorder.log_direct(log)83	}84	pub fn consume_store_reads(&self, reads: u64) -> evm_coder::execution::Result<()> {85		self.recorder86			.consume_gas(T::GasWeightMapping::weight_to_gas(87				<T as frame_system::Config>::DbWeight::get()88					.read89					.saturating_mul(reads),90			))91	}92	pub fn consume_store_writes(&self, writes: u64) -> evm_coder::execution::Result<()> {93		self.recorder94			.consume_gas(T::GasWeightMapping::weight_to_gas(95				<T as frame_system::Config>::DbWeight::get()96					.write97					.saturating_mul(writes),98			))99	}100	pub fn submit_logs(self) {101		self.recorder.submit_logs()102	}103	pub fn save(self) -> DispatchResult {104		self.recorder.submit_logs();105		<CollectionById<T>>::insert(self.id, self.collection);106		Ok(())107	}108}109impl<T: Config> Deref for CollectionHandle<T> {110	type Target = Collection<T::AccountId>;111112	fn deref(&self) -> &Self::Target {113		&self.collection114	}115}116117impl<T: Config> DerefMut for CollectionHandle<T> {118	fn deref_mut(&mut self) -> &mut Self::Target {119		&mut self.collection120	}121}122123impl<T: Config> CollectionHandle<T> {124	pub fn check_is_owner(&self, subject: &T::CrossAccountId) -> DispatchResult {125		ensure!(*subject.as_sub() == self.owner, <Error<T>>::NoPermission);126		Ok(())127	}128	pub fn is_owner_or_admin(&self, subject: &T::CrossAccountId) -> bool {129		*subject.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, subject))130	}131	pub fn check_is_owner_or_admin(&self, subject: &T::CrossAccountId) -> DispatchResult {132		ensure!(self.is_owner_or_admin(subject), <Error<T>>::NoPermission);133		Ok(())134	}135	pub fn ignores_allowance(&self, user: &T::CrossAccountId) -> bool {136		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)137	}138	pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {139		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)140	}141	pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {142		ensure!(143			<Allowlist<T>>::get((self.id, user)),144			<Error<T>>::AddressNotInAllowlist145		);146		Ok(())147	}148149	pub fn check_can_update_meta(150		&self,151		subject: &T::CrossAccountId,152		item_owner: &T::CrossAccountId,153	) -> DispatchResult {154		match self.meta_update_permission {155			MetaUpdatePermission::ItemOwner => {156				ensure!(subject == item_owner, <Error<T>>::NoPermission);157				Ok(())158			}159			MetaUpdatePermission::Admin => self.check_is_owner_or_admin(subject),160			MetaUpdatePermission::None => fail!(<Error<T>>::NoPermission),161		}162	}163}164165#[frame_support::pallet]166pub mod pallet {167	use super::*;168	use pallet_evm::account;169	use dispatch::CollectionDispatch;170	use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};171	use frame_system::pallet_prelude::*;172	use frame_support::traits::Currency;173	use up_data_structs::{TokenId, mapping::TokenAddressMapping};174	use scale_info::TypeInfo;175176	#[pallet::config]177	pub trait Config:178		frame_system::Config + pallet_evm_coder_substrate::Config + TypeInfo + account::Config179	{180		type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>;181182		type Currency: Currency<Self::AccountId>;183184		#[pallet::constant]185		type CollectionCreationPrice: Get<186			<<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,187		>;188		type CollectionDispatch: CollectionDispatch<Self>;189190		type TreasuryAccountId: Get<Self::AccountId>;191192		type EvmTokenAddressMapping: TokenAddressMapping<H160>;193		type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;194	}195196	const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);197198	#[pallet::pallet]199	#[pallet::storage_version(STORAGE_VERSION)]200	#[pallet::generate_store(pub(super) trait Store)]201	pub struct Pallet<T>(_);202203	#[pallet::extra_constants]204	impl<T: Config> Pallet<T> {205		pub fn collection_admins_limit() -> u32 {206			COLLECTION_ADMINS_LIMIT207		}208	}209210	#[pallet::event]211	#[pallet::generate_deposit(pub fn deposit_event)]212	pub enum Event<T: Config> {213		/// New collection was created214		///215		/// # Arguments216		///217		/// * collection_id: Globally unique identifier of newly created collection.218		///219		/// * mode: [CollectionMode] converted into u8.220		///221		/// * account_id: Collection owner.222		CollectionCreated(CollectionId, u8, T::AccountId),223224		/// New collection was destroyed225		///226		/// # Arguments227		///228		/// * collection_id: Globally unique identifier of collection.229		CollectionDestroyed(CollectionId),230231		/// New item was created.232		///233		/// # Arguments234		///235		/// * collection_id: Id of the collection where item was created.236		///237		/// * item_id: Id of an item. Unique within the collection.238		///239		/// * recipient: Owner of newly created item240		///241		/// * amount: Always 1 for NFT242		ItemCreated(CollectionId, TokenId, T::CrossAccountId, u128),243244		/// Collection item was burned.245		///246		/// # Arguments247		///248		/// * collection_id.249		///250		/// * item_id: Identifier of burned NFT.251		///252		/// * owner: which user has destroyed its tokens253		///254		/// * amount: Always 1 for NFT255		ItemDestroyed(CollectionId, TokenId, T::CrossAccountId, u128),256257		/// Item was transferred258		///259		/// * collection_id: Id of collection to which item is belong260		///261		/// * item_id: Id of an item262		///263		/// * sender: Original owner of item264		///265		/// * recipient: New owner of item266		///267		/// * amount: Always 1 for NFT268		Transfer(269			CollectionId,270			TokenId,271			T::CrossAccountId,272			T::CrossAccountId,273			u128,274		),275276		/// * collection_id277		///278		/// * item_id279		///280		/// * sender281		///282		/// * spender283		///284		/// * amount285		Approved(286			CollectionId,287			TokenId,288			T::CrossAccountId,289			T::CrossAccountId,290			u128,291		),292293		CollectionPropertySet(CollectionId, Property),294295		TokenPropertySet(CollectionId, TokenId, Property),296	}297298	#[pallet::error]299	pub enum Error<T> {300		/// This collection does not exist.301		CollectionNotFound,302		/// Sender parameter and item owner must be equal.303		MustBeTokenOwner,304		/// No permission to perform action305		NoPermission,306		/// Collection is not in mint mode.307		PublicMintingNotAllowed,308		/// Address is not in allow list.309		AddressNotInAllowlist,310311		/// Collection name can not be longer than 63 char.312		CollectionNameLimitExceeded,313		/// Collection description can not be longer than 255 char.314		CollectionDescriptionLimitExceeded,315		/// Token prefix can not be longer than 15 char.316		CollectionTokenPrefixLimitExceeded,317		/// Total collections bound exceeded.318		TotalCollectionsLimitExceeded,319		/// variable_data exceeded data limit.320		TokenVariableDataLimitExceeded,321		/// Exceeded max admin count322		CollectionAdminCountExceeded,323		/// Collection limit bounds per collection exceeded324		CollectionLimitBoundsExceeded,325		/// Tried to enable permissions which are only permitted to be disabled326		OwnerPermissionsCantBeReverted,327		/// Collection settings not allowing items transferring328		TransferNotAllowed,329		/// Account token limit exceeded per collection330		AccountTokenLimitExceeded,331		/// Collection token limit exceeded332		CollectionTokenLimitExceeded,333		/// Metadata flag frozen334		MetadataFlagFrozen,335336		/// Item not exists.337		TokenNotFound,338		/// Item balance not enough.339		TokenValueTooLow,340		/// Requested value more than approved.341		ApprovedValueTooLow,342		/// Tried to approve more than owned343		CantApproveMoreThanOwned,344345		/// Can't transfer tokens to ethereum zero address346		AddressIsZero,347		/// Target collection doesn't supports this operation348		UnsupportedOperation,349350		/// Not sufficient founds to perform action351		NotSufficientFounds,352353		/// Collection has nesting disabled354		NestingIsDisabled,355		/// Only owner may nest tokens under this collection356		OnlyOwnerAllowedToNest,357		/// Only tokens from specific collections may nest tokens under this358		SourceCollectionIsNotAllowedToNest,359360		/// Tried to store more data than allowed in collection field361		CollectionFieldSizeExceeded,362	}363364	#[pallet::storage]365	pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;366	#[pallet::storage]367	pub type DestroyedCollectionCount<T> =368		StorageValue<Value = CollectionId, QueryKind = ValueQuery>;369370	/// Collection info371	#[pallet::storage]372	pub type CollectionById<T> = StorageMap<373		Hasher = Blake2_128Concat,374		Key = CollectionId,375		Value = Collection<<T as frame_system::Config>::AccountId>,376		QueryKind = OptionQuery,377	>;378379	/// Collection properties380	#[pallet::storage]381	pub type CollectionProperties<T> = StorageMap<382		Hasher = Blake2_128Concat,383		Key = CollectionId,384		Value = Properties,385		QueryKind = ValueQuery,386		OnEmpty = up_data_structs::CollectionProperties,387	>;388389	#[pallet::storage]390	#[pallet::getter(fn property_permission)]391	pub type CollectionPropertyPermissions<T> = StorageMap<392		Hasher = Blake2_128Concat,393		Key = CollectionId,394		Value = PropertiesPermissionMap,395		QueryKind = ValueQuery,396	>;397398	/// Large variable-size collection fields are extracted here399	#[pallet::storage]400	pub type CollectionData<T> = StorageNMap<401		Key = (402			Key<Twox64Concat, CollectionId>,403			Key<Twox64Concat, CollectionField>,404		),405		Value = BoundedVec<u8, ConstU32<COLLECTION_FIELD_LIMIT>>,406		QueryKind = ValueQuery,407	>;408409	#[pallet::storage]410	pub type AdminAmount<T> = StorageMap<411		Hasher = Blake2_128Concat,412		Key = CollectionId,413		Value = u32,414		QueryKind = ValueQuery,415	>;416417	/// List of collection admins418	#[pallet::storage]419	pub type IsAdmin<T: Config> = StorageNMap<420		Key = (421			Key<Blake2_128Concat, CollectionId>,422			Key<Blake2_128Concat, T::CrossAccountId>,423		),424		Value = bool,425		QueryKind = ValueQuery,426	>;427428	/// Allowlisted collection users429	#[pallet::storage]430	pub type Allowlist<T: Config> = StorageNMap<431		Key = (432			Key<Blake2_128Concat, CollectionId>,433			Key<Blake2_128Concat, T::CrossAccountId>,434		),435		Value = bool,436		QueryKind = ValueQuery,437	>;438439	/// Not used by code, exists only to provide some types to metadata440	#[pallet::storage]441	pub type DummyStorageValue<T: Config> = StorageValue<442		Value = (443			CollectionStats,444			CollectionId,445			TokenId,446			PhantomType<RpcCollection<T::AccountId>>,447		),448		QueryKind = OptionQuery,449	>;450451	#[pallet::hooks]452	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {453		fn on_runtime_upgrade() -> Weight {454			if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {455				use up_data_structs::{CollectionVersion1, CollectionVersion2};456				<CollectionById<T>>::translate::<CollectionVersion1<T::AccountId>, _>(|id, v| {457					Self::set_field_raw(458						id,459						CollectionField::OffchainSchema,460						v.offchain_schema.clone().into_inner(),461					)462					.expect("data has lower bounds than field");463					Self::set_field_raw(464						id,465						CollectionField::VariableOnChainSchema,466						v.variable_on_chain_schema.clone().into_inner(),467					)468					.expect("data has lower bounds than field");469					Self::set_field_raw(470						id,471						CollectionField::ConstOnChainSchema,472						v.const_on_chain_schema.clone().into_inner(),473					)474					.expect("data has lower bounds than field");475476					Some(CollectionVersion2::from(v))477				});478			}479480			0481		}482	}483}484485impl<T: Config> Pallet<T> {486	/// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens487	pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {488		ensure!(489			&T::CrossAccountId::from_eth(H160([0; 20])) != receiver,490			<Error<T>>::AddressIsZero491		);492		Ok(())493	}494	pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {495		<IsAdmin<T>>::iter_prefix((collection,))496			.map(|(a, _)| a)497			.collect()498	}499	pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {500		<Allowlist<T>>::iter_prefix((collection,))501			.map(|(a, _)| a)502			.collect()503	}504	pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {505		<Allowlist<T>>::get((collection, user))506	}507	pub fn collection_stats() -> CollectionStats {508		let created = <CreatedCollectionCount<T>>::get();509		let destroyed = <DestroyedCollectionCount<T>>::get();510		CollectionStats {511			created: created.0,512			destroyed: destroyed.0,513			alive: created.0 - destroyed.0,514		}515	}516517	pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {518		let collection = <CollectionById<T>>::get(collection);519		if collection.is_none() {520			return None;521		}522523		let collection = collection.unwrap();524		let limits = collection.limits;525		let effective_limits = CollectionLimits {526			account_token_ownership_limit: Some(limits.account_token_ownership_limit()),527			sponsored_data_size: Some(limits.sponsored_data_size()),528			sponsored_data_rate_limit: Some(529				limits530					.sponsored_data_rate_limit531					.unwrap_or(SponsoringRateLimit::SponsoringDisabled),532			),533			token_limit: Some(limits.token_limit()),534			sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(535				match collection.mode {536					CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,537					CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,538					CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,539				},540			)),541			sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),542			owner_can_transfer: Some(limits.owner_can_transfer()),543			owner_can_destroy: Some(limits.owner_can_destroy()),544			transfers_enabled: Some(limits.transfers_enabled()),545			nesting_rule: Some(limits.nesting_rule().clone()),546		};547548		Some(effective_limits)549	}550551	pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {552		let Collection {553			name,554			description,555			owner,556			mode,557			access,558			token_prefix,559			mint_mode,560			schema_version,561			sponsorship,562			limits,563			meta_update_permission,564			..565		} = <CollectionById<T>>::get(collection)?;566		Some(RpcCollection {567			name: name.into_inner(),568			description: description.into_inner(),569			owner,570			mode,571			access,572			token_prefix: token_prefix.into_inner(),573			mint_mode,574			schema_version,575			sponsorship,576			limits,577			meta_update_permission,578			offchain_schema: <CollectionData<T>>::get((579				collection,580				CollectionField::OffchainSchema,581			))582			.into_inner(),583			const_on_chain_schema: <CollectionData<T>>::get((584				collection,585				CollectionField::ConstOnChainSchema,586			))587			.into_inner(),588			variable_on_chain_schema: <CollectionData<T>>::get((589				collection,590				CollectionField::VariableOnChainSchema,591			))592			.into_inner(),593		})594	}595}596597impl<T: Config> Pallet<T> {598	pub fn init_collection(599		owner: T::AccountId,600		data: CreateCollectionData<T::AccountId>,601	) -> Result<CollectionId, DispatchError> {602		{603			ensure!(604				data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,605				Error::<T>::CollectionTokenPrefixLimitExceeded606			);607		}608609		let created_count = <CreatedCollectionCount<T>>::get()610			.0611			.checked_add(1)612			.ok_or(ArithmeticError::Overflow)?;613		let destroyed_count = <DestroyedCollectionCount<T>>::get().0;614		let id = CollectionId(created_count);615616		// bound Total number of collections617		ensure!(618			created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,619			<Error<T>>::TotalCollectionsLimitExceeded620		);621622		// =========623624		let collection = Collection {625			owner: owner.clone(),626			name: data.name,627			mode: data.mode.clone(),628			mint_mode: false,629			access: data.access.unwrap_or_default(),630			description: data.description,631			token_prefix: data.token_prefix,632			schema_version: data.schema_version.unwrap_or_default(),633			sponsorship: data634				.pending_sponsor635				.map(SponsorshipState::Unconfirmed)636				.unwrap_or_default(),637			limits: data638				.limits639				.map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))640				.unwrap_or_else(|| Ok(CollectionLimits::default()))?,641			meta_update_permission: data.meta_update_permission.unwrap_or_default(),642			// token_property_permissions: data.token_property_permissions.unwrap_or_default(),643			// properties: Properties::from_collection_props_vec(data.properties)?644		};645646		CollectionProperties::<T>::insert(647			id,648			Properties::from_collection_props_vec(data.properties)?,649		);650651		let token_props_permissions: PropertiesPermissionMap = data652			.token_property_permissions653			.into_iter()654			.map(|property| (property.key, property.permission))655			.collect::<BTreeMap<_, _>>()656			.try_into()657			.map_err(|_| PropertiesError::PropertyLimitReached)?;658659		CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);660661		// Take a (non-refundable) deposit of collection creation662		{663			let mut imbalance =664				<<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();665			imbalance.subsume(666				<<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(667					&T::TreasuryAccountId::get(),668					T::CollectionCreationPrice::get(),669				),670			);671			<T as Config>::Currency::settle(672				&owner,673				imbalance,674				WithdrawReasons::TRANSFER,675				ExistenceRequirement::KeepAlive,676			)677			.map_err(|_| Error::<T>::NotSufficientFounds)?;678		}679680		<CreatedCollectionCount<T>>::put(created_count);681		<Pallet<T>>::deposit_event(Event::CollectionCreated(id, data.mode.id(), owner.clone()));682		<CollectionById<T>>::insert(id, collection);683		Self::set_field_raw(684			id,685			CollectionField::OffchainSchema,686			data.offchain_schema.into_inner(),687		)688		.expect("data has lower bounds than field");689		Self::set_field_raw(690			id,691			CollectionField::VariableOnChainSchema,692			data.variable_on_chain_schema.into_inner(),693		)694		.expect("data has lower bounds than field");695		Self::set_field_raw(696			id,697			CollectionField::ConstOnChainSchema,698			data.const_on_chain_schema.into_inner(),699		)700		.expect("data has lower bounds than field");701		Ok(id)702	}703704	pub fn destroy_collection(705		collection: CollectionHandle<T>,706		sender: &T::CrossAccountId,707	) -> DispatchResult {708		ensure!(709			collection.limits.owner_can_destroy(),710			<Error<T>>::NoPermission,711		);712		collection.check_is_owner(sender)?;713714		let destroyed_collections = <DestroyedCollectionCount<T>>::get()715			.0716			.checked_add(1)717			.ok_or(ArithmeticError::Overflow)?;718719		// =========720721		<DestroyedCollectionCount<T>>::put(destroyed_collections);722		<CollectionById<T>>::remove(collection.id);723		<CollectionData<T>>::remove_prefix((collection.id,), None);724		<AdminAmount<T>>::remove(collection.id);725		<IsAdmin<T>>::remove_prefix((collection.id,), None);726		<Allowlist<T>>::remove_prefix((collection.id,), None);727728		<Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));729		Ok(())730	}731732	pub fn change_collection_property(733		collection: &CollectionHandle<T>,734		sender: &T::CrossAccountId,735		property: Property,736	) -> DispatchResult {737		collection.check_is_owner_or_admin(sender)?;738739		CollectionProperties::<T>::get(collection.id).try_change_property(property)?;740741		Ok(())742	}743744	pub fn change_property_permission(745		collection: &CollectionHandle<T>,746		sender: &T::CrossAccountId,747		property_key: PropertyKey,748		permission: PropertyPermission,749	) -> DispatchResult {750		collection.check_is_owner_or_admin(sender)?;751752		CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {753			permissions.try_insert(property_key, permission)754		})755		.map_err(|_| PropertiesError::PropertyLimitReached)?;756757		Ok(())758	}759760	fn set_field_raw(761		collection_id: CollectionId,762		field: CollectionField,763		value: Vec<u8>,764	) -> DispatchResult {765		if !value.is_empty() {766			<CollectionData<T>>::insert(767				(collection_id, field),768				BoundedVec::try_from(value).map_err(|_| <Error<T>>::CollectionFieldSizeExceeded)?,769			)770		} else {771			<CollectionData<T>>::remove((collection_id, field));772		}773		Ok(())774	}775776	pub fn set_field(777		collection: &CollectionHandle<T>,778		sender: &T::CrossAccountId,779		field: CollectionField,780		value: Vec<u8>,781	) -> DispatchResult {782		collection.check_is_owner_or_admin(sender)?;783784		// =========785786		Self::set_field_raw(collection.id, field, value)787	}788789	pub fn toggle_allowlist(790		collection: &CollectionHandle<T>,791		sender: &T::CrossAccountId,792		user: &T::CrossAccountId,793		allowed: bool,794	) -> DispatchResult {795		collection.check_is_owner_or_admin(sender)?;796797		// =========798799		if allowed {800			<Allowlist<T>>::insert((collection.id, user), true);801		} else {802			<Allowlist<T>>::remove((collection.id, user));803		}804805		Ok(())806	}807808	pub fn toggle_admin(809		collection: &CollectionHandle<T>,810		sender: &T::CrossAccountId,811		user: &T::CrossAccountId,812		admin: bool,813	) -> DispatchResult {814		collection.check_is_owner_or_admin(sender)?;815816		let was_admin = <IsAdmin<T>>::get((collection.id, user));817		if was_admin == admin {818			return Ok(());819		}820		let amount = <AdminAmount<T>>::get(collection.id);821822		if admin {823			let amount = amount824				.checked_add(1)825				.ok_or(<Error<T>>::CollectionAdminCountExceeded)?;826			ensure!(827				amount <= Self::collection_admins_limit(),828				<Error<T>>::CollectionAdminCountExceeded,829			);830831			// =========832833			<AdminAmount<T>>::insert(collection.id, amount);834			<IsAdmin<T>>::insert((collection.id, user), true);835		} else {836			<AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));837			<IsAdmin<T>>::remove((collection.id, user));838		}839840		Ok(())841	}842843	pub fn clamp_limits(844		mode: CollectionMode,845		old_limit: &CollectionLimits,846		mut new_limit: CollectionLimits,847	) -> Result<CollectionLimits, DispatchError> {848		macro_rules! limit_default {849				($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{850					$(851						if let Some($new) = $new.$field {852							let $old = $old.$field($($arg)?);853							let _ = $new;854							let _ = $old;855							$check856						} else {857							$new.$field = $old.$field858						}859					)*860				}};861			}862863		limit_default!(old_limit, new_limit,864			account_token_ownership_limit => ensure!(865				new_limit <= MAX_TOKEN_OWNERSHIP,866				<Error<T>>::CollectionLimitBoundsExceeded,867			),868			sponsor_transfer_timeout(match mode {869				CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,870				CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,871				CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,872			}) => ensure!(873				new_limit <= MAX_SPONSOR_TIMEOUT,874				<Error<T>>::CollectionLimitBoundsExceeded,875			),876			sponsored_data_size => ensure!(877				new_limit <= CUSTOM_DATA_LIMIT,878				<Error<T>>::CollectionLimitBoundsExceeded,879			),880			token_limit => ensure!(881				old_limit >= new_limit && new_limit > 0,882				<Error<T>>::CollectionTokenLimitExceeded883			),884			owner_can_transfer => ensure!(885				old_limit || !new_limit,886				<Error<T>>::OwnerPermissionsCantBeReverted,887			),888			owner_can_destroy => ensure!(889				old_limit || !new_limit,890				<Error<T>>::OwnerPermissionsCantBeReverted,891			),892			sponsored_data_rate_limit => {},893			transfers_enabled => {},894		);895		Ok(new_limit)896	}897}898899#[macro_export]900macro_rules! unsupported {901	() => {902		Err(<Error<T>>::UnsupportedOperation.into())903	};904}905906/// Worst cases907pub trait CommonWeightInfo<CrossAccountId> {908	fn create_item() -> Weight;909	fn create_multiple_items(amount: u32) -> Weight;910	fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;911	fn burn_item() -> Weight;912	fn set_property() -> Weight;913	fn transfer() -> Weight;914	fn approve() -> Weight;915	fn transfer_from() -> Weight;916	fn burn_from() -> Weight;917	fn set_variable_metadata(bytes: u32) -> Weight;918}919920pub trait CommonCollectionOperations<T: Config> {921	fn create_item(922		&self,923		sender: T::CrossAccountId,924		to: T::CrossAccountId,925		data: CreateItemData,926		nesting_budget: &dyn Budget,927	) -> DispatchResultWithPostInfo;928	fn create_multiple_items(929		&self,930		sender: T::CrossAccountId,931		to: T::CrossAccountId,932		data: Vec<CreateItemData>,933		nesting_budget: &dyn Budget,934	) -> DispatchResultWithPostInfo;935	fn create_multiple_items_ex(936		&self,937		sender: T::CrossAccountId,938		data: CreateItemExData<T::CrossAccountId>,939		nesting_budget: &dyn Budget,940	) -> DispatchResultWithPostInfo;941	fn burn_item(942		&self,943		sender: T::CrossAccountId,944		token: TokenId,945		amount: u128,946	) -> DispatchResultWithPostInfo;947948	fn change_collection_property(949		&self,950		sender: T::CrossAccountId,951		property: Property,952	) -> DispatchResultWithPostInfo;953954	fn change_token_property(955		&self,956		sender: T::CrossAccountId,957		token_id: TokenId,958		property: Property,959	) -> DispatchResultWithPostInfo;960961	fn transfer(962		&self,963		sender: T::CrossAccountId,964		to: T::CrossAccountId,965		token: TokenId,966		amount: u128,967		nesting_budget: &dyn Budget,968	) -> DispatchResultWithPostInfo;969	fn approve(970		&self,971		sender: T::CrossAccountId,972		spender: T::CrossAccountId,973		token: TokenId,974		amount: u128,975	) -> DispatchResultWithPostInfo;976	fn transfer_from(977		&self,978		sender: T::CrossAccountId,979		from: T::CrossAccountId,980		to: T::CrossAccountId,981		token: TokenId,982		amount: u128,983		nesting_budget: &dyn Budget,984	) -> DispatchResultWithPostInfo;985	fn burn_from(986		&self,987		sender: T::CrossAccountId,988		from: T::CrossAccountId,989		token: TokenId,990		amount: u128,991		nesting_budget: &dyn Budget,992	) -> DispatchResultWithPostInfo;993994	fn set_variable_metadata(995		&self,996		sender: T::CrossAccountId,997		token: TokenId,998		data: BoundedVec<u8, CustomDataLimit>,999	) -> DispatchResultWithPostInfo;10001001	fn check_nesting(1002		&self,1003		sender: T::CrossAccountId,1004		from: (CollectionId, TokenId),1005		under: TokenId,1006		budget: &dyn Budget,1007	) -> DispatchResult;10081009	fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;1010	fn collection_tokens(&self) -> Vec<TokenId>;1011	fn token_exists(&self, token: TokenId) -> bool;1012	fn last_token_id(&self) -> TokenId;10131014	fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId>;1015	fn const_metadata(&self, token: TokenId) -> Vec<u8>;1016	fn variable_metadata(&self, token: TokenId) -> Vec<u8>;10171018	/// Amount of unique collection tokens1019	fn total_supply(&self) -> u32;1020	/// Amount of different tokens account has (Applicable to nonfungible/refungible)1021	fn account_balance(&self, account: T::CrossAccountId) -> u32;1022	/// Amount of specific token account have (Applicable to fungible/refungible)1023	fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;1024	fn allowance(1025		&self,1026		sender: T::CrossAccountId,1027		spender: T::CrossAccountId,1028		token: TokenId,1029	) -> u128;1030}10311032// Flexible enough for implementing CommonCollectionOperations1033pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {1034	let post_info = PostDispatchInfo {1035		actual_weight: Some(weight),1036		pays_fee: Pays::Yes,1037	};1038	match res {1039		Ok(()) => Ok(post_info),1040		Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),1041	}1042}
modifiedpallets/fungible/src/common.rsdiffbeforeafterboth
--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -21,7 +21,7 @@
 use pallet_common::{CommonCollectionOperations, CommonWeightInfo, with_weight};
 use sp_runtime::ArithmeticError;
 use sp_std::{vec::Vec, vec};
-use up_data_structs::CustomDataLimit;
+use up_data_structs::{CustomDataLimit, Property};
 
 use crate::{
 	Allowance, Balance, Config, Error, FungibleHandle, Pallet, SelfWeightOf, weights::WeightInfo,
@@ -50,6 +50,10 @@
 		<SelfWeightOf<T>>::burn_item()
 	}
 
+	fn set_property() -> Weight {
+		<SelfWeightOf<T>>::set_property()
+	}
+
 	fn transfer() -> Weight {
 		<SelfWeightOf<T>>::transfer()
 	}
@@ -225,6 +229,23 @@
 		)
 	}
 
+	fn change_collection_property(
+		&self,
+		_sender: T::CrossAccountId,
+		_property: Property,
+	) -> DispatchResultWithPostInfo {
+		fail!(<Error<T>>::PropertiesNotAllowed)
+	}
+
+	fn change_token_property(
+		&self,
+		_sender: T::CrossAccountId,
+		_token_id: TokenId,
+		_property: Property,
+	) -> DispatchResultWithPostInfo {
+		fail!(<Error<T>>::PropertiesNotAllowed)
+	}
+
 	fn set_variable_metadata(
 		&self,
 		_sender: T::CrossAccountId,
modifiedpallets/fungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -61,6 +61,8 @@
 		FungibleItemsDontHaveData,
 		/// Fungible token does not support nested
 		FungibleDisallowsNesting,
+		/// Item properties are not allowed
+		PropertiesNotAllowed,
 	}
 
 	#[pallet::config]
modifiedpallets/fungible/src/weights.rsdiffbeforeafterboth
--- a/pallets/fungible/src/weights.rs
+++ b/pallets/fungible/src/weights.rs
@@ -35,6 +35,7 @@
 	fn create_item() -> Weight;
 	fn create_multiple_items_ex(b: u32, ) -> Weight;
 	fn burn_item() -> Weight;
+	fn set_property() -> Weight;
 	fn transfer() -> Weight;
 	fn approve() -> Weight;
 	fn transfer_from() -> Weight;
@@ -69,6 +70,12 @@
 			.saturating_add(T::DbWeight::get().reads(2 as Weight))
 			.saturating_add(T::DbWeight::get().writes(2 as Weight))
 	}
+
+	fn set_property() -> Weight {
+		// Error
+		0
+	}
+
 	// Storage: Fungible Balance (r:2 w:2)
 	fn transfer() -> Weight {
 		(17_713_000 as Weight)
@@ -126,6 +133,12 @@
 			.saturating_add(RocksDbWeight::get().reads(2 as Weight))
 			.saturating_add(RocksDbWeight::get().writes(2 as Weight))
 	}
+
+	fn set_property() -> Weight {
+		// Error
+		0
+	}
+
 	// Storage: Fungible Balance (r:2 w:2)
 	fn transfer() -> Weight {
 		(17_713_000 as Weight)
modifiedpallets/nonfungible/src/common.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -17,7 +17,9 @@
 use core::marker::PhantomData;
 
 use frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight, BoundedVec};
-use up_data_structs::{TokenId, CustomDataLimit, CreateItemExData, CollectionId, budget::Budget};
+use up_data_structs::{
+	TokenId, CustomDataLimit, CreateItemExData, CollectionId, budget::Budget, Property,
+};
 use pallet_common::{CommonCollectionOperations, CommonWeightInfo, with_weight};
 use sp_runtime::DispatchError;
 use sp_std::vec::Vec;
@@ -48,6 +50,10 @@
 		<SelfWeightOf<T>>::burn_item()
 	}
 
+	fn set_property() -> Weight {
+		<SelfWeightOf<T>>::set_property()
+	}
+
 	fn transfer() -> Weight {
 		<SelfWeightOf<T>>::transfer()
 	}
@@ -235,6 +241,32 @@
 		}
 	}
 
+	fn change_collection_property(
+		&self,
+		sender: T::CrossAccountId,
+		property: Property,
+	) -> DispatchResultWithPostInfo {
+		// let token_id = None;
+		with_weight(
+			// <Pallet<T>>::change_property(self, &sender, token_id, property),
+			Ok(()),
+			<CommonWeights<T>>::set_property(),
+		)
+	}
+
+	fn change_token_property(
+		&self,
+		sender: T::CrossAccountId,
+		token_id: TokenId,
+		property: Property,
+	) -> DispatchResultWithPostInfo {
+		with_weight(
+			// <Pallet<T>>::change_property(self, &sender, Some(token_id), property),
+			Ok(()),
+			<CommonWeights<T>>::set_property(),
+		)
+	}
+
 	fn set_variable_metadata(
 		&self,
 		sender: T::CrossAccountId,
modifiedpallets/nonfungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -20,7 +20,7 @@
 use frame_support::{BoundedVec, ensure, fail};
 use up_data_structs::{
 	AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,
-	mapping::TokenAddressMapping, NestingRule, budget::Budget,
+	mapping::TokenAddressMapping, NestingRule, budget::Budget, Property, PropertyPermission,
 };
 use pallet_evm::account::CrossAccountId;
 use pallet_common::{
@@ -94,6 +94,14 @@
 		QueryKind = OptionQuery,
 	>;
 
+	#[pallet::storage]
+	pub type TokenProperties<T: Config> = StorageNMap<
+		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),
+		Value = up_data_structs::Properties,
+		QueryKind = ValueQuery,
+		OnEmpty = up_data_structs::TokenProperties,
+	>;
+
 	/// Used to enumerate tokens owned by account
 	#[pallet::storage]
 	pub type Owned<T: Config> = StorageNMap<
@@ -246,6 +254,56 @@
 		Ok(())
 	}
 
+	pub fn change_token_property(
+		collection: &NonfungibleHandle<T>,
+		sender: &T::CrossAccountId,
+		token_id: TokenId,
+		property: Property,
+	) -> DispatchResult {
+		let permission = <PalletCommon<T>>::property_permission(collection.id)
+			.get(&property.key)
+			.map(|p| p.clone())
+			.unwrap_or(PropertyPermission::None);
+
+		let check_token_owner = || -> DispatchResult {
+			let token_data = <TokenData<T>>::get((collection.id, token_id))
+				.ok_or(<CommonError<T>>::TokenNotFound)?;
+
+			ensure!(&token_data.owner == sender, <CommonError<T>>::NoPermission);
+
+			Ok(())
+		};
+
+		let is_property_exists = TokenProperties::<T>::get((collection.id, token_id))
+			.get_property(&property.key)
+			.is_some();
+
+		match (permission, is_property_exists) {
+			(PropertyPermission::AdminConst, false) => {
+				collection.check_is_owner_or_admin(sender)?
+			}
+			(PropertyPermission::Admin, _) => collection.check_is_owner_or_admin(sender)?,
+			(PropertyPermission::ItemOwnerConst, false) => check_token_owner()?,
+			(PropertyPermission::ItemOwner, _) => check_token_owner()?,
+			(PropertyPermission::ItemOwnerOrAdmin, _) => {
+				check_token_owner().or(collection.check_is_owner_or_admin(sender))?;
+			}
+			_ => return Err(<CommonError<T>>::NoPermission.into()),
+		}
+
+		<TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {
+			properties.try_change_property(property.clone())
+		})?;
+
+		<PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(
+			collection.id,
+			token_id,
+			property,
+		));
+
+		Ok(())
+	}
+
 	pub fn transfer(
 		collection: &NonfungibleHandle<T>,
 		from: &T::CrossAccountId,
modifiedpallets/nonfungible/src/weights.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/weights.rs
+++ b/pallets/nonfungible/src/weights.rs
@@ -36,6 +36,7 @@
 	fn create_multiple_items(b: u32, ) -> Weight;
 	fn create_multiple_items_ex(b: u32, ) -> Weight;
 	fn burn_item() -> Weight;
+	fn set_property() -> Weight;
 	fn transfer() -> Weight;
 	fn approve() -> Weight;
 	fn transfer_from() -> Weight;
@@ -90,6 +91,12 @@
 			.saturating_add(T::DbWeight::get().reads(4 as Weight))
 			.saturating_add(T::DbWeight::get().writes(4 as Weight))
 	}
+
+	fn set_property() -> Weight {
+		// TODO calculate appropriate weight
+		50_000_000 as Weight
+	}
+
 	// Storage: Nonfungible TokenData (r:1 w:1)
 	// Storage: Nonfungible AccountBalance (r:2 w:2)
 	// Storage: Nonfungible Allowance (r:1 w:0)
@@ -179,6 +186,12 @@
 			.saturating_add(RocksDbWeight::get().reads(4 as Weight))
 			.saturating_add(RocksDbWeight::get().writes(4 as Weight))
 	}
+
+	fn set_property() -> Weight {
+		// TODO calculate appropriate weight
+		50_000_000 as Weight
+	}
+
 	// Storage: Nonfungible TokenData (r:1 w:1)
 	// Storage: Nonfungible AccountBalance (r:2 w:2)
 	// Storage: Nonfungible Allowance (r:1 w:0)
modifiedpallets/refungible/src/common.rsdiffbeforeafterboth
--- a/pallets/refungible/src/common.rs
+++ b/pallets/refungible/src/common.rs
@@ -20,7 +20,7 @@
 use frame_support::{dispatch::DispatchResultWithPostInfo, fail, weights::Weight, BoundedVec};
 use up_data_structs::{
 	CollectionId, TokenId, CustomDataLimit, CreateItemExData, CreateRefungibleExData,
-	budget::Budget,
+	budget::Budget, Property,
 };
 use pallet_common::{CommonCollectionOperations, CommonWeightInfo, with_weight};
 use sp_runtime::DispatchError;
@@ -66,6 +66,10 @@
 		max_weight_of!(burn_item_partial(), burn_item_fully())
 	}
 
+	fn set_property() -> Weight {
+		<SelfWeightOf<T>>::set_property()
+	}
+
 	fn transfer() -> Weight {
 		max_weight_of!(
 			transfer_normal(),
@@ -244,6 +248,23 @@
 		)
 	}
 
+	fn change_collection_property(
+		&self,
+		_sender: T::CrossAccountId,
+		_property: Property,
+	) -> DispatchResultWithPostInfo {
+		fail!(<Error<T>>::PropertiesNotAllowed)
+	}
+
+	fn change_token_property(
+		&self,
+		_sender: T::CrossAccountId,
+		_token_id: TokenId,
+		_property: Property,
+	) -> DispatchResultWithPostInfo {
+		fail!(<Error<T>>::PropertiesNotAllowed)
+	}
+
 	fn set_variable_metadata(
 		&self,
 		sender: T::CrossAccountId,
modifiedpallets/refungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -62,6 +62,8 @@
 		WrongRefungiblePieces,
 		/// Refungible token can't nest other tokens
 		RefungibleDisallowsNesting,
+		/// Item properties are not allowed
+		PropertiesNotAllowed,
 	}
 
 	#[pallet::config]
modifiedpallets/refungible/src/weights.rsdiffbeforeafterboth
--- a/pallets/refungible/src/weights.rs
+++ b/pallets/refungible/src/weights.rs
@@ -38,6 +38,7 @@
 	fn create_multiple_items_ex_multiple_owners(b: u32, ) -> Weight;
 	fn burn_item_partial() -> Weight;
 	fn burn_item_fully() -> Weight;
+	fn set_property() -> Weight;
 	fn transfer_normal() -> Weight;
 	fn transfer_creating() -> Weight;
 	fn transfer_removing() -> Weight;
@@ -129,6 +130,12 @@
 			.saturating_add(T::DbWeight::get().reads(4 as Weight))
 			.saturating_add(T::DbWeight::get().writes(6 as Weight))
 	}
+
+	fn set_property() -> Weight {
+		// Error
+		0
+	}
+
 	// Storage: Refungible Balance (r:2 w:2)
 	fn transfer_normal() -> Weight {
 		(19_766_000 as Weight)
@@ -297,6 +304,12 @@
 			.saturating_add(RocksDbWeight::get().reads(4 as Weight))
 			.saturating_add(RocksDbWeight::get().writes(6 as Weight))
 	}
+
+	fn set_property() -> Weight {
+		// Error
+		0
+	}
+
 	// Storage: Refungible Balance (r:2 w:2)
 	fn transfer_normal() -> Weight {
 		(19_766_000 as Weight)
modifiedpallets/unique/src/lib.rsdiffbeforeafterboth
--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -39,7 +39,7 @@
 	MAX_COLLECTION_NAME_LENGTH, MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH,
 	AccessMode, CreateItemData, CollectionLimits, CollectionId, CollectionMode, TokenId,
 	SchemaVersion, SponsorshipState, MetaUpdatePermission, CreateCollectionData, CustomDataLimit,
-	CreateItemExData, budget, CollectionField,
+	CreateItemExData, budget, CollectionField, Property,
 };
 use pallet_evm::account::CrossAccountId;
 use pallet_common::{
modifiedprimitives/data-structs/src/lib.rsdiffbeforeafterboth
--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -22,13 +22,14 @@
 };
 use frame_support::{
 	storage::{bounded_btree_map::BoundedBTreeMap, bounded_btree_set::BoundedBTreeSet},
+	traits::Get,
 };
 
 #[cfg(feature = "serde")]
 use serde::{Serialize, Deserialize};
 
 use sp_core::U256;
-use sp_runtime::{ArithmeticError, sp_std::prelude::Vec};
+use sp_runtime::{ArithmeticError, sp_std::prelude::Vec, DispatchError};
 use codec::{Decode, Encode, EncodeLike, MaxEncodedLen};
 use frame_support::{BoundedVec, traits::ConstU32};
 use derivative::Derivative;
@@ -85,6 +86,26 @@
 pub const MAX_COLLECTION_DESCRIPTION_LENGTH: u32 = 256;
 pub const MAX_TOKEN_PREFIX_LENGTH: u32 = 16;
 
+pub const MAX_PROPERTY_KEY_LENGTH: u32 = 256;
+pub const MAX_PROPERTY_VALUE_LENGTH: u32 = 32768;
+pub const MAX_PROPERTIES_PER_ITEM: u32 = 64;
+
+// pub const MAX_PROPERTY_KEYS_OVERALL_LENGTH: u32 = MAX_PROPERTY_KEY_LENGTH * MAX_PROPERTIES_PER_ITEM;
+pub const MAX_COLLECTION_PROPERTIES_SIZE: u32 = 40960;
+pub const MAX_TOKEN_PROPERTIES_SIZE: u32 = 32768;
+
+pub const MAX_COLLECTION_PROPERTIES_ENCODE_LEN: u32 =
+	MAX_PROPERTIES_PER_ITEM * MAX_PROPERTY_KEY_LENGTH + MAX_COLLECTION_PROPERTIES_SIZE;
+
+pub struct MaxPropertiesPermissionsEncodeLen;
+
+impl Get<u32> for MaxPropertiesPermissionsEncodeLen {
+	fn get() -> u32 {
+		MAX_PROPERTIES_PER_ITEM * MAX_PROPERTY_KEY_LENGTH
+			+ <PropertyPermission as MaxEncodedLen>::max_encoded_len() as u32
+	}
+}
+
 /// How much items can be created per single
 /// create_many call
 pub const MAX_ITEMS_PER_BATCH: u32 = 200;
@@ -310,31 +331,32 @@
 	OffchainSchema,
 }
 
-#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Debug, Derivative, MaxEncodedLen)]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
-#[derivative(Default(bound = ""))]
+#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Derivative, MaxEncodedLen)]
+#[derivative(Debug, Default(bound = ""))]
 pub struct CreateCollectionData<AccountId> {
 	#[derivative(Default(value = "CollectionMode::NFT"))]
 	pub mode: CollectionMode,
 	pub access: Option<AccessMode>,
-	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]
 	pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,
-	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]
 	pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,
-	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]
 	pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,
-	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]
 	pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,
 	pub schema_version: Option<SchemaVersion>,
 	pub pending_sponsor: Option<AccountId>,
 	pub limits: Option<CollectionLimits>,
-	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]
 	pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,
-	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]
 	pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,
 	pub meta_update_permission: Option<MetaUpdatePermission>,
+	pub token_property_permissions: CollectionPropertiesPermissionsVec,
+	pub properties: CollectionPropertiesVec,
 }
 
+pub type CollectionPropertiesPermissionsVec =
+	BoundedVec<PropertyKeyPermission, MaxPropertiesPermissionsEncodeLen>;
+
+pub type CollectionPropertiesVec =
+	BoundedVec<Property, ConstU32<MAX_COLLECTION_PROPERTIES_ENCODE_LEN>>;
+
 #[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]
 #[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
 pub struct NftItemType<AccountId> {
@@ -607,3 +629,128 @@
 		0
 	}
 }
+
+pub type PropertyKey = BoundedVec<u8, ConstU32<MAX_PROPERTY_KEY_LENGTH>>;
+pub type PropertyValue = BoundedVec<u8, ConstU32<MAX_PROPERTY_VALUE_LENGTH>>;
+
+#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]
+pub enum PropertyPermission {
+	None,
+	AdminConst,
+	Admin,
+	ItemOwnerConst,
+	ItemOwner,
+	ItemOwnerOrAdmin,
+}
+
+#[derive(Encode, Decode, Debug, TypeInfo, Clone, PartialEq, MaxEncodedLen)]
+pub struct Property {
+	pub key: PropertyKey,
+	pub value: PropertyValue,
+}
+
+#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]
+pub struct PropertyKeyPermission {
+	pub key: PropertyKey,
+	pub permission: PropertyPermission,
+}
+
+pub enum PropertiesError {
+	NoSpaceForProperty,
+	PropertyLimitReached,
+}
+
+impl From<PropertiesError> for DispatchError {
+	fn from(error: PropertiesError) -> Self {
+		match error {
+			PropertiesError::NoSpaceForProperty => DispatchError::Other("no space for property"),
+			PropertiesError::PropertyLimitReached => {
+				DispatchError::Other("property key limit reached")
+			}
+		}
+	}
+}
+
+pub type PropertiesMap =
+	BoundedBTreeMap<PropertyKey, PropertyValue, ConstU32<MAX_PROPERTIES_PER_ITEM>>;
+pub type PropertiesPermissionMap =
+	BoundedBTreeMap<PropertyKey, PropertyPermission, ConstU32<MAX_PROPERTIES_PER_ITEM>>;
+
+#[derive(Encode, Decode, TypeInfo, Clone, PartialEq, MaxEncodedLen)]
+pub struct Properties {
+	map: PropertiesMap,
+	consumed_space: u32,
+	space_limit: u32,
+}
+
+impl Properties {
+	pub fn new(space_limit: u32) -> Self {
+		Self {
+			map: BoundedBTreeMap::new(),
+			consumed_space: 0,
+			space_limit,
+		}
+	}
+
+	pub fn from_collection_props_vec(
+		data: CollectionPropertiesVec,
+	) -> Result<Self, PropertiesError> {
+		let mut props = Self::new(MAX_COLLECTION_PROPERTIES_SIZE);
+
+		for property in data.into_iter() {
+			props.try_change_property(property)?;
+		}
+
+		Ok(props)
+	}
+
+	pub fn try_change_property(&mut self, property: Property) -> Result<(), PropertiesError> {
+		let value_len = property.value.len();
+
+		if self.consumed_space as usize + value_len > self.space_limit as usize {
+			return Err(PropertiesError::NoSpaceForProperty);
+		}
+
+		self.map
+			.try_insert(property.key, property.value)
+			.map_err(|_| PropertiesError::PropertyLimitReached)?;
+
+		self.consumed_space += value_len as u32;
+
+		Ok(())
+	}
+
+	pub fn get_property(&self, key: &PropertyKey) -> Option<&PropertyValue> {
+		self.map.get(key)
+	}
+}
+
+pub struct CollectionProperties;
+
+impl Get<Properties> for CollectionProperties {
+	fn get() -> Properties {
+		Properties::new(MAX_COLLECTION_PROPERTIES_SIZE)
+	}
+}
+
+pub struct TokenProperties;
+
+impl Get<Properties> for TokenProperties {
+	fn get() -> Properties {
+		Properties::new(MAX_TOKEN_PROPERTIES_SIZE)
+	}
+}
+
+// #[cfg(not(feature = "std"))]
+// fn properties_map_debug(_properties: &PropertiesMap, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {
+// 	write!(f, "<properties>")
+// }
+
+// #[cfg(not(feature = "std"))]
+// fn opt_properties_permissions_map_debug(properties: &Option<PropertiesPermissionMap>, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {
+// 	if properties.is_some() {
+// 		write!(f, "Some(<properties permissions>)")
+// 	 } else {
+// 		write!(f, "None")
+// 	}
+// }
modifiedprimitives/rpc/src/lib.rsdiffbeforeafterboth
--- a/primitives/rpc/src/lib.rs
+++ b/primitives/rpc/src/lib.rs
@@ -16,7 +16,9 @@
 
 #![cfg_attr(not(feature = "std"), no_std)]
 
-use up_data_structs::{CollectionId, TokenId, RpcCollection, CollectionStats, CollectionLimits};
+use up_data_structs::{
+	CollectionId, TokenId, RpcCollection, CollectionStats, CollectionLimits, Property,
+};
 use sp_std::vec::Vec;
 use codec::Decode;
 use sp_runtime::DispatchError;
modifiedruntime/common/src/weights.rsdiffbeforeafterboth
--- a/runtime/common/src/weights.rs
+++ b/runtime/common/src/weights.rs
@@ -54,6 +54,10 @@
 		dispatch_weight::<T>() + max_weight_of!(burn_item())
 	}
 
+	fn set_property() -> Weight {
+		dispatch_weight::<T>() + max_weight_of!(set_property())
+	}
+
 	fn transfer() -> Weight {
 		dispatch_weight::<T>() + max_weight_of!(transfer())
 	}