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
--- 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
22};22};
23use frame_support::{23use frame_support::{
24 storage::{bounded_btree_map::BoundedBTreeMap, bounded_btree_set::BoundedBTreeSet},24 storage::{bounded_btree_map::BoundedBTreeMap, bounded_btree_set::BoundedBTreeSet},
25 traits::Get,
25};26};
2627
27#[cfg(feature = "serde")]28#[cfg(feature = "serde")]
28use serde::{Serialize, Deserialize};29use serde::{Serialize, Deserialize};
2930
30use sp_core::U256;31use sp_core::U256;
31use sp_runtime::{ArithmeticError, sp_std::prelude::Vec};32use sp_runtime::{ArithmeticError, sp_std::prelude::Vec, DispatchError};
32use codec::{Decode, Encode, EncodeLike, MaxEncodedLen};33use codec::{Decode, Encode, EncodeLike, MaxEncodedLen};
33use frame_support::{BoundedVec, traits::ConstU32};34use frame_support::{BoundedVec, traits::ConstU32};
34use derivative::Derivative;35use derivative::Derivative;
85pub const MAX_COLLECTION_DESCRIPTION_LENGTH: u32 = 256;86pub const MAX_COLLECTION_DESCRIPTION_LENGTH: u32 = 256;
86pub const MAX_TOKEN_PREFIX_LENGTH: u32 = 16;87pub const MAX_TOKEN_PREFIX_LENGTH: u32 = 16;
88
89pub const MAX_PROPERTY_KEY_LENGTH: u32 = 256;
90pub const MAX_PROPERTY_VALUE_LENGTH: u32 = 32768;
91pub const MAX_PROPERTIES_PER_ITEM: u32 = 64;
92
93// pub const MAX_PROPERTY_KEYS_OVERALL_LENGTH: u32 = MAX_PROPERTY_KEY_LENGTH * MAX_PROPERTIES_PER_ITEM;
94pub const MAX_COLLECTION_PROPERTIES_SIZE: u32 = 40960;
95pub const MAX_TOKEN_PROPERTIES_SIZE: u32 = 32768;
96
97pub const MAX_COLLECTION_PROPERTIES_ENCODE_LEN: u32 =
98 MAX_PROPERTIES_PER_ITEM * MAX_PROPERTY_KEY_LENGTH + MAX_COLLECTION_PROPERTIES_SIZE;
99
100pub struct MaxPropertiesPermissionsEncodeLen;
101
102impl Get<u32> for MaxPropertiesPermissionsEncodeLen {
103 fn get() -> u32 {
104 MAX_PROPERTIES_PER_ITEM * MAX_PROPERTY_KEY_LENGTH
105 + <PropertyPermission as MaxEncodedLen>::max_encoded_len() as u32
106 }
107}
87108
88/// How much items can be created per single109/// How much items can be created per single
89/// create_many call110/// create_many call
310 OffchainSchema,331 OffchainSchema,
311}332}
312333
313#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Debug, Derivative, MaxEncodedLen)]334#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Derivative, MaxEncodedLen)]
314#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
315#[derivative(Default(bound = ""))]335#[derivative(Debug, Default(bound = ""))]
316pub struct CreateCollectionData<AccountId> {336pub struct CreateCollectionData<AccountId> {
317 #[derivative(Default(value = "CollectionMode::NFT"))]337 #[derivative(Default(value = "CollectionMode::NFT"))]
318 pub mode: CollectionMode,338 pub mode: CollectionMode,
319 pub access: Option<AccessMode>,339 pub access: Option<AccessMode>,
320 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]
321 pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,340 pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,
322 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]
323 pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,341 pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,
324 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]
325 pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,342 pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,
326 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]
327 pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,343 pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,
328 pub schema_version: Option<SchemaVersion>,344 pub schema_version: Option<SchemaVersion>,
329 pub pending_sponsor: Option<AccountId>,345 pub pending_sponsor: Option<AccountId>,
330 pub limits: Option<CollectionLimits>,346 pub limits: Option<CollectionLimits>,
331 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]
332 pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,347 pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,
333 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]
334 pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,348 pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,
335 pub meta_update_permission: Option<MetaUpdatePermission>,349 pub meta_update_permission: Option<MetaUpdatePermission>,
350 pub token_property_permissions: CollectionPropertiesPermissionsVec,
351 pub properties: CollectionPropertiesVec,
336}352}
353
354pub type CollectionPropertiesPermissionsVec =
355 BoundedVec<PropertyKeyPermission, MaxPropertiesPermissionsEncodeLen>;
356
357pub type CollectionPropertiesVec =
358 BoundedVec<Property, ConstU32<MAX_COLLECTION_PROPERTIES_ENCODE_LEN>>;
337359
338#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]360#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]
339#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]361#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
608 }630 }
609}631}
632
633pub type PropertyKey = BoundedVec<u8, ConstU32<MAX_PROPERTY_KEY_LENGTH>>;
634pub type PropertyValue = BoundedVec<u8, ConstU32<MAX_PROPERTY_VALUE_LENGTH>>;
635
636#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]
637pub enum PropertyPermission {
638 None,
639 AdminConst,
640 Admin,
641 ItemOwnerConst,
642 ItemOwner,
643 ItemOwnerOrAdmin,
644}
645
646#[derive(Encode, Decode, Debug, TypeInfo, Clone, PartialEq, MaxEncodedLen)]
647pub struct Property {
648 pub key: PropertyKey,
649 pub value: PropertyValue,
650}
651
652#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]
653pub struct PropertyKeyPermission {
654 pub key: PropertyKey,
655 pub permission: PropertyPermission,
656}
657
658pub enum PropertiesError {
659 NoSpaceForProperty,
660 PropertyLimitReached,
661}
662
663impl From<PropertiesError> for DispatchError {
664 fn from(error: PropertiesError) -> Self {
665 match error {
666 PropertiesError::NoSpaceForProperty => DispatchError::Other("no space for property"),
667 PropertiesError::PropertyLimitReached => {
668 DispatchError::Other("property key limit reached")
669 }
670 }
671 }
672}
673
674pub type PropertiesMap =
675 BoundedBTreeMap<PropertyKey, PropertyValue, ConstU32<MAX_PROPERTIES_PER_ITEM>>;
676pub type PropertiesPermissionMap =
677 BoundedBTreeMap<PropertyKey, PropertyPermission, ConstU32<MAX_PROPERTIES_PER_ITEM>>;
678
679#[derive(Encode, Decode, TypeInfo, Clone, PartialEq, MaxEncodedLen)]
680pub struct Properties {
681 map: PropertiesMap,
682 consumed_space: u32,
683 space_limit: u32,
684}
685
686impl Properties {
687 pub fn new(space_limit: u32) -> Self {
688 Self {
689 map: BoundedBTreeMap::new(),
690 consumed_space: 0,
691 space_limit,
692 }
693 }
694
695 pub fn from_collection_props_vec(
696 data: CollectionPropertiesVec,
697 ) -> Result<Self, PropertiesError> {
698 let mut props = Self::new(MAX_COLLECTION_PROPERTIES_SIZE);
699
700 for property in data.into_iter() {
701 props.try_change_property(property)?;
702 }
703
704 Ok(props)
705 }
706
707 pub fn try_change_property(&mut self, property: Property) -> Result<(), PropertiesError> {
708 let value_len = property.value.len();
709
710 if self.consumed_space as usize + value_len > self.space_limit as usize {
711 return Err(PropertiesError::NoSpaceForProperty);
712 }
713
714 self.map
715 .try_insert(property.key, property.value)
716 .map_err(|_| PropertiesError::PropertyLimitReached)?;
717
718 self.consumed_space += value_len as u32;
719
720 Ok(())
721 }
722
723 pub fn get_property(&self, key: &PropertyKey) -> Option<&PropertyValue> {
724 self.map.get(key)
725 }
726}
727
728pub struct CollectionProperties;
729
730impl Get<Properties> for CollectionProperties {
731 fn get() -> Properties {
732 Properties::new(MAX_COLLECTION_PROPERTIES_SIZE)
733 }
734}
735
736pub struct TokenProperties;
737
738impl Get<Properties> for TokenProperties {
739 fn get() -> Properties {
740 Properties::new(MAX_TOKEN_PROPERTIES_SIZE)
741 }
742}
743
744// #[cfg(not(feature = "std"))]
745// fn properties_map_debug(_properties: &PropertiesMap, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {
746// write!(f, "<properties>")
747// }
748
749// #[cfg(not(feature = "std"))]
750// fn opt_properties_permissions_map_debug(properties: &Option<PropertiesPermissionMap>, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {
751// if properties.is_some() {
752// write!(f, "Some(<properties permissions>)")
753// } else {
754// write!(f, "None")
755// }
756// }
610757
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())
 	}