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

difftreelog

CORE-390 Add read only flag

Trubnikov Sergey2022-06-03parent: #1009216.patch.diff
in: master

8 files changed

modifiedpallets/common/src/erc.rsdiffbeforeafterboth
--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -87,18 +87,16 @@
 		check_is_owner(caller, self)?;
 
 		let sponsor = T::CrossAccountId::from_eth(sponsor);
-		self.set_sponsor(sponsor.as_sub().clone());
-		save(self);
-		Ok(())
+		self.set_sponsor(sponsor.as_sub().clone()).map_err(dispatch_to_evm::<T>)?;
+		save(self)
 	}
 
 	fn confirm_collection_sponsorship(&mut self, caller: caller) -> Result<void> {
 		let caller = T::CrossAccountId::from_eth(caller);
-		if !self.confirm_sponsorship(caller.as_sub()) {
+		if !self.confirm_sponsorship(caller.as_sub()).map_err(dispatch_to_evm::<T>)? {
 			return Err(Error::Revert("Caller is not set as sponsor".into()));
 		}
-		save(self);
-		Ok(())
+		save(self)
 	}
 
 	#[solidity(rename_selector = "setCollectionLimit")]
@@ -134,8 +132,7 @@
 		}
 		self.limits = <Pallet<T>>::clamp_limits(self.mode.clone(), &self.limits, limits)
 			.map_err(dispatch_to_evm::<T>)?;
-		save(self);
-		Ok(())
+		save(self)
 	}
 
 	#[solidity(rename_selector = "setCollectionLimit")]
@@ -162,8 +159,7 @@
 		}
 		self.limits = <Pallet<T>>::clamp_limits(self.mode.clone(), &self.limits, limits)
 			.map_err(dispatch_to_evm::<T>)?;
-		save(self);
-		Ok(())
+		save(self)
 	}
 
 	fn contract_address(&self, _caller: caller) -> Result<address> {
@@ -296,7 +292,7 @@
 	}
 }
 
-fn check_is_owner<T: Config>(caller: caller, collection: &CollectionHandle<T>) -> Result<()> {
+fn check_is_owner<T: Config>(caller: caller, collection: &CollectionHandle<T>) -> Result<void> {
 	let caller = T::CrossAccountId::from_eth(caller);
 	collection
 		.check_is_owner(&caller)
@@ -315,8 +311,10 @@
 	Ok(caller)
 }
 
-fn save<T: Config>(collection: &CollectionHandle<T>) {
+fn save<T: Config>(collection: &CollectionHandle<T>) -> Result<void> {
+	collection.check_is_read_only().map_err(dispatch_to_evm::<T>)?;
 	<crate::CollectionById<T>>::insert(collection.id, collection.collection.clone());
+	Ok(())
 }
 
 pub fn token_uri_key() -> up_data_structs::PropertyKey {
modifiedpallets/common/src/lib.rsdiffbeforeafterboth
--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -148,23 +148,35 @@
 					.saturating_mul(writes),
 			))
 	}
-
-	pub fn save(self) -> DispatchResult {
+	pub fn save(self) -> Result<(), DispatchError> {
+		self.check_is_read_only()?;
 		<CollectionById<T>>::insert(self.id, self.collection);
 		Ok(())
 	}
 
-	pub fn set_sponsor(&mut self, sponsor: T::AccountId) {
+	pub fn set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {
+		self.check_is_read_only()?;
 		self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor);
+		Ok(())
 	}
 
-	pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> bool {
+	pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> Result<bool, DispatchError> {
+		self.check_is_read_only()?;
+
 		if self.collection.sponsorship.pending_sponsor() != Some(sender) {
-			return false;
-		};
+			return Ok(false);
+		}
 
 		self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());
-		true
+		Ok(true)
+	}
+
+	pub fn check_is_read_only(&self) -> DispatchResult {
+		if self.read_only {
+			return Err(<Error<T>>::CollectionNotFound)?;
+		}
+		
+		Ok(())
 	}
 }
 
@@ -434,6 +446,9 @@
 
 		/// Empty property keys are forbidden
 		EmptyPropertyKey,
+
+		/// Collection is read only
+		CollectionIsReadOnly,
 	}
 
 	#[pallet::storage]
@@ -669,6 +684,7 @@
 			sponsorship,
 			limits,
 			permissions,
+			read_only,
 		} = <CollectionById<T>>::get(collection)?;
 
 		let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)
@@ -698,6 +714,7 @@
 			permissions,
 			token_property_permissions,
 			properties,
+			read_only,
 		})
 	}
 }
@@ -778,6 +795,7 @@
 					Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)
 				})
 				.unwrap_or_else(|| Ok(CollectionPermissions::default()))?,
+			read_only: false,
 		};
 
 		let mut collection_properties = up_data_structs::CollectionProperties::get();
