git.delta.rocks / unique-network / refs/commits / 63e242dc3f1d

difftreelog

Add pieces into token data. Add negative tests.

Trubnikov Sergey2022-06-30parent: #88ef722.patch.diff
in: master

4 files changed

modifiedpallets/nonfungible/src/common.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -473,7 +473,11 @@
 		None
 	}
 
-	fn total_pieces(&self, _token: TokenId) -> Option<u128> {
-		Some(1)
+	fn total_pieces(&self, token: TokenId) -> Option<u128> {
+		if <TokenData<T>>::contains_key((self.id, token)) {
+			Some(1)
+		} else {
+			None
+		}
 	}
 }
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}185186pub struct OverflowError;187impl From<OverflowError> for &'static str {188	fn from(_: OverflowError) -> Self {189		"overflow occured"190	}191}192193pub type DecimalPoints = u8;194195#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]196#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]197pub enum CollectionMode {198	NFT,199	// decimal points200	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	Unconfirmed(AccountId),255	/// Transactions are sponsored by specified account256	Confirmed(AccountId),257}258259impl<AccountId> SponsorshipState<AccountId> {260	pub fn sponsor(&self) -> Option<&AccountId> {261		match self {262			Self::Confirmed(sponsor) => Some(sponsor),263			_ => None,264		}265	}266267	pub fn pending_sponsor(&self) -> Option<&AccountId> {268		match self {269			Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),270			_ => None,271		}272	}273274	pub fn confirmed(&self) -> bool {275		matches!(self, Self::Confirmed(_))276	}277}278279impl<T> Default for SponsorshipState<T> {280	fn default() -> Self {281		Self::Disabled282	}283}284285/// Used in storage286#[struct_versioning::versioned(version = 2, upper)]287#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen)]288pub struct Collection<AccountId> {289	pub owner: AccountId,290	pub mode: CollectionMode,291	#[version(..2)]292	pub access: AccessMode,293	pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,294	pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,295	pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,296297	#[version(..2)]298	pub mint_mode: bool,299300	#[version(..2)]301	pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,302303	#[version(..2)]304	pub schema_version: SchemaVersion,305	pub sponsorship: SponsorshipState<AccountId>,306307	pub limits: CollectionLimits,308309	#[version(2.., upper(Default::default()))]310	pub permissions: CollectionPermissions,311312	/// Marks that this collection is not "unique", and managed from external.313	#[version(2.., upper(false))]314	pub external_collection: bool,315316	#[version(..2)]317	pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,318319	#[version(..2)]320	pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,321322	#[version(..2)]323	pub meta_update_permission: MetaUpdatePermission,324}325326/// Used in RPC calls327#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]328#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]329pub struct RpcCollection<AccountId> {330	pub owner: AccountId,331	pub mode: CollectionMode,332	pub name: Vec<u16>,333	pub description: Vec<u16>,334	pub token_prefix: Vec<u8>,335	pub sponsorship: SponsorshipState<AccountId>,336	pub limits: CollectionLimits,337	pub permissions: CollectionPermissions,338	pub token_property_permissions: Vec<PropertyKeyPermission>,339	pub properties: Vec<Property>,340	pub read_only: bool,341}342343#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Derivative, MaxEncodedLen)]344#[derivative(Debug, Default(bound = ""))]345pub struct CreateCollectionData<AccountId> {346	#[derivative(Default(value = "CollectionMode::NFT"))]347	pub mode: CollectionMode,348	pub access: Option<AccessMode>,349	pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,350	pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,351	pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,352	pub pending_sponsor: Option<AccountId>,353	pub limits: Option<CollectionLimits>,354	pub permissions: Option<CollectionPermissions>,355	pub token_property_permissions: CollectionPropertiesPermissionsVec,356	pub properties: CollectionPropertiesVec,357}358359pub type CollectionPropertiesPermissionsVec =360	BoundedVec<PropertyKeyPermission, ConstU32<MAX_PROPERTIES_PER_ITEM>>;361362pub type CollectionPropertiesVec = BoundedVec<Property, ConstU32<MAX_PROPERTIES_PER_ITEM>>;363364/// All fields are wrapped in `Option`s, where None means chain default365// When adding/removing fields from this struct - don't forget to also update clamp_limits366#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]367#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]368pub struct CollectionLimits {369	pub account_token_ownership_limit: Option<u32>,370	pub sponsored_data_size: Option<u32>,371372	/// FIXME should we delete this or repurpose it?373	/// None - setVariableMetadata is not sponsored374	/// Some(v) - setVariableMetadata is sponsored375	///           if there is v block between txs376	pub sponsored_data_rate_limit: Option<SponsoringRateLimit>,377	pub token_limit: Option<u32>,378379	// Timeouts for item types in passed blocks380	pub sponsor_transfer_timeout: Option<u32>,381	pub sponsor_approve_timeout: Option<u32>,382	pub owner_can_transfer: Option<bool>,383	pub owner_can_destroy: Option<bool>,384	pub transfers_enabled: Option<bool>,385}386387impl CollectionLimits {388	pub fn account_token_ownership_limit(&self) -> u32 {389		self.account_token_ownership_limit390			.unwrap_or(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)391			.min(MAX_TOKEN_OWNERSHIP)392	}393	pub fn sponsored_data_size(&self) -> u32 {394		self.sponsored_data_size395			.unwrap_or(CUSTOM_DATA_LIMIT)396			.min(CUSTOM_DATA_LIMIT)397	}398	pub fn token_limit(&self) -> u32 {399		self.token_limit400			.unwrap_or(COLLECTION_TOKEN_LIMIT)401			.min(COLLECTION_TOKEN_LIMIT)402	}403	pub fn sponsor_transfer_timeout(&self, default: u32) -> u32 {404		self.sponsor_transfer_timeout405			.unwrap_or(default)406			.min(MAX_SPONSOR_TIMEOUT)407	}408	pub fn sponsor_approve_timeout(&self) -> u32 {409		self.sponsor_approve_timeout410			.unwrap_or(SPONSOR_APPROVE_TIMEOUT)411			.min(MAX_SPONSOR_TIMEOUT)412	}413	pub fn owner_can_transfer(&self) -> bool {414		self.owner_can_transfer.unwrap_or(false)415	}416	pub fn owner_can_transfer_instaled(&self) -> bool {417		self.owner_can_transfer.is_some()418	}419	pub fn owner_can_destroy(&self) -> bool {420		self.owner_can_destroy.unwrap_or(true)421	}422	pub fn transfers_enabled(&self) -> bool {423		self.transfers_enabled.unwrap_or(true)424	}425	pub fn sponsored_data_rate_limit(&self) -> Option<u32> {426		match self427			.sponsored_data_rate_limit428			.unwrap_or(SponsoringRateLimit::SponsoringDisabled)429		{430			SponsoringRateLimit::SponsoringDisabled => None,431			SponsoringRateLimit::Blocks(v) => Some(v.min(MAX_SPONSOR_TIMEOUT)),432		}433	}434}435436// When adding/removing fields from this struct - don't forget to also update clamp_limits437#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]438#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]439pub struct CollectionPermissions {440	pub access: Option<AccessMode>,441	pub mint_mode: Option<bool>,442	pub nesting: Option<NestingPermissions>,443}444445impl CollectionPermissions {446	pub fn access(&self) -> AccessMode {447		self.access.unwrap_or(AccessMode::Normal)448	}449	pub fn mint_mode(&self) -> bool {450		self.mint_mode.unwrap_or(false)451	}452	pub fn nesting(&self) -> &NestingPermissions {453		static DEFAULT: NestingPermissions = NestingPermissions {454			token_owner: false,455			collection_admin: false,456			restricted: None,457			#[cfg(feature = "runtime-benchmarks")]458			permissive: false,459		};460		self.nesting.as_ref().unwrap_or(&DEFAULT)461	}462}463464type OwnerRestrictedSetInner = BoundedBTreeSet<CollectionId, ConstU32<16>>;465466#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative)]467#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]468#[derivative(Debug)]469pub struct OwnerRestrictedSet(470	#[cfg_attr(feature = "serde1", serde(with = "bounded::set_serde"))]471	#[derivative(Debug(format_with = "bounded::set_debug"))]472	pub OwnerRestrictedSetInner,473);474impl OwnerRestrictedSet {475	pub fn new() -> Self {476		Self(Default::default())477	}478}479impl core::ops::Deref for OwnerRestrictedSet {480	type Target = OwnerRestrictedSetInner;481	fn deref(&self) -> &Self::Target {482		&self.0483	}484}485impl core::ops::DerefMut for OwnerRestrictedSet {486	fn deref_mut(&mut self) -> &mut Self::Target {487		&mut self.0488	}489}490491#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative)]492#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]493#[derivative(Debug)]494pub struct NestingPermissions {495	/// Owner of token can nest tokens under it496	pub token_owner: bool,497	/// Admin of token collection can nest tokens under token498	pub collection_admin: bool,499	/// If set - only tokens from specified collections can be nested500	pub restricted: Option<OwnerRestrictedSet>,501502	#[cfg(feature = "runtime-benchmarks")]503	/// Anyone can nest tokens, mutually exclusive with `token_owner`, `admin`504	pub permissive: bool,505}506507#[derive(Encode, Decode, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]508#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]509pub enum SponsoringRateLimit {510	SponsoringDisabled,511	Blocks(u32),512}513514#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]515#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]516#[derivative(Debug)]517pub struct CreateNftData {518	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]519	#[derivative(Debug(format_with = "bounded::vec_debug"))]520	pub properties: CollectionPropertiesVec,521}522523#[derive(Encode, Decode, MaxEncodedLen, Default, Debug, Clone, PartialEq, TypeInfo)]524#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]525pub struct CreateFungibleData {526	pub value: u128,527}528529#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]530#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]531#[derivative(Debug)]532pub struct CreateReFungibleData {533	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]534	#[derivative(Debug(format_with = "bounded::vec_debug"))]535	pub const_data: BoundedVec<u8, CustomDataLimit>,536	pub pieces: u128,537}538539#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]540#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]541pub enum MetaUpdatePermission {542	ItemOwner,543	Admin,544	None,545}546547#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]548#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]549pub enum CreateItemData {550	NFT(CreateNftData),551	Fungible(CreateFungibleData),552	ReFungible(CreateReFungibleData),553}554555#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]556#[derivative(Debug)]557pub struct CreateNftExData<CrossAccountId> {558	#[derivative(Debug(format_with = "bounded::vec_debug"))]559	pub properties: CollectionPropertiesVec,560	pub owner: CrossAccountId,561}562563#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]564#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]565pub struct CreateRefungibleExData<CrossAccountId> {566	#[derivative(Debug(format_with = "bounded::vec_debug"))]567	pub const_data: BoundedVec<u8, CustomDataLimit>,568	#[derivative(Debug(format_with = "bounded::map_debug"))]569	pub users: BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,570}571572#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]573#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]574pub enum CreateItemExData<CrossAccountId> {575	NFT(576		#[derivative(Debug(format_with = "bounded::vec_debug"))]577		BoundedVec<CreateNftExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,578	),579	Fungible(580		#[derivative(Debug(format_with = "bounded::map_debug"))]581		BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,582	),583	/// Many tokens, each may have only one owner584	RefungibleMultipleItems(585		#[derivative(Debug(format_with = "bounded::vec_debug"))]586		BoundedVec<CreateRefungibleExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,587	),588	/// Single token, which may have many owners589	RefungibleMultipleOwners(CreateRefungibleExData<CrossAccountId>),590}591592impl CreateItemData {593	pub fn data_size(&self) -> usize {594		match self {595			CreateItemData::ReFungible(data) => data.const_data.len(),596			_ => 0,597		}598	}599}600601impl From<CreateNftData> for CreateItemData {602	fn from(item: CreateNftData) -> Self {603		CreateItemData::NFT(item)604	}605}606607impl From<CreateReFungibleData> for CreateItemData {608	fn from(item: CreateReFungibleData) -> Self {609		CreateItemData::ReFungible(item)610	}611}612613impl From<CreateFungibleData> for CreateItemData {614	fn from(item: CreateFungibleData) -> Self {615		CreateItemData::Fungible(item)616	}617}618619#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]620#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]621// todo possibly rename to be used generally as an address pair622pub struct TokenChild {623	pub token: TokenId,624	pub collection: CollectionId,625}626627#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]628#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]629pub struct CollectionStats {630	pub created: u32,631	pub destroyed: u32,632	pub alive: u32,633}634635#[derive(Encode, Decode, Clone, Debug)]636#[cfg_attr(feature = "std", derive(PartialEq))]637pub struct PhantomType<T>(core::marker::PhantomData<T>);638639impl<T: TypeInfo + 'static> TypeInfo for PhantomType<T> {640	type Identity = PhantomType<T>;641642	fn type_info() -> scale_info::Type {643		use scale_info::{644			Type, Path,645			build::{FieldsBuilder, UnnamedFields},646			type_params,647		};648		Type::builder()649			.path(Path::new("up_data_structs", "PhantomType"))650			.type_params(type_params!(T))651			.composite(<FieldsBuilder<UnnamedFields>>::default().field(|b| b.ty::<[T; 0]>()))652	}653}654impl<T> MaxEncodedLen for PhantomType<T> {655	fn max_encoded_len() -> usize {656		0657	}658}659660pub type BoundedBytes<S> = BoundedVec<u8, S>;661662pub type AuxPropertyValue = BoundedBytes<ConstU32<MAX_AUX_PROPERTY_VALUE_LENGTH>>;663664pub type PropertyKey = BoundedBytes<ConstU32<MAX_PROPERTY_KEY_LENGTH>>;665pub type PropertyValue = BoundedBytes<ConstU32<MAX_PROPERTY_VALUE_LENGTH>>;666667#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]668#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]669pub struct PropertyPermission {670	pub mutable: bool,671	pub collection_admin: bool,672	pub token_owner: bool,673}674675impl PropertyPermission {676	pub fn none() -> Self {677		Self {678			mutable: true,679			collection_admin: false,680			token_owner: false,681		}682	}683}684685#[derive(Encode, Decode, Debug, TypeInfo, Clone, PartialEq, MaxEncodedLen)]686#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]687pub struct Property {688	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]689	pub key: PropertyKey,690691	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]692	pub value: PropertyValue,693}694695impl Into<(PropertyKey, PropertyValue)> for Property {696	fn into(self) -> (PropertyKey, PropertyValue) {697		(self.key, self.value)698	}699}700701#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]702#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]703pub struct PropertyKeyPermission {704	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]705	pub key: PropertyKey,706707	pub permission: PropertyPermission,708}709710impl Into<(PropertyKey, PropertyPermission)> for PropertyKeyPermission {711	fn into(self) -> (PropertyKey, PropertyPermission) {712		(self.key, self.permission)713	}714}715716#[derive(Debug)]717pub enum PropertiesError {718	NoSpaceForProperty,719	PropertyLimitReached,720	InvalidCharacterInPropertyKey,721	PropertyKeyIsTooLong,722	EmptyPropertyKey,723}724725#[derive(Encode, Decode, MaxEncodedLen, TypeInfo, PartialEq, Clone, Copy)]726pub enum PropertyScope {727	None,728	Rmrk,729}730731impl PropertyScope {732	pub fn apply(self, key: PropertyKey) -> Result<PropertyKey, PropertiesError> {733		let scope_str: &[u8] = match self {734			Self::None => return Ok(key),735			Self::Rmrk => b"rmrk",736		};737738		[scope_str, b":", key.as_slice()]739			.concat()740			.try_into()741			.map_err(|_| PropertiesError::PropertyKeyIsTooLong)742	}743}744745pub trait TrySetProperty: Sized {746	type Value;747748	fn try_scoped_set(749		&mut self,750		scope: PropertyScope,751		key: PropertyKey,752		value: Self::Value,753	) -> Result<(), PropertiesError>;754755	fn try_scoped_set_from_iter<I, KV>(756		&mut self,757		scope: PropertyScope,758		iter: I,759	) -> Result<(), PropertiesError>760	where761		I: Iterator<Item = KV>,762		KV: Into<(PropertyKey, Self::Value)>,763	{764		for kv in iter {765			let (key, value) = kv.into();766			self.try_scoped_set(scope, key, value)?;767		}768769		Ok(())770	}771772	fn try_set(&mut self, key: PropertyKey, value: Self::Value) -> Result<(), PropertiesError> {773		self.try_scoped_set(PropertyScope::None, key, value)774	}775776	fn try_set_from_iter<I, KV>(&mut self, iter: I) -> Result<(), PropertiesError>777	where778		I: Iterator<Item = KV>,779		KV: Into<(PropertyKey, Self::Value)>,780	{781		self.try_scoped_set_from_iter(PropertyScope::None, iter)782	}783}784785#[derive(Encode, Decode, TypeInfo, Derivative, Clone, PartialEq, MaxEncodedLen)]786#[derivative(Default(bound = ""))]787pub struct PropertiesMap<Value>(788	BoundedBTreeMap<PropertyKey, Value, ConstU32<MAX_PROPERTIES_PER_ITEM>>,789);790791impl<Value> PropertiesMap<Value> {792	pub fn new() -> Self {793		Self(BoundedBTreeMap::new())794	}795796	pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<Value>, PropertiesError> {797		Self::check_property_key(key)?;798799		Ok(self.0.remove(key))800	}801802	pub fn get(&self, key: &PropertyKey) -> Option<&Value> {803		self.0.get(key)804	}805806	pub fn contains_key(&self, key: &PropertyKey) -> bool {807		self.0.contains_key(key)808	}809810	fn check_property_key(key: &PropertyKey) -> Result<(), PropertiesError> {811		if key.is_empty() {812			return Err(PropertiesError::EmptyPropertyKey);813		}814815		for byte in key.as_slice().iter() {816			let byte = *byte;817818			if !byte.is_ascii_alphanumeric() && byte != b'_' && byte != b'-' && byte != b'.' {819				return Err(PropertiesError::InvalidCharacterInPropertyKey);820			}821		}822823		Ok(())824	}825}826827impl<Value> IntoIterator for PropertiesMap<Value> {828	type Item = (PropertyKey, Value);829	type IntoIter = <830		BoundedBTreeMap<831			PropertyKey,832			Value,833			ConstU32<MAX_PROPERTIES_PER_ITEM>834		> as IntoIterator835	>::IntoIter;836837	fn into_iter(self) -> Self::IntoIter {838		self.0.into_iter()839	}840}841842impl<Value> TrySetProperty for PropertiesMap<Value> {843	type Value = Value;844845	fn try_scoped_set(846		&mut self,847		scope: PropertyScope,848		key: PropertyKey,849		value: Self::Value,850	) -> Result<(), PropertiesError> {851		Self::check_property_key(&key)?;852853		let key = scope.apply(key)?;854		self.0855			.try_insert(key, value)856			.map_err(|_| PropertiesError::PropertyLimitReached)?;857858		Ok(())859	}860}861862pub type PropertiesPermissionMap = PropertiesMap<PropertyPermission>;863864#[derive(Encode, Decode, TypeInfo, Clone, PartialEq, MaxEncodedLen)]865pub struct Properties {866	map: PropertiesMap<PropertyValue>,867	consumed_space: u32,868	space_limit: u32,869}870871impl Properties {872	pub fn new(space_limit: u32) -> Self {873		Self {874			map: PropertiesMap::new(),875			consumed_space: 0,876			space_limit,877		}878	}879880	pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<PropertyValue>, PropertiesError> {881		let value = self.map.remove(key)?;882883		if let Some(ref value) = value {884			let value_len = value.len() as u32;885			self.consumed_space -= value_len;886		}887888		Ok(value)889	}890891	pub fn get(&self, key: &PropertyKey) -> Option<&PropertyValue> {892		self.map.get(key)893	}894}895896impl IntoIterator for Properties {897	type Item = (PropertyKey, PropertyValue);898	type IntoIter = <PropertiesMap<PropertyValue> as IntoIterator>::IntoIter;899900	fn into_iter(self) -> Self::IntoIter {901		self.map.into_iter()902	}903}904905impl TrySetProperty for Properties {906	type Value = PropertyValue;907908	fn try_scoped_set(909		&mut self,910		scope: PropertyScope,911		key: PropertyKey,912		value: Self::Value,913	) -> Result<(), PropertiesError> {914		let value_len = value.len();915916		if self.consumed_space as usize + value_len > self.space_limit as usize917			&& !cfg!(feature = "runtime-benchmarks")918		{919			return Err(PropertiesError::NoSpaceForProperty);920		}921922		self.map.try_scoped_set(scope, key, value)?;923924		self.consumed_space += value_len as u32;925926		Ok(())927	}928}929930pub struct CollectionProperties;931932impl Get<Properties> for CollectionProperties {933	fn get() -> Properties {934		Properties::new(MAX_COLLECTION_PROPERTIES_SIZE)935	}936}937938pub struct TokenProperties;939940impl Get<Properties> for TokenProperties {941	fn get() -> Properties {942		Properties::new(MAX_TOKEN_PROPERTIES_SIZE)943	}944}945946// RMRK947// todo document?948parameter_types! {949	#[derive(PartialEq, TypeInfo)]950	pub const RmrkStringLimit: u32 = 128;951	#[derive(PartialEq)]952	pub const RmrkCollectionSymbolLimit: u32 = MAX_TOKEN_PREFIX_LENGTH;953	#[derive(PartialEq)]954	pub const RmrkResourceSymbolLimit: u32 = 10;955	#[derive(PartialEq)]956	pub const RmrkBaseSymbolLimit: u32 = MAX_TOKEN_PREFIX_LENGTH;957	#[derive(PartialEq)]958	pub const RmrkKeyLimit: u32 = 32;959	#[derive(PartialEq)]960	pub const RmrkValueLimit: u32 = 256;961	#[derive(PartialEq)]962	pub const RmrkMaxCollectionsEquippablePerPart: u32 = 100;963	#[derive(PartialEq)]964	pub const MaxPropertiesPerTheme: u32 = 5;965	#[derive(PartialEq)]966	pub const RmrkPartsLimit: u32 = 25;967	#[derive(PartialEq)]968	pub const RmrkMaxPriorities: u32 = 25;969	#[derive(PartialEq)]970	pub const MaxResourcesOnMint: u32 = 100;971}972973impl From<RmrkCollectionId> for CollectionId {974	fn from(id: RmrkCollectionId) -> Self {975		Self(id)976	}977}978979impl From<RmrkNftId> for TokenId {980	fn from(id: RmrkNftId) -> Self {981		Self(id)982	}983}984985pub type RmrkCollectionInfo<AccountId> =986	CollectionInfo<RmrkString, RmrkCollectionSymbol, AccountId>;987pub type RmrkInstanceInfo<AccountId> = NftInfo<AccountId, Permill, RmrkString>;988pub type RmrkResourceInfo = ResourceInfo<RmrkString, RmrkBoundedParts>;989pub type RmrkPropertyInfo = PropertyInfo<RmrkKeyString, RmrkValueString>;990pub type RmrkBaseInfo<AccountId> = BaseInfo<AccountId, RmrkString>;991pub type BoundedEquippableCollectionIds =992	BoundedVec<RmrkCollectionId, RmrkMaxCollectionsEquippablePerPart>;993pub type RmrkPartType = PartType<RmrkString, BoundedEquippableCollectionIds>;994pub type RmrkEquippableList = EquippableList<BoundedEquippableCollectionIds>;995pub type RmrkThemeProperty = ThemeProperty<RmrkString>;996pub type RmrkTheme = Theme<RmrkString, Vec<RmrkThemeProperty>>;997pub type RmrkBoundedTheme = Theme<RmrkString, BoundedVec<RmrkThemeProperty, MaxPropertiesPerTheme>>;998pub type RmrkResourceTypes = ResourceTypes<RmrkString, RmrkBoundedParts>;9991000pub type RmrkBasicResource = BasicResource<RmrkString>;1001pub type RmrkComposableResource = ComposableResource<RmrkString, RmrkBoundedParts>;1002pub type RmrkSlotResource = SlotResource<RmrkString>;10031004pub type RmrkString = BoundedVec<u8, RmrkStringLimit>;1005pub type RmrkCollectionSymbol = BoundedVec<u8, RmrkCollectionSymbolLimit>;1006pub type RmrkBaseSymbol = BoundedVec<u8, RmrkBaseSymbolLimit>;1007pub type RmrkKeyString = BoundedVec<u8, RmrkKeyLimit>;1008pub type RmrkValueString = BoundedVec<u8, RmrkValueLimit>;1009pub type RmrkBoundedResource = BoundedVec<u8, RmrkResourceSymbolLimit>;1010pub type RmrkBoundedParts = BoundedVec<RmrkPartId, RmrkPartsLimit>; // todo make sure it is needed10111012pub type RmrkRpcString = Vec<u8>;1013pub type RmrkThemeName = RmrkRpcString;1014pub 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: Option<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>,537	pub pieces: u128,538}539540#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]541#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]542pub enum MetaUpdatePermission {543	ItemOwner,544	Admin,545	None,546}547548#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]549#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]550pub enum CreateItemData {551	NFT(CreateNftData),552	Fungible(CreateFungibleData),553	ReFungible(CreateReFungibleData),554}555556#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]557#[derivative(Debug)]558pub struct CreateNftExData<CrossAccountId> {559	#[derivative(Debug(format_with = "bounded::vec_debug"))]560	pub properties: CollectionPropertiesVec,561	pub owner: CrossAccountId,562}563564#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]565#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]566pub struct CreateRefungibleExData<CrossAccountId> {567	#[derivative(Debug(format_with = "bounded::vec_debug"))]568	pub const_data: BoundedVec<u8, CustomDataLimit>,569	#[derivative(Debug(format_with = "bounded::map_debug"))]570	pub users: BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,571}572573#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]574#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]575pub enum CreateItemExData<CrossAccountId> {576	NFT(577		#[derivative(Debug(format_with = "bounded::vec_debug"))]578		BoundedVec<CreateNftExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,579	),580	Fungible(581		#[derivative(Debug(format_with = "bounded::map_debug"))]582		BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,583	),584	/// Many tokens, each may have only one owner585	RefungibleMultipleItems(586		#[derivative(Debug(format_with = "bounded::vec_debug"))]587		BoundedVec<CreateRefungibleExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,588	),589	/// Single token, which may have many owners590	RefungibleMultipleOwners(CreateRefungibleExData<CrossAccountId>),591}592593impl CreateItemData {594	pub fn data_size(&self) -> usize {595		match self {596			CreateItemData::ReFungible(data) => data.const_data.len(),597			_ => 0,598		}599	}600}601602impl From<CreateNftData> for CreateItemData {603	fn from(item: CreateNftData) -> Self {604		CreateItemData::NFT(item)605	}606}607608impl From<CreateReFungibleData> for CreateItemData {609	fn from(item: CreateReFungibleData) -> Self {610		CreateItemData::ReFungible(item)611	}612}613614impl From<CreateFungibleData> for CreateItemData {615	fn from(item: CreateFungibleData) -> Self {616		CreateItemData::Fungible(item)617	}618}619620#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]621#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]622// todo possibly rename to be used generally as an address pair623pub struct TokenChild {624	pub token: TokenId,625	pub collection: CollectionId,626}627628#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]629#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]630pub struct CollectionStats {631	pub created: u32,632	pub destroyed: u32,633	pub alive: u32,634}635636#[derive(Encode, Decode, Clone, Debug)]637#[cfg_attr(feature = "std", derive(PartialEq))]638pub struct PhantomType<T>(core::marker::PhantomData<T>);639640impl<T: TypeInfo + 'static> TypeInfo for PhantomType<T> {641	type Identity = PhantomType<T>;642643	fn type_info() -> scale_info::Type {644		use scale_info::{645			Type, Path,646			build::{FieldsBuilder, UnnamedFields},647			type_params,648		};649		Type::builder()650			.path(Path::new("up_data_structs", "PhantomType"))651			.type_params(type_params!(T))652			.composite(<FieldsBuilder<UnnamedFields>>::default().field(|b| b.ty::<[T; 0]>()))653	}654}655impl<T> MaxEncodedLen for PhantomType<T> {656	fn max_encoded_len() -> usize {657		0658	}659}660661pub type BoundedBytes<S> = BoundedVec<u8, S>;662663pub type AuxPropertyValue = BoundedBytes<ConstU32<MAX_AUX_PROPERTY_VALUE_LENGTH>>;664665pub type PropertyKey = BoundedBytes<ConstU32<MAX_PROPERTY_KEY_LENGTH>>;666pub type PropertyValue = BoundedBytes<ConstU32<MAX_PROPERTY_VALUE_LENGTH>>;667668#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]669#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]670pub struct PropertyPermission {671	pub mutable: bool,672	pub collection_admin: bool,673	pub token_owner: bool,674}675676impl PropertyPermission {677	pub fn none() -> Self {678		Self {679			mutable: true,680			collection_admin: false,681			token_owner: false,682		}683	}684}685686#[derive(Encode, Decode, Debug, TypeInfo, Clone, PartialEq, MaxEncodedLen)]687#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]688pub struct Property {689	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]690	pub key: PropertyKey,691692	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]693	pub value: PropertyValue,694}695696impl Into<(PropertyKey, PropertyValue)> for Property {697	fn into(self) -> (PropertyKey, PropertyValue) {698		(self.key, self.value)699	}700}701702#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]703#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]704pub struct PropertyKeyPermission {705	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]706	pub key: PropertyKey,707708	pub permission: PropertyPermission,709}710711impl Into<(PropertyKey, PropertyPermission)> for PropertyKeyPermission {712	fn into(self) -> (PropertyKey, PropertyPermission) {713		(self.key, self.permission)714	}715}716717#[derive(Debug)]718pub enum PropertiesError {719	NoSpaceForProperty,720	PropertyLimitReached,721	InvalidCharacterInPropertyKey,722	PropertyKeyIsTooLong,723	EmptyPropertyKey,724}725726#[derive(Encode, Decode, MaxEncodedLen, TypeInfo, PartialEq, Clone, Copy)]727pub enum PropertyScope {728	None,729	Rmrk,730}731732impl PropertyScope {733	pub fn apply(self, key: PropertyKey) -> Result<PropertyKey, PropertiesError> {734		let scope_str: &[u8] = match self {735			Self::None => return Ok(key),736			Self::Rmrk => b"rmrk",737		};738739		[scope_str, b":", key.as_slice()]740			.concat()741			.try_into()742			.map_err(|_| PropertiesError::PropertyKeyIsTooLong)743	}744}745746pub trait TrySetProperty: Sized {747	type Value;748749	fn try_scoped_set(750		&mut self,751		scope: PropertyScope,752		key: PropertyKey,753		value: Self::Value,754	) -> Result<(), PropertiesError>;755756	fn try_scoped_set_from_iter<I, KV>(757		&mut self,758		scope: PropertyScope,759		iter: I,760	) -> Result<(), PropertiesError>761	where762		I: Iterator<Item = KV>,763		KV: Into<(PropertyKey, Self::Value)>,764	{765		for kv in iter {766			let (key, value) = kv.into();767			self.try_scoped_set(scope, key, value)?;768		}769770		Ok(())771	}772773	fn try_set(&mut self, key: PropertyKey, value: Self::Value) -> Result<(), PropertiesError> {774		self.try_scoped_set(PropertyScope::None, key, value)775	}776777	fn try_set_from_iter<I, KV>(&mut self, iter: I) -> Result<(), PropertiesError>778	where779		I: Iterator<Item = KV>,780		KV: Into<(PropertyKey, Self::Value)>,781	{782		self.try_scoped_set_from_iter(PropertyScope::None, iter)783	}784}785786#[derive(Encode, Decode, TypeInfo, Derivative, Clone, PartialEq, MaxEncodedLen)]787#[derivative(Default(bound = ""))]788pub struct PropertiesMap<Value>(789	BoundedBTreeMap<PropertyKey, Value, ConstU32<MAX_PROPERTIES_PER_ITEM>>,790);791792impl<Value> PropertiesMap<Value> {793	pub fn new() -> Self {794		Self(BoundedBTreeMap::new())795	}796797	pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<Value>, PropertiesError> {798		Self::check_property_key(key)?;799800		Ok(self.0.remove(key))801	}802803	pub fn get(&self, key: &PropertyKey) -> Option<&Value> {804		self.0.get(key)805	}806807	pub fn contains_key(&self, key: &PropertyKey) -> bool {808		self.0.contains_key(key)809	}810811	fn check_property_key(key: &PropertyKey) -> Result<(), PropertiesError> {812		if key.is_empty() {813			return Err(PropertiesError::EmptyPropertyKey);814		}815816		for byte in key.as_slice().iter() {817			let byte = *byte;818819			if !byte.is_ascii_alphanumeric() && byte != b'_' && byte != b'-' && byte != b'.' {820				return Err(PropertiesError::InvalidCharacterInPropertyKey);821			}822		}823824		Ok(())825	}826}827828impl<Value> IntoIterator for PropertiesMap<Value> {829	type Item = (PropertyKey, Value);830	type IntoIter = <831		BoundedBTreeMap<832			PropertyKey,833			Value,834			ConstU32<MAX_PROPERTIES_PER_ITEM>835		> as IntoIterator836	>::IntoIter;837838	fn into_iter(self) -> Self::IntoIter {839		self.0.into_iter()840	}841}842843impl<Value> TrySetProperty for PropertiesMap<Value> {844	type Value = Value;845846	fn try_scoped_set(847		&mut self,848		scope: PropertyScope,849		key: PropertyKey,850		value: Self::Value,851	) -> Result<(), PropertiesError> {852		Self::check_property_key(&key)?;853854		let key = scope.apply(key)?;855		self.0856			.try_insert(key, value)857			.map_err(|_| PropertiesError::PropertyLimitReached)?;858859		Ok(())860	}861}862863pub type PropertiesPermissionMap = PropertiesMap<PropertyPermission>;864865#[derive(Encode, Decode, TypeInfo, Clone, PartialEq, MaxEncodedLen)]866pub struct Properties {867	map: PropertiesMap<PropertyValue>,868	consumed_space: u32,869	space_limit: u32,870}871872impl Properties {873	pub fn new(space_limit: u32) -> Self {874		Self {875			map: PropertiesMap::new(),876			consumed_space: 0,877			space_limit,878		}879	}880881	pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<PropertyValue>, PropertiesError> {882		let value = self.map.remove(key)?;883884		if let Some(ref value) = value {885			let value_len = value.len() as u32;886			self.consumed_space -= value_len;887		}888889		Ok(value)890	}891892	pub fn get(&self, key: &PropertyKey) -> Option<&PropertyValue> {893		self.map.get(key)894	}895}896897impl IntoIterator for Properties {898	type Item = (PropertyKey, PropertyValue);899	type IntoIter = <PropertiesMap<PropertyValue> as IntoIterator>::IntoIter;900901	fn into_iter(self) -> Self::IntoIter {902		self.map.into_iter()903	}904}905906impl TrySetProperty for Properties {907	type Value = PropertyValue;908909	fn try_scoped_set(910		&mut self,911		scope: PropertyScope,912		key: PropertyKey,913		value: Self::Value,914	) -> Result<(), PropertiesError> {915		let value_len = value.len();916917		if self.consumed_space as usize + value_len > self.space_limit as usize918			&& !cfg!(feature = "runtime-benchmarks")919		{920			return Err(PropertiesError::NoSpaceForProperty);921		}922923		self.map.try_scoped_set(scope, key, value)?;924925		self.consumed_space += value_len as u32;926927		Ok(())928	}929}930931pub struct CollectionProperties;932933impl Get<Properties> for CollectionProperties {934	fn get() -> Properties {935		Properties::new(MAX_COLLECTION_PROPERTIES_SIZE)936	}937}938939pub struct TokenProperties;940941impl Get<Properties> for TokenProperties {942	fn get() -> Properties {943		Properties::new(MAX_TOKEN_PROPERTIES_SIZE)944	}945}946947// RMRK948// todo document?949parameter_types! {950	#[derive(PartialEq, TypeInfo)]951	pub const RmrkStringLimit: u32 = 128;952	#[derive(PartialEq)]953	pub const RmrkCollectionSymbolLimit: u32 = MAX_TOKEN_PREFIX_LENGTH;954	#[derive(PartialEq)]955	pub const RmrkResourceSymbolLimit: u32 = 10;956	#[derive(PartialEq)]957	pub const RmrkBaseSymbolLimit: u32 = MAX_TOKEN_PREFIX_LENGTH;958	#[derive(PartialEq)]959	pub const RmrkKeyLimit: u32 = 32;960	#[derive(PartialEq)]961	pub const RmrkValueLimit: u32 = 256;962	#[derive(PartialEq)]963	pub const RmrkMaxCollectionsEquippablePerPart: u32 = 100;964	#[derive(PartialEq)]965	pub const MaxPropertiesPerTheme: u32 = 5;966	#[derive(PartialEq)]967	pub const RmrkPartsLimit: u32 = 25;968	#[derive(PartialEq)]969	pub const RmrkMaxPriorities: u32 = 25;970	#[derive(PartialEq)]971	pub const MaxResourcesOnMint: u32 = 100;972}973974impl From<RmrkCollectionId> for CollectionId {975	fn from(id: RmrkCollectionId) -> Self {976		Self(id)977	}978}979980impl From<RmrkNftId> for TokenId {981	fn from(id: RmrkNftId) -> Self {982		Self(id)983	}984}985986pub type RmrkCollectionInfo<AccountId> =987	CollectionInfo<RmrkString, RmrkCollectionSymbol, AccountId>;988pub type RmrkInstanceInfo<AccountId> = NftInfo<AccountId, Permill, RmrkString>;989pub type RmrkResourceInfo = ResourceInfo<RmrkString, RmrkBoundedParts>;990pub type RmrkPropertyInfo = PropertyInfo<RmrkKeyString, RmrkValueString>;991pub type RmrkBaseInfo<AccountId> = BaseInfo<AccountId, RmrkString>;992pub type BoundedEquippableCollectionIds =993	BoundedVec<RmrkCollectionId, RmrkMaxCollectionsEquippablePerPart>;994pub type RmrkPartType = PartType<RmrkString, BoundedEquippableCollectionIds>;995pub type RmrkEquippableList = EquippableList<BoundedEquippableCollectionIds>;996pub type RmrkThemeProperty = ThemeProperty<RmrkString>;997pub type RmrkTheme = Theme<RmrkString, Vec<RmrkThemeProperty>>;998pub type RmrkBoundedTheme = Theme<RmrkString, BoundedVec<RmrkThemeProperty, MaxPropertiesPerTheme>>;999pub type RmrkResourceTypes = ResourceTypes<RmrkString, RmrkBoundedParts>;10001001pub type RmrkBasicResource = BasicResource<RmrkString>;1002pub type RmrkComposableResource = ComposableResource<RmrkString, RmrkBoundedParts>;1003pub type RmrkSlotResource = SlotResource<RmrkString>;10041005pub type RmrkString = BoundedVec<u8, RmrkStringLimit>;1006pub type RmrkCollectionSymbol = BoundedVec<u8, RmrkCollectionSymbolLimit>;1007pub type RmrkBaseSymbol = BoundedVec<u8, RmrkBaseSymbolLimit>;1008pub type RmrkKeyString = BoundedVec<u8, RmrkKeyLimit>;1009pub type RmrkValueString = BoundedVec<u8, RmrkValueLimit>;1010pub type RmrkBoundedResource = BoundedVec<u8, RmrkResourceSymbolLimit>;1011pub type RmrkBoundedParts = BoundedVec<RmrkPartId, RmrkPartsLimit>; // todo make sure it is needed10121013pub type RmrkRpcString = Vec<u8>;1014pub type RmrkThemeName = RmrkRpcString;1015pub type RmrkPropertyKey = RmrkRpcString;
modifiedruntime/common/src/runtime_apis.rsdiffbeforeafterboth
--- a/runtime/common/src/runtime_apis.rs
+++ b/runtime/common/src/runtime_apis.rs
@@ -89,7 +89,8 @@
                 ) -> Result<TokenData<CrossAccountId>, DispatchError> {
                     let token_data = TokenData {
                         properties: Self::token_properties(collection, token_id, keys)?,
-                        owner: Self::token_owner(collection, token_id)?
+                        owner: Self::token_owner(collection, token_id)?,
+                        pieces: Self::total_pieces(collection, token_id)?
                     };
 
                     Ok(token_data)
modifiedtests/src/createItem.test.tsdiffbeforeafterboth
--- a/tests/src/createItem.test.ts
+++ b/tests/src/createItem.test.ts
@@ -98,47 +98,57 @@
     await createItemWithPropsExpectSuccess(alice, newCollectionID, createMode, [{key: 'key1', value: 'val1'}]);
   });
 
