git.delta.rocks / unique-network / refs/commits / 3ee9e950e03f

difftreelog

source

primitives/data-structs/src/lib.rs25.8 KiBsourcehistory
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::{20	convert::{TryFrom, TryInto},21	fmt,22};23use frame_support::{24	storage::{bounded_btree_map::BoundedBTreeMap, bounded_btree_set::BoundedBTreeSet},25	traits::Get,26	parameter_types,27};2829#[cfg(feature = "serde")]30use serde::{Serialize, Deserialize};3132use sp_core::U256;33use sp_runtime::{ArithmeticError, sp_std::prelude::Vec, Permill};34use codec::{Decode, Encode, EncodeLike, MaxEncodedLen};35use frame_support::{BoundedVec, traits::ConstU32};36use derivative::Derivative;37use scale_info::TypeInfo;3839pub mod rmrk;4041// RMRK42use rmrk::{43	CollectionInfo, NftInfo, ResourceInfo, PropertyInfo, BaseInfo, PartType, Theme, ThemeProperty,44};45pub use rmrk::{46	primitives::{47		CollectionId as RmrkCollectionId, NftId as RmrkNftId, BaseId as RmrkBaseId,48		PartId as RmrkPartId, ResourceId as RmrkResourceId,49	},50	NftChild as RmrkNftChild, AccountIdOrCollectionNftTuple as RmrkAccountIdOrCollectionNftTuple,51	FixedPart as RmrkFixedPart, SlotPart as RmrkSlotPart, EquippableList as RmrkEquippableList,52	BasicResource as RmrkBasicResource, ComposableResource as RmrkComposableResource, SlotResource as RmrkSlotResource,53};5455mod bounded;56pub mod budget;57pub mod mapping;58mod migration;5960pub const MAX_DECIMAL_POINTS: DecimalPoints = 30;61pub const MAX_REFUNGIBLE_PIECES: u128 = 1_000_000_000_000_000_000_000;62pub const MAX_SPONSOR_TIMEOUT: u32 = 10_368_000;6364pub const MAX_TOKEN_OWNERSHIP: u32 = if cfg!(not(feature = "limit-testing")) {65	100_00066} else {67	1068};69pub const COLLECTION_NUMBER_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {70	100_00071} else {72	1073};74pub const CUSTOM_DATA_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {75	204876} else {77	1078};79pub const COLLECTION_ADMINS_LIMIT: u32 = 5;80pub const COLLECTION_TOKEN_LIMIT: u32 = u32::MAX;81pub const ACCOUNT_TOKEN_OWNERSHIP_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {82	1_000_00083} else {84	1085};8687// Timeouts for item types in passed blocks88pub const NFT_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;89pub const FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;90pub const REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;9192pub const SPONSOR_APPROVE_TIMEOUT: u32 = 5;9394// Schema limits95pub const OFFCHAIN_SCHEMA_LIMIT: u32 = 8192;96pub const VARIABLE_ON_CHAIN_SCHEMA_LIMIT: u32 = 8192;97pub const CONST_ON_CHAIN_SCHEMA_LIMIT: u32 = 32768;9899pub const COLLECTION_FIELD_LIMIT: u32 = CONST_ON_CHAIN_SCHEMA_LIMIT;100101pub const MAX_COLLECTION_NAME_LENGTH: u32 = 64;102pub const MAX_COLLECTION_DESCRIPTION_LENGTH: u32 = 256;103pub const MAX_TOKEN_PREFIX_LENGTH: u32 = 16;104105pub const MAX_PROPERTY_KEY_LENGTH: u32 = 256;106pub const MAX_PROPERTY_VALUE_LENGTH: u32 = 32768;107pub const MAX_PROPERTIES_PER_ITEM: u32 = 64;108109pub const MAX_COLLECTION_PROPERTIES_SIZE: u32 = 40960;110pub const MAX_TOKEN_PROPERTIES_SIZE: u32 = 32768;111112// RMRK constants113pub const RMRK_STRING_LIMIT: u32 = 128;114pub const RMRK_COLLECTION_SYMBOL_LIMIT: u32 = 100;115pub const RMRK_RESOURCE_SYMBOL_LIMIT: u32 = 10;116pub const RMRK_KEY_LIMIT: u32 = 32;117pub const RMRK_VALUE_LIMIT: u32 = 256;118119/// How much items can be created per single120/// create_many call121pub const MAX_ITEMS_PER_BATCH: u32 = 200;122123pub type CustomDataLimit = ConstU32<CUSTOM_DATA_LIMIT>;124125#[derive(126	Encode,127	Decode,128	PartialEq,129	Eq,130	PartialOrd,131	Ord,132	Clone,133	Copy,134	Debug,135	Default,136	TypeInfo,137	MaxEncodedLen,138)]139#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]140pub struct CollectionId(pub u32);141impl EncodeLike<u32> for CollectionId {}142impl EncodeLike<CollectionId> for u32 {}143144#[derive(145	Encode,146	Decode,147	PartialEq,148	Eq,149	PartialOrd,150	Ord,151	Clone,152	Copy,153	Debug,154	Default,155	TypeInfo,156	MaxEncodedLen,157)]158#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]159pub struct TokenId(pub u32);160impl EncodeLike<u32> for TokenId {}161impl EncodeLike<TokenId> for u32 {}162163impl TokenId {164	pub fn try_next(self) -> Result<TokenId, ArithmeticError> {165		self.0166			.checked_add(1)167			.ok_or(ArithmeticError::Overflow)168			.map(Self)169	}170}171172impl From<TokenId> for U256 {173	fn from(t: TokenId) -> Self {174		t.0.into()175	}176}177178impl TryFrom<U256> for TokenId {179	type Error = &'static str;180181	fn try_from(value: U256) -> Result<Self, Self::Error> {182		Ok(TokenId(value.try_into().map_err(|_| "too large token id")?))183	}184}185186#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]187#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]188pub struct TokenData<CrossAccountId> {189	pub properties: Vec<Property>,190	pub owner: Option<CrossAccountId>,191}192193pub struct OverflowError;194impl From<OverflowError> for &'static str {195	fn from(_: OverflowError) -> Self {196		"overflow occured"197	}198}199200pub type DecimalPoints = u8;201202#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]203#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]204pub enum CollectionMode {205	NFT,206	// decimal points207	Fungible(DecimalPoints),208	ReFungible,209}210211impl CollectionMode {212	pub fn id(&self) -> u8 {213		match self {214			CollectionMode::NFT => 1,215			CollectionMode::Fungible(_) => 2,216			CollectionMode::ReFungible => 3,217		}218	}219}220221pub trait SponsoringResolve<AccountId, Call> {222	fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>;223}224225#[derive(Encode, Decode, Eq, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]226#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]227pub enum AccessMode {228	Normal,229	AllowList,230}231impl Default for AccessMode {232	fn default() -> Self {233		Self::Normal234	}235}236237#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]238#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]239pub enum SchemaVersion {240	ImageURL,241	Unique,242}243impl Default for SchemaVersion {244	fn default() -> Self {245		Self::ImageURL246	}247}248249#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]250#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]251pub struct Ownership<AccountId> {252	pub owner: AccountId,253	pub fraction: u128,254}255256#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]257#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]258pub enum SponsorshipState<AccountId> {259	/// The fees are applied to the transaction sender260	Disabled,261	Unconfirmed(AccountId),262	/// Transactions are sponsored by specified account263	Confirmed(AccountId),264}265266impl<AccountId> SponsorshipState<AccountId> {267	pub fn sponsor(&self) -> Option<&AccountId> {268		match self {269			Self::Confirmed(sponsor) => Some(sponsor),270			_ => None,271		}272	}273274	pub fn pending_sponsor(&self) -> Option<&AccountId> {275		match self {276			Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),277			_ => None,278		}279	}280281	pub fn confirmed(&self) -> bool {282		matches!(self, Self::Confirmed(_))283	}284}285286impl<T> Default for SponsorshipState<T> {287	fn default() -> Self {288		Self::Disabled289	}290}291292/// Used in storage293#[struct_versioning::versioned(version = 2, upper)]294#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen)]295pub struct Collection<AccountId> {296	pub owner: AccountId,297	pub mode: CollectionMode,298	#[version(..2)]299	pub access: AccessMode,300	pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,301	pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,302	pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,303304	#[version(..2)]305	pub mint_mode: bool,306307	#[version(..2)]308	pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,309310	#[version(..2)]311	pub schema_version: SchemaVersion,312	pub sponsorship: SponsorshipState<AccountId>,313314	pub limits: CollectionLimits,315316	#[version(2.., upper(Default::default()))]317	pub permissions: CollectionPermissions,318319	#[version(..2)]320	pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,321322	#[version(..2)]323	pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,324325	#[version(..2)]326	pub meta_update_permission: MetaUpdatePermission,327}328329/// Used in RPC calls330#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]331#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]332pub struct RpcCollection<AccountId> {333	pub owner: AccountId,334	pub mode: CollectionMode,335	pub name: Vec<u16>,336	pub description: Vec<u16>,337	pub token_prefix: Vec<u8>,338	pub sponsorship: SponsorshipState<AccountId>,339	pub limits: CollectionLimits,340	pub permissions: CollectionPermissions,341	pub token_property_permissions: Vec<PropertyKeyPermission>,342	pub properties: Vec<Property>,343}344345#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Derivative, MaxEncodedLen)]346#[derivative(Debug, Default(bound = ""))]347pub struct CreateCollectionData<AccountId> {348	#[derivative(Default(value = "CollectionMode::NFT"))]349	pub mode: CollectionMode,350	pub access: Option<AccessMode>,351	pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,352	pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,353	pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,354	pub pending_sponsor: Option<AccountId>,355	pub limits: Option<CollectionLimits>,356	pub permissions: Option<CollectionPermissions>,357	pub token_property_permissions: CollectionPropertiesPermissionsVec,358	pub properties: CollectionPropertiesVec,359}360361pub type CollectionPropertiesPermissionsVec =362	BoundedVec<PropertyKeyPermission, ConstU32<MAX_PROPERTIES_PER_ITEM>>;363364pub type CollectionPropertiesVec =365	BoundedVec<Property, ConstU32<MAX_PROPERTIES_PER_ITEM>>;366367/// All fields are wrapped in `Option`s, where None means chain default368#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]369#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]370pub struct CollectionLimits {371	pub account_token_ownership_limit: Option<u32>,372	pub sponsored_data_size: Option<u32>,373374	/// FIXME should we delete this or repurpose it?375	/// None - setVariableMetadata is not sponsored376	/// Some(v) - setVariableMetadata is sponsored377	///           if there is v block between txs378	pub sponsored_data_rate_limit: Option<SponsoringRateLimit>,379	pub token_limit: Option<u32>,380381	// Timeouts for item types in passed blocks382	pub sponsor_transfer_timeout: Option<u32>,383	pub sponsor_approve_timeout: Option<u32>,384	pub owner_can_transfer: Option<bool>,385	pub owner_can_destroy: Option<bool>,386	pub transfers_enabled: Option<bool>,387}388389impl CollectionLimits {390	pub fn account_token_ownership_limit(&self) -> u32 {391		self.account_token_ownership_limit392			.unwrap_or(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)393			.min(MAX_TOKEN_OWNERSHIP)394	}395	pub fn sponsored_data_size(&self) -> u32 {396		self.sponsored_data_size397			.unwrap_or(CUSTOM_DATA_LIMIT)398			.min(CUSTOM_DATA_LIMIT)399	}400	pub fn token_limit(&self) -> u32 {401		self.token_limit402			.unwrap_or(COLLECTION_TOKEN_LIMIT)403			.min(COLLECTION_TOKEN_LIMIT)404	}405	pub fn sponsor_transfer_timeout(&self, default: u32) -> u32 {406		self.sponsor_transfer_timeout407			.unwrap_or(default)408			.min(MAX_SPONSOR_TIMEOUT)409	}410	pub fn sponsor_approve_timeout(&self) -> u32 {411		self.sponsor_approve_timeout412			.unwrap_or(SPONSOR_APPROVE_TIMEOUT)413			.min(MAX_SPONSOR_TIMEOUT)414	}415	pub fn owner_can_transfer(&self) -> bool {416		self.owner_can_transfer.unwrap_or(true)417	}418	pub fn owner_can_destroy(&self) -> bool {419		self.owner_can_destroy.unwrap_or(true)420	}421	pub fn transfers_enabled(&self) -> bool {422		self.transfers_enabled.unwrap_or(true)423	}424	pub fn sponsored_data_rate_limit(&self) -> Option<u32> {425		match self426			.sponsored_data_rate_limit427			.unwrap_or(SponsoringRateLimit::SponsoringDisabled)428		{429			SponsoringRateLimit::SponsoringDisabled => None,430			SponsoringRateLimit::Blocks(v) => Some(v.min(MAX_SPONSOR_TIMEOUT)),431		}432	}433}434435#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]436#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]437pub struct CollectionPermissions {438	pub access: Option<AccessMode>,439	pub mint_mode: Option<bool>,440	pub nesting: Option<NestingRule>,441}442443impl CollectionPermissions {444	pub fn access(&self) -> AccessMode {445		self.access.unwrap_or(AccessMode::Normal)446	}447	pub fn mint_mode(&self) -> bool {448		self.mint_mode.unwrap_or(false)449	}450	pub fn nesting(&self) -> &NestingRule {451		static DEFAULT: NestingRule = NestingRule::Disabled;452		self.nesting.as_ref().unwrap_or(&DEFAULT)453	}454}455456#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative)]457#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]458#[derivative(Debug)]459pub enum NestingRule {460	/// No one can nest tokens461	Disabled,462	/// Owner can nest any tokens463	Owner,464	/// Owner can nest tokens from specified collections465	OwnerRestricted(466		#[cfg_attr(feature = "serde1", serde(with = "bounded::set_serde"))]467		#[derivative(Debug(format_with = "bounded::set_debug"))]468		BoundedBTreeSet<CollectionId, ConstU32<16>>,469	),470}471472#[derive(Encode, Decode, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]473#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]474pub enum SponsoringRateLimit {475	SponsoringDisabled,476	Blocks(u32),477}478479#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]480#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]481#[derivative(Debug)]482pub struct CreateNftData {483	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]484	#[derivative(Debug(format_with = "bounded::vec_debug"))]485	pub const_data: BoundedVec<u8, CustomDataLimit>,486487	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]488	#[derivative(Debug(format_with = "bounded::vec_debug"))]489	pub properties: CollectionPropertiesVec,490}491492#[derive(Encode, Decode, MaxEncodedLen, Default, Debug, Clone, PartialEq, TypeInfo)]493#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]494pub struct CreateFungibleData {495	pub value: u128,496}497498#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]499#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]500#[derivative(Debug)]501pub struct CreateReFungibleData {502	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]503	#[derivative(Debug(format_with = "bounded::vec_debug"))]504	pub const_data: BoundedVec<u8, CustomDataLimit>,505	pub pieces: u128,506}507508#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]509pub enum MetaUpdatePermission {510	ItemOwner,511	Admin,512	None,513}514515#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]516#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]517pub enum CreateItemData {518	NFT(CreateNftData),519	Fungible(CreateFungibleData),520	ReFungible(CreateReFungibleData),521}522523#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]524#[derivative(Debug)]525pub struct CreateNftExData<CrossAccountId> {526	#[derivative(Debug(format_with = "bounded::vec_debug"))]527	pub properties: CollectionPropertiesVec,528	pub owner: CrossAccountId,529}530531#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]532#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]533pub struct CreateRefungibleExData<CrossAccountId> {534	#[derivative(Debug(format_with = "bounded::vec_debug"))]535	pub const_data: BoundedVec<u8, CustomDataLimit>,536	#[derivative(Debug(format_with = "bounded::map_debug"))]537	pub users: BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,538}539540#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]541#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]542pub enum CreateItemExData<CrossAccountId> {543	NFT(544		#[derivative(Debug(format_with = "bounded::vec_debug"))]545		BoundedVec<CreateNftExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,546	),547	Fungible(548		#[derivative(Debug(format_with = "bounded::map_debug"))]549		BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,550	),551	/// Many tokens, each may have only one owner552	RefungibleMultipleItems(553		#[derivative(Debug(format_with = "bounded::vec_debug"))]554		BoundedVec<CreateRefungibleExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,555	),556	/// Single token, which may have many owners557	RefungibleMultipleOwners(CreateRefungibleExData<CrossAccountId>),558}559560impl CreateItemData {561	pub fn data_size(&self) -> usize {562		match self {563			CreateItemData::NFT(data) => data.const_data.len(),564			CreateItemData::ReFungible(data) => data.const_data.len(),565			_ => 0,566		}567	}568}569570impl From<CreateNftData> for CreateItemData {571	fn from(item: CreateNftData) -> Self {572		CreateItemData::NFT(item)573	}574}575576impl From<CreateReFungibleData> for CreateItemData {577	fn from(item: CreateReFungibleData) -> Self {578		CreateItemData::ReFungible(item)579	}580}581582impl From<CreateFungibleData> for CreateItemData {583	fn from(item: CreateFungibleData) -> Self {584		CreateItemData::Fungible(item)585	}586}587588#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]589#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]590pub struct CollectionStats {591	pub created: u32,592	pub destroyed: u32,593	pub alive: u32,594}595596#[derive(Encode, Decode, Clone, Debug)]597#[cfg_attr(feature = "std", derive(PartialEq))]598pub struct PhantomType<T>(core::marker::PhantomData<T>);599600impl<T: TypeInfo + 'static> TypeInfo for PhantomType<T> {601	type Identity = PhantomType<T>;602603	fn type_info() -> scale_info::Type {604		use scale_info::{605			Type, Path,606			build::{FieldsBuilder, UnnamedFields},607			type_params,608		};609		Type::builder()610			.path(Path::new("up_data_structs", "PhantomType"))611			.type_params(type_params!(T))612			.composite(<FieldsBuilder<UnnamedFields>>::default().field(|b| b.ty::<[T; 0]>()))613	}614}615impl<T> MaxEncodedLen for PhantomType<T> {616	fn max_encoded_len() -> usize {617		0618	}619}620621pub type PropertyKey = BoundedVec<u8, ConstU32<MAX_PROPERTY_KEY_LENGTH>>;622pub type PropertyValue = BoundedVec<u8, ConstU32<MAX_PROPERTY_VALUE_LENGTH>>;623624#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]625#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]626pub struct PropertyPermission {627	pub mutable: bool,628	pub collection_admin: bool,629	pub token_owner: bool,630}631632impl PropertyPermission {633	pub fn none() -> Self {634		Self {635			mutable: true,636			collection_admin: false,637			token_owner: false,638		}639	}640}641642#[derive(Encode, Decode, Debug, TypeInfo, Clone, PartialEq, MaxEncodedLen)]643#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]644pub struct Property {645	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]646	pub key: PropertyKey,647648	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]649	pub value: PropertyValue,650}651652impl Into<(PropertyKey, PropertyValue)> for Property {653	fn into(self) -> (PropertyKey, PropertyValue) {654		(self.key, self.value)655	}656}657658#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]659#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]660pub struct PropertyKeyPermission {661	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]662	pub key: PropertyKey,663664	pub permission: PropertyPermission,665}666667impl Into<(PropertyKey, PropertyPermission)> for PropertyKeyPermission {668	fn into(self) -> (PropertyKey, PropertyPermission) {669		(self.key, self.permission)670	}671}672673#[derive(Debug)]674pub enum PropertiesError {675	NoSpaceForProperty,676	PropertyLimitReached,677	InvalidCharacterInPropertyKey,678	PropertyKeyIsTooLong,679	EmptyPropertyKey,680}681682#[derive(Clone, Copy)]683pub enum PropertyScope {684	None,685	Rmrk,686}687688impl PropertyScope {689	pub fn apply(self, key: PropertyKey) -> Result<PropertyKey, PropertiesError> {690		let scope_str: &[u8] = match self {691			Self::None => return Ok(key),692			Self::Rmrk => b"rmrk",693		};694695		[scope_str, b":", key.as_slice()]696			.concat()697			.try_into()698			.map_err(|_| PropertiesError::PropertyKeyIsTooLong)699	}700}701702pub trait TrySetProperty: Sized {703	type Value;704705	fn try_scoped_set(706		&mut self,707		scope: PropertyScope,708		key: PropertyKey,709		value: Self::Value,710	) -> Result<(), PropertiesError>;711712	fn try_scoped_set_from_iter<I, KV>(713		&mut self,714		scope: PropertyScope,715		iter: I,716	) -> Result<(), PropertiesError>717	where718		I: Iterator<Item = KV>,719		KV: Into<(PropertyKey, Self::Value)>,720	{721		for kv in iter {722			let (key, value) = kv.into();723			self.try_scoped_set(scope, key, value)?;724		}725726		Ok(())727	}728729	fn try_set(&mut self, key: PropertyKey, value: Self::Value) -> Result<(), PropertiesError> {730		self.try_scoped_set(PropertyScope::None, key, value)731	}732733	fn try_set_from_iter<I, KV>(&mut self, iter: I) -> Result<(), PropertiesError>734	where735		I: Iterator<Item = KV>,736		KV: Into<(PropertyKey, Self::Value)>,737	{738		self.try_scoped_set_from_iter(PropertyScope::None, iter)739	}740}741742#[derive(Encode, Decode, TypeInfo, Derivative, Clone, PartialEq, MaxEncodedLen)]743#[derivative(Default(bound = ""))]744pub struct PropertiesMap<Value>(745	BoundedBTreeMap<PropertyKey, Value, ConstU32<MAX_PROPERTIES_PER_ITEM>>,746);747748impl<Value> PropertiesMap<Value> {749	pub fn new() -> Self {750		Self(BoundedBTreeMap::new())751	}752753	pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<Value>, PropertiesError> {754		Self::check_property_key(key)?;755756		Ok(self.0.remove(key))757	}758759	pub fn get(&self, key: &PropertyKey) -> Option<&Value> {760		self.0.get(key)761	}762763	fn check_property_key(key: &PropertyKey) -> Result<(), PropertiesError> {764		if key.is_empty() {765			return Err(PropertiesError::EmptyPropertyKey);766		}767768		for byte in key.as_slice().iter() {769			let byte = *byte;770771			if !byte.is_ascii_alphanumeric() && byte != b'_' && byte != b'-' {772				return Err(PropertiesError::InvalidCharacterInPropertyKey);773			}774		}775776		Ok(())777	}778}779780impl<Value> IntoIterator for PropertiesMap<Value> {781	type Item = (PropertyKey, Value);782	type IntoIter = <783		BoundedBTreeMap<784			PropertyKey,785			Value,786			ConstU32<MAX_PROPERTIES_PER_ITEM>787		> as IntoIterator788	>::IntoIter;789790	fn into_iter(self) -> Self::IntoIter {791        self.0.into_iter()792    }793}794795impl<Value> TrySetProperty for PropertiesMap<Value> {796	type Value = Value;797798	fn try_scoped_set(799		&mut self,800		scope: PropertyScope,801		key: PropertyKey,802		value: Self::Value,803	) -> Result<(), PropertiesError> {804		Self::check_property_key(&key)?;805806		let key = scope.apply(key)?;807		self.0808			.try_insert(key, value)809			.map_err(|_| PropertiesError::PropertyLimitReached)?;810811		Ok(())812	}813}814815pub type PropertiesPermissionMap = PropertiesMap<PropertyPermission>;816817#[derive(Encode, Decode, TypeInfo, Clone, PartialEq, MaxEncodedLen)]818pub struct Properties {819	map: PropertiesMap<PropertyValue>,820	consumed_space: u32,821	space_limit: u32,822}823824impl Properties {825	pub fn new(space_limit: u32) -> Self {826		Self {827			map: PropertiesMap::new(),828			consumed_space: 0,829			space_limit,830		}831	}832833	pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<PropertyValue>, PropertiesError> {834		let value = self.map.remove(key)?;835836		if let Some(ref value) = value {837			let value_len = value.len() as u32;838			self.consumed_space -= value_len;839		}840841		Ok(value)842	}843844	pub fn get(&self, key: &PropertyKey) -> Option<&PropertyValue> {845		self.map.get(key)846	}847}848849impl IntoIterator for Properties {850	type Item = (PropertyKey, PropertyValue);851	type IntoIter = <PropertiesMap<PropertyValue> as IntoIterator>::IntoIter;852853	fn into_iter(self) -> Self::IntoIter {854        self.map.into_iter()855    }856}857858impl TrySetProperty for Properties {859	type Value = PropertyValue;860861	fn try_scoped_set(862		&mut self,863		scope: PropertyScope,864		key: PropertyKey,865		value: Self::Value,866	) -> Result<(), PropertiesError> {867		let value_len = value.len();868869		if self.consumed_space as usize + value_len > self.space_limit as usize870			&& !cfg!(feature = "runtime-benchmarks")871		{872			return Err(PropertiesError::NoSpaceForProperty);873		}874875		self.map.try_scoped_set(scope, key, value)?;876877		self.consumed_space += value_len as u32;878879		Ok(())880	}881}882883pub struct CollectionProperties;884885impl Get<Properties> for CollectionProperties {886	fn get() -> Properties {887		Properties::new(MAX_COLLECTION_PROPERTIES_SIZE)888	}889}890891pub struct TokenProperties;892893impl Get<Properties> for TokenProperties {894	fn get() -> Properties {895		Properties::new(MAX_TOKEN_PROPERTIES_SIZE)896	}897}898899// RMRK900// todo document?901parameter_types! {902	#[derive(PartialEq, TypeInfo)]903	pub const RmrkStringLimit: u32 = 128;904	#[derive(PartialEq)]905	pub const RmrkCollectionSymbolLimit: u32 = 100;906	#[derive(PartialEq)]907	pub const RmrkResourceSymbolLimit: u32 = 10;908	#[derive(PartialEq)]909	pub const RmrkKeyLimit: u32 = 32;910	#[derive(PartialEq)]911	pub const RmrkValueLimit: u32 = 256;912	#[derive(PartialEq)]913	pub const RmrkMaxCollectionsEquippablePerPart: u32 = 100;914	#[derive(PartialEq)]915	pub const RmrkPartsLimit: u32 = 3;916}917918impl From<RmrkCollectionId> for CollectionId {919	fn from(id: RmrkCollectionId) -> Self {920		Self(id)921	}922}923924impl From<RmrkNftId> for TokenId {925	fn from(id: RmrkNftId) -> Self {926		Self(id)927	}928}929930pub type RmrkCollectionInfo<AccountId> =931	CollectionInfo<RmrkString, RmrkCollectionSymbol, AccountId>;932pub type RmrkInstanceInfo<AccountId> = NftInfo<AccountId, Permill, RmrkString>;933pub type RmrkResourceInfo = ResourceInfo<934	RmrkBoundedResource,935	RmrkString,936	RmrkBoundedParts,937>;938pub type RmrkPropertyInfo = PropertyInfo<RmrkKeyString, RmrkValueString>;939pub type RmrkBaseInfo<AccountId> = BaseInfo<AccountId, RmrkString>;940pub type RmrkPartType =941	PartType<RmrkString, BoundedVec<RmrkCollectionId, RmrkMaxCollectionsEquippablePerPart>>;942pub type RmrkThemeProperty = ThemeProperty<RmrkString>;943pub type RmrkTheme = Theme<RmrkString, Vec<RmrkThemeProperty>>;944945pub type RmrkCollectionSymbol = BoundedVec<u8, RmrkCollectionSymbolLimit>;946pub type RmrkKeyString = BoundedVec<u8, RmrkKeyLimit>;947pub type RmrkValueString = BoundedVec<u8, RmrkValueLimit>;948949type RmrkBoundedResource = BoundedVec<u8, RmrkResourceSymbolLimit>;950type RmrkBoundedParts = BoundedVec<RmrkPartId, RmrkPartsLimit>;951952pub type RmrkRpcString = Vec<u8>;953pub type RmrkThemeName = RmrkRpcString;954pub type RmrkPropertyKey = RmrkRpcString;955956pub type RmrkString = BoundedVec<u8, RmrkStringLimit>;