git.delta.rocks / unique-network / refs/commits / 1d469f4695cf

difftreelog

feat(refungible) benchmarking

Yaroslav Bolyukin2021-10-22parent: #4e1bd65.patch.diff
in: master

5 files changed

modifiedpallets/refungible/Cargo.tomldiffbeforeafterboth
--- a/pallets/refungible/Cargo.toml
+++ b/pallets/refungible/Cargo.toml
@@ -17,6 +17,7 @@
 sp-core = { default-features = false, version = '4.0.0-dev', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.10' }
 pallet-common = { default-features = false, path = '../common' }
 nft-data-structs = { default-features = false, path = '../../primitives/nft' }
+frame-benchmarking = { default-features = false, optional = true, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.10' }
 
 [features]
 default = ["std"]
@@ -27,5 +28,10 @@
     "sp-std/std",
     "nft-data-structs/std",
     "pallet-common/std",
+    'frame-benchmarking/std',
+]
+runtime-benchmarks = [
+    'frame-benchmarking',
+    'frame-support/runtime-benchmarks',
+    'frame-system/runtime-benchmarks',
 ]
-runtime-benchmarks = []
modifiedpallets/refungible/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/refungible/src/benchmarking.rs
+++ b/pallets/refungible/src/benchmarking.rs
@@ -1 +1,161 @@
-#![cfg(feature = "runtime-benchmarking")]
+use super::*;
+use crate::{Pallet, Config, RefungibleHandle};
+
+use sp_std::prelude::*;
+use pallet_common::benchmarking::{create_collection_raw, create_data};
+use frame_benchmarking::{benchmarks, account};
+use nft_data_structs::{CollectionMode, MAX_ITEMS_PER_BATCH};
+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 {
+		const_data,
+		variable_data,
+		users: users.into_iter().collect(),
+	}
+}
+fn create_max_item<T: Config>(
+	collection: &RefungibleHandle<T>,
+	sender: &T::CrossAccountId,
+	users: impl IntoIterator<Item = (T::CrossAccountId, u128)>,
+) -> Result<TokenId, DispatchError> {
+	<Pallet<T>>::create_item(&collection, sender, create_max_item_data(users))?;
+	Ok(TokenId(<TokensMinted<T>>::get(&collection.id)))
+}
+
+fn create_collection<T: Config>(owner: T::AccountId) -> Result<RefungibleHandle<T>, DispatchError> {
+	create_collection_raw(
+		owner,
+		CollectionMode::NFT,
+		<Pallet<T>>::init_collection,
+		RefungibleHandle::cast,
+	)
+}
+benchmarks! {
+	create_item {
+		bench_init!{
+			owner: sub; collection: collection(owner);
+			sender: cross_from_sub(owner); to: cross_sub;
+		};
+	}: {create_max_item(&collection, &sender, [(to.clone(), 200)])?}
+
+	create_multiple_items {
+		let b in 0..MAX_ITEMS_PER_BATCH;
+		bench_init!{
+			owner: sub; collection: collection(owner);
+			sender: cross_from_sub(owner); to: cross_sub;
+		};
+		let data = (0..b).map(|_| create_max_item_data([(to.clone(), 200)])).collect();
+	}: {<Pallet<T>>::create_multiple_items(&collection, &sender, data)?}
+
+	// Other user left, token data is kept
+	burn_item_partial {
+		bench_init!{
+			owner: sub; collection: collection(owner);
+			sender: cross_from_sub(owner); burner: cross_sub; another_owner: cross_sub;
+		};
+		let item = create_max_item(&collection, &sender, [(burner.clone(), 200), (another_owner, 200)])?;
+	}: {<Pallet<T>>::burn(&collection, &burner, item, 200)?}
+	// No users remaining, token is destroyed
+	burn_item_fully {
+		bench_init!{
+			owner: sub; collection: collection(owner);
+			sender: cross_from_sub(owner); burner: cross_sub; another_owner: cross_sub;
+		};
+		let item = create_max_item(&collection, &sender, [(burner.clone(), 200)])?;
+	}: {<Pallet<T>>::burn(&collection, &burner, item, 200)?}
+
+	transfer_normal {
+		bench_init!{
+			owner: sub; collection: collection(owner);
+			sender: cross_from_sub(owner); receiver: cross_sub;
+		};
+		let item = create_max_item(&collection, &sender, [(sender.clone(), 200), (receiver.clone(), 200)])?;
+	}: {<Pallet<T>>::transfer(&collection, &sender, &receiver, item, 100)?}
+	// Target account is created
+	transfer_creating {
+		bench_init!{
+			owner: sub; collection: collection(owner);
+			sender: cross_from_sub(owner); receiver: cross_sub;
+		};
+		let item = create_max_item(&collection, &sender, [(sender.clone(), 200)])?;
+	}: {<Pallet<T>>::transfer(&collection, &sender, &receiver, item, 100)?}
+	// Source account is destroyed
+	transfer_removing {
+		bench_init!{
+			owner: sub; collection: collection(owner);
+			sender: cross_from_sub(owner); receiver: cross_sub;
+		};
+		let item = create_max_item(&collection, &sender, [(sender.clone(), 200), (receiver.clone(), 200)])?;
+	}: {<Pallet<T>>::transfer(&collection, &sender, &receiver, item, 200)?}
+	// Source account destroyed, target created
+	transfer_creating_removing {
+		bench_init!{
+			owner: sub; collection: collection(owner);
+			sender: cross_from_sub(owner); receiver: cross_sub;
+		};
+		let item = create_max_item(&collection, &sender, [(sender.clone(), 200)])?;
+	}: {<Pallet<T>>::transfer(&collection, &sender, &receiver, item, 200)?}
+
+	approve {
+		bench_init!{
+			owner: sub; collection: collection(owner);
+			owner: cross_from_sub; sender: cross_sub; spender: cross_sub;
+		};
+		let item = create_max_item(&collection, &owner, [(sender.clone(), 200)])?;
+	}: {<Pallet<T>>::set_allowance(&collection, &sender, &spender, item, 100)?}
+
+	transfer_from_normal {
+		bench_init!{
+			owner: sub; collection: collection(owner);
+			owner: cross_from_sub; sender: cross_sub; spender: cross_sub; receiver: cross_sub;
+		};
+		let item = create_max_item(&collection, &owner, [(sender.clone(), 200), (receiver.clone(), 200)])?;
+		<Pallet<T>>::set_allowance(&collection, &sender, &spender, item, 100)?;
+	}: {<Pallet<T>>::transfer_from(&collection, &spender, &sender, &receiver, item, 100)?}
+	// Target account is created
+	transfer_from_creating {
+		bench_init!{
+			owner: sub; collection: collection(owner);
+			owner: cross_from_sub; sender: cross_sub; spender: cross_sub; receiver: cross_sub;
+		};
+		let item = create_max_item(&collection, &owner, [(sender.clone(), 200)])?;
+		<Pallet<T>>::set_allowance(&collection, &sender, &spender, item, 100)?;
+	}: {<Pallet<T>>::transfer_from(&collection, &spender, &sender, &receiver, item, 100)?}
+	// Source account is destroyed
+	transfer_from_removing {
+		bench_init!{
+			owner: sub; collection: collection(owner);
+			owner: cross_from_sub; sender: cross_sub; spender: cross_sub; receiver: cross_sub;
+		};
+		let item = create_max_item(&collection, &owner, [(sender.clone(), 200), (receiver.clone(), 200)])?;
+		<Pallet<T>>::set_allowance(&collection, &sender, &spender, item, 200)?;
+	}: {<Pallet<T>>::transfer_from(&collection, &spender, &sender, &receiver, item, 200)?}
+	// Source account destroyed, target created
+	transfer_from_creating_removing {
+		bench_init!{
+			owner: sub; collection: collection(owner);
+			owner: cross_from_sub; sender: cross_sub; spender: cross_sub; receiver: cross_sub;
+		};
+		let item = create_max_item(&collection, &owner, [(sender.clone(), 200)])?;
+		<Pallet<T>>::set_allowance(&collection, &sender, &spender, item, 200)?;
+	}: {<Pallet<T>>::transfer_from(&collection, &spender, &sender, &receiver, item, 200)?}
+
+	set_variable_metadata {
+		let b in 0..CUSTOM_DATA_LIMIT;
+		bench_init!{
+			owner: sub; collection: collection(owner);
+			sender: cross_from_sub(owner);
+		};
+		let item = create_max_item(&collection, &sender, [(sender.clone(), 200)])?;
+		let data = create_data(b as usize);
+	}: {<Pallet<T>>::set_variable_metadata(&collection, &sender, item, data)?}
+}
modifiedpallets/refungible/src/common.rsdiffbeforeafterboth
--- a/pallets/refungible/src/common.rs
+++ b/pallets/refungible/src/common.rs
@@ -14,6 +14,15 @@
 	RefungibleHandle, SelfWeightOf, TokenData, weights::WeightInfo, TokensMinted,
 };
 
