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
--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -18,7 +18,7 @@
 
 use core::ops::{Deref, DerefMut};
 use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};
-use sp_std::vec::Vec;
+use sp_std::{vec::Vec, collections::btree_map::BTreeMap};
 use pallet_evm::account::CrossAccountId;
 use frame_support::{
 	dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},
@@ -35,7 +35,8 @@
 	FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, MAX_SPONSOR_TIMEOUT,
 	CUSTOM_DATA_LIMIT, CollectionLimits, CustomDataLimit, CreateCollectionData, SponsorshipState,
 	CreateItemExData, SponsoringRateLimit, budget::Budget, COLLECTION_FIELD_LIMIT, CollectionField,
-	PhantomType,
+	PhantomType, Property, Properties, PropertiesPermissionMap, PropertyKey, PropertyPermission,
+	PropertiesError,
 };
 pub use pallet::*;
 use sp_core::H160;
@@ -288,6 +289,10 @@
 			T::CrossAccountId,
 			u128,
 		),
+
+		CollectionPropertySet(CollectionId, Property),
+
+		TokenPropertySet(CollectionId, TokenId, Property),
 	}
 
 	#[pallet::error]
@@ -319,7 +324,6 @@
 		CollectionLimitBoundsExceeded,
 		/// Tried to enable permissions which are only permitted to be disabled
 		OwnerPermissionsCantBeReverted,
-
 		/// Collection settings not allowing items transferring
 		TransferNotAllowed,
 		/// Account token limit exceeded per collection
@@ -372,6 +376,25 @@
 		QueryKind = OptionQuery,
 	>;
 
+	/// Collection properties
+	#[pallet::storage]
+	pub type CollectionProperties<T> = StorageMap<
+		Hasher = Blake2_128Concat,
+		Key = CollectionId,
+		Value = Properties,
+		QueryKind = ValueQuery,
+		OnEmpty = up_data_structs::CollectionProperties,
+	>;
+
+	#[pallet::storage]
+	#[pallet::getter(fn property_permission)]
+	pub type CollectionPropertyPermissions<T> = StorageMap<
+		Hasher = Blake2_128Concat,
+		Key = CollectionId,
+		Value = PropertiesPermissionMap,
+		QueryKind = ValueQuery,
+	>;
+
 	/// Large variable-size collection fields are extracted here
 	#[pallet::storage]
 	pub type CollectionData<T> = StorageNMap<
@@ -538,6 +561,7 @@
 			sponsorship,
 			limits,
 			meta_update_permission,
+			..
 		} = <CollectionById<T>>::get(collection)?;
 		Some(RpcCollection {
 			name: name.into_inner(),
@@ -615,8 +639,25 @@
 				.map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))
 				.unwrap_or_else(|| Ok(CollectionLimits::default()))?,
 			meta_update_permission: data.meta_update_permission.unwrap_or_default(),
+			// token_property_permissions: data.token_property_permissions.unwrap_or_default(),
+			// properties: Properties::from_collection_props_vec(data.properties)?
 		};
 
+		CollectionProperties::<T>::insert(
+			id,
+			Properties::from_collection_props_vec(data.properties)?,
+		);
+
+		let token_props_permissions: PropertiesPermissionMap = data
+			.token_property_permissions
+			.into_iter()
+			.map(|property| (property.key, property.permission))
+			.collect::<BTreeMap<_, _>>()
+			.try_into()
+			.map_err(|_| PropertiesError::PropertyLimitReached)?;
+
+		CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);
+
 		// Take a (non-refundable) deposit of collection creation
 		{
 			let mut imbalance =
@@ -688,6 +729,34 @@
 		Ok(())
 	}
 
+	pub fn change_collection_property(
+		collection: &CollectionHandle<T>,
+		sender: &T::CrossAccountId,
+		property: Property,
+	) -> DispatchResult {
+		collection.check_is_owner_or_admin(sender)?;
+
+		CollectionProperties::<T>::get(collection.id).try_change_property(property)?;
+
+		Ok(())
+	}
+
+	pub fn change_property_permission(
+		collection: &CollectionHandle<T>,
+		sender: &T::CrossAccountId,
+		property_key: PropertyKey,
+		permission: PropertyPermission,
+	) -> DispatchResult {
+		collection.check_is_owner_or_admin(sender)?;
+
+		CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {
+			permissions.try_insert(property_key, permission)
+		})
+		.map_err(|_| PropertiesError::PropertyLimitReached)?;
+
+		Ok(())
+	}
+
 	fn set_field_raw(
 		collection_id: CollectionId,
 		field: CollectionField,
@@ -840,6 +909,7 @@
 	fn create_multiple_items(amount: u32) -> Weight;
 	fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;
 	fn burn_item() -> Weight;
+	fn set_property() -> Weight;
 	fn transfer() -> Weight;
 	fn approve() -> Weight;
 	fn transfer_from() -> Weight;
@@ -875,6 +945,19 @@
 		amount: u128,
 	) -> DispatchResultWithPostInfo;
 
