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

difftreelog

feat(weight) added benchs for decompose weight Changed weight calculation system for `transfer` & `transfer_from` (NFT)

PraetorP2023-03-28parent: #6e3cf5e.patch.diff
in: master

13 files changed

modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6262,7 +6262,7 @@
 
 [[package]]
 name = "pallet-common"
-version = "0.1.13"
+version = "0.1.14"
 dependencies = [
  "ethereum",
  "evm-coder",
@@ -6814,7 +6814,7 @@
 
 [[package]]
 name = "pallet-nonfungible"
-version = "0.1.13"
+version = "0.1.14"
 dependencies = [
  "evm-coder",
  "frame-benchmarking",
modifiedpallets/app-promotion/src/lib.rsdiffbeforeafterboth
--- a/pallets/app-promotion/src/lib.rs
+++ b/pallets/app-promotion/src/lib.rs
@@ -845,7 +845,6 @@
 	/// - `staker`: staker account.
 	pub fn total_staked_by_id(staker: impl EncodeLike<T::AccountId>) -> Option<BalanceOf<T>> {
 		let staked = Staked::<T>::iter_prefix((staker,))
-			.into_iter()
 			.fold(<BalanceOf<T>>::default(), |acc, (_, (amount, _))| {
 				acc + amount
 			});
@@ -864,7 +863,6 @@
 		staker: impl EncodeLike<T::AccountId>,
 	) -> Option<Vec<(T::BlockNumber, BalanceOf<T>)>> {
 		let mut staked = Staked::<T>::iter_prefix((staker,))
-			.into_iter()
 			.map(|(block, (amount, _))| (block, amount))
 			.collect::<Vec<_>>();
 		staked.sort_by_key(|(block, _)| *block);
@@ -883,12 +881,6 @@
 			Self::total_staked_by_id(s.as_sub())
 		})
 	}
-
-	// pub fn cross_id_locked_balance(staker: T::CrossAccountId) -> BalanceOf<T> {
-	// 	Self::get_locked_balance(staker.as_sub())
-	// 		.map(|l| l.amount)
-	// 		.unwrap_or_default()
-	// }
 
 	/// Returns all relay block numbers when stake was made,
 	/// the amount of the stake.
modifiedpallets/common/CHANGELOG.mddiffbeforeafterboth
--- a/pallets/common/CHANGELOG.md
+++ b/pallets/common/CHANGELOG.md
@@ -4,6 +4,12 @@
 
 <!-- bureaucrate goes here -->
 
+## [0.1.14] - 2023-03-28
+
+### Added
+
+- Added benchmark to check if user is contained in AllowList (`check_accesslist()`).
+
 ## [0.1.13] - 2023-01-20
 
 ### Changed
modifiedpallets/common/Cargo.tomldiffbeforeafterboth
--- a/pallets/common/Cargo.toml
+++ b/pallets/common/Cargo.toml
@@ -2,7 +2,7 @@
 edition = "2021"
 license = "GPLv3"
 name = "pallet-common"
-version = "0.1.13"
+version = "0.1.14"
 
 [dependencies]
 # Note: `package = "parity-scale-codec"` must be supplied since the `Encode` macro searches for it.
