git.delta.rocks / unique-network / refs/commits / 98013fc81aa8

difftreelog

feat check nesting rule

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

10 files changed

modifiedpallets/common/src/eth.rsdiffbeforeafterboth
--- a/pallets/common/src/eth.rs
+++ b/pallets/common/src/eth.rs
@@ -14,7 +14,7 @@
 // You should have received a copy of the GNU General Public License
 // along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
-use up_data_structs::{CollectionId, TokenId};
+use up_data_structs::CollectionId;
 use sp_core::H160;
 
 // 0x17c4e6453Cc49AAAaEACA894e6D9683e00000001 - collection 1
modifiedpallets/common/src/lib.rsdiffbeforeafterboth
--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -345,6 +345,13 @@
 
 		/// Not sufficient founds to perform action
 		NotSufficientFounds,
+
+		/// Collection has nesting disabled
+		NestingIsDisabled,
+		/// Only owner may nest tokens under this collection
+		OnlyOwnerAllowedToNest,
+		/// Only tokens from specific collections may nest tokens under this
+		SourceCollectionIsNotAllowedToNest,
 	}
 
 	#[pallet::storage]
@@ -400,8 +407,6 @@
 	#[pallet::hooks]
 	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
 		fn on_runtime_upgrade() -> Weight {
-			let mut weight = 0;
-
 			if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {
 				use up_data_structs::{CollectionVersion1, CollectionVersion2};
 				<CollectionById<T>>::translate_values::<CollectionVersion1<T::AccountId>, _>(|v| {
@@ -409,7 +414,7 @@
 				});
 			}
 
-			weight
+			0
 		}
 	}
 }
@@ -774,6 +779,13 @@
 		data: BoundedVec<u8, CustomDataLimit>,
 	) -> DispatchResultWithPostInfo;
 
+	fn nest_token(
+		&self,
+		sender: T::CrossAccountId,
+		from: (CollectionId, TokenId),
+		under: TokenId,
+	) -> DispatchResult;
+
 	fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;
 	fn token_exists(&self, token: TokenId) -> bool;
 	fn last_token_id(&self) -> TokenId;
modifiedpallets/fungible/src/common.rsdiffbeforeafterboth
--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -228,6 +228,15 @@
 		fail!(<Error<T>>::FungibleItemsDontHaveData)
 	}
 
+	fn nest_token(
+		&self,
+		_sender: <T>::CrossAccountId,
+		_from: (up_data_structs::CollectionId, TokenId),
+		_under: TokenId,
+	) -> sp_runtime::DispatchResult {
+		fail!(<Error<T>>::FungibleDisallowsNesting)
+	}
+
 	fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId> {
 		if <Balance<T>>::get((self.id, account)) != 0 {
 			vec![TokenId::default()]
modifiedpallets/fungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -18,9 +18,14 @@
 
 use core::ops::Deref;
 use frame_support::{ensure};
-use up_data_structs::{AccessMode, CollectionId, TokenId, CreateCollectionData};
-use pallet_common::{Error as CommonError, Event as CommonEvent, Pallet as PalletCommon};
 use pallet_evm::account::CrossAccountId;
+use up_data_structs::{
+	AccessMode, CollectionId, TokenId, CreateCollectionData, mapping::TokenAddressMapping,
+};
+use pallet_common::{
+	Error as CommonError, Event as CommonEvent, Pallet as PalletCommon,
+	CollectionHandle, dispatch::CollectionDispatch,
+};
 use pallet_evm_coder_substrate::WithRecorder;
 use sp_core::H160;
 use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};
@@ -52,6 +57,8 @@
 		FungibleItemsHaveNoId,
 		/// Tried to set data for fungible item
 		FungibleItemsDontHaveData,
+		/// Fungible token does not support nested
+		FungibleDisallowsNesting,
 	}
 
 	#[pallet::config]
@@ -207,7 +214,15 @@
 			None
 		};
 
-		// =========
+		if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {
+			let handle = <CollectionHandle<T>>::try_get(target.0)?;
+			let dispatch = T::CollectionDispatch::dispatch(handle);
+			let dispatch = dispatch.as_dyn();
+
+			// =========
+
+			dispatch.nest_token(from.clone(), (collection.id, TokenId::default()), target.1)?;
+		}
 
 		if let Some(balance_to) = balance_to {
 			// from != to
modifiedpallets/nonfungible/src/common.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -17,7 +17,7 @@
 use core::marker::PhantomData;
 
 use frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight, BoundedVec};
-use up_data_structs::{TokenId, CustomDataLimit, CreateItemExData};
+use up_data_structs::{TokenId, CustomDataLimit, CreateItemExData, CollectionId};
 use pallet_common::{CommonCollectionOperations, CommonWeightInfo, with_weight};
 use sp_runtime::DispatchError;
 use sp_std::vec::Vec;
@@ -237,6 +237,15 @@
 		)
 	}
 
