git.delta.rocks / unique-network / refs/commits / 742862849b4b

difftreelog

fix EVM mint with properties, minor improvements

Daniel Shiposha2023-10-13parent: #aae21d3.patch.diff
in: master

9 files changed

modifiedpallets/common/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/common/src/benchmarking.rs
+++ b/pallets/common/src/benchmarking.rs
@@ -29,9 +29,8 @@
 use sp_std::{vec, vec::Vec};
 use up_data_structs::{
 	AccessMode, CollectionId, CollectionMode, CollectionPermissions, CreateCollectionData,
-	NestingPermissions, PropertiesPermissionMap, Property, PropertyKey, PropertyValue,
-	MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_COLLECTION_NAME_LENGTH, MAX_PROPERTIES_PER_ITEM,
-	MAX_TOKEN_PREFIX_LENGTH,
+	NestingPermissions, Property, PropertyKey, PropertyValue, MAX_COLLECTION_DESCRIPTION_LENGTH,
+	MAX_COLLECTION_NAME_LENGTH, MAX_PROPERTIES_PER_ITEM, MAX_TOKEN_PREFIX_LENGTH,
 };
 
 use crate::{BenchmarkPropertyWriter, CollectionHandle, Config, Pallet};
@@ -190,31 +189,6 @@
 		#[block]
 		{
 			<Pallet<T>>::set_collection_properties(&collection, &owner, props.into_iter())?;
-		}
-
-		Ok(())
-	}
-
-	#[benchmark]
-	fn delete_collection_properties(
-		b: Linear<0, MAX_PROPERTIES_PER_ITEM>,
-	) -> Result<(), BenchmarkError> {
-		bench_init! {
-			owner: sub; collection: collection(owner);
-			owner: cross_from_sub;
-		};
-		let props = (0..b)
-			.map(|p| Property {
-				key: property_key(p as usize),
-				value: property_value(),
-			})
-			.collect::<Vec<_>>();
-		<Pallet<T>>::set_collection_properties(&collection, &owner, props.into_iter())?;
-		let to_delete = (0..b).map(|p| property_key(p as usize)).collect::<Vec<_>>();
-
-		#[block]
-		{
-			<Pallet<T>>::delete_collection_properties(&collection, &owner, to_delete.into_iter())?;
 		}
 
 		Ok(())
@@ -253,7 +227,7 @@
 	}
 
 	#[benchmark]
