git.delta.rocks / unique-network / refs/commits / 90ad566cc7e8

difftreelog

source

pallets/common/src/benchmarking.rs7.5 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, PropertiesPermissionMap, Property, PropertyKey, PropertyValue,33	MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_COLLECTION_NAME_LENGTH, MAX_PROPERTIES_PER_ITEM,34	MAX_TOKEN_PREFIX_LENGTH,35};3637use crate::{CollectionHandle, Config, Pallet};3839const SEED: u32 = 1;4041pub fn create_data<const S: u32>() -> BoundedVec<u8, ConstU32<S>> {42	create_var_data::<S>(S)43}44pub fn create_u16_data<const S: u32>() -> BoundedVec<u16, ConstU32<S>> {45	(0..S)46		.map(|v| (v & 0xffff) as u16)47		.collect::<Vec<_>>()48		.try_into()49		.unwrap()50}51pub fn create_var_data<const S: u32>(size: u32) -> BoundedVec<u8, ConstU32<S>> {52	assert!(size <= S, "size ({size}) should be less within bound ({S})",);53	(0..size)54		.map(|v| (v & 0xff) as u8)55		.collect::<Vec<_>>()56		.try_into()57		.unwrap()58}59pub fn property_key(id: usize) -> PropertyKey {60	#[cfg(not(feature = "std"))]61	use alloc::string::ToString;62	let mut data = create_data();63	// No DerefMut available for .fill64	for i in 0..data.len() {65		data[i] = b'0';66	}67	let bytes = id.to_string();68	let len = data.len();69	data[len - bytes.len()..].copy_from_slice(bytes.as_bytes());70	data71}72pub fn property_value() -> PropertyValue {73	create_data()74}7576pub fn create_collection_raw<T: Config, R>(77	owner: T::CrossAccountId,78	mode: CollectionMode,79	handler: impl FnOnce(80		T::CrossAccountId,81		CreateCollectionData<T::CrossAccountId>,82	) -> Result<CollectionId, DispatchError>,83	cast: impl FnOnce(CollectionHandle<T>) -> R,84) -> Result<R, DispatchError> {85	let imbalance = <T as Config>::Currency::deposit(86		owner.as_sub(),87		T::CollectionCreationPrice::get(),88		Precision::Exact,89	)?;90	debug_assert!(imbalance.peek().is_zero());91	let name = create_u16_data::<MAX_COLLECTION_NAME_LENGTH>();92	let description = create_u16_data::<MAX_COLLECTION_DESCRIPTION_LENGTH>();93	let token_prefix = create_data::<MAX_TOKEN_PREFIX_LENGTH>();94	handler(95		owner,96		CreateCollectionData {97			mode,98			name,99			description,100			token_prefix,101			permissions: Some(CollectionPermissions {102				nesting: Some(NestingPermissions {103					token_owner: false,104					collection_admin: false,105					restricted: None,106					#[cfg(feature = "runtime-benchmarks")]107					permissive: true,108				}),109				mint_mode: Some(true),110				..Default::default()111			}),112			..Default::default()113		},114	)115	.and_then(CollectionHandle::try_get)116	.map(cast)117}118fn create_collection<T: Config>(119	owner: T::CrossAccountId,120) -> Result<CollectionHandle<T>, DispatchError> {121	create_collection_raw(122		owner,123		CollectionMode::NFT,124		|owner: T::CrossAccountId, data| <Pallet<T>>::init_collection(owner.clone(), owner, data),125		|h| h,126	)127}128129pub fn load_is_admin_and_property_permissions<T: Config>(130	collection: &CollectionHandle<T>,131	sender: &T::CrossAccountId,132) -> (bool, PropertiesPermissionMap) {133	(134		collection.is_owner_or_admin(sender),135		<Pallet<T>>::property_permissions(collection.id),136	)137}138139/// Helper macros, which handles all benchmarking preparation in semi-declarative way140///141/// `name` is a substrate account142/// - name: sub[(id)]143/// `name` is a collection with owner `owner`144/// - name: collection(owner)145/// `name` is a cross account based on substrate146/// - name: cross_sub[(id)]147/// `name` is a cross account, which maps to substrate account `name`148/// - name: cross_from_sub149/// `name` is a cross account, which maps to substrate account `other_name`150/// - name: cross_from_sub(other_name)151#[macro_export]152macro_rules! bench_init {153	($name:ident: sub $(($id:expr))?; $($rest:tt)*) => {154		let $name: T::AccountId = account(stringify!($name), 0 $(+ $id)?, SEED);155		bench_init!($($rest)*);156	};157	($name:ident: collection($owner:ident); $($rest:tt)*) => {158		let $name = create_collection::<T>(T::CrossAccountId::from_sub($owner.clone()))?;159		bench_init!($($rest)*);160	};161	($name:ident: cross; $($rest:tt)*) => {162		let $name = T::CrossAccountId::from_sub($name);163		bench_init!($($rest)*);164	};165	($name:ident: cross_sub $(($id:expr))?; $($rest:tt)*) => {166		let account: T::AccountId = account(stringify!($name), 0 $(+ $id)?, SEED);167		let $name = T::CrossAccountId::from_sub(account);168		bench_init!($($rest)*);169	};170	($name:ident: cross_from_sub; $($rest:tt)*) => {171		let $name = T::CrossAccountId::from_sub($name);172		bench_init!($($rest)*);173	};174	($name:ident: cross_from_sub($from:ident); $($rest:tt)*) => {175		let $name = T::CrossAccountId::from_sub($from);176		bench_init!($($rest)*);177	};178	() => {}179}180181#[benchmarks]182mod benchmarks {183	use super::*;184185	#[benchmark]186	fn set_collection_properties(187		b: Linear<0, MAX_PROPERTIES_PER_ITEM>,188	) -> Result<(), BenchmarkError> {189		bench_init! {190			owner: sub; collection: collection(owner);191			owner: cross_from_sub;192		};193		let props = (0..b)194			.map(|p| Property {195				key: property_key(p as usize),196				value: property_value(),197			})198			.collect::<Vec<_>>();199200		#[block]201		{202			<Pallet<T>>::set_collection_properties(&collection, &owner, props.into_iter())?;203		}204205		Ok(())206	}207208	#[benchmark]209	fn delete_collection_properties(210		b: Linear<0, MAX_PROPERTIES_PER_ITEM>,211	) -> Result<(), BenchmarkError> {212		bench_init! {213			owner: sub; collection: collection(owner);214			owner: cross_from_sub;215		};216		let props = (0..b)217			.map(|p| Property {218				key: property_key(p as usize),219				value: property_value(),220			})221			.collect::<Vec<_>>();222		<Pallet<T>>::set_collection_properties(&collection, &owner, props.into_iter())?;223		let to_delete = (0..b).map(|p| property_key(p as usize)).collect::<Vec<_>>();224225		#[block]226		{227			<Pallet<T>>::delete_collection_properties(&collection, &owner, to_delete.into_iter())?;228		}229230		Ok(())231	}232233	#[benchmark]234	fn check_accesslist() -> Result<(), BenchmarkError> {235		bench_init! {236			owner: sub; collection: collection(owner);237			sender: cross_from_sub(owner);238		};239240		let mut collection_handle = <CollectionHandle<T>>::try_get(collection.id)?;241		<Pallet<T>>::update_permissions(242			&sender,243			&mut collection_handle,244			CollectionPermissions {245				access: Some(AccessMode::AllowList),246				..Default::default()247			},248		)?;249250		<Pallet<T>>::toggle_allowlist(&collection, &sender, &sender, true)?;251252		assert_eq!(253			collection_handle.permissions.access(),254			AccessMode::AllowList255		);256257		#[block]258		{259			collection_handle.check_allowlist(&sender)?;260		}261262		Ok(())263	}264265	#[benchmark]266	fn init_token_properties_common() -> Result<(), BenchmarkError> {267		bench_init! {268			owner: sub; collection: collection(owner);269			sender: sub;270			sender: cross_from_sub(sender);271		};272273		#[block]274		{275			load_is_admin_and_property_permissions(&collection, &sender);276		}277278		Ok(())279	}280}