+macro_rules! max_weight_of {
+	($($method:ident ($($args:tt)*)),*) => {
+		0
+		$(
+			.max(<SelfWeightOf<T>>::$method($($args)*))
+		)*
+	};
+}
+
 pub struct CommonWeights<T: Config>(PhantomData<T>);
 impl<T: Config> CommonWeightInfo for CommonWeights<T> {
 	fn create_item() -> Weight {
@@ -25,11 +34,16 @@
 	}
 
 	fn burn_item() -> Weight {
-		<SelfWeightOf<T>>::burn_item()
+		max_weight_of!(burn_item_partial(), burn_item_fully())
 	}
 
 	fn transfer() -> Weight {
-		<SelfWeightOf<T>>::transfer()
+		max_weight_of!(
+			transfer_normal(),
+			transfer_creating(),
+			transfer_removing(),
+			transfer_creating_removing()
+		)
 	}
 
 	fn approve() -> Weight {
@@ -37,11 +51,16 @@
 	}
 
 	fn transfer_from() -> Weight {
-		<SelfWeightOf<T>>::transfer_from()
+		max_weight_of!(
+			transfer_from_normal(),
+			transfer_from_creating(),
+			transfer_from_removing(),
+			transfer_from_creating_removing()
+		)
 	}
 
-	fn set_variable_metadata(_bytes: u32) -> Weight {
-		<SelfWeightOf<T>>::set_variable_metadata()
+	fn set_variable_metadata(bytes: u32) -> Weight {
+		<SelfWeightOf<T>>::set_variable_metadata(bytes)
 	}
 }
 
@@ -72,7 +91,7 @@
 	) -> DispatchResultWithPostInfo {
 		with_weight(
 			<Pallet<T>>::create_item(self, &sender, map_create_data(data, &to)?),
-			<SelfWeightOf<T>>::create_item(),
+			<CommonWeights<T>>::create_item(),
 		)
 	}
 
@@ -90,7 +109,7 @@
 		let amount = data.len();
 		with_weight(
 			<Pallet<T>>::create_multiple_items(self, &sender, data),
-			<SelfWeightOf<T>>::create_multiple_items(amount as u32),
+			<CommonWeights<T>>::create_multiple_items(amount as u32),
 		)
 	}
 
@@ -102,7 +121,7 @@
 	) -> DispatchResultWithPostInfo {
 		with_weight(
 			<Pallet<T>>::burn(self, &sender, token, amount),
-			<SelfWeightOf<T>>::burn_item(),
+			<CommonWeights<T>>::burn_item(),
 		)
 	}
 
@@ -115,7 +134,7 @@
 	) -> DispatchResultWithPostInfo {
 		with_weight(
 			<Pallet<T>>::transfer(&self, &from, &to, token, amount),
-			<SelfWeightOf<T>>::transfer(),
+			<CommonWeights<T>>::transfer(),
 		)
 	}
 
