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

difftreelog

source

pallets/common/src/benchmarking.rs7.2 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, CreateCollectionData, CollectionId, Property, PropertyKey, PropertyValue,25	CollectionPermissions, NestingPermissions, AccessMode, PropertiesPermissionMap,26	MAX_COLLECTION_NAME_LENGTH, MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH,27	MAX_PROPERTIES_PER_ITEM,28};29use frame_support::{30	traits::{Get, fungible::Balanced, Imbalance, tokens::Precision},31	pallet_prelude::ConstU32,32	BoundedVec,33};34use core::convert::TryInto;35use sp_runtime::{DispatchError, traits::Zero};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!(size <= S, "size ({size}) should be less within bound ({S})",);51	(0..size)52		.map(|v| (v & 0xff) as u8)53		.collect::<Vec<_>>()54		.try_into()55		.unwrap()56}57pub fn property_key(id: usize) -> PropertyKey {58	#[cfg(not(feature = "std"))]59	use alloc::string::ToString;60	let mut data = create_data();61	// No DerefMut available for .fill62	for i in 0..data.len() {63		data[i] = b'0';64	}65	let bytes = id.to_string();66	let len = data.len();67	data[len - bytes.len()..].copy_from_slice(bytes.as_bytes());68	data69}70pub fn property_value() -> PropertyValue {71	create_data()72}7374pub fn create_collection_raw<T: Config, R>(75	owner: T::CrossAccountId,76	mode: CollectionMode,77	handler: impl FnOnce(78		T::CrossAccountId,79		CreateCollectionData<T::CrossAccountId>,80	) -> Result<CollectionId, DispatchError>,81	cast: impl FnOnce(CollectionHandle<T>) -> R,82) -> Result<R, DispatchError> {83	let imbalance = <T as Config>::Currency::deposit(84		owner.as_sub(),85		T::CollectionCreationPrice::get(),86		Precision::Exact,87	)?;88	debug_assert!(imbalance.peek().is_zero());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| <Pallet<T>>::init_collection(owner.clone(), owner, data),123		|h| h,124	)125}126127pub fn load_is_admin_and_property_permissions<T: Config>(128	collection: &CollectionHandle<T>,129	sender: &T::CrossAccountId,130) -> (bool, PropertiesPermissionMap) {131	(132		collection.is_owner_or_admin(sender),133		<Pallet<T>>::property_permissions(collection.id),134	)135}136137/// Helper macros, which handles all benchmarking preparation in semi-declarative way138///139/// `name` is a substrate account140/// - name: sub[(id)]141/// `name` is a collection with owner `owner`142/// - name: collection(owner)143/// `name` is a cross account based on substrate144/// - name: cross_sub[(id)]145/// `name` is a cross account, which maps to substrate account `name`146/// - name: cross_from_sub147/// `name` is a cross account, which maps to substrate account `other_name`148/// - name: cross_from_sub(other_name)149#[macro_export]150macro_rules! bench_init {151	($name:ident: sub $(($id:expr))?; $($rest:tt)*) => {152		let $name: T::AccountId = account(stringify!($name), 0 $(+ $id)?, SEED);153		bench_init!($($rest)*);154	};155	($name:ident: collection($owner:ident); $($rest:tt)*) => {156		let $name = create_collection::<T>(T::CrossAccountId::from_sub($owner.clone()))?;157		bench_init!($($rest)*);158	};159	($name:ident: cross; $($rest:tt)*) => {160		let $name = T::CrossAccountId::from_sub($name);161		bench_init!($($rest)*);162	};163	($name:ident: cross_sub $(($id:expr))?; $($rest:tt)*) => {164		let account: T::AccountId = account(stringify!($name), 0 $(+ $id)?, SEED);165		let $name = T::CrossAccountId::from_sub(account);166		bench_init!($($rest)*);167	};168	($name:ident: cross_from_sub; $($rest:tt)*) => {169		let $name = T::CrossAccountId::from_sub($name);170		bench_init!($($rest)*);171	};172	($name:ident: cross_from_sub($from:ident); $($rest:tt)*) => {173		let $name = T::CrossAccountId::from_sub($from);174		bench_init!($($rest)*);175	};176	() => {}177}178179benchmarks! {180	set_collection_properties {181		let b in 0..MAX_PROPERTIES_PER_ITEM;182		bench_init!{183			owner: sub; collection: collection(owner);184			owner: cross_from_sub;185		};186		let props = (0..b).map(|p| Property {187			key: property_key(p as usize),188			value: property_value(),189		}).collect::<Vec<_>>();190	}: {<Pallet<T>>::set_collection_properties(&collection, &owner, props.into_iter())?}191192	delete_collection_properties {193		let b in 0..MAX_PROPERTIES_PER_ITEM;194		bench_init!{195			owner: sub; collection: collection(owner);196			owner: cross_from_sub;197		};198		let props = (0..b).map(|p| Property {199			key: property_key(p as usize),200			value: property_value(),201		}).collect::<Vec<_>>();202		<Pallet<T>>::set_collection_properties(&collection, &owner, props.into_iter())?;203		let to_delete = (0..b).map(|p| property_key(p as usize)).collect::<Vec<_>>();204	}: {<Pallet<T>>::delete_collection_properties(&collection, &owner, to_delete.into_iter())?}205206	check_accesslist{207		bench_init!{208			owner: sub; collection: collection(owner);209			sender: cross_from_sub(owner);210		};211212		let mut collection_handle = <CollectionHandle<T>>::try_get(collection.id)?;213			<Pallet<T>>::update_permissions(214				&sender,215				&mut collection_handle,216				CollectionPermissions { access: Some(AccessMode::AllowList), ..Default::default() }217			)?;218219		<Pallet<T>>::toggle_allowlist(220				&collection,221				&sender,222				&sender,223				true,224			)?;225226		assert_eq!(collection_handle.permissions.access(), AccessMode::AllowList);227228	}: {collection_handle.check_allowlist(&sender)?;}229230	init_token_properties_common {231		bench_init!{232			owner: sub; collection: collection(owner);233			sender: sub;234			sender: cross_from_sub(sender);235		};236	}: {load_is_admin_and_property_permissions(&collection, &sender);}237}