git.delta.rocks / unique-network / refs/commits / 6be1bb56d5e4

difftreelog

feat split large fields out of Collection

Yaroslav Bolyukin2022-04-07parent: #3db55eb.patch.diff
in: master

7 files changed

modifiedclient/rpc/src/lib.rsdiffbeforeafterboth
--- a/client/rpc/src/lib.rs
+++ b/client/rpc/src/lib.rs
@@ -19,7 +19,7 @@
 use codec::Decode;
 use jsonrpc_core::{Error as RpcError, ErrorCode, Result};
 use jsonrpc_derive::rpc;
-use up_data_structs::{Collection, CollectionId, CollectionStats, CollectionLimits, TokenId};
+use up_data_structs::{RpcCollection, Collection, CollectionId, CollectionStats, CollectionLimits, TokenId};
 use sp_api::{BlockId, BlockT, ProvideRuntimeApi, ApiExt};
 use sp_blockchain::HeaderBackend;
 use up_rpc::UniqueApi as UniqueRuntimeApi;
@@ -116,7 +116,7 @@
 		&self,
 		collection: CollectionId,
 		at: Option<BlockHash>,
-	) -> Result<Option<Collection<AccountId>>>;
+	) -> Result<Option<RpcCollection<AccountId>>>;
 	#[rpc(name = "unique_collectionStats")]
 	fn collection_stats(&self, at: Option<BlockHash>) -> Result<CollectionStats>;
 
@@ -235,7 +235,7 @@
 	pass_method!(allowlist(collection: CollectionId) -> Vec<CrossAccountId>);
 	pass_method!(allowed(collection: CollectionId, user: CrossAccountId) -> bool);
 	pass_method!(last_token_id(collection: CollectionId) -> TokenId);
-	pass_method!(collection_by_id(collection: CollectionId) -> Option<Collection<AccountId>>);
+	pass_method!(collection_by_id(collection: CollectionId) -> Option<RpcCollection<AccountId>>);
 	pass_method!(collection_stats() -> CollectionStats);
 	pass_method!(next_sponsored(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Option<u64>);
 	pass_method!(effective_collection_limits(collection_id: CollectionId) -> Option<CollectionLimits>);
modifiedpallets/common/src/lib.rsdiffbeforeafterboth
--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -29,11 +29,11 @@
 };
 use pallet_evm::GasWeightMapping;
 use up_data_structs::{
-	COLLECTION_NUMBER_LIMIT, Collection, CollectionId, CreateItemData, MAX_TOKEN_PREFIX_LENGTH,
+	COLLECTION_NUMBER_LIMIT, Collection, RpcCollection, CollectionId, CreateItemData, MAX_TOKEN_PREFIX_LENGTH,
 	COLLECTION_ADMINS_LIMIT, MetaUpdatePermission, TokenId, CollectionStats, MAX_TOKEN_OWNERSHIP,
 	CollectionMode, NFT_SPONSOR_TRANSFER_TIMEOUT, FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
 	REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, MAX_SPONSOR_TIMEOUT, CUSTOM_DATA_LIMIT, CollectionLimits,
-	CustomDataLimit, CreateCollectionData, SponsorshipState, CreateItemExData, SponsoringRateLimit, budget::Budget,
+	CustomDataLimit, CreateCollectionData, SponsorshipState, CreateItemExData, SponsoringRateLimit, budget::Budget, COLLECTION_FIELD_LIMIT, CollectionField,
 };
 pub use pallet::*;
 use sp_core::H160;
@@ -352,6 +352,9 @@
 		OnlyOwnerAllowedToNest,
 		/// Only tokens from specific collections may nest tokens under this
 		SourceCollectionIsNotAllowedToNest,
+
+		/// Tried to store more data than allowed in collection field
+		CollectionFieldSizeExceeded,
 	}
 
 	#[pallet::storage]
@@ -369,6 +372,17 @@
 		QueryKind = OptionQuery,
 	>;
 
+	/// Large variable-size collection fields are extracted here
+	#[pallet::storage]
+	pub type CollectionData<T> = StorageNMap<
+		Key = (
+			Key<Twox64Concat, CollectionId>,
+			Key<Twox64Concat, CollectionField>,
+		),
+		Value = BoundedVec<u8, ConstU32<COLLECTION_FIELD_LIMIT>>,
+		QueryKind = ValueQuery,
+	>;
+
 	#[pallet::storage]
 	pub type AdminAmount<T> = StorageMap<
 		Hasher = Blake2_128Concat,