@@ -128,7 +147,7 @@
 	) -> DispatchResultWithPostInfo {
 		with_weight(
 			<Pallet<T>>::set_allowance(&self, &sender, &spender, token, amount),
-			<SelfWeightOf<T>>::approve(),
+			<CommonWeights<T>>::approve(),
 		)
 	}
 
@@ -142,7 +161,7 @@
 	) -> DispatchResultWithPostInfo {
 		with_weight(
 			<Pallet<T>>::transfer_from(&self, &sender, &from, &to, token, amount),
-			<SelfWeightOf<T>>::approve(),
+			<CommonWeights<T>>::approve(),
 		)
 	}
 
@@ -152,9 +171,10 @@
 		token: TokenId,
 		data: Vec<u8>,
 	) -> DispatchResultWithPostInfo {
+		let len = data.len();
 		with_weight(
 			<Pallet<T>>::set_variable_metadata(&self, &sender, token, data),
-			<SelfWeightOf<T>>::set_variable_metadata(),
+			<CommonWeights<T>>::set_variable_metadata(len as u32),
 		)
 	}
 
modifiedpallets/refungible/src/lib.rsdiffbeforeafterboth
after · pallets/refungible/src/lib.rs
1#![cfg_attr(not(feature = "std"), no_std)]23use frame_support::{ensure, BoundedVec};4use nft_data_structs::{5	AccessMode, CUSTOM_DATA_LIMIT, Collection, CollectionId, CustomDataLimit,6	MAX_REFUNGIBLE_PIECES, TokenId,7};8use pallet_common::{9	Error as CommonError, Event as CommonEvent, Pallet as PalletCommon, account::CrossAccountId,10};11use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};12use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};13use core::ops::Deref;14use codec::{Encode, Decode};1516pub use pallet::*;17#[cfg(feature = "runtime-benchmarks")]18pub mod benchmarking;19pub mod common;20pub mod erc;21pub mod weights;22pub struct CreateItemData<T: Config> {23	pub const_data: BoundedVec<u8, CustomDataLimit>,24	pub variable_data: BoundedVec<u8, CustomDataLimit>,25	pub users: BTreeMap<T::CrossAccountId, u128>,26}27pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;2829#[derive(Encode, Decode, Default)]30pub struct ItemData {31	pub const_data: Vec<u8>,32	pub variable_data: Vec<u8>,33}3435#[frame_support::pallet]36pub mod pallet {37	use super::*;38	use frame_support::{Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};39	use nft_data_structs::{CollectionId, TokenId};40	use super::weights::WeightInfo;4142	#[pallet::error]43	pub enum Error<T> {44		/// Not Refungible item data used to mint in Refungible collection.45		NotRefungibleDataUsedToMintFungibleCollectionToken,46		/// Maximum refungibility exceeded47		WrongRefungiblePieces,48	}4950	#[pallet::config]51	pub trait Config: frame_system::Config + pallet_common::Config {52		type WeightInfo: WeightInfo;53	}5455	#[pallet::pallet]56	#[pallet::generate_store(pub(super) trait Store)]57	pub struct Pallet<T>(_);5859	#[pallet::storage]60	pub(super) type TokensMinted<T: Config> =61		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;62	#[pallet::storage]63	pub(super) type TokensBurnt<T: Config> =64		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;6566	#[pallet::storage]67	pub(super) type TokenData<T: Config> = StorageNMap<68		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),69		Value = ItemData,70		QueryKind = ValueQuery,71	>;7273	#[pallet::storage]74	pub(super) type TotalSupply<T: Config> = StorageNMap<75		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),76		Value = u128,77		QueryKind = ValueQuery,78	>;7980	/// Used to enumerate tokens owned by account81	#[pallet::storage]82	pub(super) type Owned<T: Config> = StorageNMap<83		Key = (84			Key<Twox64Concat, CollectionId>,85			Key<Blake2_128Concat, T::AccountId>,86			Key<Twox64Concat, TokenId>,87		),88		Value = bool,89		QueryKind = ValueQuery,90	>;9192	#[pallet::storage]93	pub(super) type AccountBalance<T: Config> = StorageNMap<94		Key = (95			Key<Twox64Concat, CollectionId>,96			// Owner97			Key<Blake2_128Concat, T::AccountId>,98		),99		Value = u32,100		QueryKind = ValueQuery,101	>;102103	#[pallet::storage]104	pub(super) type Balance<T: Config> = StorageNMap<105		Key = (106			Key<Twox64Concat, CollectionId>,107			Key<Twox64Concat, TokenId>,108			// Owner109			Key<Blake2_128Concat, T::AccountId>,110		),111		Value = u128,112		QueryKind = ValueQuery,113	>;114115	#[pallet::storage]116	pub(super) type Allowance<T: Config> = StorageNMap<117		Key = (118			Key<Twox64Concat, CollectionId>,119			Key<Twox64Concat, TokenId>,120			// Owner121			Key<Blake2_128, T::AccountId>,122			// Spender123			Key<Blake2_128Concat, T::CrossAccountId>,124		),125		Value = u128,126		QueryKind = ValueQuery,127	>;128}129130pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);131impl<T: Config> RefungibleHandle<T> {132	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {133		Self(inner)134	}135	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {136		self.0137	}138}139impl<T: Config> Deref for RefungibleHandle<T> {140	type Target = pallet_common::CollectionHandle<T>;141142	fn deref(&self) -> &Self::Target {143		&self.0144	}145}146147impl<T: Config> Pallet<T> {148	pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {149		<TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)150	}151	pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {152		<TotalSupply<T>>::contains_key((collection.id, token))153	}154}155156// unchecked calls skips any permission checks157impl<T: Config> Pallet<T> {158	pub fn init_collection(data: Collection<T>) -> Result<CollectionId, DispatchError> {159		PalletCommon::init_collection(data)160	}161	pub fn destroy_collection(162		collection: RefungibleHandle<T>,163		sender: &T::CrossAccountId,164	) -> DispatchResult {165		let id = collection.id;166167		// =========168169		PalletCommon::destroy_collection(collection.0, sender)?;170171		<TokensMinted<T>>::remove(id);172		<TokensBurnt<T>>::remove(id);173		<TokenData<T>>::remove_prefix((id,), None);174		<TotalSupply<T>>::remove_prefix((id,), None);175		<Balance<T>>::remove_prefix((id,), None);176		<Allowance<T>>::remove_prefix((id,), None);177		Ok(())178	}179180	pub fn burn_token(collection: &RefungibleHandle<T>, token_id: TokenId) -> DispatchResult {181		let burnt = <TokensBurnt<T>>::get(collection.id)182			.checked_add(1)183			.ok_or(ArithmeticError::Overflow)?;184185		<TokensBurnt<T>>::insert(collection.id, burnt);186		<TokenData<T>>::remove((collection.id, token_id));187		<TotalSupply<T>>::remove((collection.id, token_id));188		<Balance<T>>::remove_prefix((collection.id, token_id), None);189		<Allowance<T>>::remove_prefix((collection.id, token_id), None);190		// TODO: ERC721 transfer event191		return Ok(());192	}193194	pub fn burn(195		collection: &RefungibleHandle<T>,196		owner: &T::CrossAccountId,197		token: TokenId,198		amount: u128,199	) -> DispatchResult {200		let total_supply = <TotalSupply<T>>::get((collection.id, token))201			.checked_sub(amount)202			.ok_or(<CommonError<T>>::TokenValueTooLow)?;203204		// This was probally last owner of this token?205		if total_supply == 0 {206			// Ensure user actually owns this amount207			ensure!(208				<Balance<T>>::get((collection.id, token, owner.as_sub())) == amount,209				<CommonError<T>>::TokenValueTooLow210			);211			let account_balance = <AccountBalance<T>>::get((collection.id, owner.as_sub()))212				.checked_sub(1)213				// Should not occur214				.ok_or(ArithmeticError::Underflow)?;215216			// =========217218			<Owned<T>>::remove((collection.id, owner.as_sub(), token));219			<AccountBalance<T>>::insert((collection.id, owner.as_sub()), account_balance);220			Self::burn_token(collection, token)?;221			<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(222				collection.id,223				token,224				owner.clone(),225				amount,226			));227			return Ok(());228		}229230		let balance = <Balance<T>>::get((collection.id, token, owner.as_sub()))231			.checked_sub(amount)232			.ok_or(<CommonError<T>>::TokenValueTooLow)?;233		let account_balance = if balance == 0 {234			<AccountBalance<T>>::get((collection.id, owner.as_sub()))235				.checked_sub(1)236				// Should not occur237				.ok_or(ArithmeticError::Underflow)?238		} else {239			0240		};241242		// =========243244		if balance == 0 {245			<Owned<T>>::remove((collection.id, owner.as_sub(), token));246			<Balance<T>>::remove((collection.id, token, owner.as_sub()));247			<AccountBalance<T>>::insert((collection.id, owner.as_sub()), account_balance);248		} else {249			<Balance<T>>::insert((collection.id, token, owner.as_sub()), balance);250		}251		<TotalSupply<T>>::insert((collection.id, token), total_supply);252		// TODO: ERC20 transfer event253		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(254			collection.id,255			token,256			owner.clone(),257			amount,258		));259		Ok(())260	}261262	pub fn transfer(263		collection: &RefungibleHandle<T>,264		from: &T::CrossAccountId,265		to: &T::CrossAccountId,266		token: TokenId,267		amount: u128,268	) -> DispatchResult {269		ensure!(270			collection.transfers_enabled,271			<CommonError<T>>::TransferNotAllowed272		);273274		if collection.access == AccessMode::WhiteList {275			collection.check_allowlist(from)?;276			collection.check_allowlist(to)?;277		}278		<PalletCommon<T>>::ensure_correct_receiver(to)?;279280		let balance_from = <Balance<T>>::get((collection.id, token, from.as_sub()))281			.checked_sub(amount)282			.ok_or(<CommonError<T>>::TokenValueTooLow)?;283		let mut create_target = false;284		let from_to_differ = from != to;285		let balance_to = if from != to {286			let old_balance = <Balance<T>>::get((collection.id, token, to.as_sub()));287			if old_balance == 0 {288				create_target = true;289			}290			Some(291				old_balance292					.checked_add(amount)293					.ok_or(ArithmeticError::Overflow)?,294			)295		} else {296			None297		};298299		let account_balance_from = if balance_from == 0 {300			Some(301				<AccountBalance<T>>::get((collection.id, from.as_sub()))302					.checked_sub(1)303					// Should not occur304					.ok_or(ArithmeticError::Underflow)?,305			)306		} else {307			None308		};309		// Account data is created in token, AccountBalance should be increased310		// But only if from != to as we shouldn't check overflow in this case311		let account_balance_to = if create_target && from_to_differ {312			let account_balance_to = <AccountBalance<T>>::get((collection.id, to.as_sub()))313				.checked_add(1)314				.ok_or(ArithmeticError::Overflow)?;315			ensure!(316				account_balance_to < collection.limits.account_token_ownership_limit(),317				<CommonError<T>>::AccountTokenLimitExceeded,318			);319320			Some(account_balance_to)321		} else {322			None323		};324325		// =========326327		if let Some(balance_to) = balance_to {328			// from != to329			if balance_from == 0 {330				<Balance<T>>::remove((collection.id, token, from.as_sub()));331			} else {332				<Balance<T>>::insert((collection.id, token, from.as_sub()), balance_from);333			}334			<Balance<T>>::insert((collection.id, token, to.as_sub()), balance_to);335			if let Some(account_balance_from) = account_balance_from {336				<AccountBalance<T>>::insert((collection.id, from.as_sub()), account_balance_from);337				<Owned<T>>::remove((collection.id, from.as_sub(), token));338			}339			if let Some(account_balance_to) = account_balance_to {340				<AccountBalance<T>>::insert((collection.id, to.as_sub()), account_balance_to);341				<Owned<T>>::insert((collection.id, to.as_sub(), token), true);342			}343		}344345		// TODO: ERC20 transfer event346		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(347			collection.id,348			token,349			from.clone(),350			to.clone(),351			amount,352		));353		Ok(())354	}355356	pub fn create_multiple_items(357		collection: &RefungibleHandle<T>,358		sender: &T::CrossAccountId,359		data: Vec<CreateItemData<T>>,360	) -> DispatchResult {361		let unrestricted_minting = collection.is_owner_or_admin(sender)?;362		if !unrestricted_minting {363			ensure!(364				collection.mint_mode,365				<CommonError<T>>::PublicMintingNotAllowed366			);367			collection.check_allowlist(sender)?;368369			for item in data.iter() {370				for (user, _) in &item.users {371					collection.check_allowlist(&user)?;372				}373			}374		}375376		for item in data.iter() {377			for (owner, _) in item.users.iter() {378				<PalletCommon<T>>::ensure_correct_receiver(owner)?;379			}380		}381382		// Total pieces per tokens383		let totals = data384			.iter()385			.map(|data| {386				Ok(data387					.users388					.iter()389					.map(|u| u.1)390					.try_fold(0u128, |acc, v| acc.checked_add(*v))391					.ok_or(ArithmeticError::Overflow)?)392			})393			.collect::<Result<Vec<_>, DispatchError>>()?;394		for total in &totals {395			ensure!(396				*total <= MAX_REFUNGIBLE_PIECES,397				<Error<T>>::WrongRefungiblePieces398			);399		}400401		let first_token_id = <TokensMinted<T>>::get(collection.id);402		let tokens_minted = first_token_id403			.checked_add(data.len() as u32)404			.ok_or(ArithmeticError::Overflow)?;405		ensure!(406			tokens_minted < collection.limits.token_limit,407			<CommonError<T>>::CollectionTokenLimitExceeded408		);409410		let mut balances = BTreeMap::new();411		for data in &data {412			for (owner, _) in &data.users {413				let balance = balances414					.entry(owner.as_sub())415					.or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner.as_sub())));416				*balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;417418				ensure!(419					*balance <= collection.limits.account_token_ownership_limit(),420					<CommonError<T>>::AccountTokenLimitExceeded,421				);422			}423		}424425		// =========426427		<TokensMinted<T>>::insert(collection.id, tokens_minted);428		for (account, balance) in balances {429			<AccountBalance<T>>::insert((collection.id, account), balance);430		}431		for (i, token) in data.into_iter().enumerate() {432			let token_id = first_token_id + i as u32 + 1;433			<TotalSupply<T>>::insert((collection.id, token_id), totals[i]);434435			<TokenData<T>>::insert(436				(collection.id, token_id),437				ItemData {438					const_data: token.const_data.into(),439					variable_data: token.variable_data.into(),440				},441			);442			for (user, amount) in token.users.into_iter() {443				if amount == 0 {444					continue;445				}446				<Balance<T>>::insert((collection.id, token_id, user.as_sub()), amount);447				<Owned<T>>::insert((collection.id, user.as_sub(), TokenId(token_id)), true);448				// TODO: ERC20 transfer event449				<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(450					collection.id,451					TokenId(token_id),452					user,453					amount,454				));455			}456		}457		Ok(())458	}459460	pub fn set_allowance_unchecked(461		collection: &RefungibleHandle<T>,462		sender: &T::CrossAccountId,463		spender: &T::CrossAccountId,464		token: TokenId,465		amount: u128,466	) {467		<Allowance<T>>::insert((collection.id, token, sender.as_sub(), spender), amount);468		// TODO: ERC20 approval event469		<PalletCommon<T>>::deposit_event(CommonEvent::Approved(470			collection.id,471			token,472			sender.clone(),473			spender.clone(),474			amount,475		))476	}477478	pub fn set_allowance(479		collection: &RefungibleHandle<T>,480		sender: &T::CrossAccountId,481		spender: &T::CrossAccountId,482		token: TokenId,483		amount: u128,484	) -> DispatchResult {485		if collection.access == AccessMode::WhiteList {486			collection.check_allowlist(&sender)?;487			collection.check_allowlist(&spender)?;488		}489490		<PalletCommon<T>>::ensure_correct_receiver(spender)?;491492		if <Balance<T>>::get((collection.id, token, sender.as_sub())) < amount {493			ensure!(494				collection.ignores_owned_amount(sender)?,495				<CommonError<T>>::CantApproveMoreThanOwned496			);497		}498499		// =========500501		Self::set_allowance_unchecked(collection, sender, spender, token, amount);502		Ok(())503	}504505	pub fn transfer_from(506		collection: &RefungibleHandle<T>,507		spender: &T::CrossAccountId,508		from: &T::CrossAccountId,509		to: &T::CrossAccountId,510		token: TokenId,511		amount: u128,512	) -> DispatchResult {513		if spender == from {514			return Self::transfer(collection, from, to, token, amount);515		}516		if collection.access == AccessMode::WhiteList {517			// `from`, `to` checked in [`transfer`]518			collection.check_allowlist(spender)?;519		}520521		let allowance = <Allowance<T>>::get((collection.id, token, from.as_sub(), &spender))522			.checked_sub(amount);523		if allowance.is_none() {524			ensure!(525				collection.ignores_allowance(spender)?,526				<CommonError<T>>::TokenValueNotEnough527			);528		}529530		// =========531532		Self::transfer(collection, from, to, token, amount)?;533		if let Some(allowance) = allowance {534			Self::set_allowance_unchecked(collection, from, spender, token, allowance);535		}536		Ok(())537	}538539	pub fn set_variable_metadata(540		collection: &RefungibleHandle<T>,541		sender: &T::CrossAccountId,542		token: TokenId,543		data: Vec<u8>,544	) -> DispatchResult {545		ensure!(546			data.len() as u32 <= CUSTOM_DATA_LIMIT,547			<CommonError<T>>::TokenVariableDataLimitExceeded548		);549		collection.check_can_update_meta(550			sender,551			&T::CrossAccountId::from_sub(collection.owner.clone()),552		)?;553554		collection.consume_sstore()?;555		let token_data = <TokenData<T>>::get((collection.id, token));556557		// =========558559		<TokenData<T>>::insert(560			(collection.id, token),561			ItemData {562				variable_data: data,563				..token_data564			},565		);566		Ok(())567	}568569	/// Delegated to `create_multiple_items`570	pub fn create_item(571		collection: &RefungibleHandle<T>,572		sender: &T::CrossAccountId,573		data: CreateItemData<T>,574	) -> DispatchResult {575		Self::create_multiple_items(collection, sender, vec![data])576	}577}
modifiedpallets/refungible/src/weights.rsdiffbeforeafterboth
--- a/pallets/refungible/src/weights.rs
+++ b/pallets/refungible/src/weights.rs
@@ -1,3 +1,27 @@
+// Template adopted from https://github.com/paritytech/substrate/blob/master/.maintain/frame-weight-template.hbs
+
+//! Autogenerated weights for pallet_refungible
+//!
+//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev
+//! DATE: 2021-10-21, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]`
+//! EXECUTION: None, WASM-EXECUTION: Compiled, CHAIN: None, DB CACHE: 128
+
+// Executed Command:
+// target/release/nft
+// benchmark
+// --pallet
+// pallet-refungible
+// --wasm-execution
+// compiled
+// --extrinsic
+// *
+// --template
+// .maintain/frame-weight-template.hbs
+// --steps=50
+// --repeat=20
+// --output=./pallets/refungible/src/weights.rs
+
+
 #![cfg_attr(rustfmt, rustfmt_skip)]
 #![allow(unused_parens)]
 #![allow(unused_imports)]
