git.delta.rocks / unique-network / refs/commits / 7c4183b4cb3a

difftreelog

feat(rmrk-rpc) nft resources and priorities

Fahrrader2022-05-26parent: #5c5d937.patch.diff
in: master

6 files changed

modifiedpallets/proxy-rmrk-core/src/lib.rsdiffbeforeafterboth
--- a/pallets/proxy-rmrk-core/src/lib.rs
+++ b/pallets/proxy-rmrk-core/src/lib.rs
@@ -486,9 +486,8 @@
         }
     }
 
-    // should this even be here, might displace it to common/nonfungible -- but they did not need it, only rmrk does
     pub fn collection_exists(collection_id: CollectionId) -> bool {
-        <pallet_common::CollectionById<T>>::contains_key(collection_id)
+        <CollectionHandle<T>>::try_get(collection_id).is_ok()
     }
 
     pub fn nft_exists(collection_id: CollectionId, nft_id: TokenId) -> bool {
modifiedpallets/proxy-rmrk-core/src/misc.rsdiffbeforeafterboth
--- a/pallets/proxy-rmrk-core/src/misc.rs
+++ b/pallets/proxy-rmrk-core/src/misc.rs
@@ -26,18 +26,6 @@
     }
 }
 
-pub trait RmrkRebind<T, S> {
-    fn rebind(&self) -> BoundedVec<u8, S>;
-}
-
-impl<T, S> RmrkRebind<T, S> for BoundedVec<u8, T> where BoundedVec<u8, S>: TryFrom<Vec<u8>> {
-    fn rebind(&self) -> BoundedVec<u8, S> {
-        BoundedVec::<u8, S>::try_from(
-            self.clone().into_inner()
-        ).unwrap_or_default()
-    }
-}
-
 #[derive(Encode, Decode, PartialEq, Eq)]
 pub enum CollectionType {
     Regular,
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;3839pub mod rmrk;4041// RMRK42use rmrk::{43	CollectionInfo, NftInfo, ResourceInfo, PropertyInfo, BaseInfo, PartType, Theme, ThemeProperty,44};45pub use rmrk::{46	primitives::{47		CollectionId as RmrkCollectionId, NftId as RmrkNftId, BaseId as RmrkBaseId,48		PartId as RmrkPartId, ResourceId as RmrkResourceId,49	},50	NftChild as RmrkNftChild, AccountIdOrCollectionNftTuple as RmrkAccountIdOrCollectionNftTuple,51	FixedPart as RmrkFixedPart, SlotPart as RmrkSlotPart, EquippableList as RmrkEquippableList,52};5354mod bounded;55pub mod budget;56pub mod mapping;57mod migration;5859pub const MAX_DECIMAL_POINTS: DecimalPoints = 30;60pub const MAX_REFUNGIBLE_PIECES: u128 = 1_000_000_000_000_000_000_000;61pub const MAX_SPONSOR_TIMEOUT: u32 = 10_368_000;6263pub const MAX_TOKEN_OWNERSHIP: u32 = if cfg!(not(feature = "limit-testing")) {64	100_00065} else {66	1067};68pub const COLLECTION_NUMBER_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {69	100_00070} else {71	1072};73pub const CUSTOM_DATA_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {74	204875} else {76	1077};78pub const COLLECTION_ADMINS_LIMIT: u32 = 5;79pub const COLLECTION_TOKEN_LIMIT: u32 = u32::MAX;80pub const ACCOUNT_TOKEN_OWNERSHIP_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {81	1_000_00082} else {83	1084};8586// Timeouts for item types in passed blocks87pub const NFT_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;88pub const FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;89pub const REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;9091pub const SPONSOR_APPROVE_TIMEOUT: u32 = 5;9293// Schema limits94pub const OFFCHAIN_SCHEMA_LIMIT: u32 = 8192;95pub const VARIABLE_ON_CHAIN_SCHEMA_LIMIT: u32 = 8192;96pub const CONST_ON_CHAIN_SCHEMA_LIMIT: u32 = 32768;9798pub const COLLECTION_FIELD_LIMIT: u32 = CONST_ON_CHAIN_SCHEMA_LIMIT;99100pub const MAX_COLLECTION_NAME_LENGTH: u32 = 64;101pub const MAX_COLLECTION_DESCRIPTION_LENGTH: u32 = 256;102pub const MAX_TOKEN_PREFIX_LENGTH: u32 = 16;103104pub const MAX_PROPERTY_KEY_LENGTH: u32 = 256;105pub const MAX_PROPERTY_VALUE_LENGTH: u32 = 32768;106pub const MAX_PROPERTIES_PER_ITEM: u32 = 64;107108pub const MAX_COLLECTION_PROPERTIES_SIZE: u32 = 40960;109pub const MAX_TOKEN_PROPERTIES_SIZE: u32 = 32768;110111// RMRK constants112pub const RMRK_STRING_LIMIT: u32 = 128;113pub const RMRK_COLLECTION_SYMBOL_LIMIT: u32 = 100;114pub const RMRK_RESOURCE_SYMBOL_LIMIT: u32 = 10;115pub const RMRK_KEY_LIMIT: u32 = 32;116pub const RMRK_VALUE_LIMIT: u32 = 256;117118/// How much items can be created per single119/// create_many call120pub const MAX_ITEMS_PER_BATCH: u32 = 200;121122pub type CustomDataLimit = ConstU32<CUSTOM_DATA_LIMIT>;123124#[derive(125	Encode,126	Decode,127	PartialEq,128	Eq,129	PartialOrd,130	Ord,131	Clone,132	Copy,133	Debug,134	Default,135	TypeInfo,136	MaxEncodedLen,137)]138#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]139pub struct CollectionId(pub u32);140impl EncodeLike<u32> for CollectionId {}141impl EncodeLike<CollectionId> for u32 {}142143#[derive(144	Encode,145	Decode,146	PartialEq,147	Eq,148	PartialOrd,149	Ord,150	Clone,151	Copy,152	Debug,153	Default,154	TypeInfo,155	MaxEncodedLen,156)]157#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]158pub struct TokenId(pub u32);159impl EncodeLike<u32> for TokenId {}160impl EncodeLike<TokenId> for u32 {}161162impl TokenId {163	pub fn try_next(self) -> Result<TokenId, ArithmeticError> {164		self.0165			.checked_add(1)166			.ok_or(ArithmeticError::Overflow)167			.map(Self)168	}169}170171impl From<TokenId> for U256 {172	fn from(t: TokenId) -> Self {173		t.0.into()174	}175}176177impl TryFrom<U256> for TokenId {178	type Error = &'static str;179180	fn try_from(value: U256) -> Result<Self, Self::Error> {181		Ok(TokenId(value.try_into().map_err(|_| "too large token id")?))182	}183}184185#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]186#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]187pub struct TokenData<CrossAccountId> {188	pub const_data: Vec<u8>,189	pub properties: Vec<Property>,190	pub owner: Option<CrossAccountId>,191}192193pub struct OverflowError;194impl From<OverflowError> for &'static str {195	fn from(_: OverflowError) -> Self {196		"overflow occured"197	}198}199200pub type DecimalPoints = u8;201202#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]203#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]204pub enum CollectionMode {205	NFT,206	// decimal points207	Fungible(DecimalPoints),208	ReFungible,209}210211impl CollectionMode {212	pub fn id(&self) -> u8 {213		match self {214			CollectionMode::NFT => 1,215			CollectionMode::Fungible(_) => 2,216			CollectionMode::ReFungible => 3,217		}218	}219}220221pub trait SponsoringResolve<AccountId, Call> {222	fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>;223}224225#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]226#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]227pub enum AccessMode {228	Normal,229	AllowList,230}231impl Default for AccessMode {232	fn default() -> Self {233		Self::Normal234	}235}236237#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]238#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]239pub enum SchemaVersion {240	ImageURL,241	Unique,242}243impl Default for SchemaVersion {244	fn default() -> Self {245		Self::ImageURL246	}247}248249#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]250#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]251pub struct Ownership<AccountId> {252	pub owner: AccountId,253	pub fraction: u128,254}255256#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]257#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]258pub enum SponsorshipState<AccountId> {259	/// The fees are applied to the transaction sender260	Disabled,261	Unconfirmed(AccountId),262	/// Transactions are sponsored by specified account263	Confirmed(AccountId),264}265266impl<AccountId> SponsorshipState<AccountId> {267	pub fn sponsor(&self) -> Option<&AccountId> {268		match self {269			Self::Confirmed(sponsor) => Some(sponsor),270			_ => None,271		}272	}273274	pub fn pending_sponsor(&self) -> Option<&AccountId> {275		match self {276			Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),277			_ => None,278		}279	}280281	pub fn confirmed(&self) -> bool {282		matches!(self, Self::Confirmed(_))283	}284}285286impl<T> Default for SponsorshipState<T> {287	fn default() -> Self {288		Self::Disabled289	}290}291292/// Used in storage293#[struct_versioning::versioned(version = 2, upper)]294#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen)]295pub struct Collection<AccountId> {296	pub owner: AccountId,297	pub mode: CollectionMode,298	pub access: AccessMode,299	pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,300	pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,301	pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,302	pub mint_mode: bool,303304	#[version(..2)]305	pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,306307	pub schema_version: SchemaVersion,308	pub sponsorship: SponsorshipState<AccountId>,309310	#[version(..2)]311	pub limits: CollectionLimitsVersion1, // Collection private restrictions312	#[version(2.., upper(limits.into()))]313	pub limits: CollectionLimitsVersion2,314315	#[version(..2)]316	pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,317318	#[version(..2)]319	pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,320321	#[version(..2)]322	pub meta_update_permission: MetaUpdatePermission,323}324325/// Used in RPC calls326#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]327#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]328pub struct RpcCollection<AccountId> {329	pub owner: AccountId,330	pub mode: CollectionMode,331	pub access: AccessMode,332	pub name: Vec<u16>,333	pub description: Vec<u16>,334	pub token_prefix: Vec<u8>,335	pub mint_mode: bool,336	pub offchain_schema: Vec<u8>,337	pub schema_version: SchemaVersion,338	pub sponsorship: SponsorshipState<AccountId>,339	pub limits: CollectionLimits,340	pub const_on_chain_schema: Vec<u8>,341	pub token_property_permissions: Vec<PropertyKeyPermission>,342	pub properties: Vec<Property>,343}344345#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen)]346#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]347pub enum CollectionField {348	ConstOnChainSchema,349	OffchainSchema,350}351352#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Derivative, MaxEncodedLen)]353#[derivative(Debug, Default(bound = ""))]354pub struct CreateCollectionData<AccountId> {355	#[derivative(Default(value = "CollectionMode::NFT"))]356	pub mode: CollectionMode,357	pub access: Option<AccessMode>,358	pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,359	pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,360	pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,361	pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,362	pub schema_version: Option<SchemaVersion>,363	pub pending_sponsor: Option<AccountId>,364	pub limits: Option<CollectionLimits>,365	pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,366	pub token_property_permissions: CollectionPropertiesPermissionsVec,367	pub properties: CollectionPropertiesVec,368}369370pub type CollectionPropertiesPermissionsVec =371	BoundedVec<PropertyKeyPermission, ConstU32<MAX_PROPERTIES_PER_ITEM>>;372373pub type CollectionPropertiesVec =374	BoundedVec<Property, ConstU32<MAX_PROPERTIES_PER_ITEM>>;375376/// All fields are wrapped in `Option`s, where None means chain default377#[struct_versioning::versioned(version = 2, upper)]378#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]379#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]380pub struct CollectionLimits {381	pub account_token_ownership_limit: Option<u32>,382	pub sponsored_data_size: Option<u32>,383384	/// FIXME should we delete this or repurpose it?385	/// None - setVariableMetadata is not sponsored386	/// Some(v) - setVariableMetadata is sponsored387	///           if there is v block between txs388	pub sponsored_data_rate_limit: Option<SponsoringRateLimit>,389	pub token_limit: Option<u32>,390391	// Timeouts for item types in passed blocks392	pub sponsor_transfer_timeout: Option<u32>,393	pub sponsor_approve_timeout: Option<u32>,394	pub owner_can_transfer: Option<bool>,395	pub owner_can_destroy: Option<bool>,396	pub transfers_enabled: Option<bool>,397398	#[version(2.., upper(None))]399	pub nesting_rule: Option<NestingRule>,400}401402impl CollectionLimits {403	pub fn account_token_ownership_limit(&self) -> u32 {404		self.account_token_ownership_limit405			.unwrap_or(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)406			.min(MAX_TOKEN_OWNERSHIP)407	}408	pub fn sponsored_data_size(&self) -> u32 {409		self.sponsored_data_size410			.unwrap_or(CUSTOM_DATA_LIMIT)411			.min(CUSTOM_DATA_LIMIT)412	}413	pub fn token_limit(&self) -> u32 {414		self.token_limit415			.unwrap_or(COLLECTION_TOKEN_LIMIT)416			.min(COLLECTION_TOKEN_LIMIT)417	}418	pub fn sponsor_transfer_timeout(&self, default: u32) -> u32 {419		self.sponsor_transfer_timeout420			.unwrap_or(default)421			.min(MAX_SPONSOR_TIMEOUT)422	}423	pub fn sponsor_approve_timeout(&self) -> u32 {424		self.sponsor_approve_timeout425			.unwrap_or(SPONSOR_APPROVE_TIMEOUT)426			.min(MAX_SPONSOR_TIMEOUT)427	}428	pub fn owner_can_transfer(&self) -> bool {429		self.owner_can_transfer.unwrap_or(true)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	pub fn nesting_rule(&self) -> &NestingRule {447		static DEFAULT: NestingRule = NestingRule::Disabled;448		self.nesting_rule.as_ref().unwrap_or(&DEFAULT)449	}450}451452#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative)]453#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]454#[derivative(Debug)]455pub enum NestingRule {456	/// No one can nest tokens457	Disabled,458	/// Owner can nest any tokens459	Owner,460	/// Owner can nest tokens from specified collections461	OwnerRestricted(462		#[cfg_attr(feature = "serde1", serde(with = "bounded::set_serde"))]463		#[derivative(Debug(format_with = "bounded::set_debug"))]464		BoundedBTreeSet<CollectionId, ConstU32<16>>,465	),466}467468#[derive(Encode, Decode, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]469#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]470pub enum SponsoringRateLimit {471	SponsoringDisabled,472	Blocks(u32),473}474475#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]476#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]477#[derivative(Debug)]478pub struct CreateNftData {479	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]480	#[derivative(Debug(format_with = "bounded::vec_debug"))]481	pub const_data: BoundedVec<u8, CustomDataLimit>,482483	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]484	#[derivative(Debug(format_with = "bounded::vec_debug"))]485	pub properties: CollectionPropertiesVec,486}487488#[derive(Encode, Decode, MaxEncodedLen, Default, Debug, Clone, PartialEq, TypeInfo)]489#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]490pub struct CreateFungibleData {491	pub value: u128,492}493494#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]495#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]496#[derivative(Debug)]497pub struct CreateReFungibleData {498	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]499	#[derivative(Debug(format_with = "bounded::vec_debug"))]500	pub const_data: BoundedVec<u8, CustomDataLimit>,501	pub pieces: u128,502}503504#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]505pub enum MetaUpdatePermission {506	ItemOwner,507	Admin,508	None,509}510511#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]512#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]513pub enum CreateItemData {514	NFT(CreateNftData),515	Fungible(CreateFungibleData),516	ReFungible(CreateReFungibleData),517}518519#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]520#[derivative(Debug)]521pub struct CreateNftExData<CrossAccountId> {522	#[derivative(Debug(format_with = "bounded::vec_debug"))]523	pub const_data: BoundedVec<u8, CustomDataLimit>,524	#[derivative(Debug(format_with = "bounded::vec_debug"))]525	pub properties: CollectionPropertiesVec,526	pub owner: CrossAccountId,527}528529#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]530#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]531pub struct CreateRefungibleExData<CrossAccountId> {532	#[derivative(Debug(format_with = "bounded::vec_debug"))]533	pub const_data: BoundedVec<u8, CustomDataLimit>,534	#[derivative(Debug(format_with = "bounded::map_debug"))]535	pub users: BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,536}537538#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]539#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]540pub enum CreateItemExData<CrossAccountId> {541	NFT(542		#[derivative(Debug(format_with = "bounded::vec_debug"))]543		BoundedVec<CreateNftExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,544	),545	Fungible(546		#[derivative(Debug(format_with = "bounded::map_debug"))]547		BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,548	),549	/// Many tokens, each may have only one owner550	RefungibleMultipleItems(551		#[derivative(Debug(format_with = "bounded::vec_debug"))]552		BoundedVec<CreateRefungibleExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,553	),554	/// Single token, which may have many owners555	RefungibleMultipleOwners(CreateRefungibleExData<CrossAccountId>),556}557558impl CreateItemData {559	pub fn data_size(&self) -> usize {560		match self {561			CreateItemData::NFT(data) => data.const_data.len(),562			CreateItemData::ReFungible(data) => data.const_data.len(),563			_ => 0,564		}565	}566}567568impl From<CreateNftData> for CreateItemData {569	fn from(item: CreateNftData) -> Self {570		CreateItemData::NFT(item)571	}572}573574impl From<CreateReFungibleData> for CreateItemData {575	fn from(item: CreateReFungibleData) -> Self {576		CreateItemData::ReFungible(item)577	}578}579580impl From<CreateFungibleData> for CreateItemData {581	fn from(item: CreateFungibleData) -> Self {582		CreateItemData::Fungible(item)583	}584}585586#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]587#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]588pub struct CollectionStats {589	pub created: u32,590	pub destroyed: u32,591	pub alive: u32,592}593594#[derive(Encode, Decode, Clone, Debug)]595#[cfg_attr(feature = "std", derive(PartialEq))]596pub struct PhantomType<T>(core::marker::PhantomData<T>);597598impl<T: TypeInfo + 'static> TypeInfo for PhantomType<T> {599	type Identity = PhantomType<T>;600601	fn type_info() -> scale_info::Type {602		use scale_info::{603			Type, Path,604			build::{FieldsBuilder, UnnamedFields},605			type_params,606		};607		Type::builder()608			.path(Path::new("up_data_structs", "PhantomType"))609			.type_params(type_params!(T))610			.composite(<FieldsBuilder<UnnamedFields>>::default().field(|b| b.ty::<[T; 0]>()))611	}612}613impl<T> MaxEncodedLen for PhantomType<T> {614	fn max_encoded_len() -> usize {615		0616	}617}618619pub type PropertyKey = BoundedVec<u8, ConstU32<MAX_PROPERTY_KEY_LENGTH>>;620pub type PropertyValue = BoundedVec<u8, ConstU32<MAX_PROPERTY_VALUE_LENGTH>>;621622#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]623#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]624pub struct PropertyPermission {625	pub mutable: bool,626	pub collection_admin: bool,627	pub token_owner: bool,628}629630impl PropertyPermission {631	pub fn none() -> Self {632		Self {633			mutable: true,634			collection_admin: false,635			token_owner: false,636		}637	}638}639640#[derive(Encode, Decode, Debug, TypeInfo, Clone, PartialEq, MaxEncodedLen)]641#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]642pub struct Property {643	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]644	pub key: PropertyKey,645646	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]647	pub value: PropertyValue,648}649650impl Into<(PropertyKey, PropertyValue)> for Property {651	fn into(self) -> (PropertyKey, PropertyValue) {652		(self.key, self.value)653	}654}655656#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]657#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]658pub struct PropertyKeyPermission {659	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]660	pub key: PropertyKey,661662	pub permission: PropertyPermission,663}664665impl Into<(PropertyKey, PropertyPermission)> for PropertyKeyPermission {666	fn into(self) -> (PropertyKey, PropertyPermission) {667		(self.key, self.permission)668	}669}670671#[derive(Debug)]672pub enum PropertiesError {673	NoSpaceForProperty,674	PropertyLimitReached,675	InvalidCharacterInPropertyKey,676	PropertyKeyIsTooLong,677	EmptyPropertyKey,678}679680#[derive(Clone, Copy)]681pub enum PropertyScope {682	None,683	Rmrk,684}685686impl PropertyScope {687	pub fn apply(self, key: PropertyKey) -> Result<PropertyKey, PropertiesError> {688		let scope_str: &[u8] = match self {689			Self::None => return Ok(key),690			Self::Rmrk => b"rmrk",691		};692693		[scope_str, b":", key.as_slice()]694			.concat()695			.try_into()696			.map_err(|_| PropertiesError::PropertyKeyIsTooLong)697	}698}699700pub trait TrySetProperty: Sized {701	type Value;702703	fn try_scoped_set(704		&mut self,705		scope: PropertyScope,706		key: PropertyKey,707		value: Self::Value,708	) -> Result<(), PropertiesError>;709710	fn try_scoped_set_from_iter<I, KV>(711		&mut self,712		scope: PropertyScope,713		iter: I,714	) -> Result<(), PropertiesError>715	where716		I: Iterator<Item = KV>,717		KV: Into<(PropertyKey, Self::Value)>,718	{719		for kv in iter {720			let (key, value) = kv.into();721			self.try_scoped_set(scope, key, value)?;722		}723724		Ok(())725	}726727	fn try_set(&mut self, key: PropertyKey, value: Self::Value) -> Result<(), PropertiesError> {728		self.try_scoped_set(PropertyScope::None, key, value)729	}730731	fn try_set_from_iter<I, KV>(&mut self, iter: I) -> Result<(), PropertiesError>732	where733		I: Iterator<Item = KV>,734		KV: Into<(PropertyKey, Self::Value)>,735	{736		self.try_scoped_set_from_iter(PropertyScope::None, iter)737	}738}739740#[derive(Encode, Decode, TypeInfo, Derivative, Clone, PartialEq, MaxEncodedLen)]741#[derivative(Default(bound = ""))]742pub struct PropertiesMap<Value>(743	BoundedBTreeMap<PropertyKey, Value, ConstU32<MAX_PROPERTIES_PER_ITEM>>,744);745746impl<Value> PropertiesMap<Value> {747	pub fn new() -> Self {748		Self(BoundedBTreeMap::new())749	}750751	pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<Value>, PropertiesError> {752		Self::check_property_key(key)?;753754		Ok(self.0.remove(key))755	}756757	pub fn get(&self, key: &PropertyKey) -> Option<&Value> {758		self.0.get(key)759	}760761	fn check_property_key(key: &PropertyKey) -> Result<(), PropertiesError> {762		if key.is_empty() {763			return Err(PropertiesError::EmptyPropertyKey);764		}765766		for byte in key.as_slice().iter() {767			let byte = *byte;768769			if !byte.is_ascii_alphanumeric() && byte != b'_' && byte != b'-' {770				return Err(PropertiesError::InvalidCharacterInPropertyKey);771			}772		}773774		Ok(())775	}776}777778impl<Value> IntoIterator for PropertiesMap<Value> {779	type Item = (PropertyKey, Value);780	type IntoIter = <781		BoundedBTreeMap<782			PropertyKey,783			Value,784			ConstU32<MAX_PROPERTIES_PER_ITEM>785		> as IntoIterator786	>::IntoIter;787788	fn into_iter(self) -> Self::IntoIter {789        self.0.into_iter()790    }791}792793impl<Value> TrySetProperty for PropertiesMap<Value> {794	type Value = Value;795796	fn try_scoped_set(797		&mut self,798		scope: PropertyScope,799		key: PropertyKey,800		value: Self::Value,801	) -> Result<(), PropertiesError> {802		Self::check_property_key(&key)?;803804		let key = scope.apply(key)?;805		self.0806			.try_insert(key, value)807			.map_err(|_| PropertiesError::PropertyLimitReached)?;808809		Ok(())810	}811}812813pub type PropertiesPermissionMap = PropertiesMap<PropertyPermission>;814815#[derive(Encode, Decode, TypeInfo, Clone, PartialEq, MaxEncodedLen)]816pub struct Properties {817	map: PropertiesMap<PropertyValue>,818	consumed_space: u32,819	space_limit: u32,820}821822impl Properties {823	pub fn new(space_limit: u32) -> Self {824		Self {825			map: PropertiesMap::new(),826			consumed_space: 0,827			space_limit,828		}829	}830831	pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<PropertyValue>, PropertiesError> {832		let value = self.map.remove(key)?;833834		if let Some(ref value) = value {835			let value_len = value.len() as u32;836			self.consumed_space -= value_len;837		}838839		Ok(value)840	}841842	pub fn get(&self, key: &PropertyKey) -> Option<&PropertyValue> {843		self.map.get(key)844	}845}846847impl IntoIterator for Properties {848	type Item = (PropertyKey, PropertyValue);849	type IntoIter = <PropertiesMap<PropertyValue> as IntoIterator>::IntoIter;850851	fn into_iter(self) -> Self::IntoIter {852        self.map.into_iter()853    }854}855856impl TrySetProperty for Properties {857	type Value = PropertyValue;858859	fn try_scoped_set(860		&mut self,861		scope: PropertyScope,862		key: PropertyKey,863		value: Self::Value,864	) -> Result<(), PropertiesError> {865		let value_len = value.len();866867		if self.consumed_space as usize + value_len > self.space_limit as usize868			&& !cfg!(feature = "runtime-benchmarks")869		{870			return Err(PropertiesError::NoSpaceForProperty);871		}872873		self.map.try_scoped_set(scope, key, value)?;874875		self.consumed_space += value_len as u32;876877		Ok(())878	}879}880881pub struct CollectionProperties;882883impl Get<Properties> for CollectionProperties {884	fn get() -> Properties {885		Properties::new(MAX_COLLECTION_PROPERTIES_SIZE)886	}887}888889pub struct TokenProperties;890891impl Get<Properties> for TokenProperties {892	fn get() -> Properties {893		Properties::new(MAX_TOKEN_PROPERTIES_SIZE)894	}895}896897// RMRK898// todo document?899parameter_types! {900	#[derive(PartialEq, TypeInfo)]901	pub const RmrkStringLimit: u32 = 128;902	#[derive(PartialEq)]903	pub const RmrkCollectionSymbolLimit: u32 = 100;904	#[derive(PartialEq)]905	pub const RmrkResourceSymbolLimit: u32 = 10;906	#[derive(PartialEq)]907	pub const RmrkKeyLimit: u32 = 32;908	#[derive(PartialEq)]909	pub const RmrkValueLimit: u32 = 256;910	#[derive(PartialEq)]911	pub const RmrkMaxCollectionsEquippablePerPart: u32 = 100;912	#[derive(PartialEq)]913	pub const RmrkPartsLimit: u32 = 3;914}915916impl From<RmrkCollectionId> for CollectionId {917	fn from(id: RmrkCollectionId) -> Self {918		Self(id)919	}920}921922impl From<RmrkNftId> for TokenId {923	fn from(id: RmrkNftId) -> Self {924		Self(id)925	}926}927928pub type RmrkCollectionSymbol = BoundedVec<u8, RmrkCollectionSymbolLimit>;929pub type RmrkCollectionInfo<AccountId> =930	CollectionInfo<RmrkString, RmrkCollectionSymbol, AccountId>;931pub type RmrkInstanceInfo<AccountId> = NftInfo<AccountId, Permill, RmrkString>;932pub type RmrkResourceInfo = ResourceInfo<933	BoundedVec<u8, RmrkResourceSymbolLimit>,934	RmrkString,935	BoundedVec<RmrkPartId, RmrkPartsLimit>,936>;937pub type RmrkKeyString = BoundedVec<u8, RmrkKeyLimit>;938pub type RmrkValueString = BoundedVec<u8, RmrkValueLimit>;939pub type RmrkPropertyInfo = PropertyInfo<RmrkKeyString, RmrkValueString>;940pub type RmrkBaseInfo<AccountId> = BaseInfo<AccountId, RmrkString>;941pub type RmrkPartType =942	PartType<RmrkString, BoundedVec<RmrkCollectionId, RmrkMaxCollectionsEquippablePerPart>>;943pub type RmrkThemeProperty = ThemeProperty<RmrkString>;944pub type RmrkTheme = Theme<RmrkString, Vec<RmrkThemeProperty>>;945946pub type RmrkRpcString = Vec<u8>;947pub type RmrkThemeName = RmrkRpcString;948pub type RmrkPropertyKey = RmrkRpcString;949950pub type RmrkString = BoundedVec<u8, RmrkStringLimit>;
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;3839pub mod rmrk;4041// RMRK42use rmrk::{43	CollectionInfo, NftInfo, ResourceInfo, PropertyInfo, BaseInfo, PartType, Theme, ThemeProperty,44};45pub use rmrk::{46	primitives::{47		CollectionId as RmrkCollectionId, NftId as RmrkNftId, BaseId as RmrkBaseId,48		PartId as RmrkPartId, ResourceId as RmrkResourceId,49	},50	NftChild as RmrkNftChild, AccountIdOrCollectionNftTuple as RmrkAccountIdOrCollectionNftTuple,51	FixedPart as RmrkFixedPart, SlotPart as RmrkSlotPart, EquippableList as RmrkEquippableList,52	BasicResource as RmrkBasicResource, ComposableResource as RmrkComposableResource, SlotResource as RmrkSlotResource,53};5455mod bounded;56pub mod budget;57pub mod mapping;58mod migration;5960pub const MAX_DECIMAL_POINTS: DecimalPoints = 30;61pub const MAX_REFUNGIBLE_PIECES: u128 = 1_000_000_000_000_000_000_000;62pub const MAX_SPONSOR_TIMEOUT: u32 = 10_368_000;6364pub const MAX_TOKEN_OWNERSHIP: u32 = if cfg!(not(feature = "limit-testing")) {65	100_00066} else {67	1068};69pub const COLLECTION_NUMBER_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {70	100_00071} else {72	1073};74pub const CUSTOM_DATA_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {75	204876} else {77	1078};79pub const COLLECTION_ADMINS_LIMIT: u32 = 5;80pub const COLLECTION_TOKEN_LIMIT: u32 = u32::MAX;81pub const ACCOUNT_TOKEN_OWNERSHIP_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {82	1_000_00083} else {84	1085};8687// Timeouts for item types in passed blocks88pub const NFT_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;89pub const FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;90pub const REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;9192pub const SPONSOR_APPROVE_TIMEOUT: u32 = 5;9394// Schema limits95pub const OFFCHAIN_SCHEMA_LIMIT: u32 = 8192;96pub const VARIABLE_ON_CHAIN_SCHEMA_LIMIT: u32 = 8192;97pub const CONST_ON_CHAIN_SCHEMA_LIMIT: u32 = 32768;9899pub const COLLECTION_FIELD_LIMIT: u32 = CONST_ON_CHAIN_SCHEMA_LIMIT;100101pub const MAX_COLLECTION_NAME_LENGTH: u32 = 64;102pub const MAX_COLLECTION_DESCRIPTION_LENGTH: u32 = 256;103pub const MAX_TOKEN_PREFIX_LENGTH: u32 = 16;104105pub const MAX_PROPERTY_KEY_LENGTH: u32 = 256;106pub const MAX_PROPERTY_VALUE_LENGTH: u32 = 32768;107pub const MAX_PROPERTIES_PER_ITEM: u32 = 64;108109pub const MAX_COLLECTION_PROPERTIES_SIZE: u32 = 40960;110pub const MAX_TOKEN_PROPERTIES_SIZE: u32 = 32768;111112// RMRK constants113pub const RMRK_STRING_LIMIT: u32 = 128;114pub const RMRK_COLLECTION_SYMBOL_LIMIT: u32 = 100;115pub const RMRK_RESOURCE_SYMBOL_LIMIT: u32 = 10;116pub const RMRK_KEY_LIMIT: u32 = 32;117pub const RMRK_VALUE_LIMIT: u32 = 256;118119/// How much items can be created per single120/// create_many call121pub const MAX_ITEMS_PER_BATCH: u32 = 200;122123pub type CustomDataLimit = ConstU32<CUSTOM_DATA_LIMIT>;124125#[derive(126	Encode,127	Decode,128	PartialEq,129	Eq,130	PartialOrd,131	Ord,132	Clone,133	Copy,134	Debug,135	Default,136	TypeInfo,137	MaxEncodedLen,138)]139#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]140pub struct CollectionId(pub u32);141impl EncodeLike<u32> for CollectionId {}142impl EncodeLike<CollectionId> for u32 {}143144#[derive(145	Encode,146	Decode,147	PartialEq,148	Eq,149	PartialOrd,150	Ord,151	Clone,152	Copy,153	Debug,154	Default,155	TypeInfo,156	MaxEncodedLen,157)]158#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]159pub struct TokenId(pub u32);160impl EncodeLike<u32> for TokenId {}161impl EncodeLike<TokenId> for u32 {}162163impl TokenId {164	pub fn try_next(self) -> Result<TokenId, ArithmeticError> {165		self.0166			.checked_add(1)167			.ok_or(ArithmeticError::Overflow)168			.map(Self)169	}170}171172impl From<TokenId> for U256 {173	fn from(t: TokenId) -> Self {174		t.0.into()175	}176}177178impl TryFrom<U256> for TokenId {179	type Error = &'static str;180181	fn try_from(value: U256) -> Result<Self, Self::Error> {182		Ok(TokenId(value.try_into().map_err(|_| "too large token id")?))183	}184}185186#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]187#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]188pub struct TokenData<CrossAccountId> {189	pub const_data: Vec<u8>,190	pub properties: Vec<Property>,191	pub owner: Option<CrossAccountId>,192}193194pub struct OverflowError;195impl From<OverflowError> for &'static str {196	fn from(_: OverflowError) -> Self {197		"overflow occured"198	}199}200201pub type DecimalPoints = u8;202203#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]204#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]205pub enum CollectionMode {206	NFT,207	// decimal points208	Fungible(DecimalPoints),209	ReFungible,210}211212impl CollectionMode {213	pub fn id(&self) -> u8 {214		match self {215			CollectionMode::NFT => 1,216			CollectionMode::Fungible(_) => 2,217			CollectionMode::ReFungible => 3,218		}219	}220}221222pub trait SponsoringResolve<AccountId, Call> {223	fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>;224}225226#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]227#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]228pub enum AccessMode {229	Normal,230	AllowList,231}232impl Default for AccessMode {233	fn default() -> Self {234		Self::Normal235	}236}237238#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]239#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]240pub enum SchemaVersion {241	ImageURL,242	Unique,243}244impl Default for SchemaVersion {245	fn default() -> Self {246		Self::ImageURL247	}248}249250#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]251#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]252pub struct Ownership<AccountId> {253	pub owner: AccountId,254	pub fraction: u128,255}256257#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]258#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]259pub enum SponsorshipState<AccountId> {260	/// The fees are applied to the transaction sender261	Disabled,262	Unconfirmed(AccountId),263	/// Transactions are sponsored by specified account264	Confirmed(AccountId),265}266267impl<AccountId> SponsorshipState<AccountId> {268	pub fn sponsor(&self) -> Option<&AccountId> {269		match self {270			Self::Confirmed(sponsor) => Some(sponsor),271			_ => None,272		}273	}274275	pub fn pending_sponsor(&self) -> Option<&AccountId> {276		match self {277			Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),278			_ => None,279		}280	}281282	pub fn confirmed(&self) -> bool {283		matches!(self, Self::Confirmed(_))284	}285}286287impl<T> Default for SponsorshipState<T> {288	fn default() -> Self {289		Self::Disabled290	}291}292293/// Used in storage294#[struct_versioning::versioned(version = 2, upper)]295#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen)]296pub struct Collection<AccountId> {297	pub owner: AccountId,298	pub mode: CollectionMode,299	pub access: AccessMode,300	pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,301	pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,302	pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,303	pub mint_mode: bool,304305	#[version(..2)]306	pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,307308	pub schema_version: SchemaVersion,309	pub sponsorship: SponsorshipState<AccountId>,310311	#[version(..2)]312	pub limits: CollectionLimitsVersion1, // Collection private restrictions313	#[version(2.., upper(limits.into()))]314	pub limits: CollectionLimitsVersion2,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 access: AccessMode,333	pub name: Vec<u16>,334	pub description: Vec<u16>,335	pub token_prefix: Vec<u8>,336	pub mint_mode: bool,337	pub offchain_schema: Vec<u8>,338	pub schema_version: SchemaVersion,339	pub sponsorship: SponsorshipState<AccountId>,340	pub limits: CollectionLimits,341	pub const_on_chain_schema: Vec<u8>,342	pub token_property_permissions: Vec<PropertyKeyPermission>,343	pub properties: Vec<Property>,344}345346#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen)]347#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]348pub enum CollectionField {349	ConstOnChainSchema,350	OffchainSchema,351}352353#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Derivative, MaxEncodedLen)]354#[derivative(Debug, Default(bound = ""))]355pub struct CreateCollectionData<AccountId> {356	#[derivative(Default(value = "CollectionMode::NFT"))]357	pub mode: CollectionMode,358	pub access: Option<AccessMode>,359	pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,360	pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,361	pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,362	pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,363	pub schema_version: Option<SchemaVersion>,364	pub pending_sponsor: Option<AccountId>,365	pub limits: Option<CollectionLimits>,366	pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,367	pub token_property_permissions: CollectionPropertiesPermissionsVec,368	pub properties: CollectionPropertiesVec,369}370371pub type CollectionPropertiesPermissionsVec =372	BoundedVec<PropertyKeyPermission, ConstU32<MAX_PROPERTIES_PER_ITEM>>;373374pub type CollectionPropertiesVec =375	BoundedVec<Property, ConstU32<MAX_PROPERTIES_PER_ITEM>>;376377/// All fields are wrapped in `Option`s, where None means chain default378#[struct_versioning::versioned(version = 2, upper)]379#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]380#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]381pub struct CollectionLimits {382	pub account_token_ownership_limit: Option<u32>,383	pub sponsored_data_size: Option<u32>,384385	/// FIXME should we delete this or repurpose it?386	/// None - setVariableMetadata is not sponsored387	/// Some(v) - setVariableMetadata is sponsored388	///           if there is v block between txs389	pub sponsored_data_rate_limit: Option<SponsoringRateLimit>,390	pub token_limit: Option<u32>,391392	// Timeouts for item types in passed blocks393	pub sponsor_transfer_timeout: Option<u32>,394	pub sponsor_approve_timeout: Option<u32>,395	pub owner_can_transfer: Option<bool>,396	pub owner_can_destroy: Option<bool>,397	pub transfers_enabled: Option<bool>,398399	#[version(2.., upper(None))]400	pub nesting_rule: Option<NestingRule>,401}402403impl CollectionLimits {404	pub fn account_token_ownership_limit(&self) -> u32 {405		self.account_token_ownership_limit406			.unwrap_or(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)407			.min(MAX_TOKEN_OWNERSHIP)408	}409	pub fn sponsored_data_size(&self) -> u32 {410		self.sponsored_data_size411			.unwrap_or(CUSTOM_DATA_LIMIT)412			.min(CUSTOM_DATA_LIMIT)413	}414	pub fn token_limit(&self) -> u32 {415		self.token_limit416			.unwrap_or(COLLECTION_TOKEN_LIMIT)417			.min(COLLECTION_TOKEN_LIMIT)418	}419	pub fn sponsor_transfer_timeout(&self, default: u32) -> u32 {420		self.sponsor_transfer_timeout421			.unwrap_or(default)422			.min(MAX_SPONSOR_TIMEOUT)423	}424	pub fn sponsor_approve_timeout(&self) -> u32 {425		self.sponsor_approve_timeout426			.unwrap_or(SPONSOR_APPROVE_TIMEOUT)427			.min(MAX_SPONSOR_TIMEOUT)428	}429	pub fn owner_can_transfer(&self) -> bool {430		self.owner_can_transfer.unwrap_or(true)431	}432	pub fn owner_can_destroy(&self) -> bool {433		self.owner_can_destroy.unwrap_or(true)434	}435	pub fn transfers_enabled(&self) -> bool {436		self.transfers_enabled.unwrap_or(true)437	}438	pub fn sponsored_data_rate_limit(&self) -> Option<u32> {439		match self440			.sponsored_data_rate_limit441			.unwrap_or(SponsoringRateLimit::SponsoringDisabled)442		{443			SponsoringRateLimit::SponsoringDisabled => None,444			SponsoringRateLimit::Blocks(v) => Some(v.min(MAX_SPONSOR_TIMEOUT)),445		}446	}447	pub fn nesting_rule(&self) -> &NestingRule {448		static DEFAULT: NestingRule = NestingRule::Disabled;449		self.nesting_rule.as_ref().unwrap_or(&DEFAULT)450	}451}452453#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative)]454#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]455#[derivative(Debug)]456pub enum NestingRule {457	/// No one can nest tokens458	Disabled,459	/// Owner can nest any tokens460	Owner,461	/// Owner can nest tokens from specified collections462	OwnerRestricted(463		#[cfg_attr(feature = "serde1", serde(with = "bounded::set_serde"))]464		#[derivative(Debug(format_with = "bounded::set_debug"))]465		BoundedBTreeSet<CollectionId, ConstU32<16>>,466	),467}468469#[derive(Encode, Decode, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]470#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]471pub enum SponsoringRateLimit {472	SponsoringDisabled,473	Blocks(u32),474}475476#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]477#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]478#[derivative(Debug)]479pub struct CreateNftData {480	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]481	#[derivative(Debug(format_with = "bounded::vec_debug"))]482	pub const_data: BoundedVec<u8, CustomDataLimit>,483484	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]485	#[derivative(Debug(format_with = "bounded::vec_debug"))]486	pub properties: CollectionPropertiesVec,487}488489#[derive(Encode, Decode, MaxEncodedLen, Default, Debug, Clone, PartialEq, TypeInfo)]490#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]491pub struct CreateFungibleData {492	pub value: u128,493}494495#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]496#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]497#[derivative(Debug)]498pub struct CreateReFungibleData {499	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]500	#[derivative(Debug(format_with = "bounded::vec_debug"))]501	pub const_data: BoundedVec<u8, CustomDataLimit>,502	pub pieces: u128,503}504505#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]506pub enum MetaUpdatePermission {507	ItemOwner,508	Admin,509	None,510}511512#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]513#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]514pub enum CreateItemData {515	NFT(CreateNftData),516	Fungible(CreateFungibleData),517	ReFungible(CreateReFungibleData),518}519520#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]521#[derivative(Debug)]522pub struct CreateNftExData<CrossAccountId> {523	#[derivative(Debug(format_with = "bounded::vec_debug"))]524	pub const_data: BoundedVec<u8, CustomDataLimit>,525	#[derivative(Debug(format_with = "bounded::vec_debug"))]526	pub properties: CollectionPropertiesVec,527	pub owner: CrossAccountId,528}529530#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]531#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]532pub struct CreateRefungibleExData<CrossAccountId> {533	#[derivative(Debug(format_with = "bounded::vec_debug"))]534	pub const_data: BoundedVec<u8, CustomDataLimit>,535	#[derivative(Debug(format_with = "bounded::map_debug"))]536	pub users: BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,537}538539#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]540#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]541pub enum CreateItemExData<CrossAccountId> {542	NFT(543		#[derivative(Debug(format_with = "bounded::vec_debug"))]544		BoundedVec<CreateNftExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,545	),546	Fungible(547		#[derivative(Debug(format_with = "bounded::map_debug"))]548		BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,549	),550	/// Many tokens, each may have only one owner551	RefungibleMultipleItems(552		#[derivative(Debug(format_with = "bounded::vec_debug"))]553		BoundedVec<CreateRefungibleExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,554	),555	/// Single token, which may have many owners556	RefungibleMultipleOwners(CreateRefungibleExData<CrossAccountId>),557}558559impl CreateItemData {560	pub fn data_size(&self) -> usize {561		match self {562			CreateItemData::NFT(data) => data.const_data.len(),563			CreateItemData::ReFungible(data) => data.const_data.len(),564			_ => 0,565		}566	}567}568569impl From<CreateNftData> for CreateItemData {570	fn from(item: CreateNftData) -> Self {571		CreateItemData::NFT(item)572	}573}574575impl From<CreateReFungibleData> for CreateItemData {576	fn from(item: CreateReFungibleData) -> Self {577		CreateItemData::ReFungible(item)578	}579}580581impl From<CreateFungibleData> for CreateItemData {582	fn from(item: CreateFungibleData) -> Self {583		CreateItemData::Fungible(item)584	}585}586587#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]588#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]589pub struct CollectionStats {590	pub created: u32,591	pub destroyed: u32,592	pub alive: u32,593}594595#[derive(Encode, Decode, Clone, Debug)]596#[cfg_attr(feature = "std", derive(PartialEq))]597pub struct PhantomType<T>(core::marker::PhantomData<T>);598599impl<T: TypeInfo + 'static> TypeInfo for PhantomType<T> {600	type Identity = PhantomType<T>;601602	fn type_info() -> scale_info::Type {603		use scale_info::{604			Type, Path,605			build::{FieldsBuilder, UnnamedFields},606			type_params,607		};608		Type::builder()609			.path(Path::new("up_data_structs", "PhantomType"))610			.type_params(type_params!(T))611			.composite(<FieldsBuilder<UnnamedFields>>::default().field(|b| b.ty::<[T; 0]>()))612	}613}614impl<T> MaxEncodedLen for PhantomType<T> {615	fn max_encoded_len() -> usize {616		0617	}618}619620pub type PropertyKey = BoundedVec<u8, ConstU32<MAX_PROPERTY_KEY_LENGTH>>;621pub type PropertyValue = BoundedVec<u8, ConstU32<MAX_PROPERTY_VALUE_LENGTH>>;622623#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]624#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]625pub struct PropertyPermission {626	pub mutable: bool,627	pub collection_admin: bool,628	pub token_owner: bool,629}630631impl PropertyPermission {632	pub fn none() -> Self {633		Self {634			mutable: true,635			collection_admin: false,636			token_owner: false,637		}638	}639}640641#[derive(Encode, Decode, Debug, TypeInfo, Clone, PartialEq, MaxEncodedLen)]642#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]643pub struct Property {644	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]645	pub key: PropertyKey,646647	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]648	pub value: PropertyValue,649}650651impl Into<(PropertyKey, PropertyValue)> for Property {652	fn into(self) -> (PropertyKey, PropertyValue) {653		(self.key, self.value)654	}655}656657#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]658#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]659pub struct PropertyKeyPermission {660	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]661	pub key: PropertyKey,662663	pub permission: PropertyPermission,664}665666impl Into<(PropertyKey, PropertyPermission)> for PropertyKeyPermission {667	fn into(self) -> (PropertyKey, PropertyPermission) {668		(self.key, self.permission)669	}670}671672#[derive(Debug)]673pub enum PropertiesError {674	NoSpaceForProperty,675	PropertyLimitReached,676	InvalidCharacterInPropertyKey,677	PropertyKeyIsTooLong,678	EmptyPropertyKey,679}680681#[derive(Clone, Copy)]682pub enum PropertyScope {683	None,684	Rmrk,685}686687impl PropertyScope {688	pub fn apply(self, key: PropertyKey) -> Result<PropertyKey, PropertiesError> {689		let scope_str: &[u8] = match self {690			Self::None => return Ok(key),691			Self::Rmrk => b"rmrk",692		};693694		[scope_str, b":", key.as_slice()]695			.concat()696			.try_into()697			.map_err(|_| PropertiesError::PropertyKeyIsTooLong)698	}699}700701pub trait TrySetProperty: Sized {702	type Value;703704	fn try_scoped_set(705		&mut self,706		scope: PropertyScope,707		key: PropertyKey,708		value: Self::Value,709	) -> Result<(), PropertiesError>;710711	fn try_scoped_set_from_iter<I, KV>(712		&mut self,713		scope: PropertyScope,714		iter: I,715	) -> Result<(), PropertiesError>716	where717		I: Iterator<Item = KV>,718		KV: Into<(PropertyKey, Self::Value)>,719	{720		for kv in iter {721			let (key, value) = kv.into();722			self.try_scoped_set(scope, key, value)?;723		}724725		Ok(())726	}727728	fn try_set(&mut self, key: PropertyKey, value: Self::Value) -> Result<(), PropertiesError> {729		self.try_scoped_set(PropertyScope::None, key, value)730	}731732	fn try_set_from_iter<I, KV>(&mut self, iter: I) -> Result<(), PropertiesError>733	where734		I: Iterator<Item = KV>,735		KV: Into<(PropertyKey, Self::Value)>,736	{737		self.try_scoped_set_from_iter(PropertyScope::None, iter)738	}739}740741#[derive(Encode, Decode, TypeInfo, Derivative, Clone, PartialEq, MaxEncodedLen)]742#[derivative(Default(bound = ""))]743pub struct PropertiesMap<Value>(744	BoundedBTreeMap<PropertyKey, Value, ConstU32<MAX_PROPERTIES_PER_ITEM>>,745);746747impl<Value> PropertiesMap<Value> {748	pub fn new() -> Self {749		Self(BoundedBTreeMap::new())750	}751752	pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<Value>, PropertiesError> {753		Self::check_property_key(key)?;754755		Ok(self.0.remove(key))756	}757758	pub fn get(&self, key: &PropertyKey) -> Option<&Value> {759		self.0.get(key)760	}761762	fn check_property_key(key: &PropertyKey) -> Result<(), PropertiesError> {763		if key.is_empty() {764			return Err(PropertiesError::EmptyPropertyKey);765		}766767		for byte in key.as_slice().iter() {768			let byte = *byte;769770			if !byte.is_ascii_alphanumeric() && byte != b'_' && byte != b'-' {771				return Err(PropertiesError::InvalidCharacterInPropertyKey);772			}773		}774775		Ok(())776	}777}778779impl<Value> IntoIterator for PropertiesMap<Value> {780	type Item = (PropertyKey, Value);781	type IntoIter = <782		BoundedBTreeMap<783			PropertyKey,784			Value,785			ConstU32<MAX_PROPERTIES_PER_ITEM>786		> as IntoIterator787	>::IntoIter;788789	fn into_iter(self) -> Self::IntoIter {790        self.0.into_iter()791    }792}793794impl<Value> TrySetProperty for PropertiesMap<Value> {795	type Value = Value;796797	fn try_scoped_set(798		&mut self,799		scope: PropertyScope,800		key: PropertyKey,801		value: Self::Value,802	) -> Result<(), PropertiesError> {803		Self::check_property_key(&key)?;804805		let key = scope.apply(key)?;806		self.0807			.try_insert(key, value)808			.map_err(|_| PropertiesError::PropertyLimitReached)?;809810		Ok(())811	}812}813814pub type PropertiesPermissionMap = PropertiesMap<PropertyPermission>;815816#[derive(Encode, Decode, TypeInfo, Clone, PartialEq, MaxEncodedLen)]817pub struct Properties {818	map: PropertiesMap<PropertyValue>,819	consumed_space: u32,820	space_limit: u32,821}822823impl Properties {824	pub fn new(space_limit: u32) -> Self {825		Self {826			map: PropertiesMap::new(),827			consumed_space: 0,828			space_limit,829		}830	}831832	pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<PropertyValue>, PropertiesError> {833		let value = self.map.remove(key)?;834835		if let Some(ref value) = value {836			let value_len = value.len() as u32;837			self.consumed_space -= value_len;838		}839840		Ok(value)841	}842843	pub fn get(&self, key: &PropertyKey) -> Option<&PropertyValue> {844		self.map.get(key)845	}846}847848impl IntoIterator for Properties {849	type Item = (PropertyKey, PropertyValue);850	type IntoIter = <PropertiesMap<PropertyValue> as IntoIterator>::IntoIter;851852	fn into_iter(self) -> Self::IntoIter {853        self.map.into_iter()854    }855}856857impl TrySetProperty for Properties {858	type Value = PropertyValue;859860	fn try_scoped_set(861		&mut self,862		scope: PropertyScope,863		key: PropertyKey,864		value: Self::Value,865	) -> Result<(), PropertiesError> {866		let value_len = value.len();867868		if self.consumed_space as usize + value_len > self.space_limit as usize869			&& !cfg!(feature = "runtime-benchmarks")870		{871			return Err(PropertiesError::NoSpaceForProperty);872		}873874		self.map.try_scoped_set(scope, key, value)?;875876		self.consumed_space += value_len as u32;877878		Ok(())879	}880}881882pub struct CollectionProperties;883884impl Get<Properties> for CollectionProperties {885	fn get() -> Properties {886		Properties::new(MAX_COLLECTION_PROPERTIES_SIZE)887	}888}889890pub struct TokenProperties;891892impl Get<Properties> for TokenProperties {893	fn get() -> Properties {894		Properties::new(MAX_TOKEN_PROPERTIES_SIZE)895	}896}897898// RMRK899// todo document?900parameter_types! {901	#[derive(PartialEq, TypeInfo)]902	pub const RmrkStringLimit: u32 = 128;903	#[derive(PartialEq)]904	pub const RmrkCollectionSymbolLimit: u32 = 100;905	#[derive(PartialEq)]906	pub const RmrkResourceSymbolLimit: u32 = 10;907	#[derive(PartialEq)]908	pub const RmrkKeyLimit: u32 = 32;909	#[derive(PartialEq)]910	pub const RmrkValueLimit: u32 = 256;911	#[derive(PartialEq)]912	pub const RmrkMaxCollectionsEquippablePerPart: u32 = 100;913	#[derive(PartialEq)]914	pub const RmrkPartsLimit: u32 = 3;915}916917impl From<RmrkCollectionId> for CollectionId {918	fn from(id: RmrkCollectionId) -> Self {919		Self(id)920	}921}922923impl From<RmrkNftId> for TokenId {924	fn from(id: RmrkNftId) -> Self {925		Self(id)926	}927}928929pub type RmrkCollectionInfo<AccountId> =930	CollectionInfo<RmrkString, RmrkCollectionSymbol, AccountId>;931pub type RmrkInstanceInfo<AccountId> = NftInfo<AccountId, Permill, RmrkString>;932pub type RmrkResourceInfo = ResourceInfo<933	RmrkBoundedResource,934	RmrkString,935	RmrkBoundedParts,936>;937pub type RmrkPropertyInfo = PropertyInfo<RmrkKeyString, RmrkValueString>;938pub type RmrkBaseInfo<AccountId> = BaseInfo<AccountId, RmrkString>;939pub type RmrkPartType =940	PartType<RmrkString, BoundedVec<RmrkCollectionId, RmrkMaxCollectionsEquippablePerPart>>;941pub type RmrkThemeProperty = ThemeProperty<RmrkString>;942pub type RmrkTheme = Theme<RmrkString, Vec<RmrkThemeProperty>>;943944pub type RmrkCollectionSymbol = BoundedVec<u8, RmrkCollectionSymbolLimit>;945pub type RmrkKeyString = BoundedVec<u8, RmrkKeyLimit>;946pub type RmrkValueString = BoundedVec<u8, RmrkValueLimit>;947948type RmrkBoundedResource = BoundedVec<u8, RmrkResourceSymbolLimit>;949type RmrkBoundedParts = BoundedVec<RmrkPartId, RmrkPartsLimit>;950951pub type RmrkRpcString = Vec<u8>;952pub type RmrkThemeName = RmrkRpcString;953pub type RmrkPropertyKey = RmrkRpcString;954955pub type RmrkString = BoundedVec<u8, RmrkStringLimit>;
modifiedprimitives/data-structs/src/rmrk.rsdiffbeforeafterboth
--- a/primitives/data-structs/src/rmrk.rs
+++ b/primitives/data-structs/src/rmrk.rs
@@ -154,7 +154,7 @@
 	pub value: BoundedValue,
 }
 