modifiedpallets/common/src/benchmarking.rsdiffbeforeafterboth
before · pallets/common/src/benchmarking.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617#![allow(missing_docs)]1819use sp_std::vec::Vec;20use crate::{Config, CollectionHandle, Pallet};21use pallet_evm::account::CrossAccountId;22use frame_benchmarking::{benchmarks, account};23use up_data_structs::{24	CollectionMode, CollectionFlags, CreateCollectionData, CollectionId, Property, PropertyKey,25	PropertyValue, CollectionPermissions, NestingPermissions, MAX_COLLECTION_NAME_LENGTH,26	MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH, MAX_PROPERTIES_PER_ITEM,27};28use frame_support::{29	traits::{Currency, Get},30	pallet_prelude::ConstU32,31	BoundedVec,32};33use core::convert::TryInto;34use sp_runtime::DispatchError;3536const SEED: u32 = 1;3738pub fn create_data<const S: u32>() -> BoundedVec<u8, ConstU32<S>> {39	create_var_data::<S>(S)40}41pub fn create_u16_data<const S: u32>() -> BoundedVec<u16, ConstU32<S>> {42	(0..S)43		.map(|v| (v & 0xffff) as u16)44		.collect::<Vec<_>>()45		.try_into()46		.unwrap()47}48pub fn create_var_data<const S: u32>(size: u32) -> BoundedVec<u8, ConstU32<S>> {49	assert!(50		size <= S,51		"size ({}) should be less within bound ({})",52		size,53		S54	);55	(0..size)56		.map(|v| (v & 0xff) as u8)57		.collect::<Vec<_>>()58		.try_into()59		.unwrap()60}61pub fn property_key(id: usize) -> PropertyKey {62	#[cfg(not(feature = "std"))]63	use alloc::string::ToString;64	let mut data = create_data();65	// No DerefMut available for .fill66	for i in 0..data.len() {67		data[i] = b'0';68	}69	let bytes = id.to_string();70	let len = data.len();71	data[len - bytes.len()..].copy_from_slice(&bytes.as_bytes());72	data73}74pub fn property_value() -> PropertyValue {75	create_data()76}7778pub fn create_collection_raw<T: Config, R>(79	owner: T::CrossAccountId,80	mode: CollectionMode,81	handler: impl FnOnce(82		T::CrossAccountId,83		CreateCollectionData<T::AccountId>,84	) -> Result<CollectionId, DispatchError>,85	cast: impl FnOnce(CollectionHandle<T>) -> R,86) -> Result<R, DispatchError> {87	<T as Config>::Currency::deposit_creating(&owner.as_sub(), T::CollectionCreationPrice::get());88	let name = create_u16_data::<MAX_COLLECTION_NAME_LENGTH>();89	let description = create_u16_data::<MAX_COLLECTION_DESCRIPTION_LENGTH>();90	let token_prefix = create_data::<MAX_TOKEN_PREFIX_LENGTH>();91	handler(92		owner,93		CreateCollectionData {94			mode,95			name,96			description,97			token_prefix,98			permissions: Some(CollectionPermissions {99				nesting: Some(NestingPermissions {100					token_owner: false,101					collection_admin: false,102					restricted: None,103					#[cfg(feature = "runtime-benchmarks")]104					permissive: true,105				}),106				mint_mode: Some(true),107				..Default::default()108			}),109			..Default::default()110		},111	)112	.and_then(CollectionHandle::try_get)113	.map(cast)114}115fn create_collection<T: Config>(116	owner: T::CrossAccountId,117) -> Result<CollectionHandle<T>, DispatchError> {118	create_collection_raw(119		owner,120		CollectionMode::NFT,121		|owner: T::CrossAccountId, data| {122			<Pallet<T>>::init_collection(owner.clone(), owner, data, CollectionFlags::default())123		},124		|h| h,125	)126}127128/// Helper macros, which handles all benchmarking preparation in semi-declarative way129///130/// `name` is a substrate account131/// - name: sub[(id)]132/// `name` is a collection with owner `owner`133/// - name: collection(owner)134/// `name` is a cross account based on substrate135/// - name: cross_sub[(id)]136/// `name` is a cross account, which maps to substrate account `name`137/// - name: cross_from_sub138/// `name` is a cross account, which maps to substrate account `other_name`139/// - name: cross_from_sub(other_name)140#[macro_export]141macro_rules! bench_init {142	($name:ident: sub $(($id:expr))?; $($rest:tt)*) => {143		let $name: T::AccountId = account(stringify!($name), 0 $(+ $id)?, SEED);144		bench_init!($($rest)*);145	};146	($name:ident: collection($owner:ident); $($rest:tt)*) => {147		let $name = create_collection::<T>(T::CrossAccountId::from_sub($owner.clone()))?;148		bench_init!($($rest)*);149	};150	($name:ident: cross; $($rest:tt)*) => {151		let $name = T::CrossAccountId::from_sub($name);152		bench_init!($($rest)*);153	};154	($name:ident: cross_sub $(($id:expr))?; $($rest:tt)*) => {155		let account: T::AccountId = account(stringify!($name), 0 $(+ $id)?, SEED);156		let $name = T::CrossAccountId::from_sub(account);157		bench_init!($($rest)*);158	};159	($name:ident: cross_from_sub; $($rest:tt)*) => {160		let $name = T::CrossAccountId::from_sub($name);161		bench_init!($($rest)*);162	};163	($name:ident: cross_from_sub($from:ident); $($rest:tt)*) => {164		let $name = T::CrossAccountId::from_sub($from);165		bench_init!($($rest)*);166	};167	() => {}168}169170benchmarks! {171	set_collection_properties {172		let b in 0..MAX_PROPERTIES_PER_ITEM;173		bench_init!{174			owner: sub; collection: collection(owner);175			owner: cross_from_sub;176		};177		let props = (0..b).map(|p| Property {178			key: property_key(p as usize),179			value: property_value(),180		}).collect::<Vec<_>>();181	}: {<Pallet<T>>::set_collection_properties(&collection, &owner, props.into_iter())?}182183	delete_collection_properties {184		let b in 0..MAX_PROPERTIES_PER_ITEM;185		bench_init!{186			owner: sub; collection: collection(owner);187			owner: cross_from_sub;188		};189		let props = (0..b).map(|p| Property {190			key: property_key(p as usize),191			value: property_value(),192		}).collect::<Vec<_>>();193		<Pallet<T>>::set_collection_properties(&collection, &owner, props.into_iter())?;194		let to_delete = (0..b).map(|p| property_key(p as usize)).collect::<Vec<_>>();195	}: {<Pallet<T>>::delete_collection_properties(&collection, &owner, to_delete.into_iter())?}196}
modifiedpallets/common/src/weights.rsdiffbeforeafterboth
--- a/pallets/common/src/weights.rs
+++ b/pallets/common/src/weights.rs
@@ -36,6 +36,7 @@
 pub trait WeightInfo {
 	fn set_collection_properties(b: u32, ) -> Weight;
 	fn delete_collection_properties(b: u32, ) -> Weight;
+	fn check_accesslist() -> Weight;
 }
 
 /// Weights for pallet_common using the Substrate node and recommended hardware.
