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

difftreelog

source

primitives/data-structs/src/lib.rs28.5 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	// decimal points201	Fungible(DecimalPoints),202	ReFungible,203}204205impl CollectionMode {206	pub fn id(&self) -> u8 {207		match self {208			CollectionMode::NFT => 1,209			CollectionMode::Fungible(_) => 2,210			CollectionMode::ReFungible => 3,211		}212	}213}214215pub trait SponsoringResolve<AccountId, Call> {216	fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>;217}218219#[derive(Encode, Decode, Eq, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]220#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]221pub enum AccessMode {222	Normal,223	AllowList,224}225impl Default for AccessMode {226	fn default() -> Self {227		Self::Normal228	}229}230231#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]232#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]233pub enum SchemaVersion {234	ImageURL,235	Unique,236}237impl Default for SchemaVersion {238	fn default() -> Self {239		Self::ImageURL240	}241}242243#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]244#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]245pub struct Ownership<AccountId> {246	pub owner: AccountId,247	pub fraction: u128,248}249250#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]251#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]252pub enum SponsorshipState<AccountId> {253	/// The fees are applied to the transaction sender254	Disabled,255	Unconfirmed(AccountId),256	/// Transactions are sponsored by specified account257	Confirmed(AccountId),258}259260impl<AccountId> SponsorshipState<AccountId> {261	pub fn sponsor(&self) -> Option<&AccountId> {262		match self {263			Self::Confirmed(sponsor) => Some(sponsor),264			_ => None,265		}266	}267268	pub fn pending_sponsor(&self) -> Option<&AccountId> {269		match self {270			Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),271			_ => None,272		}273	}274275	pub fn confirmed(&self) -> bool {276		matches!(self, Self::Confirmed(_))277	}278}279280impl<T> Default for SponsorshipState<T> {281	fn default() -> Self {282		Self::Disabled283	}284}285286/// Used in storage287#[struct_versioning::versioned(version = 2, upper)]288#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen)]289pub struct Collection<AccountId> {290	pub owner: AccountId,291	pub mode: CollectionMode,292	#[version(..2)]293	pub access: AccessMode,294	pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,295	pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,296	pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,297298	#[version(..2)]299	pub mint_mode: bool,300301	#[version(..2)]302	pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,303304	#[version(..2)]305	pub schema_version: SchemaVersion,306	pub sponsorship: SponsorshipState<AccountId>,307308	pub limits: CollectionLimits,309310	#[version(2.., upper(Default::default()))]311	pub permissions: CollectionPermissions,312313	/// Marks that this collection is not "unique", and managed from external.314	#[version(2.., upper(false))]315	pub external_collection: bool,316317	#[version(..2)]318	pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,319320	#[version(..2)]321	pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,322323	#[version(..2)]324	pub meta_update_permission: MetaUpdatePermission,325}326327/// Used in RPC calls328#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]329#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]330pub struct RpcCollection<AccountId> {331	pub owner: AccountId,332	pub mode: CollectionMode,333	pub name: Vec<u16>,334	pub description: Vec<u16>,335	pub token_prefix: Vec<u8>,336	pub sponsorship: SponsorshipState<AccountId>,337	pub limits: CollectionLimits,338	pub permissions: CollectionPermissions,339	pub token_property_permissions: Vec<PropertyKeyPermission>,340	pub properties: Vec<Property>,341	pub read_only: bool,342}343344#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Derivative, MaxEncodedLen)]345#[derivative(Debug, Default(bound = ""))]346pub struct CreateCollectionData<AccountId> {347	#[derivative(Default(value = "CollectionMode::NFT"))]348	pub mode: CollectionMode,349	pub access: Option<AccessMode>,350	pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,351	pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,352	pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,353	pub pending_sponsor: Option<AccountId>,354	pub limits: Option<CollectionLimits>,355	pub permissions: Option<CollectionPermissions>,356	pub token_property_permissions: CollectionPropertiesPermissionsVec,357	pub properties: CollectionPropertiesVec,358}359360pub type CollectionPropertiesPermissionsVec =361	BoundedVec<PropertyKeyPermission, ConstU32<MAX_PROPERTIES_PER_ITEM>>;362363pub type CollectionPropertiesVec = BoundedVec<Property, ConstU32<MAX_PROPERTIES_PER_ITEM>>;364365/// All fields are wrapped in `Option`s, where None means chain default366// When adding/removing fields from this struct - don't forget to also update clamp_limits367#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]368#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]369pub struct CollectionLimits {370	pub account_token_ownership_limit: Option<u32>,371	pub sponsored_data_size: Option<u32>,372373	/// FIXME should we delete this or repurpose it?374	/// None - setVariableMetadata is not sponsored375	/// Some(v) - setVariableMetadata is sponsored376	///           if there is v block between txs377	pub sponsored_data_rate_limit: Option<SponsoringRateLimit>,378	pub token_limit: Option<u32>,379380	// Timeouts for item types in passed blocks381	pub sponsor_transfer_timeout: Option<u32>,382	pub sponsor_approve_timeout: Option<u32>,383	pub owner_can_transfer: Option<bool>,384	pub owner_can_destroy: Option<bool>,385	pub transfers_enabled: Option<bool>,386}387388impl CollectionLimits {389	pub fn account_token_ownership_limit(&self) -> u32 {390		self.account_token_ownership_limit391			.unwrap_or(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)392			.min(MAX_TOKEN_OWNERSHIP)393	}394	pub fn sponsored_data_size(&self) -> u32 {395		self.sponsored_data_size396			.unwrap_or(CUSTOM_DATA_LIMIT)397			.min(CUSTOM_DATA_LIMIT)398	}399	pub fn token_limit(&self) -> u32 {400		self.token_limit401			.unwrap_or(COLLECTION_TOKEN_LIMIT)402			.min(COLLECTION_TOKEN_LIMIT)403	}404	pub fn sponsor_transfer_timeout(&self, default: u32) -> u32 {405		self.sponsor_transfer_timeout406			.unwrap_or(default)407			.min(MAX_SPONSOR_TIMEOUT)408	}409	pub fn sponsor_approve_timeout(&self) -> u32 {410		self.sponsor_approve_timeout411			.unwrap_or(SPONSOR_APPROVE_TIMEOUT)412			.min(MAX_SPONSOR_TIMEOUT)413	}414	pub fn owner_can_transfer(&self) -> bool {415		self.owner_can_transfer.unwrap_or(false)416	}417	pub fn owner_can_transfer_instaled(&self) -> bool {418		self.owner_can_transfer.is_some()419	}420	pub fn owner_can_destroy(&self) -> bool {421		self.owner_can_destroy.unwrap_or(true)422	}423	pub fn transfers_enabled(&self) -> bool {424		self.transfers_enabled.unwrap_or(true)425	}426	pub fn sponsored_data_rate_limit(&self) -> Option<u32> {427		match self428			.sponsored_data_rate_limit429			.unwrap_or(SponsoringRateLimit::SponsoringDisabled)430		{431			SponsoringRateLimit::SponsoringDisabled => None,432			SponsoringRateLimit::Blocks(v) => Some(v.min(MAX_SPONSOR_TIMEOUT)),433		}434	}435}436437// When adding/removing fields from this struct - don't forget to also update clamp_limits438#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]439#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]440pub struct CollectionPermissions {441	pub access: Option<AccessMode>,442	pub mint_mode: Option<bool>,443	pub nesting: Option<NestingPermissions>,444}445446impl CollectionPermissions {447	pub fn access(&self) -> AccessMode {448		self.access.unwrap_or(AccessMode::Normal)449	}450	pub fn mint_mode(&self) -> bool {451		self.mint_mode.unwrap_or(false)452	}453	pub fn nesting(&self) -> &NestingPermissions {454		static DEFAULT: NestingPermissions = NestingPermissions {455			token_owner: false,456			collection_admin: false,457			restricted: None,458			#[cfg(feature = "runtime-benchmarks")]459			permissive: false,460		};461		self.nesting.as_ref().unwrap_or(&DEFAULT)462	}463}464465type OwnerRestrictedSetInner = BoundedBTreeSet<CollectionId, ConstU32<16>>;466467#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative)]468#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]469#[derivative(Debug)]470pub struct OwnerRestrictedSet(471	#[cfg_attr(feature = "serde1", serde(with = "bounded::set_serde"))]472	#[derivative(Debug(format_with = "bounded::set_debug"))]473	pub OwnerRestrictedSetInner,474);475impl OwnerRestrictedSet {476	pub fn new() -> Self {477		Self(Default::default())478	}479}480impl core::ops::Deref for OwnerRestrictedSet {481	type Target = OwnerRestrictedSetInner;482	fn deref(&self) -> &Self::Target {483		&self.0484	}485}486impl core::ops::DerefMut for OwnerRestrictedSet {487	fn deref_mut(&mut self) -> &mut Self::Target {488		&mut self.0489	}490}491492#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative)]493#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]494#[derivative(Debug)]495pub struct NestingPermissions {496	/// Owner of token can nest tokens under it497	pub token_owner: bool,498	/// Admin of token collection can nest tokens under token499	pub collection_admin: bool,500	/// If set - only tokens from specified collections can be nested501	pub restricted: Option<OwnerRestrictedSet>,502503	#[cfg(feature = "runtime-benchmarks")]504	/// Anyone can nest tokens, mutually exclusive with `token_owner`, `admin`505	pub permissive: bool,506}507508#[derive(Encode, Decode, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]509#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]510pub enum SponsoringRateLimit {511	SponsoringDisabled,512	Blocks(u32),513}514515#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]516#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]517#[derivative(Debug)]518pub struct CreateNftData {519	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]520	#[derivative(Debug(format_with = "bounded::vec_debug"))]521	pub properties: CollectionPropertiesVec,522}523524#[derive(Encode, Decode, MaxEncodedLen, Default, Debug, Clone, PartialEq, TypeInfo)]525#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]526pub struct CreateFungibleData {527	pub value: u128,528}529530#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]531#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]532#[derivative(Debug)]533pub struct CreateReFungibleData {534	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]535	#[derivative(Debug(format_with = "bounded::vec_debug"))]536	pub const_data: BoundedVec<u8, CustomDataLimit>,537538	pub pieces: u128,539540	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]541	#[derivative(Debug(format_with = "bounded::vec_debug"))]542	pub properties: CollectionPropertiesVec,543}544545#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]546#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]547pub enum MetaUpdatePermission {548	ItemOwner,549	Admin,550	None,551}552553#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]554#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]555pub enum CreateItemData {556	NFT(CreateNftData),557	Fungible(CreateFungibleData),558	ReFungible(CreateReFungibleData),559}560561#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]562#[derivative(Debug)]563pub struct CreateNftExData<CrossAccountId> {564	#[derivative(Debug(format_with = "bounded::vec_debug"))]565	pub properties: CollectionPropertiesVec,566	pub owner: CrossAccountId,567}568569#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]570#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]571pub struct CreateRefungibleExData<CrossAccountId> {572	#[derivative(Debug(format_with = "bounded::vec_debug"))]573	pub const_data: BoundedVec<u8, CustomDataLimit>,574	#[derivative(Debug(format_with = "bounded::map_debug"))]575	pub users: BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,576	#[derivative(Debug(format_with = "bounded::vec_debug"))]577	pub properties: CollectionPropertiesVec,578}579580#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]581#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]582pub enum CreateItemExData<CrossAccountId> {583	NFT(584		#[derivative(Debug(format_with = "bounded::vec_debug"))]585		BoundedVec<CreateNftExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,586	),587	Fungible(588		#[derivative(Debug(format_with = "bounded::map_debug"))]589		BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,590	),591	/// Many tokens, each may have only one owner592	RefungibleMultipleItems(593		#[derivative(Debug(format_with = "bounded::vec_debug"))]594		BoundedVec<CreateRefungibleExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,595	),596	/// Single token, which may have many owners597	RefungibleMultipleOwners(CreateRefungibleExData<CrossAccountId>),598}599600impl CreateItemData {601	pub fn data_size(&self) -> usize {602		match self {603			CreateItemData::ReFungible(data) => data.const_data.len(),604			_ => 0,605		}606	}607}608609impl From<CreateNftData> for CreateItemData {610	fn from(item: CreateNftData) -> Self {611		CreateItemData::NFT(item)612	}613}614615impl From<CreateReFungibleData> for CreateItemData {616	fn from(item: CreateReFungibleData) -> Self {617		CreateItemData::ReFungible(item)618	}619}620621impl From<CreateFungibleData> for CreateItemData {622	fn from(item: CreateFungibleData) -> Self {623		CreateItemData::Fungible(item)624	}625}626627#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]628#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]629// todo possibly rename to be used generally as an address pair630pub struct TokenChild {631	pub token: TokenId,632	pub collection: CollectionId,633}634635#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]636#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]637pub struct CollectionStats {638	pub created: u32,639	pub destroyed: u32,640	pub alive: u32,641}642643#[derive(Encode, Decode, Clone, Debug)]644#[cfg_attr(feature = "std", derive(PartialEq))]645pub struct PhantomType<T>(core::marker::PhantomData<T>);646647impl<T: TypeInfo + 'static> TypeInfo for PhantomType<T> {648	type Identity = PhantomType<T>;649650	fn type_info() -> scale_info::Type {651		use scale_info::{652			Type, Path,653			build::{FieldsBuilder, UnnamedFields},654			type_params,655		};656		Type::builder()657			.path(Path::new("up_data_structs", "PhantomType"))658			.type_params(type_params!(T))659			.composite(<FieldsBuilder<UnnamedFields>>::default().field(|b| b.ty::<[T; 0]>()))660	}661}662impl<T> MaxEncodedLen for PhantomType<T> {663	fn max_encoded_len() -> usize {664		0665	}666}667668pub type BoundedBytes<S> = BoundedVec<u8, S>;669670pub type AuxPropertyValue = BoundedBytes<ConstU32<MAX_AUX_PROPERTY_VALUE_LENGTH>>;671672pub type PropertyKey = BoundedBytes<ConstU32<MAX_PROPERTY_KEY_LENGTH>>;673pub type PropertyValue = BoundedBytes<ConstU32<MAX_PROPERTY_VALUE_LENGTH>>;674675#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]676#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]677pub struct PropertyPermission {678	pub mutable: bool,679	pub collection_admin: bool,680	pub token_owner: bool,681}682683impl PropertyPermission {684	pub fn none() -> Self {685		Self {686			mutable: true,687			collection_admin: false,688			token_owner: false,689		}690	}691}692693#[derive(Encode, Decode, Debug, TypeInfo, Clone, PartialEq, MaxEncodedLen)]694#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]695pub struct Property {696	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]697	pub key: PropertyKey,698699	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]700	pub value: PropertyValue,701}702703impl Into<(PropertyKey, PropertyValue)> for Property {704	fn into(self) -> (PropertyKey, PropertyValue) {705		(self.key, self.value)706	}707}708709#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]710#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]711pub struct PropertyKeyPermission {712	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]713	pub key: PropertyKey,714715	pub permission: PropertyPermission,716}717718impl Into<(PropertyKey, PropertyPermission)> for PropertyKeyPermission {719	fn into(self) -> (PropertyKey, PropertyPermission) {720		(self.key, self.permission)721	}722}723724#[derive(Debug)]725pub enum PropertiesError {726	NoSpaceForProperty,727	PropertyLimitReached,728	InvalidCharacterInPropertyKey,729	PropertyKeyIsTooLong,730	EmptyPropertyKey,731}732733#[derive(Encode, Decode, MaxEncodedLen, TypeInfo, PartialEq, Clone, Copy)]734pub enum PropertyScope {735	None,736	Rmrk,737}738739impl PropertyScope {740	pub fn apply(self, key: PropertyKey) -> Result<PropertyKey, PropertiesError> {741		let scope_str: &[u8] = match self {742			Self::None => return Ok(key),743			Self::Rmrk => b"rmrk",744		};745746		[scope_str, b":", key.as_slice()]747			.concat()748			.try_into()749			.map_err(|_| PropertiesError::PropertyKeyIsTooLong)750	}751}752753pub trait TrySetProperty: Sized {754	type Value;755756	fn try_scoped_set(757		&mut self,758		scope: PropertyScope,759		key: PropertyKey,760		value: Self::Value,761	) -> Result<(), PropertiesError>;762763	fn try_scoped_set_from_iter<I, KV>(764		&mut self,765		scope: PropertyScope,766		iter: I,767	) -> Result<(), PropertiesError>768	where769		I: Iterator<Item = KV>,770		KV: Into<(PropertyKey, Self::Value)>,771	{772		for kv in iter {773			let (key, value) = kv.into();774			self.try_scoped_set(scope, key, value)?;775		}776777		Ok(())778	}779780	fn try_set(&mut self, key: PropertyKey, value: Self::Value) -> Result<(), PropertiesError> {781		self.try_scoped_set(PropertyScope::None, key, value)782	}783784	fn try_set_from_iter<I, KV>(&mut self, iter: I) -> Result<(), PropertiesError>785	where786		I: Iterator<Item = KV>,787		KV: Into<(PropertyKey, Self::Value)>,788	{789		self.try_scoped_set_from_iter(PropertyScope::None, iter)790	}791}792793#[derive(Encode, Decode, TypeInfo, Derivative, Clone, PartialEq, MaxEncodedLen)]794#[derivative(Default(bound = ""))]795pub struct PropertiesMap<Value>(796	BoundedBTreeMap<PropertyKey, Value, ConstU32<MAX_PROPERTIES_PER_ITEM>>,797);798799impl<Value> PropertiesMap<Value> {800	pub fn new() -> Self {801		Self(BoundedBTreeMap::new())802	}803804	pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<Value>, PropertiesError> {805		Self::check_property_key(key)?;806807		Ok(self.0.remove(key))808	}809810	pub fn get(&self, key: &PropertyKey) -> Option<&Value> {811		self.0.get(key)812	}813814	pub fn contains_key(&self, key: &PropertyKey) -> bool {815		self.0.contains_key(key)816	}817818	fn check_property_key(key: &PropertyKey) -> Result<(), PropertiesError> {819		if key.is_empty() {820			return Err(PropertiesError::EmptyPropertyKey);821		}822823		for byte in key.as_slice().iter() {824			let byte = *byte;825826			if !byte.is_ascii_alphanumeric() && byte != b'_' && byte != b'-' && byte != b'.' {827				return Err(PropertiesError::InvalidCharacterInPropertyKey);828			}829		}830831		Ok(())832	}833}834835impl<Value> IntoIterator for PropertiesMap<Value> {836	type Item = (PropertyKey, Value);837	type IntoIter = <838		BoundedBTreeMap<839			PropertyKey,840			Value,841			ConstU32<MAX_PROPERTIES_PER_ITEM>842		> as IntoIterator843	>::IntoIter;844845	fn into_iter(self) -> Self::IntoIter {846		self.0.into_iter()847	}848}849850impl<Value> TrySetProperty for PropertiesMap<Value> {851	type Value = Value;852853	fn try_scoped_set(854		&mut self,855		scope: PropertyScope,856		key: PropertyKey,857		value: Self::Value,858	) -> Result<(), PropertiesError> {859		Self::check_property_key(&key)?;860861		let key = scope.apply(key)?;862		self.0863			.try_insert(key, value)864			.map_err(|_| PropertiesError::PropertyLimitReached)?;865866		Ok(())867	}868}869870pub type PropertiesPermissionMap = PropertiesMap<PropertyPermission>;871872#[derive(Encode, Decode, TypeInfo, Clone, PartialEq, MaxEncodedLen)]873pub struct Properties {874	map: PropertiesMap<PropertyValue>,875	consumed_space: u32,876	space_limit: u32,877}878879impl Properties {880	pub fn new(space_limit: u32) -> Self {881		Self {882			map: PropertiesMap::new(),883			consumed_space: 0,884			space_limit,885		}886	}887888	pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<PropertyValue>, PropertiesError> {889		let value = self.map.remove(key)?;890891		if let Some(ref value) = value {892			let value_len = value.len() as u32;893			self.consumed_space -= value_len;894		}895896		Ok(value)897	}898899	pub fn get(&self, key: &PropertyKey) -> Option<&PropertyValue> {900		self.map.get(key)901	}902}903904impl IntoIterator for Properties {905	type Item = (PropertyKey, PropertyValue);906	type IntoIter = <PropertiesMap<PropertyValue> as IntoIterator>::IntoIter;907908	fn into_iter(self) -> Self::IntoIter {909		self.map.into_iter()910	}911}912913impl TrySetProperty for Properties {914	type Value = PropertyValue;915916	fn try_scoped_set(917		&mut self,918		scope: PropertyScope,919		key: PropertyKey,920		value: Self::Value,921	) -> Result<(), PropertiesError> {922		let value_len = value.len();923924		if self.consumed_space as usize + value_len > self.space_limit as usize925			&& !cfg!(feature = "runtime-benchmarks")926		{927			return Err(PropertiesError::NoSpaceForProperty);928		}929930		self.map.try_scoped_set(scope, key, value)?;931932		self.consumed_space += value_len as u32;933934		Ok(())935	}936}937938pub struct CollectionProperties;939940impl Get<Properties> for CollectionProperties {941	fn get() -> Properties {942		Properties::new(MAX_COLLECTION_PROPERTIES_SIZE)943	}944}945946pub struct TokenProperties;947948impl Get<Properties> for TokenProperties {949	fn get() -> Properties {950		Properties::new(MAX_TOKEN_PROPERTIES_SIZE)951	}952}953954// RMRK955// todo document?956parameter_types! {957	#[derive(PartialEq, TypeInfo)]958	pub const RmrkStringLimit: u32 = 128;959	#[derive(PartialEq)]960	pub const RmrkCollectionSymbolLimit: u32 = MAX_TOKEN_PREFIX_LENGTH;961	#[derive(PartialEq)]962	pub const RmrkResourceSymbolLimit: u32 = 10;963	#[derive(PartialEq)]964	pub const RmrkBaseSymbolLimit: u32 = MAX_TOKEN_PREFIX_LENGTH;965	#[derive(PartialEq)]966	pub const RmrkKeyLimit: u32 = 32;967	#[derive(PartialEq)]968	pub const RmrkValueLimit: u32 = 256;969	#[derive(PartialEq)]970	pub const RmrkMaxCollectionsEquippablePerPart: u32 = 100;971	#[derive(PartialEq)]972	pub const MaxPropertiesPerTheme: u32 = 5;973	#[derive(PartialEq)]974	pub const RmrkPartsLimit: u32 = 25;975	#[derive(PartialEq)]976	pub const RmrkMaxPriorities: u32 = 25;977	#[derive(PartialEq)]978	pub const MaxResourcesOnMint: u32 = 100;979}980981impl From<RmrkCollectionId> for CollectionId {982	fn from(id: RmrkCollectionId) -> Self {983		Self(id)984	}985}986987impl From<RmrkNftId> for TokenId {988	fn from(id: RmrkNftId) -> Self {989		Self(id)990	}991}992993pub type RmrkCollectionInfo<AccountId> =994	CollectionInfo<RmrkString, RmrkCollectionSymbol, AccountId>;995pub type RmrkInstanceInfo<AccountId> = NftInfo<AccountId, Permill, RmrkString>;996pub type RmrkResourceInfo = ResourceInfo<RmrkString, RmrkBoundedParts>;997pub type RmrkPropertyInfo = PropertyInfo<RmrkKeyString, RmrkValueString>;998pub type RmrkBaseInfo<AccountId> = BaseInfo<AccountId, RmrkString>;999pub type BoundedEquippableCollectionIds =1000	BoundedVec<RmrkCollectionId, RmrkMaxCollectionsEquippablePerPart>;1001pub type RmrkPartType = PartType<RmrkString, BoundedEquippableCollectionIds>;1002pub type RmrkEquippableList = EquippableList<BoundedEquippableCollectionIds>;1003pub type RmrkThemeProperty = ThemeProperty<RmrkString>;1004pub type RmrkTheme = Theme<RmrkString, Vec<RmrkThemeProperty>>;1005pub type RmrkBoundedTheme = Theme<RmrkString, BoundedVec<RmrkThemeProperty, MaxPropertiesPerTheme>>;1006pub type RmrkResourceTypes = ResourceTypes<RmrkString, RmrkBoundedParts>;10071008pub type RmrkBasicResource = BasicResource<RmrkString>;1009pub type RmrkComposableResource = ComposableResource<RmrkString, RmrkBoundedParts>;1010pub type RmrkSlotResource = SlotResource<RmrkString>;10111012pub type RmrkString = BoundedVec<u8, RmrkStringLimit>;1013pub type RmrkCollectionSymbol = BoundedVec<u8, RmrkCollectionSymbolLimit>;1014pub type RmrkBaseSymbol = BoundedVec<u8, RmrkBaseSymbolLimit>;1015pub type RmrkKeyString = BoundedVec<u8, RmrkKeyLimit>;1016pub type RmrkValueString = BoundedVec<u8, RmrkValueLimit>;1017pub type RmrkBoundedResource = BoundedVec<u8, RmrkResourceSymbolLimit>;1018pub type RmrkBoundedParts = BoundedVec<RmrkPartId, RmrkPartsLimit>; // todo make sure it is needed10191020pub type RmrkRpcString = Vec<u8>;1021pub type RmrkThemeName = RmrkRpcString;1022pub type RmrkPropertyKey = RmrkRpcString;