-	fn init_token_properties_common() -> Result<(), BenchmarkError> {
+	fn property_writer_load_collection_info() -> Result<(), BenchmarkError> {
 		bench_init! {
 			owner: sub; collection: collection(owner);
 			sender: sub;
modifiedpallets/common/src/erc.rsdiffbeforeafterboth
--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -126,7 +126,7 @@
 	///
 	/// @param key Property key.
 	#[solidity(hide)]
-	#[weight(<SelfWeightOf<T>>::delete_collection_properties(1))]
+	#[weight(<SelfWeightOf<T>>::set_collection_properties(1))]
 	fn delete_collection_property(&mut self, caller: Caller, key: String) -> Result<()> {
 		let caller = T::CrossAccountId::from_eth(caller);
 		let key = <Vec<u8>>::from(key)
@@ -139,7 +139,7 @@
 	/// Delete collection properties.
 	///
 	/// @param keys Properties keys.
-	#[weight(<SelfWeightOf<T>>::delete_collection_properties(keys.len() as u32))]
+	#[weight(<SelfWeightOf<T>>::set_collection_properties(keys.len() as u32))]
 	fn delete_collection_properties(&mut self, caller: Caller, keys: Vec<String>) -> Result<()> {
 		let caller = T::CrossAccountId::from_eth(caller);
 		let keys = keys
modifiedpallets/common/src/lib.rsdiffbeforeafterboth
--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -2626,8 +2626,8 @@
 impl<T: Config> BenchmarkPropertyWriter<T> {
 	/// Creates a [`PropertyWriter`] for benchmarking tokens properties writing.
 	pub fn new<'a, Handle>(
-		collection: &Handle,
-		collection_lazy_info: PropertyWriterLazyCollectionInfo,
+		collection: &'a Handle,
+		collection_lazy_info: PropertyWriterLazyCollectionInfo<'a>,
 	) -> PropertyWriter<'a, Self, T, Handle>
 	where
 		Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,
modifiedpallets/nonfungible/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/benchmarking.rs
+++ b/pallets/nonfungible/src/benchmarking.rs
@@ -18,7 +18,6 @@
 use pallet_common::{
 	bench_init,
 	benchmarking::{create_collection_raw, property_key, property_value},
-	CommonCollectionOperations,
 };
 use sp_std::prelude::*;
 use up_data_structs::{
@@ -131,53 +130,12 @@
 		#[block]
 		{
 			<Pallet<T>>::burn(&collection, &burner, item)?;
-		}
-
-		Ok(())
-	}
-
-	#[benchmark]
-	fn burn_recursively_self_raw() -> Result<(), BenchmarkError> {
-		bench_init! {
-			owner: sub; collection: collection(owner);
-			sender: cross_from_sub(owner); burner: cross_sub;
-		};
-		let item = create_max_item(&collection, &sender, burner.clone())?;
-
-		#[block]
-		{
-			<Pallet<T>>::burn_recursively(&collection, &burner, item, &Unlimited, &Unlimited)?;
 		}
 
 		Ok(())
 	}
 
 	#[benchmark]
-	fn burn_recursively_breadth_plus_self_plus_self_per_each_raw(
-		b: Linear<0, 200>,
-	) -> Result<(), BenchmarkError> {
-		bench_init! {
-			owner: sub; collection: collection(owner);
-			sender: cross_from_sub(owner); burner: cross_sub;
-		};
-		let item = create_max_item(&collection, &sender, burner.clone())?;
-		for _ in 0..b {
-			create_max_item(
-				&collection,
-				&sender,
-				T::CrossTokenAddressMapping::token_to_address(collection.id, item),
-			)?;
-		}
-
-		#[block]
-		{
-			<Pallet<T>>::burn_recursively(&collection, &burner, item, &Unlimited, &Unlimited)?;
-		}
-
-		Ok(())
-	}
-
-	#[benchmark]
 	fn transfer_raw() -> Result<(), BenchmarkError> {
 		bench_init! {
 			owner: sub; collection: collection(owner);
@@ -262,116 +220,34 @@
 		{
 			<Pallet<T>>::burn_from(&collection, &burner, &sender, item, &Unlimited)?;
 		}
-	}
 
-	// set_token_properties {
-	// 	let b in 0..MAX_PROPERTIES_PER_ITEM;
-	// 	bench_init!{
-	// 		owner: sub; collection: collection(owner);
-	// 		owner: cross_from_sub;
-	// 	};
-	// 	let perms = (0..b).map(|k| PropertyKeyPermission {
-	// 		key: property_key(k as usize),
-	// 		permission: PropertyPermission {
-	// 			mutable: false,
-	// 			collection_admin: true,
-	// 			token_owner: true,
-	// 		},
-	// 	}).collect::<Vec<_>>();
-	// 	<Pallet<T>>::set_token_property_permissions(&collection, &owner, perms)?;
-	// 	let props = (0..b).map(|k| Property {
-	// 		key: property_key(k as usize),
-	// 		value: property_value(),
-	// 	}).collect::<Vec<_>>();
-	// 	let item = create_max_item(&collection, &owner, owner.clone())?;
-	// }: {<Pallet<T>>::set_token_properties(&collection, &owner, item, props.into_iter(), &Unlimited)?}
-
-	// load_token_properties {
-	// 	bench_init!{
-	// 		owner: sub; collection: collection(owner);
-	// 		owner: cross_from_sub;
-	// 	};
-
-	// 	let item = create_max_item(&collection, &owner, owner.clone())?;
-	// }: {
-	// 	pallet_common::BenchmarkPropertyWriter::<T>::load_token_properties(
-	// 		&collection,
-	// 		item,
-	// 	)
-	// }
-
-	// write_token_properties {
-	// 	let b in 0..MAX_PROPERTIES_PER_ITEM;
-	// 	bench_init!{
-	// 		owner: sub; collection: collection(owner);
-	// 		owner: cross_from_sub;
-	// 	};
+		Ok(())
+	}
 
-	// 	let perms = (0..b).map(|k| PropertyKeyPermission {
-	// 		key: property_key(k as usize),
-	// 		permission: PropertyPermission {
-	// 			mutable: false,
-	// 			collection_admin: true,
-	// 			token_owner: true,
-	// 		},
-	// 	}).collect::<Vec<_>>();
-	// 	<Pallet<T>>::set_token_property_permissions(&collection, &owner, perms)?;
-	// 	let props = (0..b).map(|k| Property {
-	// 		key: property_key(k as usize),
-	// 		value: property_value(),
-	// 	}).collect::<Vec<_>>();
-	// 	let item = create_max_item(&collection, &owner, owner.clone())?;
-
-	// 	let lazy_collection_info = pallet_common::BenchmarkPropertyWriter::<T>::load_collection_info(
-	// 		&collection,
-	// 		&owner,
-	// 	);
-	// }: {
-	// 	let mut property_writer = pallet_common::BenchmarkPropertyWriter::new(&collection, lazy_collection_info);
-
-	// 	property_writer.write_token_properties(
-	// 		item,
-	// 		props.into_iter(),
-	// 		crate::erc::ERC721TokenEvent::TokenChanged {
-	// 			token_id: item.into(),
-	// 		}
-	// 		.to_log(T::ContractAddress::get()),
-	// 	)?
-	// }
-
 	#[benchmark]
-	fn set_token_property_permissions(
-		b: Linear<0, MAX_PROPERTIES_PER_ITEM>,
-	) -> Result<(), BenchmarkError> {
+	fn load_token_properties() -> Result<(), BenchmarkError> {
 		bench_init! {
 			owner: sub; collection: collection(owner);
 			owner: cross_from_sub;
 		};
-		let perms = (0..b)
-			.map(|k| PropertyKeyPermission {
-				key: property_key(k as usize),
-				permission: PropertyPermission {
-					mutable: false,
-					collection_admin: false,
-					token_owner: false,
-				},
-			})
-			.collect::<Vec<_>>();
 
+		let item = create_max_item(&collection, &owner, owner.clone())?;
+
 		#[block]
 		{
-			<Pallet<T>>::set_token_property_permissions(&collection, &owner, perms)?;
+			pallet_common::BenchmarkPropertyWriter::<T>::load_token_properties(&collection, item);
 		}
 
 		Ok(())
 	}
 
 	#[benchmark]
-	fn set_token_properties(b: Linear<0, MAX_PROPERTIES_PER_ITEM>) -> Result<(), BenchmarkError> {
+	fn write_token_properties(b: Linear<0, MAX_PROPERTIES_PER_ITEM>) -> Result<(), BenchmarkError> {
 		bench_init! {
 			owner: sub; collection: collection(owner);
 			owner: cross_from_sub;
 		};
+
 		let perms = (0..b)
 			.map(|k| PropertyKeyPermission {
 				key: property_key(k as usize),
@@ -391,71 +267,29 @@
 			.collect::<Vec<_>>();
 		let item = create_max_item(&collection, &owner, owner.clone())?;
 
+		let lazy_collection_info =
+			pallet_common::BenchmarkPropertyWriter::<T>::load_collection_info(&collection, &owner);
+
 		#[block]
 		{
-			<Pallet<T>>::set_token_properties(
-				&collection,
-				&owner,
+			let mut property_writer =
+				pallet_common::BenchmarkPropertyWriter::new(&collection, lazy_collection_info);
+
+			property_writer.write_token_properties(
 				item,
 				props.into_iter(),
-				&Unlimited,
+				crate::erc::ERC721TokenEvent::TokenChanged {
+					token_id: item.into(),
+				}
+				.to_log(T::ContractAddress::get()),
 			)?;
 		}
 
 		Ok(())
 	}
 
-	// TODO:
 	#[benchmark]
-	fn init_token_properties(b: Linear<0, MAX_PROPERTIES_PER_ITEM>) -> Result<(), BenchmarkError> {
-		// bench_init! {
-		// 	owner: sub; collection: collection(owner);
-		// 	owner: cross_from_sub;
-		// };
-
-		// let perms = (0..b)
-		// 	.map(|k| PropertyKeyPermission {
-		// 		key: property_key(k as usize),
-		// 		permission: PropertyPermission {
-		// 			mutable: false,
-		// 			collection_admin: true,
-		// 			token_owner: true,
-		// 		},
-		// 	})
-		// 	.collect::<Vec<_>>();
-		// <Pallet<T>>::set_token_property_permissions(&collection, &owner, perms)?;
-		#[block]
-		{}
-		// let props = (0..b)
-		// 	.map(|k| Property {
-		// 		key: property_key(k as usize),
-		// 		value: property_value(),
-		// 	})
-		// 	.collect::<Vec<_>>();
-		// let item = create_max_item(&collection, &owner, owner.clone())?;
-
-		// let (is_collection_admin, property_permissions) =
-		// 	load_is_admin_and_property_permissions(&collection, &owner);
-		// #[block]
-		// {
-		// 	let mut property_writer =
-		// 		pallet_common::BenchmarkPropertyWriter::new(&collection, lazy_collection_info);
-
-		// 	property_writer.write_token_properties(
-		// 		item,
-		// 		props.into_iter(),
-		// 		crate::erc::ERC721TokenEvent::TokenChanged {
-		// 			token_id: item.into(),
-		// 		}
-		// 		.to_log(T::ContractAddress::get()),
-		// 	)?;
-		// }
-
-		Ok(())
-	}
-
-	#[benchmark]
-	fn delete_token_properties(
+	fn set_token_property_permissions(
 		b: Linear<0, MAX_PROPERTIES_PER_ITEM>,
 	) -> Result<(), BenchmarkError> {
 		bench_init! {
@@ -466,54 +300,16 @@
 			.map(|k| PropertyKeyPermission {
 				key: property_key(k as usize),
 				permission: PropertyPermission {
-					mutable: true,
-					collection_admin: true,
-					token_owner: true,
+					mutable: false,
+					collection_admin: false,
+					token_owner: false,
 				},
-			})
-			.collect::<Vec<_>>();
-		<Pallet<T>>::set_token_property_permissions(&collection, &owner, perms)?;
-		let props = (0..b)
-			.map(|k| Property {
-				key: property_key(k as usize),
-				value: property_value(),
 			})
 			.collect::<Vec<_>>();
-		let item = create_max_item(&collection, &owner, owner.clone())?;
-		<Pallet<T>>::set_token_properties(
-			&collection,
-			&owner,
-			item,
-			props.into_iter(),
-			&Unlimited,
-		)?;
-		let to_delete = (0..b).map(|k| property_key(k as usize)).collect::<Vec<_>>();
 
 		#[block]
 		{
-			<Pallet<T>>::delete_token_properties(
-				&collection,
-				&owner,
-				item,
-				to_delete.into_iter(),
-				&Unlimited,
-			)?;
-		}
-
-		Ok(())
-	}
-
-	#[benchmark]
-	fn token_owner() -> Result<(), BenchmarkError> {
-		bench_init! {
-			owner: sub; collection: collection(owner);
-			owner: cross_from_sub;
-		};
-		let item = create_max_item(&collection, &owner, owner.clone())?;
-
-		#[block]
-		{
-			collection.token_owner(item).unwrap();
+			<Pallet<T>>::set_token_property_permissions(&collection, &owner, perms)?;
 		}
 
 		Ok(())
modifiedpallets/nonfungible/src/common.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -39,24 +39,21 @@
 impl<T: Config> CommonWeightInfo<T::CrossAccountId> for CommonWeights<T> {
 	fn create_multiple_items_ex(data: &CreateItemExData<T::CrossAccountId>) -> Weight {
 		match data {
-			CreateItemExData::NFT(t) => <SelfWeightOf<T>>::create_multiple_items_ex(t.len() as u32)
-				.saturating_add(write_token_properties_total_weight::<T, _>(
-					t.iter().map(|t| t.properties.len() as u32),
-					<SelfWeightOf<T>>::write_token_properties,
-				)),
+			CreateItemExData::NFT(t) => mint_with_props_weight::<T>(
+				<SelfWeightOf<T>>::create_multiple_items_ex(t.len() as u32),
+				t.iter().map(|t| t.properties.len() as u32),
+			),
 			_ => Weight::zero(),
 		}
 	}
 
 	fn create_multiple_items(data: &[up_data_structs::CreateItemData]) -> Weight {
-		<SelfWeightOf<T>>::create_multiple_items(data.len() as u32).saturating_add(
-			write_token_properties_total_weight::<T, _>(
-				data.iter().map(|t| match t {
-					up_data_structs::CreateItemData::NFT(n) => n.properties.len() as u32,
-					_ => 0,
-				}),
-				<SelfWeightOf<T>>::write_token_properties,
-			),
+		mint_with_props_weight::<T>(
+			<SelfWeightOf<T>>::create_multiple_items(data.len() as u32),
+			data.iter().map(|t| match t {
+				up_data_structs::CreateItemData::NFT(n) => n.properties.len() as u32,
+				_ => 0,
+			}),
 		)
 	}
 
@@ -113,6 +110,16 @@
 	}
 }
 
+pub(crate) fn mint_with_props_weight<T: Config>(
+	create_no_data_weight: Weight,
+	tokens: impl Iterator<Item = u32> + Clone,
+) -> Weight {
+	create_no_data_weight.saturating_add(write_token_properties_total_weight::<T, _>(
+		tokens,
+		<SelfWeightOf<T>>::write_token_properties,
+	))
+}
+
 fn map_create_data<T: Config>(
 	data: up_data_structs::CreateItemData,
 	to: &T::CrossAccountId,
modifiedpallets/nonfungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -49,8 +49,10 @@
 };
 
 use crate::{
-	common::CommonWeights, weights::WeightInfo, AccountBalance, Config, CreateItemData,
-	NonfungibleHandle, Pallet, SelfWeightOf, TokenData, TokenProperties, TokensMinted,
+	common::{mint_with_props_weight, CommonWeights},
+	weights::WeightInfo,
+	AccountBalance, Config, CreateItemData, NonfungibleHandle, Pallet, SelfWeightOf, TokenData,
+	TokenProperties, TokensMinted,
 };
 
 /// Nft events.
@@ -620,7 +622,7 @@
 	/// @param tokenUri Token URI that would be stored in the NFT properties
 	/// @return uint256 The id of the newly minted token
 	#[solidity(rename_selector = "mintWithTokenURI")]
-	#[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(1))]
+	#[weight(mint_with_props_weight::<T>(<SelfWeightOf<T>>::create_item(), [1].into_iter()))]
 	fn mint_with_token_uri(
 		&mut self,
 		caller: Caller,
@@ -642,7 +644,7 @@
 	/// @param tokenId ID of the minted NFT
 	/// @param tokenUri Token URI that would be stored in the NFT properties
 	#[solidity(hide, rename_selector = "mintWithTokenURI")]
-	#[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(1))]
+	#[weight(mint_with_props_weight::<T>(<SelfWeightOf<T>>::create_item(), [1].into_iter()))]
 	fn mint_with_token_uri_check_id(
 		&mut self,
 		caller: Caller,
@@ -974,7 +976,12 @@
 
 	/// @notice Function to mint a token.
 	/// @param data Array of pairs of token owner and token's properties for minted token
-	#[weight(<SelfWeightOf<T>>::create_multiple_items(data.len() as u32) + <SelfWeightOf<T>>::set_token_properties(data.len() as u32))]
+	#[weight(
+		mint_with_props_weight::<T>(
+			<SelfWeightOf<T>>::create_multiple_items_ex(data.len() as u32),
+			data.iter().map(|d| d.properties.len() as u32),
+		)
+	)]
 	fn mint_bulk_cross(&mut self, caller: Caller, data: Vec<MintTokenData>) -> Result<bool> {
 		let caller = T::CrossAccountId::from_eth(caller);
 
@@ -1008,7 +1015,12 @@
 	/// @param to The new owner
 	/// @param tokens array of pairs of token ID and token URI for minted tokens
 	#[solidity(hide, rename_selector = "mintBulkWithTokenURI")]
-	#[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32) + <SelfWeightOf<T>>::set_token_properties(tokens.len() as u32))]
+	#[weight(
+		mint_with_props_weight::<T>(
+			<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32),
+			tokens.iter().map(|_| 1),
+		)
+	)]
 	fn mint_bulk_with_token_uri(
 		&mut self,
 		caller: Caller,
@@ -1056,7 +1068,7 @@
 	/// @param to The new owner crossAccountId
 	/// @param properties Properties of minted token
 	/// @return uint256 The id of the newly minted token
-	#[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(properties.len() as u32))]
+	#[weight(mint_with_props_weight::<T>(<SelfWeightOf<T>>::create_item(), [properties.len() as u32].into_iter()))]
 	fn mint_cross(
 		&mut self,
 		caller: Caller,
modifiedpallets/refungible/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/refungible/src/benchmarking.rs
+++ b/pallets/refungible/src/benchmarking.rs
@@ -421,114 +421,30 @@
 		Ok(())
 	}
 
-	// set_token_properties {
-	// 	let b in 0..MAX_PROPERTIES_PER_ITEM;
-	// 	bench_init!{
-	// 		owner: sub; collection: collection(owner);
-	// 		owner: cross_from_sub;
-	// 	};
-	// 	let perms = (0..b).map(|k| PropertyKeyPermission {
-	// 		key: property_key(k as usize),
-	// 		permission: PropertyPermission {
-	// 			mutable: false,
-	// 			collection_admin: true,
-	// 			token_owner: true,
-	// 		},
-	// 	}).collect::<Vec<_>>();
-	// 	<Pallet<T>>::set_token_property_permissions(&collection, &owner, perms)?;
-	// 	let props = (0..b).map(|k| Property {
-	// 		key: property_key(k as usize),
-	// 		value: property_value(),
-	// 	}).collect::<Vec<_>>();
-	// 	let item = create_max_item(&collection, &owner, [(owner.clone(), 200)])?;
-	// }: {<Pallet<T>>::set_token_properties(&collection, &owner, item, props.into_iter(), &Unlimited)?}
-
-	// load_token_properties {
-	// 	bench_init!{
-	// 		owner: sub; collection: collection(owner);
-	// 		owner: cross_from_sub;
-	// 	};
-
-	// 	let item = create_max_item(&collection, &owner, [(owner.clone(), 200)])?;
-	// }: {
-	// 	pallet_common::BenchmarkPropertyWriter::<T>::load_token_properties(
-	// 		&collection,
-	// 		item,
-	// 	)
-	// }
-
-	// write_token_properties {
-	// 	let b in 0..MAX_PROPERTIES_PER_ITEM;
-	// 	bench_init!{
-	// 		owner: sub; collection: collection(owner);
-	// 		owner: cross_from_sub;
-	// 	};
-
-	// 	let perms = (0..b).map(|k| PropertyKeyPermission {
-	// 		key: property_key(k as usize),
-	// 		permission: PropertyPermission {
-	// 			mutable: false,
-	// 			collection_admin: true,
-	// 			token_owner: true,
-	// 		},
-	// 	}).collect::<Vec<_>>();
-	// 	<Pallet<T>>::set_token_property_permissions(&collection, &owner, perms)?;
-	// 	let props = (0..b).map(|k| Property {
-	// 		key: property_key(k as usize),
-	// 		value: property_value(),
-	// 	}).collect::<Vec<_>>();
-	// 	let item = create_max_item(&collection, &owner, [(owner.clone(), 200)])?;
-
-	// 	let lazy_collection_info = pallet_common::BenchmarkPropertyWriter::<T>::load_collection_info(
-	// 		&collection,
-	// 		&owner,
-	// 	);
-	// }: {
-	// 	let mut property_writer = pallet_common::BenchmarkPropertyWriter::new(&collection, lazy_collection_info);
-
-	// 	property_writer.write_token_properties(
-	// 		item,
-	// 		props.into_iter(),
-	// 		crate::erc::ERC721TokenEvent::TokenChanged {
-	// 			token_id: item.into(),
-	// 		}
-	// 		.to_log(T::ContractAddress::get()),
-	// 	)?
-	// }
-
 	#[benchmark]
-	fn set_token_property_permissions(
-		b: Linear<0, MAX_PROPERTIES_PER_ITEM>,
-	) -> Result<(), BenchmarkError> {
+	fn load_token_properties() -> Result<(), BenchmarkError> {
 		bench_init! {
 			owner: sub; collection: collection(owner);
 			owner: cross_from_sub;
 		};
-		let perms = (0..b)
-			.map(|k| PropertyKeyPermission {
-				key: property_key(k as usize),
-				permission: PropertyPermission {
-					mutable: false,
-					collection_admin: false,
-					token_owner: false,
-				},
-			})
-			.collect::<Vec<_>>();
 
+		let item = create_max_item(&collection, &owner, [(owner.clone(), 200)])?;
+
 		#[block]
 		{
-			<Pallet<T>>::set_token_property_permissions(&collection, &owner, perms)?;
+			pallet_common::BenchmarkPropertyWriter::<T>::load_token_properties(&collection, item);
 		}
 
 		Ok(())
 	}
 
 	#[benchmark]
-	fn set_token_properties(b: Linear<0, MAX_PROPERTIES_PER_ITEM>) -> Result<(), BenchmarkError> {
+	fn write_token_properties(b: Linear<0, MAX_PROPERTIES_PER_ITEM>) -> Result<(), BenchmarkError> {
 		bench_init! {
 			owner: sub; collection: collection(owner);
 			owner: cross_from_sub;
 		};
+
 		let perms = (0..b)
 			.map(|k| PropertyKeyPermission {
 				key: property_key(k as usize),
@@ -548,73 +464,29 @@
 			.collect::<Vec<_>>();
 		let item = create_max_item(&collection, &owner, [(owner.clone(), 200)])?;
 
+		let lazy_collection_info =
+			pallet_common::BenchmarkPropertyWriter::<T>::load_collection_info(&collection, &owner);
+
 		#[block]
 		{
-			<Pallet<T>>::set_token_properties(
-				&collection,
-				&owner,
+			let mut property_writer =
+				pallet_common::BenchmarkPropertyWriter::new(&collection, lazy_collection_info);
+
+			property_writer.write_token_properties(
 				item,
 				props.into_iter(),
-				&Unlimited,
+				crate::erc::ERC721TokenEvent::TokenChanged {
+					token_id: item.into(),
+				}
+				.to_log(T::ContractAddress::get()),
 			)?;
 		}
 
 		Ok(())
 	}
 
-	// TODO:
 	#[benchmark]
-	fn init_token_properties(b: Linear<0, MAX_PROPERTIES_PER_ITEM>) -> Result<(), BenchmarkError> {
-		// bench_init! {
-		// 	owner: sub; collection: collection(owner);
-		// 	owner: cross_from_sub;
-		// };
-
-		// let perms = (0..b)
-		// 	.map(|k| PropertyKeyPermission {
-		// 		key: property_key(k as usize),
-		// 		permission: PropertyPermission {
-		// 			mutable: false,
-		// 			collection_admin: true,
-		// 			token_owner: true,
-		// 		},
-		// 	})
-		// 	.collect::<Vec<_>>();
-		// <Pallet<T>>::set_token_property_permissions(&collection, &owner, perms)?;
-
-		#[block]
-		{}
-		// let props = (0..b).map(|k| Property {
-		// 	key: property_key(k as usize),
-		// 	value: property_value(),
-		// }).collect::<Vec<_>>();
-		// let item = create_max_item(&collection, &owner, [(owner.clone(), 200)])?;
-
-		// let (is_collection_admin, property_permissions) = load_is_admin_and_property_permissions(&collection, &owner)
-		// let mut property_writer = pallet_common::collection_info_loaded_property_writer(
-		// 	&collection,
-		// 	is_collection_admin,
-		// 	property_permissions,
-		// );
-
-		// #[block]
-		// {
-		// 	property_writer.write_token_properties(
-		// 		true,
-		// 		item,
-		// 		props.into_iter(),
-		// 		crate::erc::ERC721TokenEvent::TokenChanged {
-		// 			token_id: item.into(),
-		// 		}
-		// 		.to_log(T::ContractAddress::get()),
-		// 	)?;
-		// }
-
-		Ok(())
-	}
-
-	#[benchmark]
-	fn delete_token_properties(
+	fn set_token_property_permissions(
 		b: Linear<0, MAX_PROPERTIES_PER_ITEM>,
 	) -> Result<(), BenchmarkError> {
 		bench_init! {
@@ -625,38 +497,16 @@
 			.map(|k| PropertyKeyPermission {
 				key: property_key(k as usize),
 				permission: PropertyPermission {
-					mutable: true,
-					collection_admin: true,
-					token_owner: true,
+					mutable: false,
+					collection_admin: false,
+					token_owner: false,
 				},
-			})
-			.collect::<Vec<_>>();
-		<Pallet<T>>::set_token_property_permissions(&collection, &owner, perms)?;
-		let props = (0..b)
-			.map(|k| Property {
-				key: property_key(k as usize),
-				value: property_value(),
 			})
 			.collect::<Vec<_>>();
-		let item = create_max_item(&collection, &owner, [(owner.clone(), 200)])?;
-		<Pallet<T>>::set_token_properties(
-			&collection,
-			&owner,
-			item,
-			props.into_iter(),
-			&Unlimited,
-		)?;
-		let to_delete = (0..b).map(|k| property_key(k as usize)).collect::<Vec<_>>();
 
 		#[block]
 		{
-			<Pallet<T>>::delete_token_properties(
-				&collection,
-				&owner,
-				item,
-				to_delete.into_iter(),
-				&Unlimited,
-			)?;
+			<Pallet<T>>::set_token_property_permissions(&collection, &owner, perms)?;
 		}
 
 		Ok(())
@@ -673,22 +523,6 @@
 		#[block]
 		{
 			<Pallet<T>>::repartition(&collection, &owner, item, 200)?;
-		}
-
-		Ok(())
-	}
-
-	#[benchmark]
-	fn token_owner() -> Result<(), BenchmarkError> {
-		bench_init! {
-			owner: sub; collection: collection(owner);
-			sender: cross_from_sub(owner); owner: cross_sub;
-		};
-		let item = create_max_item(&collection, &sender, [(owner, 100)])?;
-
-		#[block]
-		{
-			<Pallet<T>>::token_owner(collection.id, item).unwrap();
 		}
 
 		Ok(())
modifiedpallets/refungible/src/common.rsdiffbeforeafterboth
before · pallets/refungible/src/common.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/>.1617use core::marker::PhantomData;1819use frame_support::{dispatch::DispatchResultWithPostInfo, fail, weights::Weight};20use pallet_common::{21	weights::WeightInfo as _, with_weight, write_token_properties_total_weight,22	CommonCollectionOperations, CommonWeightInfo, RefungibleExtensions,23};24use pallet_structure::Pallet as PalletStructure;25use sp_runtime::DispatchError;26use sp_std::{collections::btree_map::BTreeMap, vec, vec::Vec};27use up_data_structs::{28	budget::Budget, CollectionId, CreateItemExData, CreateRefungibleExMultipleOwners,29	CreateRefungibleExSingleOwner, Property, PropertyKey, PropertyKeyPermission, PropertyValue,30	TokenId, TokenOwnerError,31};3233use crate::{34	weights::WeightInfo, AccountBalance, Allowance, Balance, Config, CreateItemData, Error, Owned,35	Pallet, RefungibleHandle, SelfWeightOf, TokenProperties, TokensMinted, TotalSupply,36};3738macro_rules! max_weight_of {39	($($method:ident ($($args:tt)*)),*) => {40		Weight::zero()41		$(42			.max(<SelfWeightOf<T>>::$method($($args)*))43		)*44	};45}4647pub struct CommonWeights<T: Config>(PhantomData<T>);48impl<T: Config> CommonWeightInfo<T::CrossAccountId> for CommonWeights<T> {49	fn create_multiple_items(data: &[up_data_structs::CreateItemData]) -> Weight {50		<SelfWeightOf<T>>::create_multiple_items(data.len() as u32).saturating_add(51			write_token_properties_total_weight::<T, _>(52				data.iter().map(|data| match data {53					up_data_structs::CreateItemData::ReFungible(rft_data) => {54						rft_data.properties.len() as u3255					}56					_ => 0,57				}),58				<SelfWeightOf<T>>::write_token_properties,59			),60		)61	}6263	fn create_multiple_items_ex(call: &CreateItemExData<T::CrossAccountId>) -> Weight {64		match call {65			CreateItemExData::RefungibleMultipleOwners(i) => {66				<SelfWeightOf<T>>::create_multiple_items_ex_multiple_owners(i.users.len() as u32)67					.saturating_add(write_token_properties_total_weight::<T, _>(68						[i.properties.len() as u32].into_iter(),69						<SelfWeightOf<T>>::write_token_properties,70					))71			}72			CreateItemExData::RefungibleMultipleItems(i) => {73				<SelfWeightOf<T>>::create_multiple_items_ex_multiple_items(i.len() as u32)74					.saturating_add(write_token_properties_total_weight::<T, _>(75						i.iter().map(|d| d.properties.len() as u32),76						<SelfWeightOf<T>>::write_token_properties,77					))78			}79			_ => Weight::zero(),80		}81	}8283	fn burn_item() -> Weight {84		max_weight_of!(burn_item_partial(), burn_item_fully())85	}8687	fn set_collection_properties(amount: u32) -> Weight {88		<pallet_common::SelfWeightOf<T>>::set_collection_properties(amount)89	}9091	fn set_token_properties(amount: u32) -> Weight {92		write_token_properties_total_weight::<T, _>([amount].into_iter(), |amount| {93			<SelfWeightOf<T>>::load_token_properties()94				+ <SelfWeightOf<T>>::write_token_properties(amount)95		})96	}9798	fn set_token_property_permissions(amount: u32) -> Weight {99		<SelfWeightOf<T>>::set_token_property_permissions(amount)100	}101102	fn transfer() -> Weight {103		max_weight_of!(104			transfer_normal(),105			transfer_creating(),106			transfer_removing(),107			transfer_creating_removing()108		)109	}110111	fn approve() -> Weight {112		<SelfWeightOf<T>>::approve()113	}114115	fn approve_from() -> Weight {116		<SelfWeightOf<T>>::approve_from()117	}118119	fn transfer_from() -> Weight {120		max_weight_of!(121			transfer_from_normal(),122			transfer_from_creating(),123			transfer_from_removing(),124			transfer_from_creating_removing()125		)126	}127128	fn burn_from() -> Weight {129		<SelfWeightOf<T>>::burn_from()130	}131132	fn set_allowance_for_all() -> Weight {133		<SelfWeightOf<T>>::set_allowance_for_all()134	}135136	fn force_repair_item() -> Weight {137		<SelfWeightOf<T>>::repair_item()138	}139}140141fn map_create_data<T: Config>(142	data: up_data_structs::CreateItemData,143	to: &T::CrossAccountId,144) -> Result<CreateItemData<T>, DispatchError> {145	match data {146		up_data_structs::CreateItemData::ReFungible(data) => Ok(CreateItemData::<T> {147			users: {148				let mut out = BTreeMap::new();149				out.insert(to.clone(), data.pieces);150				out.try_into().expect("limit > 0")151			},152			properties: data.properties,153		}),154		_ => fail!(<Error<T>>::NotRefungibleDataUsedToMintFungibleCollectionToken),155	}156}157158/// Implementation of `CommonCollectionOperations` for `RefungibleHandle`. It wraps Refungible Pallete159/// methods and adds weight info.160impl<T: Config> CommonCollectionOperations<T> for RefungibleHandle<T> {161	fn create_item(162		&self,163		sender: T::CrossAccountId,164		to: T::CrossAccountId,165		data: up_data_structs::CreateItemData,166		nesting_budget: &dyn Budget,167	) -> DispatchResultWithPostInfo {168		let weight = <CommonWeights<T>>::create_item(&data);169		with_weight(170			<Pallet<T>>::create_item(171				self,172				&sender,173				map_create_data::<T>(data, &to)?,174				nesting_budget,175			),176			weight,177		)178	}179180	fn create_multiple_items(181		&self,182		sender: T::CrossAccountId,183		to: T::CrossAccountId,184		data: Vec<up_data_structs::CreateItemData>,185		nesting_budget: &dyn Budget,186	) -> DispatchResultWithPostInfo {187		let weight = <CommonWeights<T>>::create_multiple_items(&data);188		let data = data189			.into_iter()190			.map(|d| map_create_data::<T>(d, &to))191			.collect::<Result<Vec<_>, DispatchError>>()?;192193		with_weight(194			<Pallet<T>>::create_multiple_items(self, &sender, data, nesting_budget),195			weight,196		)197	}198199	fn create_multiple_items_ex(200		&self,201		sender: <T>::CrossAccountId,202		data: CreateItemExData<T::CrossAccountId>,203		nesting_budget: &dyn Budget,204	) -> DispatchResultWithPostInfo {205		let weight = <CommonWeights<T>>::create_multiple_items_ex(&data);206		let data = match data {207			CreateItemExData::RefungibleMultipleOwners(CreateRefungibleExMultipleOwners {208				users,209				properties,210			}) => vec![CreateItemData::<T> { users, properties }],211			CreateItemExData::RefungibleMultipleItems(r) => r212				.into_inner()213				.into_iter()214				.map(215					|CreateRefungibleExSingleOwner {216					     user,217					     pieces,218					     properties,219					 }| CreateItemData::<T> {220						users: BTreeMap::from([(user, pieces)])221							.try_into()222							.expect("limit >= 1"),223						properties,224					},225				)226				.collect(),227			_ => fail!(<Error<T>>::NotRefungibleDataUsedToMintFungibleCollectionToken),228		};229230		with_weight(231			<Pallet<T>>::create_multiple_items(self, &sender, data, nesting_budget),232			weight,233		)234	}235236	fn burn_item(237		&self,238		sender: T::CrossAccountId,239		token: TokenId,240		amount: u128,241	) -> DispatchResultWithPostInfo {242		with_weight(243			<Pallet<T>>::burn(self, &sender, token, amount),244			<CommonWeights<T>>::burn_item(),245		)246	}247248	fn transfer(249		&self,250		from: T::CrossAccountId,251		to: T::CrossAccountId,252		token: TokenId,253		amount: u128,254		nesting_budget: &dyn Budget,255	) -> DispatchResultWithPostInfo {256		with_weight(257			<Pallet<T>>::transfer(self, &from, &to, token, amount, nesting_budget),258			<CommonWeights<T>>::transfer(),259		)260	}261262	fn approve(263		&self,264		sender: T::CrossAccountId,265		spender: T::CrossAccountId,266		token: TokenId,267		amount: u128,268	) -> DispatchResultWithPostInfo {269		with_weight(270			<Pallet<T>>::set_allowance(self, &sender, &spender, token, amount),271			<CommonWeights<T>>::approve(),272		)273	}274275	fn approve_from(276		&self,277		sender: T::CrossAccountId,278		from: T::CrossAccountId,279		to: T::CrossAccountId,280		token_id: TokenId,281		amount: u128,282	) -> DispatchResultWithPostInfo {283		with_weight(284			<Pallet<T>>::set_allowance_from(self, &sender, &from, &to, token_id, amount),285			<CommonWeights<T>>::approve_from(),286		)287	}288289	fn transfer_from(290		&self,291		sender: T::CrossAccountId,292		from: T::CrossAccountId,293		to: T::CrossAccountId,294		token: TokenId,295		amount: u128,296		nesting_budget: &dyn Budget,297	) -> DispatchResultWithPostInfo {298		with_weight(299			<Pallet<T>>::transfer_from(self, &sender, &from, &to, token, amount, nesting_budget),300			<CommonWeights<T>>::transfer_from(),301		)302	}303304	fn burn_from(305		&self,306		sender: T::CrossAccountId,307		from: T::CrossAccountId,308		token: TokenId,309		amount: u128,310		nesting_budget: &dyn Budget,311	) -> DispatchResultWithPostInfo {312		with_weight(313			<Pallet<T>>::burn_from(self, &sender, &from, token, amount, nesting_budget),314			<CommonWeights<T>>::burn_from(),315		)316	}317318	fn set_collection_properties(319		&self,320		sender: T::CrossAccountId,321		properties: Vec<Property>,322	) -> DispatchResultWithPostInfo {323		let weight = <CommonWeights<T>>::set_collection_properties(properties.len() as u32);324325		with_weight(326			<Pallet<T>>::set_collection_properties(self, &sender, properties),327			weight,328		)329	}330331	fn delete_collection_properties(332		&self,333		sender: &T::CrossAccountId,334		property_keys: Vec<PropertyKey>,335	) -> DispatchResultWithPostInfo {336		let weight = <CommonWeights<T>>::delete_collection_properties(property_keys.len() as u32);337338		with_weight(339			<Pallet<T>>::delete_collection_properties(self, sender, property_keys),340			weight,341		)342	}343344	fn set_token_properties(345		&self,346		sender: T::CrossAccountId,347		token_id: TokenId,348		properties: Vec<Property>,349		nesting_budget: &dyn Budget,350	) -> DispatchResultWithPostInfo {351		let weight = <CommonWeights<T>>::set_token_properties(properties.len() as u32);352353		with_weight(354			<Pallet<T>>::set_token_properties(355				self,356				&sender,357				token_id,358				properties.into_iter(),359				nesting_budget,360			),361			weight,362		)363	}364365	fn set_token_property_permissions(366		&self,367		sender: &T::CrossAccountId,368		property_permissions: Vec<PropertyKeyPermission>,369	) -> DispatchResultWithPostInfo {370		let weight =371			<CommonWeights<T>>::set_token_property_permissions(property_permissions.len() as u32);372373		with_weight(374			<Pallet<T>>::set_token_property_permissions(self, sender, property_permissions),375			weight,376		)377	}378379	fn delete_token_properties(380		&self,381		sender: T::CrossAccountId,382		token_id: TokenId,383		property_keys: Vec<PropertyKey>,384		nesting_budget: &dyn Budget,385	) -> DispatchResultWithPostInfo {386		let weight = <CommonWeights<T>>::delete_token_properties(property_keys.len() as u32);387388		with_weight(389			<Pallet<T>>::delete_token_properties(390				self,391				&sender,392				token_id,393				property_keys.into_iter(),394				nesting_budget,395			),396			weight,397		)398	}399400	fn get_token_properties_raw(401		&self,402		token_id: TokenId,403	) -> Option<up_data_structs::TokenProperties> {404		<TokenProperties<T>>::get((self.id, token_id))405	}406407	fn set_token_properties_raw(&self, token_id: TokenId, map: up_data_structs::TokenProperties) {408		<TokenProperties<T>>::insert((self.id, token_id), map)409	}410411	fn check_nesting(412		&self,413		_sender: <T>::CrossAccountId,414		_from: (CollectionId, TokenId),415		_under: TokenId,416		_nesting_budget: &dyn Budget,417	) -> sp_runtime::DispatchResult {418		fail!(<Error<T>>::RefungibleDisallowsNesting)419	}420421	fn nest(&self, _under: TokenId, _to_nest: (CollectionId, TokenId)) {}422423	fn unnest(&self, _under: TokenId, _to_nest: (CollectionId, TokenId)) {}424425	fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId> {426		<Owned<T>>::iter_prefix((self.id, account))427			.map(|(id, _)| id)428			.collect()429	}430431	fn collection_tokens(&self) -> Vec<TokenId> {432		<TotalSupply<T>>::iter_prefix((self.id,))433			.map(|(id, _)| id)434			.collect()435	}436437	fn token_exists(&self, token: TokenId) -> bool {438		<Pallet<T>>::token_exists(self, token)439	}440441	fn last_token_id(&self) -> TokenId {442		TokenId(<TokensMinted<T>>::get(self.id))443	}444445	fn token_owner(&self, token: TokenId) -> Result<T::CrossAccountId, TokenOwnerError> {446		<Pallet<T>>::token_owner(self.id, token)447	}448449	fn check_token_indirect_owner(450		&self,451		token: TokenId,452		maybe_owner: &T::CrossAccountId,453		nesting_budget: &dyn Budget,454	) -> Result<bool, DispatchError> {455		let balance = self.balance(maybe_owner.clone(), token);456		let total_pieces: u128 = <Pallet<T>>::total_pieces(self.id, token).unwrap_or(u128::MAX);457		if balance != total_pieces {458			return Ok(false);459		}460461		<PalletStructure<T>>::check_indirectly_owned(462			maybe_owner.clone(),463			self.id,464			token,465			None,466			nesting_budget,467		)468	}469470	/// Returns 10 token in no particular order.471	fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId> {472		<Pallet<T>>::token_owners(self.id, token).unwrap_or_default()473	}474475	fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue> {476		<Pallet<T>>::token_properties((self.id, token_id))?477			.get(key)478			.cloned()479	}480481	fn token_properties(&self, token_id: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property> {482		let Some(properties) = <Pallet<T>>::token_properties((self.id, token_id)) else {483			return vec![];484		};485486		keys.map(|keys| {487			keys.into_iter()488				.filter_map(|key| {489					properties.get(&key).map(|value| Property {490						key,491						value: value.clone(),492					})493				})494				.collect()495		})496		.unwrap_or_else(|| {497			properties498				.into_iter()499				.map(|(key, value)| Property { key, value })500				.collect()501		})502	}503504	fn total_supply(&self) -> u32 {505		<Pallet<T>>::total_supply(self)506	}507508	fn account_balance(&self, account: T::CrossAccountId) -> u32 {509		<AccountBalance<T>>::get((self.id, account))510	}511512	fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128 {513		<Balance<T>>::get((self.id, token, account))514	}515516	fn allowance(517		&self,518		sender: T::CrossAccountId,519		spender: T::CrossAccountId,520		token: TokenId,521	) -> u128 {522		<Allowance<T>>::get((self.id, token, sender, spender))523	}524525	fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>> {526		Some(self)527	}528529	fn total_pieces(&self, token: TokenId) -> Option<u128> {530		<Pallet<T>>::total_pieces(self.id, token)531	}532533	fn set_allowance_for_all(534		&self,535		owner: T::CrossAccountId,536		operator: T::CrossAccountId,537		approve: bool,538	) -> DispatchResultWithPostInfo {539		with_weight(540			<Pallet<T>>::set_allowance_for_all(self, &owner, &operator, approve),541			<CommonWeights<T>>::set_allowance_for_all(),542		)543	}544545	fn allowance_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool {546		<Pallet<T>>::allowance_for_all(self, &owner, &operator)547	}548549	fn repair_item(&self, token: TokenId) -> DispatchResultWithPostInfo {550		with_weight(551			<Pallet<T>>::repair_item(self, token),552			<CommonWeights<T>>::force_repair_item(),553		)554	}555}556557impl<T: Config> RefungibleExtensions<T> for RefungibleHandle<T> {558	fn repartition(559		&self,560		owner: &T::CrossAccountId,561		token: TokenId,562		amount: u128,563	) -> DispatchResultWithPostInfo {564		with_weight(565			<Pallet<T>>::repartition(self, owner, token, amount),566			<SelfWeightOf<T>>::repartition_item(),567		)568	}569}
after · pallets/refungible/src/common.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/>.1617use core::marker::PhantomData;1819use frame_support::{dispatch::DispatchResultWithPostInfo, fail, weights::Weight};20use pallet_common::{21	weights::WeightInfo as _, with_weight, write_token_properties_total_weight,22	CommonCollectionOperations, CommonWeightInfo, RefungibleExtensions,23};24use pallet_structure::Pallet as PalletStructure;25use sp_runtime::DispatchError;26use sp_std::{collections::btree_map::BTreeMap, vec, vec::Vec};27use up_data_structs::{28	budget::Budget, CollectionId, CreateItemExData, CreateRefungibleExMultipleOwners,29	CreateRefungibleExSingleOwner, Property, PropertyKey, PropertyKeyPermission, PropertyValue,30	TokenId, TokenOwnerError,31};3233use crate::{34	weights::WeightInfo, AccountBalance, Allowance, Balance, Config, CreateItemData, Error, Owned,35	Pallet, RefungibleHandle, SelfWeightOf, TokenProperties, TokensMinted, TotalSupply,36};3738macro_rules! max_weight_of {39	($($method:ident ($($args:tt)*)),*) => {40		Weight::zero()41		$(42			.max(<SelfWeightOf<T>>::$method($($args)*))43		)*44	};45}4647pub struct CommonWeights<T: Config>(PhantomData<T>);48impl<T: Config> CommonWeightInfo<T::CrossAccountId> for CommonWeights<T> {49	fn create_multiple_items(data: &[up_data_structs::CreateItemData]) -> Weight {50		mint_with_props_weight::<T>(51			<SelfWeightOf<T>>::create_multiple_items(data.len() as u32),52			data.iter().map(|data| match data {53				up_data_structs::CreateItemData::ReFungible(rft_data) => {54					rft_data.properties.len() as u3255				}56				_ => 0,57			}),58		)59	}6061	fn create_multiple_items_ex(call: &CreateItemExData<T::CrossAccountId>) -> Weight {62		match call {63			CreateItemExData::RefungibleMultipleOwners(i) => mint_with_props_weight::<T>(64				<SelfWeightOf<T>>::create_multiple_items_ex_multiple_owners(i.users.len() as u32),65				[i.properties.len() as u32].into_iter(),66			),67			CreateItemExData::RefungibleMultipleItems(i) => mint_with_props_weight::<T>(68				<SelfWeightOf<T>>::create_multiple_items_ex_multiple_items(i.len() as u32),69				i.iter().map(|d| d.properties.len() as u32),70			),71			_ => Weight::zero(),72		}73	}7475	fn burn_item() -> Weight {76		max_weight_of!(burn_item_partial(), burn_item_fully())77	}7879	fn set_collection_properties(amount: u32) -> Weight {80		<pallet_common::SelfWeightOf<T>>::set_collection_properties(amount)81	}8283	fn set_token_properties(amount: u32) -> Weight {84		write_token_properties_total_weight::<T, _>([amount].into_iter(), |amount| {85			<SelfWeightOf<T>>::load_token_properties()86				+ <SelfWeightOf<T>>::write_token_properties(amount)87		})88	}8990	fn set_token_property_permissions(amount: u32) -> Weight {91		<SelfWeightOf<T>>::set_token_property_permissions(amount)92	}9394	fn transfer() -> Weight {95		max_weight_of!(96			transfer_normal(),97			transfer_creating(),98			transfer_removing(),99			transfer_creating_removing()100		)101	}102103	fn approve() -> Weight {104		<SelfWeightOf<T>>::approve()105	}106107	fn approve_from() -> Weight {108		<SelfWeightOf<T>>::approve_from()109	}110111	fn transfer_from() -> Weight {112		max_weight_of!(113			transfer_from_normal(),114			transfer_from_creating(),115			transfer_from_removing(),116			transfer_from_creating_removing()117		)118	}119120	fn burn_from() -> Weight {121		<SelfWeightOf<T>>::burn_from()122	}123124	fn set_allowance_for_all() -> Weight {125		<SelfWeightOf<T>>::set_allowance_for_all()126	}127128	fn force_repair_item() -> Weight {129		<SelfWeightOf<T>>::repair_item()130	}131}132133pub(crate) fn mint_with_props_weight<T: Config>(134	create_no_data_weight: Weight,135	tokens: impl Iterator<Item = u32> + Clone,136) -> Weight {137	create_no_data_weight.saturating_add(write_token_properties_total_weight::<T, _>(138		tokens,139		<SelfWeightOf<T>>::write_token_properties,140	))141}142143fn map_create_data<T: Config>(144	data: up_data_structs::CreateItemData,145	to: &T::CrossAccountId,146) -> Result<CreateItemData<T>, DispatchError> {147	match data {148		up_data_structs::CreateItemData::ReFungible(data) => Ok(CreateItemData::<T> {149			users: {150				let mut out = BTreeMap::new();151				out.insert(to.clone(), data.pieces);152				out.try_into().expect("limit > 0")153			},154			properties: data.properties,155		}),156		_ => fail!(<Error<T>>::NotRefungibleDataUsedToMintFungibleCollectionToken),157	}158}159160/// Implementation of `CommonCollectionOperations` for `RefungibleHandle`. It wraps Refungible Pallete161/// methods and adds weight info.162impl<T: Config> CommonCollectionOperations<T> for RefungibleHandle<T> {163	fn create_item(164		&self,165		sender: T::CrossAccountId,166		to: T::CrossAccountId,167		data: up_data_structs::CreateItemData,168		nesting_budget: &dyn Budget,169	) -> DispatchResultWithPostInfo {170		let weight = <CommonWeights<T>>::create_item(&data);171		with_weight(172			<Pallet<T>>::create_item(173				self,174				&sender,175				map_create_data::<T>(data, &to)?,176				nesting_budget,177			),178			weight,179		)180	}181182	fn create_multiple_items(183		&self,184		sender: T::CrossAccountId,185		to: T::CrossAccountId,186		data: Vec<up_data_structs::CreateItemData>,187		nesting_budget: &dyn Budget,188	) -> DispatchResultWithPostInfo {189		let weight = <CommonWeights<T>>::create_multiple_items(&data);190		let data = data191			.into_iter()192			.map(|d| map_create_data::<T>(d, &to))193			.collect::<Result<Vec<_>, DispatchError>>()?;194195		with_weight(196			<Pallet<T>>::create_multiple_items(self, &sender, data, nesting_budget),197			weight,198		)199	}200201	fn create_multiple_items_ex(202		&self,203		sender: <T>::CrossAccountId,204		data: CreateItemExData<T::CrossAccountId>,205		nesting_budget: &dyn Budget,206	) -> DispatchResultWithPostInfo {207		let weight = <CommonWeights<T>>::create_multiple_items_ex(&data);208		let data = match data {209			CreateItemExData::RefungibleMultipleOwners(CreateRefungibleExMultipleOwners {210				users,211				properties,212			}) => vec![CreateItemData::<T> { users, properties }],213			CreateItemExData::RefungibleMultipleItems(r) => r214				.into_inner()215				.into_iter()216				.map(217					|CreateRefungibleExSingleOwner {218					     user,219					     pieces,220					     properties,221					 }| CreateItemData::<T> {222						users: BTreeMap::from([(user, pieces)])223							.try_into()224							.expect("limit >= 1"),225						properties,226					},227				)228				.collect(),229			_ => fail!(<Error<T>>::NotRefungibleDataUsedToMintFungibleCollectionToken),230		};231232		with_weight(233			<Pallet<T>>::create_multiple_items(self, &sender, data, nesting_budget),234			weight,235		)236	}237238	fn burn_item(239		&self,240		sender: T::CrossAccountId,241		token: TokenId,242		amount: u128,243	) -> DispatchResultWithPostInfo {244		with_weight(245			<Pallet<T>>::burn(self, &sender, token, amount),246			<CommonWeights<T>>::burn_item(),247		)248	}249250	fn transfer(251		&self,252		from: T::CrossAccountId,253		to: T::CrossAccountId,254		token: TokenId,255		amount: u128,256		nesting_budget: &dyn Budget,257	) -> DispatchResultWithPostInfo {258		with_weight(259			<Pallet<T>>::transfer(self, &from, &to, token, amount, nesting_budget),260			<CommonWeights<T>>::transfer(),261		)262	}263264	fn approve(265		&self,266		sender: T::CrossAccountId,267		spender: T::CrossAccountId,268		token: TokenId,269		amount: u128,270	) -> DispatchResultWithPostInfo {271		with_weight(272			<Pallet<T>>::set_allowance(self, &sender, &spender, token, amount),273			<CommonWeights<T>>::approve(),274		)275	}276277	fn approve_from(278		&self,279		sender: T::CrossAccountId,280		from: T::CrossAccountId,281		to: T::CrossAccountId,282		token_id: TokenId,283		amount: u128,284	) -> DispatchResultWithPostInfo {285		with_weight(286			<Pallet<T>>::set_allowance_from(self, &sender, &from, &to, token_id, amount),287			<CommonWeights<T>>::approve_from(),288		)289	}290291	fn transfer_from(292		&self,293		sender: T::CrossAccountId,294		from: T::CrossAccountId,295		to: T::CrossAccountId,296		token: TokenId,297		amount: u128,298		nesting_budget: &dyn Budget,299	) -> DispatchResultWithPostInfo {300		with_weight(301			<Pallet<T>>::transfer_from(self, &sender, &from, &to, token, amount, nesting_budget),302			<CommonWeights<T>>::transfer_from(),303		)304	}305306	fn burn_from(307		&self,308		sender: T::CrossAccountId,309		from: T::CrossAccountId,310		token: TokenId,311		amount: u128,312		nesting_budget: &dyn Budget,313	) -> DispatchResultWithPostInfo {314		with_weight(315			<Pallet<T>>::burn_from(self, &sender, &from, token, amount, nesting_budget),316			<CommonWeights<T>>::burn_from(),317		)318	}319320	fn set_collection_properties(321		&self,322		sender: T::CrossAccountId,323		properties: Vec<Property>,324	) -> DispatchResultWithPostInfo {325		let weight = <CommonWeights<T>>::set_collection_properties(properties.len() as u32);326327		with_weight(328			<Pallet<T>>::set_collection_properties(self, &sender, properties),329			weight,330		)331	}332333	fn delete_collection_properties(334		&self,335		sender: &T::CrossAccountId,336		property_keys: Vec<PropertyKey>,337	) -> DispatchResultWithPostInfo {338		let weight = <CommonWeights<T>>::delete_collection_properties(property_keys.len() as u32);339340		with_weight(341			<Pallet<T>>::delete_collection_properties(self, sender, property_keys),342			weight,343		)344	}345346	fn set_token_properties(347		&self,348		sender: T::CrossAccountId,349		token_id: TokenId,350		properties: Vec<Property>,351		nesting_budget: &dyn Budget,352	) -> DispatchResultWithPostInfo {353		let weight = <CommonWeights<T>>::set_token_properties(properties.len() as u32);354355		with_weight(356			<Pallet<T>>::set_token_properties(357				self,358				&sender,359				token_id,360				properties.into_iter(),361				nesting_budget,362			),363			weight,364		)365	}366367	fn set_token_property_permissions(368		&self,369		sender: &T::CrossAccountId,370		property_permissions: Vec<PropertyKeyPermission>,371	) -> DispatchResultWithPostInfo {372		let weight =373			<CommonWeights<T>>::set_token_property_permissions(property_permissions.len() as u32);374375		with_weight(376			<Pallet<T>>::set_token_property_permissions(self, sender, property_permissions),377			weight,378		)379	}380381	fn delete_token_properties(382		&self,383		sender: T::CrossAccountId,384		token_id: TokenId,385		property_keys: Vec<PropertyKey>,386		nesting_budget: &dyn Budget,387	) -> DispatchResultWithPostInfo {388		let weight = <CommonWeights<T>>::delete_token_properties(property_keys.len() as u32);389390		with_weight(391			<Pallet<T>>::delete_token_properties(392				self,393				&sender,394				token_id,395				property_keys.into_iter(),396				nesting_budget,397			),398			weight,399		)400	}401402	fn get_token_properties_raw(403		&self,404		token_id: TokenId,405	) -> Option<up_data_structs::TokenProperties> {406		<TokenProperties<T>>::get((self.id, token_id))407	}408409	fn set_token_properties_raw(&self, token_id: TokenId, map: up_data_structs::TokenProperties) {410		<TokenProperties<T>>::insert((self.id, token_id), map)411	}412413	fn check_nesting(414		&self,415		_sender: <T>::CrossAccountId,416		_from: (CollectionId, TokenId),417		_under: TokenId,418		_nesting_budget: &dyn Budget,419	) -> sp_runtime::DispatchResult {420		fail!(<Error<T>>::RefungibleDisallowsNesting)421	}422423	fn nest(&self, _under: TokenId, _to_nest: (CollectionId, TokenId)) {}424425	fn unnest(&self, _under: TokenId, _to_nest: (CollectionId, TokenId)) {}426427	fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId> {428		<Owned<T>>::iter_prefix((self.id, account))429			.map(|(id, _)| id)430			.collect()431	}432433	fn collection_tokens(&self) -> Vec<TokenId> {434		<TotalSupply<T>>::iter_prefix((self.id,))435			.map(|(id, _)| id)436			.collect()437	}438439	fn token_exists(&self, token: TokenId) -> bool {440		<Pallet<T>>::token_exists(self, token)441	}442443	fn last_token_id(&self) -> TokenId {444		TokenId(<TokensMinted<T>>::get(self.id))445	}446447	fn token_owner(&self, token: TokenId) -> Result<T::CrossAccountId, TokenOwnerError> {448		<Pallet<T>>::token_owner(self.id, token)449	}450451	fn check_token_indirect_owner(452		&self,453		token: TokenId,454		maybe_owner: &T::CrossAccountId,455		nesting_budget: &dyn Budget,456	) -> Result<bool, DispatchError> {457		let balance = self.balance(maybe_owner.clone(), token);458		let total_pieces: u128 = <Pallet<T>>::total_pieces(self.id, token).unwrap_or(u128::MAX);459		if balance != total_pieces {460			return Ok(false);461		}462463		<PalletStructure<T>>::check_indirectly_owned(464			maybe_owner.clone(),465			self.id,466			token,467			None,468			nesting_budget,469		)470	}471472	/// Returns 10 token in no particular order.473	fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId> {474		<Pallet<T>>::token_owners(self.id, token).unwrap_or_default()475	}476477	fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue> {478		<Pallet<T>>::token_properties((self.id, token_id))?479			.get(key)480			.cloned()481	}482483	fn token_properties(&self, token_id: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property> {484		let Some(properties) = <Pallet<T>>::token_properties((self.id, token_id)) else {485			return vec![];486		};487488		keys.map(|keys| {489			keys.into_iter()490				.filter_map(|key| {491					properties.get(&key).map(|value| Property {492						key,493						value: value.clone(),494					})495				})496				.collect()497		})498		.unwrap_or_else(|| {499			properties500				.into_iter()501				.map(|(key, value)| Property { key, value })502				.collect()503		})504	}505506	fn total_supply(&self) -> u32 {507		<Pallet<T>>::total_supply(self)508	}509510	fn account_balance(&self, account: T::CrossAccountId) -> u32 {511		<AccountBalance<T>>::get((self.id, account))512	}513514	fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128 {515		<Balance<T>>::get((self.id, token, account))516	}517518	fn allowance(519		&self,520		sender: T::CrossAccountId,521		spender: T::CrossAccountId,522		token: TokenId,523	) -> u128 {524		<Allowance<T>>::get((self.id, token, sender, spender))525	}526527	fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>> {528		Some(self)529	}530531	fn total_pieces(&self, token: TokenId) -> Option<u128> {532		<Pallet<T>>::total_pieces(self.id, token)533	}534535	fn set_allowance_for_all(536		&self,537		owner: T::CrossAccountId,538		operator: T::CrossAccountId,539		approve: bool,540	) -> DispatchResultWithPostInfo {541		with_weight(542			<Pallet<T>>::set_allowance_for_all(self, &owner, &operator, approve),543			<CommonWeights<T>>::set_allowance_for_all(),544		)545	}546547	fn allowance_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool {548		<Pallet<T>>::allowance_for_all(self, &owner, &operator)549	}550551	fn repair_item(&self, token: TokenId) -> DispatchResultWithPostInfo {552		with_weight(553			<Pallet<T>>::repair_item(self, token),554			<CommonWeights<T>>::force_repair_item(),555		)556	}557}558559impl<T: Config> RefungibleExtensions<T> for RefungibleHandle<T> {560	fn repartition(561		&self,562		owner: &T::CrossAccountId,563		token: TokenId,564		amount: u128,565	) -> DispatchResultWithPostInfo {566		with_weight(567			<Pallet<T>>::repartition(self, owner, token, amount),568			<SelfWeightOf<T>>::repartition_item(),569		)570	}571}
modifiedpallets/refungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/refungible/src/erc.rs
+++ b/pallets/refungible/src/erc.rs
@@ -50,8 +50,10 @@
 };
 
 use crate::{
-	common::CommonWeights, weights::WeightInfo, AccountBalance, Balance, Config, CreateItemData,
-	Pallet, RefungibleHandle, SelfWeightOf, TokenProperties, TokensMinted, TotalSupply,
+	common::{mint_with_props_weight, CommonWeights},
+	weights::WeightInfo,
+	AccountBalance, Balance, Config, CreateItemData, Pallet, RefungibleHandle, SelfWeightOf,
+	TokenProperties, TokensMinted, TotalSupply,
 };
 
 frontier_contract! {
@@ -661,7 +663,7 @@
 	/// @param tokenUri Token URI that would be stored in the NFT properties
 	/// @return uint256 The id of the newly minted token
 	#[solidity(rename_selector = "mintWithTokenURI")]
-	#[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(1))]
+	#[weight(mint_with_props_weight::<T>(<SelfWeightOf<T>>::create_item(), [1].into_iter()))]
 	fn mint_with_token_uri(
 		&mut self,
 		caller: Caller,
@@ -683,7 +685,7 @@
 	/// @param tokenId ID of the minted RFT
 	/// @param tokenUri Token URI that would be stored in the RFT properties
 	#[solidity(hide, rename_selector = "mintWithTokenURI")]
-	#[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(1))]
+	#[weight(mint_with_props_weight::<T>(<SelfWeightOf<T>>::create_item(), [1].into_iter()))]
 	fn mint_with_token_uri_check_id(
 		&mut self,
 		caller: Caller,
@@ -1052,22 +1054,26 @@
 	}
 
 	/// @notice Function to mint a token.
-	/// @param tokenProperties Properties of minted token
-	#[weight(if token_properties.len() == 1 {
-		<SelfWeightOf<T>>::create_multiple_items_ex_multiple_owners(token_properties.iter().next().unwrap().owners.len() as u32)
+	/// @param tokensData Data of minted token(s)
+	#[weight(if tokens_data.len() == 1 {
+		let token_data = tokens_data.first().unwrap();
+
+		mint_with_props_weight::<T>(
+			<SelfWeightOf<T>>::create_multiple_items_ex_multiple_owners(token_data.owners.len() as u32),
+			[token_data.properties.len() as u32].into_iter(),
+		)
 	} else {
-		<SelfWeightOf<T>>::create_multiple_items_ex_multiple_items(token_properties.len() as u32)
-	} + <SelfWeightOf<T>>::set_token_properties(token_properties.len() as u32))]
-	fn mint_bulk_cross(
-		&mut self,
-		caller: Caller,
-		token_properties: Vec<MintTokenData>,
-	) -> Result<bool> {
+		mint_with_props_weight::<T>(
+			<SelfWeightOf<T>>::create_multiple_items_ex_multiple_items(tokens_data.len() as u32),
+			tokens_data.iter().map(|d| d.properties.len() as u32),
+		)
+	})]
+	fn mint_bulk_cross(&mut self, caller: Caller, tokens_data: Vec<MintTokenData>) -> Result<bool> {
 		let caller = T::CrossAccountId::from_eth(caller);
-		let has_multiple_tokens = token_properties.len() > 1;
+		let has_multiple_tokens = tokens_data.len() > 1;
 
-		let mut create_rft_data = Vec::with_capacity(token_properties.len());
-		for MintTokenData { owners, properties } in token_properties {
+		let mut create_rft_data = Vec::with_capacity(tokens_data.len());
+		for MintTokenData { owners, properties } in tokens_data {
 			let has_multiple_owners = owners.len() > 1;
 			if has_multiple_tokens & has_multiple_owners {
 				return Err(
@@ -1108,7 +1114,12 @@
 	/// @param to The new owner
 	/// @param tokens array of pairs of token ID and token URI for minted tokens
 	#[solidity(hide, rename_selector = "mintBulkWithTokenURI")]
-	#[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32) + <SelfWeightOf<T>>::set_token_properties(tokens.len() as u32))]
+	#[weight(
+		mint_with_props_weight::<T>(
+			<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32),
+			tokens.iter().map(|_| 1),
+		)
+	)]
 	fn mint_bulk_with_token_uri(
 		&mut self,
 		caller: Caller,
@@ -1162,7 +1173,7 @@
 	/// @param to The new owner crossAccountId
 	/// @param properties Properties of minted token
 	/// @return uint256 The id of the newly minted token
-	#[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(properties.len() as u32))]
+	#[weight(mint_with_props_weight::<T>(<SelfWeightOf<T>>::create_item(), [properties.len() as u32].into_iter()))]
 	fn mint_cross(
 		&mut self,
 		caller: Caller,