git.delta.rocks / unique-network / refs/commits / 1eed41e9dfea

difftreelog

fix restore foreign flag, minor fixes

Daniel Shiposha2023-10-19parent: #56fde60.patch.diff
in: master

11 files changed

modifiedpallets/common/src/benchmarking.rsdiffbeforeafterboth
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 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, Property, PropertyKey, PropertyValue, MAX_COLLECTION_DESCRIPTION_LENGTH,33	MAX_COLLECTION_NAME_LENGTH, MAX_PROPERTIES_PER_ITEM, MAX_TOKEN_PREFIX_LENGTH,34};3536use crate::{BenchmarkPropertyWriter, CollectionHandle, Config, Pallet};3738const SEED: u32 = 1;3940pub fn create_data<const S: u32>() -> BoundedVec<u8, ConstU32<S>> {41	create_var_data::<S>(S)42}43pub fn create_u16_data<const S: u32>() -> BoundedVec<u16, ConstU32<S>> {44	(0..S)45		.map(|v| (v & 0xffff) as u16)46		.collect::<Vec<_>>()47		.try_into()48		.unwrap()49}50pub fn create_var_data<const S: u32>(size: u32) -> BoundedVec<u8, ConstU32<S>> {51	assert!(size <= S, "size ({size}) should be less within bound ({S})",);52	(0..size)53		.map(|v| (v & 0xff) as u8)54		.collect::<Vec<_>>()55		.try_into()56		.unwrap()57}58pub fn property_key(id: usize) -> PropertyKey {59	#[cfg(not(feature = "std"))]60	use alloc::string::ToString;61	let mut data = create_data();62	// No DerefMut available for .fill63	for i in 0..data.len() {64		data[i] = b'0';65	}66	let bytes = id.to_string();67	let len = data.len();68	data[len - bytes.len()..].copy_from_slice(bytes.as_bytes());69	data70}71pub fn property_value() -> PropertyValue {72	create_data()73}7475pub fn create_collection_raw<T: Config, R>(76	owner: T::CrossAccountId,77	mode: CollectionMode,78	handler: impl FnOnce(79		T::CrossAccountId,80		CreateCollectionData<T::CrossAccountId>,81	) -> Result<CollectionId, DispatchError>,82	cast: impl FnOnce(CollectionHandle<T>) -> R,83) -> Result<R, DispatchError> {84	let imbalance = <T as Config>::Currency::deposit(85		owner.as_sub(),86		T::CollectionCreationPrice::get(),87		Precision::Exact,88	)?;89	debug_assert!(imbalance.peek().is_zero());90	let name = create_u16_data::<MAX_COLLECTION_NAME_LENGTH>();91	let description = create_u16_data::<MAX_COLLECTION_DESCRIPTION_LENGTH>();92	let token_prefix = create_data::<MAX_TOKEN_PREFIX_LENGTH>();93	handler(94		owner,95		CreateCollectionData {96			mode,97			name,98			description,99			token_prefix,100			permissions: Some(CollectionPermissions {101				nesting: Some(NestingPermissions {102					token_owner: false,103					collection_admin: false,104					restricted: None,105					#[cfg(feature = "runtime-benchmarks")]106					permissive: true,107				}),108				mint_mode: Some(true),109				..Default::default()110			}),111			..Default::default()112		},113	)114	.and_then(CollectionHandle::try_get)115	.map(cast)116}117fn create_collection<T: Config>(118	owner: T::CrossAccountId,119) -> Result<CollectionHandle<T>, DispatchError> {120	create_collection_raw(121		owner,122		CollectionMode::NFT,123		|owner: T::CrossAccountId, data| {124			<Pallet<T>>::init_collection(owner.clone(), Some(owner), false, data)125		},126		|h| h,127	)128}129130/// Helper macros, which handles all benchmarking preparation in semi-declarative way131///132/// `name` is a substrate account133/// - name: sub[(id)]134/// `name` is a collection with owner `owner`135/// - name: collection(owner)136/// `name` is a cross account based on substrate137/// - name: cross_sub[(id)]138/// `name` is a cross account, which maps to substrate account `name`139/// - name: cross_from_sub140/// `name` is a cross account, which maps to substrate account `other_name`141/// - name: cross_from_sub(other_name)142#[macro_export]143macro_rules! bench_init {144	($name:ident: sub $(($id:expr))?; $($rest:tt)*) => {145		let $name: T::AccountId = account(stringify!($name), 0 $(+ $id)?, SEED);146		bench_init!($($rest)*);147	};148	($name:ident: collection($owner:ident); $($rest:tt)*) => {149		let $name = create_collection::<T>(T::CrossAccountId::from_sub($owner.clone()))?;150		bench_init!($($rest)*);151	};152	($name:ident: cross; $($rest:tt)*) => {153		let $name = T::CrossAccountId::from_sub($name);154		bench_init!($($rest)*);155	};156	($name:ident: cross_sub $(($id:expr))?; $($rest:tt)*) => {157		let account: T::AccountId = account(stringify!($name), 0 $(+ $id)?, SEED);158		let $name = T::CrossAccountId::from_sub(account);159		bench_init!($($rest)*);160	};161	($name:ident: cross_from_sub; $($rest:tt)*) => {162		let $name = T::CrossAccountId::from_sub($name);163		bench_init!($($rest)*);164	};165	($name:ident: cross_from_sub($from:ident); $($rest:tt)*) => {166		let $name = T::CrossAccountId::from_sub($from);167		bench_init!($($rest)*);168	};169	() => {}170}171172#[benchmarks]173mod benchmarks {174	use super::*;175176	#[benchmark]177	fn set_collection_properties(178		b: Linear<0, MAX_PROPERTIES_PER_ITEM>,179	) -> Result<(), BenchmarkError> {180		bench_init! {181			owner: sub; collection: collection(owner);182			owner: cross_from_sub;183		};184		let props = (0..b)185			.map(|p| Property {186				key: property_key(p as usize),187				value: property_value(),188			})189			.collect::<Vec<_>>();190191		#[block]192		{193			<Pallet<T>>::set_collection_properties(&collection, &owner, props.into_iter())?;194		}195196		Ok(())197	}198199	#[benchmark]200	fn check_accesslist() -> Result<(), BenchmarkError> {201		bench_init! {202			owner: sub; collection: collection(owner);203			sender: cross_from_sub(owner);204		};205206		let mut collection_handle = <CollectionHandle<T>>::try_get(collection.id)?;207		<Pallet<T>>::update_permissions(208			&sender,209			&mut collection_handle,210			CollectionPermissions {211				access: Some(AccessMode::AllowList),212				..Default::default()213			},214		)?;215216		<Pallet<T>>::toggle_allowlist(&collection, &sender, &sender, true)?;217218		assert_eq!(219			collection_handle.permissions.access(),220			AccessMode::AllowList221		);222223		#[block]224		{225			collection_handle.check_allowlist(&sender)?;226		}227228		Ok(())229	}230231	#[benchmark]232	fn property_writer_load_collection_info() -> Result<(), BenchmarkError> {233		bench_init! {234			owner: sub; collection: collection(owner);235			sender: sub;236			sender: cross_from_sub(sender);237		};238239		#[block]240		{241			<BenchmarkPropertyWriter<T>>::load_collection_info(&&collection, &sender);242		}243244		Ok(())245	}246}
modifiedpallets/common/src/dispatch.rsdiffbeforeafterboth
--- a/pallets/common/src/dispatch.rs
+++ b/pallets/common/src/dispatch.rs
@@ -78,6 +78,21 @@
 		sender: T::CrossAccountId,
 		payer: Option<T::CrossAccountId>,
 		data: CreateCollectionData<T::CrossAccountId>,
+	) -> Result<CollectionId, DispatchError> {
+		Self::create_internal(sender, payer, false, data)
+	}
+
+	/// Create a collection. The collection will be created according to the value of [`data.mode`](CreateCollectionData::mode).
+	///
+	/// * `sender` - The user who will become the owner of the collection.
+	/// * `payer` - If set, the user who pays the collection creation deposit.
+	/// * `data` - Description of the created collection.
+	/// * `is_special_collection` -- Whether this collection is a system one, i.e. can have special flags set.
+	fn create_internal(
+		sender: T::CrossAccountId,
+		payer: Option<T::CrossAccountId>,
+		is_special_collection: bool,
+		data: CreateCollectionData<T::CrossAccountId>,
 	) -> Result<CollectionId, DispatchError>;
 
 	/// Delete the collection.