@@ -66,11 +67,8 @@
 		Weight::from_parts(6_684_000, 43467)
 			// Standard Error: 67_984
 			.saturating_add(Weight::from_parts(21_502_829, 0).saturating_mul(b.into()))
-			.saturating_add(T::DbWeight::get().reads(1_u64))
 			.saturating_add(T::DbWeight::get().writes(1_u64))
 	}
-}
-
 // For backwards compatibility and tests
 impl WeightInfo for () {
 	/// Storage: Common CollectionProperties (r:1 w:1)
@@ -98,8 +96,5 @@
 		Weight::from_parts(6_684_000, 43467)
 			// Standard Error: 67_984
 			.saturating_add(Weight::from_parts(21_502_829, 0).saturating_mul(b.into()))
-			.saturating_add(RocksDbWeight::get().reads(1_u64))
 			.saturating_add(RocksDbWeight::get().writes(1_u64))
 	}
-}
-
modifiedpallets/nonfungible/CHANGELOG.mddiffbeforeafterboth
--- a/pallets/nonfungible/CHANGELOG.md
+++ b/pallets/nonfungible/CHANGELOG.md
@@ -4,6 +4,12 @@
 
 <!-- bureaucrate goes here -->
 
+## [0.1.14] - 2023-03-28
+
+### Fixed
+
+- The weight of `transfer` and `transfer_from`.
+
 ## [0.1.13] - 2023-01-20
 
 ### Fixed
modifiedpallets/nonfungible/Cargo.tomldiffbeforeafterboth
--- a/pallets/nonfungible/Cargo.toml
+++ b/pallets/nonfungible/Cargo.toml
@@ -2,7 +2,7 @@
 edition = "2021"
 license = "GPLv3"
 name = "pallet-nonfungible"
-version = "0.1.13"
+version = "0.1.14"
 
 [dependencies]
 # Note: `package = "parity-scale-codec"` must be supplied since the `Encode` macro searches for it.
modifiedpallets/nonfungible/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/benchmarking.rs
+++ b/pallets/nonfungible/src/benchmarking.rs
@@ -146,14 +146,14 @@
 		let item = create_max_item(&collection, &owner, owner_eth.clone())?;
 	}: {<Pallet<T>>::set_allowance_from(&collection, &sender, &owner_eth, item, Some(&spender))?}
 
