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

difftreelog

feat switch `common` from `Currency` trait to `fungible::*` traits

Grigoriy Simonov2023-05-22parent: #3539f20.patch.diff
in: master

2 files changed

modifiedpallets/common/src/benchmarking.rsdiffbeforeafterboth
before · pallets/common/src/benchmarking.rs
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}
after · pallets/common/src/benchmarking.rs
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}
modifiedpallets/common/src/lib.rsdiffbeforeafterboth
--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -64,7 +64,11 @@
 use frame_support::{
 	dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},
 	ensure,
-	traits::{Imbalance, Get, Currency, WithdrawReasons, ExistenceRequirement},
+	traits::{
+		Get,
+		fungible::{Balanced, Debt, Inspect},
+		tokens::{Imbalance, Precision, Preservation},
+	},
 	dispatch::Pays,
 	transactional, fail,
 };
@@ -85,7 +89,7 @@
 
 pub use pallet::*;
 use sp_core::H160;
-use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};
+use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, traits::Zero};
 
 #[cfg(feature = "runtime-benchmarks")]
 pub mod benchmarking;
@@ -424,7 +428,6 @@
 	use super::*;
 	use dispatch::CollectionDispatch;
 	use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};
-	use frame_support::traits::Currency;
 	use up_data_structs::{TokenId, mapping::TokenAddressMapping};
 	use scale_info::TypeInfo;
 	use weights::WeightInfo;
@@ -440,12 +443,12 @@
 		type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;
 
 		/// Handler of accounts and payment.
-		type Currency: Currency<Self::AccountId>;
+		type Currency: Balanced<Self::AccountId> + Inspect<Self::AccountId>;
 
 		/// Set price to create a collection.
 		#[pallet::constant]
 		type CollectionCreationPrice: Get<
-			<<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,
+			<<Self as Config>::Currency as Inspect<Self::AccountId>>::Balance,
 		>;
 
 		/// Dispatcher of operations on collections.
@@ -1112,21 +1115,17 @@
 
 		// Take a (non-refundable) deposit of collection creation
 		{
-			let mut imbalance =
-				<<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();
-			imbalance.subsume(
-				<<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(
-					&T::TreasuryAccountId::get(),
-					T::CollectionCreationPrice::get(),
-				),
-			);
-			<T as Config>::Currency::settle(
-				payer.as_sub(),
-				imbalance,
-				WithdrawReasons::TRANSFER,
-				ExistenceRequirement::KeepAlive,
-			)
-			.map_err(|_| Error::<T>::NotSufficientFounds)?;
+			let mut imbalance = <Debt<T::AccountId, <T as Config>::Currency>>::zero();
+			imbalance.subsume(<T as Config>::Currency::deposit(
+				&T::TreasuryAccountId::get(),
+				T::CollectionCreationPrice::get(),
+				Precision::Exact,
+			)?);
+			let credit =
+				<T as Config>::Currency::settle(payer.as_sub(), imbalance, Preservation::Preserve)
+					.map_err(|_| Error::<T>::NotSufficientFounds)?;
+
+			debug_assert!(credit.peek().is_zero())
 		}
 
 		<CreatedCollectionCount<T>>::put(created_count);