1234567891011121314151617#![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::{BenchmarkPropertyWriter, 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 64 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}128129130131132133134135136137138139140141#[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}170171#[benchmarks]172mod benchmarks {173 use super::*;174175 #[benchmark]176 fn set_collection_properties(177 b: Linear<0, MAX_PROPERTIES_PER_ITEM>,178 ) -> Result<(), BenchmarkError> {179 bench_init! {180 owner: sub; collection: collection(owner);181 owner: cross_from_sub;182 };183 let props = (0..b)184 .map(|p| Property {185 key: property_key(p as usize),186 value: property_value(),187 })188 .collect::<Vec<_>>();189190 #[block]191 {192 <Pallet<T>>::set_collection_properties(&collection, &owner, props.into_iter())?;193 }194195 Ok(())196 }197198 #[benchmark]199 fn delete_collection_properties(200 b: Linear<0, MAX_PROPERTIES_PER_ITEM>,201 ) -> Result<(), BenchmarkError> {202 bench_init! {203 owner: sub; collection: collection(owner);204 owner: cross_from_sub;205 };206 let props = (0..b)207 .map(|p| Property {208 key: property_key(p as usize),209 value: property_value(),210 })211 .collect::<Vec<_>>();212 <Pallet<T>>::set_collection_properties(&collection, &owner, props.into_iter())?;213 let to_delete = (0..b).map(|p| property_key(p as usize)).collect::<Vec<_>>();214215 #[block]216 {217 <Pallet<T>>::delete_collection_properties(&collection, &owner, to_delete.into_iter())?;218 }219220 Ok(())221 }222223 #[benchmark]224 fn check_accesslist() -> Result<(), BenchmarkError> {225 bench_init! {226 owner: sub; collection: collection(owner);227 sender: cross_from_sub(owner);228 };229230 let mut collection_handle = <CollectionHandle<T>>::try_get(collection.id)?;231 <Pallet<T>>::update_permissions(232 &sender,233 &mut collection_handle,234 CollectionPermissions {235 access: Some(AccessMode::AllowList),236 ..Default::default()237 },238 )?;239240 <Pallet<T>>::toggle_allowlist(&collection, &sender, &sender, true)?;241242 assert_eq!(243 collection_handle.permissions.access(),244 AccessMode::AllowList245 );246247 #[block]248 {249 collection_handle.check_allowlist(&sender)?;250 }251252 Ok(())253 }254255 #[benchmark]256 fn init_token_properties_common() -> Result<(), BenchmarkError> {257 bench_init! {258 owner: sub; collection: collection(owner);259 sender: sub;260 sender: cross_from_sub(sender);261 };262263 #[block]264 {265 <BenchmarkPropertyWriter<T>>::load_collection_info(&&collection, &sender);266 }267268 Ok(())269 }270}