-	transfer_from {
+	checks_for_transfer_from {
 		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())?;
 		<Pallet<T>>::set_allowance(&collection, &sender, item, Some(&spender))?;
-	}: {<Pallet<T>>::transfer_from(&collection, &spender, &sender, &receiver, item, &Unlimited)?}
+	}: {<Pallet<T>>::check_allowed(&collection, &spender, &sender, item, &Unlimited)?}
 
 	burn_from {
 		bench_init!{
modifiedpallets/nonfungible/src/common.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -23,7 +23,7 @@
 };
 use pallet_common::{
 	CommonCollectionOperations, CommonWeightInfo, RefungibleExtensions, with_weight,
-	weights::WeightInfo as _,
+	weights::WeightInfo as _, SelfWeightOf as PalletCommonWeightOf,
 };
 use sp_runtime::DispatchError;
 use sp_std::{vec::Vec, vec};
@@ -91,7 +91,7 @@
 	}
 
 	fn transfer() -> Weight {
-		<SelfWeightOf<T>>::transfer()
+		<SelfWeightOf<T>>::transfer() + <PalletCommonWeightOf<T>>::check_accesslist() * 2
 	}
 
 	fn approve() -> Weight {
@@ -103,7 +103,7 @@
 	}
 
 	fn transfer_from() -> Weight {
-		<SelfWeightOf<T>>::transfer_from()
+		Self::transfer() + <SelfWeightOf<T>>::checks_for_transfer_from()
 	}
 
 	fn burn_from() -> Weight {
@@ -325,10 +325,7 @@
 	) -> DispatchResultWithPostInfo {
 		ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);
 		if amount == 1 {
-			with_weight(
-				<Pallet<T>>::transfer(self, &from, &to, token, nesting_budget),
-				<CommonWeights<T>>::transfer(),
-			)
+			<Pallet<T>>::transfer(self, &from, &to, token, nesting_budget)
 		} else {
 			<Pallet<T>>::check_token_immediate_ownership(self, token, &from)?;
 			Ok(().into())
@@ -386,10 +383,7 @@
 		ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);
 
 		if amount == 1 {
-			with_weight(
-				<Pallet<T>>::transfer_from(self, &sender, &from, &to, token, nesting_budget),
-				<CommonWeights<T>>::transfer_from(),
-			)
+			<Pallet<T>>::transfer_from(self, &sender, &from, &to, token, nesting_budget)
 		} else {
 			<Pallet<T>>::check_allowed(self, &sender, &from, token, nesting_budget)?;
 
modifiedpallets/nonfungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -39,6 +39,7 @@
 	CollectionHandle, CollectionPropertyPermissions, CommonCollectionOperations,
 	erc::{CommonEvmHandler, PrecompileResult, CollectionCall, static_property::key},
 	eth::{self, TokenUri},
+	CommonWeightInfo,
 };
 use pallet_evm::{account::CrossAccountId, PrecompileHandle};
 use pallet_evm_coder_substrate::call;
@@ -47,7 +48,7 @@
 
 use crate::{
 	AccountBalance, Config, CreateItemData, NonfungibleHandle, Pallet, TokenData, TokensMinted,
-	TokenProperties, SelfWeightOf, weights::WeightInfo,
+	TokenProperties, SelfWeightOf, weights::WeightInfo, common::CommonWeights,
 };
 
 /// Nft events.
@@ -458,7 +459,7 @@
 	/// @param from The current owner of the NFT
 	/// @param to The new owner
 	/// @param tokenId The NFT to transfer
-	#[weight(<SelfWeightOf<T>>::transfer_from())]
+	#[weight(<CommonWeights<T>>::transfer_from())]
 	fn transfer_from(
 		&mut self,
 		caller: Caller,
@@ -475,7 +476,7 @@
 			.weight_calls_budget(<StructureWeight<T>>::find_parent());
 
 		<Pallet<T>>::transfer_from(self, &caller, &from, &to, token, &budget)
-			.map_err(dispatch_to_evm::<T>)?;
+			.map_err(|e| dispatch_to_evm::<T>(e.error))?;
 		Ok(())
 	}
 
@@ -824,7 +825,7 @@
 	///  is the zero address. Throws if `tokenId` is not a valid NFT.
 	/// @param to The new owner
 	/// @param tokenId The NFT to transfer
-	#[weight(<SelfWeightOf<T>>::transfer())]
+	#[weight(<CommonWeights<T>>::transfer())]
 	fn transfer(&mut self, caller: Caller, to: Address, token_id: U256) -> Result<()> {
 		let caller = T::CrossAccountId::from_eth(caller);
 		let to = T::CrossAccountId::from_eth(to);
@@ -833,7 +834,8 @@
 			.recorder
 			.weight_calls_budget(<StructureWeight<T>>::find_parent());
 
-		<Pallet<T>>::transfer(self, &caller, &to, token, &budget).map_err(dispatch_to_evm::<T>)?;
+		<Pallet<T>>::transfer(self, &caller, &to, token, &budget)
+			.map_err(|e| dispatch_to_evm::<T>(e.error))?;
 		Ok(())
 	}
 
@@ -842,7 +844,7 @@
 	///  is the zero address. Throws if `tokenId` is not a valid NFT.
 	/// @param to The new owner
 	/// @param tokenId The NFT to transfer
