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

difftreelog

source

pallets/common/src/benchmarking.rs6.6 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 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, AccessMode,26	MAX_COLLECTION_NAME_LENGTH, MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH,27	MAX_PROPERTIES_PER_ITEM,28};29use frame_support::{30	traits::{Currency, Get},31	pallet_prelude::ConstU32,32	BoundedVec,33};34use core::convert::TryInto;35use sp_runtime::DispatchError;3637const SEED: u32 = 1;3839pub fn create_data<const S: u32>() -> BoundedVec<u8, ConstU32<S>> {40	create_var_data::<S>(S)41}42pub fn create_u16_data<const S: u32>() -> BoundedVec<u16, ConstU32<S>> {43	(0..S)44		.map(|v| (v & 0xffff) as u16)45		.collect::<Vec<_>>()46		.try_into()47		.unwrap()48}49pub fn create_var_data<const S: u32>(size: u32) -> BoundedVec<u8, ConstU32<S>> {50	assert!(51		size <= S,52		"size ({}) should be less within bound ({})",53		size,54		S55	);56	(0..size)57		.map(|v| (v & 0xff) as u8)58		.collect::<Vec<_>>()59		.try_into()60		.unwrap()61}62pub fn property_key(id: usize) -> PropertyKey {63	#[cfg(not(feature = "std"))]64	use alloc::string::ToString;65	let mut data = create_data();66	// No DerefMut available for .fill67	for i in 0..data.len() {68		data[i] = b'0';69	}70	let bytes = id.to_string();71	let len = data.len();72	data[len - bytes.len()..].copy_from_slice(&bytes.as_bytes());73	data74}75pub fn property_value() -> PropertyValue {76	create_data()77}7879pub fn create_collection_raw<T: Config, R>(80	owner: T::CrossAccountId,81	mode: CollectionMode,82	handler: impl FnOnce(83		T::CrossAccountId,84		CreateCollectionData<T::AccountId>,85	) -> Result<CollectionId, DispatchError>,86	cast: impl FnOnce(CollectionHandle<T>) -> R,87) -> Result<R, DispatchError> {88	<T as Config>::Currency::deposit_creating(&owner.as_sub(), T::CollectionCreationPrice::get());89	let name = create_u16_data::<MAX_COLLECTION_NAME_LENGTH>();90	let description = create_u16_data::<MAX_COLLECTION_DESCRIPTION_LENGTH>();91	let token_prefix = create_data::<MAX_TOKEN_PREFIX_LENGTH>();92	handler(93		owner,94		CreateCollectionData {95			mode,96			name,97			description,98			token_prefix,99			permissions: Some(CollectionPermissions {100				nesting: Some(NestingPermissions {101					token_owner: false,102					collection_admin: false,103					restricted: None,104					#[cfg(feature = "runtime-benchmarks")]105					permissive: true,106				}),107				mint_mode: Some(true),108				..Default::default()109			}),110			..Default::default()111		},112	)113	.and_then(CollectionHandle::try_get)114	.map(cast)115}116fn create_collection<T: Config>(117	owner: T::CrossAccountId,118) -> Result<CollectionHandle<T>, DispatchError> {119	create_collection_raw(120		owner,121		CollectionMode::NFT,122		|owner: T::CrossAccountId, data| {123			<Pallet<T>>::init_collection(owner.clone(), owner, data, CollectionFlags::default())124		},125		|h| h,126	)127}128129/// Helper macros, which handles all benchmarking preparation in semi-declarative way130///131/// `name` is a substrate account132/// - name: sub[(id)]133/// `name` is a collection with owner `owner`134/// - name: collection(owner)135/// `name` is a cross account based on substrate136/// - name: cross_sub[(id)]137/// `name` is a cross account, which maps to substrate account `name`138/// - name: cross_from_sub139/// `name` is a cross account, which maps to substrate account `other_name`140/// - name: cross_from_sub(other_name)141#[macro_export]142macro_rules! bench_init {143	($name:ident: sub $(($id:expr))?; $($rest:tt)*) => {144		let $name: T::AccountId = account(stringify!($name), 0 $(+ $id)?, SEED);145		bench_init!($($rest)*);146	};147	($name:ident: collection($owner:ident); $($rest:tt)*) => {148		let $name = create_collection::<T>(T::CrossAccountId::from_sub($owner.clone()))?;149		bench_init!($($rest)*);150	};151	($name:ident: cross; $($rest:tt)*) => {152		let $name = T::CrossAccountId::from_sub($name);153		bench_init!($($rest)*);154	};155	($name:ident: cross_sub $(($id:expr))?; $($rest:tt)*) => {156		let account: T::AccountId = account(stringify!($name), 0 $(+ $id)?, SEED);157		let $name = T::CrossAccountId::from_sub(account);158		bench_init!($($rest)*);159	};160	($name:ident: cross_from_sub; $($rest:tt)*) => {161		let $name = T::CrossAccountId::from_sub($name);162		bench_init!($($rest)*);163	};164	($name:ident: cross_from_sub($from:ident); $($rest:tt)*) => {165		let $name = T::CrossAccountId::from_sub($from);166		bench_init!($($rest)*);167	};168	() => {}169}170171benchmarks! {172	set_collection_properties {173		let b in 0..MAX_PROPERTIES_PER_ITEM;174		bench_init!{175			owner: sub; collection: collection(owner);176			owner: cross_from_sub;177		};178		let props = (0..b).map(|p| Property {179			key: property_key(p as usize),180			value: property_value(),181		}).collect::<Vec<_>>();182	}: {<Pallet<T>>::set_collection_properties(&collection, &owner, props.into_iter())?}183184	delete_collection_properties {185		let b in 0..MAX_PROPERTIES_PER_ITEM;186		bench_init!{187			owner: sub; collection: collection(owner);188			owner: cross_from_sub;189		};190		let props = (0..b).map(|p| Property {191			key: property_key(p as usize),192			value: property_value(),193		}).collect::<Vec<_>>();194		<Pallet<T>>::set_collection_properties(&collection, &owner, props.into_iter())?;195		let to_delete = (0..b).map(|p| property_key(p as usize)).collect::<Vec<_>>();196	}: {<Pallet<T>>::delete_collection_properties(&collection, &owner, to_delete.into_iter())?}197198	check_accesslist{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 { access: Some(AccessMode::AllowList), ..Default::default() }209			)?;210211		<Pallet<T>>::toggle_allowlist(212				&collection,213				&sender,214				&sender,215				true,216			)?;217218		assert_eq!(collection_handle.permissions.access(), AccessMode::AllowList);219220	}: {collection_handle.check_allowlist(&sender)?;}221}