git.delta.rocks / unique-network / refs/commits / 9b4da675e61d

difftreelog

source

primitives/data-structs/src/lib.rs29.4 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;3839// RMRK40use rmrk_traits::{41	CollectionInfo, NftInfo, ResourceInfo, PropertyInfo, BaseInfo, PartType, Theme, ThemeProperty,42	ResourceTypes, BasicResource, ComposableResource, SlotResource, EquippableList,43};44pub use rmrk_traits::{45	primitives::{46		CollectionId as RmrkCollectionId, NftId as RmrkNftId, BaseId as RmrkBaseId,47		SlotId as RmrkSlotId, PartId as RmrkPartId, ResourceId as RmrkResourceId,48	},49	NftChild as RmrkNftChild, AccountIdOrCollectionNftTuple as RmrkAccountIdOrCollectionNftTuple,50	FixedPart as RmrkFixedPart, SlotPart as RmrkSlotPart,51};5253mod bounded;54pub mod budget;55pub mod mapping;56mod migration;5758pub const MAX_DECIMAL_POINTS: DecimalPoints = 30;59pub const MAX_REFUNGIBLE_PIECES: u128 = 1_000_000_000_000_000_000_000;60pub const MAX_SPONSOR_TIMEOUT: u32 = 10_368_000;6162pub const MAX_TOKEN_OWNERSHIP: u32 = if cfg!(not(feature = "limit-testing")) {63	100_00064} else {65	1066};67pub const COLLECTION_NUMBER_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {68	100_00069} else {70	1071};72pub const CUSTOM_DATA_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {73	204874} else {75	1076};77pub const COLLECTION_ADMINS_LIMIT: u32 = 5;78pub const COLLECTION_TOKEN_LIMIT: u32 = u32::MAX;79pub const ACCOUNT_TOKEN_OWNERSHIP_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {80	1_000_00081} else {82	1083};8485// Timeouts for item types in passed blocks86pub const NFT_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;87pub const FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;88pub const REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;8990pub const SPONSOR_APPROVE_TIMEOUT: u32 = 5;9192// Schema limits93pub const OFFCHAIN_SCHEMA_LIMIT: u32 = 8192;94pub const VARIABLE_ON_CHAIN_SCHEMA_LIMIT: u32 = 8192;95pub const CONST_ON_CHAIN_SCHEMA_LIMIT: u32 = 32768;9697pub const COLLECTION_FIELD_LIMIT: u32 = CONST_ON_CHAIN_SCHEMA_LIMIT;9899pub const MAX_COLLECTION_NAME_LENGTH: u32 = 64;100pub const MAX_COLLECTION_DESCRIPTION_LENGTH: u32 = 256;101pub const MAX_TOKEN_PREFIX_LENGTH: u32 = 16;102103pub const MAX_PROPERTY_KEY_LENGTH: u32 = 256;104pub const MAX_PROPERTY_VALUE_LENGTH: u32 = 32768;105pub const MAX_PROPERTIES_PER_ITEM: u32 = 64;106107pub const MAX_AUX_PROPERTY_VALUE_LENGTH: u32 = 2048;108109pub const MAX_COLLECTION_PROPERTIES_SIZE: u32 = 40960;110pub const MAX_TOKEN_PROPERTIES_SIZE: u32 = 32768;111112/// How much items can be created per single113/// create_many call114pub const MAX_ITEMS_PER_BATCH: u32 = 200;115116pub type CustomDataLimit = ConstU32<CUSTOM_DATA_LIMIT>;117118#[derive(119	Encode,120	Decode,121	PartialEq,122	Eq,123	PartialOrd,124	Ord,125	Clone,126	Copy,127	Debug,128	Default,129	TypeInfo,130	MaxEncodedLen,131)]132#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]133pub struct CollectionId(pub u32);134impl EncodeLike<u32> for CollectionId {}135impl EncodeLike<CollectionId> for u32 {}136137#[derive(138	Encode,139	Decode,140	PartialEq,141	Eq,142	PartialOrd,143	Ord,144	Clone,145	Copy,146	Debug,147	Default,148	TypeInfo,149	MaxEncodedLen,150)]151#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]152pub struct TokenId(pub u32);153impl EncodeLike<u32> for TokenId {}154impl EncodeLike<TokenId> for u32 {}155156impl TokenId {157	pub fn try_next(self) -> Result<TokenId, ArithmeticError> {158		self.0159			.checked_add(1)160			.ok_or(ArithmeticError::Overflow)161			.map(Self)162	}163}164165impl From<TokenId> for U256 {166	fn from(t: TokenId) -> Self {167		t.0.into()168	}169}170171impl TryFrom<U256> for TokenId {172	type Error = &'static str;173174	fn try_from(value: U256) -> Result<Self, Self::Error> {175		Ok(TokenId(value.try_into().map_err(|_| "too large token id")?))176	}177}178179#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]180#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]181pub struct TokenData<CrossAccountId> {182	pub properties: Vec<Property>,183	pub owner: Option<CrossAccountId>,184	pub pieces: u128,185}186187pub struct OverflowError;188impl From<OverflowError> for &'static str {189	fn from(_: OverflowError) -> Self {190		"overflow occured"191	}192}193194pub type DecimalPoints = u8;195196#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]197#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]198pub enum CollectionMode {199	NFT,200	Fungible(DecimalPoints),201	ReFungible,202}203204impl CollectionMode {205	pub fn id(&self) -> u8 {206		match self {207			CollectionMode::NFT => 1,208			CollectionMode::Fungible(_) => 2,209			CollectionMode::ReFungible => 3,210		}211	}212}213214pub trait SponsoringResolve<AccountId, Call> {215	fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>;216}217218#[derive(Encode, Decode, Eq, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]219#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]220pub enum AccessMode {221	Normal,222	AllowList,223}224impl Default for AccessMode {225	fn default() -> Self {226		Self::Normal227	}228}229230#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]231#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]232pub enum SchemaVersion {233	ImageURL,234	Unique,235}236impl Default for SchemaVersion {237	fn default() -> Self {238		Self::ImageURL239	}240}241242#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]243#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]244pub struct Ownership<AccountId> {245	pub owner: AccountId,246	pub fraction: u128,247}248249#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]250#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]251pub enum SponsorshipState<AccountId> {252	/// The fees are applied to the transaction sender253	Disabled,254	/// Pending confirmation from a sponsor-to-be255	Unconfirmed(AccountId),256	/// Transactions are sponsored by specified account257	Confirmed(AccountId),258}259260impl<AccountId> SponsorshipState<AccountId> {261	/// Get the acting sponsor account, if present262	pub fn sponsor(&self) -> Option<&AccountId> {263		match self {264			Self::Confirmed(sponsor) => Some(sponsor),265			_ => None,266		}267	}268269	/// Get the sponsor account currently pending confirmation, if present270	pub fn pending_sponsor(&self) -> Option<&AccountId> {271		match self {272			Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),273			_ => None,274		}275	}276277	/// Is sponsorship set and acting278	pub fn confirmed(&self) -> bool {279		matches!(self, Self::Confirmed(_))280	}281}282283impl<T> Default for SponsorshipState<T> {284	fn default() -> Self {285		Self::Disabled286	}287}288289/// Collection parameters, used in storage (see [`RpcCollection`] for the RPC version).290#[struct_versioning::versioned(version = 2, upper)]291#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen)]292pub struct Collection<AccountId> {293	pub owner: AccountId,294	pub mode: CollectionMode,295	#[version(..2)]296	pub access: AccessMode,297	pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,298	pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,299	pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,300301	#[version(..2)]302	pub mint_mode: bool,303304	#[version(..2)]305	pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,306307	#[version(..2)]308	pub schema_version: SchemaVersion,309	pub sponsorship: SponsorshipState<AccountId>,310311	pub limits: CollectionLimits,312313	#[version(2.., upper(Default::default()))]314	pub permissions: CollectionPermissions,315316	/// Marks that this collection is not "unique", and managed from external.317	#[version(2.., upper(false))]318	pub external_collection: bool,319320	#[version(..2)]321	pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,322323	#[version(..2)]324	pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,325326	#[version(..2)]327	pub meta_update_permission: MetaUpdatePermission,328}329330/// Collection parameters, used in RPC calls (see [`Collection`] for the storage version).331#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]332#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]333pub struct RpcCollection<AccountId> {334	pub owner: AccountId,335	pub mode: CollectionMode,336	pub name: Vec<u16>,337	pub description: Vec<u16>,338	pub token_prefix: Vec<u8>,339	pub sponsorship: SponsorshipState<AccountId>,340	pub limits: CollectionLimits,341	pub permissions: CollectionPermissions,342	pub token_property_permissions: Vec<PropertyKeyPermission>,343	pub properties: Vec<Property>,344	pub read_only: bool,345}346347#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Derivative, MaxEncodedLen)]348#[derivative(Debug, Default(bound = ""))]349pub struct CreateCollectionData<AccountId> {350	#[derivative(Default(value = "CollectionMode::NFT"))]351	pub mode: CollectionMode,352	pub access: Option<AccessMode>,353	pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,354	pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,355	pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,356	pub pending_sponsor: Option<AccountId>,357	pub limits: Option<CollectionLimits>,358	pub permissions: Option<CollectionPermissions>,359	pub token_property_permissions: CollectionPropertiesPermissionsVec,360	pub properties: CollectionPropertiesVec,361}362363pub type CollectionPropertiesPermissionsVec =364	BoundedVec<PropertyKeyPermission, ConstU32<MAX_PROPERTIES_PER_ITEM>>;365366pub type CollectionPropertiesVec = BoundedVec<Property, ConstU32<MAX_PROPERTIES_PER_ITEM>>;367368/// Limits and restrictions of a collection.369/// All fields are wrapped in `Option`s, where None means chain default.370// When adding/removing fields from this struct - don't forget to also update clamp_limits371#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]372#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]373pub struct CollectionLimits {374	/// Maximum number of owned tokens per account375	pub account_token_ownership_limit: Option<u32>,376	/// Maximum size of data of a sponsored transaction377	pub sponsored_data_size: Option<u32>,378379	/// FIXME should we delete this or repurpose it?380	/// None - setVariableMetadata is not sponsored381	/// Some(v) - setVariableMetadata is sponsored382	///           if there is v block between txs383	pub sponsored_data_rate_limit: Option<SponsoringRateLimit>,384	/// Maximum amount of tokens inside the collection385	pub token_limit: Option<u32>,386387	/// Timeout for sponsoring a token transfer in passed blocks388	pub sponsor_transfer_timeout: Option<u32>,389	/// Timeout for sponsoring an approval in passed blocks390	pub sponsor_approve_timeout: Option<u32>,391	/// Can a token be transferred by the owner392	pub owner_can_transfer: Option<bool>,393	/// Can a token be burned by the owner394	pub owner_can_destroy: Option<bool>,395	/// Can a token be transferred at all396	pub transfers_enabled: Option<bool>,397}398399impl CollectionLimits {400	pub fn account_token_ownership_limit(&self) -> u32 {401		self.account_token_ownership_limit402			.unwrap_or(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)403			.min(MAX_TOKEN_OWNERSHIP)404	}405	pub fn sponsored_data_size(&self) -> u32 {406		self.sponsored_data_size407			.unwrap_or(CUSTOM_DATA_LIMIT)408			.min(CUSTOM_DATA_LIMIT)409	}410	pub fn token_limit(&self) -> u32 {411		self.token_limit412			.unwrap_or(COLLECTION_TOKEN_LIMIT)413			.min(COLLECTION_TOKEN_LIMIT)414	}415	pub fn sponsor_transfer_timeout(&self, default: u32) -> u32 {416		self.sponsor_transfer_timeout417			.unwrap_or(default)418			.min(MAX_SPONSOR_TIMEOUT)419	}420	pub fn sponsor_approve_timeout(&self) -> u32 {421		self.sponsor_approve_timeout422			.unwrap_or(SPONSOR_APPROVE_TIMEOUT)423			.min(MAX_SPONSOR_TIMEOUT)424	}425	pub fn owner_can_transfer(&self) -> bool {426		self.owner_can_transfer.unwrap_or(false)427	}428	pub fn owner_can_transfer_instaled(&self) -> bool {429		self.owner_can_transfer.is_some()430	}431	pub fn owner_can_destroy(&self) -> bool {432		self.owner_can_destroy.unwrap_or(true)433	}434	pub fn transfers_enabled(&self) -> bool {435		self.transfers_enabled.unwrap_or(true)436	}437	pub fn sponsored_data_rate_limit(&self) -> Option<u32> {438		match self439			.sponsored_data_rate_limit440			.unwrap_or(SponsoringRateLimit::SponsoringDisabled)441		{442			SponsoringRateLimit::SponsoringDisabled => None,443			SponsoringRateLimit::Blocks(v) => Some(v.min(MAX_SPONSOR_TIMEOUT)),444		}445	}446}447448// When adding/removing fields from this struct - don't forget to also update clamp_limits449#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]450#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]451pub struct CollectionPermissions {452	pub access: Option<AccessMode>,453	pub mint_mode: Option<bool>,454	pub nesting: Option<NestingPermissions>,455}456457impl CollectionPermissions {458	pub fn access(&self) -> AccessMode {459		self.access.unwrap_or(AccessMode::Normal)460	}461	pub fn mint_mode(&self) -> bool {462		self.mint_mode.unwrap_or(false)463	}464	pub fn nesting(&self) -> &NestingPermissions {465		static DEFAULT: NestingPermissions = NestingPermissions {466			token_owner: false,467			collection_admin: false,468			restricted: None,469			#[cfg(feature = "runtime-benchmarks")]470			permissive: false,471		};472		self.nesting.as_ref().unwrap_or(&DEFAULT)473	}474}475476type OwnerRestrictedSetInner = BoundedBTreeSet<CollectionId, ConstU32<16>>;477478#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative)]479#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]480#[derivative(Debug)]481pub struct OwnerRestrictedSet(482	#[cfg_attr(feature = "serde1", serde(with = "bounded::set_serde"))]483	#[derivative(Debug(format_with = "bounded::set_debug"))]484	pub OwnerRestrictedSetInner,485);486impl OwnerRestrictedSet {487	pub fn new() -> Self {488		Self(Default::default())489	}490}491impl core::ops::Deref for OwnerRestrictedSet {492	type Target = OwnerRestrictedSetInner;493	fn deref(&self) -> &Self::Target {494		&self.0495	}496}497impl core::ops::DerefMut for OwnerRestrictedSet {498	fn deref_mut(&mut self) -> &mut Self::Target {499		&mut self.0500	}501}502503#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative)]504#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]505#[derivative(Debug)]506pub struct NestingPermissions {507	/// Owner of token can nest tokens under it508	pub token_owner: bool,509	/// Admin of token collection can nest tokens under token510	pub collection_admin: bool,511	/// If set - only tokens from specified collections can be nested512	pub restricted: Option<OwnerRestrictedSet>,513514	#[cfg(feature = "runtime-benchmarks")]515	/// Anyone can nest tokens, mutually exclusive with `token_owner`, `admin`516	pub permissive: bool,517}518519#[derive(Encode, Decode, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]520#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]521pub enum SponsoringRateLimit {522	SponsoringDisabled,523	/// Once per how many blocks can sponsorship of a transaction type occur524	Blocks(u32),525}526527#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]528#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]529#[derivative(Debug)]530pub struct CreateNftData {531	/// Key-value pairs used to describe the token as metadata532	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]533	#[derivative(Debug(format_with = "bounded::vec_debug"))]534	pub properties: CollectionPropertiesVec,535}536537#[derive(Encode, Decode, MaxEncodedLen, Default, Debug, Clone, PartialEq, TypeInfo)]538#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]539pub struct CreateFungibleData {540	/// Number of fungible tokens minted541	pub value: u128,542}543544#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]545#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]546#[derivative(Debug)]547pub struct CreateReFungibleData {548	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]549	#[derivative(Debug(format_with = "bounded::vec_debug"))]550	pub const_data: BoundedVec<u8, CustomDataLimit>,551	/// Number of pieces the RFT is split into552	pub pieces: u128,553}554555#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]556#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]557pub enum MetaUpdatePermission {558	ItemOwner,559	Admin,560	None,561}562563#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]564#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]565pub enum CreateItemData {566	NFT(CreateNftData),567	Fungible(CreateFungibleData),568	ReFungible(CreateReFungibleData),569}570571/// Explicit NFT creation data with meta parameters.572#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]573#[derivative(Debug)]574pub struct CreateNftExData<CrossAccountId> {575	#[derivative(Debug(format_with = "bounded::vec_debug"))]576	pub properties: CollectionPropertiesVec,577	pub owner: CrossAccountId,578}579580/// Explicit RFT creation data with meta parameters.581#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]582#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]583pub struct CreateRefungibleExData<CrossAccountId> {584	#[derivative(Debug(format_with = "bounded::vec_debug"))]585	pub const_data: BoundedVec<u8, CustomDataLimit>,586	#[derivative(Debug(format_with = "bounded::map_debug"))]587	pub users: BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,588}589590/// Explicit item creation data with meta parameters, namely the owner.591#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]592#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]593pub enum CreateItemExData<CrossAccountId> {594	NFT(595		#[derivative(Debug(format_with = "bounded::vec_debug"))]596		BoundedVec<CreateNftExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,597	),598	Fungible(599		#[derivative(Debug(format_with = "bounded::map_debug"))]600		BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,601	),602	/// Many tokens, each may have only one owner603	RefungibleMultipleItems(604		#[derivative(Debug(format_with = "bounded::vec_debug"))]605		BoundedVec<CreateRefungibleExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,606	),607	/// Single token, which may have many owners608	RefungibleMultipleOwners(CreateRefungibleExData<CrossAccountId>),609}610611impl CreateItemData {612	pub fn data_size(&self) -> usize {613		match self {614			CreateItemData::ReFungible(data) => data.const_data.len(),615			_ => 0,616		}617	}618}619620impl From<CreateNftData> for CreateItemData {621	fn from(item: CreateNftData) -> Self {622		CreateItemData::NFT(item)623	}624}625626impl From<CreateReFungibleData> for CreateItemData {627	fn from(item: CreateReFungibleData) -> Self {628		CreateItemData::ReFungible(item)629	}630}631632impl From<CreateFungibleData> for CreateItemData {633	fn from(item: CreateFungibleData) -> Self {634		CreateItemData::Fungible(item)635	}636}637638/// Token's address, dictated by its collection and token IDs.639#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]640#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]641// todo possibly rename to be used generally as an address pair642pub struct TokenChild {643	pub token: TokenId,644	pub collection: CollectionId,645}646647#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]648#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]649pub struct CollectionStats {650	pub created: u32,651	pub destroyed: u32,652	pub alive: u32,653}654655#[derive(Encode, Decode, Clone, Debug)]656#[cfg_attr(feature = "std", derive(PartialEq))]657pub struct PhantomType<T>(core::marker::PhantomData<T>);658659impl<T: TypeInfo + 'static> TypeInfo for PhantomType<T> {660	type Identity = PhantomType<T>;661662	fn type_info() -> scale_info::Type {663		use scale_info::{664			Type, Path,665			build::{FieldsBuilder, UnnamedFields},666			type_params,667		};668		Type::builder()669			.path(Path::new("up_data_structs", "PhantomType"))670			.type_params(type_params!(T))671			.composite(<FieldsBuilder<UnnamedFields>>::default().field(|b| b.ty::<[T; 0]>()))672	}673}674impl<T> MaxEncodedLen for PhantomType<T> {675	fn max_encoded_len() -> usize {676		0677	}678}679680pub type BoundedBytes<S> = BoundedVec<u8, S>;681682pub type AuxPropertyValue = BoundedBytes<ConstU32<MAX_AUX_PROPERTY_VALUE_LENGTH>>;683684pub type PropertyKey = BoundedBytes<ConstU32<MAX_PROPERTY_KEY_LENGTH>>;685pub type PropertyValue = BoundedBytes<ConstU32<MAX_PROPERTY_VALUE_LENGTH>>;686687#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]688#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]689pub struct PropertyPermission {690	pub mutable: bool,691	pub collection_admin: bool,692	pub token_owner: bool,693}694695impl PropertyPermission {696	pub fn none() -> Self {697		Self {698			mutable: true,699			collection_admin: false,700			token_owner: false,701		}702	}703}704705#[derive(Encode, Decode, Debug, TypeInfo, Clone, PartialEq, MaxEncodedLen)]706#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]707pub struct Property {708	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]709	pub key: PropertyKey,710711	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]712	pub value: PropertyValue,713}714715impl Into<(PropertyKey, PropertyValue)> for Property {716	fn into(self) -> (PropertyKey, PropertyValue) {717		(self.key, self.value)718	}719}720721#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]722#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]723pub struct PropertyKeyPermission {724	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]725	pub key: PropertyKey,726727	pub permission: PropertyPermission,728}729730impl Into<(PropertyKey, PropertyPermission)> for PropertyKeyPermission {731	fn into(self) -> (PropertyKey, PropertyPermission) {732		(self.key, self.permission)733	}734}735736#[derive(Debug)]737pub enum PropertiesError {738	NoSpaceForProperty,739	PropertyLimitReached,740	InvalidCharacterInPropertyKey,741	PropertyKeyIsTooLong,742	EmptyPropertyKey,743}744745#[derive(Encode, Decode, MaxEncodedLen, TypeInfo, PartialEq, Clone, Copy)]746pub enum PropertyScope {747	None,748	Rmrk,749}750751impl PropertyScope {752	pub fn apply(self, key: PropertyKey) -> Result<PropertyKey, PropertiesError> {753		let scope_str: &[u8] = match self {754			Self::None => return Ok(key),755			Self::Rmrk => b"rmrk",756		};757758		[scope_str, b":", key.as_slice()]759			.concat()760			.try_into()761			.map_err(|_| PropertiesError::PropertyKeyIsTooLong)762	}763}764765pub trait TrySetProperty: Sized {766	type Value;767768	fn try_scoped_set(769		&mut self,770		scope: PropertyScope,771		key: PropertyKey,772		value: Self::Value,773	) -> Result<(), PropertiesError>;774775	fn try_scoped_set_from_iter<I, KV>(776		&mut self,777		scope: PropertyScope,778		iter: I,779	) -> Result<(), PropertiesError>780	where781		I: Iterator<Item = KV>,782		KV: Into<(PropertyKey, Self::Value)>,783	{784		for kv in iter {785			let (key, value) = kv.into();786			self.try_scoped_set(scope, key, value)?;787		}788789		Ok(())790	}791792	fn try_set(&mut self, key: PropertyKey, value: Self::Value) -> Result<(), PropertiesError> {793		self.try_scoped_set(PropertyScope::None, key, value)794	}795796	fn try_set_from_iter<I, KV>(&mut self, iter: I) -> Result<(), PropertiesError>797	where798		I: Iterator<Item = KV>,799		KV: Into<(PropertyKey, Self::Value)>,800	{801		self.try_scoped_set_from_iter(PropertyScope::None, iter)802	}803}804805#[derive(Encode, Decode, TypeInfo, Derivative, Clone, PartialEq, MaxEncodedLen)]806#[derivative(Default(bound = ""))]807pub struct PropertiesMap<Value>(808	BoundedBTreeMap<PropertyKey, Value, ConstU32<MAX_PROPERTIES_PER_ITEM>>,809);810811impl<Value> PropertiesMap<Value> {812	pub fn new() -> Self {813		Self(BoundedBTreeMap::new())814	}815816	pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<Value>, PropertiesError> {817		Self::check_property_key(key)?;818819		Ok(self.0.remove(key))820	}821822	pub fn get(&self, key: &PropertyKey) -> Option<&Value> {823		self.0.get(key)824	}825826	pub fn contains_key(&self, key: &PropertyKey) -> bool {827		self.0.contains_key(key)828	}829830	fn check_property_key(key: &PropertyKey) -> Result<(), PropertiesError> {831		if key.is_empty() {832			return Err(PropertiesError::EmptyPropertyKey);833		}834835		for byte in key.as_slice().iter() {836			let byte = *byte;837838			if !byte.is_ascii_alphanumeric() && byte != b'_' && byte != b'-' && byte != b'.' {839				return Err(PropertiesError::InvalidCharacterInPropertyKey);840			}841		}842843		Ok(())844	}845}846847impl<Value> IntoIterator for PropertiesMap<Value> {848	type Item = (PropertyKey, Value);849	type IntoIter = <850		BoundedBTreeMap<851			PropertyKey,852			Value,853			ConstU32<MAX_PROPERTIES_PER_ITEM>854		> as IntoIterator855	>::IntoIter;856857	fn into_iter(self) -> Self::IntoIter {858		self.0.into_iter()859	}860}861862impl<Value> TrySetProperty for PropertiesMap<Value> {863	type Value = Value;864865	fn try_scoped_set(866		&mut self,867		scope: PropertyScope,868		key: PropertyKey,869		value: Self::Value,870	) -> Result<(), PropertiesError> {871		Self::check_property_key(&key)?;872873		let key = scope.apply(key)?;874		self.0875			.try_insert(key, value)876			.map_err(|_| PropertiesError::PropertyLimitReached)?;877878		Ok(())879	}880}881882pub type PropertiesPermissionMap = PropertiesMap<PropertyPermission>;883884#[derive(Encode, Decode, TypeInfo, Clone, PartialEq, MaxEncodedLen)]885pub struct Properties {886	map: PropertiesMap<PropertyValue>,887	consumed_space: u32,888	space_limit: u32,889}890891impl Properties {892	pub fn new(space_limit: u32) -> Self {893		Self {894			map: PropertiesMap::new(),895			consumed_space: 0,896			space_limit,897		}898	}899900	pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<PropertyValue>, PropertiesError> {901		let value = self.map.remove(key)?;902903		if let Some(ref value) = value {904			let value_len = value.len() as u32;905			self.consumed_space -= value_len;906		}907908		Ok(value)909	}910911	pub fn get(&self, key: &PropertyKey) -> Option<&PropertyValue> {912		self.map.get(key)913	}914}915916impl IntoIterator for Properties {917	type Item = (PropertyKey, PropertyValue);918	type IntoIter = <PropertiesMap<PropertyValue> as IntoIterator>::IntoIter;919920	fn into_iter(self) -> Self::IntoIter {921		self.map.into_iter()922	}923}924925impl TrySetProperty for Properties {926	type Value = PropertyValue;927928	fn try_scoped_set(929		&mut self,930		scope: PropertyScope,931		key: PropertyKey,932		value: Self::Value,933	) -> Result<(), PropertiesError> {934		let value_len = value.len();935936		if self.consumed_space as usize + value_len > self.space_limit as usize937			&& !cfg!(feature = "runtime-benchmarks")938		{939			return Err(PropertiesError::NoSpaceForProperty);940		}941942		self.map.try_scoped_set(scope, key, value)?;943944		self.consumed_space += value_len as u32;945946		Ok(())947	}948}949950pub struct CollectionProperties;951952impl Get<Properties> for CollectionProperties {953	fn get() -> Properties {954		Properties::new(MAX_COLLECTION_PROPERTIES_SIZE)955	}956}957958pub struct TokenProperties;959960impl Get<Properties> for TokenProperties {961	fn get() -> Properties {962		Properties::new(MAX_TOKEN_PROPERTIES_SIZE)963	}964}965966// RMRK967// todo document?968parameter_types! {969	#[derive(PartialEq, TypeInfo)]970	pub const RmrkStringLimit: u32 = 128;971	#[derive(PartialEq)]972	pub const RmrkCollectionSymbolLimit: u32 = MAX_TOKEN_PREFIX_LENGTH;973	#[derive(PartialEq)]974	pub const RmrkResourceSymbolLimit: u32 = 10;975	#[derive(PartialEq)]976	pub const RmrkBaseSymbolLimit: u32 = MAX_TOKEN_PREFIX_LENGTH;977	#[derive(PartialEq)]978	pub const RmrkKeyLimit: u32 = 32;979	#[derive(PartialEq)]980	pub const RmrkValueLimit: u32 = 256;981	#[derive(PartialEq)]982	pub const RmrkMaxCollectionsEquippablePerPart: u32 = 100;983	#[derive(PartialEq)]984	pub const MaxPropertiesPerTheme: u32 = 5;985	#[derive(PartialEq)]986	pub const RmrkPartsLimit: u32 = 25;987	#[derive(PartialEq)]988	pub const RmrkMaxPriorities: u32 = 25;989	#[derive(PartialEq)]990	pub const MaxResourcesOnMint: u32 = 100;991}992993impl From<RmrkCollectionId> for CollectionId {994	fn from(id: RmrkCollectionId) -> Self {995		Self(id)996	}997}998999impl From<RmrkNftId> for TokenId {1000	fn from(id: RmrkNftId) -> Self {1001		Self(id)1002	}1003}10041005pub type RmrkCollectionInfo<AccountId> =1006	CollectionInfo<RmrkString, RmrkCollectionSymbol, AccountId>;1007pub type RmrkInstanceInfo<AccountId> = NftInfo<AccountId, Permill, RmrkString>;1008pub type RmrkResourceInfo = ResourceInfo<RmrkString, RmrkBoundedParts>;1009pub type RmrkPropertyInfo = PropertyInfo<RmrkKeyString, RmrkValueString>;1010pub type RmrkBaseInfo<AccountId> = BaseInfo<AccountId, RmrkString>;1011pub type BoundedEquippableCollectionIds =1012	BoundedVec<RmrkCollectionId, RmrkMaxCollectionsEquippablePerPart>;1013pub type RmrkPartType = PartType<RmrkString, BoundedEquippableCollectionIds>;1014pub type RmrkEquippableList = EquippableList<BoundedEquippableCollectionIds>;1015pub type RmrkThemeProperty = ThemeProperty<RmrkString>;1016pub type RmrkTheme = Theme<RmrkString, Vec<RmrkThemeProperty>>;1017pub type RmrkBoundedTheme = Theme<RmrkString, BoundedVec<RmrkThemeProperty, MaxPropertiesPerTheme>>;1018pub type RmrkResourceTypes = ResourceTypes<RmrkString, RmrkBoundedParts>;10191020pub type RmrkBasicResource = BasicResource<RmrkString>;1021pub type RmrkComposableResource = ComposableResource<RmrkString, RmrkBoundedParts>;1022pub type RmrkSlotResource = SlotResource<RmrkString>;10231024pub type RmrkString = BoundedVec<u8, RmrkStringLimit>;1025pub type RmrkCollectionSymbol = BoundedVec<u8, RmrkCollectionSymbolLimit>;1026pub type RmrkBaseSymbol = BoundedVec<u8, RmrkBaseSymbolLimit>;1027pub type RmrkKeyString = BoundedVec<u8, RmrkKeyLimit>;1028pub type RmrkValueString = BoundedVec<u8, RmrkValueLimit>;1029pub type RmrkBoundedResource = BoundedVec<u8, RmrkResourceSymbolLimit>;1030pub type RmrkBoundedParts = BoundedVec<RmrkPartId, RmrkPartsLimit>; // todo make sure it is needed10311032pub type RmrkRpcString = Vec<u8>;1033pub type RmrkThemeName = RmrkRpcString;1034pub type RmrkPropertyKey = RmrkRpcString;