-	#[weight(<SelfWeightOf<T>>::transfer())]
+	#[weight(<CommonWeights<T>>::transfer())]
 	fn transfer_cross(
 		&mut self,
 		caller: Caller,
@@ -856,7 +858,8 @@
 			.recorder
 			.weight_calls_budget(<StructureWeight<T>>::find_parent());
 
-		<Pallet<T>>::transfer(self, &caller, &to, token, &budget).map_err(dispatch_to_evm::<T>)?;
+		<Pallet<T>>::transfer(self, &caller, &to, token, &budget)
+			.map_err(|e| dispatch_to_evm::<T>(e.error))?;
 		Ok(())
 	}
 
@@ -866,7 +869,7 @@
 	/// @param from Cross acccount address of current owner
 	/// @param to Cross acccount address of new owner
 	/// @param tokenId The NFT to transfer
-	#[weight(<SelfWeightOf<T>>::transfer())]
+	#[weight(<CommonWeights<T>>::transfer_from())]
 	fn transfer_from_cross(
 		&mut self,
 		caller: Caller,
@@ -882,7 +885,7 @@
 			.recorder
 			.weight_calls_budget(<StructureWeight<T>>::find_parent());
 		Pallet::<T>::transfer_from(self, &caller, &from, &to, token_id, &budget)
-			.map_err(dispatch_to_evm::<T>)?;
+			.map_err(|e| dispatch_to_evm::<T>(e.error))?;
 		Ok(())
 	}
 
modifiedpallets/nonfungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -108,7 +108,8 @@
 use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};
 use pallet_common::{
 	Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, CollectionHandle,
-	eth::collection_id_to_address,
+	eth::collection_id_to_address, SelfWeightOf as PalletCommonWeightOf,
+	weights::WeightInfo as CommonWeightInfo,
 };
 use pallet_structure::{Pallet as PalletStructure, Error as StructureError};
 use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};
@@ -802,7 +803,7 @@
 		to: &T::CrossAccountId,
 		token: TokenId,
 		nesting_budget: &dyn Budget,
-	) -> DispatchResult {
+	) -> DispatchResultWithPostInfo {
 		ensure!(
 			collection.limits.transfers_enabled(),
 			<CommonError<T>>::TransferNotAllowed
@@ -812,7 +813,8 @@
 			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;
 		ensure!(&token_data.owner == from, <CommonError<T>>::NoPermission);
 
-		if collection.permissions.access() == AccessMode::AllowList {
+		let is_allow_list_mode = collection.permissions.access() == AccessMode::AllowList;
+		if is_allow_list_mode {
 			collection.check_allowlist(from)?;
 			collection.check_allowlist(to)?;
 		}
@@ -884,7 +886,18 @@
 			to.clone(),
 			1,
 		));
-		Ok(())
+
+		let actual_weight = match is_allow_list_mode {
+			true => Some(
+				<SelfWeightOf<T>>::transfer() + <PalletCommonWeightOf<T>>::check_accesslist() * 2,
+			),
+			false => Some(<SelfWeightOf<T>>::transfer()),
+		};
+
+		Ok(PostDispatchInfo {
+			actual_weight,
+			pays_fee: Pays::Yes,
+		})
 	}
 
 	/// Batch operation to mint multiple NFT tokens.
@@ -1228,13 +1241,18 @@
 		to: &T::CrossAccountId,
 		token: TokenId,
 		nesting_budget: &dyn Budget,
-	) -> DispatchResult {
+	) -> DispatchResultWithPostInfo {
 		Self::check_allowed(collection, spender, from, token, nesting_budget)?;
 
 		// =========
 
 		// Allowance is reset in [`transfer`]
-		Self::transfer(collection, from, to, token, nesting_budget)
+		Self::transfer(collection, from, to, token, nesting_budget).map(|mut p| {
+			p.actual_weight = Some(
+				p.actual_weight.unwrap_or_default() + <SelfWeightOf<T>>::checks_for_transfer_from(),
+			);
+			p
+		})
 	}
 
 	/// Burn NFT token for `from` account.
modifiedpallets/nonfungible/src/weights.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/weights.rs
+++ b/pallets/nonfungible/src/weights.rs
@@ -43,7 +43,7 @@
 	fn transfer() -> Weight;
 	fn approve() -> Weight;
 	fn approve_from() -> Weight;
-	fn transfer_from() -> Weight;
+	fn checks_for_transfer_from() -> Weight;
 	fn burn_from() -> Weight;
 	fn set_token_property_permissions(b: u32, ) -> Weight;
 	fn set_token_properties(b: u32, ) -> Weight;