-  it.only('Check total pieces of Fungible token', async () => {
+  it('Check total pieces of Fungible token', async () => {
     await usingApi(async api => {
       const createMode = 'Fungible';
       const collectionId = await createCollectionExpectSuccess({mode: {type: createMode, decimalPoints: 0}});
+      const amountPieces = 10n;
       const tokenId = await createItemExpectSuccess(alice, collectionId, createMode, bob.address);
       {
         const totalPieces = await api.rpc.unique.totalPieces(collectionId, tokenId);
         expect(totalPieces.isSome).to.be.true;
-        expect(totalPieces.unwrap().toBigInt()).to.be.eq(10n);
+        expect(totalPieces.unwrap().toBigInt()).to.be.eq(amountPieces);
       }
 
       await transferExpectSuccess(collectionId, tokenId, bob, alice, 1, createMode);
       {
         const totalPieces = await api.rpc.unique.totalPieces(collectionId, tokenId);
         expect(totalPieces.isSome).to.be.true;
-        expect(totalPieces.unwrap().toBigInt()).to.be.eq(10n);
+        expect(totalPieces.unwrap().toBigInt()).to.be.eq(amountPieces);
       }
+
+      const totalPieces = (await api.rpc.unique.tokenData(collectionId, tokenId, [])).pieces;
+      expect(totalPieces.isSome).to.be.true;
+      expect(totalPieces.unwrap().toBigInt()).to.be.eq(amountPieces);
     });
   });
 
-  it.only('Check total pieces of NFT token', async () => {
+  it('Check total pieces of NFT token', async () => {
     await usingApi(async api => {
       const createMode = 'NFT';
       const collectionId = await createCollectionExpectSuccess({mode: {type: createMode}});
+      const amountPieces = 1n;
       const tokenId = await createItemExpectSuccess(alice, collectionId, createMode, bob.address);
       {
         const totalPieces = await api.rpc.unique.totalPieces(collectionId, tokenId);
         expect(totalPieces.isSome).to.be.true;
-        expect(totalPieces.unwrap().toBigInt()).to.be.eq(1n);
+        expect(totalPieces.unwrap().toBigInt()).to.be.eq(amountPieces);
       }
 
       await transferExpectSuccess(collectionId, tokenId, bob, alice, 1, createMode);
       {
         const totalPieces = await api.rpc.unique.totalPieces(collectionId, tokenId);
         expect(totalPieces.isSome).to.be.true;
-        expect(totalPieces.unwrap().toBigInt()).to.be.eq(1n);
+        expect(totalPieces.unwrap().toBigInt()).to.be.eq(amountPieces);
       }
+
+      const totalPieces = (await api.rpc.unique.tokenData(collectionId, tokenId, [])).pieces;
+      expect(totalPieces.isSome).to.be.true;
+      expect(totalPieces.unwrap().toBigInt()).to.be.eq(amountPieces);
     });
   });
 
-  it.only('Check total pieces of ReFungible token', async () => {
+  it('Check total pieces of ReFungible token', async () => {
     await usingApi(async api => {
       const createMode = 'ReFungible';
       const createCollectionResult = await createCollection(api, alice, {mode: {type: createMode}});
@@ -157,6 +167,10 @@
         expect(totalPieces.isSome).to.be.true;
         expect(totalPieces.unwrap().toBigInt()).to.be.eq(amountPieces);
       }
+
+      const totalPieces = (await api.rpc.unique.tokenData(collectionId, tokenId, [])).pieces;
+      expect(totalPieces.isSome).to.be.true;
+      expect(totalPieces.unwrap().toBigInt()).to.be.eq(amountPieces);
     });
   });
 });
@@ -233,4 +247,37 @@
       await createItemWithPropsExpectFailure(alice, newCollectionID, 'NFT', [{key: 'k', value: 'vvvvvv'.repeat(5000)}, {key: 'k2', value: 'vvv'.repeat(5000)}]);
     });
   });