+	fn nest_token(
+		&self,
+		sender: T::CrossAccountId,
+		(from, _): (CollectionId, TokenId),
+		under: TokenId,
+	) -> sp_runtime::DispatchResult {
+		<Pallet<T>>::nest_token(self, sender, from, under)
+	}
+
 	fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId> {
 		<Owned<T>>::iter_prefix((self.id, account))
 			.map(|(id, _)| id)
modifiedpallets/nonfungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -17,12 +17,16 @@
 #![cfg_attr(not(feature = "std"), no_std)]
 
 use erc::ERC721Events;
-use frame_support::{BoundedVec, ensure};
+use frame_support::{BoundedVec, ensure, fail};
 use up_data_structs::{
 	AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,
+	mapping::TokenAddressMapping, NestingRule,
 };
-use pallet_common::{Error as CommonError, Pallet as PalletCommon, Event as CommonEvent};
 use pallet_evm::account::CrossAccountId;
+use pallet_common::{
+	Error as CommonError, Pallet as PalletCommon, Event as CommonEvent,
+	CollectionHandle, dispatch::CollectionDispatch,
+};
 use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};
 use sp_core::H160;
 use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};
@@ -282,8 +286,16 @@
 			None
 		};
 
-		// =========
+		if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {
+			let handle = <CollectionHandle<T>>::try_get(target.0)?;
+			let dispatch = T::CollectionDispatch::dispatch(handle);
+			let dispatch = dispatch.as_dyn();
+
+			// =========
 
+			dispatch.nest_token(from.clone(), (collection.id, token), target.1)?;
+		}
+
 		<TokenData<T>>::insert(
 			(collection.id, token),
 			ItemData {
@@ -567,6 +579,40 @@
 		Ok(())
 	}
 
+	pub fn nest_token(
+		handle: &NonfungibleHandle<T>,
+		sender: T::CrossAccountId,
+		from: CollectionId,
+		under: TokenId,
+	) -> DispatchResult {
+		fn ensure_sender_allowed<T: Config>(
+			collection: CollectionId,
+			token: TokenId,
+			sender: T::CrossAccountId,
+		) -> DispatchResult {
+			ensure!(
+				<TokenData<T>>::get((collection, token))
+					.ok_or(<CommonError<T>>::TokenNotFound)?
+					.owner
+					.conv_eq(&sender),
+				<CommonError<T>>::OnlyOwnerAllowedToNest,
+			);
+			Ok(())
+		}
+		match handle.limits.nesting_rule() {
+			NestingRule::Disabled => fail!(<CommonError<T>>::NestingIsDisabled),
+			NestingRule::Owner => ensure_sender_allowed::<T>(from, under, sender)?,
+			NestingRule::OwnerRestricted(whitelist) => {
+				ensure!(
+					whitelist.contains(&from),
+					<CommonError<T>>::SourceCollectionIsNotAllowedToNest
+				);
+				ensure_sender_allowed::<T>(from, under, sender)?
+			}
+		}
+		Ok(())
+	}
+
 	/// Delegated to `create_multiple_items`
 	pub fn create_item(
 		collection: &NonfungibleHandle<T>,
modifiedpallets/refungible/src/common.rsdiffbeforeafterboth
--- a/pallets/refungible/src/common.rs
+++ b/pallets/refungible/src/common.rs
@@ -243,6 +243,15 @@
 		)
 	}
 
+	fn nest_token(
+		&self,
+		_sender: <T>::CrossAccountId,
+		_from: (up_data_structs::CollectionId, TokenId),
+		_under: TokenId,
+	) -> sp_runtime::DispatchResult {
+		fail!(<Error<T>>::RefungibleDisallowsNesting)
+	}
+
 	fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId> {
 		<Owned<T>>::iter_prefix((self.id, account))
 			.map(|(id, _)| id)
modifiedpallets/refungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -19,10 +19,13 @@
 use frame_support::{ensure, BoundedVec};
 use up_data_structs::{
 	AccessMode, CollectionId, CustomDataLimit, MAX_REFUNGIBLE_PIECES, TokenId,
-	CreateCollectionData, CreateRefungibleExData,
+	CreateCollectionData, CreateRefungibleExData, mapping::TokenAddressMapping,
 };
-use pallet_common::{Error as CommonError, Event as CommonEvent, Pallet as PalletCommon};
 use pallet_evm::account::CrossAccountId;
+use pallet_common::{
+	Error as CommonError, Event as CommonEvent, Pallet as PalletCommon,
+	CollectionHandle, dispatch::CollectionDispatch,
+};
 use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};
 use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};
 use core::ops::Deref;
@@ -56,6 +59,8 @@
 		NotRefungibleDataUsedToMintFungibleCollectionToken,
 		/// Maximum refungibility exceeded
 		WrongRefungiblePieces,
+		/// Refungible token can't nest other tokens
+		RefungibleDisallowsNesting,
 	}
 
 	#[pallet::config]
@@ -338,7 +343,15 @@
 			None
 		};
 