@@ -5,33 +29,273 @@
 use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}};
 use sp_std::marker::PhantomData;
 
+/// Weight functions needed for pallet_refungible.
 pub trait WeightInfo {
 	fn create_item() -> Weight;
-	fn create_multiple_items(b: u32) -> Weight;
-	fn burn_item() -> Weight;
-	fn transfer() -> Weight;
+	fn create_multiple_items(b: u32, ) -> Weight;
+	fn burn_item_partial() -> Weight;
+	fn burn_item_fully() -> Weight;
+	fn transfer_normal() -> Weight;
+	fn transfer_creating() -> Weight;
+	fn transfer_removing() -> Weight;
+	fn transfer_creating_removing() -> Weight;
 	fn approve() -> Weight;
-	fn transfer_from() -> Weight;
-	fn set_variable_metadata() -> Weight;
+	fn transfer_from_normal() -> Weight;
+	fn transfer_from_creating() -> Weight;
+	fn transfer_from_removing() -> Weight;
+	fn transfer_from_creating_removing() -> Weight;
+	fn set_variable_metadata(b: u32, ) -> Weight;
 }
 
+/// Weights for pallet_refungible using the Substrate node and recommended hardware.
 pub struct SubstrateWeight<T>(PhantomData<T>);
 impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
-    fn create_item() -> Weight {0}
-	fn create_multiple_items(_b: u32) -> Weight {0}
-	fn burn_item() -> Weight {0}
-	fn transfer() -> Weight {0}
-	fn approve() -> Weight {0}
-	fn transfer_from() -> Weight {0}
-	fn set_variable_metadata() -> Weight {0}
+	// Storage: Refungible TokensMinted (r:1 w:1)
+	// Storage: Refungible AccountBalance (r:1 w:1)
+	// Storage: Refungible Balance (r:0 w:1)
+	// Storage: Refungible TotalSupply (r:0 w:1)
+	// Storage: Refungible TokenData (r:0 w:1)
+	// Storage: Refungible Owned (r:0 w:1)
+	fn create_item() -> Weight {
+		(18_681_000 as Weight)
+			.saturating_add(T::DbWeight::get().reads(2 as Weight))
+			.saturating_add(T::DbWeight::get().writes(6 as Weight))
+	}
+	// Storage: Refungible TokensMinted (r:1 w:1)
+	// Storage: Refungible AccountBalance (r:1 w:1)
+	// Storage: Refungible Balance (r:0 w:4)
+	// Storage: Refungible TotalSupply (r:0 w:4)
+	// Storage: Refungible TokenData (r:0 w:4)
+	// Storage: Refungible Owned (r:0 w:4)
+	fn create_multiple_items(b: u32, ) -> Weight {
+		(13_869_000 as Weight)
+			// Standard Error: 28_000
+			.saturating_add((5_611_000 as Weight).saturating_mul(b as Weight))
+			.saturating_add(T::DbWeight::get().reads(2 as Weight))
+			.saturating_add(T::DbWeight::get().writes(2 as Weight))
+			.saturating_add(T::DbWeight::get().writes((4 as Weight).saturating_mul(b as Weight)))
+	}
+	// Storage: Refungible TotalSupply (r:1 w:1)
+	// Storage: Refungible Balance (r:1 w:1)
+	// Storage: Refungible AccountBalance (r:1 w:1)
+	// Storage: Refungible Owned (r:0 w:1)
+	fn burn_item_partial() -> Weight {
+		(21_591_000 as Weight)
+			.saturating_add(T::DbWeight::get().reads(3 as Weight))
+			.saturating_add(T::DbWeight::get().writes(4 as Weight))
+	}
+	// Storage: Refungible TotalSupply (r:1 w:1)
+	// Storage: Refungible Balance (r:1 w:1)
+	// Storage: Refungible AccountBalance (r:1 w:1)
+	// Storage: Refungible TokensBurnt (r:1 w:1)
+	// Storage: Refungible TokenData (r:0 w:1)
+	// Storage: Refungible Owned (r:0 w:1)
+	fn burn_item_fully() -> Weight {
+		(29_257_000 as Weight)
+			.saturating_add(T::DbWeight::get().reads(4 as Weight))
+			.saturating_add(T::DbWeight::get().writes(6 as Weight))
+	}
+	// Storage: Refungible Balance (r:2 w:2)
+	fn transfer_normal() -> Weight {
+		(17_733_000 as Weight)
+			.saturating_add(T::DbWeight::get().reads(2 as Weight))
+			.saturating_add(T::DbWeight::get().writes(2 as Weight))
+	}
+	// Storage: Refungible Balance (r:2 w:2)
+	// Storage: Refungible AccountBalance (r:1 w:1)
+	// Storage: Refungible Owned (r:0 w:1)
+	fn transfer_creating() -> Weight {
+		(20_943_000 as Weight)
+			.saturating_add(T::DbWeight::get().reads(3 as Weight))
+			.saturating_add(T::DbWeight::get().writes(4 as Weight))
+	}
+	// Storage: Refungible Balance (r:2 w:2)
+	// Storage: Refungible AccountBalance (r:1 w:1)
+	// Storage: Refungible Owned (r:0 w:1)
+	fn transfer_removing() -> Weight {
+		(22_406_000 as Weight)
+			.saturating_add(T::DbWeight::get().reads(3 as Weight))
+			.saturating_add(T::DbWeight::get().writes(4 as Weight))
+	}
+	// Storage: Refungible Balance (r:2 w:2)
+	// Storage: Refungible AccountBalance (r:2 w:2)
+	// Storage: Refungible Owned (r:0 w:2)
+	fn transfer_creating_removing() -> Weight {
+		(24_762_000 as Weight)
+			.saturating_add(T::DbWeight::get().reads(4 as Weight))
+			.saturating_add(T::DbWeight::get().writes(6 as Weight))
+	}
+	// Storage: Refungible Balance (r:1 w:0)
+	// Storage: Refungible Allowance (r:0 w:1)
+	fn approve() -> Weight {
+		(14_109_000 as Weight)
+			.saturating_add(T::DbWeight::get().reads(1 as Weight))
+			.saturating_add(T::DbWeight::get().writes(1 as Weight))
+	}
+	// Storage: Refungible Allowance (r:1 w:1)
+	// Storage: Refungible Balance (r:2 w:2)
+	fn transfer_from_normal() -> Weight {
+		(25_348_000 as Weight)
+			.saturating_add(T::DbWeight::get().reads(3 as Weight))
+			.saturating_add(T::DbWeight::get().writes(3 as Weight))
+	}
+	// Storage: Refungible Allowance (r:1 w:1)
+	// Storage: Refungible Balance (r:2 w:2)
+	// Storage: Refungible AccountBalance (r:1 w:1)
+	// Storage: Refungible Owned (r:0 w:1)
+	fn transfer_from_creating() -> Weight {
+		(28_647_000 as Weight)
+			.saturating_add(T::DbWeight::get().reads(4 as Weight))
+			.saturating_add(T::DbWeight::get().writes(5 as Weight))
+	}
+	// Storage: Refungible Allowance (r:1 w:1)
+	// Storage: Refungible Balance (r:2 w:2)
+	// Storage: Refungible AccountBalance (r:1 w:1)
+	// Storage: Refungible Owned (r:0 w:1)
+	fn transfer_from_removing() -> Weight {
+		(30_472_000 as Weight)
+			.saturating_add(T::DbWeight::get().reads(4 as Weight))
+			.saturating_add(T::DbWeight::get().writes(5 as Weight))
+	}
+	// Storage: Refungible Allowance (r:1 w:1)
+	// Storage: Refungible Balance (r:2 w:2)
+	// Storage: Refungible AccountBalance (r:2 w:2)
+	// Storage: Refungible Owned (r:0 w:2)
+	fn transfer_from_creating_removing() -> Weight {
+		(32_362_000 as Weight)
+			.saturating_add(T::DbWeight::get().reads(5 as Weight))
+			.saturating_add(T::DbWeight::get().writes(7 as Weight))
+	}
+	// Storage: Refungible TokenData (r:1 w:1)
+	fn set_variable_metadata(_b: u32, ) -> Weight {
+		(6_801_000 as Weight)
+			.saturating_add(T::DbWeight::get().reads(1 as Weight))
+			.saturating_add(T::DbWeight::get().writes(1 as Weight))
+	}
 }
 
