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
before · 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::*;17pub mod benchmarking;18pub mod common;19pub mod erc;20pub mod weights;21pub struct CreateItemData<T: Config> {22	pub const_data: BoundedVec<u8, CustomDataLimit>,23	pub variable_data: BoundedVec<u8, CustomDataLimit>,24	pub users: BTreeMap<T::CrossAccountId, u128>,25}26pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;2728#[derive(Encode, Decode, Default)]29pub struct ItemData {30	pub const_data: Vec<u8>,31	pub variable_data: Vec<u8>,32}3334#[frame_support::pallet]35pub mod pallet {36	use super::*;37	use frame_support::{Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};38	use nft_data_structs::{CollectionId, TokenId};39	use super::weights::WeightInfo;4041	#[pallet::error]42	pub enum Error<T> {43		/// Not Refungible item data used to mint in Refungible collection.44		NotRefungibleDataUsedToMintFungibleCollectionToken,45		/// Maximum refungibility exceeded46		WrongRefungiblePieces,47	}4849	#[pallet::config]50	pub trait Config: frame_system::Config + pallet_common::Config {51		type WeightInfo: WeightInfo;52	}5354	#[pallet::pallet]55	#[pallet::generate_store(pub(super) trait Store)]56	pub struct Pallet<T>(_);5758	#[pallet::storage]59	pub(super) type TokensMinted<T: Config> =60		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;61	#[pallet::storage]62	pub(super) type TokensBurnt<T: Config> =63		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;6465	#[pallet::storage]66	pub(super) type TokenData<T: Config> = StorageNMap<67		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),68		Value = ItemData,69		QueryKind = ValueQuery,70	>;7172	#[pallet::storage]73	pub(super) type TotalSupply<T: Config> = StorageNMap<74		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),75		Value = u128,76		QueryKind = ValueQuery,77	>;7879	/// Used to enumerate tokens owned by account80	#[pallet::storage]81	pub(super) type Owned<T: Config> = StorageNMap<82		Key = (83			Key<Twox64Concat, CollectionId>,84			Key<Blake2_128Concat, T::AccountId>,85			Key<Twox64Concat, TokenId>,86		),87		Value = bool,88		QueryKind = ValueQuery,89	>;9091	#[pallet::storage]92	pub(super) type AccountBalance<T: Config> = StorageNMap<93		Key = (94			Key<Twox64Concat, CollectionId>,95			// Owner96			Key<Blake2_128Concat, T::AccountId>,97		),98		Value = u32,99		QueryKind = ValueQuery,100	>;101102	#[pallet::storage]103	pub(super) type Balance<T: Config> = StorageNMap<104		Key = (105			Key<Twox64Concat, CollectionId>,106			Key<Twox64Concat, TokenId>,107			// Owner108			Key<Blake2_128Concat, T::AccountId>,109		),110		Value = u128,111		QueryKind = ValueQuery,112	>;113114	#[pallet::storage]115	pub(super) type Allowance<T: Config> = StorageNMap<116		Key = (117			Key<Twox64Concat, CollectionId>,118			Key<Twox64Concat, TokenId>,119			// Owner120			Key<Blake2_128, T::AccountId>,121			// Spender122			Key<Blake2_128Concat, T::CrossAccountId>,123		),124		Value = u128,125		QueryKind = ValueQuery,126	>;127}128129pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);130impl<T: Config> RefungibleHandle<T> {131	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {132		Self(inner)133	}134	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {135		self.0136	}137}138impl<T: Config> Deref for RefungibleHandle<T> {139	type Target = pallet_common::CollectionHandle<T>;140141	fn deref(&self) -> &Self::Target {142		&self.0143	}144}145146impl<T: Config> Pallet<T> {147	pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {148		<TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)149	}150	pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {151		<TotalSupply<T>>::contains_key((collection.id, token))152	}153}154155// unchecked calls skips any permission checks156impl<T: Config> Pallet<T> {157	pub fn init_collection(data: Collection<T>) -> Result<CollectionId, DispatchError> {158		PalletCommon::init_collection(data)159	}160	pub fn destroy_collection(161		collection: RefungibleHandle<T>,162		sender: &T::CrossAccountId,163	) -> DispatchResult {164		let id = collection.id;165166		// =========167168		PalletCommon::destroy_collection(collection.0, sender)?;169170		<TokensMinted<T>>::remove(id);171		<TokensBurnt<T>>::remove(id);172		<TokenData<T>>::remove_prefix((id,), None);173		<TotalSupply<T>>::remove_prefix((id,), None);174		<Balance<T>>::remove_prefix((id,), None);175		<Allowance<T>>::remove_prefix((id,), None);176		Ok(())177	}178179	pub fn burn_token(collection: &RefungibleHandle<T>, token_id: TokenId) -> DispatchResult {180		let burnt = <TokensBurnt<T>>::get(collection.id)181			.checked_add(1)182			.ok_or(ArithmeticError::Overflow)?;183184		<TokensBurnt<T>>::insert(collection.id, burnt);185		<TokenData<T>>::remove((collection.id, token_id));186		<TotalSupply<T>>::remove((collection.id, token_id));187		<Balance<T>>::remove_prefix((collection.id, token_id), None);188		<Allowance<T>>::remove_prefix((collection.id, token_id), None);189		// TODO: ERC721 transfer event190		return Ok(());191	}192193	pub fn burn(194		collection: &RefungibleHandle<T>,195		owner: &T::CrossAccountId,196		token: TokenId,197		amount: u128,198	) -> DispatchResult {199		let total_supply = <TotalSupply<T>>::get((collection.id, token))200			.checked_sub(amount)201			.ok_or(<CommonError<T>>::TokenValueTooLow)?;202203		// This was probally last owner of this token?204		if total_supply == 0 {205			// Ensure user actually owns this amount206			ensure!(207				<Balance<T>>::get((collection.id, token, owner.as_sub())) == amount,208				<CommonError<T>>::TokenValueTooLow209			);210			let account_balance = <AccountBalance<T>>::get((collection.id, owner.as_sub()))211				.checked_sub(1)212				// Should not occur213				.ok_or(ArithmeticError::Underflow)?;214215			// =========216217			<Owned<T>>::remove((collection.id, owner.as_sub(), token));218			<AccountBalance<T>>::insert((collection.id, owner.as_sub()), account_balance);219			Self::burn_token(collection, token)?;220			<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(221				collection.id,222				token,223				owner.clone(),224				amount,225			));226			return Ok(());227		}228229		let balance = <Balance<T>>::get((collection.id, token, owner.as_sub()))230			.checked_sub(amount)231			.ok_or(<CommonError<T>>::TokenValueTooLow)?;232		let account_balance = if balance == 0 {233			<AccountBalance<T>>::get((collection.id, owner.as_sub()))234				.checked_sub(1)235				// Should not occur236				.ok_or(ArithmeticError::Underflow)?237		} else {238			0239		};240241		// =========242243		if balance == 0 {244			<Owned<T>>::remove((collection.id, owner.as_sub(), token));245			<Balance<T>>::remove((collection.id, token, owner.as_sub()));246			<AccountBalance<T>>::insert((collection.id, owner.as_sub()), account_balance);247		} else {248			<Balance<T>>::insert((collection.id, token, owner.as_sub()), balance);249		}250		<TotalSupply<T>>::insert((collection.id, token), total_supply);251		// TODO: ERC20 transfer event252		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(253			collection.id,254			token,255			owner.clone(),256			amount,257		));258		Ok(())259	}260261	pub fn transfer(262		collection: &RefungibleHandle<T>,263		from: &T::CrossAccountId,264		to: &T::CrossAccountId,265		token: TokenId,266		amount: u128,267	) -> DispatchResult {268		ensure!(269			collection.transfers_enabled,270			<CommonError<T>>::TransferNotAllowed271		);272273		if collection.access == AccessMode::WhiteList {274			collection.check_allowlist(from)?;275			collection.check_allowlist(to)?;276		}277		<PalletCommon<T>>::ensure_correct_receiver(to)?;278279		let balance_from = <Balance<T>>::get((collection.id, token, from.as_sub()))280			.checked_sub(amount)281			.ok_or(<CommonError<T>>::TokenValueTooLow)?;282		let mut create_target = false;283		let from_to_differ = from != to;284		let balance_to = if from != to {285			let old_balance = <Balance<T>>::get((collection.id, token, to.as_sub()));286			if old_balance == 0 {287				create_target = true;288			}289			Some(290				old_balance291					.checked_add(amount)292					.ok_or(ArithmeticError::Overflow)?,293			)294		} else {295			None296		};297298		let account_balance_from = if balance_from == 0 {299			Some(300				<AccountBalance<T>>::get((collection.id, from.as_sub()))301					.checked_sub(1)302					// Should not occur303					.ok_or(ArithmeticError::Underflow)?,304			)305		} else {306			None307		};308		// Account data is created in token, AccountBalance should be increased309		// But only if from != to as we shouldn't check overflow in this case310		let account_balance_to = if create_target && from_to_differ {311			let account_balance_to = <AccountBalance<T>>::get((collection.id, to.as_sub()))312				.checked_add(1)313				.ok_or(ArithmeticError::Overflow)?;314			ensure!(315				account_balance_to < collection.limits.account_token_ownership_limit(),316				<CommonError<T>>::AccountTokenLimitExceeded,317			);318319			Some(account_balance_to)320		} else {321			None322		};323324		// =========325326		if let Some(balance_to) = balance_to {327			// from != to328			if balance_from == 0 {329				<Balance<T>>::remove((collection.id, token, from.as_sub()));330			} else {331				<Balance<T>>::insert((collection.id, token, from.as_sub()), balance_from);332			}333			<Balance<T>>::insert((collection.id, token, to.as_sub()), balance_to);334			if let Some(account_balance_from) = account_balance_from {335				<AccountBalance<T>>::insert((collection.id, from.as_sub()), account_balance_from);336				<Owned<T>>::remove((collection.id, from.as_sub(), token));337			}338			if let Some(account_balance_to) = account_balance_to {339				<AccountBalance<T>>::insert((collection.id, to.as_sub()), account_balance_to);340				<Owned<T>>::insert((collection.id, to.as_sub(), token), true);341			}342		}343344		// TODO: ERC20 transfer event345		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(346			collection.id,347			token,348			from.clone(),349			to.clone(),350			amount,351		));352		Ok(())353	}354355	pub fn create_multiple_items(356		collection: &RefungibleHandle<T>,357		sender: &T::CrossAccountId,358		data: Vec<CreateItemData<T>>,359	) -> DispatchResult {360		let unrestricted_minting = collection.is_owner_or_admin(sender)?;361		if !unrestricted_minting {362			ensure!(363				collection.mint_mode,364				<CommonError<T>>::PublicMintingNotAllowed365			);366			collection.check_allowlist(sender)?;367368			for item in data.iter() {369				for (user, _) in &item.users {370					collection.check_allowlist(&user)?;371				}372			}373		}374375		for item in data.iter() {376			for (owner, _) in item.users.iter() {377				<PalletCommon<T>>::ensure_correct_receiver(owner)?;378			}379		}380381		// Total pieces per tokens382		let totals = data383			.iter()384			.map(|data| {385				Ok(data386					.users387					.iter()388					.map(|u| u.1)389					.try_fold(0u128, |acc, v| acc.checked_add(*v))390					.ok_or(ArithmeticError::Overflow)?)391			})392			.collect::<Result<Vec<_>, DispatchError>>()?;393		for total in &totals {394			ensure!(395				*total <= MAX_REFUNGIBLE_PIECES,396				<Error<T>>::WrongRefungiblePieces397			);398		}399400		let first_token_id = <TokensMinted<T>>::get(collection.id);401		let tokens_minted = first_token_id402			.checked_add(data.len() as u32)403			.ok_or(ArithmeticError::Overflow)?;404		ensure!(405			tokens_minted < collection.limits.token_limit,406			<CommonError<T>>::CollectionTokenLimitExceeded407		);408409		let mut balances = BTreeMap::new();410		for data in &data {411			for (owner, _) in &data.users {412				let balance = balances413					.entry(owner.as_sub())414					.or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner.as_sub())));415				*balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;416417				ensure!(418					*balance <= collection.limits.account_token_ownership_limit(),419					<CommonError<T>>::AccountTokenLimitExceeded,420				);421			}422		}423424		// =========425426		<TokensMinted<T>>::insert(collection.id, tokens_minted);427		for (account, balance) in balances {428			<AccountBalance<T>>::insert((collection.id, account), balance);429		}430		for (i, token) in data.into_iter().enumerate() {431			let token_id = first_token_id + i as u32 + 1;432			<TotalSupply<T>>::insert((collection.id, token_id), totals[i]);433434			<TokenData<T>>::insert(435				(collection.id, token_id),436				ItemData {437					const_data: token.const_data.into(),438					variable_data: token.variable_data.into(),439				},440			);441			for (user, amount) in token.users.into_iter() {442				if amount == 0 {443					continue;444				}445				<Balance<T>>::insert((collection.id, token_id, user.as_sub()), amount);446				<Owned<T>>::insert((collection.id, user.as_sub(), TokenId(token_id)), true);447				// TODO: ERC20 transfer event448				<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(449					collection.id,450					TokenId(token_id),451					user,452					amount,453				));454			}455		}456		Ok(())457	}458459	pub fn set_allowance_unchecked(460		collection: &RefungibleHandle<T>,461		sender: &T::CrossAccountId,462		spender: &T::CrossAccountId,463		token: TokenId,464		amount: u128,465	) {466		<Allowance<T>>::insert((collection.id, token, sender.as_sub(), spender), amount);467		// TODO: ERC20 approval event468		<PalletCommon<T>>::deposit_event(CommonEvent::Approved(469			collection.id,470			token,471			sender.clone(),472			spender.clone(),473			amount,474		))475	}476477	pub fn set_allowance(478		collection: &RefungibleHandle<T>,479		sender: &T::CrossAccountId,480		spender: &T::CrossAccountId,481		token: TokenId,482		amount: u128,483	) -> DispatchResult {484		if collection.access == AccessMode::WhiteList {485			collection.check_allowlist(&sender)?;486			collection.check_allowlist(&spender)?;487		}488489		<PalletCommon<T>>::ensure_correct_receiver(spender)?;490491		if <Balance<T>>::get((collection.id, token, sender.as_sub())) < amount {492			ensure!(493				collection.ignores_owned_amount(sender)?,494				<CommonError<T>>::CantApproveMoreThanOwned495			);496		}497498		// =========499500		Self::set_allowance_unchecked(collection, sender, spender, token, amount);501		Ok(())502	}503504	pub fn transfer_from(505		collection: &RefungibleHandle<T>,506		spender: &T::CrossAccountId,507		from: &T::CrossAccountId,508		to: &T::CrossAccountId,509		token: TokenId,510		amount: u128,511	) -> DispatchResult {512		if spender == from {513			return Self::transfer(collection, from, to, token, amount);514		}515		if collection.access == AccessMode::WhiteList {516			// `from`, `to` checked in [`transfer`]517			collection.check_allowlist(spender)?;518		}519520		let allowance = <Allowance<T>>::get((collection.id, token, from.as_sub(), &spender))521			.checked_sub(amount);522		if allowance.is_none() {523			ensure!(524				collection.ignores_allowance(spender)?,525				<CommonError<T>>::TokenValueNotEnough526			);527		}528529		// =========530531		Self::transfer(collection, from, to, token, amount)?;532		if let Some(allowance) = allowance {533			Self::set_allowance_unchecked(collection, from, spender, token, allowance);534		}535		Ok(())536	}537538	pub fn set_variable_metadata(539		collection: &RefungibleHandle<T>,540		sender: &T::CrossAccountId,541		token: TokenId,542		data: Vec<u8>,543	) -> DispatchResult {544		ensure!(545			data.len() as u32 <= CUSTOM_DATA_LIMIT,546			<CommonError<T>>::TokenVariableDataLimitExceeded547		);548		collection.check_can_update_meta(549			sender,550			&T::CrossAccountId::from_sub(collection.owner.clone()),551		)?;552553		collection.consume_sstore()?;554		let token_data = <TokenData<T>>::get((collection.id, token));555556		// =========557558		<TokenData<T>>::insert(559			(collection.id, token),560			ItemData {561				variable_data: data,562				..token_data563			},564		);565		Ok(())566	}567568	/// Delegated to `create_multiple_items`569	pub fn create_item(570		collection: &RefungibleHandle<T>,571		sender: &T::CrossAccountId,572		data: CreateItemData<T>,573	) -> DispatchResult {574		Self::create_multiple_items(collection, sender, vec![data])575	}576}
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))
+	}
 }