git.delta.rocks / unique-network / refs/commits / 9c50a8cd1ee9

difftreelog

fix benchmarks

Daniel Shiposha2023-10-18parent: #cfd2e2a.patch.diff
in: master

5 files changed

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 core::convert::TryInto;2021use frame_benchmarking::{account, v2::*};22use frame_support::{23	pallet_prelude::ConstU32,24	traits::{fungible::Balanced, tokens::Precision, Get, Imbalance},25	BoundedVec,26};27use pallet_evm::account::CrossAccountId;28use sp_runtime::{traits::Zero, DispatchError};29use sp_std::{vec, vec::Vec};30use up_data_structs::{31	AccessMode, CollectionId, CollectionMode, CollectionPermissions, CreateCollectionData,32	NestingPermissions, Property, PropertyKey, PropertyValue, MAX_COLLECTION_DESCRIPTION_LENGTH,33	MAX_COLLECTION_NAME_LENGTH, MAX_PROPERTIES_PER_ITEM, MAX_TOKEN_PREFIX_LENGTH,34};3536use crate::{BenchmarkPropertyWriter, CollectionHandle, Config, Pallet};3738const SEED: u32 = 1;3940pub fn create_data<const S: u32>() -> BoundedVec<u8, ConstU32<S>> {41	create_var_data::<S>(S)42}43pub fn create_u16_data<const S: u32>() -> BoundedVec<u16, ConstU32<S>> {44	(0..S)45		.map(|v| (v & 0xffff) as u16)46		.collect::<Vec<_>>()47		.try_into()48		.unwrap()49}50pub fn create_var_data<const S: u32>(size: u32) -> BoundedVec<u8, ConstU32<S>> {51	assert!(size <= S, "size ({size}) should be less within bound ({S})",);52	(0..size)53		.map(|v| (v & 0xff) as u8)54		.collect::<Vec<_>>()55		.try_into()56		.unwrap()57}58pub fn property_key(id: usize) -> PropertyKey {59	#[cfg(not(feature = "std"))]60	use alloc::string::ToString;61	let mut data = create_data();62	// No DerefMut available for .fill63	for i in 0..data.len() {64		data[i] = b'0';65	}66	let bytes = id.to_string();67	let len = data.len();68	data[len - bytes.len()..].copy_from_slice(bytes.as_bytes());69	data70}71pub fn property_value() -> PropertyValue {72	create_data()73}7475pub fn create_collection_raw<T: Config, R>(76	owner: T::CrossAccountId,77	mode: CollectionMode,78	handler: impl FnOnce(79		T::CrossAccountId,80		CreateCollectionData<T::CrossAccountId>,81	) -> Result<CollectionId, DispatchError>,82	cast: impl FnOnce(CollectionHandle<T>) -> R,83) -> Result<R, DispatchError> {84	let imbalance = <T as Config>::Currency::deposit(85		owner.as_sub(),86		T::CollectionCreationPrice::get(),87		Precision::Exact,88	)?;89	debug_assert!(imbalance.peek().is_zero());90	let name = create_u16_data::<MAX_COLLECTION_NAME_LENGTH>();91	let description = create_u16_data::<MAX_COLLECTION_DESCRIPTION_LENGTH>();92	let token_prefix = create_data::<MAX_TOKEN_PREFIX_LENGTH>();93	handler(94		owner,95		CreateCollectionData {96			mode,97			name,98			description,99			token_prefix,100			permissions: Some(CollectionPermissions {101				nesting: Some(NestingPermissions {102					token_owner: false,103					collection_admin: false,104					restricted: None,105					#[cfg(feature = "runtime-benchmarks")]106					permissive: true,107				}),108				mint_mode: Some(true),109				..Default::default()110			}),111			..Default::default()112		},113	)114	.and_then(CollectionHandle::try_get)115	.map(cast)116}117fn create_collection<T: Config>(118	owner: T::CrossAccountId,119) -> Result<CollectionHandle<T>, DispatchError> {120	create_collection_raw(121		owner,122		CollectionMode::NFT,123		|owner: T::CrossAccountId, data| <Pallet<T>>::init_collection(owner.clone(), owner, data),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}169170#[benchmarks]171mod benchmarks {172	use super::*;173174	#[benchmark]175	fn set_collection_properties(176		b: Linear<0, MAX_PROPERTIES_PER_ITEM>,177	) -> Result<(), BenchmarkError> {178		bench_init! {179			owner: sub; collection: collection(owner);180			owner: cross_from_sub;181		};182		let props = (0..b)183			.map(|p| Property {184				key: property_key(p as usize),185				value: property_value(),186			})187			.collect::<Vec<_>>();188189		#[block]190		{191			<Pallet<T>>::set_collection_properties(&collection, &owner, props.into_iter())?;192		}193194		Ok(())195	}196197	#[benchmark]198	fn check_accesslist() -> Result<(), BenchmarkError> {199		bench_init! {200			owner: sub; collection: collection(owner);201			sender: cross_from_sub(owner);202		};203204		let mut collection_handle = <CollectionHandle<T>>::try_get(collection.id)?;205		<Pallet<T>>::update_permissions(206			&sender,207			&mut collection_handle,208			CollectionPermissions {209				access: Some(AccessMode::AllowList),210				..Default::default()211			},212		)?;213214		<Pallet<T>>::toggle_allowlist(&collection, &sender, &sender, true)?;215216		assert_eq!(217			collection_handle.permissions.access(),218			AccessMode::AllowList219		);220221		#[block]222		{223			collection_handle.check_allowlist(&sender)?;224		}225226		Ok(())227	}228229	#[benchmark]230	fn property_writer_load_collection_info() -> Result<(), BenchmarkError> {231		bench_init! {232			owner: sub; collection: collection(owner);233			sender: sub;234			sender: cross_from_sub(sender);235		};236237		#[block]238		{239			<BenchmarkPropertyWriter<T>>::load_collection_info(&&collection, &sender);240		}241242		Ok(())243	}244}
after · 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 core::convert::TryInto;2021use frame_benchmarking::{account, v2::*};22use frame_support::{23	pallet_prelude::ConstU32,24	traits::{fungible::Balanced, tokens::Precision, Get, Imbalance},25	BoundedVec,26};27use pallet_evm::account::CrossAccountId;28use sp_runtime::{traits::Zero, DispatchError};29use sp_std::{vec, vec::Vec};30use up_data_structs::{31	AccessMode, CollectionId, CollectionMode, CollectionPermissions, CreateCollectionData,32	NestingPermissions, Property, PropertyKey, PropertyValue, MAX_COLLECTION_DESCRIPTION_LENGTH,33	MAX_COLLECTION_NAME_LENGTH, MAX_PROPERTIES_PER_ITEM, MAX_TOKEN_PREFIX_LENGTH,34};3536use crate::{BenchmarkPropertyWriter, CollectionHandle, Config, Pallet};3738const SEED: u32 = 1;3940pub fn create_data<const S: u32>() -> BoundedVec<u8, ConstU32<S>> {41	create_var_data::<S>(S)42}43pub fn create_u16_data<const S: u32>() -> BoundedVec<u16, ConstU32<S>> {44	(0..S)45		.map(|v| (v & 0xffff) as u16)46		.collect::<Vec<_>>()47		.try_into()48		.unwrap()49}50pub fn create_var_data<const S: u32>(size: u32) -> BoundedVec<u8, ConstU32<S>> {51	assert!(size <= S, "size ({size}) should be less within bound ({S})",);52	(0..size)53		.map(|v| (v & 0xff) as u8)54		.collect::<Vec<_>>()55		.try_into()56		.unwrap()57}58pub fn property_key(id: usize) -> PropertyKey {59	#[cfg(not(feature = "std"))]60	use alloc::string::ToString;61	let mut data = create_data();62	// No DerefMut available for .fill63	for i in 0..data.len() {64		data[i] = b'0';65	}66	let bytes = id.to_string();67	let len = data.len();68	data[len - bytes.len()..].copy_from_slice(bytes.as_bytes());69	data70}71pub fn property_value() -> PropertyValue {72	create_data()73}7475pub fn create_collection_raw<T: Config, R>(76	owner: T::CrossAccountId,77	mode: CollectionMode,78	handler: impl FnOnce(79		T::CrossAccountId,80		CreateCollectionData<T::CrossAccountId>,81	) -> Result<CollectionId, DispatchError>,82	cast: impl FnOnce(CollectionHandle<T>) -> R,83) -> Result<R, DispatchError> {84	let imbalance = <T as Config>::Currency::deposit(85		owner.as_sub(),86		T::CollectionCreationPrice::get(),87		Precision::Exact,88	)?;89	debug_assert!(imbalance.peek().is_zero());90	let name = create_u16_data::<MAX_COLLECTION_NAME_LENGTH>();91	let description = create_u16_data::<MAX_COLLECTION_DESCRIPTION_LENGTH>();92	let token_prefix = create_data::<MAX_TOKEN_PREFIX_LENGTH>();93	handler(94		owner,95		CreateCollectionData {96			mode,97			name,98			description,99			token_prefix,100			permissions: Some(CollectionPermissions {101				nesting: Some(NestingPermissions {102					token_owner: false,103					collection_admin: false,104					restricted: None,105					#[cfg(feature = "runtime-benchmarks")]106					permissive: true,107				}),108				mint_mode: Some(true),109				..Default::default()110			}),111			..Default::default()112		},113	)114	.and_then(CollectionHandle::try_get)115	.map(cast)116}117fn create_collection<T: Config>(118	owner: T::CrossAccountId,119) -> Result<CollectionHandle<T>, DispatchError> {120	create_collection_raw(121		owner,122		CollectionMode::NFT,123		|owner: T::CrossAccountId, data| {124			<Pallet<T>>::init_collection(owner.clone(), Some(owner), data)125		},126		|h| h,127	)128}129130/// Helper macros, which handles all benchmarking preparation in semi-declarative way131///132/// `name` is a substrate account133/// - name: sub[(id)]134/// `name` is a collection with owner `owner`135/// - name: collection(owner)136/// `name` is a cross account based on substrate137/// - name: cross_sub[(id)]138/// `name` is a cross account, which maps to substrate account `name`139/// - name: cross_from_sub140/// `name` is a cross account, which maps to substrate account `other_name`141/// - name: cross_from_sub(other_name)142#[macro_export]143macro_rules! bench_init {144	($name:ident: sub $(($id:expr))?; $($rest:tt)*) => {145		let $name: T::AccountId = account(stringify!($name), 0 $(+ $id)?, SEED);146		bench_init!($($rest)*);147	};148	($name:ident: collection($owner:ident); $($rest:tt)*) => {149		let $name = create_collection::<T>(T::CrossAccountId::from_sub($owner.clone()))?;150		bench_init!($($rest)*);151	};152	($name:ident: cross; $($rest:tt)*) => {153		let $name = T::CrossAccountId::from_sub($name);154		bench_init!($($rest)*);155	};156	($name:ident: cross_sub $(($id:expr))?; $($rest:tt)*) => {157		let account: T::AccountId = account(stringify!($name), 0 $(+ $id)?, SEED);158		let $name = T::CrossAccountId::from_sub(account);159		bench_init!($($rest)*);160	};161	($name:ident: cross_from_sub; $($rest:tt)*) => {162		let $name = T::CrossAccountId::from_sub($name);163		bench_init!($($rest)*);164	};165	($name:ident: cross_from_sub($from:ident); $($rest:tt)*) => {166		let $name = T::CrossAccountId::from_sub($from);167		bench_init!($($rest)*);168	};169	() => {}170}171172#[benchmarks]173mod benchmarks {174	use super::*;175176	#[benchmark]177	fn set_collection_properties(178		b: Linear<0, MAX_PROPERTIES_PER_ITEM>,179	) -> Result<(), BenchmarkError> {180		bench_init! {181			owner: sub; collection: collection(owner);182			owner: cross_from_sub;183		};184		let props = (0..b)185			.map(|p| Property {186				key: property_key(p as usize),187				value: property_value(),188			})189			.collect::<Vec<_>>();190191		#[block]192		{193			<Pallet<T>>::set_collection_properties(&collection, &owner, props.into_iter())?;194		}195196		Ok(())197	}198199	#[benchmark]200	fn check_accesslist() -> Result<(), BenchmarkError> {201		bench_init! {202			owner: sub; collection: collection(owner);203			sender: cross_from_sub(owner);204		};205206		let mut collection_handle = <CollectionHandle<T>>::try_get(collection.id)?;207		<Pallet<T>>::update_permissions(208			&sender,209			&mut collection_handle,210			CollectionPermissions {211				access: Some(AccessMode::AllowList),212				..Default::default()213			},214		)?;215216		<Pallet<T>>::toggle_allowlist(&collection, &sender, &sender, true)?;217218		assert_eq!(219			collection_handle.permissions.access(),220			AccessMode::AllowList221		);222223		#[block]224		{225			collection_handle.check_allowlist(&sender)?;226		}227228		Ok(())229	}230231	#[benchmark]232	fn property_writer_load_collection_info() -> Result<(), BenchmarkError> {233		bench_init! {234			owner: sub; collection: collection(owner);235			sender: sub;236			sender: cross_from_sub(sender);237		};238239		#[block]240		{241			<BenchmarkPropertyWriter<T>>::load_collection_info(&&collection, &sender);242		}243244		Ok(())245	}246}
modifiedpallets/foreign-assets/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/foreign-assets/src/benchmarking.rs
+++ b/pallets/foreign-assets/src/benchmarking.rs
@@ -16,88 +16,29 @@
 
 #![allow(missing_docs)]
 
-use frame_benchmarking::{account, v2::*};
-use frame_support::traits::Currency;
+use frame_benchmarking::v2::*;
 use frame_system::RawOrigin;
-use sp_std::{boxed::Box, vec, vec::Vec};
-use staging_xcm::{opaque::latest::Junction::Parachain, v3::Junctions::X1, VersionedMultiLocation};
+use pallet_common::benchmarking::create_u16_data;
+use sp_std::vec;
+use staging_xcm::prelude::*;
+use up_data_structs::{CollectionMode, MAX_COLLECTION_NAME_LENGTH};
 
 use super::{Call, Config, Pallet};
-use crate::AssetMetadata;
 
-fn bounded<T: TryFrom<Vec<u8>>>(slice: &[u8]) -> T {
-	T::try_from(slice.to_vec())
-		.map_err(|_| "slice doesn't fit")
-		.unwrap()
-}
-
 #[benchmarks]
 mod benchmarks {
-	use super::*;
-
-	#[benchmark]
-	fn register_foreign_asset() -> Result<(), BenchmarkError> {
-		let owner: T::AccountId = account("user", 0, 1);
-		let location: VersionedMultiLocation = VersionedMultiLocation::from(X1(Parachain(1000)));
-		let metadata: AssetMetadata<
-			<<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance,
-		> = AssetMetadata {
-			name: bounded(b"name"),
-			symbol: bounded(b"symbol"),
-			decimals: 18,
-			minimal_balance: 1u32.into(),
-		};
-		let mut balance: <<T as Config>::Currency as Currency<
-			<T as frame_system::Config>::AccountId,
-		>>::Balance = 4_000_000_000u32.into();
-		balance = balance * balance;
-		<T as Config>::Currency::make_free_balance_be(&owner, balance);
 
-		#[extrinsic_call]
-		_(
-			RawOrigin::Root,
-			owner,
-			Box::new(location),
-			Box::new(metadata),
-		);
-
-		Ok(())
-	}
+	use super::*;
 
 	#[benchmark]
-	fn update_foreign_asset() -> Result<(), BenchmarkError> {
-		let owner: T::AccountId = account("user", 0, 1);
-		let location: VersionedMultiLocation = VersionedMultiLocation::from(X1(Parachain(2000)));
-		let metadata: AssetMetadata<
-			<<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance,
-		> = AssetMetadata {
-			name: bounded(b"name"),
-			symbol: bounded(b"symbol"),
-			decimals: 18,
-			minimal_balance: 1u32.into(),
-		};
-		let metadata2: AssetMetadata<
-			<<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance,
-		> = AssetMetadata {
-			name: bounded(b"name2"),
-			symbol: bounded(b"symbol2"),
-			decimals: 18,
-			minimal_balance: 1u32.into(),
-		};
-		let mut balance: <<T as Config>::Currency as Currency<
-			<T as frame_system::Config>::AccountId,
-		>>::Balance = 4_000_000_000u32.into();
-		balance = balance * balance;
-		<T as Config>::Currency::make_free_balance_be(&owner, balance);
-		Pallet::<T>::register_foreign_asset(
-			RawOrigin::Root.into(),
-			owner,
-			Box::new(location.clone()),
-			Box::new(metadata),
-		)?;
+	fn force_register_foreign_asset() -> Result<(), BenchmarkError> {
+		let location =
+			MultiLocation::from(X3(Parachain(1000), PalletInstance(42), GeneralIndex(1)));
+		let name = create_u16_data::<MAX_COLLECTION_NAME_LENGTH>();
+		let mode = CollectionMode::NFT;
 
 		#[extrinsic_call]
-		_(RawOrigin::Root, 0, Box::new(location), Box::new(metadata2));
+		_(RawOrigin::Root, location, name, mode);
 
 		Ok(())
 	}
modifiedpallets/fungible/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/fungible/src/benchmarking.rs
+++ b/pallets/fungible/src/benchmarking.rs
@@ -15,7 +15,7 @@
 // along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
 use frame_benchmarking::{account, v2::*};
-use pallet_common::{bench_init, benchmarking::create_collection_raw};
+use pallet_common::{bench_init, benchmarking::create_collection_raw, Pallet as PalletCommon};
 use sp_std::prelude::*;
 use up_data_structs::{budget::Unlimited, CollectionMode, MAX_ITEMS_PER_BATCH};
 
@@ -30,7 +30,9 @@
 	create_collection_raw(
 		owner,
 		CollectionMode::Fungible(0),
-		|owner: T::CrossAccountId, data| <Pallet<T>>::init_collection(owner.clone(), owner, data),
+		|owner: T::CrossAccountId, data| {
+			<PalletCommon<T>>::init_collection(owner.clone(), Some(owner), data)
+		},
 		FungibleHandle::cast,
 	)
 }
modifiedpallets/nonfungible/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/benchmarking.rs
+++ b/pallets/nonfungible/src/benchmarking.rs
@@ -18,6 +18,7 @@
 use pallet_common::{
 	bench_init,
 	benchmarking::{create_collection_raw, property_key, property_value},
+	Pallet as PalletCommon,
 };
 use sp_std::prelude::*;
 use up_data_structs::{
@@ -56,7 +57,9 @@
 	create_collection_raw(
 		owner,
 		CollectionMode::NFT,
-		|owner: T::CrossAccountId, data| <Pallet<T>>::init_collection(owner.clone(), owner, data),
+		|owner: T::CrossAccountId, data| {
+			<PalletCommon<T>>::init_collection(owner.clone(), Some(owner), data)
+		},
 		NonfungibleHandle::cast,
 	)
 }
modifiedpallets/structure/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/structure/src/benchmarking.rs
+++ b/pallets/structure/src/benchmarking.rs
@@ -44,7 +44,7 @@
 		.unwrap();
 		T::CollectionDispatch::create(
 			caller_cross.clone(),
-			caller_cross.clone(),
+			Some(caller_cross.clone()),
 			CreateCollectionData {
 				mode: CollectionMode::NFT,
 				..Default::default()