-#[derive(Encode, Decode, Eq, PartialEq, Clone, Debug, TypeInfo, MaxEncodedLen)]
+#[derive(Encode, Decode, Default, Eq, PartialEq, Clone, Debug, TypeInfo, MaxEncodedLen)]
 #[cfg_attr(feature = "std", derive(Serialize))]
 #[cfg_attr(
 	feature = "std",
@@ -275,7 +275,7 @@
 	pub thumb: Option<BoundedString>,
 }
 
-#[derive(Encode, Decode, Eq, PartialEq, Clone, Debug, TypeInfo, MaxEncodedLen)]
+#[derive(Encode, Decode, Derivative, Eq, PartialEq, Clone, Debug, TypeInfo, MaxEncodedLen)]
 #[cfg_attr(feature = "std", derive(Serialize))]
 #[cfg_attr(
 	feature = "std",
@@ -286,7 +286,9 @@
 		"#
 	)
 )]
-pub enum ResourceTypes<BoundedString, BoundedParts> {
+#[derivative(Default(bound=""))]
+pub enum ResourceTypes<BoundedString: Default, BoundedParts> {
+	#[derivative(Default)]
 	Basic(BasicResource<BoundedString>),
 	Composable(ComposableResource<BoundedString, BoundedParts>),
 	Slot(SlotResource<BoundedString>),
@@ -305,7 +307,7 @@
 		"#
 	)
 )]