@@ -409,7 +423,26 @@
 		fn on_runtime_upgrade() -> Weight {
 			if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {
 				use up_data_structs::{CollectionVersion1, CollectionVersion2};
-				<CollectionById<T>>::translate_values::<CollectionVersion1<T::AccountId>, _>(|v| {
+				<CollectionById<T>>::translate::<CollectionVersion1<T::AccountId>, _>(|id, v| {
+					Self::set_field_raw(
+						id,
+						CollectionField::OffchainSchema,
+						v.offchain_schema.clone().into_inner(),
+					)
+					.expect("data has lower bounds than field");
+					Self::set_field_raw(
+						id,
+						CollectionField::VariableOnChainSchema,
+						v.variable_on_chain_schema.clone().into_inner(),
+					)
+					.expect("data has lower bounds than field");
+					Self::set_field_raw(
+						id,
+						CollectionField::ConstOnChainSchema,
+						v.const_on_chain_schema.clone().into_inner(),
+					)
+					.expect("data has lower bounds than field");
+
 					Some(CollectionVersion2::from(v))
 				});
 			}
@@ -483,6 +516,50 @@
 
 		Some(effective_limits)
 	}
+
+	pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {
+		let Collection {
+			name,
+			description,
+			owner,
+			mode,
+			access,
+			token_prefix,
+			mint_mode,
+			schema_version,
+			sponsorship,
+			limits,
+			meta_update_permission,
+		} = <CollectionById<T>>::get(collection)?;
+		Some(RpcCollection {
+			name: name.into_inner(),
+			description: description.into_inner(),
+			owner,
+			mode,
+			access,
+			token_prefix: token_prefix.into_inner(),
+			mint_mode,
+			schema_version,
+			sponsorship,
+			limits,
+			meta_update_permission,
+			offchain_schema: <CollectionData<T>>::get((
+				collection,
+				CollectionField::OffchainSchema,
+			))
+			.into_inner(),
+			const_on_chain_schema: <CollectionData<T>>::get((
+				collection,
+				CollectionField::ConstOnChainSchema,
+			))
+			.into_inner(),
+			variable_on_chain_schema: <CollectionData<T>>::get((
+				collection,
+				CollectionField::VariableOnChainSchema,
+			))
+			.into_inner(),
+		})
+	}
 }
 
 impl<T: Config> Pallet<T> {
@@ -520,14 +597,11 @@
 			access: data.access.unwrap_or_default(),
 			description: data.description,
 			token_prefix: data.token_prefix,
-			offchain_schema: data.offchain_schema,
 			schema_version: data.schema_version.unwrap_or_default(),
 			sponsorship: data
 				.pending_sponsor
 				.map(SponsorshipState::Unconfirmed)
 				.unwrap_or_default(),
-			variable_on_chain_schema: data.variable_on_chain_schema,
-			const_on_chain_schema: data.const_on_chain_schema,
 			limits: data
 				.limits
 				.map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))
@@ -557,6 +631,24 @@
 		<CreatedCollectionCount<T>>::put(created_count);
 		<Pallet<T>>::deposit_event(Event::CollectionCreated(id, data.mode.id(), owner.clone()));
 		<CollectionById<T>>::insert(id, collection);
+		Self::set_field_raw(
+			id,
+			CollectionField::OffchainSchema,
+			data.offchain_schema.into_inner(),
+		)
+		.expect("data has lower bounds than field");
+		Self::set_field_raw(
+			id,
+			CollectionField::VariableOnChainSchema,
+			data.variable_on_chain_schema.into_inner(),
+		)
+		.expect("data has lower bounds than field");
+		Self::set_field_raw(
+			id,
+			CollectionField::ConstOnChainSchema,
+			data.const_on_chain_schema.into_inner(),
+		)
+		.expect("data has lower bounds than field");
 		Ok(id)
 	}
 
@@ -579,6 +671,7 @@
 
 		<DestroyedCollectionCount<T>>::put(destroyed_collections);
 		<CollectionById<T>>::remove(collection.id);
+		<CollectionData<T>>::remove_prefix((collection.id,), None);
 		<AdminAmount<T>>::remove(collection.id);
 		<IsAdmin<T>>::remove_prefix((collection.id,), None);
 		<Allowlist<T>>::remove_prefix((collection.id,), None);
@@ -587,6 +680,35 @@
 		Ok(())
 	}
 
+	fn set_field_raw(
+		collection_id: CollectionId,
+		field: CollectionField,
+		value: Vec<u8>,
+	) -> DispatchResult {
+		if !value.is_empty() {
+			<CollectionData<T>>::insert(
+				(collection_id, field),
+				BoundedVec::try_from(value).map_err(|_| <Error<T>>::CollectionFieldSizeExceeded)?,
+			)
+		} else {
+			<CollectionData<T>>::remove((collection_id, field));
+		}
+		Ok(())
+	}
+
+	pub fn set_field(
+		collection: &CollectionHandle<T>,
+		sender: &T::CrossAccountId,
+		field: CollectionField,
+		value: Vec<u8>,
+	) -> DispatchResult {
+		collection.check_is_owner_or_admin(sender)?;
+
+		// =========
+
+		Self::set_field_raw(collection.id, field, value)
+	}
+
 	pub fn toggle_allowlist(
 		collection: &CollectionHandle<T>,
 		sender: &T::CrossAccountId,
modifiedpallets/unique/src/lib.rsdiffbeforeafterboth
--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -43,7 +43,7 @@
 	MAX_COLLECTION_NAME_LENGTH, MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH,
 	AccessMode, CreateItemData, CollectionLimits, CollectionId, CollectionMode, TokenId,
 	SchemaVersion, SponsorshipState, MetaUpdatePermission, CreateCollectionData, CustomDataLimit,
-	CreateItemExData, budget,
+	CreateItemExData, budget, CollectionField,
 };
 use pallet_evm::account::CrossAccountId;
 use pallet_common::{
@@ -1004,16 +1004,16 @@
 			schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,
 		) -> DispatchResult {
 			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
-			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
-			target_collection.check_is_owner_or_admin(&sender)?;
+			let collection = <CollectionHandle<T>>::try_get(collection_id)?;
+
+			// =========
 
-			target_collection.offchain_schema = schema;
+			<PalletCommon<T>>::set_field(&collection, &sender, CollectionField::OffchainSchema, schema.into_inner())?;
 
 			<Pallet<T>>::deposit_event(Event::<T>::OffchainSchemaSet(
 				collection_id
 			));
-
-			target_collection.save()
+			Ok(())
 		}
 
 		/// Set const on-chain data schema.
@@ -1036,16 +1036,16 @@
 			schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>
 		) -> DispatchResult {
 			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
-			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
-			target_collection.check_is_owner_or_admin(&sender)?;
+			let collection = <CollectionHandle<T>>::try_get(collection_id)?;
+
+			// =========
 
-			target_collection.const_on_chain_schema = schema;
+			<PalletCommon<T>>::set_field(&collection, &sender, CollectionField::ConstOnChainSchema, schema.into_inner())?;
 
 			<Pallet<T>>::deposit_event(Event::<T>::ConstOnChainSchemaSet(
 				collection_id
 			));
-
-			target_collection.save()
+			Ok(())
 		}
 
 		/// Set variable on-chain data schema.
