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

difftreelog

feat allow more fields to be set on collection creation

Yaroslav Bolyukin2022-01-11parent: #fcf0631.patch.diff
in: master

7 files changed

modifiedpallets/common/src/lib.rsdiffbeforeafterboth
--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -14,7 +14,10 @@
 	COLLECTION_NUMBER_LIMIT, Collection, CollectionId, CreateItemData, ExistenceRequirement,
 	MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_COLLECTION_NAME_LENGTH, MAX_TOKEN_PREFIX_LENGTH,
 	COLLECTION_ADMINS_LIMIT, MetaUpdatePermission, Pays, PostDispatchInfo, TokenId, Weight,
-	WithdrawReasons, CollectionStats,
+	WithdrawReasons, CollectionStats, MAX_TOKEN_OWNERSHIP, CollectionMode,
+	NFT_SPONSOR_TRANSFER_TIMEOUT, FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
+	REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, MAX_SPONSOR_TIMEOUT, CUSTOM_DATA_LIMIT, CollectionLimits,
+	CreateCollectionData, SponsorshipState,
 };
 pub use pallet::*;
 use sp_core::H160;
@@ -282,6 +285,10 @@
 		TokenVariableDataLimitExceeded,
 		/// Exceeded max admin count
 		CollectionAdminCountExceeded,
+		/// Collection limit bounds per collection exceeded
+		CollectionLimitBoundsExceeded,
+		/// Tried to enable permissions which are only permitted to be disabled
+		OwnerPermissionsCantBeReverted,
 
 		/// Collection settings not allowing items transferring
 		TransferNotAllowed,
@@ -392,7 +399,10 @@
 }
 
 impl<T: Config> Pallet<T> {
-	pub fn init_collection(data: Collection<T::AccountId>) -> Result<CollectionId, DispatchError> {
+	pub fn init_collection(
+		owner: T::AccountId,
+		data: CreateCollectionData<T::AccountId>,
+	) -> Result<CollectionId, DispatchError> {
 		{
 			ensure!(
 				data.name.len() <= MAX_COLLECTION_NAME_LENGTH,
@@ -423,6 +433,29 @@
 
 		// =========
 
+		let collection = Collection {
+			owner: owner.clone(),
+			name: data.name,
+			mode: data.mode.clone(),
+			mint_mode: false,
+			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))
+				.unwrap_or_else(|| Ok(CollectionLimits::default()))?,
+			meta_update_permission: data.meta_update_permission.unwrap_or_default(),
+		};
+
 		// Take a (non-refundable) deposit of collection creation
 		{
 			let mut imbalance =
@@ -434,7 +467,7 @@
 				),
 			);
 			<T as Config>::Currency::settle(
-				&data.owner,
+				&owner,
 				imbalance,
 				WithdrawReasons::TRANSFER,
 				ExistenceRequirement::KeepAlive,
@@ -443,12 +476,8 @@
 		}
 
 		<CreatedCollectionCount<T>>::put(created_count);
-		<Pallet<T>>::deposit_event(Event::CollectionCreated(
-			id,
-			data.mode.id(),
-			data.owner.clone(),
-		));
-		<CollectionById<T>>::insert(id, data);
+		<Pallet<T>>::deposit_event(Event::CollectionCreated(id, data.mode.id(), owner.clone()));
+		<CollectionById<T>>::insert(id, collection);
 		Ok(id)
 	}
 
@@ -532,6 +561,61 @@
 
 		Ok(())
 	}
+
+	pub fn clamp_limits(
+		mode: CollectionMode,
+		old_limit: &CollectionLimits,
+		mut new_limit: CollectionLimits,
+	) -> Result<CollectionLimits, DispatchError> {
+		macro_rules! limit_default {
+				($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{
+					$(
+						if let Some($new) = $new.$field {
+							let $old = $old.$field($($arg)?);
+							let _ = $new;
+							let _ = $old;
+							$check
+						} else {
+							$new.$field = $old.$field
+						}
+					)*
+				}};
+			}
+
+		limit_default!(old_limit, new_limit,
+			account_token_ownership_limit => ensure!(
+				new_limit <= MAX_TOKEN_OWNERSHIP,
+				<Error<T>>::CollectionLimitBoundsExceeded,
+			),
+			sponsor_transfer_timeout(match mode {
+				CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,
+				CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
+				CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
+			}) => ensure!(
+				new_limit <= MAX_SPONSOR_TIMEOUT,
+				<Error<T>>::CollectionLimitBoundsExceeded,
+			),
+			sponsored_data_size => ensure!(
+				new_limit <= CUSTOM_DATA_LIMIT,
+				<Error<T>>::CollectionLimitBoundsExceeded,
+			),
+			token_limit => ensure!(
+				old_limit >= new_limit && new_limit > 0,
+				<Error<T>>::CollectionTokenLimitExceeded
+			),
+			owner_can_transfer => ensure!(
+				old_limit || !new_limit,
+				<Error<T>>::OwnerPermissionsCantBeReverted,
+			),
+			owner_can_destroy => ensure!(
+				old_limit || !new_limit,
+				<Error<T>>::OwnerPermissionsCantBeReverted,
+			),
+			sponsored_data_rate_limit => {},
+			transfers_enabled => {},
+		);
+		Ok(new_limit)
+	}
 }
 
 #[macro_export]
