git.delta.rocks / unique-network / refs/commits / 73817f448a72

difftreelog

test upgrade benchmarks for new substrate

Yaroslav Bolyukin2022-02-26parent: #c9e84df.patch.diff
in: master

12 files changed

modified.maintain/frame-weight-template.hbsdiffbeforeafterboth
--- a/.maintain/frame-weight-template.hbs
+++ b/.maintain/frame-weight-template.hbs
@@ -7,7 +7,7 @@
 //! EXECUTION: {{cmd.execution}}, WASM-EXECUTION: {{cmd.wasm_execution}}, CHAIN: {{cmd.chain}}, DB CACHE: {{cmd.db_cache}}
 
 // Executed Command:
-{{#each args as |arg|~}}
+{{#each args as |arg|}}
 // {{arg}}
 {{/each}}
 
@@ -21,76 +21,80 @@
 
 /// Weight functions needed for {{pallet}}.
 pub trait WeightInfo {
-	{{~#each benchmarks as |benchmark|}}
+	{{#each benchmarks as |benchmark|}}
 	fn {{benchmark.name~}}
 	(
 		{{~#each benchmark.components as |c| ~}}
 		{{c.name}}: u32, {{/each~}}
 	) -> Weight;
-	{{~/each}}
+	{{/each}}
 }
 
 /// Weights for {{pallet}} using the Substrate node and recommended hardware.
 pub struct SubstrateWeight<T>(PhantomData<T>);
+{{#if (eq pallet "frame_system")}}
+impl<T: crate::Config> WeightInfo for SubstrateWeight<T> {
+{{else}}
 impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
-	{{~#each benchmarks as |benchmark|}}
-	{{~#each benchmark.comments as |comment|}}
+{{/if}}
+	{{#each benchmarks as |benchmark|}}
+	{{#each benchmark.comments as |comment|}}
 	// {{comment}}
-	{{~/each}}
+	{{/each}}
 	fn {{benchmark.name~}}
 	(
 		{{~#each benchmark.components as |c| ~}}
 		{{~#if (not c.is_used)}}_{{/if}}{{c.name}}: u32, {{/each~}}
 	) -> Weight {
 		({{underscore benchmark.base_weight}} as Weight)
-			{{~#each benchmark.component_weight as |cw|}}
+			{{#each benchmark.component_weight as |cw|}}
 			// Standard Error: {{underscore cw.error}}
 			.saturating_add(({{underscore cw.slope}} as Weight).saturating_mul({{cw.name}} as Weight))
-			{{~/each}}
-			{{~#if (ne benchmark.base_reads "0")}}
+			{{/each}}
+			{{#if (ne benchmark.base_reads "0")}}
 			.saturating_add(T::DbWeight::get().reads({{benchmark.base_reads}} as Weight))
-			{{~/if}}
-			{{~#each benchmark.component_reads as |cr|}}
+			{{/if}}
+			{{#each benchmark.component_reads as |cr|}}
 			.saturating_add(T::DbWeight::get().reads(({{cr.slope}} as Weight).saturating_mul({{cr.name}} as Weight)))
-			{{~/each}}
-			{{~#if (ne benchmark.base_writes "0")}}
+			{{/each}}
+			{{#if (ne benchmark.base_writes "0")}}
 			.saturating_add(T::DbWeight::get().writes({{benchmark.base_writes}} as Weight))
-			{{~/if}}
-			{{~#each benchmark.component_writes as |cw|}}
+			{{/if}}
+			{{#each benchmark.component_writes as |cw|}}
 			.saturating_add(T::DbWeight::get().writes(({{cw.slope}} as Weight).saturating_mul({{cw.name}} as Weight)))
-			{{~/each}}
+			{{/each}}
 	}
-	{{~/each}}
+	{{/each}}
 }
 
 // For backwards compatibility and tests
 impl WeightInfo for () {
-	{{~#each benchmarks as |benchmark|}}
-	{{~#each benchmark.comments as |comment|}}
+	{{#each benchmarks as |benchmark|}}
+	{{#each benchmark.comments as |comment|}}
 	// {{comment}}
-	{{~/each}}
+	{{/each}}
 	fn {{benchmark.name~}}
 	(
 		{{~#each benchmark.components as |c| ~}}
 		{{~#if (not c.is_used)}}_{{/if}}{{c.name}}: u32, {{/each~}}
 	) -> Weight {
 		({{underscore benchmark.base_weight}} as Weight)
-			{{~#each benchmark.component_weight as |cw|}}
+			{{#each benchmark.component_weight as |cw|}}
 			// Standard Error: {{underscore cw.error}}
 			.saturating_add(({{underscore cw.slope}} as Weight).saturating_mul({{cw.name}} as Weight))
-			{{~/each}}
-			{{~#if (ne benchmark.base_reads "0")}}
+			{{/each}}
+			{{#if (ne benchmark.base_reads "0")}}
 			.saturating_add(RocksDbWeight::get().reads({{benchmark.base_reads}} as Weight))
-			{{~/if}}
-			{{~#each benchmark.component_reads as |cr|}}
+			{{/if}}
+			{{#each benchmark.component_reads as |cr|}}
 			.saturating_add(RocksDbWeight::get().reads(({{cr.slope}} as Weight).saturating_mul({{cr.name}} as Weight)))
-			{{~/each}}
-			{{~#if (ne benchmark.base_writes "0")}}
+			{{/each}}
+			{{#if (ne benchmark.base_writes "0")}}
 			.saturating_add(RocksDbWeight::get().writes({{benchmark.base_writes}} as Weight))
-			{{~/if}}
-			{{~#each benchmark.component_writes as |cw|}}
+			{{/if}}
+			{{#each benchmark.component_writes as |cw|}}
 			.saturating_add(RocksDbWeight::get().writes(({{cw.slope}} as Weight).saturating_mul({{cw.name}} as Weight)))
-			{{~/each}}
+			{{/each}}
 	}
-	{{~/each}}
+	{{/each}}
 }
modifiedpallets/common/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/common/src/benchmarking.rs
+++ b/pallets/common/src/benchmarking.rs
@@ -1,64 +1,87 @@
 use sp_std::vec::Vec;
 use crate::{Config, CollectionHandle};
 use up_data_structs::{
-	CollectionMode, Collection, CollectionId, MAX_COLLECTION_NAME_LENGTH,
+	CollectionMode, CreateCollectionData, CollectionId, MAX_COLLECTION_NAME_LENGTH,
 	MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH, OFFCHAIN_SCHEMA_LIMIT,
 	VARIABLE_ON_CHAIN_SCHEMA_LIMIT, CONST_ON_CHAIN_SCHEMA_LIMIT,
 };
-use frame_support::traits::{Currency, Get};
+use frame_support::{
+	traits::{Currency, Get},
+	pallet_prelude::ConstU32,
+	BoundedVec,
+};
 use core::convert::TryInto;
 use sp_runtime::DispatchError;
 
-pub fn create_data(size: usize) -> Vec<u8> {
-	(0..size).map(|v| (v & 0xff) as u8).collect()
+pub fn create_data<const S: u32>() -> BoundedVec<u8, ConstU32<S>> {
+	create_var_data::<S>(S)
 }
-pub fn create_u16_data(size: usize) -> Vec<u16> {
-	(0..size).map(|v| (v & 0xffff) as u16).collect()
+pub fn create_u16_data<const S: u32>() -> BoundedVec<u16, ConstU32<S>> {
+	(0..S)
+		.map(|v| (v & 0xffff) as u16)
+		.collect::<Vec<_>>()
+		.try_into()
+		.unwrap()
+}
+pub fn create_var_data<const S: u32>(size: u32) -> BoundedVec<u8, ConstU32<S>> {
+	assert!(
+		size <= S,
+		"size ({}) should be less within bound ({})",
+		size,
+		S
+	);
+	(0..size)
+		.map(|v| (v & 0xff) as u8)
+		.collect::<Vec<_>>()
+		.try_into()
+		.unwrap()
 }
 
 pub fn create_collection_raw<T: Config, R>(
 	owner: T::AccountId,
 	mode: CollectionMode,
-	handler: impl FnOnce(Collection<T::AccountId>) -> Result<CollectionId, DispatchError>,
+	handler: impl FnOnce(
+		T::AccountId,
+		CreateCollectionData<T::AccountId>,
+	) -> Result<CollectionId, DispatchError>,
 	cast: impl FnOnce(CollectionHandle<T>) -> R,
 ) -> Result<R, DispatchError> {
 	T::Currency::deposit_creating(&owner, T::CollectionCreationPrice::get());
-	let name = create_u16_data(MAX_COLLECTION_NAME_LENGTH)
-		.try_into()
-		.unwrap();
-	let description = create_u16_data(MAX_COLLECTION_DESCRIPTION_LENGTH)
-		.try_into()
-		.unwrap();
-	let token_prefix = create_data(MAX_TOKEN_PREFIX_LENGTH).try_into().unwrap();
-	let offchain_schema = create_data(OFFCHAIN_SCHEMA_LIMIT as usize)
-		.try_into()
-		.unwrap();
-	let variable_on_chain_schema = create_data(VARIABLE_ON_CHAIN_SCHEMA_LIMIT as usize)
-		.try_into()
-		.unwrap();
-	let const_on_chain_schema = create_data(CONST_ON_CHAIN_SCHEMA_LIMIT as usize)
-		.try_into()
-		.unwrap();
-	handler(Collection {
+	let name = create_u16_data::<MAX_COLLECTION_NAME_LENGTH>();
+	let description = create_u16_data::<MAX_COLLECTION_DESCRIPTION_LENGTH>();
+	let token_prefix = create_data::<MAX_TOKEN_PREFIX_LENGTH>();
+	let offchain_schema = create_data::<OFFCHAIN_SCHEMA_LIMIT>();
+	let variable_on_chain_schema = create_data::<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>();
+	let const_on_chain_schema = create_data::<CONST_ON_CHAIN_SCHEMA_LIMIT>();
+	handler(
 		owner,
-		mode,
-		access: Default::default(),
-		name,
-		description,
-		token_prefix,
-		mint_mode: true,
-		offchain_schema,
-		schema_version: Default::default(),
-		sponsorship: Default::default(),
-		limits: Default::default(),
-		variable_on_chain_schema,
-		const_on_chain_schema,
-		meta_update_permission: Default::default(),
-	})
+		CreateCollectionData {
+			mode,
+			name,
+			description,
+			token_prefix,
+			offchain_schema,
+			variable_on_chain_schema,
+			const_on_chain_schema,
+			..Default::default()
+		},
+	)
 	.and_then(CollectionHandle::try_get)
 	.map(cast)
 }
 
+/// Helper macros, which handles all benchmarking preparation in semi-declarative way
+///
+/// `name` is a substrate account
+/// - name: sub[(id)]
+/// `name` is a collection with owner `owner`
+/// - name: collection(owner)
+/// `name` is a cross account based on substrate
+/// - name: cross_sub[(id)]
+/// `name` is a cross account, which maps to substrate account `name`
+/// - name: cross_from_sub
+/// `name` is a cross account, which maps to substrate account `other_name`
+/// - name: cross_from_sub(other_name)
 #[macro_export]
 macro_rules! bench_init {
 	($name:ident: sub $(($id:expr))?; $($rest:tt)*) => {
modifiedpallets/fungible/src/common.rsdiffbeforeafterboth
--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -12,7 +12,7 @@
 };
 
 pub struct CommonWeights<T: Config>(PhantomData<T>);
-impl<T: Config> CommonWeightInfo for CommonWeights<T> {
+impl<T: Config> CommonWeightInfo<T::CrossAccountId> for CommonWeights<T> {
 	fn create_item() -> Weight {
 		<SelfWeightOf<T>>::create_item()
 	}
modifiedpallets/fungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -9,7 +9,7 @@
 use pallet_evm_coder_substrate::WithRecorder;
 use sp_core::H160;
 use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};
-use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};
+use sp_std::collections::btree_map::BTreeMap;
 
 pub use pallet::*;
 
@@ -222,7 +222,7 @@
 	pub fn create_multiple_items(
 		collection: &FungibleHandle<T>,
 		sender: &T::CrossAccountId,
-		data: Vec<CreateItemData<T>>,
+		data: BTreeMap<T::CrossAccountId, u128>,
 	) -> DispatchResult {
 		if !collection.is_owner_or_admin(sender) {
 			ensure!(
@@ -236,22 +236,18 @@
 			}
 		}
 
-		let mut balances = BTreeMap::new();
-
 		let total_supply = data
 			.iter()
-			.map(|u| u.1)
+			.map(|(_, v)| *v)
 			.try_fold(<TotalSupply<T>>::get(collection.id), |acc, v| {
 				acc.checked_add(v)
 			})
 			.ok_or(ArithmeticError::Overflow)?;
 
-		for (user, amount) in data.into_iter() {
-			let balance = balances
-				.entry(user.clone())
-				.or_insert_with(|| <Balance<T>>::get((collection.id, user)));
-			*balance = (*balance)
-				.checked_add(amount)
+		let mut balances = data;
+		for (k, v) in balances.iter_mut() {
+			*v = <Balance<T>>::get((collection.id, &k))
+				.checked_add(*v)
 				.ok_or(ArithmeticError::Overflow)?;
 		}
 
modifiedpallets/inflation/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/inflation/src/benchmarking.rs
+++ b/pallets/inflation/src/benchmarking.rs
@@ -1,7 +1,7 @@
 #![cfg(feature = "runtime-benchmarks")]
 
 use super::*;
-use crate::Module as Inflation;
+use crate::Pallet as Inflation;
 
 use frame_benchmarking::{benchmarks};
 use frame_support::traits::OnInitialize;
modifiedpallets/nonfungible/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/benchmarking.rs
+++ b/pallets/nonfungible/src/benchmarking.rs
@@ -2,18 +2,18 @@
 use crate::{Pallet, Config, NonfungibleHandle};
 
 use sp_std::prelude::*;
-use pallet_common::benchmarking::{create_collection_raw, create_data};
+use pallet_common::benchmarking::{create_collection_raw, create_data, create_var_data};
 use frame_benchmarking::{benchmarks, account};
-use up_data_structs::{CollectionMode, MAX_ITEMS_PER_BATCH};
+use up_data_structs::{CollectionMode, MAX_ITEMS_PER_BATCH, CUSTOM_DATA_LIMIT};
 use pallet_common::bench_init;
 use core::convert::TryInto;
 
 const SEED: u32 = 1;
 
 fn create_max_item_data<T: Config>(owner: T::CrossAccountId) -> CreateItemData<T> {
-	let const_data = create_data(CUSTOM_DATA_LIMIT as usize).try_into().unwrap();
-	let variable_data = create_data(CUSTOM_DATA_LIMIT as usize).try_into().unwrap();
-	CreateItemData {
+	let const_data = create_data::<CUSTOM_DATA_LIMIT>();
+	let variable_data = create_data::<CUSTOM_DATA_LIMIT>();
+	CreateItemData::<T> {
 		const_data,
 		variable_data,
 		owner,
@@ -24,7 +24,7 @@
 	sender: &T::CrossAccountId,
 	owner: T::CrossAccountId,
 ) -> Result<TokenId, DispatchError> {
-	<Pallet<T>>::create_item(&collection, sender, create_max_item_data(owner))?;
+	<Pallet<T>>::create_item(&collection, sender, create_max_item_data::<T>(owner))?;
 	Ok(TokenId(<TokensMinted<T>>::get(&collection.id)))
 }
 
@@ -53,7 +53,9 @@
 			owner: sub; collection: collection(owner);
 			sender: cross_from_sub(owner); to: cross_sub;
 		};
-		let data = (0..b).map(|_| create_max_item_data(to.clone())).collect();
+		let data = (0..b).map(|_| create_max_item_data::<T>(to.clone())).collect();
+	}: {<Pallet<T>>::create_multiple_items(&collection, &sender, data)?}
+
 	}: {<Pallet<T>>::create_multiple_items(&collection, &sender, data)?}
 
 	burn_item {
@@ -105,6 +107,6 @@
 			owner: cross_from_sub; sender: cross_sub;
 		};
 		let item = create_max_item(&collection, &owner, sender.clone())?;
-		let data = create_data(b as usize);
+		let data = create_var_data(b).try_into().unwrap();
 	}: {<Pallet<T>>::set_variable_metadata(&collection, &sender, item, data)?}
 }
modifiedpallets/nonfungible/src/common.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -12,7 +12,7 @@
 };
 
 pub struct CommonWeights<T: Config>(PhantomData<T>);
-impl<T: Config> CommonWeightInfo for CommonWeights<T> {
+impl<T: Config> CommonWeightInfo<T::CrossAccountId> for CommonWeights<T> {
 	fn create_item() -> Weight {
 		<SelfWeightOf<T>>::create_item()
 	}
@@ -51,7 +51,7 @@
 	to: &T::CrossAccountId,
 ) -> Result<CreateItemData<T>, DispatchError> {
 	match data {
-		up_data_structs::CreateItemData::NFT(data) => Ok(CreateItemData {
+		up_data_structs::CreateItemData::NFT(data) => Ok(CreateItemData::<T> {
 			const_data: data.const_data,
 			variable_data: data.variable_data,
 			owner: to.clone(),
@@ -68,7 +68,7 @@
 		data: up_data_structs::CreateItemData,
 	) -> DispatchResultWithPostInfo {
 		with_weight(
-			<Pallet<T>>::create_item(self, &sender, map_create_data(data, &to)?),
+			<Pallet<T>>::create_item(self, &sender, map_create_data::<T>(data, &to)?),
 			<CommonWeights<T>>::create_item(),
 		)
 	}
modifiedpallets/nonfungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -232,7 +232,7 @@
 		<Pallet<T>>::create_item(
 			self,
 			&caller,
-			CreateItemData {
+			CreateItemData::<T> {
 				const_data: BoundedVec::default(),
 				variable_data: BoundedVec::default(),
 				owner: to,
@@ -268,7 +268,7 @@
 		<Pallet<T>>::create_item(
 			self,
 			&caller,
-			CreateItemData {
+			CreateItemData::<T> {
 				const_data: Vec::<u8>::from(token_uri)
 					.try_into()
 					.map_err(|_| "token uri is too long")?,
@@ -376,7 +376,7 @@
 			expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;
 		}
 		let data = (0..total_tokens)
-			.map(|_| CreateItemData {
+			.map(|_| CreateItemData::<T> {
 				const_data: BoundedVec::default(),
 				variable_data: BoundedVec::default(),
 				owner: to.clone(),
@@ -409,7 +409,7 @@
 			}
 			expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;
 
-			data.push(CreateItemData {
+			data.push(CreateItemData::<T> {
 				const_data: Vec::<u8>::from(token_uri)
 					.try_into()
 					.map_err(|_| "token uri is too long")?,
modifiedpallets/refungible/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/refungible/src/benchmarking.rs
+++ b/pallets/refungible/src/benchmarking.rs
@@ -2,24 +2,28 @@
 use crate::{Pallet, Config, RefungibleHandle};
 
 use sp_std::prelude::*;
-use pallet_common::benchmarking::{create_collection_raw, create_data};
+use pallet_common::benchmarking::{create_collection_raw, create_data, create_var_data};
 use frame_benchmarking::{benchmarks, account};
-use up_data_structs::{CollectionMode, MAX_ITEMS_PER_BATCH};
+use up_data_structs::{CollectionMode, MAX_ITEMS_PER_BATCH, CUSTOM_DATA_LIMIT};
 use pallet_common::bench_init;
 use core::convert::TryInto;
 use core::iter::IntoIterator;
 
 const SEED: u32 = 1;
 
-fn create_max_item_data<T: Config>(
-	users: impl IntoIterator<Item = (T::CrossAccountId, u128)>,
-) -> CreateItemData<T> {
-	let const_data = create_data(CUSTOM_DATA_LIMIT as usize).try_into().unwrap();
-	let variable_data = create_data(CUSTOM_DATA_LIMIT as usize).try_into().unwrap();
-	CreateItemData {
+fn create_max_item_data<CrossAccountId: Ord>(
+	users: impl IntoIterator<Item = (CrossAccountId, u128)>,
+) -> CreateRefungibleExData<CrossAccountId> {
+	let const_data = create_data::<CUSTOM_DATA_LIMIT>();
+	let variable_data = create_data::<CUSTOM_DATA_LIMIT>();
+	CreateRefungibleExData {
 		const_data,
 		variable_data,
-		users: users.into_iter().collect(),
+		users: users
+			.into_iter()
+			.collect::<BTreeMap<_, _>>()
+			.try_into()
+			.unwrap(),
 	}
 }
 fn create_max_item<T: Config>(
modifiedpallets/refungible/src/common.rsdiffbeforeafterboth
--- a/pallets/refungible/src/common.rs
+++ b/pallets/refungible/src/common.rs
@@ -8,8 +8,8 @@
 use sp_std::vec::Vec;
 
 use crate::{
-	AccountBalance, Allowance, Balance, Config, CreateItemData, Error, Owned, Pallet,
-	RefungibleHandle, SelfWeightOf, TokenData, weights::WeightInfo, TokensMinted,
+	AccountBalance, Allowance, Balance, Config, Error, Owned, Pallet, RefungibleHandle,
+	SelfWeightOf, TokenData, weights::WeightInfo, TokensMinted,
 };
 
 macro_rules! max_weight_of {
@@ -22,7 +22,7 @@
 }
 
 pub struct CommonWeights<T: Config>(PhantomData<T>);
-impl<T: Config> CommonWeightInfo for CommonWeights<T> {
+impl<T: Config> CommonWeightInfo<T::CrossAccountId> for CommonWeights<T> {
 	fn create_item() -> Weight {
 		<SelfWeightOf<T>>::create_item()
 	}
modifiedpallets/unique/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/unique/src/benchmarking.rs
+++ b/pallets/unique/src/benchmarking.rs
@@ -5,9 +5,8 @@
 use frame_system::RawOrigin;
 use frame_benchmarking::{benchmarks, account};
 use up_data_structs::*;
-use core::convert::TryInto;
 use sp_runtime::DispatchError;
-use pallet_common::benchmarking::{create_data, create_u16_data};
+use pallet_common::benchmarking::{create_data, create_var_data, create_u16_data};
 
 const SEED: u32 = 1;
 
@@ -16,13 +15,9 @@
 	mode: CollectionMode,
 ) -> Result<CollectionId, DispatchError> {
 	T::Currency::deposit_creating(&owner, T::CollectionCreationPrice::get());
-	let col_name = create_u16_data(MAX_COLLECTION_NAME_LENGTH)
-		.try_into()
-		.unwrap();
-	let col_desc = create_u16_data(MAX_COLLECTION_DESCRIPTION_LENGTH)
-		.try_into()
-		.unwrap();
-	let token_prefix = create_data(MAX_TOKEN_PREFIX_LENGTH).try_into().unwrap();
+	let col_name = create_u16_data::<MAX_COLLECTION_NAME_LENGTH>();
+	let col_desc = create_u16_data::<MAX_COLLECTION_DESCRIPTION_LENGTH>();
+	let token_prefix = create_data::<MAX_TOKEN_PREFIX_LENGTH>();
 	<Pallet<T>>::create_collection(
 		RawOrigin::Signed(owner).into(),
 		col_name,
@@ -37,11 +32,10 @@
 }
 
 benchmarks! {
-
 	create_collection {
-		let col_name: Vec<u16> = create_u16_data(MAX_COLLECTION_NAME_LENGTH);
-		let col_desc: Vec<u16> = create_u16_data(MAX_COLLECTION_DESCRIPTION_LENGTH);
-		let token_prefix: Vec<u8> = create_data(MAX_TOKEN_PREFIX_LENGTH);
+		let col_name = create_u16_data::<MAX_COLLECTION_NAME_LENGTH>();
+		let col_desc = create_u16_data::<MAX_COLLECTION_DESCRIPTION_LENGTH>();
+		let token_prefix = create_data::<MAX_TOKEN_PREFIX_LENGTH>();
 		let mode: CollectionMode = CollectionMode::NFT;
 		let caller: T::AccountId = account("caller", 0, SEED);
 		T::Currency::deposit_creating(&caller, T::CollectionCreationPrice::get());
@@ -125,7 +119,7 @@
 
 		let caller: T::AccountId = account("caller", 0, SEED);
 		let collection = create_nft_collection::<T>(caller.clone())?;
-		let data = create_data(b as usize);
+		let data = create_var_data(b);
 	}: set_offchain_schema(RawOrigin::Signed(caller.clone()), collection, data)
 
 	set_const_on_chain_schema {
@@ -133,7 +127,7 @@
 
 		let caller: T::AccountId = account("caller", 0, SEED);
 		let collection = create_nft_collection::<T>(caller.clone())?;
-		let data = create_data(b as usize);
+		let data = create_var_data(b);
 	}: set_const_on_chain_schema(RawOrigin::Signed(caller.clone()), collection, data)
 
 	set_variable_on_chain_schema {
@@ -141,7 +135,7 @@
 
 		let caller: T::AccountId = account("caller", 0, SEED);
 		let collection = create_nft_collection::<T>(caller.clone())?;
-		let data = create_data(b as usize);
+		let data = create_var_data(b);
 	}: set_variable_on_chain_schema(RawOrigin::Signed(caller.clone()), collection, data)
 
 	set_schema_version {
modifiedprimitives/data-structs/src/lib.rsdiffbeforeafterboth
before · primitives/data-structs/src/lib.rs
1#![cfg_attr(not(feature = "std"), no_std)]23use core::convert::{TryFrom, TryInto};45#[cfg(feature = "serde")]6pub use serde::{Serialize, Deserialize};78use sp_core::U256;9use sp_runtime::{ArithmeticError, sp_std::prelude::Vec};10use codec::{Decode, Encode, EncodeLike, MaxEncodedLen};11pub use frame_support::{12	BoundedVec, construct_runtime, decl_event, decl_module, decl_storage, decl_error,13	dispatch::DispatchResult,14	ensure, fail, parameter_types,15	traits::{16		Currency, ExistenceRequirement, Get, Imbalance, KeyOwnerProofSystem, OnUnbalanced,17		Randomness, IsSubType, WithdrawReasons,18	},19	weights::{20		constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},21		DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,22		WeightToFeePolynomial, DispatchClass,23	},24	StorageValue, transactional,25	pallet_prelude::ConstU32,26};27use derivative::Derivative;28use scale_info::TypeInfo;2930mod migration;3132pub const MAX_DECIMAL_POINTS: DecimalPoints = 30;33pub const MAX_REFUNGIBLE_PIECES: u128 = 1_000_000_000_000_000_000_000;34pub const MAX_SPONSOR_TIMEOUT: u32 = 10_368_000;3536pub const MAX_TOKEN_OWNERSHIP: u32 = if cfg!(not(feature = "limit-testing")) {37	100_00038} else {39	1040};41pub const COLLECTION_NUMBER_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {42	100_00043} else {44	1045};46pub const CUSTOM_DATA_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {47	204848} else {49	1050};51pub const COLLECTION_ADMINS_LIMIT: u32 = 5;52pub const COLLECTION_TOKEN_LIMIT: u32 = u32::MAX;53pub const ACCOUNT_TOKEN_OWNERSHIP_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {54	1_000_00055} else {56	1057};5859// Timeouts for item types in passed blocks60pub const NFT_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;61pub const FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;62pub const REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;6364pub const SPONSOR_APPROVE_TIMEOUT: u32 = 5;6566// Schema limits67pub const OFFCHAIN_SCHEMA_LIMIT: u32 = 8192;68pub const VARIABLE_ON_CHAIN_SCHEMA_LIMIT: u32 = 8192;69pub const CONST_ON_CHAIN_SCHEMA_LIMIT: u32 = 32768;7071pub const MAX_COLLECTION_NAME_LENGTH: u32 = 64;72pub const MAX_COLLECTION_DESCRIPTION_LENGTH: u32 = 256;73pub const MAX_TOKEN_PREFIX_LENGTH: u32 = 16;7475/// How much items can be created per single76/// create_many call77pub const MAX_ITEMS_PER_BATCH: u32 = 200;7879parameter_types! {80	pub const CustomDataLimit: u32 = CUSTOM_DATA_LIMIT;81}8283#[derive(84	Encode,85	Decode,86	PartialEq,87	Eq,88	PartialOrd,89	Ord,90	Clone,91	Copy,92	Debug,93	Default,94	TypeInfo,95	MaxEncodedLen,96)]97#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]98pub struct CollectionId(pub u32);99impl EncodeLike<u32> for CollectionId {}100impl EncodeLike<CollectionId> for u32 {}101102#[derive(103	Encode,104	Decode,105	PartialEq,106	Eq,107	PartialOrd,108	Ord,109	Clone,110	Copy,111	Debug,112	Default,113	TypeInfo,114	MaxEncodedLen,115)]116#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]117pub struct TokenId(pub u32);118impl EncodeLike<u32> for TokenId {}119impl EncodeLike<TokenId> for u32 {}120121impl TokenId {122	pub fn try_next(self) -> Result<TokenId, ArithmeticError> {123		self.0124			.checked_add(1)125			.ok_or(ArithmeticError::Overflow)126			.map(Self)127	}128}129130impl From<TokenId> for U256 {131	fn from(t: TokenId) -> Self {132		t.0.into()133	}134}135136impl TryFrom<U256> for TokenId {137	type Error = &'static str;138139	fn try_from(value: U256) -> Result<Self, Self::Error> {140		Ok(TokenId(value.try_into().map_err(|_| "too large token id")?))141	}142}143144pub struct OverflowError;145impl From<OverflowError> for &'static str {146	fn from(_: OverflowError) -> Self {147		"overflow occured"148	}149}150151pub type DecimalPoints = u8;152153#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]154#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]155pub enum CollectionMode {156	NFT,157	// decimal points158	Fungible(DecimalPoints),159	ReFungible,160}161162impl CollectionMode {163	pub fn id(&self) -> u8 {164		match self {165			CollectionMode::NFT => 1,166			CollectionMode::Fungible(_) => 2,167			CollectionMode::ReFungible => 3,168		}169	}170}171172pub trait SponsoringResolve<AccountId, Call> {173	fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>;174}175176#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]177#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]178pub enum AccessMode {179	Normal,180	AllowList,181}182impl Default for AccessMode {183	fn default() -> Self {184		Self::Normal185	}186}187188#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]189#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]190pub enum SchemaVersion {191	ImageURL,192	Unique,193}194impl Default for SchemaVersion {195	fn default() -> Self {196		Self::ImageURL197	}198}199200#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]201#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]202pub struct Ownership<AccountId> {203	pub owner: AccountId,204	pub fraction: u128,205}206207#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]208#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]209pub enum SponsorshipState<AccountId> {210	/// The fees are applied to the transaction sender211	Disabled,212	Unconfirmed(AccountId),213	/// Transactions are sponsored by specified account214	Confirmed(AccountId),215}216217impl<AccountId> SponsorshipState<AccountId> {218	pub fn sponsor(&self) -> Option<&AccountId> {219		match self {220			Self::Confirmed(sponsor) => Some(sponsor),221			_ => None,222		}223	}224225	pub fn pending_sponsor(&self) -> Option<&AccountId> {226		match self {227			Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),228			_ => None,229		}230	}231232	pub fn confirmed(&self) -> bool {233		matches!(self, Self::Confirmed(_))234	}235}236237impl<T> Default for SponsorshipState<T> {238	fn default() -> Self {239		Self::Disabled240	}241}242243#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen)]244#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]245pub struct Collection<AccountId> {246	pub owner: AccountId,247	pub mode: CollectionMode,248	pub access: AccessMode,249	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]250	pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,251	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]252	pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,253	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]254	pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,255	pub mint_mode: bool,256	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]257	pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,258	pub schema_version: SchemaVersion,259	pub sponsorship: SponsorshipState<AccountId>,260	pub limits: CollectionLimits, // Collection private restrictions261	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]262	pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,263	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]264	pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,265	pub meta_update_permission: MetaUpdatePermission,266}267268#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Debug, Derivative, MaxEncodedLen)]269#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]270#[derivative(Default(bound = ""))]271pub struct CreateCollectionData<AccountId> {272	#[derivative(Default(value = "CollectionMode::NFT"))]273	pub mode: CollectionMode,274	pub access: Option<AccessMode>,275	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]276	pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,277	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]278	pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,279	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]280	pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,281	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]282	pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,283	pub schema_version: Option<SchemaVersion>,284	pub pending_sponsor: Option<AccountId>,285	pub limits: Option<CollectionLimits>,286	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]287	pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,288	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]289	pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,290	pub meta_update_permission: Option<MetaUpdatePermission>,291}292293#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]294#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]295pub struct NftItemType<AccountId> {296	pub owner: AccountId,297	pub const_data: Vec<u8>,298	pub variable_data: Vec<u8>,299}300301#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]302#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]303pub struct FungibleItemType {304	pub value: u128,305}306307#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]308#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]309pub struct ReFungibleItemType<AccountId> {310	pub owner: Vec<Ownership<AccountId>>,311	pub const_data: Vec<u8>,312	pub variable_data: Vec<u8>,313}314315/// All fields are wrapped in `Option`s, where None means chain default316#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]317#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]318pub struct CollectionLimits {319	pub account_token_ownership_limit: Option<u32>,320	pub sponsored_data_size: Option<u32>,321	/// None - setVariableMetadata is not sponsored322	/// Some(v) - setVariableMetadata is sponsored323	///           if there is v block between txs324	pub sponsored_data_rate_limit: Option<SponsoringRateLimit>,325	pub token_limit: Option<u32>,326327	// Timeouts for item types in passed blocks328	pub sponsor_transfer_timeout: Option<u32>,329	pub sponsor_approve_timeout: Option<u32>,330	pub owner_can_transfer: Option<bool>,331	pub owner_can_destroy: Option<bool>,332	pub transfers_enabled: Option<bool>,333}334335impl CollectionLimits {336	pub fn account_token_ownership_limit(&self) -> u32 {337		self.account_token_ownership_limit338			.unwrap_or(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)339			.min(MAX_TOKEN_OWNERSHIP)340	}341	pub fn sponsored_data_size(&self) -> u32 {342		self.sponsored_data_size343			.unwrap_or(CUSTOM_DATA_LIMIT)344			.min(CUSTOM_DATA_LIMIT)345	}346	pub fn token_limit(&self) -> u32 {347		self.token_limit348			.unwrap_or(COLLECTION_TOKEN_LIMIT)349			.min(COLLECTION_TOKEN_LIMIT)350	}351	pub fn sponsor_transfer_timeout(&self, default: u32) -> u32 {352		self.sponsor_transfer_timeout353			.unwrap_or(default)354			.min(MAX_SPONSOR_TIMEOUT)355	}356	pub fn sponsor_approve_timeout(&self) -> u32 {357		self.sponsor_approve_timeout358			.unwrap_or(SPONSOR_APPROVE_TIMEOUT)359			.min(MAX_SPONSOR_TIMEOUT)360	}361	pub fn owner_can_transfer(&self) -> bool {362		self.owner_can_transfer.unwrap_or(true)363	}364	pub fn owner_can_destroy(&self) -> bool {365		self.owner_can_destroy.unwrap_or(true)366	}367	pub fn transfers_enabled(&self) -> bool {368		self.transfers_enabled.unwrap_or(true)369	}370	pub fn sponsored_data_rate_limit(&self) -> Option<u32> {371		match self372			.sponsored_data_rate_limit373			.unwrap_or(SponsoringRateLimit::SponsoringDisabled)374		{375			SponsoringRateLimit::SponsoringDisabled => None,376			SponsoringRateLimit::Blocks(v) => Some(v.min(MAX_SPONSOR_TIMEOUT)),377		}378	}379}380381#[derive(Encode, Decode, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]382#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]383pub enum SponsoringRateLimit {384	SponsoringDisabled,385	Blocks(u32),386}387388/// BoundedVec doesn't supports serde389#[cfg(feature = "serde1")]390mod bounded_serde {391	use core::convert::TryFrom;392	use frame_support::{BoundedVec, traits::Get};393	use serde::{394		ser::{self, Serialize},395		de::{self, Deserialize, Error},396	};397	use sp_std::vec::Vec;398399	pub fn serialize<D, V, S>(value: &BoundedVec<V, S>, serializer: D) -> Result<D::Ok, D::Error>400	where401		D: ser::Serializer,402		V: Serialize,403	{404		(value as &Vec<_>).serialize(serializer)405	}406407	pub fn deserialize<'de, D, V, S>(deserializer: D) -> Result<BoundedVec<V, S>, D::Error>408	where409		D: de::Deserializer<'de>,410		V: de::Deserialize<'de>,411		S: Get<u32>,412	{413		// TODO: Implement custom visitor, which will limit vec size at parse time? Will serde only be used by chainspec?414		let vec = <Vec<V>>::deserialize(deserializer)?;415		let len = vec.len();416		TryFrom::try_from(vec).map_err(|_| D::Error::invalid_length(len, &"lesser size"))417	}418}419420#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]421#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]422#[derivative(Debug)]423pub struct CreateNftData {424	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]425	#[derivative(Debug = "ignore")]426	pub const_data: BoundedVec<u8, CustomDataLimit>,427	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]428	#[derivative(Debug = "ignore")]429	pub variable_data: BoundedVec<u8, CustomDataLimit>,430}431432#[derive(Encode, Decode, MaxEncodedLen, Default, Debug, Clone, PartialEq, TypeInfo)]433#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]434pub struct CreateFungibleData {435	pub value: u128,436}437438#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]439#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]440#[derivative(Debug)]441pub struct CreateReFungibleData {442	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]443	#[derivative(Debug = "ignore")]444	pub const_data: BoundedVec<u8, CustomDataLimit>,445	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]446	#[derivative(Debug = "ignore")]447	pub variable_data: BoundedVec<u8, CustomDataLimit>,448	pub pieces: u128,449}450451#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]452#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]453pub enum MetaUpdatePermission {454	ItemOwner,455	Admin,456	None,457}458459impl Default for MetaUpdatePermission {460	fn default() -> Self {461		Self::ItemOwner462	}463}464465#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]466#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]467pub enum CreateItemData {468	NFT(CreateNftData),469	Fungible(CreateFungibleData),470	ReFungible(CreateReFungibleData),471}472473impl CreateItemData {474	pub fn data_size(&self) -> usize {475		match self {476			CreateItemData::NFT(data) => data.variable_data.len() + data.const_data.len(),477			CreateItemData::ReFungible(data) => data.variable_data.len() + data.const_data.len(),478			_ => 0,479		}480	}481}482483impl From<CreateNftData> for CreateItemData {484	fn from(item: CreateNftData) -> Self {485		CreateItemData::NFT(item)486	}487}488489impl From<CreateReFungibleData> for CreateItemData {490	fn from(item: CreateReFungibleData) -> Self {491		CreateItemData::ReFungible(item)492	}493}494495impl From<CreateFungibleData> for CreateItemData {496	fn from(item: CreateFungibleData) -> Self {497		CreateItemData::Fungible(item)498	}499}500501#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]502#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]503pub struct CollectionStats {504	pub created: u32,505	pub destroyed: u32,506	pub alive: u32,507}
after · primitives/data-structs/src/lib.rs
1#![cfg_attr(not(feature = "std"), no_std)]23use core::convert::{TryFrom, TryInto};45#[cfg(feature = "serde")]6pub use serde::{Serialize, Deserialize};78use sp_core::U256;9use sp_runtime::{ArithmeticError, sp_std::prelude::Vec};10use codec::{Decode, Encode, EncodeLike, MaxEncodedLen};11pub use frame_support::{12	BoundedVec, construct_runtime, decl_event, decl_module, decl_storage, decl_error,13	dispatch::DispatchResult,14	ensure, fail, parameter_types,15	traits::{16		Currency, ExistenceRequirement, Get, Imbalance, KeyOwnerProofSystem, OnUnbalanced,17		Randomness, IsSubType, WithdrawReasons,18	},19	weights::{20		constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},21		DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,22		WeightToFeePolynomial, DispatchClass,23	},24	StorageValue, transactional,25	pallet_prelude::ConstU32,26};27use derivative::Derivative;28use scale_info::TypeInfo;2930mod migration;3132pub const MAX_DECIMAL_POINTS: DecimalPoints = 30;33pub const MAX_REFUNGIBLE_PIECES: u128 = 1_000_000_000_000_000_000_000;34pub const MAX_SPONSOR_TIMEOUT: u32 = 10_368_000;3536pub const MAX_TOKEN_OWNERSHIP: u32 = if cfg!(not(feature = "limit-testing")) {37	100_00038} else {39	1040};41pub const COLLECTION_NUMBER_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {42	100_00043} else {44	1045};46pub const CUSTOM_DATA_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {47	204848} else {49	1050};51pub const COLLECTION_ADMINS_LIMIT: u32 = 5;52pub const COLLECTION_TOKEN_LIMIT: u32 = u32::MAX;53pub const ACCOUNT_TOKEN_OWNERSHIP_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {54	1_000_00055} else {56	1057};5859// Timeouts for item types in passed blocks60pub const NFT_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;61pub const FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;62pub const REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;6364pub const SPONSOR_APPROVE_TIMEOUT: u32 = 5;6566// Schema limits67pub const OFFCHAIN_SCHEMA_LIMIT: u32 = 8192;68pub const VARIABLE_ON_CHAIN_SCHEMA_LIMIT: u32 = 8192;69pub const CONST_ON_CHAIN_SCHEMA_LIMIT: u32 = 32768;7071pub const MAX_COLLECTION_NAME_LENGTH: u32 = 64;72pub const MAX_COLLECTION_DESCRIPTION_LENGTH: u32 = 256;73pub const MAX_TOKEN_PREFIX_LENGTH: u32 = 16;7475/// How much items can be created per single76/// create_many call77pub const MAX_ITEMS_PER_BATCH: u32 = 200;7879pub type CustomDataLimit = ConstU32<CUSTOM_DATA_LIMIT>;8081#[derive(82	Encode,83	Decode,84	PartialEq,85	Eq,86	PartialOrd,87	Ord,88	Clone,89	Copy,90	Debug,91	Default,92	TypeInfo,93	MaxEncodedLen,94)]95#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]96pub struct CollectionId(pub u32);97impl EncodeLike<u32> for CollectionId {}98impl EncodeLike<CollectionId> for u32 {}99100#[derive(101	Encode,102	Decode,103	PartialEq,104	Eq,105	PartialOrd,106	Ord,107	Clone,108	Copy,109	Debug,110	Default,111	TypeInfo,112	MaxEncodedLen,113)]114#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]115pub struct TokenId(pub u32);116impl EncodeLike<u32> for TokenId {}117impl EncodeLike<TokenId> for u32 {}118119impl TokenId {120	pub fn try_next(self) -> Result<TokenId, ArithmeticError> {121		self.0122			.checked_add(1)123			.ok_or(ArithmeticError::Overflow)124			.map(Self)125	}126}127128impl From<TokenId> for U256 {129	fn from(t: TokenId) -> Self {130		t.0.into()131	}132}133134impl TryFrom<U256> for TokenId {135	type Error = &'static str;136137	fn try_from(value: U256) -> Result<Self, Self::Error> {138		Ok(TokenId(value.try_into().map_err(|_| "too large token id")?))139	}140}141142pub struct OverflowError;143impl From<OverflowError> for &'static str {144	fn from(_: OverflowError) -> Self {145		"overflow occured"146	}147}148149pub type DecimalPoints = u8;150151#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]152#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]153pub enum CollectionMode {154	NFT,155	// decimal points156	Fungible(DecimalPoints),157	ReFungible,158}159160impl CollectionMode {161	pub fn id(&self) -> u8 {162		match self {163			CollectionMode::NFT => 1,164			CollectionMode::Fungible(_) => 2,165			CollectionMode::ReFungible => 3,166		}167	}168}169170pub trait SponsoringResolve<AccountId, Call> {171	fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>;172}173174#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]175#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]176pub enum AccessMode {177	Normal,178	AllowList,179}180impl Default for AccessMode {181	fn default() -> Self {182		Self::Normal183	}184}185186#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]187#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]188pub enum SchemaVersion {189	ImageURL,190	Unique,191}192impl Default for SchemaVersion {193	fn default() -> Self {194		Self::ImageURL195	}196}197198#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]199#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]200pub struct Ownership<AccountId> {201	pub owner: AccountId,202	pub fraction: u128,203}204205#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]206#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]207pub enum SponsorshipState<AccountId> {208	/// The fees are applied to the transaction sender209	Disabled,210	Unconfirmed(AccountId),211	/// Transactions are sponsored by specified account212	Confirmed(AccountId),213}214215impl<AccountId> SponsorshipState<AccountId> {216	pub fn sponsor(&self) -> Option<&AccountId> {217		match self {218			Self::Confirmed(sponsor) => Some(sponsor),219			_ => None,220		}221	}222223	pub fn pending_sponsor(&self) -> Option<&AccountId> {224		match self {225			Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),226			_ => None,227		}228	}229230	pub fn confirmed(&self) -> bool {231		matches!(self, Self::Confirmed(_))232	}233}234235impl<T> Default for SponsorshipState<T> {236	fn default() -> Self {237		Self::Disabled238	}239}240241#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen)]242#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]243pub struct Collection<AccountId> {244	pub owner: AccountId,245	pub mode: CollectionMode,246	pub access: AccessMode,247	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]248	pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,249	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]250	pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,251	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]252	pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,253	pub mint_mode: bool,254	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]255	pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,256	pub schema_version: SchemaVersion,257	pub sponsorship: SponsorshipState<AccountId>,258	pub limits: CollectionLimits, // Collection private restrictions259	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]260	pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,261	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]262	pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,263	pub meta_update_permission: MetaUpdatePermission,264}265266#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Debug, Derivative, MaxEncodedLen)]267#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]268#[derivative(Default(bound = ""))]269pub struct CreateCollectionData<AccountId> {270	#[derivative(Default(value = "CollectionMode::NFT"))]271	pub mode: CollectionMode,272	pub access: Option<AccessMode>,273	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]274	pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,275	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]276	pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,277	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]278	pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,279	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]280	pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,281	pub schema_version: Option<SchemaVersion>,282	pub pending_sponsor: Option<AccountId>,283	pub limits: Option<CollectionLimits>,284	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]285	pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,286	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]287	pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,288	pub meta_update_permission: Option<MetaUpdatePermission>,289}290291#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]292#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]293pub struct NftItemType<AccountId> {294	pub owner: AccountId,295	pub const_data: Vec<u8>,296	pub variable_data: Vec<u8>,297}298299#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]300#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]301pub struct FungibleItemType {302	pub value: u128,303}304305#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]306#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]307pub struct ReFungibleItemType<AccountId> {308	pub owner: Vec<Ownership<AccountId>>,309	pub const_data: Vec<u8>,310	pub variable_data: Vec<u8>,311}312313/// All fields are wrapped in `Option`s, where None means chain default314#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]315#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]316pub struct CollectionLimits {317	pub account_token_ownership_limit: Option<u32>,318	pub sponsored_data_size: Option<u32>,319	/// None - setVariableMetadata is not sponsored320	/// Some(v) - setVariableMetadata is sponsored321	///           if there is v block between txs322	pub sponsored_data_rate_limit: Option<SponsoringRateLimit>,323	pub token_limit: Option<u32>,324325	// Timeouts for item types in passed blocks326	pub sponsor_transfer_timeout: Option<u32>,327	pub sponsor_approve_timeout: Option<u32>,328	pub owner_can_transfer: Option<bool>,329	pub owner_can_destroy: Option<bool>,330	pub transfers_enabled: Option<bool>,331}332333impl CollectionLimits {334	pub fn account_token_ownership_limit(&self) -> u32 {335		self.account_token_ownership_limit336			.unwrap_or(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)337			.min(MAX_TOKEN_OWNERSHIP)338	}339	pub fn sponsored_data_size(&self) -> u32 {340		self.sponsored_data_size341			.unwrap_or(CUSTOM_DATA_LIMIT)342			.min(CUSTOM_DATA_LIMIT)343	}344	pub fn token_limit(&self) -> u32 {345		self.token_limit346			.unwrap_or(COLLECTION_TOKEN_LIMIT)347			.min(COLLECTION_TOKEN_LIMIT)348	}349	pub fn sponsor_transfer_timeout(&self, default: u32) -> u32 {350		self.sponsor_transfer_timeout351			.unwrap_or(default)352			.min(MAX_SPONSOR_TIMEOUT)353	}354	pub fn sponsor_approve_timeout(&self) -> u32 {355		self.sponsor_approve_timeout356			.unwrap_or(SPONSOR_APPROVE_TIMEOUT)357			.min(MAX_SPONSOR_TIMEOUT)358	}359	pub fn owner_can_transfer(&self) -> bool {360		self.owner_can_transfer.unwrap_or(true)361	}362	pub fn owner_can_destroy(&self) -> bool {363		self.owner_can_destroy.unwrap_or(true)364	}365	pub fn transfers_enabled(&self) -> bool {366		self.transfers_enabled.unwrap_or(true)367	}368	pub fn sponsored_data_rate_limit(&self) -> Option<u32> {369		match self370			.sponsored_data_rate_limit371			.unwrap_or(SponsoringRateLimit::SponsoringDisabled)372		{373			SponsoringRateLimit::SponsoringDisabled => None,374			SponsoringRateLimit::Blocks(v) => Some(v.min(MAX_SPONSOR_TIMEOUT)),375		}376	}377}378379#[derive(Encode, Decode, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]380#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]381pub enum SponsoringRateLimit {382	SponsoringDisabled,383	Blocks(u32),384}385386/// BoundedVec doesn't supports serde387#[cfg(feature = "serde1")]388mod bounded_serde {389	use core::convert::TryFrom;390	use frame_support::{BoundedVec, traits::Get};391	use serde::{392		ser::{self, Serialize},393		de::{self, Deserialize, Error},394	};395	use sp_std::vec::Vec;396397	pub fn serialize<D, V, S>(value: &BoundedVec<V, S>, serializer: D) -> Result<D::Ok, D::Error>398	where399		D: ser::Serializer,400		V: Serialize,401	{402		(value as &Vec<_>).serialize(serializer)403	}404405	pub fn deserialize<'de, D, V, S>(deserializer: D) -> Result<BoundedVec<V, S>, D::Error>406	where407		D: de::Deserializer<'de>,408		V: de::Deserialize<'de>,409		S: Get<u32>,410	{411		// TODO: Implement custom visitor, which will limit vec size at parse time? Will serde only be used by chainspec?412		let vec = <Vec<V>>::deserialize(deserializer)?;413		let len = vec.len();414		TryFrom::try_from(vec).map_err(|_| D::Error::invalid_length(len, &"lesser size"))415	}416}417418fn bounded_debug<V, S>(v: &BoundedVec<V, S>, f: &mut fmt::Formatter) -> Result<(), fmt::Error>419where420	V: fmt::Debug,421{422	use core::fmt::Debug;423	(&v as &Vec<V>).fmt(f)424}425426#[cfg(feature = "serde1")]427#[allow(dead_code)]428mod bounded_map_serde {429	use core::convert::TryFrom;430	use sp_std::collections::btree_map::BTreeMap;431	use frame_support::{traits::Get, storage::bounded_btree_map::BoundedBTreeMap};432	use serde::{433		ser::{self, Serialize},434		de::{self, Deserialize, Error},435	};436	pub fn serialize<D, K, V, S>(437		value: &BoundedBTreeMap<K, V, S>,438		serializer: D,439	) -> Result<D::Ok, D::Error>440	where441		D: ser::Serializer,442		K: Serialize + Ord,443		V: Serialize,444	{445		(value as &BTreeMap<_, _>).serialize(serializer)446	}447448	pub fn deserialize<'de, D, K, V, S>(449		deserializer: D,450	) -> Result<BoundedBTreeMap<K, V, S>, D::Error>451	where452		D: de::Deserializer<'de>,453		K: de::Deserialize<'de> + Ord,454		V: de::Deserialize<'de>,455		S: Get<u32>,456	{457		let map = <BTreeMap<K, V>>::deserialize(deserializer)?;458		let len = map.len();459		TryFrom::try_from(map).map_err(|_| D::Error::invalid_length(len, &"lesser size"))460	}461}462463fn bounded_map_debug<K, V, S>(464	v: &BoundedBTreeMap<K, V, S>,465	f: &mut fmt::Formatter,466) -> Result<(), fmt::Error>467where468	K: fmt::Debug + Ord,469	V: fmt::Debug,470{471	use core::fmt::Debug;472	(&v as &BTreeMap<K, V>).fmt(f)473}474475#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]476#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]477#[derivative(Debug)]478pub struct CreateNftData {479	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]480	#[derivative(Debug(format_with = "bounded_debug"))]481	pub const_data: BoundedVec<u8, CustomDataLimit>,482	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]483	#[derivative(Debug(format_with = "bounded_debug"))]484	pub variable_data: BoundedVec<u8, CustomDataLimit>,485}486487#[derive(Encode, Decode, MaxEncodedLen, Default, Debug, Clone, PartialEq, TypeInfo)]488#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]489pub struct CreateFungibleData {490	pub value: u128,491}492493#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]494#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]495#[derivative(Debug)]496pub struct CreateReFungibleData {497	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]498	#[derivative(Debug(format_with = "bounded_debug"))]499	pub const_data: BoundedVec<u8, CustomDataLimit>,500	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]501	#[derivative(Debug(format_with = "bounded_debug"))]502	pub variable_data: BoundedVec<u8, CustomDataLimit>,503	pub pieces: u128,504}505506#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]507#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]508pub enum MetaUpdatePermission {509	ItemOwner,510	Admin,511	None,512}513514impl Default for MetaUpdatePermission {515	fn default() -> Self {516		Self::ItemOwner517	}518}519520#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]521#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]522pub enum CreateItemData {523	NFT(CreateNftData),524	Fungible(CreateFungibleData),525	ReFungible(CreateReFungibleData),526}527528impl CreateItemData {529	pub fn data_size(&self) -> usize {530		match self {531			CreateItemData::NFT(data) => data.variable_data.len() + data.const_data.len(),532			CreateItemData::ReFungible(data) => data.variable_data.len() + data.const_data.len(),533			_ => 0,534		}535	}536}537538impl From<CreateNftData> for CreateItemData {539	fn from(item: CreateNftData) -> Self {540		CreateItemData::NFT(item)541	}542}543544impl From<CreateReFungibleData> for CreateItemData {545	fn from(item: CreateReFungibleData) -> Self {546		CreateItemData::ReFungible(item)547	}548}549550impl From<CreateFungibleData> for CreateItemData {551	fn from(item: CreateFungibleData) -> Self {552		CreateItemData::Fungible(item)553	}554}555556#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]557#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]558pub struct CollectionStats {559	pub created: u32,560	pub destroyed: u32,561	pub alive: u32,562}