@@ -1068,16 +1068,16 @@
 			schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>
 		) -> DispatchResult {
 			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
-			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
-			target_collection.check_is_owner_or_admin(&sender)?;
+			let collection = <CollectionHandle<T>>::try_get(collection_id)?;
+
+			// =========
 
-			target_collection.variable_on_chain_schema = schema;
+			<PalletCommon<T>>::set_field(&collection, &sender, CollectionField::VariableOnChainSchema, schema.into_inner())?;
 
 			<Pallet<T>>::deposit_event(Event::<T>::VariableOnChainSchemaSet(
 				collection_id
 			));
-
-			target_collection.save()
+			Ok(())
 		}
 
 		#[weight = <SelfWeightOf<T>>::set_collection_limits()]
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};2627#[cfg(feature = "serde")]28use serde::{Serialize, Deserialize};2930use sp_core::U256;31use sp_runtime::{ArithmeticError, sp_std::prelude::Vec};32use codec::{Decode, Encode, EncodeLike, MaxEncodedLen};33use frame_support::{BoundedVec, traits::ConstU32};34use derivative::Derivative;35use scale_info::TypeInfo;3637mod bounded;38pub mod budget;39pub mod mapping;40mod migration;4142pub const MAX_DECIMAL_POINTS: DecimalPoints = 30;43pub const MAX_REFUNGIBLE_PIECES: u128 = 1_000_000_000_000_000_000_000;44pub const MAX_SPONSOR_TIMEOUT: u32 = 10_368_000;4546pub const MAX_TOKEN_OWNERSHIP: u32 = if cfg!(not(feature = "limit-testing")) {47	100_00048} else {49	1050};51pub const COLLECTION_NUMBER_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {52	100_00053} else {54	1055};56pub const CUSTOM_DATA_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {57	204858} else {59	1060};61pub const COLLECTION_ADMINS_LIMIT: u32 = 5;62pub const COLLECTION_TOKEN_LIMIT: u32 = u32::MAX;63pub const ACCOUNT_TOKEN_OWNERSHIP_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {64	1_000_00065} else {66	1067};6869// Timeouts for item types in passed blocks70pub const NFT_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;71pub const FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;72pub const REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;7374pub const SPONSOR_APPROVE_TIMEOUT: u32 = 5;7576// Schema limits77pub const OFFCHAIN_SCHEMA_LIMIT: u32 = 8192;78pub const VARIABLE_ON_CHAIN_SCHEMA_LIMIT: u32 = 8192;79pub const CONST_ON_CHAIN_SCHEMA_LIMIT: u32 = 32768;8081pub const MAX_COLLECTION_NAME_LENGTH: u32 = 64;82pub const MAX_COLLECTION_DESCRIPTION_LENGTH: u32 = 256;83pub const MAX_TOKEN_PREFIX_LENGTH: u32 = 16;8485/// How much items can be created per single86/// create_many call87pub const MAX_ITEMS_PER_BATCH: u32 = 200;8889pub type CustomDataLimit = ConstU32<CUSTOM_DATA_LIMIT>;9091#[derive(92	Encode,93	Decode,94	PartialEq,95	Eq,96	PartialOrd,97	Ord,98	Clone,99	Copy,100	Debug,101	Default,102	TypeInfo,103	MaxEncodedLen,104)]105#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]106pub struct CollectionId(pub u32);107impl EncodeLike<u32> for CollectionId {}108impl EncodeLike<CollectionId> for u32 {}109110#[derive(111	Encode,112	Decode,113	PartialEq,114	Eq,115	PartialOrd,116	Ord,117	Clone,118	Copy,119	Debug,120	Default,121	TypeInfo,122	MaxEncodedLen,123)]124#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]125pub struct TokenId(pub u32);126impl EncodeLike<u32> for TokenId {}127impl EncodeLike<TokenId> for u32 {}128129impl TokenId {130	pub fn try_next(self) -> Result<TokenId, ArithmeticError> {131		self.0132			.checked_add(1)133			.ok_or(ArithmeticError::Overflow)134			.map(Self)135	}136}137138impl From<TokenId> for U256 {139	fn from(t: TokenId) -> Self {140		t.0.into()141	}142}143144impl TryFrom<U256> for TokenId {145	type Error = &'static str;146147	fn try_from(value: U256) -> Result<Self, Self::Error> {148		Ok(TokenId(value.try_into().map_err(|_| "too large token id")?))149	}150}151152pub struct OverflowError;153impl From<OverflowError> for &'static str {154	fn from(_: OverflowError) -> Self {155		"overflow occured"156	}157}158159pub type DecimalPoints = u8;160161#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]162#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]163pub enum CollectionMode {164	NFT,165	// decimal points166	Fungible(DecimalPoints),167	ReFungible,168}169170impl CollectionMode {171	pub fn id(&self) -> u8 {172		match self {173			CollectionMode::NFT => 1,174			CollectionMode::Fungible(_) => 2,175			CollectionMode::ReFungible => 3,176		}177	}178}179180pub trait SponsoringResolve<AccountId, Call> {181	fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>;182}183184#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]185#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]186pub enum AccessMode {187	Normal,188	AllowList,189}190impl Default for AccessMode {191	fn default() -> Self {192		Self::Normal193	}194}195196#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]197#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]198pub enum SchemaVersion {199	ImageURL,200	Unique,201}202impl Default for SchemaVersion {203	fn default() -> Self {204		Self::ImageURL205	}206}207208#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]209#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]210pub struct Ownership<AccountId> {211	pub owner: AccountId,212	pub fraction: u128,213}214215#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]216#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]217pub enum SponsorshipState<AccountId> {218	/// The fees are applied to the transaction sender219	Disabled,220	Unconfirmed(AccountId),221	/// Transactions are sponsored by specified account222	Confirmed(AccountId),223}224225impl<AccountId> SponsorshipState<AccountId> {226	pub fn sponsor(&self) -> Option<&AccountId> {227		match self {228			Self::Confirmed(sponsor) => Some(sponsor),229			_ => None,230		}231	}232233	pub fn pending_sponsor(&self) -> Option<&AccountId> {234		match self {235			Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),236			_ => None,237		}238	}239240	pub fn confirmed(&self) -> bool {241		matches!(self, Self::Confirmed(_))242	}243}244245impl<T> Default for SponsorshipState<T> {246	fn default() -> Self {247		Self::Disabled248	}249}250251#[struct_versioning::versioned(version = 2, upper)]252#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen)]253#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]254pub struct Collection<AccountId> {255	pub owner: AccountId,256	pub mode: CollectionMode,257	pub access: AccessMode,258	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]259	pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,260	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]261	pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,262	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]263	pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,264	pub mint_mode: bool,265	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]266	pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,267	pub schema_version: SchemaVersion,268	pub sponsorship: SponsorshipState<AccountId>,269270	#[version(..2)]271	pub limits: CollectionLimitsVersion1, // Collection private restrictions272	#[version(2.., upper(limits.into()))]273	pub limits: CollectionLimitsVersion2,274275	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]276	pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,277	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]278	pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,279	pub meta_update_permission: MetaUpdatePermission,280}281282#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Debug, Derivative, MaxEncodedLen)]283#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]284#[derivative(Default(bound = ""))]285pub struct CreateCollectionData<AccountId> {286	#[derivative(Default(value = "CollectionMode::NFT"))]287	pub mode: CollectionMode,288	pub access: Option<AccessMode>,289	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]290	pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,291	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]292	pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,293	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]294	pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,295	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]296	pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,297	pub schema_version: Option<SchemaVersion>,298	pub pending_sponsor: Option<AccountId>,299	pub limits: Option<CollectionLimits>,300	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]301	pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,302	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]303	pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,304	pub meta_update_permission: Option<MetaUpdatePermission>,305}306307#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]308#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]309pub struct NftItemType<AccountId> {310	pub owner: AccountId,311	pub const_data: Vec<u8>,312	pub variable_data: Vec<u8>,313}314315#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]316#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]317pub struct FungibleItemType {318	pub value: u128,319}320321#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]322#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]323pub struct ReFungibleItemType<AccountId> {324	pub owner: Vec<Ownership<AccountId>>,325	pub const_data: Vec<u8>,326	pub variable_data: Vec<u8>,327}328329/// All fields are wrapped in `Option`s, where None means chain default330#[struct_versioning::versioned(version = 2, upper)]331#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]332#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]333pub struct CollectionLimits {334	pub account_token_ownership_limit: Option<u32>,335	pub sponsored_data_size: Option<u32>,336	/// None - setVariableMetadata is not sponsored337	/// Some(v) - setVariableMetadata is sponsored338	///           if there is v block between txs339	pub sponsored_data_rate_limit: Option<SponsoringRateLimit>,340	pub token_limit: Option<u32>,341342	// Timeouts for item types in passed blocks343	pub sponsor_transfer_timeout: Option<u32>,344	pub sponsor_approve_timeout: Option<u32>,345	pub owner_can_transfer: Option<bool>,346	pub owner_can_destroy: Option<bool>,347	pub transfers_enabled: Option<bool>,348349	#[version(2.., upper(None))]350	pub nesting_rule: Option<NestingRule>,351}352353impl CollectionLimits {354	pub fn account_token_ownership_limit(&self) -> u32 {355		self.account_token_ownership_limit356			.unwrap_or(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)357			.min(MAX_TOKEN_OWNERSHIP)358	}359	pub fn sponsored_data_size(&self) -> u32 {360		self.sponsored_data_size361			.unwrap_or(CUSTOM_DATA_LIMIT)362			.min(CUSTOM_DATA_LIMIT)363	}364	pub fn token_limit(&self) -> u32 {365		self.token_limit366			.unwrap_or(COLLECTION_TOKEN_LIMIT)367			.min(COLLECTION_TOKEN_LIMIT)368	}369	pub fn sponsor_transfer_timeout(&self, default: u32) -> u32 {370		self.sponsor_transfer_timeout371			.unwrap_or(default)372			.min(MAX_SPONSOR_TIMEOUT)373	}374	pub fn sponsor_approve_timeout(&self) -> u32 {375		self.sponsor_approve_timeout376			.unwrap_or(SPONSOR_APPROVE_TIMEOUT)377			.min(MAX_SPONSOR_TIMEOUT)378	}379	pub fn owner_can_transfer(&self) -> bool {380		self.owner_can_transfer.unwrap_or(true)381	}382	pub fn owner_can_destroy(&self) -> bool {383		self.owner_can_destroy.unwrap_or(true)384	}385	pub fn transfers_enabled(&self) -> bool {386		self.transfers_enabled.unwrap_or(true)387	}388	pub fn sponsored_data_rate_limit(&self) -> Option<u32> {389		match self390			.sponsored_data_rate_limit391			.unwrap_or(SponsoringRateLimit::SponsoringDisabled)392		{393			SponsoringRateLimit::SponsoringDisabled => None,394			SponsoringRateLimit::Blocks(v) => Some(v.min(MAX_SPONSOR_TIMEOUT)),395		}396	}397	pub fn nesting_rule(&self) -> &NestingRule {398		static DEFAULT: NestingRule = NestingRule::Owner;399		self.nesting_rule.as_ref().unwrap_or(&DEFAULT)400	}401}402403#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative)]404#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]405#[derivative(Debug)]406pub enum NestingRule {407	/// No one can nest tokens408	Disabled,409	/// Owner can nest any tokens410	Owner,411	/// Owner can nest tokens from specified collections412	OwnerRestricted(413		#[cfg_attr(feature = "serde1", serde(with = "bounded::set_serde"))]414		#[derivative(Debug(format_with = "bounded::set_debug"))]415		BoundedBTreeSet<CollectionId, ConstU32<16>>,416	),417}418419#[derive(Encode, Decode, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]420#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]421pub enum SponsoringRateLimit {422	SponsoringDisabled,423	Blocks(u32),424}425426#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]427#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]428#[derivative(Debug)]429pub struct CreateNftData {430	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]431	#[derivative(Debug(format_with = "bounded::vec_debug"))]432	pub const_data: BoundedVec<u8, CustomDataLimit>,433	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]434	#[derivative(Debug(format_with = "bounded::vec_debug"))]435	pub variable_data: BoundedVec<u8, CustomDataLimit>,436}437438#[derive(Encode, Decode, MaxEncodedLen, Default, Debug, Clone, PartialEq, TypeInfo)]439#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]440pub struct CreateFungibleData {441	pub value: u128,442}443444#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]445#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]446#[derivative(Debug)]447pub struct CreateReFungibleData {448	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]449	#[derivative(Debug(format_with = "bounded::vec_debug"))]450	pub const_data: BoundedVec<u8, CustomDataLimit>,451	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]452	#[derivative(Debug(format_with = "bounded::vec_debug"))]453	pub variable_data: BoundedVec<u8, CustomDataLimit>,454	pub pieces: u128,455}456457#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]458#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]459pub enum MetaUpdatePermission {460	ItemOwner,461	Admin,462	None,463}464465impl Default for MetaUpdatePermission {466	fn default() -> Self {467		Self::ItemOwner468	}469}470471#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]472#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]473pub enum CreateItemData {474	NFT(CreateNftData),475	Fungible(CreateFungibleData),476	ReFungible(CreateReFungibleData),477}478479#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]480#[derivative(Debug)]481pub struct CreateNftExData<CrossAccountId> {482	#[derivative(Debug(format_with = "bounded::vec_debug"))]483	pub const_data: BoundedVec<u8, CustomDataLimit>,484	#[derivative(Debug(format_with = "bounded::vec_debug"))]485	pub variable_data: BoundedVec<u8, CustomDataLimit>,486	pub owner: CrossAccountId,487}488489#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]490#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]491pub struct CreateRefungibleExData<CrossAccountId> {492	#[derivative(Debug(format_with = "bounded::vec_debug"))]493	pub const_data: BoundedVec<u8, CustomDataLimit>,494	#[derivative(Debug(format_with = "bounded::vec_debug"))]495	pub variable_data: BoundedVec<u8, CustomDataLimit>,496	#[derivative(Debug(format_with = "bounded::map_debug"))]497	pub users: BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,498}499500#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]501#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]502pub enum CreateItemExData<CrossAccountId> {503	NFT(504		#[derivative(Debug(format_with = "bounded::vec_debug"))]505		BoundedVec<CreateNftExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,506	),507	Fungible(508		#[derivative(Debug(format_with = "bounded::map_debug"))]509		BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,510	),511	/// Many tokens, each may have only one owner512	RefungibleMultipleItems(513		#[derivative(Debug(format_with = "bounded::vec_debug"))]514		BoundedVec<CreateRefungibleExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,515	),516	/// Single token, which may have many owners517	RefungibleMultipleOwners(CreateRefungibleExData<CrossAccountId>),518}519520impl CreateItemData {521	pub fn data_size(&self) -> usize {522		match self {523			CreateItemData::NFT(data) => data.variable_data.len() + data.const_data.len(),524			CreateItemData::ReFungible(data) => data.variable_data.len() + data.const_data.len(),525			_ => 0,526		}527	}528}529530impl From<CreateNftData> for CreateItemData {531	fn from(item: CreateNftData) -> Self {532		CreateItemData::NFT(item)533	}534}535536impl From<CreateReFungibleData> for CreateItemData {537	fn from(item: CreateReFungibleData) -> Self {538		CreateItemData::ReFungible(item)539	}540}541542impl From<CreateFungibleData> for CreateItemData {543	fn from(item: CreateFungibleData) -> Self {544		CreateItemData::Fungible(item)545	}546}547548#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]549#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]550pub struct CollectionStats {551	pub created: u32,552	pub destroyed: u32,553	pub alive: u32,554}
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};2627#[cfg(feature = "serde")]28use serde::{Serialize, Deserialize};2930use sp_core::U256;31use sp_runtime::{ArithmeticError, sp_std::prelude::Vec};32use codec::{Decode, Encode, EncodeLike, MaxEncodedLen};33use frame_support::{BoundedVec, traits::ConstU32};34use derivative::Derivative;35use scale_info::TypeInfo;3637mod bounded;38pub mod budget;39pub mod mapping;40mod migration;4142pub const MAX_DECIMAL_POINTS: DecimalPoints = 30;43pub const MAX_REFUNGIBLE_PIECES: u128 = 1_000_000_000_000_000_000_000;44pub const MAX_SPONSOR_TIMEOUT: u32 = 10_368_000;4546pub const MAX_TOKEN_OWNERSHIP: u32 = if cfg!(not(feature = "limit-testing")) {47	100_00048} else {49	1050};51pub const COLLECTION_NUMBER_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {52	100_00053} else {54	1055};56pub const CUSTOM_DATA_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {57	204858} else {59	1060};61pub const COLLECTION_ADMINS_LIMIT: u32 = 5;62pub const COLLECTION_TOKEN_LIMIT: u32 = u32::MAX;63pub const ACCOUNT_TOKEN_OWNERSHIP_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {64	1_000_00065} else {66	1067};6869// Timeouts for item types in passed blocks70pub const NFT_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;71pub const FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;72pub const REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;7374pub const SPONSOR_APPROVE_TIMEOUT: u32 = 5;7576// Schema limits77pub const OFFCHAIN_SCHEMA_LIMIT: u32 = 8192;78pub const VARIABLE_ON_CHAIN_SCHEMA_LIMIT: u32 = 8192;79pub const CONST_ON_CHAIN_SCHEMA_LIMIT: u32 = 32768;8081pub const COLLECTION_FIELD_LIMIT: u32 = CONST_ON_CHAIN_SCHEMA_LIMIT;82// u32::max is not const: OFFCHAIN_SCHEMA_LIMIT.max(VARIABLE_ON_CHAIN_SCHEMA_LIMIT).max(CONST_ON_CHAIN_SCHEMA_LIMIT);8384pub const MAX_COLLECTION_NAME_LENGTH: u32 = 64;85pub const MAX_COLLECTION_DESCRIPTION_LENGTH: u32 = 256;86pub const MAX_TOKEN_PREFIX_LENGTH: u32 = 16;8788/// How much items can be created per single89/// create_many call90pub const MAX_ITEMS_PER_BATCH: u32 = 200;9192pub type CustomDataLimit = ConstU32<CUSTOM_DATA_LIMIT>;9394#[derive(95	Encode,96	Decode,97	PartialEq,98	Eq,99	PartialOrd,100	Ord,101	Clone,102	Copy,103	Debug,104	Default,105	TypeInfo,106	MaxEncodedLen,107)]108#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]109pub struct CollectionId(pub u32);110impl EncodeLike<u32> for CollectionId {}111impl EncodeLike<CollectionId> for u32 {}112113#[derive(114	Encode,115	Decode,116	PartialEq,117	Eq,118	PartialOrd,119	Ord,120	Clone,121	Copy,122	Debug,123	Default,124	TypeInfo,125	MaxEncodedLen,126)]127#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]128pub struct TokenId(pub u32);129impl EncodeLike<u32> for TokenId {}130impl EncodeLike<TokenId> for u32 {}131132impl TokenId {133	pub fn try_next(self) -> Result<TokenId, ArithmeticError> {134		self.0135			.checked_add(1)136			.ok_or(ArithmeticError::Overflow)137			.map(Self)138	}139}140141impl From<TokenId> for U256 {142	fn from(t: TokenId) -> Self {143		t.0.into()144	}145}146147impl TryFrom<U256> for TokenId {148	type Error = &'static str;149150	fn try_from(value: U256) -> Result<Self, Self::Error> {151		Ok(TokenId(value.try_into().map_err(|_| "too large token id")?))152	}153}154155pub struct OverflowError;156impl From<OverflowError> for &'static str {157	fn from(_: OverflowError) -> Self {158		"overflow occured"159	}160}161162pub type DecimalPoints = u8;163164#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]165#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]166pub enum CollectionMode {167	NFT,168	// decimal points169	Fungible(DecimalPoints),170	ReFungible,171}172173impl CollectionMode {174	pub fn id(&self) -> u8 {175		match self {176			CollectionMode::NFT => 1,177			CollectionMode::Fungible(_) => 2,178			CollectionMode::ReFungible => 3,179		}180	}181}182183pub trait SponsoringResolve<AccountId, Call> {184	fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>;185}186187#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]188#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]189pub enum AccessMode {190	Normal,191	AllowList,192}193impl Default for AccessMode {194	fn default() -> Self {195		Self::Normal196	}197}198199#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]200#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]201pub enum SchemaVersion {202	ImageURL,203	Unique,204}205impl Default for SchemaVersion {206	fn default() -> Self {207		Self::ImageURL208	}209}210211#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]212#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]213pub struct Ownership<AccountId> {214	pub owner: AccountId,215	pub fraction: u128,216}217218#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]219#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]220pub enum SponsorshipState<AccountId> {221	/// The fees are applied to the transaction sender222	Disabled,223	Unconfirmed(AccountId),224	/// Transactions are sponsored by specified account225	Confirmed(AccountId),226}227228impl<AccountId> SponsorshipState<AccountId> {229	pub fn sponsor(&self) -> Option<&AccountId> {230		match self {231			Self::Confirmed(sponsor) => Some(sponsor),232			_ => None,233		}234	}235236	pub fn pending_sponsor(&self) -> Option<&AccountId> {237		match self {238			Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),239			_ => None,240		}241	}242243	pub fn confirmed(&self) -> bool {244		matches!(self, Self::Confirmed(_))245	}246}247248impl<T> Default for SponsorshipState<T> {249	fn default() -> Self {250		Self::Disabled251	}252}253254/// Used in storage255#[struct_versioning::versioned(version = 2, upper)]256#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen)]257pub struct Collection<AccountId> {258	pub owner: AccountId,259	pub mode: CollectionMode,260	pub access: AccessMode,261	pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,262	pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,263	pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,264	pub mint_mode: bool,265266	#[version(..2)]267	pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,268269	pub schema_version: SchemaVersion,270	pub sponsorship: SponsorshipState<AccountId>,271272	#[version(..2)]273	pub limits: CollectionLimitsVersion1, // Collection private restrictions274	#[version(2.., upper(limits.into()))]275	pub limits: CollectionLimitsVersion2,276277	#[version(..2)]278	pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,279	#[version(..2)]280	pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,281282	pub meta_update_permission: MetaUpdatePermission,283}284285/// Used in RPC calls286#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]287#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]288pub struct RpcCollection<AccountId> {289	pub owner: AccountId,290	pub mode: CollectionMode,291	pub access: AccessMode,292	pub name: Vec<u16>,293	pub description: Vec<u16>,294	pub token_prefix: Vec<u8>,295	pub mint_mode: bool,296	pub offchain_schema: Vec<u8>,297	pub schema_version: SchemaVersion,298	pub sponsorship: SponsorshipState<AccountId>,299	pub limits: CollectionLimits,300	pub variable_on_chain_schema: Vec<u8>,301	pub const_on_chain_schema: Vec<u8>,302	pub meta_update_permission: MetaUpdatePermission,303}304305#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen)]306#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]307pub enum CollectionField {308	VariableOnChainSchema,309	ConstOnChainSchema,310	OffchainSchema,311}312313#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Debug, Derivative, MaxEncodedLen)]314#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]315#[derivative(Default(bound = ""))]316pub struct CreateCollectionData<AccountId> {317	#[derivative(Default(value = "CollectionMode::NFT"))]318	pub mode: CollectionMode,319	pub access: Option<AccessMode>,320	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]321	pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,322	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]323	pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,324	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]325	pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,326	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]327	pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,328	pub schema_version: Option<SchemaVersion>,329	pub pending_sponsor: Option<AccountId>,330	pub limits: Option<CollectionLimits>,331	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]332	pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,333	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]334	pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,335	pub meta_update_permission: Option<MetaUpdatePermission>,336}337338#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]339#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]340pub struct NftItemType<AccountId> {341	pub owner: AccountId,342	pub const_data: Vec<u8>,343	pub variable_data: Vec<u8>,344}345346#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]347#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]348pub struct FungibleItemType {349	pub value: u128,350}351352#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]353#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]354pub struct ReFungibleItemType<AccountId> {355	pub owner: Vec<Ownership<AccountId>>,356	pub const_data: Vec<u8>,357	pub variable_data: Vec<u8>,358}359360/// All fields are wrapped in `Option`s, where None means chain default361#[struct_versioning::versioned(version = 2, upper)]362#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]363#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]364pub struct CollectionLimits {365	pub account_token_ownership_limit: Option<u32>,366	pub sponsored_data_size: Option<u32>,367	/// None - setVariableMetadata is not sponsored368	/// Some(v) - setVariableMetadata is sponsored369	///           if there is v block between txs370	pub sponsored_data_rate_limit: Option<SponsoringRateLimit>,371	pub token_limit: Option<u32>,372373	// Timeouts for item types in passed blocks374	pub sponsor_transfer_timeout: Option<u32>,375	pub sponsor_approve_timeout: Option<u32>,376	pub owner_can_transfer: Option<bool>,377	pub owner_can_destroy: Option<bool>,378	pub transfers_enabled: Option<bool>,379380	#[version(2.., upper(None))]381	pub nesting_rule: Option<NestingRule>,382}383384impl CollectionLimits {385	pub fn account_token_ownership_limit(&self) -> u32 {386		self.account_token_ownership_limit387			.unwrap_or(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)388			.min(MAX_TOKEN_OWNERSHIP)389	}390	pub fn sponsored_data_size(&self) -> u32 {391		self.sponsored_data_size392			.unwrap_or(CUSTOM_DATA_LIMIT)393			.min(CUSTOM_DATA_LIMIT)394	}395	pub fn token_limit(&self) -> u32 {396		self.token_limit397			.unwrap_or(COLLECTION_TOKEN_LIMIT)398			.min(COLLECTION_TOKEN_LIMIT)399	}400	pub fn sponsor_transfer_timeout(&self, default: u32) -> u32 {401		self.sponsor_transfer_timeout402			.unwrap_or(default)403			.min(MAX_SPONSOR_TIMEOUT)404	}405	pub fn sponsor_approve_timeout(&self) -> u32 {406		self.sponsor_approve_timeout407			.unwrap_or(SPONSOR_APPROVE_TIMEOUT)408			.min(MAX_SPONSOR_TIMEOUT)409	}410	pub fn owner_can_transfer(&self) -> bool {411		self.owner_can_transfer.unwrap_or(true)412	}413	pub fn owner_can_destroy(&self) -> bool {414		self.owner_can_destroy.unwrap_or(true)415	}416	pub fn transfers_enabled(&self) -> bool {417		self.transfers_enabled.unwrap_or(true)418	}419	pub fn sponsored_data_rate_limit(&self) -> Option<u32> {420		match self421			.sponsored_data_rate_limit422			.unwrap_or(SponsoringRateLimit::SponsoringDisabled)423		{424			SponsoringRateLimit::SponsoringDisabled => None,425			SponsoringRateLimit::Blocks(v) => Some(v.min(MAX_SPONSOR_TIMEOUT)),426		}427	}428	pub fn nesting_rule(&self) -> &NestingRule {429		static DEFAULT: NestingRule = NestingRule::Owner;430		self.nesting_rule.as_ref().unwrap_or(&DEFAULT)431	}432}433434#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative)]435#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]436#[derivative(Debug)]437pub enum NestingRule {438	/// No one can nest tokens439	Disabled,440	/// Owner can nest any tokens441	Owner,442	/// Owner can nest tokens from specified collections443	OwnerRestricted(444		#[cfg_attr(feature = "serde1", serde(with = "bounded::set_serde"))]445		#[derivative(Debug(format_with = "bounded::set_debug"))]446		BoundedBTreeSet<CollectionId, ConstU32<16>>,447	),448}449450#[derive(Encode, Decode, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]451#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]452pub enum SponsoringRateLimit {453	SponsoringDisabled,454	Blocks(u32),455}456457#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]458#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]459#[derivative(Debug)]460pub struct CreateNftData {461	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]462	#[derivative(Debug(format_with = "bounded::vec_debug"))]463	pub const_data: BoundedVec<u8, CustomDataLimit>,464	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]465	#[derivative(Debug(format_with = "bounded::vec_debug"))]466	pub variable_data: BoundedVec<u8, CustomDataLimit>,467}468469#[derive(Encode, Decode, MaxEncodedLen, Default, Debug, Clone, PartialEq, TypeInfo)]470#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]471pub struct CreateFungibleData {472	pub value: u128,473}474475#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]476#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]477#[derivative(Debug)]478pub struct CreateReFungibleData {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>,482	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]483	#[derivative(Debug(format_with = "bounded::vec_debug"))]484	pub variable_data: BoundedVec<u8, CustomDataLimit>,485	pub pieces: u128,486}487488#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]489#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]490pub enum MetaUpdatePermission {491	ItemOwner,492	Admin,493	None,494}495496impl Default for MetaUpdatePermission {497	fn default() -> Self {498		Self::ItemOwner499	}500}501502#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]503#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]504pub enum CreateItemData {505	NFT(CreateNftData),506	Fungible(CreateFungibleData),507	ReFungible(CreateReFungibleData),508}509510#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]511#[derivative(Debug)]512pub struct CreateNftExData<CrossAccountId> {513	#[derivative(Debug(format_with = "bounded::vec_debug"))]514	pub const_data: BoundedVec<u8, CustomDataLimit>,515	#[derivative(Debug(format_with = "bounded::vec_debug"))]516	pub variable_data: BoundedVec<u8, CustomDataLimit>,517	pub owner: CrossAccountId,518}519520#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]521#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]522pub struct CreateRefungibleExData<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 variable_data: BoundedVec<u8, CustomDataLimit>,527	#[derivative(Debug(format_with = "bounded::map_debug"))]528	pub users: BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,529}530531#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]532#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]533pub enum CreateItemExData<CrossAccountId> {534	NFT(535		#[derivative(Debug(format_with = "bounded::vec_debug"))]536		BoundedVec<CreateNftExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,537	),538	Fungible(539		#[derivative(Debug(format_with = "bounded::map_debug"))]540		BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,541	),542	/// Many tokens, each may have only one owner543	RefungibleMultipleItems(544		#[derivative(Debug(format_with = "bounded::vec_debug"))]545		BoundedVec<CreateRefungibleExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,546	),547	/// Single token, which may have many owners548	RefungibleMultipleOwners(CreateRefungibleExData<CrossAccountId>),549}550551impl CreateItemData {552	pub fn data_size(&self) -> usize {553		match self {554			CreateItemData::NFT(data) => data.variable_data.len() + data.const_data.len(),555			CreateItemData::ReFungible(data) => data.variable_data.len() + data.const_data.len(),556			_ => 0,557		}558	}559}560561impl From<CreateNftData> for CreateItemData {562	fn from(item: CreateNftData) -> Self {563		CreateItemData::NFT(item)564	}565}566567impl From<CreateReFungibleData> for CreateItemData {568	fn from(item: CreateReFungibleData) -> Self {569		CreateItemData::ReFungible(item)570	}571}572573impl From<CreateFungibleData> for CreateItemData {574	fn from(item: CreateFungibleData) -> Self {575		CreateItemData::Fungible(item)576	}577}578579#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]580#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]581pub struct CollectionStats {582	pub created: u32,583	pub destroyed: u32,584	pub alive: u32,585}
modifiedprimitives/rpc/src/lib.rsdiffbeforeafterboth
--- a/primitives/rpc/src/lib.rs
+++ b/primitives/rpc/src/lib.rs
@@ -16,7 +16,7 @@
 
 #![cfg_attr(not(feature = "std"), no_std)]
 