+
+  it('Check total pieces for invalid Fungible token', async () => {
+    await usingApi(async api => {
+      const createCollectionResult = await createCollection(api, alice, {mode: {type: 'Fungible', decimalPoints: 0}});
+      const collectionId  = createCollectionResult.collectionId;
+      const invalidTokenId = 1000_000;
+      
+      expect((await api.rpc.unique.totalPieces(collectionId, invalidTokenId)).isNone).to.be.true;
+      expect((await api.rpc.unique.tokenData(collectionId, invalidTokenId, [])).pieces.isNone).to.be.true;
+    });
+  });
+
+  it('Check total pieces for invalid NFT token', async () => {
+    await usingApi(async api => {
+      const createCollectionResult = await createCollection(api, alice, {mode: {type: 'NFT'}});
+      const collectionId  = createCollectionResult.collectionId;
+      const invalidTokenId = 1000_000;
+      
+      expect((await api.rpc.unique.totalPieces(collectionId, invalidTokenId)).isNone).to.be.true;
+      expect((await api.rpc.unique.tokenData(collectionId, invalidTokenId, [])).pieces.isNone).to.be.true;
+    });
+  });
+
+  it('Check total pieces for invalid Refungible token', async () => {
+    await usingApi(async api => {
+      const createCollectionResult = await createCollection(api, alice, {mode: {type: 'ReFungible'}});
+      const collectionId  = createCollectionResult.collectionId;
+      const invalidTokenId = 1000_000;
+      
+      expect((await api.rpc.unique.totalPieces(collectionId, invalidTokenId)).isNone).to.be.true;
+      expect((await api.rpc.unique.tokenData(collectionId, invalidTokenId, [])).pieces.isNone).to.be.true;
+    });
+  });
 });