@@ -834,6 +852,7 @@
 		collection: CollectionHandle<T>,
 		sender: &T::CrossAccountId,
 	) -> DispatchResult {
+		collection.check_is_read_only()?;
 		ensure!(
 			collection.limits.owner_can_destroy(),
 			<Error<T>>::NoPermission,
@@ -863,6 +882,7 @@
 		sender: &T::CrossAccountId,
 		property: Property,
 	) -> DispatchResult {
+		collection.check_is_read_only()?;
 		collection.check_is_owner_or_admin(sender)?;
 
 		CollectionProperties::<T>::try_mutate(collection.id, |properties| {
@@ -908,6 +928,8 @@
 		sender: &T::CrossAccountId,
 		properties: Vec<Property>,
 	) -> DispatchResult {
+		collection.check_is_read_only()?;
+
 		for property in properties {
 			Self::set_collection_property(collection, sender, property)?;
 		}
@@ -920,6 +942,7 @@
 		sender: &T::CrossAccountId,
 		property_key: PropertyKey,
 	) -> DispatchResult {
+		collection.check_is_read_only()?;
 		collection.check_is_owner_or_admin(sender)?;
 
 		CollectionProperties::<T>::try_mutate(collection.id, |properties| {
@@ -941,6 +964,8 @@
 		sender: &T::CrossAccountId,
 		property_keys: Vec<PropertyKey>,
 	) -> DispatchResult {
+		collection.check_is_read_only()?;
+
 		for key in property_keys {
 			Self::delete_collection_property(collection, sender, key)?;
 		}
@@ -965,6 +990,7 @@
 		sender: &T::CrossAccountId,
 		property_permission: PropertyKeyPermission,
 	) -> DispatchResult {
+		collection.check_is_read_only()?;
 		collection.check_is_owner_or_admin(sender)?;
 
 		let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);
@@ -996,6 +1022,8 @@
 		sender: &T::CrossAccountId,
 		property_permissions: Vec<PropertyKeyPermission>,
 	) -> DispatchResult {
+		collection.check_is_read_only()?;
+
 		for prop_pemission in property_permissions {
 			Self::set_property_permission(collection, sender, prop_pemission)?;
 		}
@@ -1083,6 +1111,7 @@
 		user: &T::CrossAccountId,
 		allowed: bool,
 	) -> DispatchResult {
+		collection.check_is_read_only()?;
 		collection.check_is_owner_or_admin(sender)?;
 
 		// =========
@@ -1102,6 +1131,7 @@
 		user: &T::CrossAccountId,
 		admin: bool,
 	) -> DispatchResult {
+		collection.check_is_read_only()?;
 		collection.check_is_owner_or_admin(sender)?;
 
 		let was_admin = <IsAdmin<T>>::get((collection.id, user));
modifiedpallets/fungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -168,6 +168,8 @@
 		owner: &T::CrossAccountId,
 		amount: u128,
 	) -> DispatchResult {
+		collection.check_is_read_only()?;
+
 		let total_supply = <TotalSupply<T>>::get(collection.id)
 			.checked_sub(amount)
 			.ok_or(<CommonError<T>>::TokenValueTooLow)?;
@@ -214,6 +216,8 @@
 		amount: u128,
 		nesting_budget: &dyn Budget,
 	) -> DispatchResult {
+		collection.check_is_read_only()?;
+
 		ensure!(
 			collection.limits.transfers_enabled(),
 			<CommonError<T>>::TransferNotAllowed,
@@ -283,6 +287,8 @@
 		data: BTreeMap<T::CrossAccountId, u128>,
 		nesting_budget: &dyn Budget,
 	) -> DispatchResult {
+		collection.check_is_read_only()?;
+
 		if !collection.is_owner_or_admin(sender) {
 			ensure!(
 				collection.permissions.mint_mode(),
@@ -384,6 +390,7 @@
 		spender: &T::CrossAccountId,
 		amount: u128,
 	) -> DispatchResult {
+		collection.check_is_read_only()?;
 		if collection.permissions.access() == AccessMode::AllowList {
 			collection.check_allowlist(owner)?;
 			collection.check_allowlist(spender)?;
modifiedpallets/nonfungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -336,6 +336,8 @@
 		sender: &T::CrossAccountId,
 		token: TokenId,
 	) -> DispatchResult {
+		collection.check_is_read_only()?;
+
 		let token_data =
 			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;
 		ensure!(
@@ -456,6 +458,7 @@
 			&property.key,
 			is_token_create,
 		)?;
+		collection.check_is_read_only()?;
 
 		<TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {
 			let property = property.clone();
@@ -494,6 +497,7 @@
 		property_key: PropertyKey,
 	) -> DispatchResult {
 		Self::check_token_change_permission(collection, sender, token_id, &property_key, false)?;
+		collection.check_is_read_only()?;
 
 		<TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {
 			properties.remove(&property_key)
@@ -570,6 +574,8 @@
 		token_id: TokenId,
 		property_keys: Vec<PropertyKey>,
 	) -> DispatchResult {
+		collection.check_is_read_only()?;
+
 		for key in property_keys {
 			Self::delete_token_property(collection, sender, token_id, key)?;
 		}
@@ -616,6 +622,8 @@
 		token: TokenId,
 		nesting_budget: &dyn Budget,
 	) -> DispatchResult {
+		collection.check_is_read_only()?;
+
 		ensure!(
 			collection.limits.transfers_enabled(),
 			<CommonError<T>>::TransferNotAllowed
@@ -894,6 +902,8 @@
 		token: TokenId,
 		spender: Option<&T::CrossAccountId>,
 	) -> DispatchResult {
+		collection.check_is_read_only()?;
+		
 		if collection.permissions.access() == AccessMode::AllowList {
 			collection.check_allowlist(sender)?;
 			if let Some(spender) = spender {
modifiedpallets/refungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -234,6 +234,7 @@
 	}
 
 	pub fn burn_token(collection: &RefungibleHandle<T>, token_id: TokenId) -> DispatchResult {
+		collection.check_is_read_only()?;
 		let burnt = <TokensBurnt<T>>::get(collection.id)
 			.checked_add(1)
 			.ok_or(ArithmeticError::Overflow)?;
@@ -253,6 +254,7 @@
 		token: TokenId,
 		amount: u128,
 	) -> DispatchResult {
+		collection.check_is_read_only()?;
 		let total_supply = <TotalSupply<T>>::get((collection.id, token))
 			.checked_sub(amount)
 			.ok_or(<CommonError<T>>::TokenValueTooLow)?;
@@ -325,6 +327,7 @@
 		amount: u128,
 		nesting_budget: &dyn Budget,
 	) -> DispatchResult {
+		collection.check_is_read_only()?;
 		ensure!(
 			collection.limits.transfers_enabled(),
 			<CommonError<T>>::TransferNotAllowed
@@ -573,6 +576,7 @@
 		token: TokenId,
 		amount: u128,
 	) -> DispatchResult {
+		collection.check_is_read_only()?;
 		if collection.permissions.access() == AccessMode::AllowList {
 			collection.check_allowlist(sender)?;
 			collection.check_allowlist(spender)?;
modifiedpallets/unique/src/lib.rsdiffbeforeafterboth
--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -304,6 +304,7 @@
 		pub fn destroy_collection(origin, collection_id: CollectionId) -> DispatchResult {
 			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
 			let collection = <CollectionHandle<T>>::try_get(collection_id)?;
+			collection.check_is_read_only()?;
 
 			// =========
 
@@ -406,6 +407,7 @@
 			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
 
 			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
+			target_collection.check_is_read_only()?;
 			target_collection.check_is_owner(&sender)?;
 
 			target_collection.owner = new_owner.clone();
@@ -487,7 +489,7 @@
 			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
 			target_collection.check_is_owner(&sender)?;
 
-			target_collection.set_sponsor(new_sponsor.clone());
+			target_collection.set_sponsor(new_sponsor.clone())?;
 
 			<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(
 				collection_id,
@@ -511,7 +513,7 @@
 
 			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
 			ensure!(
-				target_collection.confirm_sponsorship(&sender),
+				target_collection.confirm_sponsorship(&sender)?,
 				Error::<T>::ConfirmUnsetSponsorFail
 			);
 
modifiedprimitives/data-structs/src/lib.rsdiffbeforeafterboth
before · primitives/data-structs/src/lib.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617#![cfg_attr(not(feature = "std"), no_std)]1819use core::{20	convert::{TryFrom, TryInto},21	fmt,22};23use frame_support::{24	storage::{bounded_btree_map::BoundedBTreeMap, bounded_btree_set::BoundedBTreeSet},25	traits::Get,26	parameter_types,27};2829#[cfg(feature = "serde")]30use serde::{Serialize, Deserialize};3132use sp_core::U256;33use sp_runtime::{ArithmeticError, sp_std::prelude::Vec, Permill};34use codec::{Decode, Encode, EncodeLike, MaxEncodedLen};35use frame_support::{BoundedVec, traits::ConstU32};36use derivative::Derivative;37use scale_info::TypeInfo;3839pub mod rmrk;4041// RMRK42use rmrk::{43	CollectionInfo, NftInfo, ResourceInfo, PropertyInfo, BaseInfo, PartType, Theme, ThemeProperty,44	ResourceTypes, BasicResource, ComposableResource, SlotResource,45};46pub use rmrk::{47	primitives::{48		CollectionId as RmrkCollectionId, NftId as RmrkNftId, BaseId as RmrkBaseId,49		PartId as RmrkPartId, ResourceId as RmrkResourceId,50	},51	NftChild as RmrkNftChild, AccountIdOrCollectionNftTuple as RmrkAccountIdOrCollectionNftTuple,52	FixedPart as RmrkFixedPart, SlotPart as RmrkSlotPart, EquippableList as RmrkEquippableList,53};5455mod bounded;56pub mod budget;57pub mod mapping;58mod migration;5960pub const MAX_DECIMAL_POINTS: DecimalPoints = 30;61pub const MAX_REFUNGIBLE_PIECES: u128 = 1_000_000_000_000_000_000_000;62pub const MAX_SPONSOR_TIMEOUT: u32 = 10_368_000;6364pub const MAX_TOKEN_OWNERSHIP: u32 = if cfg!(not(feature = "limit-testing")) {65	100_00066} else {67	1068};69pub const COLLECTION_NUMBER_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {70	100_00071} else {72	1073};74pub const CUSTOM_DATA_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {75	204876} else {77	1078};79pub const COLLECTION_ADMINS_LIMIT: u32 = 5;80pub const COLLECTION_TOKEN_LIMIT: u32 = u32::MAX;81pub const ACCOUNT_TOKEN_OWNERSHIP_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {82	1_000_00083} else {84	1085};8687// Timeouts for item types in passed blocks88pub const NFT_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;89pub const FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;90pub const REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;9192pub const SPONSOR_APPROVE_TIMEOUT: u32 = 5;9394// Schema limits95pub const OFFCHAIN_SCHEMA_LIMIT: u32 = 8192;96pub const VARIABLE_ON_CHAIN_SCHEMA_LIMIT: u32 = 8192;97pub const CONST_ON_CHAIN_SCHEMA_LIMIT: u32 = 32768;9899pub const COLLECTION_FIELD_LIMIT: u32 = CONST_ON_CHAIN_SCHEMA_LIMIT;100101pub const MAX_COLLECTION_NAME_LENGTH: u32 = 64;102pub const MAX_COLLECTION_DESCRIPTION_LENGTH: u32 = 256;103pub const MAX_TOKEN_PREFIX_LENGTH: u32 = 16;104105pub const MAX_PROPERTY_KEY_LENGTH: u32 = 256;106pub const MAX_PROPERTY_VALUE_LENGTH: u32 = 32768;107pub const MAX_PROPERTIES_PER_ITEM: u32 = 64;108109pub const MAX_COLLECTION_PROPERTIES_SIZE: u32 = 40960;110pub const MAX_TOKEN_PROPERTIES_SIZE: u32 = 32768;111112// RMRK constants113pub const RMRK_STRING_LIMIT: u32 = 128;114pub const RMRK_COLLECTION_SYMBOL_LIMIT: u32 = 100;115pub const RMRK_RESOURCE_SYMBOL_LIMIT: u32 = 10;116pub const RMRK_KEY_LIMIT: u32 = 32;117pub const RMRK_VALUE_LIMIT: u32 = 256;118119/// How much items can be created per single120/// create_many call121pub const MAX_ITEMS_PER_BATCH: u32 = 200;122123pub type CustomDataLimit = ConstU32<CUSTOM_DATA_LIMIT>;124125#[derive(126	Encode,127	Decode,128	PartialEq,129	Eq,130	PartialOrd,131	Ord,132	Clone,133	Copy,134	Debug,135	Default,136	TypeInfo,137	MaxEncodedLen,138)]139#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]140pub struct CollectionId(pub u32);141impl EncodeLike<u32> for CollectionId {}142impl EncodeLike<CollectionId> for u32 {}143144#[derive(145	Encode,146	Decode,147	PartialEq,148	Eq,149	PartialOrd,150	Ord,151	Clone,152	Copy,153	Debug,154	Default,155	TypeInfo,156	MaxEncodedLen,157)]158#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]159pub struct TokenId(pub u32);160impl EncodeLike<u32> for TokenId {}161impl EncodeLike<TokenId> for u32 {}162163impl TokenId {164	pub fn try_next(self) -> Result<TokenId, ArithmeticError> {165		self.0166			.checked_add(1)167			.ok_or(ArithmeticError::Overflow)168			.map(Self)169	}170}171172impl From<TokenId> for U256 {173	fn from(t: TokenId) -> Self {174		t.0.into()175	}176}177178impl TryFrom<U256> for TokenId {179	type Error = &'static str;180181	fn try_from(value: U256) -> Result<Self, Self::Error> {182		Ok(TokenId(value.try_into().map_err(|_| "too large token id")?))183	}184}185186#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]187#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]188pub struct TokenData<CrossAccountId> {189	pub properties: Vec<Property>,190	pub owner: Option<CrossAccountId>,191}192193pub struct OverflowError;194impl From<OverflowError> for &'static str {195	fn from(_: OverflowError) -> Self {196		"overflow occured"197	}198}199200pub type DecimalPoints = u8;201202#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]203#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]204pub enum CollectionMode {205	NFT,206	// decimal points207	Fungible(DecimalPoints),208	ReFungible,209}210211impl CollectionMode {212	pub fn id(&self) -> u8 {213		match self {214			CollectionMode::NFT => 1,215			CollectionMode::Fungible(_) => 2,216			CollectionMode::ReFungible => 3,217		}218	}219}220221pub trait SponsoringResolve<AccountId, Call> {222	fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>;223}224225#[derive(Encode, Decode, Eq, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]226#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]227pub enum AccessMode {228	Normal,229	AllowList,230}231impl Default for AccessMode {232	fn default() -> Self {233		Self::Normal234	}235}236237#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]238#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]239pub enum SchemaVersion {240	ImageURL,241	Unique,242}243impl Default for SchemaVersion {244	fn default() -> Self {245		Self::ImageURL246	}247}248249#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]250#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]251pub struct Ownership<AccountId> {252	pub owner: AccountId,253	pub fraction: u128,254}255256#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]257#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]258pub enum SponsorshipState<AccountId> {259	/// The fees are applied to the transaction sender260	Disabled,261	Unconfirmed(AccountId),262	/// Transactions are sponsored by specified account263	Confirmed(AccountId),264}265266impl<AccountId> SponsorshipState<AccountId> {267	pub fn sponsor(&self) -> Option<&AccountId> {268		match self {269			Self::Confirmed(sponsor) => Some(sponsor),270			_ => None,271		}272	}273274	pub fn pending_sponsor(&self) -> Option<&AccountId> {275		match self {276			Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),277			_ => None,278		}279	}280281	pub fn confirmed(&self) -> bool {282		matches!(self, Self::Confirmed(_))283	}284}285286impl<T> Default for SponsorshipState<T> {287	fn default() -> Self {288		Self::Disabled289	}290}291292/// Used in storage293#[struct_versioning::versioned(version = 2, upper)]294#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen)]295pub struct Collection<AccountId> {296	pub owner: AccountId,297	pub mode: CollectionMode,298	#[version(..2)]299	pub access: AccessMode,300	pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,301	pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,302	pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,303304	#[version(..2)]305	pub mint_mode: bool,306307	#[version(..2)]308	pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,309310	#[version(..2)]311	pub schema_version: SchemaVersion,312	pub sponsorship: SponsorshipState<AccountId>,313314	pub limits: CollectionLimits,315316	#[version(2.., upper(Default::default()))]317	pub permissions: CollectionPermissions,318319	#[version(..2)]320	pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,321322	#[version(..2)]323	pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,324325	#[version(..2)]326	pub meta_update_permission: MetaUpdatePermission,327}328329/// Used in RPC calls330#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]331#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]332pub struct RpcCollection<AccountId> {333	pub owner: AccountId,334	pub mode: CollectionMode,335	pub name: Vec<u16>,336	pub description: Vec<u16>,337	pub token_prefix: Vec<u8>,338	pub sponsorship: SponsorshipState<AccountId>,339	pub limits: CollectionLimits,340	pub permissions: CollectionPermissions,341	pub token_property_permissions: Vec<PropertyKeyPermission>,342	pub properties: Vec<Property>,343}344345#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Derivative, MaxEncodedLen)]346#[derivative(Debug, Default(bound = ""))]347pub struct CreateCollectionData<AccountId> {348	#[derivative(Default(value = "CollectionMode::NFT"))]349	pub mode: CollectionMode,350	pub access: Option<AccessMode>,351	pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,352	pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,353	pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,354	pub pending_sponsor: Option<AccountId>,355	pub limits: Option<CollectionLimits>,356	pub permissions: Option<CollectionPermissions>,357	pub token_property_permissions: CollectionPropertiesPermissionsVec,358	pub properties: CollectionPropertiesVec,359}360361pub type CollectionPropertiesPermissionsVec =362	BoundedVec<PropertyKeyPermission, ConstU32<MAX_PROPERTIES_PER_ITEM>>;363364pub type CollectionPropertiesVec = BoundedVec<Property, ConstU32<MAX_PROPERTIES_PER_ITEM>>;365366/// All fields are wrapped in `Option`s, where None means chain default367// When adding/removing fields from this struct - don't forget to also update clamp_limits368#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]369#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]370pub struct CollectionLimits {371	pub account_token_ownership_limit: Option<u32>,372	pub sponsored_data_size: Option<u32>,373374	/// FIXME should we delete this or repurpose it?375	/// None - setVariableMetadata is not sponsored376	/// Some(v) - setVariableMetadata is sponsored377	///           if there is v block between txs378	pub sponsored_data_rate_limit: Option<SponsoringRateLimit>,379	pub token_limit: Option<u32>,380381	// Timeouts for item types in passed blocks382	pub sponsor_transfer_timeout: Option<u32>,383	pub sponsor_approve_timeout: Option<u32>,384	pub owner_can_transfer: Option<bool>,385	pub owner_can_destroy: Option<bool>,386	pub transfers_enabled: Option<bool>,387}388389impl CollectionLimits {390	pub fn account_token_ownership_limit(&self) -> u32 {391		self.account_token_ownership_limit392			.unwrap_or(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)393			.min(MAX_TOKEN_OWNERSHIP)394	}395	pub fn sponsored_data_size(&self) -> u32 {396		self.sponsored_data_size397			.unwrap_or(CUSTOM_DATA_LIMIT)398			.min(CUSTOM_DATA_LIMIT)399	}400	pub fn token_limit(&self) -> u32 {401		self.token_limit402			.unwrap_or(COLLECTION_TOKEN_LIMIT)403			.min(COLLECTION_TOKEN_LIMIT)404	}405	pub fn sponsor_transfer_timeout(&self, default: u32) -> u32 {406		self.sponsor_transfer_timeout407			.unwrap_or(default)408			.min(MAX_SPONSOR_TIMEOUT)409	}410	pub fn sponsor_approve_timeout(&self) -> u32 {411		self.sponsor_approve_timeout412			.unwrap_or(SPONSOR_APPROVE_TIMEOUT)413			.min(MAX_SPONSOR_TIMEOUT)414	}415	pub fn owner_can_transfer(&self) -> bool {416		self.owner_can_transfer.unwrap_or(true)417	}418	pub fn owner_can_destroy(&self) -> bool {419		self.owner_can_destroy.unwrap_or(true)420	}421	pub fn transfers_enabled(&self) -> bool {422		self.transfers_enabled.unwrap_or(true)423	}424	pub fn sponsored_data_rate_limit(&self) -> Option<u32> {425		match self426			.sponsored_data_rate_limit427			.unwrap_or(SponsoringRateLimit::SponsoringDisabled)428		{429			SponsoringRateLimit::SponsoringDisabled => None,430			SponsoringRateLimit::Blocks(v) => Some(v.min(MAX_SPONSOR_TIMEOUT)),431		}432	}433}434435// When adding/removing fields from this struct - don't forget to also update clamp_limits436#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]437#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]438pub struct CollectionPermissions {439	pub access: Option<AccessMode>,440	pub mint_mode: Option<bool>,441	pub nesting: Option<NestingRule>,442}443444impl CollectionPermissions {445	pub fn access(&self) -> AccessMode {446		self.access.unwrap_or(AccessMode::Normal)447	}448	pub fn mint_mode(&self) -> bool {449		self.mint_mode.unwrap_or(false)450	}451	pub fn nesting(&self) -> &NestingRule {452		static DEFAULT: NestingRule = NestingRule::Disabled;453		self.nesting.as_ref().unwrap_or(&DEFAULT)454	}455}456457pub type OwnerRestrictedSet = BoundedBTreeSet<CollectionId, ConstU32<16>>;458459#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative)]460#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]461#[derivative(Debug)]462pub enum NestingRule {463	/// No one can nest tokens464	Disabled,465	/// Owner can nest any tokens466	Owner,467	/// Owner can nest tokens from specified collections468	OwnerRestricted(469		#[cfg_attr(feature = "serde1", serde(with = "bounded::set_serde"))]470		#[derivative(Debug(format_with = "bounded::set_debug"))]471		OwnerRestrictedSet,472	),473	/// Used for tests474	Permissive,475}476477#[derive(Encode, Decode, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]478#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]479pub enum SponsoringRateLimit {480	SponsoringDisabled,481	Blocks(u32),482}483484#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]485#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]486#[derivative(Debug)]487pub struct CreateNftData {488	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]489	#[derivative(Debug(format_with = "bounded::vec_debug"))]490	pub properties: CollectionPropertiesVec,491}492493#[derive(Encode, Decode, MaxEncodedLen, Default, Debug, Clone, PartialEq, TypeInfo)]494#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]495pub struct CreateFungibleData {496	pub value: u128,497}498499#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]500#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]501#[derivative(Debug)]502pub struct CreateReFungibleData {503	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]504	#[derivative(Debug(format_with = "bounded::vec_debug"))]505	pub const_data: BoundedVec<u8, CustomDataLimit>,506	pub pieces: u128,507}508509#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]510#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]511pub enum MetaUpdatePermission {512	ItemOwner,513	Admin,514	None,515}516517#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]518#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]519pub enum CreateItemData {520	NFT(CreateNftData),521	Fungible(CreateFungibleData),522	ReFungible(CreateReFungibleData),523}524525#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]526#[derivative(Debug)]527pub struct CreateNftExData<CrossAccountId> {528	#[derivative(Debug(format_with = "bounded::vec_debug"))]529	pub properties: CollectionPropertiesVec,530	pub owner: CrossAccountId,531}532533#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]534#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]535pub struct CreateRefungibleExData<CrossAccountId> {536	#[derivative(Debug(format_with = "bounded::vec_debug"))]537	pub const_data: BoundedVec<u8, CustomDataLimit>,538	#[derivative(Debug(format_with = "bounded::map_debug"))]539	pub users: BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,540}541542#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]543#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]544pub enum CreateItemExData<CrossAccountId> {545	NFT(546		#[derivative(Debug(format_with = "bounded::vec_debug"))]547		BoundedVec<CreateNftExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,548	),549	Fungible(550		#[derivative(Debug(format_with = "bounded::map_debug"))]551		BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,552	),553	/// Many tokens, each may have only one owner554	RefungibleMultipleItems(555		#[derivative(Debug(format_with = "bounded::vec_debug"))]556		BoundedVec<CreateRefungibleExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,557	),558	/// Single token, which may have many owners559	RefungibleMultipleOwners(CreateRefungibleExData<CrossAccountId>),560}561562impl CreateItemData {563	pub fn data_size(&self) -> usize {564		match self {565			CreateItemData::ReFungible(data) => data.const_data.len(),566			_ => 0,567		}568	}569}570571impl From<CreateNftData> for CreateItemData {572	fn from(item: CreateNftData) -> Self {573		CreateItemData::NFT(item)574	}575}576577impl From<CreateReFungibleData> for CreateItemData {578	fn from(item: CreateReFungibleData) -> Self {579		CreateItemData::ReFungible(item)580	}581}582583impl From<CreateFungibleData> for CreateItemData {584	fn from(item: CreateFungibleData) -> Self {585		CreateItemData::Fungible(item)586	}587}588589#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]590#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]591// todo possibly rename to be used generally as an address pair592pub struct TokenChild {593	pub token: TokenId,594	pub collection: CollectionId,595}596597#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]598#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]599pub struct CollectionStats {600	pub created: u32,601	pub destroyed: u32,602	pub alive: u32,603}604605#[derive(Encode, Decode, Clone, Debug)]606#[cfg_attr(feature = "std", derive(PartialEq))]607pub struct PhantomType<T>(core::marker::PhantomData<T>);608609impl<T: TypeInfo + 'static> TypeInfo for PhantomType<T> {610	type Identity = PhantomType<T>;611612	fn type_info() -> scale_info::Type {613		use scale_info::{614			Type, Path,615			build::{FieldsBuilder, UnnamedFields},616			type_params,617		};618		Type::builder()619			.path(Path::new("up_data_structs", "PhantomType"))620			.type_params(type_params!(T))621			.composite(<FieldsBuilder<UnnamedFields>>::default().field(|b| b.ty::<[T; 0]>()))622	}623}624impl<T> MaxEncodedLen for PhantomType<T> {625	fn max_encoded_len() -> usize {626		0627	}628}629630pub type PropertyKey = BoundedVec<u8, ConstU32<MAX_PROPERTY_KEY_LENGTH>>;631pub type PropertyValue = BoundedVec<u8, ConstU32<MAX_PROPERTY_VALUE_LENGTH>>;632633#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]634#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]635pub struct PropertyPermission {636	pub mutable: bool,637	pub collection_admin: bool,638	pub token_owner: bool,639}640641impl PropertyPermission {642	pub fn none() -> Self {643		Self {644			mutable: true,645			collection_admin: false,646			token_owner: false,647		}648	}649}650651#[derive(Encode, Decode, Debug, TypeInfo, Clone, PartialEq, MaxEncodedLen)]652#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]653pub struct Property {654	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]655	pub key: PropertyKey,656657	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]658	pub value: PropertyValue,659}660661impl Into<(PropertyKey, PropertyValue)> for Property {662	fn into(self) -> (PropertyKey, PropertyValue) {663		(self.key, self.value)664	}665}666667#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]668#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]669pub struct PropertyKeyPermission {670	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]671	pub key: PropertyKey,672673	pub permission: PropertyPermission,674}675676impl Into<(PropertyKey, PropertyPermission)> for PropertyKeyPermission {677	fn into(self) -> (PropertyKey, PropertyPermission) {678		(self.key, self.permission)679	}680}681682#[derive(Debug)]683pub enum PropertiesError {684	NoSpaceForProperty,685	PropertyLimitReached,686	InvalidCharacterInPropertyKey,687	PropertyKeyIsTooLong,688	EmptyPropertyKey,689}690691#[derive(Clone, Copy)]692pub enum PropertyScope {693	None,694	Rmrk,695}696697impl PropertyScope {698	pub fn apply(self, key: PropertyKey) -> Result<PropertyKey, PropertiesError> {699		let scope_str: &[u8] = match self {700			Self::None => return Ok(key),701			Self::Rmrk => b"rmrk",702		};703704		[scope_str, b":", key.as_slice()]705			.concat()706			.try_into()707			.map_err(|_| PropertiesError::PropertyKeyIsTooLong)708	}709}710711pub trait TrySetProperty: Sized {712	type Value;713714	fn try_scoped_set(715		&mut self,716		scope: PropertyScope,717		key: PropertyKey,718		value: Self::Value,719	) -> Result<(), PropertiesError>;720721	fn try_scoped_set_from_iter<I, KV>(722		&mut self,723		scope: PropertyScope,724		iter: I,725	) -> Result<(), PropertiesError>726	where727		I: Iterator<Item = KV>,728		KV: Into<(PropertyKey, Self::Value)>,729	{730		for kv in iter {731			let (key, value) = kv.into();732			self.try_scoped_set(scope, key, value)?;733		}734735		Ok(())736	}737738	fn try_set(&mut self, key: PropertyKey, value: Self::Value) -> Result<(), PropertiesError> {739		self.try_scoped_set(PropertyScope::None, key, value)740	}741742	fn try_set_from_iter<I, KV>(&mut self, iter: I) -> Result<(), PropertiesError>743	where744		I: Iterator<Item = KV>,745		KV: Into<(PropertyKey, Self::Value)>,746	{747		self.try_scoped_set_from_iter(PropertyScope::None, iter)748	}749}750751#[derive(Encode, Decode, TypeInfo, Derivative, Clone, PartialEq, MaxEncodedLen)]752#[derivative(Default(bound = ""))]753pub struct PropertiesMap<Value>(754	BoundedBTreeMap<PropertyKey, Value, ConstU32<MAX_PROPERTIES_PER_ITEM>>,755);756757impl<Value> PropertiesMap<Value> {758	pub fn new() -> Self {759		Self(BoundedBTreeMap::new())760	}761762	pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<Value>, PropertiesError> {763		Self::check_property_key(key)?;764765		Ok(self.0.remove(key))766	}767768	pub fn get(&self, key: &PropertyKey) -> Option<&Value> {769		self.0.get(key)770	}771772	pub fn contains_key(&self, key: &PropertyKey) -> bool {773		self.0.contains_key(key)774	}775776	fn check_property_key(key: &PropertyKey) -> Result<(), PropertiesError> {777		if key.is_empty() {778			return Err(PropertiesError::EmptyPropertyKey);779		}780781		for byte in key.as_slice().iter() {782			let byte = *byte;783784			if !byte.is_ascii_alphanumeric() && byte != b'_' && byte != b'-' {785				return Err(PropertiesError::InvalidCharacterInPropertyKey);786			}787		}788789		Ok(())790	}791}792793impl<Value> IntoIterator for PropertiesMap<Value> {794	type Item = (PropertyKey, Value);795	type IntoIter = <796		BoundedBTreeMap<797			PropertyKey,798			Value,799			ConstU32<MAX_PROPERTIES_PER_ITEM>800		> as IntoIterator801	>::IntoIter;802803	fn into_iter(self) -> Self::IntoIter {804		self.0.into_iter()805	}806}807808impl<Value> TrySetProperty for PropertiesMap<Value> {809	type Value = Value;810811	fn try_scoped_set(812		&mut self,813		scope: PropertyScope,814		key: PropertyKey,815		value: Self::Value,816	) -> Result<(), PropertiesError> {817		Self::check_property_key(&key)?;818819		let key = scope.apply(key)?;820		self.0821			.try_insert(key, value)822			.map_err(|_| PropertiesError::PropertyLimitReached)?;823824		Ok(())825	}826}827828pub type PropertiesPermissionMap = PropertiesMap<PropertyPermission>;829830#[derive(Encode, Decode, TypeInfo, Clone, PartialEq, MaxEncodedLen)]831pub struct Properties {832	map: PropertiesMap<PropertyValue>,833	consumed_space: u32,834	space_limit: u32,835}836837impl Properties {838	pub fn new(space_limit: u32) -> Self {839		Self {840			map: PropertiesMap::new(),841			consumed_space: 0,842			space_limit,843		}844	}845846	pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<PropertyValue>, PropertiesError> {847		let value = self.map.remove(key)?;848849		if let Some(ref value) = value {850			let value_len = value.len() as u32;851			self.consumed_space -= value_len;852		}853854		Ok(value)855	}856857	pub fn get(&self, key: &PropertyKey) -> Option<&PropertyValue> {858		self.map.get(key)859	}860}861862impl IntoIterator for Properties {863	type Item = (PropertyKey, PropertyValue);864	type IntoIter = <PropertiesMap<PropertyValue> as IntoIterator>::IntoIter;865866	fn into_iter(self) -> Self::IntoIter {867		self.map.into_iter()868	}869}870871impl TrySetProperty for Properties {872	type Value = PropertyValue;873874	fn try_scoped_set(875		&mut self,876		scope: PropertyScope,877		key: PropertyKey,878		value: Self::Value,879	) -> Result<(), PropertiesError> {880		let value_len = value.len();881882		if self.consumed_space as usize + value_len > self.space_limit as usize883			&& !cfg!(feature = "runtime-benchmarks")884		{885			return Err(PropertiesError::NoSpaceForProperty);886		}887888		self.map.try_scoped_set(scope, key, value)?;889890		self.consumed_space += value_len as u32;891892		Ok(())893	}894}895896pub struct CollectionProperties;897898impl Get<Properties> for CollectionProperties {899	fn get() -> Properties {900		Properties::new(MAX_COLLECTION_PROPERTIES_SIZE)901	}902}903904pub struct TokenProperties;905906impl Get<Properties> for TokenProperties {907	fn get() -> Properties {908		Properties::new(MAX_TOKEN_PROPERTIES_SIZE)909	}910}911912// RMRK913// todo document?914parameter_types! {915	#[derive(PartialEq, TypeInfo)]916	pub const RmrkStringLimit: u32 = 128;917	#[derive(PartialEq)]918	pub const RmrkCollectionSymbolLimit: u32 = 100;919	#[derive(PartialEq)]920	pub const RmrkResourceSymbolLimit: u32 = 10;921	#[derive(PartialEq)]922	pub const RmrkKeyLimit: u32 = 32;923	#[derive(PartialEq)]924	pub const RmrkValueLimit: u32 = 256;925	#[derive(PartialEq)]926	pub const RmrkMaxCollectionsEquippablePerPart: u32 = 100;927	#[derive(PartialEq)]928	pub const RmrkPartsLimit: u32 = 3;929}930931impl From<RmrkCollectionId> for CollectionId {932	fn from(id: RmrkCollectionId) -> Self {933		Self(id)934	}935}936937impl From<RmrkNftId> for TokenId {938	fn from(id: RmrkNftId) -> Self {939		Self(id)940	}941}942943pub type RmrkCollectionInfo<AccountId> =944	CollectionInfo<RmrkString, RmrkCollectionSymbol, AccountId>;945pub type RmrkInstanceInfo<AccountId> = NftInfo<AccountId, Permill, RmrkString>;946pub type RmrkResourceInfo = ResourceInfo<RmrkString, RmrkBoundedParts>;947pub type RmrkPropertyInfo = PropertyInfo<RmrkKeyString, RmrkValueString>;948pub type RmrkBaseInfo<AccountId> = BaseInfo<AccountId, RmrkString>;949pub type RmrkPartType =950	PartType<RmrkString, BoundedVec<RmrkCollectionId, RmrkMaxCollectionsEquippablePerPart>>;951pub type RmrkThemeProperty = ThemeProperty<RmrkString>;952pub type RmrkTheme = Theme<RmrkString, Vec<RmrkThemeProperty>>;953pub type RmrkResourceTypes = ResourceTypes<RmrkString, RmrkBoundedParts>;954955pub type RmrkBasicResource = BasicResource<RmrkString>;956pub type RmrkComposableResource = ComposableResource<RmrkString, RmrkBoundedParts>;957pub type RmrkSlotResource = SlotResource<RmrkString>;958959pub type RmrkString = BoundedVec<u8, RmrkStringLimit>;960pub type RmrkCollectionSymbol = BoundedVec<u8, RmrkCollectionSymbolLimit>;961pub type RmrkKeyString = BoundedVec<u8, RmrkKeyLimit>;962pub type RmrkValueString = BoundedVec<u8, RmrkValueLimit>;963pub type RmrkBoundedResource = BoundedVec<u8, RmrkResourceSymbolLimit>;964pub type RmrkBoundedParts = BoundedVec<RmrkPartId, RmrkPartsLimit>; // todo make sure it is needed965966pub type RmrkRpcString = Vec<u8>;967pub type RmrkThemeName = RmrkRpcString;968pub type RmrkPropertyKey = RmrkRpcString;
after · primitives/data-structs/src/lib.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617#![cfg_attr(not(feature = "std"), no_std)]1819use core::{20	convert::{TryFrom, TryInto},21	fmt,22};23use frame_support::{24	storage::{bounded_btree_map::BoundedBTreeMap, bounded_btree_set::BoundedBTreeSet},25	traits::Get,26	parameter_types,27};2829#[cfg(feature = "serde")]30use serde::{Serialize, Deserialize};3132use sp_core::U256;33use sp_runtime::{ArithmeticError, sp_std::prelude::Vec, Permill};34use codec::{Decode, Encode, EncodeLike, MaxEncodedLen};35use frame_support::{BoundedVec, traits::ConstU32};36use derivative::Derivative;37use scale_info::TypeInfo;3839pub mod rmrk;4041// RMRK42use rmrk::{43	CollectionInfo, NftInfo, ResourceInfo, PropertyInfo, BaseInfo, PartType, Theme, ThemeProperty,44	ResourceTypes, BasicResource, ComposableResource, SlotResource,45};46pub use rmrk::{47	primitives::{48		CollectionId as RmrkCollectionId, NftId as RmrkNftId, BaseId as RmrkBaseId,49		PartId as RmrkPartId, ResourceId as RmrkResourceId,50	},51	NftChild as RmrkNftChild, AccountIdOrCollectionNftTuple as RmrkAccountIdOrCollectionNftTuple,52	FixedPart as RmrkFixedPart, SlotPart as RmrkSlotPart, EquippableList as RmrkEquippableList,53};5455mod bounded;56pub mod budget;57pub mod mapping;58mod migration;5960pub const MAX_DECIMAL_POINTS: DecimalPoints = 30;61pub const MAX_REFUNGIBLE_PIECES: u128 = 1_000_000_000_000_000_000_000;62pub const MAX_SPONSOR_TIMEOUT: u32 = 10_368_000;6364pub const MAX_TOKEN_OWNERSHIP: u32 = if cfg!(not(feature = "limit-testing")) {65	100_00066} else {67	1068};69pub const COLLECTION_NUMBER_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {70	100_00071} else {72	1073};74pub const CUSTOM_DATA_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {75	204876} else {77	1078};79pub const COLLECTION_ADMINS_LIMIT: u32 = 5;80pub const COLLECTION_TOKEN_LIMIT: u32 = u32::MAX;81pub const ACCOUNT_TOKEN_OWNERSHIP_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {82	1_000_00083} else {84	1085};8687// Timeouts for item types in passed blocks88pub const NFT_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;89pub const FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;90pub const REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;9192pub const SPONSOR_APPROVE_TIMEOUT: u32 = 5;9394// Schema limits95pub const OFFCHAIN_SCHEMA_LIMIT: u32 = 8192;96pub const VARIABLE_ON_CHAIN_SCHEMA_LIMIT: u32 = 8192;97pub const CONST_ON_CHAIN_SCHEMA_LIMIT: u32 = 32768;9899pub const COLLECTION_FIELD_LIMIT: u32 = CONST_ON_CHAIN_SCHEMA_LIMIT;100101pub const MAX_COLLECTION_NAME_LENGTH: u32 = 64;102pub const MAX_COLLECTION_DESCRIPTION_LENGTH: u32 = 256;103pub const MAX_TOKEN_PREFIX_LENGTH: u32 = 16;104105pub const MAX_PROPERTY_KEY_LENGTH: u32 = 256;106pub const MAX_PROPERTY_VALUE_LENGTH: u32 = 32768;107pub const MAX_PROPERTIES_PER_ITEM: u32 = 64;108109pub const MAX_COLLECTION_PROPERTIES_SIZE: u32 = 40960;110pub const MAX_TOKEN_PROPERTIES_SIZE: u32 = 32768;111112// RMRK constants113pub const RMRK_STRING_LIMIT: u32 = 128;114pub const RMRK_COLLECTION_SYMBOL_LIMIT: u32 = 100;115pub const RMRK_RESOURCE_SYMBOL_LIMIT: u32 = 10;116pub const RMRK_KEY_LIMIT: u32 = 32;117pub const RMRK_VALUE_LIMIT: u32 = 256;118119/// How much items can be created per single120/// create_many call121pub const MAX_ITEMS_PER_BATCH: u32 = 200;122123pub type CustomDataLimit = ConstU32<CUSTOM_DATA_LIMIT>;124125#[derive(126	Encode,127	Decode,128	PartialEq,129	Eq,130	PartialOrd,131	Ord,132	Clone,133	Copy,134	Debug,135	Default,136	TypeInfo,137	MaxEncodedLen,138)]139#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]140pub struct CollectionId(pub u32);141impl EncodeLike<u32> for CollectionId {}142impl EncodeLike<CollectionId> for u32 {}143144#[derive(145	Encode,146	Decode,147	PartialEq,148	Eq,149	PartialOrd,150	Ord,151	Clone,152	Copy,153	Debug,154	Default,155	TypeInfo,156	MaxEncodedLen,157)]158#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]159pub struct TokenId(pub u32);160impl EncodeLike<u32> for TokenId {}161impl EncodeLike<TokenId> for u32 {}162163impl TokenId {164	pub fn try_next(self) -> Result<TokenId, ArithmeticError> {165		self.0166			.checked_add(1)167			.ok_or(ArithmeticError::Overflow)168			.map(Self)169	}170}171172impl From<TokenId> for U256 {173	fn from(t: TokenId) -> Self {174		t.0.into()175	}176}177178impl TryFrom<U256> for TokenId {179	type Error = &'static str;180181	fn try_from(value: U256) -> Result<Self, Self::Error> {182		Ok(TokenId(value.try_into().map_err(|_| "too large token id")?))183	}184}185186#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]187#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]188pub struct TokenData<CrossAccountId> {189	pub properties: Vec<Property>,190	pub owner: Option<CrossAccountId>,191}192193pub struct OverflowError;194impl From<OverflowError> for &'static str {195	fn from(_: OverflowError) -> Self {196		"overflow occured"197	}198}199200pub type DecimalPoints = u8;201202#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]203#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]204pub enum CollectionMode {205	NFT,206	// decimal points207	Fungible(DecimalPoints),208	ReFungible,209}210211impl CollectionMode {212	pub fn id(&self) -> u8 {213		match self {214			CollectionMode::NFT => 1,215			CollectionMode::Fungible(_) => 2,216			CollectionMode::ReFungible => 3,217		}218	}219}220221pub trait SponsoringResolve<AccountId, Call> {222	fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>;223}224225#[derive(Encode, Decode, Eq, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]226#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]227pub enum AccessMode {228	Normal,229	AllowList,230}231impl Default for AccessMode {232	fn default() -> Self {233		Self::Normal234	}235}236237#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]238#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]239pub enum SchemaVersion {240	ImageURL,241	Unique,242}243impl Default for SchemaVersion {244	fn default() -> Self {245		Self::ImageURL246	}247}248249#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]250#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]251pub struct Ownership<AccountId> {252	pub owner: AccountId,253	pub fraction: u128,254}255256#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]257#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]258pub enum SponsorshipState<AccountId> {259	/// The fees are applied to the transaction sender260	Disabled,261	Unconfirmed(AccountId),262	/// Transactions are sponsored by specified account263	Confirmed(AccountId),264}265266impl<AccountId> SponsorshipState<AccountId> {267	pub fn sponsor(&self) -> Option<&AccountId> {268		match self {269			Self::Confirmed(sponsor) => Some(sponsor),270			_ => None,271		}272	}273274	pub fn pending_sponsor(&self) -> Option<&AccountId> {275		match self {276			Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),277			_ => None,278		}279	}280281	pub fn confirmed(&self) -> bool {282		matches!(self, Self::Confirmed(_))283	}284}285286impl<T> Default for SponsorshipState<T> {287	fn default() -> Self {288		Self::Disabled289	}290}291292/// Used in storage293#[struct_versioning::versioned(version = 2, upper)]294#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen)]295pub struct Collection<AccountId> {296	pub owner: AccountId,297	pub mode: CollectionMode,298	#[version(..2)]299	pub access: AccessMode,300	pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,301	pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,302	pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,303304	#[version(..2)]305	pub mint_mode: bool,306307	#[version(..2)]308	pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,309310	#[version(..2)]311	pub schema_version: SchemaVersion,312	pub sponsorship: SponsorshipState<AccountId>,313314	pub limits: CollectionLimits,315316	#[version(2.., upper(Default::default()))]317	pub permissions: CollectionPermissions,318319	#[version(2.., upper(false))]320	pub read_only: bool,321322	#[version(..2)]323	pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,324325	#[version(..2)]326	pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,327328	#[version(..2)]329	pub meta_update_permission: MetaUpdatePermission,330}331332/// Used in RPC calls333#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]334#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]335pub struct RpcCollection<AccountId> {336	pub owner: AccountId,337	pub mode: CollectionMode,338	pub name: Vec<u16>,339	pub description: Vec<u16>,340	pub token_prefix: Vec<u8>,341	pub sponsorship: SponsorshipState<AccountId>,342	pub limits: CollectionLimits,343	pub permissions: CollectionPermissions,344	pub token_property_permissions: Vec<PropertyKeyPermission>,345	pub properties: Vec<Property>,346	pub read_only: bool,347}348349#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Derivative, MaxEncodedLen)]350#[derivative(Debug, Default(bound = ""))]351pub struct CreateCollectionData<AccountId> {352	#[derivative(Default(value = "CollectionMode::NFT"))]353	pub mode: CollectionMode,354	pub access: Option<AccessMode>,355	pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,356	pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,357	pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,358	pub pending_sponsor: Option<AccountId>,359	pub limits: Option<CollectionLimits>,360	pub permissions: Option<CollectionPermissions>,361	pub token_property_permissions: CollectionPropertiesPermissionsVec,362	pub properties: CollectionPropertiesVec,363}364365pub type CollectionPropertiesPermissionsVec =366	BoundedVec<PropertyKeyPermission, ConstU32<MAX_PROPERTIES_PER_ITEM>>;367368pub type CollectionPropertiesVec = BoundedVec<Property, ConstU32<MAX_PROPERTIES_PER_ITEM>>;369370/// All fields are wrapped in `Option`s, where None means chain default371// When adding/removing fields from this struct - don't forget to also update clamp_limits372#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]373#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]374pub struct CollectionLimits {375	pub account_token_ownership_limit: Option<u32>,376	pub sponsored_data_size: Option<u32>,377378	/// FIXME should we delete this or repurpose it?379	/// None - setVariableMetadata is not sponsored380	/// Some(v) - setVariableMetadata is sponsored381	///           if there is v block between txs382	pub sponsored_data_rate_limit: Option<SponsoringRateLimit>,383	pub token_limit: Option<u32>,384385	// Timeouts for item types in passed blocks386	pub sponsor_transfer_timeout: Option<u32>,387	pub sponsor_approve_timeout: Option<u32>,388	pub owner_can_transfer: Option<bool>,389	pub owner_can_destroy: Option<bool>,390	pub transfers_enabled: Option<bool>,391}392393impl CollectionLimits {394	pub fn account_token_ownership_limit(&self) -> u32 {395		self.account_token_ownership_limit396			.unwrap_or(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)397			.min(MAX_TOKEN_OWNERSHIP)398	}399	pub fn sponsored_data_size(&self) -> u32 {400		self.sponsored_data_size401			.unwrap_or(CUSTOM_DATA_LIMIT)402			.min(CUSTOM_DATA_LIMIT)403	}404	pub fn token_limit(&self) -> u32 {405		self.token_limit406			.unwrap_or(COLLECTION_TOKEN_LIMIT)407			.min(COLLECTION_TOKEN_LIMIT)408	}409	pub fn sponsor_transfer_timeout(&self, default: u32) -> u32 {410		self.sponsor_transfer_timeout411			.unwrap_or(default)412			.min(MAX_SPONSOR_TIMEOUT)413	}414	pub fn sponsor_approve_timeout(&self) -> u32 {415		self.sponsor_approve_timeout416			.unwrap_or(SPONSOR_APPROVE_TIMEOUT)417			.min(MAX_SPONSOR_TIMEOUT)418	}419	pub fn owner_can_transfer(&self) -> bool {420		self.owner_can_transfer.unwrap_or(true)421	}422	pub fn owner_can_destroy(&self) -> bool {423		self.owner_can_destroy.unwrap_or(true)424	}425	pub fn transfers_enabled(&self) -> bool {426		self.transfers_enabled.unwrap_or(true)427	}428	pub fn sponsored_data_rate_limit(&self) -> Option<u32> {429		match self430			.sponsored_data_rate_limit431			.unwrap_or(SponsoringRateLimit::SponsoringDisabled)432		{433			SponsoringRateLimit::SponsoringDisabled => None,434			SponsoringRateLimit::Blocks(v) => Some(v.min(MAX_SPONSOR_TIMEOUT)),435		}436	}437}438439// When adding/removing fields from this struct - don't forget to also update clamp_limits440#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]441#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]442pub struct CollectionPermissions {443	pub access: Option<AccessMode>,444	pub mint_mode: Option<bool>,445	pub nesting: Option<NestingRule>,446}447448impl CollectionPermissions {449	pub fn access(&self) -> AccessMode {450		self.access.unwrap_or(AccessMode::Normal)451	}452	pub fn mint_mode(&self) -> bool {453		self.mint_mode.unwrap_or(false)454	}455	pub fn nesting(&self) -> &NestingRule {456		static DEFAULT: NestingRule = NestingRule::Disabled;457		self.nesting.as_ref().unwrap_or(&DEFAULT)458	}459}460461pub type OwnerRestrictedSet = BoundedBTreeSet<CollectionId, ConstU32<16>>;462463#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative)]464#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]465#[derivative(Debug)]466pub enum NestingRule {467	/// No one can nest tokens468	Disabled,469	/// Owner can nest any tokens470	Owner,471	/// Owner can nest tokens from specified collections472	OwnerRestricted(473		#[cfg_attr(feature = "serde1", serde(with = "bounded::set_serde"))]474		#[derivative(Debug(format_with = "bounded::set_debug"))]475		OwnerRestrictedSet,476	),477	/// Used for tests478	Permissive,479}480481#[derive(Encode, Decode, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]482#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]483pub enum SponsoringRateLimit {484	SponsoringDisabled,485	Blocks(u32),486}487488#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]489#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]490#[derivative(Debug)]491pub struct CreateNftData {492	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]493	#[derivative(Debug(format_with = "bounded::vec_debug"))]494	pub properties: CollectionPropertiesVec,495}496497#[derive(Encode, Decode, MaxEncodedLen, Default, Debug, Clone, PartialEq, TypeInfo)]498#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]499pub struct CreateFungibleData {500	pub value: u128,501}502503#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]504#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]505#[derivative(Debug)]506pub struct CreateReFungibleData {507	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]508	#[derivative(Debug(format_with = "bounded::vec_debug"))]509	pub const_data: BoundedVec<u8, CustomDataLimit>,510	pub pieces: u128,511}512513#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]514#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]515pub enum MetaUpdatePermission {516	ItemOwner,517	Admin,518	None,519}520521#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]522#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]523pub enum CreateItemData {524	NFT(CreateNftData),525	Fungible(CreateFungibleData),526	ReFungible(CreateReFungibleData),527}528529#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]530#[derivative(Debug)]531pub struct CreateNftExData<CrossAccountId> {532	#[derivative(Debug(format_with = "bounded::vec_debug"))]533	pub properties: CollectionPropertiesVec,534	pub owner: CrossAccountId,535}536537#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]538#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]539pub struct CreateRefungibleExData<CrossAccountId> {540	#[derivative(Debug(format_with = "bounded::vec_debug"))]541	pub const_data: BoundedVec<u8, CustomDataLimit>,542	#[derivative(Debug(format_with = "bounded::map_debug"))]543	pub users: BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,544}545546#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]547#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]548pub enum CreateItemExData<CrossAccountId> {549	NFT(550		#[derivative(Debug(format_with = "bounded::vec_debug"))]551		BoundedVec<CreateNftExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,552	),553	Fungible(554		#[derivative(Debug(format_with = "bounded::map_debug"))]555		BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,556	),557	/// Many tokens, each may have only one owner558	RefungibleMultipleItems(559		#[derivative(Debug(format_with = "bounded::vec_debug"))]560		BoundedVec<CreateRefungibleExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,561	),562	/// Single token, which may have many owners563	RefungibleMultipleOwners(CreateRefungibleExData<CrossAccountId>),564}565566impl CreateItemData {567	pub fn data_size(&self) -> usize {568		match self {569			CreateItemData::ReFungible(data) => data.const_data.len(),570			_ => 0,571		}572	}573}574575impl From<CreateNftData> for CreateItemData {576	fn from(item: CreateNftData) -> Self {577		CreateItemData::NFT(item)578	}579}580581impl From<CreateReFungibleData> for CreateItemData {582	fn from(item: CreateReFungibleData) -> Self {583		CreateItemData::ReFungible(item)584	}585}586587impl From<CreateFungibleData> for CreateItemData {588	fn from(item: CreateFungibleData) -> Self {589		CreateItemData::Fungible(item)590	}591}592593#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]594#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]595// todo possibly rename to be used generally as an address pair596pub struct TokenChild {597	pub token: TokenId,598	pub collection: CollectionId,599}600601#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]602#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]603pub struct CollectionStats {604	pub created: u32,605	pub destroyed: u32,606	pub alive: u32,607}608609#[derive(Encode, Decode, Clone, Debug)]610#[cfg_attr(feature = "std", derive(PartialEq))]611pub struct PhantomType<T>(core::marker::PhantomData<T>);612613impl<T: TypeInfo + 'static> TypeInfo for PhantomType<T> {614	type Identity = PhantomType<T>;615616	fn type_info() -> scale_info::Type {617		use scale_info::{618			Type, Path,619			build::{FieldsBuilder, UnnamedFields},620			type_params,621		};622		Type::builder()623			.path(Path::new("up_data_structs", "PhantomType"))624			.type_params(type_params!(T))625			.composite(<FieldsBuilder<UnnamedFields>>::default().field(|b| b.ty::<[T; 0]>()))626	}627}628impl<T> MaxEncodedLen for PhantomType<T> {629	fn max_encoded_len() -> usize {630		0631	}632}633634pub type PropertyKey = BoundedVec<u8, ConstU32<MAX_PROPERTY_KEY_LENGTH>>;635pub type PropertyValue = BoundedVec<u8, ConstU32<MAX_PROPERTY_VALUE_LENGTH>>;636637#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]638#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]639pub struct PropertyPermission {640	pub mutable: bool,641	pub collection_admin: bool,642	pub token_owner: bool,643}644645impl PropertyPermission {646	pub fn none() -> Self {647		Self {648			mutable: true,649			collection_admin: false,650			token_owner: false,651		}652	}653}654655#[derive(Encode, Decode, Debug, TypeInfo, Clone, PartialEq, MaxEncodedLen)]656#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]657pub struct Property {658	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]659	pub key: PropertyKey,660661	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]662	pub value: PropertyValue,663}664665impl Into<(PropertyKey, PropertyValue)> for Property {666	fn into(self) -> (PropertyKey, PropertyValue) {667		(self.key, self.value)668	}669}670671#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]672#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]673pub struct PropertyKeyPermission {674	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]675	pub key: PropertyKey,676677	pub permission: PropertyPermission,678}679680impl Into<(PropertyKey, PropertyPermission)> for PropertyKeyPermission {681	fn into(self) -> (PropertyKey, PropertyPermission) {682		(self.key, self.permission)683	}684}685686#[derive(Debug)]687pub enum PropertiesError {688	NoSpaceForProperty,689	PropertyLimitReached,690	InvalidCharacterInPropertyKey,691	PropertyKeyIsTooLong,692	EmptyPropertyKey,693}694695#[derive(Clone, Copy)]696pub enum PropertyScope {697	None,698	Rmrk,699}700701impl PropertyScope {702	pub fn apply(self, key: PropertyKey) -> Result<PropertyKey, PropertiesError> {703		let scope_str: &[u8] = match self {704			Self::None => return Ok(key),705			Self::Rmrk => b"rmrk",706		};707708		[scope_str, b":", key.as_slice()]709			.concat()710			.try_into()711			.map_err(|_| PropertiesError::PropertyKeyIsTooLong)712	}713}714715pub trait TrySetProperty: Sized {716	type Value;717718	fn try_scoped_set(719		&mut self,720		scope: PropertyScope,721		key: PropertyKey,722		value: Self::Value,723	) -> Result<(), PropertiesError>;724725	fn try_scoped_set_from_iter<I, KV>(726		&mut self,727		scope: PropertyScope,728		iter: I,729	) -> Result<(), PropertiesError>730	where731		I: Iterator<Item = KV>,732		KV: Into<(PropertyKey, Self::Value)>,733	{734		for kv in iter {735			let (key, value) = kv.into();736			self.try_scoped_set(scope, key, value)?;737		}738739		Ok(())740	}741742	fn try_set(&mut self, key: PropertyKey, value: Self::Value) -> Result<(), PropertiesError> {743		self.try_scoped_set(PropertyScope::None, key, value)744	}745746	fn try_set_from_iter<I, KV>(&mut self, iter: I) -> Result<(), PropertiesError>747	where748		I: Iterator<Item = KV>,749		KV: Into<(PropertyKey, Self::Value)>,750	{751		self.try_scoped_set_from_iter(PropertyScope::None, iter)752	}753}754755#[derive(Encode, Decode, TypeInfo, Derivative, Clone, PartialEq, MaxEncodedLen)]756#[derivative(Default(bound = ""))]757pub struct PropertiesMap<Value>(758	BoundedBTreeMap<PropertyKey, Value, ConstU32<MAX_PROPERTIES_PER_ITEM>>,759);760761impl<Value> PropertiesMap<Value> {762	pub fn new() -> Self {763		Self(BoundedBTreeMap::new())764	}765766	pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<Value>, PropertiesError> {767		Self::check_property_key(key)?;768769		Ok(self.0.remove(key))770	}771772	pub fn get(&self, key: &PropertyKey) -> Option<&Value> {773		self.0.get(key)774	}775776	pub fn contains_key(&self, key: &PropertyKey) -> bool {777		self.0.contains_key(key)778	}779780	fn check_property_key(key: &PropertyKey) -> Result<(), PropertiesError> {781		if key.is_empty() {782			return Err(PropertiesError::EmptyPropertyKey);783		}784785		for byte in key.as_slice().iter() {786			let byte = *byte;787788			if !byte.is_ascii_alphanumeric() && byte != b'_' && byte != b'-' {789				return Err(PropertiesError::InvalidCharacterInPropertyKey);790			}791		}792793		Ok(())794	}795}796797impl<Value> IntoIterator for PropertiesMap<Value> {798	type Item = (PropertyKey, Value);799	type IntoIter = <800		BoundedBTreeMap<801			PropertyKey,802			Value,803			ConstU32<MAX_PROPERTIES_PER_ITEM>804		> as IntoIterator805	>::IntoIter;806807	fn into_iter(self) -> Self::IntoIter {808		self.0.into_iter()809	}810}811812impl<Value> TrySetProperty for PropertiesMap<Value> {813	type Value = Value;814815	fn try_scoped_set(816		&mut self,817		scope: PropertyScope,818		key: PropertyKey,819		value: Self::Value,820	) -> Result<(), PropertiesError> {821		Self::check_property_key(&key)?;822823		let key = scope.apply(key)?;824		self.0825			.try_insert(key, value)826			.map_err(|_| PropertiesError::PropertyLimitReached)?;827828		Ok(())829	}830}831832pub type PropertiesPermissionMap = PropertiesMap<PropertyPermission>;833834#[derive(Encode, Decode, TypeInfo, Clone, PartialEq, MaxEncodedLen)]835pub struct Properties {836	map: PropertiesMap<PropertyValue>,837	consumed_space: u32,838	space_limit: u32,839}840841impl Properties {842	pub fn new(space_limit: u32) -> Self {843		Self {844			map: PropertiesMap::new(),845			consumed_space: 0,846			space_limit,847		}848	}849850	pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<PropertyValue>, PropertiesError> {851		let value = self.map.remove(key)?;852853		if let Some(ref value) = value {854			let value_len = value.len() as u32;855			self.consumed_space -= value_len;856		}857858		Ok(value)859	}860861	pub fn get(&self, key: &PropertyKey) -> Option<&PropertyValue> {862		self.map.get(key)863	}864}865866impl IntoIterator for Properties {867	type Item = (PropertyKey, PropertyValue);868	type IntoIter = <PropertiesMap<PropertyValue> as IntoIterator>::IntoIter;869870	fn into_iter(self) -> Self::IntoIter {871		self.map.into_iter()872	}873}874875impl TrySetProperty for Properties {876	type Value = PropertyValue;877878	fn try_scoped_set(879		&mut self,880		scope: PropertyScope,881		key: PropertyKey,882		value: Self::Value,883	) -> Result<(), PropertiesError> {884		let value_len = value.len();885886		if self.consumed_space as usize + value_len > self.space_limit as usize887			&& !cfg!(feature = "runtime-benchmarks")888		{889			return Err(PropertiesError::NoSpaceForProperty);890		}891892		self.map.try_scoped_set(scope, key, value)?;893894		self.consumed_space += value_len as u32;895896		Ok(())897	}898}899900pub struct CollectionProperties;901902impl Get<Properties> for CollectionProperties {903	fn get() -> Properties {904		Properties::new(MAX_COLLECTION_PROPERTIES_SIZE)905	}906}907908pub struct TokenProperties;909910impl Get<Properties> for TokenProperties {911	fn get() -> Properties {912		Properties::new(MAX_TOKEN_PROPERTIES_SIZE)913	}914}915916// RMRK917// todo document?918parameter_types! {919	#[derive(PartialEq, TypeInfo)]920	pub const RmrkStringLimit: u32 = 128;921	#[derive(PartialEq)]922	pub const RmrkCollectionSymbolLimit: u32 = 100;923	#[derive(PartialEq)]924	pub const RmrkResourceSymbolLimit: u32 = 10;925	#[derive(PartialEq)]926	pub const RmrkKeyLimit: u32 = 32;927	#[derive(PartialEq)]928	pub const RmrkValueLimit: u32 = 256;929	#[derive(PartialEq)]930	pub const RmrkMaxCollectionsEquippablePerPart: u32 = 100;931	#[derive(PartialEq)]932	pub const RmrkPartsLimit: u32 = 3;933}934935impl From<RmrkCollectionId> for CollectionId {936	fn from(id: RmrkCollectionId) -> Self {937		Self(id)938	}939}940941impl From<RmrkNftId> for TokenId {942	fn from(id: RmrkNftId) -> Self {943		Self(id)944	}945}946947pub type RmrkCollectionInfo<AccountId> =948	CollectionInfo<RmrkString, RmrkCollectionSymbol, AccountId>;949pub type RmrkInstanceInfo<AccountId> = NftInfo<AccountId, Permill, RmrkString>;950pub type RmrkResourceInfo = ResourceInfo<RmrkString, RmrkBoundedParts>;951pub type RmrkPropertyInfo = PropertyInfo<RmrkKeyString, RmrkValueString>;952pub type RmrkBaseInfo<AccountId> = BaseInfo<AccountId, RmrkString>;953pub type RmrkPartType =954	PartType<RmrkString, BoundedVec<RmrkCollectionId, RmrkMaxCollectionsEquippablePerPart>>;955pub type RmrkThemeProperty = ThemeProperty<RmrkString>;956pub type RmrkTheme = Theme<RmrkString, Vec<RmrkThemeProperty>>;957pub type RmrkResourceTypes = ResourceTypes<RmrkString, RmrkBoundedParts>;958959pub type RmrkBasicResource = BasicResource<RmrkString>;960pub type RmrkComposableResource = ComposableResource<RmrkString, RmrkBoundedParts>;961pub type RmrkSlotResource = SlotResource<RmrkString>;962963pub type RmrkString = BoundedVec<u8, RmrkStringLimit>;964pub type RmrkCollectionSymbol = BoundedVec<u8, RmrkCollectionSymbolLimit>;965pub type RmrkKeyString = BoundedVec<u8, RmrkKeyLimit>;966pub type RmrkValueString = BoundedVec<u8, RmrkValueLimit>;967pub type RmrkBoundedResource = BoundedVec<u8, RmrkResourceSymbolLimit>;968pub type RmrkBoundedParts = BoundedVec<RmrkPartId, RmrkPartsLimit>; // todo make sure it is needed969970pub type RmrkRpcString = Vec<u8>;971pub type RmrkThemeName = RmrkRpcString;972pub type RmrkPropertyKey = RmrkRpcString;
modifiedtests/src/createCollection.test.tsdiffbeforeafterboth
--- a/tests/src/createCollection.test.ts
+++ b/tests/src/createCollection.test.ts
@@ -87,6 +87,20 @@
       expect(collection.limits.accountTokenOwnershipLimit.unwrap().toNumber()).to.equal(3);
     });
   });
+
+  it('Create new collection is not read only', async () => {
+    await usingApi(async api => {
+      const alice = privateKey('//Alice');
+      const tx = api.tx.unique.createCollectionEx({
+        readOnly: true
+      });
+      const events = await submitTransactionAsync(alice, tx);
+      const result = getCreateCollectionResult(events);
+
+      const collection = (await getDetailedCollectionInfo(api, result.collectionId))!;
+      expect(collection.readOnly.toHuman()).to.be.false;
+    });
+  });
 });
 
 describe('(!negative test!) integration test: ext. createCollection():', () => {