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

difftreelog

doc: clarifications to primitives and rpcs

Farhad Hakimov2022-07-15parent: #6fe077c.patch.diff
in: master

3 files changed

modifiedclient/rpc/src/lib.rsdiffbeforeafterboth
--- a/client/rpc/src/lib.rs
+++ b/client/rpc/src/lib.rs
@@ -42,7 +42,7 @@
 #[rpc(server)]
 #[async_trait]
 pub trait UniqueApi<BlockHash, CrossAccountId, AccountId> {
-	/// Get tokens owned by account
+	/// Get tokens owned by account.
 	#[method(name = "unique_accountTokens")]
 	fn account_tokens(
 		&self,
@@ -51,7 +51,7 @@
 		at: Option<BlockHash>,
 	) -> Result<Vec<TokenId>>;
 
-	/// Get tokens contained in collection
+	/// Get tokens contained within a collection.
 	#[method(name = "unique_collectionTokens")]
 	fn collection_tokens(
 		&self,
@@ -59,7 +59,7 @@
 		at: Option<BlockHash>,
 	) -> Result<Vec<TokenId>>;
 
-	/// Check if token exists
+	/// Check if the token exists.
 	#[method(name = "unique_tokenExists")]
 	fn token_exists(
 		&self,
@@ -68,7 +68,7 @@
 		at: Option<BlockHash>,
 	) -> Result<bool>;
 
-	/// Get token owner
+	/// Get the token owner.
 	#[method(name = "unique_tokenOwner")]
 	fn token_owner(
 		&self,
@@ -77,7 +77,7 @@
 		at: Option<BlockHash>,
 	) -> Result<Option<CrossAccountId>>;
 
-	/// Get token owner, in case of nested token - find the parent recursively
+	/// Get the topmost token owner in the hierarchy of a possibly nested token.
 	#[method(name = "unique_topmostTokenOwner")]
 	fn topmost_token_owner(
 		&self,
@@ -86,7 +86,7 @@
 		at: Option<BlockHash>,
 	) -> Result<Option<CrossAccountId>>;
 
-	/// Get tokens nested directly into the token
+	/// Get tokens nested directly into the token.
 	#[method(name = "unique_tokenChildren")]
 	fn token_children(
 		&self,
@@ -95,7 +95,7 @@
 		at: Option<BlockHash>,
 	) -> Result<Vec<TokenChild>>;
 
-	/// Get collection properties
+	/// Get collection properties, optionally limited to the provided keys.
 	#[method(name = "unique_collectionProperties")]
 	fn collection_properties(
 		&self,
@@ -104,7 +104,7 @@
 		at: Option<BlockHash>,
 	) -> Result<Vec<Property>>;
 
-	/// Get token properties
+	/// Get token properties, optionally limited to the provided keys.
 	#[method(name = "unique_tokenProperties")]
 	fn token_properties(
 		&self,
@@ -114,7 +114,7 @@
 		at: Option<BlockHash>,
 	) -> Result<Vec<Property>>;
 
-	/// Get property permissions
+	/// Get property permissions, optionally limited to the provided keys.
 	#[method(name = "unique_propertyPermissions")]
 	fn property_permissions(
 		&self,
@@ -123,7 +123,7 @@
 		at: Option<BlockHash>,
 	) -> Result<Vec<PropertyKeyPermission>>;
 
-	/// Get token data
+	/// Get token data, including properties, optionally limited to the provided keys, and total pieces for an RFT.
 	#[method(name = "unique_tokenData")]
 	fn token_data(
 		&self,
@@ -133,11 +133,11 @@
 		at: Option<BlockHash>,
 	) -> Result<TokenData<CrossAccountId>>;
 
-	/// Get amount of unique collection tokens
+	/// Get the amount of distinctive tokens present in a collection.
 	#[method(name = "unique_totalSupply")]
 	fn total_supply(&self, collection: CollectionId, at: Option<BlockHash>) -> Result<u32>;
 
-	/// Get owned amount of any user tokens
+	/// Get the amount of any user tokens owned by an account.
 	#[method(name = "unique_accountBalance")]
 	fn account_balance(
 		&self,
@@ -146,7 +146,7 @@
 		at: Option<BlockHash>,
 	) -> Result<u32>;
 
-	/// Get owned amount of specific account token
+	/// Get the amount of a specific token owned by an account.
 	#[method(name = "unique_balance")]
 	fn balance(
 		&self,
@@ -156,7 +156,7 @@
 		at: Option<BlockHash>,
 	) -> Result<String>;
 
-	/// Get allowed amount
+	/// Get the amount of currently possible sponsored transactions on a token for the fee to be taken off a sponsor.
 	#[method(name = "unique_allowance")]
 	fn allowance(
 		&self,
@@ -167,7 +167,7 @@
 		at: Option<BlockHash>,
 	) -> Result<String>;
 
-	/// Get admin list
+	/// Get the list of admin accounts of a collection.
 	#[method(name = "unique_adminlist")]
 	fn adminlist(
 		&self,
@@ -175,7 +175,7 @@
 		at: Option<BlockHash>,
 	) -> Result<Vec<CrossAccountId>>;
 
-	/// Get allowlist
+	/// Get the list of accounts allowed to operate within a collection.
 	#[method(name = "unique_allowlist")]
 	fn allowlist(
 		&self,
@@ -183,7 +183,7 @@
 		at: Option<BlockHash>,
 	) -> Result<Vec<CrossAccountId>>;
 
-	/// Check if user is allowed to use collection
+	/// Check if a user is allowed to operate within a collection.
 	#[method(name = "unique_allowed")]
 	fn allowed(
 		&self,
@@ -192,11 +192,11 @@
 		at: Option<BlockHash>,
 	) -> Result<bool>;
 
-	/// Get last token ID created in a collection
+	/// Get the last token ID created in a collection.
 	#[method(name = "unique_lastTokenId")]
 	fn last_token_id(&self, collection: CollectionId, at: Option<BlockHash>) -> Result<TokenId>;
 
-	/// Get collection by specified ID
+	/// Get collection info by the specified ID.
 	#[method(name = "unique_collectionById")]
 	fn collection_by_id(
 		&self,
@@ -204,11 +204,11 @@
 		at: Option<BlockHash>,
 	) -> Result<Option<RpcCollection<AccountId>>>;
 
-	/// Get collection stats
+	/// Get chain stats about collections.
 	#[method(name = "unique_collectionStats")]
 	fn collection_stats(&self, at: Option<BlockHash>) -> Result<CollectionStats>;
 
-	/// Get number of blocks when sponsored transaction is available
+	/// Get the number of blocks until sponsoring a transaction is available.
 	#[method(name = "unique_nextSponsored")]
 	fn next_sponsored(
 		&self,
@@ -218,7 +218,7 @@
 		at: Option<BlockHash>,
 	) -> Result<Option<u64>>;
 
-	/// Get effective collection limits
+	/// Get effective collection limits. If not explicitly set, get the chain defaults.
 	#[method(name = "unique_effectiveCollectionLimits")]
 	fn effective_collection_limits(
 		&self,
@@ -226,7 +226,7 @@
 		at: Option<BlockHash>,
 	) -> Result<Option<CollectionLimits>>;
 
-	/// Get total pieces of token
+	/// Get the total amount of pieces of an RFT.
 	#[method(name = "unique_totalPieces")]
 	fn total_pieces(
 		&self,
@@ -253,20 +253,20 @@
 		Theme,
 	>
 	{
+		/// Get the latest created collection ID.
 		#[method(name = "rmrk_lastCollectionIdx")]
-		/// Get the latest created collection id
 		fn last_collection_idx(&self, at: Option<BlockHash>) -> Result<RmrkCollectionId>;
 
+		/// Get collection info by ID.
 		#[method(name = "rmrk_collectionById")]
-		/// Get collection by id
 		fn collection_by_id(
 			&self,
 			id: RmrkCollectionId,
 			at: Option<BlockHash>,
 		) -> Result<Option<CollectionInfo>>;
 
+		/// Get NFT info by collection and NFT IDs.
 		#[method(name = "rmrk_nftById")]
-		/// Get NFT by collection id and NFT id
 		fn nft_by_id(
 			&self,
 			collection_id: RmrkCollectionId,
@@ -274,8 +274,8 @@
 			at: Option<BlockHash>,
 		) -> Result<Option<NftInfo>>;
 
+		/// Get tokens owned by an account in a collection.
 		#[method(name = "rmrk_accountTokens")]
-		/// Get tokens owned by an account in a collection
 		fn account_tokens(
 			&self,
 			account_id: AccountId,
@@ -283,8 +283,8 @@
 			at: Option<BlockHash>,
 		) -> Result<Vec<RmrkNftId>>;
 
+		/// Get tokens nested in an NFT - its direct children (not the children's children).
 		#[method(name = "rmrk_nftChildren")]
-		/// Get NFT children
 		fn nft_children(
 			&self,
 			collection_id: RmrkCollectionId,
@@ -292,8 +292,8 @@
 			at: Option<BlockHash>,
 		) -> Result<Vec<RmrkNftChild>>;
 
+		/// Get collection properties, created by the user - not the proxy-specific properties.
 		#[method(name = "rmrk_collectionProperties")]
-		/// Get collection properties
 		fn collection_properties(
 			&self,
 			collection_id: RmrkCollectionId,
@@ -301,8 +301,8 @@
 			at: Option<BlockHash>,
 		) -> Result<Vec<PropertyInfo>>;
 
+		/// Get NFT properties, created by the user - not the proxy-specific properties.
 		#[method(name = "rmrk_nftProperties")]
-		/// Get NFT properties
 		fn nft_properties(
 			&self,
 			collection_id: RmrkCollectionId,
@@ -311,8 +311,8 @@
 			at: Option<BlockHash>,
 		) -> Result<Vec<PropertyInfo>>;
 
+		/// Get data of resources of an NFT.
 		#[method(name = "rmrk_nftResources")]
-		/// Get NFT resources
 		fn nft_resources(
 			&self,
 			collection_id: RmrkCollectionId,
@@ -320,8 +320,8 @@
 			at: Option<BlockHash>,
 		) -> Result<Vec<ResourceInfo>>;
 
+		/// Get the priority of a resource in an NFT.
 		#[method(name = "rmrk_nftResourcePriority")]
-		/// Get NFT resource priority
 		fn nft_resource_priority(
 			&self,
 			collection_id: RmrkCollectionId,
@@ -330,24 +330,24 @@
 			at: Option<BlockHash>,
 		) -> Result<Option<u32>>;
 
+		/// Get base info by its ID.
 		#[method(name = "rmrk_base")]
-		/// Get base info
 		fn base(&self, base_id: RmrkBaseId, at: Option<BlockHash>) -> Result<Option<BaseInfo>>;
 
+		/// Get all parts of a base.
 		#[method(name = "rmrk_baseParts")]
-		/// Get all Base's parts
 		fn base_parts(&self, base_id: RmrkBaseId, at: Option<BlockHash>) -> Result<Vec<PartType>>;
 
+		/// Get the theme names belonging to a base.
 		#[method(name = "rmrk_themeNames")]
-		/// Get Base's theme names
 		fn theme_names(
 			&self,
 			base_id: RmrkBaseId,
 			at: Option<BlockHash>,
 		) -> Result<Vec<RmrkThemeName>>;
 
+		/// Get theme info, including properties, optionally limited to the provided keys.
 		#[method(name = "rmrk_themes")]
-		/// Get Theme info -- name, properties, and inherit flag
 		fn theme(
 			&self,
 			base_id: RmrkBaseId,
modifiedprimitives/data-structs/src/lib.rsdiffbeforeafterboth
before · primitives/data-structs/src/lib.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617#![cfg_attr(not(feature = "std"), no_std)]1819use 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;
after · primitives/data-structs/src/lib.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617#![cfg_attr(not(feature = "std"), no_std)]1819use 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///371/// todo:doc links to chain defaults372// IMPORTANT: When adding/removing fields from this struct - don't forget to also373// update clamp_limits() in pallet-common.374#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]375#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]376pub struct CollectionLimits {377	/// Maximum number of owned tokens per account. Chain default: [`ACCOUNT_TOKEN_OWNERSHIP_LIMIT`]378	pub account_token_ownership_limit: Option<u32>,379	/// Maximum size of data in bytes of a sponsored transaction. Chain default: [`CUSTOM_DATA_LIMIT`]380	pub sponsored_data_size: Option<u32>,381382	/// FIXME should we delete this or repurpose it?383	/// None - setVariableMetadata is not sponsored384	/// Some(v) - setVariableMetadata is sponsored385	///           if there is v block between txs386	///387	/// In any case, chain default: [`SponsoringRateLimit::SponsoringDisabled`]388	pub sponsored_data_rate_limit: Option<SponsoringRateLimit>,389	/// Maximum amount of tokens inside the collection. Chain default: [`COLLECTION_TOKEN_LIMIT`]390	pub token_limit: Option<u32>,391392	/// Timeout for sponsoring a token transfer in passed blocks. Chain default: [`MAX_SPONSOR_TIMEOUT`]393	pub sponsor_transfer_timeout: Option<u32>,394	/// Timeout for sponsoring an approval in passed blocks. Chain default: [`SPONSOR_APPROVE_TIMEOUT`]395	pub sponsor_approve_timeout: Option<u32>,396	/// Can a token be transferred by the owner. Chain default: `false`397	pub owner_can_transfer: Option<bool>,398	/// Can a token be burned by the owner. Chain default: `true`399	pub owner_can_destroy: Option<bool>,400	/// Can a token be transferred at all. Chain default: `true`401	pub transfers_enabled: Option<bool>,402}403404impl CollectionLimits {405	pub fn account_token_ownership_limit(&self) -> u32 {406		self.account_token_ownership_limit407			.unwrap_or(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)408			.min(MAX_TOKEN_OWNERSHIP)409	}410	pub fn sponsored_data_size(&self) -> u32 {411		self.sponsored_data_size412			.unwrap_or(CUSTOM_DATA_LIMIT)413			.min(CUSTOM_DATA_LIMIT)414	}415	pub fn token_limit(&self) -> u32 {416		self.token_limit417			.unwrap_or(COLLECTION_TOKEN_LIMIT)418			.min(COLLECTION_TOKEN_LIMIT)419	}420	pub fn sponsor_transfer_timeout(&self, default: u32) -> u32 {421		self.sponsor_transfer_timeout422			.unwrap_or(default)423			.min(MAX_SPONSOR_TIMEOUT)424	}425	pub fn sponsor_approve_timeout(&self) -> u32 {426		self.sponsor_approve_timeout427			.unwrap_or(SPONSOR_APPROVE_TIMEOUT)428			.min(MAX_SPONSOR_TIMEOUT)429	}430	pub fn owner_can_transfer(&self) -> bool {431		self.owner_can_transfer.unwrap_or(false)432	}433	pub fn owner_can_transfer_instaled(&self) -> bool {434		self.owner_can_transfer.is_some()435	}436	pub fn owner_can_destroy(&self) -> bool {437		self.owner_can_destroy.unwrap_or(true)438	}439	pub fn transfers_enabled(&self) -> bool {440		self.transfers_enabled.unwrap_or(true)441	}442	pub fn sponsored_data_rate_limit(&self) -> Option<u32> {443		match self444			.sponsored_data_rate_limit445			.unwrap_or(SponsoringRateLimit::SponsoringDisabled)446		{447			SponsoringRateLimit::SponsoringDisabled => None,448			SponsoringRateLimit::Blocks(v) => Some(v.min(MAX_SPONSOR_TIMEOUT)),449		}450	}451}452453/// Permissions on certain operations within a collection.454/// All fields are wrapped in `Option`s, where None means chain default.455// IMPORTANT: When adding/removing fields from this struct - don't forget to also456// update clamp_limits() in pallet-common.457#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]458#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]459pub struct CollectionPermissions {460	pub access: Option<AccessMode>,461	pub mint_mode: Option<bool>,462	pub nesting: Option<NestingPermissions>,463}464465impl CollectionPermissions {466	pub fn access(&self) -> AccessMode {467		self.access.unwrap_or(AccessMode::Normal)468	}469	pub fn mint_mode(&self) -> bool {470		self.mint_mode.unwrap_or(false)471	}472	pub fn nesting(&self) -> &NestingPermissions {473		static DEFAULT: NestingPermissions = NestingPermissions {474			token_owner: false,475			collection_admin: false,476			restricted: None,477			#[cfg(feature = "runtime-benchmarks")]478			permissive: false,479		};480		self.nesting.as_ref().unwrap_or(&DEFAULT)481	}482}483484type OwnerRestrictedSetInner = BoundedBTreeSet<CollectionId, ConstU32<16>>;485486#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative)]487#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]488#[derivative(Debug)]489pub struct OwnerRestrictedSet(490	#[cfg_attr(feature = "serde1", serde(with = "bounded::set_serde"))]491	#[derivative(Debug(format_with = "bounded::set_debug"))]492	pub OwnerRestrictedSetInner,493);494impl OwnerRestrictedSet {495	pub fn new() -> Self {496		Self(Default::default())497	}498}499impl core::ops::Deref for OwnerRestrictedSet {500	type Target = OwnerRestrictedSetInner;501	fn deref(&self) -> &Self::Target {502		&self.0503	}504}505impl core::ops::DerefMut for OwnerRestrictedSet {506	fn deref_mut(&mut self) -> &mut Self::Target {507		&mut self.0508	}509}510511/// Part of collection permissions, if set, defines who is able to nest tokens into other tokens.512#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative)]513#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]514#[derivative(Debug)]515pub struct NestingPermissions {516	/// Owner of token can nest tokens under it517	pub token_owner: bool,518	/// Admin of token collection can nest tokens under token519	pub collection_admin: bool,520	/// If set - only tokens from specified collections can be nested521	pub restricted: Option<OwnerRestrictedSet>,522523	#[cfg(feature = "runtime-benchmarks")]524	/// Anyone can nest tokens, mutually exclusive with `token_owner`, `admin`525	pub permissive: bool,526}527528/// Enum denominating how often can sponsoring occur if it is enabled.529#[derive(Encode, Decode, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]530#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]531pub enum SponsoringRateLimit {532	/// Sponsoring is disabled, and the collection sponsor will not pay for transactions533	SponsoringDisabled,534	/// Once per how many blocks can sponsorship of a transaction type occur535	Blocks(u32),536}537538/// Data used to describe an NFT at creation.539#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]540#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]541#[derivative(Debug)]542pub struct CreateNftData {543	/// Key-value pairs used to describe the token as metadata544	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]545	#[derivative(Debug(format_with = "bounded::vec_debug"))]546	pub properties: CollectionPropertiesVec,547}548549/// Data used to describe a Fungible token at creation.550#[derive(Encode, Decode, MaxEncodedLen, Default, Debug, Clone, PartialEq, TypeInfo)]551#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]552pub struct CreateFungibleData {553	/// Number of fungible coins minted554	pub value: u128,555}556557/// Data used to describe a Refungible token at creation.558#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]559#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]560#[derivative(Debug)]561pub struct CreateReFungibleData {562	/// Immutable metadata of the token563	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]564	#[derivative(Debug(format_with = "bounded::vec_debug"))]565	pub const_data: BoundedVec<u8, CustomDataLimit>,566	/// Number of pieces the RFT is split into567	pub pieces: u128,568}569570#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]571#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]572pub enum MetaUpdatePermission {573	ItemOwner,574	Admin,575	None,576}577578/// Enum holding data used for creation of all three item types.579#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]580#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]581pub enum CreateItemData {582	NFT(CreateNftData),583	Fungible(CreateFungibleData),584	ReFungible(CreateReFungibleData),585}586587/// Explicit NFT creation data with meta parameters.588#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]589#[derivative(Debug)]590pub struct CreateNftExData<CrossAccountId> {591	#[derivative(Debug(format_with = "bounded::vec_debug"))]592	pub properties: CollectionPropertiesVec,593	pub owner: CrossAccountId,594}595596/// Explicit RFT creation data with meta parameters.597#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]598#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]599pub struct CreateRefungibleExData<CrossAccountId> {600	#[derivative(Debug(format_with = "bounded::vec_debug"))]601	pub const_data: BoundedVec<u8, CustomDataLimit>,602	#[derivative(Debug(format_with = "bounded::map_debug"))]603	pub users: BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,604}605606/// Explicit item creation data with meta parameters, namely the owner.607#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]608#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]609pub enum CreateItemExData<CrossAccountId> {610	NFT(611		#[derivative(Debug(format_with = "bounded::vec_debug"))]612		BoundedVec<CreateNftExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,613	),614	Fungible(615		#[derivative(Debug(format_with = "bounded::map_debug"))]616		BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,617	),618	/// Many tokens, each may have only one owner619	RefungibleMultipleItems(620		#[derivative(Debug(format_with = "bounded::vec_debug"))]621		BoundedVec<CreateRefungibleExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,622	),623	/// Single token, which may have many owners624	RefungibleMultipleOwners(CreateRefungibleExData<CrossAccountId>),625}626627impl CreateItemData {628	pub fn data_size(&self) -> usize {629		match self {630			CreateItemData::ReFungible(data) => data.const_data.len(),631			_ => 0,632		}633	}634}635636impl From<CreateNftData> for CreateItemData {637	fn from(item: CreateNftData) -> Self {638		CreateItemData::NFT(item)639	}640}641642impl From<CreateReFungibleData> for CreateItemData {643	fn from(item: CreateReFungibleData) -> Self {644		CreateItemData::ReFungible(item)645	}646}647648impl From<CreateFungibleData> for CreateItemData {649	fn from(item: CreateFungibleData) -> Self {650		CreateItemData::Fungible(item)651	}652}653654/// Token's address, dictated by its collection and token IDs.655#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]656#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]657// todo possibly rename to be used generally as an address pair658pub struct TokenChild {659	pub token: TokenId,660	pub collection: CollectionId,661}662663#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]664#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]665pub struct CollectionStats {666	pub created: u32,667	pub destroyed: u32,668	pub alive: u32,669}670671#[derive(Encode, Decode, Clone, Debug)]672#[cfg_attr(feature = "std", derive(PartialEq))]673pub struct PhantomType<T>(core::marker::PhantomData<T>);674675impl<T: TypeInfo + 'static> TypeInfo for PhantomType<T> {676	type Identity = PhantomType<T>;677678	fn type_info() -> scale_info::Type {679		use scale_info::{680			Type, Path,681			build::{FieldsBuilder, UnnamedFields},682			type_params,683		};684		Type::builder()685			.path(Path::new("up_data_structs", "PhantomType"))686			.type_params(type_params!(T))687			.composite(<FieldsBuilder<UnnamedFields>>::default().field(|b| b.ty::<[T; 0]>()))688	}689}690impl<T> MaxEncodedLen for PhantomType<T> {691	fn max_encoded_len() -> usize {692		0693	}694}695696pub type BoundedBytes<S> = BoundedVec<u8, S>;697698pub type AuxPropertyValue = BoundedBytes<ConstU32<MAX_AUX_PROPERTY_VALUE_LENGTH>>;699700pub type PropertyKey = BoundedBytes<ConstU32<MAX_PROPERTY_KEY_LENGTH>>;701pub type PropertyValue = BoundedBytes<ConstU32<MAX_PROPERTY_VALUE_LENGTH>>;702703#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]704#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]705pub struct PropertyPermission {706	pub mutable: bool,707	pub collection_admin: bool,708	pub token_owner: bool,709}710711impl PropertyPermission {712	pub fn none() -> Self {713		Self {714			mutable: true,715			collection_admin: false,716			token_owner: false,717		}718	}719}720721#[derive(Encode, Decode, Debug, TypeInfo, Clone, PartialEq, MaxEncodedLen)]722#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]723pub struct Property {724	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]725	pub key: PropertyKey,726727	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]728	pub value: PropertyValue,729}730731impl Into<(PropertyKey, PropertyValue)> for Property {732	fn into(self) -> (PropertyKey, PropertyValue) {733		(self.key, self.value)734	}735}736737#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]738#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]739pub struct PropertyKeyPermission {740	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]741	pub key: PropertyKey,742743	pub permission: PropertyPermission,744}745746impl Into<(PropertyKey, PropertyPermission)> for PropertyKeyPermission {747	fn into(self) -> (PropertyKey, PropertyPermission) {748		(self.key, self.permission)749	}750}751752#[derive(Debug)]753pub enum PropertiesError {754	NoSpaceForProperty,755	PropertyLimitReached,756	InvalidCharacterInPropertyKey,757	PropertyKeyIsTooLong,758	EmptyPropertyKey,759}760761#[derive(Encode, Decode, MaxEncodedLen, TypeInfo, PartialEq, Clone, Copy)]762pub enum PropertyScope {763	None,764	Rmrk,765}766767impl PropertyScope {768	pub fn apply(self, key: PropertyKey) -> Result<PropertyKey, PropertiesError> {769		let scope_str: &[u8] = match self {770			Self::None => return Ok(key),771			Self::Rmrk => b"rmrk",772		};773774		[scope_str, b":", key.as_slice()]775			.concat()776			.try_into()777			.map_err(|_| PropertiesError::PropertyKeyIsTooLong)778	}779}780781pub trait TrySetProperty: Sized {782	type Value;783784	fn try_scoped_set(785		&mut self,786		scope: PropertyScope,787		key: PropertyKey,788		value: Self::Value,789	) -> Result<(), PropertiesError>;790791	fn try_scoped_set_from_iter<I, KV>(792		&mut self,793		scope: PropertyScope,794		iter: I,795	) -> Result<(), PropertiesError>796	where797		I: Iterator<Item = KV>,798		KV: Into<(PropertyKey, Self::Value)>,799	{800		for kv in iter {801			let (key, value) = kv.into();802			self.try_scoped_set(scope, key, value)?;803		}804805		Ok(())806	}807808	fn try_set(&mut self, key: PropertyKey, value: Self::Value) -> Result<(), PropertiesError> {809		self.try_scoped_set(PropertyScope::None, key, value)810	}811812	fn try_set_from_iter<I, KV>(&mut self, iter: I) -> Result<(), PropertiesError>813	where814		I: Iterator<Item = KV>,815		KV: Into<(PropertyKey, Self::Value)>,816	{817		self.try_scoped_set_from_iter(PropertyScope::None, iter)818	}819}820821#[derive(Encode, Decode, TypeInfo, Derivative, Clone, PartialEq, MaxEncodedLen)]822#[derivative(Default(bound = ""))]823pub struct PropertiesMap<Value>(824	BoundedBTreeMap<PropertyKey, Value, ConstU32<MAX_PROPERTIES_PER_ITEM>>,825);826827impl<Value> PropertiesMap<Value> {828	pub fn new() -> Self {829		Self(BoundedBTreeMap::new())830	}831832	pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<Value>, PropertiesError> {833		Self::check_property_key(key)?;834835		Ok(self.0.remove(key))836	}837838	pub fn get(&self, key: &PropertyKey) -> Option<&Value> {839		self.0.get(key)840	}841842	pub fn contains_key(&self, key: &PropertyKey) -> bool {843		self.0.contains_key(key)844	}845846	fn check_property_key(key: &PropertyKey) -> Result<(), PropertiesError> {847		if key.is_empty() {848			return Err(PropertiesError::EmptyPropertyKey);849		}850851		for byte in key.as_slice().iter() {852			let byte = *byte;853854			if !byte.is_ascii_alphanumeric() && byte != b'_' && byte != b'-' && byte != b'.' {855				return Err(PropertiesError::InvalidCharacterInPropertyKey);856			}857		}858859		Ok(())860	}861}862863impl<Value> IntoIterator for PropertiesMap<Value> {864	type Item = (PropertyKey, Value);865	type IntoIter = <866		BoundedBTreeMap<867			PropertyKey,868			Value,869			ConstU32<MAX_PROPERTIES_PER_ITEM>870		> as IntoIterator871	>::IntoIter;872873	fn into_iter(self) -> Self::IntoIter {874		self.0.into_iter()875	}876}877878impl<Value> TrySetProperty for PropertiesMap<Value> {879	type Value = Value;880881	fn try_scoped_set(882		&mut self,883		scope: PropertyScope,884		key: PropertyKey,885		value: Self::Value,886	) -> Result<(), PropertiesError> {887		Self::check_property_key(&key)?;888889		let key = scope.apply(key)?;890		self.0891			.try_insert(key, value)892			.map_err(|_| PropertiesError::PropertyLimitReached)?;893894		Ok(())895	}896}897898pub type PropertiesPermissionMap = PropertiesMap<PropertyPermission>;899900#[derive(Encode, Decode, TypeInfo, Clone, PartialEq, MaxEncodedLen)]901pub struct Properties {902	map: PropertiesMap<PropertyValue>,903	consumed_space: u32,904	space_limit: u32,905}906907impl Properties {908	pub fn new(space_limit: u32) -> Self {909		Self {910			map: PropertiesMap::new(),911			consumed_space: 0,912			space_limit,913		}914	}915916	pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<PropertyValue>, PropertiesError> {917		let value = self.map.remove(key)?;918919		if let Some(ref value) = value {920			let value_len = value.len() as u32;921			self.consumed_space -= value_len;922		}923924		Ok(value)925	}926927	pub fn get(&self, key: &PropertyKey) -> Option<&PropertyValue> {928		self.map.get(key)929	}930}931932impl IntoIterator for Properties {933	type Item = (PropertyKey, PropertyValue);934	type IntoIter = <PropertiesMap<PropertyValue> as IntoIterator>::IntoIter;935936	fn into_iter(self) -> Self::IntoIter {937		self.map.into_iter()938	}939}940941impl TrySetProperty for Properties {942	type Value = PropertyValue;943944	fn try_scoped_set(945		&mut self,946		scope: PropertyScope,947		key: PropertyKey,948		value: Self::Value,949	) -> Result<(), PropertiesError> {950		let value_len = value.len();951952		if self.consumed_space as usize + value_len > self.space_limit as usize953			&& !cfg!(feature = "runtime-benchmarks")954		{955			return Err(PropertiesError::NoSpaceForProperty);956		}957958		self.map.try_scoped_set(scope, key, value)?;959960		self.consumed_space += value_len as u32;961962		Ok(())963	}964}965966pub struct CollectionProperties;967968impl Get<Properties> for CollectionProperties {969	fn get() -> Properties {970		Properties::new(MAX_COLLECTION_PROPERTIES_SIZE)971	}972}973974pub struct TokenProperties;975976impl Get<Properties> for TokenProperties {977	fn get() -> Properties {978		Properties::new(MAX_TOKEN_PROPERTIES_SIZE)979	}980}981982// RMRK983// todo document?984parameter_types! {985	#[derive(PartialEq, TypeInfo)]986	pub const RmrkStringLimit: u32 = 128;987	#[derive(PartialEq)]988	pub const RmrkCollectionSymbolLimit: u32 = MAX_TOKEN_PREFIX_LENGTH;989	#[derive(PartialEq)]990	pub const RmrkResourceSymbolLimit: u32 = 10;991	#[derive(PartialEq)]992	pub const RmrkBaseSymbolLimit: u32 = MAX_TOKEN_PREFIX_LENGTH;993	#[derive(PartialEq)]994	pub const RmrkKeyLimit: u32 = 32;995	#[derive(PartialEq)]996	pub const RmrkValueLimit: u32 = 256;997	#[derive(PartialEq)]998	pub const RmrkMaxCollectionsEquippablePerPart: u32 = 100;999	#[derive(PartialEq)]1000	pub const MaxPropertiesPerTheme: u32 = 5;1001	#[derive(PartialEq)]1002	pub const RmrkPartsLimit: u32 = 25;1003	#[derive(PartialEq)]1004	pub const RmrkMaxPriorities: u32 = 25;1005	#[derive(PartialEq)]1006	pub const MaxResourcesOnMint: u32 = 100;1007}10081009impl From<RmrkCollectionId> for CollectionId {1010	fn from(id: RmrkCollectionId) -> Self {1011		Self(id)1012	}1013}10141015impl From<RmrkNftId> for TokenId {1016	fn from(id: RmrkNftId) -> Self {1017		Self(id)1018	}1019}10201021pub type RmrkCollectionInfo<AccountId> =1022	CollectionInfo<RmrkString, RmrkCollectionSymbol, AccountId>;1023pub type RmrkInstanceInfo<AccountId> = NftInfo<AccountId, Permill, RmrkString>;1024pub type RmrkResourceInfo = ResourceInfo<RmrkString, RmrkBoundedParts>;1025pub type RmrkPropertyInfo = PropertyInfo<RmrkKeyString, RmrkValueString>;1026pub type RmrkBaseInfo<AccountId> = BaseInfo<AccountId, RmrkString>;1027pub type BoundedEquippableCollectionIds =1028	BoundedVec<RmrkCollectionId, RmrkMaxCollectionsEquippablePerPart>;1029pub type RmrkPartType = PartType<RmrkString, BoundedEquippableCollectionIds>;1030pub type RmrkEquippableList = EquippableList<BoundedEquippableCollectionIds>;1031pub type RmrkThemeProperty = ThemeProperty<RmrkString>;1032pub type RmrkTheme = Theme<RmrkString, Vec<RmrkThemeProperty>>;1033pub type RmrkBoundedTheme = Theme<RmrkString, BoundedVec<RmrkThemeProperty, MaxPropertiesPerTheme>>;1034pub type RmrkResourceTypes = ResourceTypes<RmrkString, RmrkBoundedParts>;10351036pub type RmrkBasicResource = BasicResource<RmrkString>;1037pub type RmrkComposableResource = ComposableResource<RmrkString, RmrkBoundedParts>;1038pub type RmrkSlotResource = SlotResource<RmrkString>;10391040pub type RmrkString = BoundedVec<u8, RmrkStringLimit>;1041pub type RmrkCollectionSymbol = BoundedVec<u8, RmrkCollectionSymbolLimit>;1042pub type RmrkBaseSymbol = BoundedVec<u8, RmrkBaseSymbolLimit>;1043pub type RmrkKeyString = BoundedVec<u8, RmrkKeyLimit>;1044pub type RmrkValueString = BoundedVec<u8, RmrkValueLimit>;1045pub type RmrkBoundedResource = BoundedVec<u8, RmrkResourceSymbolLimit>;1046pub type RmrkBoundedParts = BoundedVec<RmrkPartId, RmrkPartsLimit>; // todo make sure it is needed10471048pub type RmrkRpcString = Vec<u8>;1049pub type RmrkThemeName = RmrkRpcString;1050pub type RmrkPropertyKey = RmrkRpcString;
modifiedtests/src/interfaces/unique/definitions.tsdiffbeforeafterboth
--- a/tests/src/interfaces/unique/definitions.ts
+++ b/tests/src/interfaces/unique/definitions.ts
@@ -37,48 +37,123 @@
 export default {
   types: {},
   rpc: {
-    adminlist: fun('Get admin list', [collectionParam], 'Vec<PalletEvmAccountBasicCrossAccountIdRepr>'),
-    allowlist: fun('Get allowlist', [collectionParam], 'Vec<PalletEvmAccountBasicCrossAccountIdRepr>'),
+    accountTokens: fun(
+      'Get tokens owned by an account in a collection', 
+      [collectionParam, crossAccountParam()], 
+      'Vec<u32>',
+    ),
+    collectionTokens: fun(
+      'Get tokens contained within a collection', 
+      [collectionParam], 
+      'Vec<u32>',
+    ),
+    tokenExists: fun(
+      'Check if the token exists', 
+      [collectionParam, tokenParam], 
+      'bool',
+    ),
 
-    accountTokens: fun('Get tokens owned by account', [collectionParam, crossAccountParam()], 'Vec<u32>'),
-    collectionTokens: fun('Get tokens contained in collection', [collectionParam], 'Vec<u32>'),
+    tokenOwner: fun(
+      'Get the token owner', 
+      [collectionParam, tokenParam], 
+      `Option<${CROSS_ACCOUNT_ID_TYPE}>`,
+    ),
+    topmostTokenOwner: fun(
+      'Get the topmost token owner in the hierarchy of a possibly nested token', 
+      [collectionParam, tokenParam], 
+      `Option<${CROSS_ACCOUNT_ID_TYPE}>`,
+    ),
+    tokenChildren: fun(
+      'Get tokens nested directly into the token', 
+      [collectionParam, tokenParam], 
+      'Vec<UpDataStructsTokenChild>',
+    ),
 
-    lastTokenId: fun('Get last token ID created in a collection', [collectionParam], 'u32'),
-    totalSupply: fun('Get amount of unique collection tokens', [collectionParam], 'u32'),
-    accountBalance: fun('Get owned amount of any user tokens', [collectionParam, crossAccountParam()], 'u32'),
-    balance: fun('Get owned amount of specific account token', [collectionParam, crossAccountParam(), tokenParam], 'u128'),
-    allowance: fun('Get allowed amount', [collectionParam, crossAccountParam('sender'), crossAccountParam('spender'), tokenParam], 'u128'),
-    tokenOwner: fun('Get token owner', [collectionParam, tokenParam], `Option<${CROSS_ACCOUNT_ID_TYPE}>`),
-    topmostTokenOwner: fun('Get token owner, in case of nested token - find the parent recursively', [collectionParam, tokenParam], `Option<${CROSS_ACCOUNT_ID_TYPE}>`),
-    tokenChildren: fun('Get tokens nested directly into the token', [collectionParam, tokenParam], 'Vec<UpDataStructsTokenChild>'),
-    constMetadata: fun('Get token constant metadata', [collectionParam, tokenParam], 'Vec<u8>'),
-    variableMetadata: fun('Get token variable metadata', [collectionParam, tokenParam], 'Vec<u8>'),
     collectionProperties: fun(
-      'Get collection properties',
+      'Get collection properties, optionally limited to the provided keys',
       [collectionParam, propertyKeysParam],
       'Vec<UpDataStructsProperty>',
     ),
     tokenProperties: fun(
-      'Get token properties',
+      'Get token properties, optionally limited to the provided keys',
       [collectionParam, tokenParam, propertyKeysParam],
       'Vec<UpDataStructsProperty>',
     ),
     propertyPermissions: fun(
-      'Get property permissions',
+      'Get property permissions, optionally limited to the provided keys',
       [collectionParam, propertyKeysParam],
       'Vec<UpDataStructsPropertyKeyPermission>',
     ),
+
     tokenData: fun(
-      'Get token data',
+      'Get token data, including properties, optionally limited to the provided keys, and total pieces for an RFT',
       [collectionParam, tokenParam, propertyKeysParam],
       'UpDataStructsTokenData',
     ),
-    tokenExists: fun('Check if token exists', [collectionParam, tokenParam], 'bool'),
-    collectionById: fun('Get collection by specified ID', [collectionParam], 'Option<UpDataStructsRpcCollection>'),
-    collectionStats: fun('Get collection stats', [], 'UpDataStructsCollectionStats'),
-    allowed: fun('Check if user is allowed to use collection', [collectionParam, crossAccountParam()], 'bool'),
-    nextSponsored: fun('Get number of blocks when sponsored transaction is available', [collectionParam, crossAccountParam(), tokenParam], 'Option<u64>'),
-    effectiveCollectionLimits: fun('Get effective collection limits', [collectionParam], 'Option<UpDataStructsCollectionLimits>'),
-    totalPieces: fun('Get total pieces of token', [collectionParam, tokenParam], 'Option<u128>'),
+    totalSupply: fun(
+      'Get the amount of distinctive tokens present in a collection', 
+      [collectionParam], 
+      'u32',
+    ),
+
+    accountBalance: fun(
+      'Get the amount of any user tokens owned by an account', 
+      [collectionParam, crossAccountParam()], 
+      'u32',
+    ),
+    balance: fun(
+      'Get the amount of a specific token owned by an account', 
+      [collectionParam, crossAccountParam(), tokenParam], 
+      'u128',
+    ),
+    allowance: fun(
+      'Get the amount of currently possible sponsored transactions on a token for the fee to be taken off a sponsor', 
+      [collectionParam, crossAccountParam('sender'), crossAccountParam('spender'), tokenParam], 
+      'u128',
+    ),
+
+    adminlist: fun(
+      'Get the list of admin accounts of a collection', 
+      [collectionParam], 
+      'Vec<PalletEvmAccountBasicCrossAccountIdRepr>',
+    ),
+    allowlist: fun(
+      'Get the list of accounts allowed to operate within a collection', 
+      [collectionParam], 
+      'Vec<PalletEvmAccountBasicCrossAccountIdRepr>',
+    ),
+    allowed: fun(
+      'Check if a user is allowed to operate within a collection', 
+      [collectionParam, crossAccountParam()], 
+      'bool',
+    ),
+
+    lastTokenId: fun('Get the last token ID created in a collection', [collectionParam], 'u32'),
+    collectionById: fun(
+      'Get a collection by the specified ID', 
+      [collectionParam], 
+      'Option<UpDataStructsRpcCollection>',
+    ),
+    collectionStats: fun(
+      'Get chain stats about collections', 
+      [], 
+      'UpDataStructsCollectionStats',
+    ),
+
+    nextSponsored: fun(
+      'Get the number of blocks until sponsoring a transaction is available', 
+      [collectionParam, crossAccountParam(), tokenParam], 
+      'Option<u64>',
+    ),
+    effectiveCollectionLimits: fun(
+      'Get effective collection limits', 
+      [collectionParam], 
+      'Option<UpDataStructsCollectionLimits>',
+    ),
+    totalPieces: fun(
+      'Get the total amount of pieces of an RFT', 
+      [collectionParam, tokenParam], 
+      'Option<u128>',
+    ),
   },
 };