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

difftreelog

source

pallets/common/src/benchmarking.rs6.7 KiBsourcehistory
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}