modifiedpallets/fungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -2,7 +2,7 @@
 
 use core::ops::Deref;
 use frame_support::{ensure};
-use up_data_structs::{AccessMode, Collection, CollectionId, TokenId};
+use up_data_structs::{AccessMode, Collection, CollectionId, TokenId, CreateCollectionData};
 use pallet_common::{
 	Error as CommonError, Event as CommonEvent, Pallet as PalletCommon, account::CrossAccountId,
 };
@@ -100,8 +100,11 @@
 }
 
 impl<T: Config> Pallet<T> {
-	pub fn init_collection(data: Collection<T::AccountId>) -> Result<CollectionId, DispatchError> {
-		<PalletCommon<T>>::init_collection(data)
+	pub fn init_collection(
+		owner: T::AccountId,
+		data: CreateCollectionData<T::AccountId>,
+	) -> Result<CollectionId, DispatchError> {
+		<PalletCommon<T>>::init_collection(owner, data)
 	}
 	pub fn destroy_collection(
 		collection: FungibleHandle<T>,
modifiedpallets/nonfungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -4,6 +4,7 @@
 use frame_support::{BoundedVec, ensure};
 use up_data_structs::{
 	AccessMode, CUSTOM_DATA_LIMIT, Collection, CollectionId, CustomDataLimit, TokenId,
+	CreateCollectionData,
 };
 use pallet_common::{
 	Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, account::CrossAccountId,
@@ -142,8 +143,11 @@
 
 // unchecked calls skips any permission checks
 impl<T: Config> Pallet<T> {
-	pub fn init_collection(data: Collection<T::AccountId>) -> Result<CollectionId, DispatchError> {
-		<PalletCommon<T>>::init_collection(data)
+	pub fn init_collection(
+		owner: T::AccountId,
+		data: CreateCollectionData<T::AccountId>,
+	) -> Result<CollectionId, DispatchError> {
+		<PalletCommon<T>>::init_collection(owner, data)
 	}
 	pub fn destroy_collection(
 		collection: NonfungibleHandle<T>,
modifiedpallets/refungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -3,7 +3,7 @@
 use frame_support::{ensure, BoundedVec};
 use up_data_structs::{
 	AccessMode, CUSTOM_DATA_LIMIT, Collection, CollectionId, CustomDataLimit,
-	MAX_REFUNGIBLE_PIECES, TokenId,
+	MAX_REFUNGIBLE_PIECES, TokenId, CreateCollectionData,
 };
 use pallet_common::{
 	Error as CommonError, Event as CommonEvent, Pallet as PalletCommon, account::CrossAccountId,
@@ -156,8 +156,11 @@
 
 // unchecked calls skips any permission checks
 impl<T: Config> Pallet<T> {
-	pub fn init_collection(data: Collection<T::AccountId>) -> Result<CollectionId, DispatchError> {
-		<PalletCommon<T>>::init_collection(data)
+	pub fn init_collection(
+		owner: T::AccountId,
+		data: CreateCollectionData<T::AccountId>,
+	) -> Result<CollectionId, DispatchError> {
+		<PalletCommon<T>>::init_collection(owner, data)
 	}
 	pub fn destroy_collection(
 		collection: RefungibleHandle<T>,
modifiedpallets/unique/src/lib.rsdiffbeforeafterboth
--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -35,11 +35,10 @@
 use frame_system::{self as system, ensure_signed};
 use sp_runtime::{sp_std::prelude::Vec};
 use up_data_structs::{
-	MAX_DECIMAL_POINTS, MAX_SPONSOR_TIMEOUT, MAX_TOKEN_OWNERSHIP, CUSTOM_DATA_LIMIT,
-	VARIABLE_ON_CHAIN_SCHEMA_LIMIT, CONST_ON_CHAIN_SCHEMA_LIMIT, OFFCHAIN_SCHEMA_LIMIT,
-	FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
-	NFT_SPONSOR_TRANSFER_TIMEOUT, AccessMode, Collection, CreateItemData, CollectionLimits,
-	CollectionId, CollectionMode, TokenId, SchemaVersion, SponsorshipState, MetaUpdatePermission,
+	MAX_DECIMAL_POINTS, VARIABLE_ON_CHAIN_SCHEMA_LIMIT, CONST_ON_CHAIN_SCHEMA_LIMIT,
+	OFFCHAIN_SCHEMA_LIMIT, AccessMode, CreateItemData, CollectionLimits, CollectionId,
+	CollectionMode, TokenId, SchemaVersion, SponsorshipState, MetaUpdatePermission,
+	CreateCollectionData,
 };
 use pallet_common::{
 	account::CrossAccountId, CollectionHandle, Pallet as PalletCommon, Error as CommonError,
@@ -81,10 +80,6 @@
 		ConfirmUnsetSponsorFail,
 		/// Length of items properties must be greater than 0.
 		EmptyArgument,
-		/// Collection limit bounds per collection exceeded
-		CollectionLimitBoundsExceeded,
-		/// Tried to enable permissions which are only permitted to be disabled
-		OwnerPermissionsCantBeReverted,
 	}
 }
 
@@ -318,42 +313,38 @@
 		// returns collection ID
 		#[weight = <SelfWeightOf<T>>::create_collection()]
 		#[transactional]
+		#[deprecated]
 		pub fn create_collection(origin,
 								 collection_name: Vec<u16>,
 								 collection_description: Vec<u16>,
 								 token_prefix: Vec<u8>,
 								 mode: CollectionMode) -> DispatchResult {
-
-			// Anyone can create a collection
-			let who = ensure_signed(origin)?;
-
-			// Create new collection
-			let new_collection = Collection {
-				owner: who,
+			Self::create_collection_ex(origin, CreateCollectionData {
 				name: collection_name,
-				mode: mode.clone(),
-				mint_mode: false,
-				access: AccessMode::Normal,
 				description: collection_description,
 				token_prefix,
-				offchain_schema: Vec::new(),
-				schema_version: SchemaVersion::ImageURL,
-				sponsorship: SponsorshipState::Disabled,
-				variable_on_chain_schema: Vec::new(),
-				const_on_chain_schema: Vec::new(),
-				limits: Default::default(),
-				meta_update_permission: Default::default(),
-			};
+				mode,
+				..Default::default()
+			})
+		}
+
+		/// This method creates a collection
+		///
+		/// Prefer it to deprecated [`created_collection`] method
+		#[weight = <SelfWeightOf<T>>::create_collection()]
+		#[transactional]
+		pub fn create_collection_ex(origin, data: CreateCollectionData<T::AccountId>) -> DispatchResult {
+			let owner = ensure_signed(origin)?;
 
-			let _id = match mode {
-				CollectionMode::NFT => {<PalletNonfungible<T>>::init_collection(new_collection)?},
+			let _id = match data.mode {
+				CollectionMode::NFT => {<PalletNonfungible<T>>::init_collection(owner, data)?},
 				CollectionMode::Fungible(decimal_points) => {
 					// check params
 					ensure!(decimal_points <= MAX_DECIMAL_POINTS, Error::<T>::CollectionDecimalPointLimitExceeded);
-					<PalletFungible<T>>::init_collection(new_collection)?
+					<PalletFungible<T>>::init_collection(owner, data)?
 				}
 				CollectionMode::ReFungible => {
-					<PalletRefungible<T>>::init_collection(new_collection)?
+					<PalletRefungible<T>>::init_collection(owner, data)?
 				}
 			};
 
@@ -1099,61 +1090,12 @@
 			collection_id: CollectionId,
 			new_limit: CollectionLimits,
 		) -> DispatchResult {
-			let mut new_limit = new_limit;
 			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
 			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
 			target_collection.check_is_owner(&sender)?;
 			let old_limit = &target_collection.limits;
 
-			macro_rules! limit_default {
-				($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{
-					$(
-						if let Some($new) = $new.$field {
-							let $old = $old.$field($($arg)?);
-							let _ = $new;
-							let _ = $old;
-							$check
-						} else {
-							$new.$field = $old.$field
-						}
-					)*
-				}};
-			}
-
-			limit_default!(old_limit, new_limit,
-				account_token_ownership_limit => ensure!(
-					new_limit <= MAX_TOKEN_OWNERSHIP,
-					<Error<T>>::CollectionLimitBoundsExceeded,
-				),
-				sponsor_transfer_timeout(match target_collection.mode {
-					CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,
-					CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
-					CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
-				}) => ensure!(
-					new_limit <= MAX_SPONSOR_TIMEOUT,
-					<Error<T>>::CollectionLimitBoundsExceeded,
-				),
-				sponsored_data_size => ensure!(
-					new_limit <= CUSTOM_DATA_LIMIT,
-					<Error<T>>::CollectionLimitBoundsExceeded,
-				),
-				token_limit => ensure!(
-					old_limit >= new_limit && new_limit > 0,
-					<CommonError<T>>::CollectionTokenLimitExceeded
-				),
-				owner_can_transfer => ensure!(
-					old_limit || !new_limit,
-					<Error<T>>::OwnerPermissionsCantBeReverted,
-				),
-				owner_can_destroy => ensure!(
-					old_limit || !new_limit,
-					<Error<T>>::OwnerPermissionsCantBeReverted,
-				),
-				sponsored_data_rate_limit => {},
-				transfers_enabled => {},
-			);
-
-			target_collection.limits = new_limit;
+			target_collection.limits = <PalletCommon<T>>::clamp_limits(target_collection.mode.clone(), &old_limit, new_limit)?;
 
 			<Pallet<T>>::deposit_event(Event::<T>::CollectionLimitSet(
 				collection_id
modifiedpallets/unique/src/tests.rsdiffbeforeafterboth
--- a/pallets/unique/src/tests.rs
+++ b/pallets/unique/src/tests.rs
@@ -5,7 +5,7 @@
 use up_data_structs::{
 	COLLECTION_NUMBER_LIMIT, CollectionId, CreateItemData, CreateFungibleData, CreateNftData,
 	CreateReFungibleData, MAX_DECIMAL_POINTS, COLLECTION_ADMINS_LIMIT, MetaUpdatePermission,
-	TokenId,
+	TokenId, MAX_TOKEN_OWNERSHIP,
 };
 use frame_support::{assert_noop, assert_ok};
 use sp_std::convert::TryInto;
modifiedprimitives/data-structs/src/lib.rsdiffbeforeafterboth
before · primitives/data-structs/src/lib.rs
1#![cfg_attr(not(feature = "std"), no_std)]23use core::convert::{TryFrom, TryInto};45#[cfg(feature = "serde")]6pub use serde::{Serialize, Deserialize};78use sp_core::U256;9use sp_runtime::{ArithmeticError, sp_std::prelude::Vec};10use codec::{Decode, Encode, EncodeLike, MaxEncodedLen};11pub use frame_support::{12	BoundedVec, construct_runtime, decl_event, decl_module, decl_storage, decl_error,13	dispatch::DispatchResult,14	ensure, fail, parameter_types,15	traits::{16		Currency, ExistenceRequirement, Get, Imbalance, KeyOwnerProofSystem, OnUnbalanced,17		Randomness, IsSubType, WithdrawReasons,18	},19	weights::{20		constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},21		DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,22		WeightToFeePolynomial, DispatchClass,23	},24	StorageValue, transactional,25};26use derivative::Derivative;27use scale_info::TypeInfo;2829pub const MAX_DECIMAL_POINTS: DecimalPoints = 30;30pub const MAX_REFUNGIBLE_PIECES: u128 = 1_000_000_000_000_000_000_000;31pub const MAX_SPONSOR_TIMEOUT: u32 = 10_368_000;3233pub const MAX_TOKEN_OWNERSHIP: u32 = if cfg!(not(feature = "limit-testing")) {34	100_00035} else {36	1037};38pub const COLLECTION_NUMBER_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {39	100_00040} else {41	1042};43pub const CUSTOM_DATA_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {44	204845} else {46	1047};48pub const COLLECTION_ADMINS_LIMIT: u32 = 5;49pub const COLLECTION_TOKEN_LIMIT: u32 = u32::MAX;50pub const ACCOUNT_TOKEN_OWNERSHIP_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {51	1_000_00052} else {53	1054};5556// Timeouts for item types in passed blocks57pub const NFT_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;58pub const FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;59pub const REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;6061pub const SPONSOR_APPROVE_TIMEOUT: u32 = 5;6263// Schema limits64pub const OFFCHAIN_SCHEMA_LIMIT: u32 = 8192;65pub const VARIABLE_ON_CHAIN_SCHEMA_LIMIT: u32 = 8192;66pub const CONST_ON_CHAIN_SCHEMA_LIMIT: u32 = 1048576;6768pub const MAX_COLLECTION_NAME_LENGTH: usize = 64;69pub const MAX_COLLECTION_DESCRIPTION_LENGTH: usize = 256;70pub const MAX_TOKEN_PREFIX_LENGTH: usize = 16;7172/// How much items can be created per single73/// create_many call74pub const MAX_ITEMS_PER_BATCH: u32 = 200;7576parameter_types! {77	pub const CustomDataLimit: u32 = CUSTOM_DATA_LIMIT;78}7980#[derive(Encode, Decode, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Debug, Default, TypeInfo)]81#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]82pub struct CollectionId(pub u32);83impl EncodeLike<u32> for CollectionId {}84impl EncodeLike<CollectionId> for u32 {}8586#[derive(Encode, Decode, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Debug, Default, TypeInfo)]87#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]88pub struct TokenId(pub u32);89impl EncodeLike<u32> for TokenId {}90impl EncodeLike<TokenId> for u32 {}9192impl TokenId {93	pub fn try_next(self) -> Result<TokenId, ArithmeticError> {94		self.095			.checked_add(1)96			.ok_or(ArithmeticError::Overflow)97			.map(Self)98	}99}100101impl From<TokenId> for U256 {102	fn from(t: TokenId) -> Self {103		t.0.into()104	}105}106107impl TryFrom<U256> for TokenId {108	type Error = &'static str;109110	fn try_from(value: U256) -> Result<Self, Self::Error> {111		Ok(TokenId(value.try_into().map_err(|_| "too large token id")?))112	}113}114115pub struct OverflowError;116impl From<OverflowError> for &'static str {117	fn from(_: OverflowError) -> Self {118		"overflow occured"119	}120}121122pub type DecimalPoints = u8;123124#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo)]125#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]126pub enum CollectionMode {127	NFT,128	// decimal points129	Fungible(DecimalPoints),130	ReFungible,131}132133impl CollectionMode {134	pub fn id(&self) -> u8 {135		match self {136			CollectionMode::NFT => 1,137			CollectionMode::Fungible(_) => 2,138			CollectionMode::ReFungible => 3,139		}140	}141}142143pub trait SponsoringResolve<AccountId, Call> {144	fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>;145}146147#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo)]148#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]149pub enum AccessMode {150	Normal,151	AllowList,152}153impl Default for AccessMode {154	fn default() -> Self {155		Self::Normal156	}157}158159#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo)]160#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]161pub enum SchemaVersion {162	ImageURL,163	Unique,164}165impl Default for SchemaVersion {166	fn default() -> Self {167		Self::ImageURL168	}169}170171#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]172#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]173pub struct Ownership<AccountId> {174	pub owner: AccountId,175	pub fraction: u128,176}177178#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]179#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]180pub enum SponsorshipState<AccountId> {181	/// The fees are applied to the transaction sender182	Disabled,183	Unconfirmed(AccountId),184	/// Transactions are sponsored by specified account185	Confirmed(AccountId),186}187188impl<AccountId> SponsorshipState<AccountId> {189	pub fn sponsor(&self) -> Option<&AccountId> {190		match self {191			Self::Confirmed(sponsor) => Some(sponsor),192			_ => None,193		}194	}195196	pub fn pending_sponsor(&self) -> Option<&AccountId> {197		match self {198			Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),199			_ => None,200		}201	}202203	pub fn confirmed(&self) -> bool {204		matches!(self, Self::Confirmed(_))205	}206}207208impl<T> Default for SponsorshipState<T> {209	fn default() -> Self {210		Self::Disabled211	}212}213214#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]215#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]216pub struct Collection<AccountId> {217	pub owner: AccountId,218	pub mode: CollectionMode,219	pub access: AccessMode,220	pub name: Vec<u16>,        // 64 include null escape char221	pub description: Vec<u16>, // 256 include null escape char222	pub token_prefix: Vec<u8>, // 16 include null escape char223	pub mint_mode: bool,224	pub offchain_schema: Vec<u8>,225	pub schema_version: SchemaVersion,226	pub sponsorship: SponsorshipState<AccountId>,227	pub limits: CollectionLimits,          // Collection private restrictions228	pub variable_on_chain_schema: Vec<u8>, //229	pub const_on_chain_schema: Vec<u8>,    //230	pub meta_update_permission: MetaUpdatePermission,231}232233#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]234#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]235pub struct NftItemType<AccountId> {236	pub owner: AccountId,237	pub const_data: Vec<u8>,238	pub variable_data: Vec<u8>,239}240241#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]242#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]243pub struct FungibleItemType {244	pub value: u128,245}246247#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]248#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]249pub struct ReFungibleItemType<AccountId> {250	pub owner: Vec<Ownership<AccountId>>,251	pub const_data: Vec<u8>,252	pub variable_data: Vec<u8>,253}254255/// All fields are wrapped in `Option`s, where None means chain default256#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo)]257#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]258pub struct CollectionLimits {259	pub account_token_ownership_limit: Option<u32>,260	pub sponsored_data_size: Option<u32>,261	/// None - setVariableMetadata is not sponsored262	/// Some(v) - setVariableMetadata is sponsored263	///           if there is v block between txs264	pub sponsored_data_rate_limit: Option<(Option<u32>,)>,265	pub token_limit: Option<u32>,266267	// Timeouts for item types in passed blocks268	pub sponsor_transfer_timeout: Option<u32>,269	pub sponsor_approve_timeout: Option<u32>,270	pub owner_can_transfer: Option<bool>,271	pub owner_can_destroy: Option<bool>,272	pub transfers_enabled: Option<bool>,273}274275impl CollectionLimits {276	pub fn account_token_ownership_limit(&self) -> u32 {277		self.account_token_ownership_limit278			.unwrap_or(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)279			.min(MAX_TOKEN_OWNERSHIP)280	}281	pub fn sponsored_data_size(&self) -> u32 {282		self.sponsored_data_size283			.unwrap_or(CUSTOM_DATA_LIMIT)284			.min(CUSTOM_DATA_LIMIT)285	}286	pub fn token_limit(&self) -> u32 {287		self.token_limit288			.unwrap_or(COLLECTION_TOKEN_LIMIT)289			.min(COLLECTION_TOKEN_LIMIT)290	}291	pub fn sponsor_transfer_timeout(&self, default: u32) -> u32 {292		self.sponsor_transfer_timeout293			.unwrap_or(default)294			.min(MAX_SPONSOR_TIMEOUT)295	}296	pub fn sponsor_approve_timeout(&self) -> u32 {297		self.sponsor_approve_timeout298			.unwrap_or(SPONSOR_APPROVE_TIMEOUT)299			.min(MAX_SPONSOR_TIMEOUT)300	}301	pub fn owner_can_transfer(&self) -> bool {302		self.owner_can_transfer.unwrap_or(true)303	}304	pub fn owner_can_destroy(&self) -> bool {305		self.owner_can_destroy.unwrap_or(true)306	}307	pub fn transfers_enabled(&self) -> bool {308		self.transfers_enabled.unwrap_or(true)309	}310	pub fn sponsored_data_rate_limit(&self) -> Option<u32> {311		self.sponsored_data_rate_limit312			.unwrap_or((None,))313			.0314			.map(|v| v.min(MAX_SPONSOR_TIMEOUT))315	}316}317318/// BoundedVec doesn't supports serde319#[cfg(feature = "serde1")]320mod bounded_serde {321	use core::convert::TryFrom;322	use frame_support::{BoundedVec, traits::Get};323	use serde::{324		ser::{self, Serialize},325		de::{self, Deserialize, Error},326	};327	use sp_std::vec::Vec;328329	pub fn serialize<D, V, S>(value: &BoundedVec<V, S>, serializer: D) -> Result<D::Ok, D::Error>330	where331		D: ser::Serializer,332		V: Serialize,333	{334		(value as &Vec<_>).serialize(serializer)335	}336337	pub fn deserialize<'de, D, V, S>(deserializer: D) -> Result<BoundedVec<V, S>, D::Error>338	where339		D: de::Deserializer<'de>,340		V: de::Deserialize<'de>,341		S: Get<u32>,342	{343		// TODO: Implement custom visitor, which will limit vec size at parse time? Will serde only be used by chainspec?344		let vec = <Vec<V>>::deserialize(deserializer)?;345		let len = vec.len();346		TryFrom::try_from(vec).map_err(|_| D::Error::invalid_length(len, &"lesser size"))347	}348}349350#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]351#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]352#[derivative(Debug)]353pub struct CreateNftData {354	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]355	#[derivative(Debug = "ignore")]356	pub const_data: BoundedVec<u8, CustomDataLimit>,357	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]358	#[derivative(Debug = "ignore")]359	pub variable_data: BoundedVec<u8, CustomDataLimit>,360}361362#[derive(Encode, Decode, MaxEncodedLen, Default, Debug, Clone, PartialEq, TypeInfo)]363#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]364pub struct CreateFungibleData {365	pub value: u128,366}367368#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]369#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]370#[derivative(Debug)]371pub struct CreateReFungibleData {372	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]373	#[derivative(Debug = "ignore")]374	pub const_data: BoundedVec<u8, CustomDataLimit>,375	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]376	#[derivative(Debug = "ignore")]377	pub variable_data: BoundedVec<u8, CustomDataLimit>,378	pub pieces: u128,379}380381#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]382#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]383pub enum MetaUpdatePermission {384	ItemOwner,385	Admin,386	None,387}388389impl Default for MetaUpdatePermission {390	fn default() -> Self {391		Self::ItemOwner392	}393}394395#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]396#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]397pub enum CreateItemData {398	NFT(CreateNftData),399	Fungible(CreateFungibleData),400	ReFungible(CreateReFungibleData),401}402403impl CreateItemData {404	pub fn data_size(&self) -> usize {405		match self {406			CreateItemData::NFT(data) => data.variable_data.len() + data.const_data.len(),407			CreateItemData::ReFungible(data) => data.variable_data.len() + data.const_data.len(),408			_ => 0,409		}410	}411}412413impl From<CreateNftData> for CreateItemData {414	fn from(item: CreateNftData) -> Self {415		CreateItemData::NFT(item)416	}417}418419impl From<CreateReFungibleData> for CreateItemData {420	fn from(item: CreateReFungibleData) -> Self {421		CreateItemData::ReFungible(item)422	}423}424425impl From<CreateFungibleData> for CreateItemData {426	fn from(item: CreateFungibleData) -> Self {427		CreateItemData::Fungible(item)428	}429}430431#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]432#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]433pub struct CollectionStats {434	pub created: u32,435	pub destroyed: u32,436	pub alive: u32,437}
after · primitives/data-structs/src/lib.rs
1#![cfg_attr(not(feature = "std"), no_std)]23use core::convert::{TryFrom, TryInto};45#[cfg(feature = "serde")]6pub use serde::{Serialize, Deserialize};78use sp_core::U256;9use sp_runtime::{ArithmeticError, sp_std::prelude::Vec};10use codec::{Decode, Encode, EncodeLike, MaxEncodedLen};11pub use frame_support::{12	BoundedVec, construct_runtime, decl_event, decl_module, decl_storage, decl_error,13	dispatch::DispatchResult,14	ensure, fail, parameter_types,15	traits::{16		Currency, ExistenceRequirement, Get, Imbalance, KeyOwnerProofSystem, OnUnbalanced,17		Randomness, IsSubType, WithdrawReasons,18	},19	weights::{20		constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},21		DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,22		WeightToFeePolynomial, DispatchClass,23	},24	StorageValue, transactional,25};26use derivative::Derivative;27use scale_info::TypeInfo;2829pub const MAX_DECIMAL_POINTS: DecimalPoints = 30;30pub const MAX_REFUNGIBLE_PIECES: u128 = 1_000_000_000_000_000_000_000;31pub const MAX_SPONSOR_TIMEOUT: u32 = 10_368_000;3233pub const MAX_TOKEN_OWNERSHIP: u32 = if cfg!(not(feature = "limit-testing")) {34	100_00035} else {36	1037};38pub const COLLECTION_NUMBER_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {39	100_00040} else {41	1042};43pub const CUSTOM_DATA_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {44	204845} else {46	1047};48pub const COLLECTION_ADMINS_LIMIT: u32 = 5;49pub const COLLECTION_TOKEN_LIMIT: u32 = u32::MAX;50pub const ACCOUNT_TOKEN_OWNERSHIP_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {51	1_000_00052} else {53	1054};5556// Timeouts for item types in passed blocks57pub const NFT_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;58pub const FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;59pub const REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;6061pub const SPONSOR_APPROVE_TIMEOUT: u32 = 5;6263// Schema limits64pub const OFFCHAIN_SCHEMA_LIMIT: u32 = 8192;65pub const VARIABLE_ON_CHAIN_SCHEMA_LIMIT: u32 = 8192;66pub const CONST_ON_CHAIN_SCHEMA_LIMIT: u32 = 1048576;6768pub const MAX_COLLECTION_NAME_LENGTH: usize = 64;69pub const MAX_COLLECTION_DESCRIPTION_LENGTH: usize = 256;70pub const MAX_TOKEN_PREFIX_LENGTH: usize = 16;7172/// How much items can be created per single73/// create_many call74pub const MAX_ITEMS_PER_BATCH: u32 = 200;7576parameter_types! {77	pub const CustomDataLimit: u32 = CUSTOM_DATA_LIMIT;78}7980#[derive(Encode, Decode, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Debug, Default, TypeInfo)]81#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]82pub struct CollectionId(pub u32);83impl EncodeLike<u32> for CollectionId {}84impl EncodeLike<CollectionId> for u32 {}8586#[derive(Encode, Decode, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Debug, Default, TypeInfo)]87#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]88pub struct TokenId(pub u32);89impl EncodeLike<u32> for TokenId {}90impl EncodeLike<TokenId> for u32 {}9192impl TokenId {93	pub fn try_next(self) -> Result<TokenId, ArithmeticError> {94		self.095			.checked_add(1)96			.ok_or(ArithmeticError::Overflow)97			.map(Self)98	}99}100101impl From<TokenId> for U256 {102	fn from(t: TokenId) -> Self {103		t.0.into()104	}105}106107impl TryFrom<U256> for TokenId {108	type Error = &'static str;109110	fn try_from(value: U256) -> Result<Self, Self::Error> {111		Ok(TokenId(value.try_into().map_err(|_| "too large token id")?))112	}113}114115pub struct OverflowError;116impl From<OverflowError> for &'static str {117	fn from(_: OverflowError) -> Self {118		"overflow occured"119	}120}121122pub type DecimalPoints = u8;123124#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo)]125#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]126pub enum CollectionMode {127	NFT,128	// decimal points129	Fungible(DecimalPoints),130	ReFungible,131}132133impl CollectionMode {134	pub fn id(&self) -> u8 {135		match self {136			CollectionMode::NFT => 1,137			CollectionMode::Fungible(_) => 2,138			CollectionMode::ReFungible => 3,139		}140	}141}142143pub trait SponsoringResolve<AccountId, Call> {144	fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>;145}146147#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo)]148#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]149pub enum AccessMode {150	Normal,151	AllowList,152}153impl Default for AccessMode {154	fn default() -> Self {155		Self::Normal156	}157}158159#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo)]160#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]161pub enum SchemaVersion {162	ImageURL,163	Unique,164}165impl Default for SchemaVersion {166	fn default() -> Self {167		Self::ImageURL168	}169}170171#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]172#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]173pub struct Ownership<AccountId> {174	pub owner: AccountId,175	pub fraction: u128,176}177178#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]179#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]180pub enum SponsorshipState<AccountId> {181	/// The fees are applied to the transaction sender182	Disabled,183	Unconfirmed(AccountId),184	/// Transactions are sponsored by specified account185	Confirmed(AccountId),186}187188impl<AccountId> SponsorshipState<AccountId> {189	pub fn sponsor(&self) -> Option<&AccountId> {190		match self {191			Self::Confirmed(sponsor) => Some(sponsor),192			_ => None,193		}194	}195196	pub fn pending_sponsor(&self) -> Option<&AccountId> {197		match self {198			Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),199			_ => None,200		}201	}202203	pub fn confirmed(&self) -> bool {204		matches!(self, Self::Confirmed(_))205	}206}207208impl<T> Default for SponsorshipState<T> {209	fn default() -> Self {210		Self::Disabled211	}212}213214#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]215#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]216pub struct Collection<AccountId> {217	pub owner: AccountId,218	pub mode: CollectionMode,219	pub access: AccessMode,220	pub name: Vec<u16>,        // 64 include null escape char221	pub description: Vec<u16>, // 256 include null escape char222	pub token_prefix: Vec<u8>, // 16 include null escape char223	pub mint_mode: bool,224	pub offchain_schema: Vec<u8>,225	pub schema_version: SchemaVersion,226	pub sponsorship: SponsorshipState<AccountId>,227	pub limits: CollectionLimits,          // Collection private restrictions228	pub variable_on_chain_schema: Vec<u8>, //229	pub const_on_chain_schema: Vec<u8>,    //230	pub meta_update_permission: MetaUpdatePermission,231}232233#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Debug, Derivative)]234#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]235#[derivative(Default)]236pub struct CreateCollectionData<AccountId> {237	#[derivative(Default(value = "CollectionMode::NFT"))]238	pub mode: CollectionMode,239	pub access: Option<AccessMode>,240	pub name: Vec<u16>,241	pub description: Vec<u16>,242	pub token_prefix: Vec<u8>,243	pub offchain_schema: Vec<u8>,244	pub schema_version: Option<SchemaVersion>,245	pub pending_sponsor: Option<AccountId>,246	pub limits: Option<CollectionLimits>,247	pub variable_on_chain_schema: Vec<u8>,248	pub const_on_chain_schema: Vec<u8>,249	pub meta_update_permission: Option<MetaUpdatePermission>,250}251252#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]253#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]254pub struct NftItemType<AccountId> {255	pub owner: AccountId,256	pub const_data: Vec<u8>,257	pub variable_data: Vec<u8>,258}259260#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]261#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]262pub struct FungibleItemType {263	pub value: u128,264}265266#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]267#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]268pub struct ReFungibleItemType<AccountId> {269	pub owner: Vec<Ownership<AccountId>>,270	pub const_data: Vec<u8>,271	pub variable_data: Vec<u8>,272}273274/// All fields are wrapped in `Option`s, where None means chain default275#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo)]276#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]277pub struct CollectionLimits {278	pub account_token_ownership_limit: Option<u32>,279	pub sponsored_data_size: Option<u32>,280	/// None - setVariableMetadata is not sponsored281	/// Some(v) - setVariableMetadata is sponsored282	///           if there is v block between txs283	pub sponsored_data_rate_limit: Option<(Option<u32>,)>,284	pub token_limit: Option<u32>,285286	// Timeouts for item types in passed blocks287	pub sponsor_transfer_timeout: Option<u32>,288	pub sponsor_approve_timeout: Option<u32>,289	pub owner_can_transfer: Option<bool>,290	pub owner_can_destroy: Option<bool>,291	pub transfers_enabled: Option<bool>,292}293294impl CollectionLimits {295	pub fn account_token_ownership_limit(&self) -> u32 {296		self.account_token_ownership_limit297			.unwrap_or(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)298			.min(MAX_TOKEN_OWNERSHIP)299	}300	pub fn sponsored_data_size(&self) -> u32 {301		self.sponsored_data_size302			.unwrap_or(CUSTOM_DATA_LIMIT)303			.min(CUSTOM_DATA_LIMIT)304	}305	pub fn token_limit(&self) -> u32 {306		self.token_limit307			.unwrap_or(COLLECTION_TOKEN_LIMIT)308			.min(COLLECTION_TOKEN_LIMIT)309	}310	pub fn sponsor_transfer_timeout(&self, default: u32) -> u32 {311		self.sponsor_transfer_timeout312			.unwrap_or(default)313			.min(MAX_SPONSOR_TIMEOUT)314	}315	pub fn sponsor_approve_timeout(&self) -> u32 {316		self.sponsor_approve_timeout317			.unwrap_or(SPONSOR_APPROVE_TIMEOUT)318			.min(MAX_SPONSOR_TIMEOUT)319	}320	pub fn owner_can_transfer(&self) -> bool {321		self.owner_can_transfer.unwrap_or(true)322	}323	pub fn owner_can_destroy(&self) -> bool {324		self.owner_can_destroy.unwrap_or(true)325	}326	pub fn transfers_enabled(&self) -> bool {327		self.transfers_enabled.unwrap_or(true)328	}329	pub fn sponsored_data_rate_limit(&self) -> Option<u32> {330		self.sponsored_data_rate_limit331			.unwrap_or((None,))332			.0333			.map(|v| v.min(MAX_SPONSOR_TIMEOUT))334	}335}336337/// BoundedVec doesn't supports serde338#[cfg(feature = "serde1")]339mod bounded_serde {340	use core::convert::TryFrom;341	use frame_support::{BoundedVec, traits::Get};342	use serde::{343		ser::{self, Serialize},344		de::{self, Deserialize, Error},345	};346	use sp_std::vec::Vec;347348	pub fn serialize<D, V, S>(value: &BoundedVec<V, S>, serializer: D) -> Result<D::Ok, D::Error>349	where350		D: ser::Serializer,351		V: Serialize,352	{353		(value as &Vec<_>).serialize(serializer)354	}355356	pub fn deserialize<'de, D, V, S>(deserializer: D) -> Result<BoundedVec<V, S>, D::Error>357	where358		D: de::Deserializer<'de>,359		V: de::Deserialize<'de>,360		S: Get<u32>,361	{362		// TODO: Implement custom visitor, which will limit vec size at parse time? Will serde only be used by chainspec?363		let vec = <Vec<V>>::deserialize(deserializer)?;364		let len = vec.len();365		TryFrom::try_from(vec).map_err(|_| D::Error::invalid_length(len, &"lesser size"))366	}367}368369#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]370#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]371#[derivative(Debug)]372pub struct CreateNftData {373	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]374	#[derivative(Debug = "ignore")]375	pub const_data: BoundedVec<u8, CustomDataLimit>,376	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]377	#[derivative(Debug = "ignore")]378	pub variable_data: BoundedVec<u8, CustomDataLimit>,379}380381#[derive(Encode, Decode, MaxEncodedLen, Default, Debug, Clone, PartialEq, TypeInfo)]382#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]383pub struct CreateFungibleData {384	pub value: u128,385}386387#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]388#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]389#[derivative(Debug)]390pub struct CreateReFungibleData {391	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]392	#[derivative(Debug = "ignore")]393	pub const_data: BoundedVec<u8, CustomDataLimit>,394	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]395	#[derivative(Debug = "ignore")]396	pub variable_data: BoundedVec<u8, CustomDataLimit>,397	pub pieces: u128,398}399400#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]401#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]402pub enum MetaUpdatePermission {403	ItemOwner,404	Admin,405	None,406}407408impl Default for MetaUpdatePermission {409	fn default() -> Self {410		Self::ItemOwner411	}412}413414#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]415#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]416pub enum CreateItemData {417	NFT(CreateNftData),418	Fungible(CreateFungibleData),419	ReFungible(CreateReFungibleData),420}421422impl CreateItemData {423	pub fn data_size(&self) -> usize {424		match self {425			CreateItemData::NFT(data) => data.variable_data.len() + data.const_data.len(),426			CreateItemData::ReFungible(data) => data.variable_data.len() + data.const_data.len(),427			_ => 0,428		}429	}430}431432impl From<CreateNftData> for CreateItemData {433	fn from(item: CreateNftData) -> Self {434		CreateItemData::NFT(item)435	}436}437438impl From<CreateReFungibleData> for CreateItemData {439	fn from(item: CreateReFungibleData) -> Self {440		CreateItemData::ReFungible(item)441	}442}443444impl From<CreateFungibleData> for CreateItemData {445	fn from(item: CreateFungibleData) -> Self {446		CreateItemData::Fungible(item)447	}448}449450#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]451#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]452pub struct CollectionStats {453	pub created: u32,454	pub destroyed: u32,455	pub alive: u32,456}