-pub struct ResourceInfo<BoundedResource, BoundedString, BoundedParts> {
+pub struct ResourceInfo<BoundedResource, BoundedString: Default, BoundedParts> {
 	/// id is a 5-character string of reasonable uniqueness.
 	/// The combination of base ID and resource id should be unique across the entire RMRK
 	/// ecosystem which
modifiedruntime/common/src/runtime_apis.rsdiffbeforeafterboth
--- a/runtime/common/src/runtime_apis.rs
+++ b/runtime/common/src/runtime_apis.rs
@@ -146,9 +146,7 @@
                 }
 
                 fn collection_by_id(collection_id: RmrkCollectionId) -> Result<Option<RmrkCollectionInfo<AccountId>>, DispatchError> {
-                    use frame_support::BoundedVec;
-                    use scale_info::prelude::string::String;
-                    use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, RmrkRebind, RmrkDecode}};
+                    use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, RmrkDecode}};
 
                     let collection_id = CollectionId(collection_id);
                     let collection = match RmrkCore::get_typed_nft_collection(collection_id, CollectionType::Regular) {
@@ -156,20 +154,18 @@
                         Err(_) => return Ok(None),
                     };
 
-                    let nfts_count = (dispatch_unique_runtime!(collection_id.total_supply()) as Result<u32, DispatchError>)?;
-                    //<Runtime as up_rpc::UniqueApi>::total_supply(collection_id); // todo can't find UniqueApi with disabled default features
+                    let nfts_count = dispatch_unique_runtime!(collection_id.total_supply())?;
 
                     Ok(Some(RmrkCollectionInfo {
                         issuer: collection.owner.clone(),
                         metadata: RmrkCore::get_collection_property(collection_id, RmrkProperty::Metadata)?.decode_or_default(),
                         max: collection.limits.token_limit,
-                        symbol: collection.token_prefix.rebind(), // change
+                        symbol: collection.token_prefix.decode_or_default(),
                         nfts_count
                     }))
                 }
 
                 fn nft_by_id(collection_id: RmrkCollectionId, nft_by_id: RmrkNftId) -> Result<Option<RmrkInstanceInfo<AccountId>>, DispatchError> {
-                    use frame_support::BoundedVec;
                     use up_data_structs::mapping::TokenAddressMapping;
                     use pallet_proxy_rmrk_core::{RmrkProperty, misc::RmrkDecode};
 
@@ -177,7 +173,7 @@
                     let nft_id = TokenId(nft_by_id);
                     if !RmrkCore::nft_exists(collection_id, nft_id) { return Ok(None); }
 
-                    let owner = match (dispatch_unique_runtime!(collection_id.token_owner(nft_id)) as Result<Option<CrossAccountId>, DispatchError>)? {
+                    let owner = match dispatch_unique_runtime!(collection_id.token_owner(nft_id))? {
                         Some(owner) => match <Runtime as pallet_common::Config>::CrossTokenAddressMapping::address_to_token(&owner) {
                             Some((col, tok)) => RmrkAccountIdOrCollectionNftTuple::CollectionAndNftTuple(col.0, tok.0),
                             None => RmrkAccountIdOrCollectionNftTuple::AccountId(owner.as_sub().clone())
@@ -197,16 +193,17 @@
                 }
 
                 fn account_tokens(account_id: AccountId, collection_id: RmrkCollectionId) -> Result<Vec<RmrkNftId>, DispatchError> {
+                    use pallet_proxy_rmrk_core::misc::CollectionType;
+
                     let cross_account_id = CrossAccountId::from_sub(account_id);
                     let collection_id = CollectionId(collection_id);
-                    if !RmrkCore::collection_exists(collection_id) { return Ok(Vec::new()); }
+                    if RmrkCore::ensure_collection_type(collection_id, CollectionType::Regular).is_err() { return Ok(Vec::new()); }
 
                     Ok(
-                        (dispatch_unique_runtime!(collection_id.account_tokens(cross_account_id)) as Result<Vec<TokenId>, DispatchError>)?
-                        //<Runtime as up_rpc::UniqueApi<Block, CrossAccountId, AccountId>>::account_tokens(collection_id, cross_account_id)?
+                        dispatch_unique_runtime!(collection_id.account_tokens(cross_account_id))?
                             .into_iter()
                             .map(|token| token.0)
-                            .collect::<Vec<_>>()
+                            .collect()
                     )
                 }
 
@@ -226,8 +223,7 @@
                             .map(|(child_id, _)| RmrkNftChild {
                                 collection_id: collection_id.0, // todo make sure they're always from this collection // spoiler: they're not
                                 nft_id: child_id.0,
-                            })
-                            .collect()
+                            }).collect()
                     )
                 }
 