-		// =========
+		if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {
+			let handle = <CollectionHandle<T>>::try_get(target.0)?;
+			let dispatch = T::CollectionDispatch::dispatch(handle);
+			let dispatch = dispatch.as_dyn();
+
+			// =========
+
+			dispatch.nest_token(from.clone(), (collection.id, token), target.1)?;
+		}
 
 		if let Some(balance_to) = balance_to {
 			// from != to
addedprimitives/data-structs/src/bounded.rsdiffbeforeafterboth
--- /dev/null
+++ b/primitives/data-structs/src/bounded.rs
@@ -0,0 +1,138 @@
+use core::fmt;
+use sp_std::collections::{btree_map::BTreeMap, btree_set::BTreeSet};
+use sp_std::vec::Vec;
+
+use frame_support::{
+	BoundedVec,
+	storage::{bounded_btree_map::BoundedBTreeMap, bounded_btree_set::BoundedBTreeSet},
+};
+
+/// BoundedVec doesn't supports serde
+#[cfg(feature = "serde1")]
+pub mod vec_serde {
+	use core::convert::TryFrom;
+	use frame_support::{BoundedVec, traits::Get};
+	use serde::{
+		ser::{self, Serialize},
+		de::{self, Deserialize, Error},
+	};
+	use sp_std::vec::Vec;
+
+	pub fn serialize<D, V, S>(value: &BoundedVec<V, S>, serializer: D) -> Result<D::Ok, D::Error>
+	where
+		D: ser::Serializer,
+		V: Serialize,
+	{
+		(value as &Vec<_>).serialize(serializer)
+	}
+
+	pub fn deserialize<'de, D, V, S>(deserializer: D) -> Result<BoundedVec<V, S>, D::Error>
+	where
+		D: de::Deserializer<'de>,
+		V: de::Deserialize<'de>,
+		S: Get<u32>,
+	{
+		// TODO: Implement custom visitor, which will limit vec size at parse time? Will serde only be used by chainspec?
+		let vec = <Vec<V>>::deserialize(deserializer)?;
+		let len = vec.len();
+		TryFrom::try_from(vec).map_err(|_| D::Error::invalid_length(len, &"lesser size"))
+	}
+}
+
+pub fn vec_debug<V, S>(v: &BoundedVec<V, S>, f: &mut fmt::Formatter) -> Result<(), fmt::Error>
+where
+	V: fmt::Debug,
+{
+	use core::fmt::Debug;
+	(&v as &Vec<V>).fmt(f)
+}
+
+#[cfg(feature = "serde1")]
+#[allow(dead_code)]
+pub mod map_serde {
+	use core::convert::TryFrom;
+	use sp_std::collections::btree_map::BTreeMap;
+	use frame_support::{traits::Get, storage::bounded_btree_map::BoundedBTreeMap};
+	use serde::{
+		ser::{self, Serialize},
+		de::{self, Deserialize, Error},
+	};
+	pub fn serialize<D, K, V, S>(
+		value: &BoundedBTreeMap<K, V, S>,
+		serializer: D,
+	) -> Result<D::Ok, D::Error>
+	where
+		D: ser::Serializer,
+		K: Serialize + Ord,
+		V: Serialize,
+	{
+		(value as &BTreeMap<_, _>).serialize(serializer)
+	}
+
+	pub fn deserialize<'de, D, K, V, S>(
+		deserializer: D,
+	) -> Result<BoundedBTreeMap<K, V, S>, D::Error>
+	where
+		D: de::Deserializer<'de>,
+		K: de::Deserialize<'de> + Ord,
+		V: de::Deserialize<'de>,
+		S: Get<u32>,
+	{
+		let map = <BTreeMap<K, V>>::deserialize(deserializer)?;
+		let len = map.len();
+		TryFrom::try_from(map).map_err(|_| D::Error::invalid_length(len, &"lesser size"))
+	}
+}
+
+pub fn map_debug<K, V, S>(
+	v: &BoundedBTreeMap<K, V, S>,
+	f: &mut fmt::Formatter,
+) -> Result<(), fmt::Error>
+where
+	K: fmt::Debug + Ord,
+	V: fmt::Debug,
+{
+	use core::fmt::Debug;
+	(&v as &BTreeMap<K, V>).fmt(f)
+}
+
+#[cfg(feature = "serde1")]
+#[allow(dead_code)]
+pub mod set_serde {
+	use core::convert::TryFrom;
+	use sp_std::collections::btree_set::BTreeSet;
+	use frame_support::{traits::Get, storage::bounded_btree_set::BoundedBTreeSet};
+	use serde::{
+		ser::{self, Serialize},
+		de::{self, Deserialize, Error},
+	};
+	pub fn serialize<D, K, S>(
+		value: &BoundedBTreeSet<K, S>,
+		serializer: D,
+	) -> Result<D::Ok, D::Error>
+	where
+		D: ser::Serializer,
+		K: Serialize + Ord,
+	{
+		(value as &BTreeSet<_>).serialize(serializer)
+	}
+
+	pub fn deserialize<'de, D, K, S>(deserializer: D) -> Result<BoundedBTreeSet<K, S>, D::Error>
+	where
+		D: de::Deserializer<'de>,
+		K: de::Deserialize<'de> + Ord,
+		S: Get<u32>,
+	{
+		let map = <BTreeSet<K>>::deserialize(deserializer)?;
+		let len = map.len();
+		TryFrom::try_from(map).map_err(|_| D::Error::invalid_length(len, &"lesser size"))
+	}
+}
+
+pub fn set_debug<K, S>(v: &BoundedBTreeSet<K, S>, f: &mut fmt::Formatter) -> Result<(), fmt::Error>
+where
+	K: fmt::Debug + Ord,
+{
+	use core::fmt::Debug;
+	(&v as &BTreeSet<K>).fmt(f)
+}
modifiedprimitives/data-structs/src/lib.rsdiffbeforeafterboth
before · primitives/data-structs/src/lib.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617#![cfg_attr(not(feature = "std"), no_std)]1819use core::{20	convert::{TryFrom, TryInto},21	fmt,22};23use frame_support::{24	storage::{bounded_btree_map::BoundedBTreeMap, bounded_btree_set::BoundedBTreeSet},25	traits::ConstU16,26};27use sp_std::collections::{btree_map::BTreeMap, btree_set::BTreeSet};2829#[cfg(feature = "serde")]30use serde::{Serialize, Deserialize};3132use sp_core::U256;33use sp_runtime::{ArithmeticError, sp_std::prelude::Vec};34use codec::{Decode, Encode, EncodeLike, MaxEncodedLen};35use frame_support::{BoundedVec, traits::ConstU32};36use derivative::Derivative;37use scale_info::TypeInfo;3839pub 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_serde"))]259	pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,260	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]261	pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,262	#[cfg_attr(feature = "serde1", serde(with = "bounded_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_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_serde"))]276	pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,277	#[cfg_attr(feature = "serde1", serde(with = "bounded_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_serde"))]290	pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,291	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]292	pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,293	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]294	pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,295	#[cfg_attr(feature = "serde1", serde(with = "bounded_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_serde"))]301	pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,302	#[cfg_attr(feature = "serde1", serde(with = "bounded_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/// BoundedVec doesn't supports serde427#[cfg(feature = "serde1")]428mod bounded_serde {429	use core::convert::TryFrom;430	use frame_support::{BoundedVec, traits::Get};431	use serde::{432		ser::{self, Serialize},433		de::{self, Deserialize, Error},434	};435	use sp_std::vec::Vec;436437	pub fn serialize<D, V, S>(value: &BoundedVec<V, S>, serializer: D) -> Result<D::Ok, D::Error>438	where439		D: ser::Serializer,440		V: Serialize,441	{442		(value as &Vec<_>).serialize(serializer)443	}444445	pub fn deserialize<'de, D, V, S>(deserializer: D) -> Result<BoundedVec<V, S>, D::Error>446	where447		D: de::Deserializer<'de>,448		V: de::Deserialize<'de>,449		S: Get<u32>,450	{451		// TODO: Implement custom visitor, which will limit vec size at parse time? Will serde only be used by chainspec?452		let vec = <Vec<V>>::deserialize(deserializer)?;453		let len = vec.len();454		TryFrom::try_from(vec).map_err(|_| D::Error::invalid_length(len, &"lesser size"))455	}456}457458fn bounded_debug<V, S>(v: &BoundedVec<V, S>, f: &mut fmt::Formatter) -> Result<(), fmt::Error>459where460	V: fmt::Debug,461{462	use core::fmt::Debug;463	(&v as &Vec<V>).fmt(f)464}465466#[cfg(feature = "serde1")]467#[allow(dead_code)]468mod bounded_map_serde {469	use core::convert::TryFrom;470	use sp_std::collections::btree_map::BTreeMap;471	use frame_support::{traits::Get, storage::bounded_btree_map::BoundedBTreeMap};472	use serde::{473		ser::{self, Serialize},474		de::{self, Deserialize, Error},475	};476	pub fn serialize<D, K, V, S>(477		value: &BoundedBTreeMap<K, V, S>,478		serializer: D,479	) -> Result<D::Ok, D::Error>480	where481		D: ser::Serializer,482		K: Serialize + Ord,483		V: Serialize,484	{485		(value as &BTreeMap<_, _>).serialize(serializer)486	}487488	pub fn deserialize<'de, D, K, V, S>(489		deserializer: D,490	) -> Result<BoundedBTreeMap<K, V, S>, D::Error>491	where492		D: de::Deserializer<'de>,493		K: de::Deserialize<'de> + Ord,494		V: de::Deserialize<'de>,495		S: Get<u32>,496	{497		let map = <BTreeMap<K, V>>::deserialize(deserializer)?;498		let len = map.len();499		TryFrom::try_from(map).map_err(|_| D::Error::invalid_length(len, &"lesser size"))500	}501}502503fn bounded_map_debug<K, V, S>(504	v: &BoundedBTreeMap<K, V, S>,505	f: &mut fmt::Formatter,506) -> Result<(), fmt::Error>507where508	K: fmt::Debug + Ord,509	V: fmt::Debug,510{511	use core::fmt::Debug;512	(&v as &BTreeMap<K, V>).fmt(f)513}514515#[cfg(feature = "serde1")]516#[allow(dead_code)]517mod bounded_set_serde {518	use core::convert::TryFrom;519	use sp_std::collections::btree_set::BTreeSet;520	use frame_support::{traits::Get, storage::bounded_btree_set::BoundedBTreeSet};521	use serde::{522		ser::{self, Serialize},523		de::{self, Deserialize, Error},524	};525	pub fn serialize<D, K, S>(526		value: &BoundedBTreeSet<K, S>,527		serializer: D,528	) -> Result<D::Ok, D::Error>529	where530		D: ser::Serializer,531		K: Serialize + Ord,532	{533		(value as &BTreeSet<_>).serialize(serializer)534	}535536	pub fn deserialize<'de, D, K, S>(deserializer: D) -> Result<BoundedBTreeSet<K, S>, D::Error>537	where538		D: de::Deserializer<'de>,539		K: de::Deserialize<'de> + Ord,540		S: Get<u32>,541	{542		let map = <BTreeSet<K>>::deserialize(deserializer)?;543		let len = map.len();544		TryFrom::try_from(map).map_err(|_| D::Error::invalid_length(len, &"lesser size"))545	}546}547548fn bounded_set_debug<K, S>(549	v: &BoundedBTreeSet<K, S>,550	f: &mut fmt::Formatter,551) -> Result<(), fmt::Error>552where553	K: fmt::Debug + Ord,554{555	use core::fmt::Debug;556	(&v as &BTreeSet<K>).fmt(f)557}558559#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]560#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]561#[derivative(Debug)]562pub struct CreateNftData {563	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]564	#[derivative(Debug(format_with = "bounded_debug"))]565	pub const_data: BoundedVec<u8, CustomDataLimit>,566	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]567	#[derivative(Debug(format_with = "bounded_debug"))]568	pub variable_data: BoundedVec<u8, CustomDataLimit>,569}570571#[derive(Encode, Decode, MaxEncodedLen, Default, Debug, Clone, PartialEq, TypeInfo)]572#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]573pub struct CreateFungibleData {574	pub value: u128,575}576577#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]578#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]579#[derivative(Debug)]580pub struct CreateReFungibleData {581	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]582	#[derivative(Debug(format_with = "bounded_debug"))]583	pub const_data: BoundedVec<u8, CustomDataLimit>,584	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]585	#[derivative(Debug(format_with = "bounded_debug"))]586	pub variable_data: BoundedVec<u8, CustomDataLimit>,587	pub pieces: u128,588}589590#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]591#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]592pub enum MetaUpdatePermission {593	ItemOwner,594	Admin,595	None,596}597598impl Default for MetaUpdatePermission {599	fn default() -> Self {600		Self::ItemOwner601	}602}603604#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]605#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]606pub enum CreateItemData {607	NFT(CreateNftData),608	Fungible(CreateFungibleData),609	ReFungible(CreateReFungibleData),610}611612#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]613#[derivative(Debug)]614pub struct CreateNftExData<CrossAccountId> {615	#[derivative(Debug(format_with = "bounded_debug"))]616	pub const_data: BoundedVec<u8, CustomDataLimit>,617	#[derivative(Debug(format_with = "bounded_debug"))]618	pub variable_data: BoundedVec<u8, CustomDataLimit>,619	pub owner: CrossAccountId,620}621622#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]623#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]624pub struct CreateRefungibleExData<CrossAccountId> {625	#[derivative(Debug(format_with = "bounded_debug"))]626	pub const_data: BoundedVec<u8, CustomDataLimit>,627	#[derivative(Debug(format_with = "bounded_debug"))]628	pub variable_data: BoundedVec<u8, CustomDataLimit>,629	#[derivative(Debug(format_with = "bounded_map_debug"))]630	pub users: BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,631}632633#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]634#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]635pub enum CreateItemExData<CrossAccountId> {636	NFT(637		#[derivative(Debug(format_with = "bounded_debug"))]638		BoundedVec<CreateNftExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,639	),640	Fungible(641		#[derivative(Debug(format_with = "bounded_map_debug"))]642		BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,643	),644	/// Many tokens, each may have only one owner645	RefungibleMultipleItems(646		#[derivative(Debug(format_with = "bounded_debug"))]647		BoundedVec<CreateRefungibleExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,648	),649	/// Single token, which may have many owners650	RefungibleMultipleOwners(CreateRefungibleExData<CrossAccountId>),651}652653impl CreateItemData {654	pub fn data_size(&self) -> usize {655		match self {656			CreateItemData::NFT(data) => data.variable_data.len() + data.const_data.len(),657			CreateItemData::ReFungible(data) => data.variable_data.len() + data.const_data.len(),658			_ => 0,659		}660	}661}662663impl From<CreateNftData> for CreateItemData {664	fn from(item: CreateNftData) -> Self {665		CreateItemData::NFT(item)666	}667}668669impl From<CreateReFungibleData> for CreateItemData {670	fn from(item: CreateReFungibleData) -> Self {671		CreateItemData::ReFungible(item)672	}673}674675impl From<CreateFungibleData> for CreateItemData {676	fn from(item: CreateFungibleData) -> Self {677		CreateItemData::Fungible(item)678	}679}680681#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]682#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]683pub struct CollectionStats {684	pub created: u32,685	pub destroyed: u32,686	pub alive: u32,687}
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 mapping;39mod migration;4041pub const MAX_DECIMAL_POINTS: DecimalPoints = 30;42pub const MAX_REFUNGIBLE_PIECES: u128 = 1_000_000_000_000_000_000_000;43pub const MAX_SPONSOR_TIMEOUT: u32 = 10_368_000;4445pub const MAX_TOKEN_OWNERSHIP: u32 = if cfg!(not(feature = "limit-testing")) {46	100_00047} else {48	1049};50pub const COLLECTION_NUMBER_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {51	100_00052} else {53	1054};55pub const CUSTOM_DATA_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {56	204857} else {58	1059};60pub const COLLECTION_ADMINS_LIMIT: u32 = 5;61pub const COLLECTION_TOKEN_LIMIT: u32 = u32::MAX;62pub const ACCOUNT_TOKEN_OWNERSHIP_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {63	1_000_00064} else {65	1066};6768// Timeouts for item types in passed blocks69pub const NFT_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;70pub const FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;71pub const REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;7273pub const SPONSOR_APPROVE_TIMEOUT: u32 = 5;7475// Schema limits76pub const OFFCHAIN_SCHEMA_LIMIT: u32 = 8192;77pub const VARIABLE_ON_CHAIN_SCHEMA_LIMIT: u32 = 8192;78pub const CONST_ON_CHAIN_SCHEMA_LIMIT: u32 = 32768;7980pub const MAX_COLLECTION_NAME_LENGTH: u32 = 64;81pub const MAX_COLLECTION_DESCRIPTION_LENGTH: u32 = 256;82pub const MAX_TOKEN_PREFIX_LENGTH: u32 = 16;8384/// How much items can be created per single85/// create_many call86pub const MAX_ITEMS_PER_BATCH: u32 = 200;8788pub type CustomDataLimit = ConstU32<CUSTOM_DATA_LIMIT>;8990#[derive(91	Encode,92	Decode,93	PartialEq,94	Eq,95	PartialOrd,96	Ord,97	Clone,98	Copy,99	Debug,100	Default,101	TypeInfo,102	MaxEncodedLen,103)]104#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]105pub struct CollectionId(pub u32);106impl EncodeLike<u32> for CollectionId {}107impl EncodeLike<CollectionId> for u32 {}108109#[derive(110	Encode,111	Decode,112	PartialEq,113	Eq,114	PartialOrd,115	Ord,116	Clone,117	Copy,118	Debug,119	Default,120	TypeInfo,121	MaxEncodedLen,122)]123#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]124pub struct TokenId(pub u32);125impl EncodeLike<u32> for TokenId {}126impl EncodeLike<TokenId> for u32 {}127128impl TokenId {129	pub fn try_next(self) -> Result<TokenId, ArithmeticError> {130		self.0131			.checked_add(1)132			.ok_or(ArithmeticError::Overflow)133			.map(Self)134	}135}136137impl From<TokenId> for U256 {138	fn from(t: TokenId) -> Self {139		t.0.into()140	}141}142143impl TryFrom<U256> for TokenId {144	type Error = &'static str;145146	fn try_from(value: U256) -> Result<Self, Self::Error> {147		Ok(TokenId(value.try_into().map_err(|_| "too large token id")?))148	}149}150151pub struct OverflowError;152impl From<OverflowError> for &'static str {153	fn from(_: OverflowError) -> Self {154		"overflow occured"155	}156}157158pub type DecimalPoints = u8;159160#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]161#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]162pub enum CollectionMode {163	NFT,164	// decimal points165	Fungible(DecimalPoints),166	ReFungible,167}168169impl CollectionMode {170	pub fn id(&self) -> u8 {171		match self {172			CollectionMode::NFT => 1,173			CollectionMode::Fungible(_) => 2,174			CollectionMode::ReFungible => 3,175		}176	}177}178179pub trait SponsoringResolve<AccountId, Call> {180	fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>;181}182183#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]184#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]185pub enum AccessMode {186	Normal,187	AllowList,188}189impl Default for AccessMode {190	fn default() -> Self {191		Self::Normal192	}193}194195#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]196#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]197pub enum SchemaVersion {198	ImageURL,199	Unique,200}201impl Default for SchemaVersion {202	fn default() -> Self {203		Self::ImageURL204	}205}206207#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]208#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]209pub struct Ownership<AccountId> {210	pub owner: AccountId,211	pub fraction: u128,212}213214#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]215#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]216pub enum SponsorshipState<AccountId> {217	/// The fees are applied to the transaction sender218	Disabled,219	Unconfirmed(AccountId),220	/// Transactions are sponsored by specified account221	Confirmed(AccountId),222}223224impl<AccountId> SponsorshipState<AccountId> {225	pub fn sponsor(&self) -> Option<&AccountId> {226		match self {227			Self::Confirmed(sponsor) => Some(sponsor),228			_ => None,229		}230	}231232	pub fn pending_sponsor(&self) -> Option<&AccountId> {233		match self {234			Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),235			_ => None,236		}237	}238239	pub fn confirmed(&self) -> bool {240		matches!(self, Self::Confirmed(_))241	}242}243244impl<T> Default for SponsorshipState<T> {245	fn default() -> Self {246		Self::Disabled247	}248}249250#[struct_versioning::versioned(version = 2, upper)]251#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen)]252#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]253pub struct Collection<AccountId> {254	pub owner: AccountId,255	pub mode: CollectionMode,256	pub access: AccessMode,257	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]258	pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,259	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]260	pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,261	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]262	pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,263	pub mint_mode: bool,264	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]265	pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,266	pub schema_version: SchemaVersion,267	pub sponsorship: SponsorshipState<AccountId>,268269	#[version(..2)]270	pub limits: CollectionLimitsVersion1, // Collection private restrictions271	#[version(2.., upper(limits.into()))]272	pub limits: CollectionLimitsVersion2,273274	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]275	pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,276	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]277	pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,278	pub meta_update_permission: MetaUpdatePermission,279}280281#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Debug, Derivative, MaxEncodedLen)]282#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]283#[derivative(Default(bound = ""))]284pub struct CreateCollectionData<AccountId> {285	#[derivative(Default(value = "CollectionMode::NFT"))]286	pub mode: CollectionMode,287	pub access: Option<AccessMode>,288	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]289	pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,290	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]291	pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,292	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]293	pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,294	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]295	pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,296	pub schema_version: Option<SchemaVersion>,297	pub pending_sponsor: Option<AccountId>,298	pub limits: Option<CollectionLimits>,299	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]300	pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,301	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]302	pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,303	pub meta_update_permission: Option<MetaUpdatePermission>,304}305306#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]307#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]308pub struct NftItemType<AccountId> {309	pub owner: AccountId,310	pub const_data: Vec<u8>,311	pub variable_data: Vec<u8>,312}313314#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]315#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]316pub struct FungibleItemType {317	pub value: u128,318}319320#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]321#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]322pub struct ReFungibleItemType<AccountId> {323	pub owner: Vec<Ownership<AccountId>>,324	pub const_data: Vec<u8>,325	pub variable_data: Vec<u8>,326}327328/// All fields are wrapped in `Option`s, where None means chain default329#[struct_versioning::versioned(version = 2, upper)]330#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]331#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]332pub struct CollectionLimits {333	pub account_token_ownership_limit: Option<u32>,334	pub sponsored_data_size: Option<u32>,335	/// None - setVariableMetadata is not sponsored336	/// Some(v) - setVariableMetadata is sponsored337	///           if there is v block between txs338	pub sponsored_data_rate_limit: Option<SponsoringRateLimit>,339	pub token_limit: Option<u32>,340341	// Timeouts for item types in passed blocks342	pub sponsor_transfer_timeout: Option<u32>,343	pub sponsor_approve_timeout: Option<u32>,344	pub owner_can_transfer: Option<bool>,345	pub owner_can_destroy: Option<bool>,346	pub transfers_enabled: Option<bool>,347348	#[version(2.., upper(None))]349	pub nesting_rule: Option<NestingRule>,350}351352impl CollectionLimits {353	pub fn account_token_ownership_limit(&self) -> u32 {354		self.account_token_ownership_limit355			.unwrap_or(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)356			.min(MAX_TOKEN_OWNERSHIP)357	}358	pub fn sponsored_data_size(&self) -> u32 {359		self.sponsored_data_size360			.unwrap_or(CUSTOM_DATA_LIMIT)361			.min(CUSTOM_DATA_LIMIT)362	}363	pub fn token_limit(&self) -> u32 {364		self.token_limit365			.unwrap_or(COLLECTION_TOKEN_LIMIT)366			.min(COLLECTION_TOKEN_LIMIT)367	}368	pub fn sponsor_transfer_timeout(&self, default: u32) -> u32 {369		self.sponsor_transfer_timeout370			.unwrap_or(default)371			.min(MAX_SPONSOR_TIMEOUT)372	}373	pub fn sponsor_approve_timeout(&self) -> u32 {374		self.sponsor_approve_timeout375			.unwrap_or(SPONSOR_APPROVE_TIMEOUT)376			.min(MAX_SPONSOR_TIMEOUT)377	}378	pub fn owner_can_transfer(&self) -> bool {379		self.owner_can_transfer.unwrap_or(true)380	}381	pub fn owner_can_destroy(&self) -> bool {382		self.owner_can_destroy.unwrap_or(true)383	}384	pub fn transfers_enabled(&self) -> bool {385		self.transfers_enabled.unwrap_or(true)386	}387	pub fn sponsored_data_rate_limit(&self) -> Option<u32> {388		match self389			.sponsored_data_rate_limit390			.unwrap_or(SponsoringRateLimit::SponsoringDisabled)391		{392			SponsoringRateLimit::SponsoringDisabled => None,393			SponsoringRateLimit::Blocks(v) => Some(v.min(MAX_SPONSOR_TIMEOUT)),394		}395	}396	pub fn nesting_rule(&self) -> &NestingRule {397		static DEFAULT: NestingRule = NestingRule::Owner;398		self.nesting_rule.as_ref().unwrap_or(&DEFAULT)399	}400}401402#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative)]403#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]404#[derivative(Debug)]405pub enum NestingRule {406	/// No one can nest tokens407	Disabled,408	/// Owner can nest any tokens409	Owner,410	/// Owner can nest tokens from specified collections411	OwnerRestricted(412		#[cfg_attr(feature = "serde1", serde(with = "bounded::set_serde"))]413		#[derivative(Debug(format_with = "bounded::set_debug"))]414		BoundedBTreeSet<CollectionId, ConstU32<16>>,415	),416}417418#[derive(Encode, Decode, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]419#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]420pub enum SponsoringRateLimit {421	SponsoringDisabled,422	Blocks(u32),423}424425#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]426#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]427#[derivative(Debug)]428pub struct CreateNftData {429	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]430	#[derivative(Debug(format_with = "bounded::vec_debug"))]431	pub const_data: BoundedVec<u8, CustomDataLimit>,432	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]433	#[derivative(Debug(format_with = "bounded::vec_debug"))]434	pub variable_data: BoundedVec<u8, CustomDataLimit>,435}436437#[derive(Encode, Decode, MaxEncodedLen, Default, Debug, Clone, PartialEq, TypeInfo)]438#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]439pub struct CreateFungibleData {440	pub value: u128,441}442443#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]444#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]445#[derivative(Debug)]446pub struct CreateReFungibleData {447	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]448	#[derivative(Debug(format_with = "bounded::vec_debug"))]449	pub const_data: BoundedVec<u8, CustomDataLimit>,450	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]451	#[derivative(Debug(format_with = "bounded::vec_debug"))]452	pub variable_data: BoundedVec<u8, CustomDataLimit>,453	pub pieces: u128,454}455456#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]457#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]458pub enum MetaUpdatePermission {459	ItemOwner,460	Admin,461	None,462}463464impl Default for MetaUpdatePermission {465	fn default() -> Self {466		Self::ItemOwner467	}468}469470#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]471#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]472pub enum CreateItemData {473	NFT(CreateNftData),474	Fungible(CreateFungibleData),475	ReFungible(CreateReFungibleData),476}477478#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]479#[derivative(Debug)]480pub struct CreateNftExData<CrossAccountId> {481	#[derivative(Debug(format_with = "bounded::vec_debug"))]482	pub const_data: BoundedVec<u8, CustomDataLimit>,483	#[derivative(Debug(format_with = "bounded::vec_debug"))]484	pub variable_data: BoundedVec<u8, CustomDataLimit>,485	pub owner: CrossAccountId,486}487488#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]489#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]490pub struct CreateRefungibleExData<CrossAccountId> {491	#[derivative(Debug(format_with = "bounded::vec_debug"))]492	pub const_data: BoundedVec<u8, CustomDataLimit>,493	#[derivative(Debug(format_with = "bounded::vec_debug"))]494	pub variable_data: BoundedVec<u8, CustomDataLimit>,495	#[derivative(Debug(format_with = "bounded::map_debug"))]496	pub users: BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,497}498499#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]500#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]501pub enum CreateItemExData<CrossAccountId> {502	NFT(503		#[derivative(Debug(format_with = "bounded::vec_debug"))]504		BoundedVec<CreateNftExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,505	),506	Fungible(507		#[derivative(Debug(format_with = "bounded::map_debug"))]508		BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,509	),510	/// Many tokens, each may have only one owner511	RefungibleMultipleItems(512		#[derivative(Debug(format_with = "bounded::vec_debug"))]513		BoundedVec<CreateRefungibleExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,514	),515	/// Single token, which may have many owners516	RefungibleMultipleOwners(CreateRefungibleExData<CrossAccountId>),517}518519impl CreateItemData {520	pub fn data_size(&self) -> usize {521		match self {522			CreateItemData::NFT(data) => data.variable_data.len() + data.const_data.len(),523			CreateItemData::ReFungible(data) => data.variable_data.len() + data.const_data.len(),524			_ => 0,525		}526	}527}528529impl From<CreateNftData> for CreateItemData {530	fn from(item: CreateNftData) -> Self {531		CreateItemData::NFT(item)532	}533}534535impl From<CreateReFungibleData> for CreateItemData {536	fn from(item: CreateReFungibleData) -> Self {537		CreateItemData::ReFungible(item)538	}539}540541impl From<CreateFungibleData> for CreateItemData {542	fn from(item: CreateFungibleData) -> Self {543		CreateItemData::Fungible(item)544	}545}546547#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]548#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]549pub struct CollectionStats {550	pub created: u32,551	pub destroyed: u32,552	pub alive: u32,553}