-use up_data_structs::{CollectionId, TokenId, Collection, CollectionStats, CollectionLimits};
+use up_data_structs::{CollectionId, TokenId, RpcCollection, Collection, CollectionStats, CollectionLimits};
 use sp_std::vec::Vec;
 use codec::Decode;
 use sp_runtime::DispatchError;
@@ -53,7 +53,7 @@
 		fn allowlist(collection: CollectionId) -> Result<Vec<CrossAccountId>>;
 		fn allowed(collection: CollectionId, user: CrossAccountId) -> Result<bool>;
 		fn last_token_id(collection: CollectionId) -> Result<TokenId>;
-		fn collection_by_id(collection: CollectionId) -> Result<Option<Collection<AccountId>>>;
+		fn collection_by_id(collection: CollectionId) -> Result<Option<RpcCollection<AccountId>>>;
 		fn collection_stats() -> Result<CollectionStats>;
 		fn next_sponsored(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<Option<u64>>;
 		fn effective_collection_limits(collection_id: CollectionId) -> Result<Option<CollectionLimits>>;
modifiedruntime/common/src/runtime_apis.rsdiffbeforeafterboth
--- a/runtime/common/src/runtime_apis.rs
+++ b/runtime/common/src/runtime_apis.rs
@@ -58,8 +58,8 @@
                 fn last_token_id(collection: CollectionId) -> Result<TokenId, DispatchError> {
                     dispatch_unique_runtime!(collection.last_token_id())
                 }
-                fn collection_by_id(collection: CollectionId) -> Result<Option<Collection<AccountId>>, DispatchError> {
-                    Ok(<pallet_common::CollectionById<Runtime>>::get(collection))
+                fn collection_by_id(collection: CollectionId) -> Result<Option<RpcCollection<AccountId>>, DispatchError> {
+                    Ok(<pallet_common::Pallet<Runtime>>::rpc_collection(collection))
                 }
                 fn collection_stats() -> Result<CollectionStats, DispatchError> {
                     Ok(<pallet_common::Pallet<Runtime>>::collection_stats())
modifiedruntime/opal/src/lib.rsdiffbeforeafterboth
--- a/runtime/opal/src/lib.rs
+++ b/runtime/opal/src/lib.rs
@@ -67,7 +67,7 @@
 	},
 };
 use up_data_structs::mapping::{EvmTokenAddressMapping, CrossTokenAddressMapping};
-use up_data_structs::{CollectionId, TokenId, CollectionStats, Collection};
+use up_data_structs::{CollectionId, TokenId, CollectionStats, Collection, RpcCollection};
 // use pallet_contracts::weights::WeightInfo;
 // #[cfg(any(feature = "std", test))]
 use frame_system::{