@@ -277,28 +273,70 @@
 
                 fn nft_resources(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Result<Vec<RmrkResourceInfo>, DispatchError> {
                     use frame_support::BoundedVec;
-                    use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, NftType}};
+                    use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, NftType, RmrkDecode}};
 
                     let collection_id = CollectionId(collection_id);
-                    if RmrkCore::ensure_collection_type(collection_id, CollectionType::Resource).is_err() { return Ok(Vec::new()); }
+                    if !RmrkCore::collection_exists(collection_id) { return Ok(Vec::new()); } // todo make sure the collection type doesn't matter
 
                     let nft_id = TokenId(nft_id);
                     if RmrkCore::ensure_nft_type(collection_id, nft_id, NftType::Resource).is_err() { return Ok(Vec::new()); }
 
-                    Ok(Vec::new(/*[RmrkResourceInfo {
+                    let resource_collection_id: CollectionId = RmrkCore::get_nft_property(collection_id, nft_id, RmrkProperty::ResourceCollection)
+                        .unwrap()
+                        .decode_or_default();
+                    if RmrkCore::ensure_collection_type(collection_id, CollectionType::Resource).is_err() { return Ok(Vec::new()); }
 
-                    }]*/))
+                    let resources = pallet_nonfungible::TokenProperties::<Runtime>::iter_prefix((resource_collection_id,))
+                        .filter_map(|(resource_id, properties)| Some(RmrkResourceInfo {
+                            id: BoundedVec::default(), // todo ResourceId property
+                            pending: RmrkCore::get_nft_property(resource_collection_id, resource_id, RmrkProperty::PendingResourceAccept).unwrap().decode_or_default(),
+                            pending_removal: RmrkCore::get_nft_property(resource_collection_id, resource_id, RmrkProperty::PendingResourceRemoval).unwrap().decode_or_default(),
+                            resource: RmrkCore::get_nft_property(resource_collection_id, resource_id, RmrkProperty::ResourceType).unwrap().decode_or_default(),/* {
+                                RmrkResourceTypes::Basic(resource) => RmrkResourceTypes::Basic(),/*(RmrkBasicResource {
+                                    src: RmrkCore::get_nft_property_inner(properties, RmrkProperty::Src).unwrap().decode_or_default(),
+                                    metadata: RmrkCore::get_nft_property_inner(properties, RmrkProperty::Metadata).unwrap().decode_or_default(),
+                                    license: RmrkCore::get_nft_property_inner(properties, RmrkProperty::License).unwrap().decode_or_default(),
+                                    thumb: RmrkCore::get_nft_property_inner(properties, RmrkProperty::Thumb).unwrap().decode_or_default(),
+                                },*///BasicResource<BoundedString>)
+                                _ => todo!(), //RmrkResourceTypes::Composable(ComposableResource<BoundedString, BoundedParts>),
+                                //RmrkResourceTypes::Slot(SlotResource<BoundedString>),
+                            },*/
+                        }))
+                        .collect();
+
+                    Ok(resources)
                 }
 
                 fn nft_resource_priorities(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Result<Vec<RmrkResourceId>, DispatchError> {
-                    todo!()
+                    use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, NftType, RmrkDecode}};
+
+                    let collection_id = CollectionId(collection_id);
+                    if !RmrkCore::collection_exists(collection_id) { return Ok(Vec::new()); } // todo ensure the collection type doesn't matter
+
+                    let nft_id = TokenId(nft_id);
+                    if RmrkCore::ensure_nft_type(collection_id, nft_id, NftType::Resource).is_err() { return Ok(Vec::new()); }
+
+                    /*let resource_collection_id: CollectionId = RmrkCore::get_nft_property(collection_id, nft_id, RmrkProperty::ResourceCollection)
+                        .unwrap()
+                        .decode_or_default();
+                    if RmrkCore::ensure_collection_type(collection_id, CollectionType::Resource).is_err() { return Ok(Vec::new()); }
+
+                    let resources = pallet_nonfungible::TokenProperties::<Runtime>::iter_prefix((resource_collection_id,))
+                        .filter_map(|(resource_id, properties)| Some((
+                            resource_id, // ResourceId property
+                            RmrkCore::get_nft_property(resource_collection_id, resource_id, RmrkProperty::Priority).unwrap().decode_or_default(),
+                        )))
+                        .collect()
+                        .sort_by_key(|(_, index)| *index)
+                        .into_iter().map(|(resource_id, _)| resource_id)*/
+                    let priorities = RmrkCore::get_nft_property(collection_id, nft_id, RmrkProperty::ResourcePriorities)?.decode_or_default();
+
+                    Ok(priorities)
                 }
 
                 fn base(base_id: RmrkBaseId) -> Result<Option<RmrkBaseInfo<AccountId>>, DispatchError> {
-                    use frame_support::BoundedVec;
-                    use scale_info::prelude::string::String;
                     use pallet_proxy_rmrk_core::{
-                        RmrkProperty, misc::{CollectionType, RmrkRebind, RmrkDecode},
+                        RmrkProperty, misc::{CollectionType, RmrkDecode},
                     };
 
                     let collection_id = CollectionId(base_id);
@@ -310,18 +348,17 @@
                     Ok(Some(RmrkBaseInfo {
                         issuer: collection.owner.clone(),
                         base_type: RmrkCore::get_collection_property(collection_id, RmrkProperty::BaseType)?.decode_or_default(),
-                        symbol: collection.token_prefix.rebind(),
+                        symbol: collection.token_prefix.decode_or_default(),
                     }))
                 }
 
                 fn base_parts(base_id: RmrkBaseId) -> Result<Vec<RmrkPartType>, DispatchError> {
-                    use frame_support::BoundedVec;
                     use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, NftType, RmrkDecode}};
 
                     let collection_id = CollectionId(base_id);
                     if RmrkCore::ensure_collection_type(collection_id, CollectionType::Base).is_err() { return Ok(Vec::new()); }
 