modifiedpallets/common/src/lib.rsdiffbeforeafterboth
--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -1088,6 +1088,7 @@
 			read_only: flags.external,
 
 			flags: RpcCollectionFlags {
+				foreign: flags.foreign,
 				erc721metadata: flags.erc721metadata,
 			},
 		})
@@ -1129,12 +1130,16 @@
 	/// * `owner` - The owner of the collection.
 	/// * `payer` - If set, the user that will pay a deposit for the collection creation.
 	/// * `data` - Description of the created collection.
+	/// * `is_special_collection` -- Whether this collection is a special one, i.e. can have special flags set.
 	pub fn init_collection(
 		owner: T::CrossAccountId,
 		payer: Option<T::CrossAccountId>,
+		is_special_collection: bool,
 		data: CreateCollectionData<T::CrossAccountId>,
 	) -> Result<CollectionId, DispatchError> {
-		ensure!(data.flags.is_allowed_for_user(), <Error<T>>::NoPermission);
+		if !is_special_collection {
+			ensure!(data.flags.is_allowed_for_user(), <Error<T>>::NoPermission);
+		}
 
 		// Take a (non-refundable) deposit of collection creation
 		if let Some(payer) = payer {
modifiedpallets/foreign-assets/src/lib.rsdiffbeforeafterboth
--- a/pallets/foreign-assets/src/lib.rs
+++ b/pallets/foreign-assets/src/lib.rs
@@ -153,9 +153,11 @@
 				.expect("description length < max description length; qed");
 
 			let payer = None;
-			let collection_id = T::CollectionDispatch::create(
+			let is_special_collection = true;
+			let collection_id = T::CollectionDispatch::create_internal(
 				foreign_collection_owner,
 				payer,
+				is_special_collection,
 				CreateCollectionData {
 					name,
 					description,
modifiedpallets/fungible/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/fungible/src/benchmarking.rs
+++ b/pallets/fungible/src/benchmarking.rs
@@ -31,7 +31,7 @@
 		owner,
 		CollectionMode::Fungible(0),
 		|owner: T::CrossAccountId, data| {
-			<PalletCommon<T>>::init_collection(owner.clone(), Some(owner), data)
+			<PalletCommon<T>>::init_collection(owner.clone(), Some(owner), false, data)
 		},
 		FungibleHandle::cast,
 	)
modifiedpallets/nonfungible/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/benchmarking.rs
+++ b/pallets/nonfungible/src/benchmarking.rs
@@ -58,7 +58,7 @@
 		owner,
 		CollectionMode::NFT,
 		|owner: T::CrossAccountId, data| {
-			<PalletCommon<T>>::init_collection(owner.clone(), Some(owner), data)
+			<PalletCommon<T>>::init_collection(owner.clone(), Some(owner), false, data)
 		},
 		NonfungibleHandle::cast,
 	)
modifiedpallets/refungible/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/refungible/src/benchmarking.rs
+++ b/pallets/refungible/src/benchmarking.rs
@@ -20,6 +20,7 @@
 use pallet_common::{
 	bench_init,
 	benchmarking::{create_collection_raw, property_key, property_value},
+	Pallet as PalletCommon,
 };
 use sp_std::prelude::*;
 use up_data_structs::{
@@ -61,7 +62,9 @@
 	create_collection_raw(
 		owner,
 		CollectionMode::ReFungible,
-		|owner: T::CrossAccountId, data| <Pallet<T>>::init_collection(owner.clone(), owner, data),
+		|owner: T::CrossAccountId, data| {
+			<PalletCommon<T>>::init_collection(owner.clone(), Some(owner), false, data)
+		},
 		RefungibleHandle::cast,
 	)
 }
modifiedpallets/refungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -103,7 +103,7 @@
 use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};
 use sp_std::{collections::btree_map::BTreeMap, vec, vec::Vec};
 use up_data_structs::{
-	budget::Budget, mapping::TokenAddressMapping, AccessMode, CollectionId, CreateCollectionData,
+	budget::Budget, mapping::TokenAddressMapping, AccessMode, CollectionId,
 	CreateRefungibleExMultipleOwners, PropertiesPermissionMap, Property, PropertyKey,
 	PropertyKeyPermission, PropertyScope, PropertyValue, TokenId, TokenOwnerError,
 	TokenProperties as TokenPropertiesT, MAX_REFUNGIBLE_PIECES,
@@ -296,19 +296,6 @@
 
 // unchecked calls skips any permission checks
 impl<T: Config> Pallet<T> {
-	/// Create RFT collection
-	///
-	/// `init_collection` will take non-refundable deposit for collection creation.
-	///
-	/// - `data`: Contains settings for collection limits and permissions.
-	pub fn init_collection(
-		owner: T::CrossAccountId,
-		payer: T::CrossAccountId,
-		data: CreateCollectionData<T::CrossAccountId>,
-	) -> Result<CollectionId, DispatchError> {
-		<PalletCommon<T>>::init_collection(owner, Some(payer), data)
-	}
-
 	/// Destroy RFT collection
 	///
 	/// `destroy_collection` will throw error if collection contains any tokens.
modifiedprimitives/data-structs/src/lib.rsdiffbeforeafterboth
--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -380,7 +380,7 @@
 pub struct CollectionFlags {
 	/// Reserved flag
 	#[bondrewd(bits = "0..1")]
-	pub reserved_0: bool,
+	pub foreign: bool,
 	/// Supports ERC721Metadata
 	#[bondrewd(bits = "1..2")]
 	pub erc721metadata: bool,
@@ -395,7 +395,7 @@
 
 impl CollectionFlags {
 	pub fn is_allowed_for_user(self) -> bool {
-		!self.reserved_0 && !self.external && self.reserved == 0
+		!self.foreign && !self.external && self.reserved == 0
 	}
 }
 
@@ -461,6 +461,8 @@
 
 #[derive(Debug, Encode, Decode, Clone, PartialEq, TypeInfo, Serialize, Deserialize)]
 pub struct RpcCollectionFlags {
+	/// Is collection is foreign.
+	pub foreign: bool,
 	/// Collection supports ERC721Metadata.
 	pub erc721metadata: bool,
 }
@@ -503,7 +505,7 @@
 	pub read_only: bool,
 
 	/// Extra collection flags
-	#[version(2.., upper(RpcCollectionFlags {erc721metadata: false}))]
+	#[version(2.., upper(RpcCollectionFlags {foreign: false, erc721metadata: false}))]
 	pub flags: RpcCollectionFlags,
 }
 
@@ -540,6 +542,7 @@
 			read_only: true,
 
 			flags: RpcCollectionFlags {
+				foreign: false,
 				erc721metadata: false,
 			},
 		}
modifiedruntime/common/config/pallets/foreign_asset.rsdiffbeforeafterboth
--- a/runtime/common/config/pallets/foreign_asset.rs
+++ b/runtime/common/config/pallets/foreign_asset.rs
@@ -1,4 +1,6 @@
 use frame_support::{parameter_types, PalletId};
+#[cfg(not(feature = "governance"))]
+use frame_system::EnsureRoot;
 use pallet_evm::account::CrossAccountId;
 use sp_core::H160;
 use staging_xcm::prelude::*;
@@ -6,10 +8,6 @@
 
 #[cfg(feature = "governance")]
 use crate::runtime_common::config::governance;
-
-#[cfg(not(feature = "governance"))]
-use frame_system::EnsureRoot;
-
 use crate::{
 	runtime_common::config::{
 		ethereum::CrossAccountId as ConfigCrossAccountId,
modifiedruntime/common/dispatch.rsdiffbeforeafterboth
--- a/runtime/common/dispatch.rs
+++ b/runtime/common/dispatch.rs
@@ -66,9 +66,10 @@
 		}
 	}
 
-	fn create(
+	fn create_internal(
 		sender: T::CrossAccountId,
 		payer: Option<T::CrossAccountId>,
+		is_special_collection: bool,
 		data: CreateCollectionData<T::CrossAccountId>,
 	) -> Result<CollectionId, DispatchError> {
 		match data.mode {
@@ -86,7 +87,7 @@
 			_ => {}
 		};
 
-		<PalletCommon<T>>::init_collection(sender, payer, data)
+		<PalletCommon<T>>::init_collection(sender, payer, is_special_collection, data)
 	}
 
 	fn destroy(sender: T::CrossAccountId, collection_id: CollectionId) -> DispatchResult {