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

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 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::{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!(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	let imbalance = <T as Config>::Currency::deposit(89		&owner.as_sub(),90		T::CollectionCreationPrice::get(),91		Precision::Exact,92	)?;93	debug_assert!(imbalance.peek().is_zero());94	let name = create_u16_data::<MAX_COLLECTION_NAME_LENGTH>();95	let description = create_u16_data::<MAX_COLLECTION_DESCRIPTION_LENGTH>();96	let token_prefix = create_data::<MAX_TOKEN_PREFIX_LENGTH>();97	handler(98		owner,99		CreateCollectionData {100			mode,101			name,102			description,103			token_prefix,104			permissions: Some(CollectionPermissions {105				nesting: Some(NestingPermissions {106					token_owner: false,107					collection_admin: false,108					restricted: None,109					#[cfg(feature = "runtime-benchmarks")]110					permissive: true,111				}),112				mint_mode: Some(true),113				..Default::default()114			}),115			..Default::default()116		},117	)118	.and_then(CollectionHandle::try_get)119	.map(cast)120}121fn create_collection<T: Config>(122	owner: T::CrossAccountId,123) -> Result<CollectionHandle<T>, DispatchError> {124	create_collection_raw(125		owner,126		CollectionMode::NFT,127		|owner: T::CrossAccountId, data| {128			<Pallet<T>>::init_collection(owner.clone(), owner, data, CollectionFlags::default())129		},130		|h| h,131	)132}133134/// Helper macros, which handles all benchmarking preparation in semi-declarative way135///136/// `name` is a substrate account137/// - name: sub[(id)]138/// `name` is a collection with owner `owner`139/// - name: collection(owner)140/// `name` is a cross account based on substrate141/// - name: cross_sub[(id)]142/// `name` is a cross account, which maps to substrate account `name`143/// - name: cross_from_sub144/// `name` is a cross account, which maps to substrate account `other_name`145/// - name: cross_from_sub(other_name)146#[macro_export]147macro_rules! bench_init {148	($name:ident: sub $(($id:expr))?; $($rest:tt)*) => {149		let $name: T::AccountId = account(stringify!($name), 0 $(+ $id)?, SEED);150		bench_init!($($rest)*);151	};152	($name:ident: collection($owner:ident); $($rest:tt)*) => {153		let $name = create_collection::<T>(T::CrossAccountId::from_sub($owner.clone()))?;154		bench_init!($($rest)*);155	};156	($name:ident: cross; $($rest:tt)*) => {157		let $name = T::CrossAccountId::from_sub($name);158		bench_init!($($rest)*);159	};160	($name:ident: cross_sub $(($id:expr))?; $($rest:tt)*) => {161		let account: T::AccountId = account(stringify!($name), 0 $(+ $id)?, SEED);162		let $name = T::CrossAccountId::from_sub(account);163		bench_init!($($rest)*);164	};165	($name:ident: cross_from_sub; $($rest:tt)*) => {166		let $name = T::CrossAccountId::from_sub($name);167		bench_init!($($rest)*);168	};169	($name:ident: cross_from_sub($from:ident); $($rest:tt)*) => {170		let $name = T::CrossAccountId::from_sub($from);171		bench_init!($($rest)*);172	};173	() => {}174}175176benchmarks! {177	set_collection_properties {178		let b in 0..MAX_PROPERTIES_PER_ITEM;179		bench_init!{180			owner: sub; collection: collection(owner);181			owner: cross_from_sub;182		};183		let props = (0..b).map(|p| Property {184			key: property_key(p as usize),185			value: property_value(),186		}).collect::<Vec<_>>();187	}: {<Pallet<T>>::set_collection_properties(&collection, &owner, props.into_iter())?}188189	delete_collection_properties {190		let b in 0..MAX_PROPERTIES_PER_ITEM;191		bench_init!{192			owner: sub; collection: collection(owner);193			owner: cross_from_sub;194		};195		let props = (0..b).map(|p| Property {196			key: property_key(p as usize),197			value: property_value(),198		}).collect::<Vec<_>>();199		<Pallet<T>>::set_collection_properties(&collection, &owner, props.into_iter())?;200		let to_delete = (0..b).map(|p| property_key(p as usize)).collect::<Vec<_>>();201	}: {<Pallet<T>>::delete_collection_properties(&collection, &owner, to_delete.into_iter())?}202203	check_accesslist{204		bench_init!{205			owner: sub; collection: collection(owner);206			sender: cross_from_sub(owner);207		};208209		let mut collection_handle = <CollectionHandle<T>>::try_get(collection.id)?;210			<Pallet<T>>::update_permissions(211				&sender,212				&mut collection_handle,213				CollectionPermissions { access: Some(AccessMode::AllowList), ..Default::default() }214			)?;215216		<Pallet<T>>::toggle_allowlist(217				&collection,218				&sender,219				&sender,220				true,221			)?;222223		assert_eq!(collection_handle.permissions.access(), AccessMode::AllowList);224225	}: {collection_handle.check_allowlist(&sender)?;}226}