+// For backwards compatibility and tests
 impl WeightInfo for () {
-    fn create_item() -> Weight {0}
-	fn create_multiple_items(_b: u32) -> Weight {0}
-	fn burn_item() -> Weight {0}
-	fn transfer() -> Weight {0}
-	fn approve() -> Weight {0}
-	fn transfer_from() -> Weight {0}
-	fn set_variable_metadata() -> Weight {0}
+	// Storage: Refungible TokensMinted (r:1 w:1)
+	// Storage: Refungible AccountBalance (r:1 w:1)
+	// Storage: Refungible Balance (r:0 w:1)
+	// Storage: Refungible TotalSupply (r:0 w:1)
+	// Storage: Refungible TokenData (r:0 w:1)
+	// Storage: Refungible Owned (r:0 w:1)
+	fn create_item() -> Weight {
+		(18_681_000 as Weight)
+			.saturating_add(RocksDbWeight::get().reads(2 as Weight))
+			.saturating_add(RocksDbWeight::get().writes(6 as Weight))
+	}
+	// Storage: Refungible TokensMinted (r:1 w:1)
+	// Storage: Refungible AccountBalance (r:1 w:1)
+	// Storage: Refungible Balance (r:0 w:4)
+	// Storage: Refungible TotalSupply (r:0 w:4)
+	// Storage: Refungible TokenData (r:0 w:4)
+	// Storage: Refungible Owned (r:0 w:4)
+	fn create_multiple_items(b: u32, ) -> Weight {
+		(13_869_000 as Weight)
+			// Standard Error: 28_000
+			.saturating_add((5_611_000 as Weight).saturating_mul(b as Weight))
+			.saturating_add(RocksDbWeight::get().reads(2 as Weight))
+			.saturating_add(RocksDbWeight::get().writes(2 as Weight))
+			.saturating_add(RocksDbWeight::get().writes((4 as Weight).saturating_mul(b as Weight)))
+	}
+	// Storage: Refungible TotalSupply (r:1 w:1)
+	// Storage: Refungible Balance (r:1 w:1)
+	// Storage: Refungible AccountBalance (r:1 w:1)
+	// Storage: Refungible Owned (r:0 w:1)
+	fn burn_item_partial() -> Weight {
+		(21_591_000 as Weight)
+			.saturating_add(RocksDbWeight::get().reads(3 as Weight))
+			.saturating_add(RocksDbWeight::get().writes(4 as Weight))
+	}
+	// Storage: Refungible TotalSupply (r:1 w:1)
+	// Storage: Refungible Balance (r:1 w:1)
+	// Storage: Refungible AccountBalance (r:1 w:1)
+	// Storage: Refungible TokensBurnt (r:1 w:1)
+	// Storage: Refungible TokenData (r:0 w:1)
+	// Storage: Refungible Owned (r:0 w:1)
+	fn burn_item_fully() -> Weight {
+		(29_257_000 as Weight)
+			.saturating_add(RocksDbWeight::get().reads(4 as Weight))
+			.saturating_add(RocksDbWeight::get().writes(6 as Weight))
+	}
+	// Storage: Refungible Balance (r:2 w:2)
+	fn transfer_normal() -> Weight {
+		(17_733_000 as Weight)
+			.saturating_add(RocksDbWeight::get().reads(2 as Weight))
+			.saturating_add(RocksDbWeight::get().writes(2 as Weight))
+	}
+	// Storage: Refungible Balance (r:2 w:2)
+	// Storage: Refungible AccountBalance (r:1 w:1)
+	// Storage: Refungible Owned (r:0 w:1)
+	fn transfer_creating() -> Weight {
+		(20_943_000 as Weight)
+			.saturating_add(RocksDbWeight::get().reads(3 as Weight))
+			.saturating_add(RocksDbWeight::get().writes(4 as Weight))
+	}
+	// Storage: Refungible Balance (r:2 w:2)
+	// Storage: Refungible AccountBalance (r:1 w:1)
+	// Storage: Refungible Owned (r:0 w:1)
+	fn transfer_removing() -> Weight {
+		(22_406_000 as Weight)
+			.saturating_add(RocksDbWeight::get().reads(3 as Weight))
+			.saturating_add(RocksDbWeight::get().writes(4 as Weight))
+	}
+	// Storage: Refungible Balance (r:2 w:2)
+	// Storage: Refungible AccountBalance (r:2 w:2)
+	// Storage: Refungible Owned (r:0 w:2)
+	fn transfer_creating_removing() -> Weight {
+		(24_762_000 as Weight)
+			.saturating_add(RocksDbWeight::get().reads(4 as Weight))
+			.saturating_add(RocksDbWeight::get().writes(6 as Weight))
+	}
+	// Storage: Refungible Balance (r:1 w:0)
+	// Storage: Refungible Allowance (r:0 w:1)
+	fn approve() -> Weight {
+		(14_109_000 as Weight)
+			.saturating_add(RocksDbWeight::get().reads(1 as Weight))
+			.saturating_add(RocksDbWeight::get().writes(1 as Weight))
+	}
+	// Storage: Refungible Allowance (r:1 w:1)
+	// Storage: Refungible Balance (r:2 w:2)
+	fn transfer_from_normal() -> Weight {
+		(25_348_000 as Weight)
+			.saturating_add(RocksDbWeight::get().reads(3 as Weight))
+			.saturating_add(RocksDbWeight::get().writes(3 as Weight))
+	}
+	// Storage: Refungible Allowance (r:1 w:1)
+	// Storage: Refungible Balance (r:2 w:2)
+	// Storage: Refungible AccountBalance (r:1 w:1)
+	// Storage: Refungible Owned (r:0 w:1)
+	fn transfer_from_creating() -> Weight {
+		(28_647_000 as Weight)
+			.saturating_add(RocksDbWeight::get().reads(4 as Weight))
+			.saturating_add(RocksDbWeight::get().writes(5 as Weight))
+	}
+	// Storage: Refungible Allowance (r:1 w:1)
+	// Storage: Refungible Balance (r:2 w:2)
+	// Storage: Refungible AccountBalance (r:1 w:1)
+	// Storage: Refungible Owned (r:0 w:1)
+	fn transfer_from_removing() -> Weight {
+		(30_472_000 as Weight)
+			.saturating_add(RocksDbWeight::get().reads(4 as Weight))
+			.saturating_add(RocksDbWeight::get().writes(5 as Weight))
+	}
+	// Storage: Refungible Allowance (r:1 w:1)
+	// Storage: Refungible Balance (r:2 w:2)
+	// Storage: Refungible AccountBalance (r:2 w:2)
+	// Storage: Refungible Owned (r:0 w:2)
+	fn transfer_from_creating_removing() -> Weight {
+		(32_362_000 as Weight)
+			.saturating_add(RocksDbWeight::get().reads(5 as Weight))
+			.saturating_add(RocksDbWeight::get().writes(7 as Weight))
+	}
+	// Storage: Refungible TokenData (r:1 w:1)
+	fn set_variable_metadata(_b: u32, ) -> Weight {
+		(6_801_000 as Weight)
+			.saturating_add(RocksDbWeight::get().reads(1 as Weight))
+			.saturating_add(RocksDbWeight::get().writes(1 as Weight))
+	}
 }