-                    let parts = (dispatch_unique_runtime!(collection_id.collection_tokens()))?
+                    let parts = dispatch_unique_runtime!(collection_id.collection_tokens())?
                         .into_iter()
                         .filter_map(|token_id| {
                             let nft_type = RmrkCore::get_nft_type(collection_id, token_id).ok()?;
@@ -347,7 +384,6 @@
                 }
 
                 fn theme_names(base_id: RmrkBaseId) -> Result<Vec<RmrkThemeName>, DispatchError> {
-                    use frame_support::BoundedVec;
                     use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, RmrkDecode}};
 
                     let collection_id = CollectionId(base_id);
@@ -355,7 +391,7 @@
                         return Ok(Vec::new());
                     }
 
-                    let theme_names = (dispatch_unique_runtime!(collection_id.collection_tokens()))?
+                    let theme_names = dispatch_unique_runtime!(collection_id.collection_tokens())?
                         .iter()
                         .filter_map(|token_id| {
                             let nft_type = RmrkCore::get_nft_type(collection_id, *token_id).unwrap();
@@ -373,7 +409,6 @@
                 }
 
                 fn theme(base_id: RmrkBaseId, theme_name: RmrkThemeName, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Result<Option<RmrkTheme>, DispatchError> {
-                    use frame_support::BoundedVec;
                     use pallet_proxy_rmrk_core::{
                         RmrkProperty,
                         misc::{CollectionType, NftType, RmrkDecode}
@@ -384,7 +419,7 @@
                         return Ok(None);
                     }
 
-                    let theme_info = (dispatch_unique_runtime!(collection_id.collection_tokens()))?
+                    let theme_info = dispatch_unique_runtime!(collection_id.collection_tokens())?
                         .into_iter()
                         .find_map(|token_id| {
                             RmrkCore::ensure_nft_type(collection_id, token_id, NftType::Theme).ok()?;
modifiedtests/src/nesting/properties.test.tsdiffbeforeafterboth
--- a/tests/src/nesting/properties.test.ts
+++ b/tests/src/nesting/properties.test.ts
@@ -711,7 +711,7 @@
     });
   });
 
-  it('Forbids changing/deleting properties of a token if the property is permanent (constant)', async () => {
+  it('Forbids changing/deleting properties of a token if the property is permanent (immutable)', async () => {
     await usingApi(async api => {
       let i = -1;
       for (const permission of constitution) {