+	fn change_collection_property(
+		&self,
+		sender: T::CrossAccountId,
+		property: Property,
+	) -> DispatchResultWithPostInfo;
+
+	fn change_token_property(
+		&self,
+		sender: T::CrossAccountId,
+		token_id: TokenId,
+		property: Property,
+	) -> DispatchResultWithPostInfo;
+
 	fn transfer(
 		&self,
 		sender: T::CrossAccountId,
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
before · pallets/nonfungible/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 erc::ERC721Events;20use frame_support::{BoundedVec, ensure, fail};21use up_data_structs::{22	AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,23	mapping::TokenAddressMapping, NestingRule, budget::Budget,24};25use pallet_evm::account::CrossAccountId;26use pallet_common::{27	Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, CollectionHandle,28	dispatch::CollectionDispatch,29};30use pallet_structure::Pallet as PalletStructure;31use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};32use sp_core::H160;33use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};34use sp_std::{vec::Vec, vec};35use core::ops::Deref;36use sp_std::collections::btree_map::BTreeMap;37use codec::{Encode, Decode, MaxEncodedLen};38use scale_info::TypeInfo;3940pub use pallet::*;41#[cfg(feature = "runtime-benchmarks")]42pub mod benchmarking;43pub mod common;44pub mod erc;45pub mod weights;4647pub type CreateItemData<T> = CreateNftExData<<T as pallet_evm::account::Config>::CrossAccountId>;48pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;4950#[derive(Encode, Decode, TypeInfo, MaxEncodedLen)]51pub struct ItemData<CrossAccountId> {52	pub const_data: BoundedVec<u8, CustomDataLimit>,53	pub variable_data: BoundedVec<u8, CustomDataLimit>,54	pub owner: CrossAccountId,55}5657#[frame_support::pallet]58pub mod pallet {59	use super::*;60	use frame_support::{Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};61	use up_data_structs::{CollectionId, TokenId};62	use super::weights::WeightInfo;6364	#[pallet::error]65	pub enum Error<T> {66		/// Not Nonfungible item data used to mint in Nonfungible collection.67		NotNonfungibleDataUsedToMintFungibleCollectionToken,68		/// Used amount > 1 with NFT69		NonfungibleItemsHaveNoAmount,70	}7172	#[pallet::config]73	pub trait Config:74		frame_system::Config + pallet_common::Config + pallet_structure::Config75	{76		type WeightInfo: WeightInfo;77	}7879	#[pallet::pallet]80	#[pallet::generate_store(pub(super) trait Store)]81	pub struct Pallet<T>(_);8283	#[pallet::storage]84	pub type TokensMinted<T: Config> =85		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;86	#[pallet::storage]87	pub type TokensBurnt<T: Config> =88		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;8990	#[pallet::storage]91	pub type TokenData<T: Config> = StorageNMap<92		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),93		Value = ItemData<T::CrossAccountId>,94		QueryKind = OptionQuery,95	>;9697	/// Used to enumerate tokens owned by account98	#[pallet::storage]99	pub type Owned<T: Config> = StorageNMap<100		Key = (101			Key<Twox64Concat, CollectionId>,102			Key<Blake2_128Concat, T::CrossAccountId>,103			Key<Twox64Concat, TokenId>,104		),105		Value = bool,106		QueryKind = ValueQuery,107	>;108109	#[pallet::storage]110	pub type AccountBalance<T: Config> = StorageNMap<111		Key = (112			Key<Twox64Concat, CollectionId>,113			Key<Blake2_128Concat, T::CrossAccountId>,114		),115		Value = u32,116		QueryKind = ValueQuery,117	>;118119	#[pallet::storage]120	pub type Allowance<T: Config> = StorageNMap<121		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),122		Value = T::CrossAccountId,123		QueryKind = OptionQuery,124	>;125}126127pub struct NonfungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);128impl<T: Config> NonfungibleHandle<T> {129	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {130		Self(inner)131	}132	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {133		self.0134	}135}136impl<T: Config> WithRecorder<T> for NonfungibleHandle<T> {137	fn recorder(&self) -> &SubstrateRecorder<T> {138		self.0.recorder()139	}140	fn into_recorder(self) -> SubstrateRecorder<T> {141		self.0.into_recorder()142	}143}144impl<T: Config> Deref for NonfungibleHandle<T> {145	type Target = pallet_common::CollectionHandle<T>;146147	fn deref(&self) -> &Self::Target {148		&self.0149	}150}151152impl<T: Config> Pallet<T> {153	pub fn total_supply(collection: &NonfungibleHandle<T>) -> u32 {154		<TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)155	}156	pub fn token_exists(collection: &NonfungibleHandle<T>, token: TokenId) -> bool {157		<TokenData<T>>::contains_key((collection.id, token))158	}159}160161// unchecked calls skips any permission checks162impl<T: Config> Pallet<T> {163	pub fn init_collection(164		owner: T::AccountId,165		data: CreateCollectionData<T::AccountId>,166	) -> Result<CollectionId, DispatchError> {167		<PalletCommon<T>>::init_collection(owner, data)168	}169	pub fn destroy_collection(170		collection: NonfungibleHandle<T>,171		sender: &T::CrossAccountId,172	) -> DispatchResult {173		let id = collection.id;174175		// =========176177		PalletCommon::destroy_collection(collection.0, sender)?;178179		<TokenData<T>>::remove_prefix((id,), None);180		<Owned<T>>::remove_prefix((id,), None);181		<TokensMinted<T>>::remove(id);182		<TokensBurnt<T>>::remove(id);183		<Allowance<T>>::remove_prefix((id,), None);184		<AccountBalance<T>>::remove_prefix((id,), None);185		Ok(())186	}187188	pub fn burn(189		collection: &NonfungibleHandle<T>,190		sender: &T::CrossAccountId,191		token: TokenId,192	) -> DispatchResult {193		let token_data =194			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;195		ensure!(196			&token_data.owner == sender197				|| (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(sender)),198			<CommonError<T>>::NoPermission199		);200201		if collection.access == AccessMode::AllowList {202			collection.check_allowlist(sender)?;203		}204205		let burnt = <TokensBurnt<T>>::get(collection.id)206			.checked_add(1)207			.ok_or(ArithmeticError::Overflow)?;208209		let balance = <AccountBalance<T>>::get((collection.id, token_data.owner.clone()))210			.checked_sub(1)211			.ok_or(ArithmeticError::Overflow)?;212213		if balance == 0 {214			<AccountBalance<T>>::remove((collection.id, token_data.owner.clone()));215		} else {216			<AccountBalance<T>>::insert((collection.id, token_data.owner.clone()), balance);217		}218		// =========219220		<Owned<T>>::remove((collection.id, &token_data.owner, token));221		<TokensBurnt<T>>::insert(collection.id, burnt);222		<TokenData<T>>::remove((collection.id, token));223		let old_spender = <Allowance<T>>::take((collection.id, token));224225		if let Some(old_spender) = old_spender {226			<PalletCommon<T>>::deposit_event(CommonEvent::Approved(227				collection.id,228				token,229				sender.clone(),230				old_spender,231				0,232			));233		}234235		collection.log_mirrored(ERC721Events::Transfer {236			from: *token_data.owner.as_eth(),237			to: H160::default(),238			token_id: token.into(),239		});240		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(241			collection.id,242			token,243			token_data.owner,244			1,245		));246		Ok(())247	}248249	pub fn transfer(250		collection: &NonfungibleHandle<T>,251		from: &T::CrossAccountId,252		to: &T::CrossAccountId,253		token: TokenId,254		nesting_budget: &dyn Budget,255	) -> DispatchResult {256		ensure!(257			collection.limits.transfers_enabled(),258			<CommonError<T>>::TransferNotAllowed259		);260261		let token_data =262			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;263		// TODO: require sender to be token, owner, require admins to go through transfer_from264		ensure!(265			&token_data.owner == from266				|| (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(from)),267			<CommonError<T>>::NoPermission268		);269270		if collection.access == AccessMode::AllowList {271			collection.check_allowlist(from)?;272			collection.check_allowlist(to)?;273		}274		<PalletCommon<T>>::ensure_correct_receiver(to)?;275276		let balance_from = <AccountBalance<T>>::get((collection.id, from))277			.checked_sub(1)278			.ok_or(<CommonError<T>>::TokenValueTooLow)?;279		let balance_to = if from != to {280			let balance_to = <AccountBalance<T>>::get((collection.id, to))281				.checked_add(1)282				.ok_or(ArithmeticError::Overflow)?;283284			ensure!(285				balance_to < collection.limits.account_token_ownership_limit(),286				<CommonError<T>>::AccountTokenLimitExceeded,287			);288289			Some(balance_to)290		} else {291			None292		};293294		if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {295			let handle = <CollectionHandle<T>>::try_get(target.0)?;296			let dispatch = T::CollectionDispatch::dispatch(handle);297			let dispatch = dispatch.as_dyn();298299			dispatch.check_nesting(300				from.clone(),301				(collection.id, token),302				target.1,303				nesting_budget,304			)?;305		}306307		// =========308309		<TokenData<T>>::insert(310			(collection.id, token),311			ItemData {312				owner: to.clone(),313				..token_data314			},315		);316317		if let Some(balance_to) = balance_to {318			// from != to319			if balance_from == 0 {320				<AccountBalance<T>>::remove((collection.id, from));321			} else {322				<AccountBalance<T>>::insert((collection.id, from), balance_from);323			}324			<AccountBalance<T>>::insert((collection.id, to), balance_to);325			<Owned<T>>::remove((collection.id, from, token));326			<Owned<T>>::insert((collection.id, to, token), true);327		}328		Self::set_allowance_unchecked(collection, from, token, None, true);329330		collection.log_mirrored(ERC721Events::Transfer {331			from: *from.as_eth(),332			to: *to.as_eth(),333			token_id: token.into(),334		});335		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(336			collection.id,337			token,338			from.clone(),339			to.clone(),340			1,341		));342		Ok(())343	}344345	pub fn create_multiple_items(346		collection: &NonfungibleHandle<T>,347		sender: &T::CrossAccountId,348		data: Vec<CreateItemData<T>>,349		nesting_budget: &dyn Budget,350	) -> DispatchResult {351		if !collection.is_owner_or_admin(sender) {352			ensure!(353				collection.mint_mode,354				<CommonError<T>>::PublicMintingNotAllowed355			);356			collection.check_allowlist(sender)?;357358			for item in data.iter() {359				collection.check_allowlist(&item.owner)?;360			}361		}362363		for data in data.iter() {364			<PalletCommon<T>>::ensure_correct_receiver(&data.owner)?;365		}366367		let first_token = <TokensMinted<T>>::get(collection.id);368		let tokens_minted = first_token369			.checked_add(data.len() as u32)370			.ok_or(ArithmeticError::Overflow)?;371		ensure!(372			tokens_minted <= collection.limits.token_limit(),373			<CommonError<T>>::CollectionTokenLimitExceeded374		);375376		let mut balances = BTreeMap::new();377		for data in &data {378			let balance = balances379				.entry(&data.owner)380				.or_insert_with(|| <AccountBalance<T>>::get((collection.id, &data.owner)));381			*balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;382383			ensure!(384				*balance <= collection.limits.account_token_ownership_limit(),385				<CommonError<T>>::AccountTokenLimitExceeded,386			);387		}388389		for (i, data) in data.iter().enumerate() {390			let token = TokenId(first_token + i as u32 + 1);391			if let Some(target) = T::CrossTokenAddressMapping::address_to_token(&data.owner) {392				let handle = <CollectionHandle<T>>::try_get(target.0)?;393				let dispatch = T::CollectionDispatch::dispatch(handle);394				let dispatch = dispatch.as_dyn();395				dispatch.check_nesting(396					sender.clone(),397					(collection.id, token),398					target.1,399					nesting_budget,400				)?;401			}402		}403404		// =========405406		<TokensMinted<T>>::insert(collection.id, tokens_minted);407		for (account, balance) in balances {408			<AccountBalance<T>>::insert((collection.id, account), balance);409		}410		for (i, data) in data.into_iter().enumerate() {411			let token = first_token + i as u32 + 1;412413			<TokenData<T>>::insert(414				(collection.id, token),415				ItemData {416					const_data: data.const_data,417					variable_data: data.variable_data,418					owner: data.owner.clone(),419				},420			);421			<Owned<T>>::insert((collection.id, &data.owner, token), true);422423			collection.log_mirrored(ERC721Events::Transfer {424				from: H160::default(),425				to: *data.owner.as_eth(),426				token_id: token.into(),427			});428			<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(429				collection.id,430				TokenId(token),431				data.owner.clone(),432				1,433			));434		}435		Ok(())436	}437438	pub fn set_allowance_unchecked(439		collection: &NonfungibleHandle<T>,440		sender: &T::CrossAccountId,441		token: TokenId,442		spender: Option<&T::CrossAccountId>,443		assume_implicit_eth: bool,444	) {445		if let Some(spender) = spender {446			let old_spender = <Allowance<T>>::get((collection.id, token));447			<Allowance<T>>::insert((collection.id, token), spender);448			// In ERC721 there is only one possible approved user of token, so we set449			// approved user to spender450			collection.log_mirrored(ERC721Events::Approval {451				owner: *sender.as_eth(),452				approved: *spender.as_eth(),453				token_id: token.into(),454			});455			// In Unique chain, any token can have any amount of approved users, so we need to456			// set allowance of old owner to 0, and allowance of new owner to 1457			if old_spender.as_ref() != Some(spender) {458				if let Some(old_owner) = old_spender {459					<PalletCommon<T>>::deposit_event(CommonEvent::Approved(460						collection.id,461						token,462						sender.clone(),463						old_owner,464						0,465					));466				}467				<PalletCommon<T>>::deposit_event(CommonEvent::Approved(468					collection.id,469					token,470					sender.clone(),471					spender.clone(),472					1,473				));474			}475		} else {476			let old_spender = <Allowance<T>>::take((collection.id, token));477			if !assume_implicit_eth {478				// In ERC721 there is only one possible approved user of token, so we set479				// approved user to zero address480				collection.log_mirrored(ERC721Events::Approval {481					owner: *sender.as_eth(),482					approved: H160::default(),483					token_id: token.into(),484				});485			}486			// In Unique chain, any token can have any amount of approved users, so we need to487			// set allowance of old owner to 0488			if let Some(old_spender) = old_spender {489				<PalletCommon<T>>::deposit_event(CommonEvent::Approved(490					collection.id,491					token,492					sender.clone(),493					old_spender,494					0,495				));496			}497		}498	}499500	pub fn set_allowance(501		collection: &NonfungibleHandle<T>,502		sender: &T::CrossAccountId,503		token: TokenId,504		spender: Option<&T::CrossAccountId>,505	) -> DispatchResult {506		if collection.access == AccessMode::AllowList {507			collection.check_allowlist(sender)?;508			if let Some(spender) = spender {509				collection.check_allowlist(spender)?;510			}511		}512513		if let Some(spender) = spender {514			<PalletCommon<T>>::ensure_correct_receiver(spender)?;515		}516		let token_data =517			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;518		if &token_data.owner != sender {519			ensure!(520				collection.ignores_owned_amount(sender),521				<CommonError<T>>::CantApproveMoreThanOwned522			);523		}524525		// =========526527		Self::set_allowance_unchecked(collection, sender, token, spender, false);528		Ok(())529	}530531	fn check_allowed(532		collection: &NonfungibleHandle<T>,533		spender: &T::CrossAccountId,534		from: &T::CrossAccountId,535		token: TokenId,536		nesting_budget: &dyn Budget,537	) -> DispatchResult {538		if spender.conv_eq(from) {539			return Ok(());540		}541		if collection.access == AccessMode::AllowList {542			// `from`, `to` checked in [`transfer`]543			collection.check_allowlist(spender)?;544		}545		if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {546			// TODO: should collection owner be allowed to perform this transfer?547			ensure!(548				<PalletStructure<T>>::check_indirectly_owned(549					spender.clone(),550					source.0,551					source.1,552					None,553					nesting_budget554				)?,555				<CommonError<T>>::ApprovedValueTooLow,556			);557			return Ok(());558		}559		if <Allowance<T>>::get((collection.id, token)).as_ref() == Some(spender) {560			return Ok(());561		}562		ensure!(563			collection.ignores_allowance(spender),564			<CommonError<T>>::ApprovedValueTooLow565		);566		Ok(())567	}568569	pub fn transfer_from(570		collection: &NonfungibleHandle<T>,571		spender: &T::CrossAccountId,572		from: &T::CrossAccountId,573		to: &T::CrossAccountId,574		token: TokenId,575		nesting_budget: &dyn Budget,576	) -> DispatchResult {577		Self::check_allowed(collection, spender, from, token, nesting_budget)?;578579		// =========580581		// Allowance is reset in [`transfer`]582		Self::transfer(collection, from, to, token, nesting_budget)583	}584585	pub fn burn_from(586		collection: &NonfungibleHandle<T>,587		spender: &T::CrossAccountId,588		from: &T::CrossAccountId,589		token: TokenId,590		nesting_budget: &dyn Budget,591	) -> DispatchResult {592		Self::check_allowed(collection, spender, from, token, nesting_budget)?;593594		// =========595596		Self::burn(collection, from, token)597	}598599	pub fn set_variable_metadata(600		collection: &NonfungibleHandle<T>,601		sender: &T::CrossAccountId,602		token: TokenId,603		data: BoundedVec<u8, CustomDataLimit>,604	) -> DispatchResult {605		let token_data =606			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;607		collection.check_can_update_meta(sender, &token_data.owner)?;608609		// =========610611		<TokenData<T>>::insert(612			(collection.id, token),613			ItemData {614				variable_data: data,615				..token_data616			},617		);618		Ok(())619	}620621	pub fn check_nesting(622		handle: &NonfungibleHandle<T>,623		sender: T::CrossAccountId,624		from: (CollectionId, TokenId),625		under: TokenId,626		nesting_budget: &dyn Budget,627	) -> DispatchResult {628		fn ensure_sender_allowed<T: Config>(629			collection: CollectionId,630			token: TokenId,631			for_nest: (CollectionId, TokenId),632			sender: T::CrossAccountId,633			budget: &dyn Budget,634		) -> DispatchResult {635			ensure!(636				<PalletStructure<T>>::check_indirectly_owned(637					sender,638					collection,639					token,640					Some(for_nest),641					budget642				)?,643				<CommonError<T>>::OnlyOwnerAllowedToNest,644			);645			Ok(())646		}647		match handle.limits.nesting_rule() {648			NestingRule::Disabled => fail!(<CommonError<T>>::NestingIsDisabled),649			NestingRule::Owner => {650				ensure_sender_allowed::<T>(handle.id, under, from, sender, nesting_budget)?651			}652			NestingRule::OwnerRestricted(whitelist) => {653				ensure!(654					whitelist.contains(&from.0),655					<CommonError<T>>::SourceCollectionIsNotAllowedToNest656				);657				ensure_sender_allowed::<T>(handle.id, under, from, sender, nesting_budget)?658			}659		}660		Ok(())661	}662663	/// Delegated to `create_multiple_items`664	pub fn create_item(665		collection: &NonfungibleHandle<T>,666		sender: &T::CrossAccountId,667		data: CreateItemData<T>,668		nesting_budget: &dyn Budget,669	) -> DispatchResult {670		Self::create_multiple_items(collection, sender, vec![data], nesting_budget)671	}672}
after · pallets/nonfungible/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 erc::ERC721Events;20use frame_support::{BoundedVec, ensure, fail};21use up_data_structs::{22	AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,23	mapping::TokenAddressMapping, NestingRule, budget::Budget, Property, PropertyPermission,24};25use pallet_evm::account::CrossAccountId;26use pallet_common::{27	Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, CollectionHandle,28	dispatch::CollectionDispatch,29};30use pallet_structure::Pallet as PalletStructure;31use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};32use sp_core::H160;33use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};34use sp_std::{vec::Vec, vec};35use core::ops::Deref;36use sp_std::collections::btree_map::BTreeMap;37use codec::{Encode, Decode, MaxEncodedLen};38use scale_info::TypeInfo;3940pub use pallet::*;41#[cfg(feature = "runtime-benchmarks")]42pub mod benchmarking;43pub mod common;44pub mod erc;45pub mod weights;4647pub type CreateItemData<T> = CreateNftExData<<T as pallet_evm::account::Config>::CrossAccountId>;48pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;4950#[derive(Encode, Decode, TypeInfo, MaxEncodedLen)]51pub struct ItemData<CrossAccountId> {52	pub const_data: BoundedVec<u8, CustomDataLimit>,53	pub variable_data: BoundedVec<u8, CustomDataLimit>,54	pub owner: CrossAccountId,55}5657#[frame_support::pallet]58pub mod pallet {59	use super::*;60	use frame_support::{Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};61	use up_data_structs::{CollectionId, TokenId};62	use super::weights::WeightInfo;6364	#[pallet::error]65	pub enum Error<T> {66		/// Not Nonfungible item data used to mint in Nonfungible collection.67		NotNonfungibleDataUsedToMintFungibleCollectionToken,68		/// Used amount > 1 with NFT69		NonfungibleItemsHaveNoAmount,70	}7172	#[pallet::config]73	pub trait Config:74		frame_system::Config + pallet_common::Config + pallet_structure::Config75	{76		type WeightInfo: WeightInfo;77	}7879	#[pallet::pallet]80	#[pallet::generate_store(pub(super) trait Store)]81	pub struct Pallet<T>(_);8283	#[pallet::storage]84	pub type TokensMinted<T: Config> =85		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;86	#[pallet::storage]87	pub type TokensBurnt<T: Config> =88		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;8990	#[pallet::storage]91	pub type TokenData<T: Config> = StorageNMap<92		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),93		Value = ItemData<T::CrossAccountId>,94		QueryKind = OptionQuery,95	>;9697	#[pallet::storage]98	pub type TokenProperties<T: Config> = StorageNMap<99		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),100		Value = up_data_structs::Properties,101		QueryKind = ValueQuery,102		OnEmpty = up_data_structs::TokenProperties,103	>;104105	/// Used to enumerate tokens owned by account106	#[pallet::storage]107	pub type Owned<T: Config> = StorageNMap<108		Key = (109			Key<Twox64Concat, CollectionId>,110			Key<Blake2_128Concat, T::CrossAccountId>,111			Key<Twox64Concat, TokenId>,112		),113		Value = bool,114		QueryKind = ValueQuery,115	>;116117	#[pallet::storage]118	pub type AccountBalance<T: Config> = StorageNMap<119		Key = (120			Key<Twox64Concat, CollectionId>,121			Key<Blake2_128Concat, T::CrossAccountId>,122		),123		Value = u32,124		QueryKind = ValueQuery,125	>;126127	#[pallet::storage]128	pub type Allowance<T: Config> = StorageNMap<129		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),130		Value = T::CrossAccountId,131		QueryKind = OptionQuery,132	>;133}134135pub struct NonfungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);136impl<T: Config> NonfungibleHandle<T> {137	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {138		Self(inner)139	}140	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {141		self.0142	}143}144impl<T: Config> WithRecorder<T> for NonfungibleHandle<T> {145	fn recorder(&self) -> &SubstrateRecorder<T> {146		self.0.recorder()147	}148	fn into_recorder(self) -> SubstrateRecorder<T> {149		self.0.into_recorder()150	}151}152impl<T: Config> Deref for NonfungibleHandle<T> {153	type Target = pallet_common::CollectionHandle<T>;154155	fn deref(&self) -> &Self::Target {156		&self.0157	}158}159160impl<T: Config> Pallet<T> {161	pub fn total_supply(collection: &NonfungibleHandle<T>) -> u32 {162		<TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)163	}164	pub fn token_exists(collection: &NonfungibleHandle<T>, token: TokenId) -> bool {165		<TokenData<T>>::contains_key((collection.id, token))166	}167}168169// unchecked calls skips any permission checks170impl<T: Config> Pallet<T> {171	pub fn init_collection(172		owner: T::AccountId,173		data: CreateCollectionData<T::AccountId>,174	) -> Result<CollectionId, DispatchError> {175		<PalletCommon<T>>::init_collection(owner, data)176	}177	pub fn destroy_collection(178		collection: NonfungibleHandle<T>,179		sender: &T::CrossAccountId,180	) -> DispatchResult {181		let id = collection.id;182183		// =========184185		PalletCommon::destroy_collection(collection.0, sender)?;186187		<TokenData<T>>::remove_prefix((id,), None);188		<Owned<T>>::remove_prefix((id,), None);189		<TokensMinted<T>>::remove(id);190		<TokensBurnt<T>>::remove(id);191		<Allowance<T>>::remove_prefix((id,), None);192		<AccountBalance<T>>::remove_prefix((id,), None);193		Ok(())194	}195196	pub fn burn(197		collection: &NonfungibleHandle<T>,198		sender: &T::CrossAccountId,199		token: TokenId,200	) -> DispatchResult {201		let token_data =202			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;203		ensure!(204			&token_data.owner == sender205				|| (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(sender)),206			<CommonError<T>>::NoPermission207		);208209		if collection.access == AccessMode::AllowList {210			collection.check_allowlist(sender)?;211		}212213		let burnt = <TokensBurnt<T>>::get(collection.id)214			.checked_add(1)215			.ok_or(ArithmeticError::Overflow)?;216217		let balance = <AccountBalance<T>>::get((collection.id, token_data.owner.clone()))218			.checked_sub(1)219			.ok_or(ArithmeticError::Overflow)?;220221		if balance == 0 {222			<AccountBalance<T>>::remove((collection.id, token_data.owner.clone()));223		} else {224			<AccountBalance<T>>::insert((collection.id, token_data.owner.clone()), balance);225		}226		// =========227228		<Owned<T>>::remove((collection.id, &token_data.owner, token));229		<TokensBurnt<T>>::insert(collection.id, burnt);230		<TokenData<T>>::remove((collection.id, token));231		let old_spender = <Allowance<T>>::take((collection.id, token));232233		if let Some(old_spender) = old_spender {234			<PalletCommon<T>>::deposit_event(CommonEvent::Approved(235				collection.id,236				token,237				sender.clone(),238				old_spender,239				0,240			));241		}242243		collection.log_mirrored(ERC721Events::Transfer {244			from: *token_data.owner.as_eth(),245			to: H160::default(),246			token_id: token.into(),247		});248		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(249			collection.id,250			token,251			token_data.owner,252			1,253		));254		Ok(())255	}256257	pub fn change_token_property(258		collection: &NonfungibleHandle<T>,259		sender: &T::CrossAccountId,260		token_id: TokenId,261		property: Property,262	) -> DispatchResult {263		let permission = <PalletCommon<T>>::property_permission(collection.id)264			.get(&property.key)265			.map(|p| p.clone())266			.unwrap_or(PropertyPermission::None);267268		let check_token_owner = || -> DispatchResult {269			let token_data = <TokenData<T>>::get((collection.id, token_id))270				.ok_or(<CommonError<T>>::TokenNotFound)?;271272			ensure!(&token_data.owner == sender, <CommonError<T>>::NoPermission);273274			Ok(())275		};276277		let is_property_exists = TokenProperties::<T>::get((collection.id, token_id))278			.get_property(&property.key)279			.is_some();280281		match (permission, is_property_exists) {282			(PropertyPermission::AdminConst, false) => {283				collection.check_is_owner_or_admin(sender)?284			}285			(PropertyPermission::Admin, _) => collection.check_is_owner_or_admin(sender)?,286			(PropertyPermission::ItemOwnerConst, false) => check_token_owner()?,287			(PropertyPermission::ItemOwner, _) => check_token_owner()?,288			(PropertyPermission::ItemOwnerOrAdmin, _) => {289				check_token_owner().or(collection.check_is_owner_or_admin(sender))?;290			}291			_ => return Err(<CommonError<T>>::NoPermission.into()),292		}293294		<TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {295			properties.try_change_property(property.clone())296		})?;297298		<PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(299			collection.id,300			token_id,301			property,302		));303304		Ok(())305	}306307	pub fn transfer(308		collection: &NonfungibleHandle<T>,309		from: &T::CrossAccountId,310		to: &T::CrossAccountId,311		token: TokenId,312		nesting_budget: &dyn Budget,313	) -> DispatchResult {314		ensure!(315			collection.limits.transfers_enabled(),316			<CommonError<T>>::TransferNotAllowed317		);318319		let token_data =320			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;321		// TODO: require sender to be token, owner, require admins to go through transfer_from322		ensure!(323			&token_data.owner == from324				|| (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(from)),325			<CommonError<T>>::NoPermission326		);327328		if collection.access == AccessMode::AllowList {329			collection.check_allowlist(from)?;330			collection.check_allowlist(to)?;331		}332		<PalletCommon<T>>::ensure_correct_receiver(to)?;333334		let balance_from = <AccountBalance<T>>::get((collection.id, from))335			.checked_sub(1)336			.ok_or(<CommonError<T>>::TokenValueTooLow)?;337		let balance_to = if from != to {338			let balance_to = <AccountBalance<T>>::get((collection.id, to))339				.checked_add(1)340				.ok_or(ArithmeticError::Overflow)?;341342			ensure!(343				balance_to < collection.limits.account_token_ownership_limit(),344				<CommonError<T>>::AccountTokenLimitExceeded,345			);346347			Some(balance_to)348		} else {349			None350		};351352		if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {353			let handle = <CollectionHandle<T>>::try_get(target.0)?;354			let dispatch = T::CollectionDispatch::dispatch(handle);355			let dispatch = dispatch.as_dyn();356357			dispatch.check_nesting(358				from.clone(),359				(collection.id, token),360				target.1,361				nesting_budget,362			)?;363		}364365		// =========366367		<TokenData<T>>::insert(368			(collection.id, token),369			ItemData {370				owner: to.clone(),371				..token_data372			},373		);374375		if let Some(balance_to) = balance_to {376			// from != to377			if balance_from == 0 {378				<AccountBalance<T>>::remove((collection.id, from));379			} else {380				<AccountBalance<T>>::insert((collection.id, from), balance_from);381			}382			<AccountBalance<T>>::insert((collection.id, to), balance_to);383			<Owned<T>>::remove((collection.id, from, token));384			<Owned<T>>::insert((collection.id, to, token), true);385		}386		Self::set_allowance_unchecked(collection, from, token, None, true);387388		collection.log_mirrored(ERC721Events::Transfer {389			from: *from.as_eth(),390			to: *to.as_eth(),391			token_id: token.into(),392		});393		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(394			collection.id,395			token,396			from.clone(),397			to.clone(),398			1,399		));400		Ok(())401	}402403	pub fn create_multiple_items(404		collection: &NonfungibleHandle<T>,405		sender: &T::CrossAccountId,406		data: Vec<CreateItemData<T>>,407		nesting_budget: &dyn Budget,408	) -> DispatchResult {409		if !collection.is_owner_or_admin(sender) {410			ensure!(411				collection.mint_mode,412				<CommonError<T>>::PublicMintingNotAllowed413			);414			collection.check_allowlist(sender)?;415416			for item in data.iter() {417				collection.check_allowlist(&item.owner)?;418			}419		}420421		for data in data.iter() {422			<PalletCommon<T>>::ensure_correct_receiver(&data.owner)?;423		}424425		let first_token = <TokensMinted<T>>::get(collection.id);426		let tokens_minted = first_token427			.checked_add(data.len() as u32)428			.ok_or(ArithmeticError::Overflow)?;429		ensure!(430			tokens_minted <= collection.limits.token_limit(),431			<CommonError<T>>::CollectionTokenLimitExceeded432		);433434		let mut balances = BTreeMap::new();435		for data in &data {436			let balance = balances437				.entry(&data.owner)438				.or_insert_with(|| <AccountBalance<T>>::get((collection.id, &data.owner)));439			*balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;440441			ensure!(442				*balance <= collection.limits.account_token_ownership_limit(),443				<CommonError<T>>::AccountTokenLimitExceeded,444			);445		}446447		for (i, data) in data.iter().enumerate() {448			let token = TokenId(first_token + i as u32 + 1);449			if let Some(target) = T::CrossTokenAddressMapping::address_to_token(&data.owner) {450				let handle = <CollectionHandle<T>>::try_get(target.0)?;451				let dispatch = T::CollectionDispatch::dispatch(handle);452				let dispatch = dispatch.as_dyn();453				dispatch.check_nesting(454					sender.clone(),455					(collection.id, token),456					target.1,457					nesting_budget,458				)?;459			}460		}461462		// =========463464		<TokensMinted<T>>::insert(collection.id, tokens_minted);465		for (account, balance) in balances {466			<AccountBalance<T>>::insert((collection.id, account), balance);467		}468		for (i, data) in data.into_iter().enumerate() {469			let token = first_token + i as u32 + 1;470471			<TokenData<T>>::insert(472				(collection.id, token),473				ItemData {474					const_data: data.const_data,475					variable_data: data.variable_data,476					owner: data.owner.clone(),477				},478			);479			<Owned<T>>::insert((collection.id, &data.owner, token), true);480481			collection.log_mirrored(ERC721Events::Transfer {482				from: H160::default(),483				to: *data.owner.as_eth(),484				token_id: token.into(),485			});486			<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(487				collection.id,488				TokenId(token),489				data.owner.clone(),490				1,491			));492		}493		Ok(())494	}495496	pub fn set_allowance_unchecked(497		collection: &NonfungibleHandle<T>,498		sender: &T::CrossAccountId,499		token: TokenId,500		spender: Option<&T::CrossAccountId>,501		assume_implicit_eth: bool,502	) {503		if let Some(spender) = spender {504			let old_spender = <Allowance<T>>::get((collection.id, token));505			<Allowance<T>>::insert((collection.id, token), spender);506			// In ERC721 there is only one possible approved user of token, so we set507			// approved user to spender508			collection.log_mirrored(ERC721Events::Approval {509				owner: *sender.as_eth(),510				approved: *spender.as_eth(),511				token_id: token.into(),512			});513			// In Unique chain, any token can have any amount of approved users, so we need to514			// set allowance of old owner to 0, and allowance of new owner to 1515			if old_spender.as_ref() != Some(spender) {516				if let Some(old_owner) = old_spender {517					<PalletCommon<T>>::deposit_event(CommonEvent::Approved(518						collection.id,519						token,520						sender.clone(),521						old_owner,522						0,523					));524				}525				<PalletCommon<T>>::deposit_event(CommonEvent::Approved(526					collection.id,527					token,528					sender.clone(),529					spender.clone(),530					1,531				));532			}533		} else {534			let old_spender = <Allowance<T>>::take((collection.id, token));535			if !assume_implicit_eth {536				// In ERC721 there is only one possible approved user of token, so we set537				// approved user to zero address538				collection.log_mirrored(ERC721Events::Approval {539					owner: *sender.as_eth(),540					approved: H160::default(),541					token_id: token.into(),542				});543			}544			// In Unique chain, any token can have any amount of approved users, so we need to545			// set allowance of old owner to 0546			if let Some(old_spender) = old_spender {547				<PalletCommon<T>>::deposit_event(CommonEvent::Approved(548					collection.id,549					token,550					sender.clone(),551					old_spender,552					0,553				));554			}555		}556	}557558	pub fn set_allowance(559		collection: &NonfungibleHandle<T>,560		sender: &T::CrossAccountId,561		token: TokenId,562		spender: Option<&T::CrossAccountId>,563	) -> DispatchResult {564		if collection.access == AccessMode::AllowList {565			collection.check_allowlist(sender)?;566			if let Some(spender) = spender {567				collection.check_allowlist(spender)?;568			}569		}570571		if let Some(spender) = spender {572			<PalletCommon<T>>::ensure_correct_receiver(spender)?;573		}574		let token_data =575			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;576		if &token_data.owner != sender {577			ensure!(578				collection.ignores_owned_amount(sender),579				<CommonError<T>>::CantApproveMoreThanOwned580			);581		}582583		// =========584585		Self::set_allowance_unchecked(collection, sender, token, spender, false);586		Ok(())587	}588589	fn check_allowed(590		collection: &NonfungibleHandle<T>,591		spender: &T::CrossAccountId,592		from: &T::CrossAccountId,593		token: TokenId,594		nesting_budget: &dyn Budget,595	) -> DispatchResult {596		if spender.conv_eq(from) {597			return Ok(());598		}599		if collection.access == AccessMode::AllowList {600			// `from`, `to` checked in [`transfer`]601			collection.check_allowlist(spender)?;602		}603		if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {604			// TODO: should collection owner be allowed to perform this transfer?605			ensure!(606				<PalletStructure<T>>::check_indirectly_owned(607					spender.clone(),608					source.0,609					source.1,610					None,611					nesting_budget612				)?,613				<CommonError<T>>::ApprovedValueTooLow,614			);615			return Ok(());616		}617		if <Allowance<T>>::get((collection.id, token)).as_ref() == Some(spender) {618			return Ok(());619		}620		ensure!(621			collection.ignores_allowance(spender),622			<CommonError<T>>::ApprovedValueTooLow623		);624		Ok(())625	}626627	pub fn transfer_from(628		collection: &NonfungibleHandle<T>,629		spender: &T::CrossAccountId,630		from: &T::CrossAccountId,631		to: &T::CrossAccountId,632		token: TokenId,633		nesting_budget: &dyn Budget,634	) -> DispatchResult {635		Self::check_allowed(collection, spender, from, token, nesting_budget)?;636637		// =========638639		// Allowance is reset in [`transfer`]640		Self::transfer(collection, from, to, token, nesting_budget)641	}642643	pub fn burn_from(644		collection: &NonfungibleHandle<T>,645		spender: &T::CrossAccountId,646		from: &T::CrossAccountId,647		token: TokenId,648		nesting_budget: &dyn Budget,649	) -> DispatchResult {650		Self::check_allowed(collection, spender, from, token, nesting_budget)?;651652		// =========653654		Self::burn(collection, from, token)655	}656657	pub fn set_variable_metadata(658		collection: &NonfungibleHandle<T>,659		sender: &T::CrossAccountId,660		token: TokenId,661		data: BoundedVec<u8, CustomDataLimit>,662	) -> DispatchResult {663		let token_data =664			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;665		collection.check_can_update_meta(sender, &token_data.owner)?;666667		// =========668669		<TokenData<T>>::insert(670			(collection.id, token),671			ItemData {672				variable_data: data,673				..token_data674			},675		);676		Ok(())677	}678679	pub fn check_nesting(680		handle: &NonfungibleHandle<T>,681		sender: T::CrossAccountId,682		from: (CollectionId, TokenId),683		under: TokenId,684		nesting_budget: &dyn Budget,685	) -> DispatchResult {686		fn ensure_sender_allowed<T: Config>(687			collection: CollectionId,688			token: TokenId,689			for_nest: (CollectionId, TokenId),690			sender: T::CrossAccountId,691			budget: &dyn Budget,692		) -> DispatchResult {693			ensure!(694				<PalletStructure<T>>::check_indirectly_owned(695					sender,696					collection,697					token,698					Some(for_nest),699					budget700				)?,701				<CommonError<T>>::OnlyOwnerAllowedToNest,702			);703			Ok(())704		}705		match handle.limits.nesting_rule() {706			NestingRule::Disabled => fail!(<CommonError<T>>::NestingIsDisabled),707			NestingRule::Owner => {708				ensure_sender_allowed::<T>(handle.id, under, from, sender, nesting_budget)?709			}710			NestingRule::OwnerRestricted(whitelist) => {711				ensure!(712					whitelist.contains(&from.0),713					<CommonError<T>>::SourceCollectionIsNotAllowedToNest714				);715				ensure_sender_allowed::<T>(handle.id, under, from, sender, nesting_budget)?716			}717		}718		Ok(())719	}720721	/// Delegated to `create_multiple_items`722	pub fn create_item(723		collection: &NonfungibleHandle<T>,724		sender: &T::CrossAccountId,725		data: CreateItemData<T>,726		nesting_budget: &dyn Budget,727	) -> DispatchResult {728		Self::create_multiple_items(collection, sender, vec![data], nesting_budget)729	}730}
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())
 	}