git.delta.rocks / unique-network / refs/commits / 3ee9e950e03f

difftreelog

refactor move properties around

Yaroslav Bolyukin2022-05-27parent: #a034a2f.patch.diff
in: master

18 files changed

modifiedclient/rpc/src/lib.rsdiffbeforeafterboth
--- a/client/rpc/src/lib.rs
+++ b/client/rpc/src/lib.rs
@@ -73,13 +73,6 @@
 		token: TokenId,
 		at: Option<BlockHash>,
 	) -> Result<Option<CrossAccountId>>;
-	#[rpc(name = "unique_constMetadata")]
-	fn const_metadata(
-		&self,
-		collection: CollectionId,
-		token: TokenId,
-		at: Option<BlockHash>,
-	) -> Result<Vec<u8>>;
 
 	#[rpc(name = "unique_collectionProperties")]
 	fn collection_properties(
@@ -418,9 +411,6 @@
 	);
 	pass_method!(
 		topmost_token_owner(collection: CollectionId, token: TokenId) -> Option<CrossAccountId>, unique_api
-	);
-	pass_method!(
-		const_metadata(collection: CollectionId, token: TokenId) -> Vec<u8>, unique_api
 	);
 	pass_method!(total_supply(collection: CollectionId) -> u32, unique_api);
 	pass_method!(account_balance(collection: CollectionId, account: CrossAccountId) -> u32, unique_api);
modifiedpallets/common/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/common/src/benchmarking.rs
+++ b/pallets/common/src/benchmarking.rs
@@ -86,8 +86,6 @@
 	let name = create_u16_data::<MAX_COLLECTION_NAME_LENGTH>();
 	let description = create_u16_data::<MAX_COLLECTION_DESCRIPTION_LENGTH>();
 	let token_prefix = create_data::<MAX_TOKEN_PREFIX_LENGTH>();
-	let offchain_schema = create_data::<OFFCHAIN_SCHEMA_LIMIT>();
-	let const_on_chain_schema = create_data::<CONST_ON_CHAIN_SCHEMA_LIMIT>();
 	handler(
 		owner,
 		CreateCollectionData {
@@ -95,8 +93,6 @@
 			name,
 			description,
 			token_prefix,
-			offchain_schema,
-			const_on_chain_schema,
 			..Default::default()
 		},
 	)
modifiedpallets/common/src/lib.rsdiffbeforeafterboth
--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -55,7 +55,6 @@
 	SponsoringRateLimit,
 	budget::Budget,
 	COLLECTION_FIELD_LIMIT,
-	CollectionField,
 	PhantomType,
 	Property,
 	Properties,
@@ -77,6 +76,8 @@
 	RmrkPartType,
 	RmrkTheme,
 	RmrkNftChild,
+	CollectionPermissions,
+	SchemaVersion,
 };
 
 pub use pallet::*;
@@ -433,17 +434,6 @@
 		Hasher = Blake2_128Concat,
 		Key = CollectionId,
 		Value = PropertiesPermissionMap,
-		QueryKind = ValueQuery,
-	>;
-
-	/// Large variable-size collection fields are extracted here
-	#[pallet::storage]
-	pub type CollectionData<T> = StorageNMap<
-		Key = (
-			Key<Twox64Concat, CollectionId>,
-			Key<Twox64Concat, CollectionField>,
-		),
-		Value = BoundedVec<u8, ConstU32<COLLECTION_FIELD_LIMIT>>,
 		QueryKind = ValueQuery,
 	>;
 
@@ -505,19 +495,37 @@
 			if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {
 				use up_data_structs::{CollectionVersion1, CollectionVersion2};
 				<CollectionById<T>>::translate::<CollectionVersion1<T::AccountId>, _>(|id, v| {
-					Self::set_field_raw(
-						id,
-						CollectionField::OffchainSchema,
-						v.offchain_schema.clone().into_inner(),
-					)
-					.expect("data has lower bounds than field");
-					Self::set_field_raw(
+					let mut props = Vec::new();
+					if !v.offchain_schema.is_empty() {
+						props.push(Property {
+							key: b"_old_offchainSchema".to_vec().try_into().unwrap(),
+							value: v.offchain_schema.clone().into_inner().try_into().expect("offchain schema too big"),
+						});
+					}
+					if !v.variable_on_chain_schema.is_empty() {
+						props.push(Property {
+							key: b"_old_variableOnChainSchema".to_vec().try_into().unwrap(),
+							value: v.variable_on_chain_schema.clone().into_inner().try_into().expect("offchain schema too big"),
+						});
+					}
+					if !v.const_on_chain_schema.is_empty() {
+						props.push(Property {
+							key: b"_old_constOnChainSchema".to_vec().try_into().unwrap(),
+							value: v.const_on_chain_schema.clone().into_inner().try_into().expect("offchain schema too big"),
+						});
+					}
+					props.push(Property {
+						key: b"_old_schemaVersion".to_vec().try_into().unwrap(),
+						value: match v.schema_version {
+							SchemaVersion::ImageURL => b"ImageUrl".as_slice(),
+							SchemaVersion::Unique => b"Unique".as_slice(),
+						}.to_vec().try_into().unwrap(),
+					});
+					Self::set_scoped_collection_properties(
 						id,
-						CollectionField::ConstOnChainSchema,
-						v.const_on_chain_schema.clone().into_inner(),
-					)
-					.expect("data has lower bounds than field");
-
+						PropertyScope::None,
+						props.into_iter(),
+					).expect("existing data larger than properties");
 					Some(CollectionVersion2::from(v))
 				});
 			}
@@ -587,7 +595,6 @@
 			owner_can_transfer: Some(limits.owner_can_transfer()),
 			owner_can_destroy: Some(limits.owner_can_destroy()),
 			transfers_enabled: Some(limits.transfers_enabled()),
-			nesting_rule: Some(limits.nesting_rule().clone()),
 		};
 
 		Some(effective_limits)
@@ -599,12 +606,10 @@
 			description,
 			owner,
 			mode,
-			access,
 			token_prefix,
-			mint_mode,
-			schema_version,
 			sponsorship,
 			limits,
+			permissions,
 		} = <CollectionById<T>>::get(collection)?;
 
 		let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)
@@ -628,28 +633,45 @@
 			description: description.into_inner(),
 			owner,
 			mode,
-			access,
 			token_prefix: token_prefix.into_inner(),
-			mint_mode,
-			schema_version,
 			sponsorship,
 			limits,
-			offchain_schema: <CollectionData<T>>::get((
-				collection,
-				CollectionField::OffchainSchema,
-			))
-			.into_inner(),
-			const_on_chain_schema: <CollectionData<T>>::get((
-				collection,
-				CollectionField::ConstOnChainSchema,
-			))
-			.into_inner(),
+			permissions,
 			token_property_permissions,
 			properties,
 		})
 	}
 }
 
+macro_rules! limit_default {
+	($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{
+		$(
+			if let Some($new) = $new.$field {
+				let $old = $old.$field($($arg)?);
+				let _ = $new;
+				let _ = $old;
+				$check
+			} else {
+				$new.$field = $old.$field
+			}
+		)*
+	}};
+}
+macro_rules! limit_default_clone {
+	($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{
+		$(
+			if let Some($new) = $new.$field.clone() {
+				let $old = $old.$field($($arg)?);
+				let _ = $new;
+				let _ = $old;
+				$check
+			} else {
+				$new.$field = $old.$field.clone()
+			}
+		)*
+	}};
+}
+
 impl<T: Config> Pallet<T> {
 	pub fn init_collection(
 		owner: T::AccountId,
@@ -681,11 +703,8 @@
 			owner: owner.clone(),
 			name: data.name,
 			mode: data.mode.clone(),
-			mint_mode: false,
-			access: data.access.unwrap_or_default(),
 			description: data.description,
 			token_prefix: data.token_prefix,
-			schema_version: data.schema_version.unwrap_or_default(),
 			sponsorship: data
 				.pending_sponsor
 				.map(SponsorshipState::Unconfirmed)
@@ -694,6 +713,10 @@
 				.limits
 				.map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))
 				.unwrap_or_else(|| Ok(CollectionLimits::default()))?,
+			permissions: data
+				.permissions
+				.map(|permissions| Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions))
+				.unwrap_or_else(|| Ok(CollectionPermissions::default()))?,
 		};
 
 		let mut collection_properties = up_data_structs::CollectionProperties::get();
@@ -732,18 +755,6 @@
 		<CreatedCollectionCount<T>>::put(created_count);
 		<Pallet<T>>::deposit_event(Event::CollectionCreated(id, data.mode.id(), owner.clone()));
 		<CollectionById<T>>::insert(id, collection);
-		Self::set_field_raw(
-			id,
-			CollectionField::OffchainSchema,
-			data.offchain_schema.into_inner(),
-		)
-		.expect("data has lower bounds than field");
-		Self::set_field_raw(
-			id,
-			CollectionField::ConstOnChainSchema,
-			data.const_on_chain_schema.into_inner(),
-		)
-		.expect("data has lower bounds than field");
 		Ok(id)
 	}
 
@@ -766,7 +777,6 @@
 
 		<DestroyedCollectionCount<T>>::put(destroyed_collections);
 		<CollectionById<T>>::remove(collection.id);
-		<CollectionData<T>>::remove_prefix((collection.id,), None);
 		<AdminAmount<T>>::remove(collection.id);
 		<IsAdmin<T>>::remove_prefix((collection.id,), None);
 		<Allowlist<T>>::remove_prefix((collection.id,), None);
@@ -866,6 +876,18 @@
 		Ok(())
 	}
 
+	// For migrations
+	pub fn set_property_permission_unchecked(
+		collection: CollectionId,
+		property_permission: PropertyKeyPermission,
+	) -> DispatchResult {
+		<CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {
+			permissions.try_set(property_permission.key, property_permission.permission)
+		})
+		.map_err(<Error<T>>::from)?;
+		Ok(())
+	}
+
 	pub fn set_property_permission(
 		collection: &CollectionHandle<T>,
 		sender: &T::CrossAccountId,
@@ -989,35 +1011,6 @@
 		Ok(key_permissions)
 	}
 
-	fn set_field_raw(
-		collection_id: CollectionId,
-		field: CollectionField,
-		value: Vec<u8>,
-	) -> DispatchResult {
-		if !value.is_empty() {
-			<CollectionData<T>>::insert(
-				(collection_id, field),
-				BoundedVec::try_from(value).map_err(|_| <Error<T>>::CollectionFieldSizeExceeded)?,
-			)
-		} else {
-			<CollectionData<T>>::remove((collection_id, field));
-		}
-		Ok(())
-	}
-
-	pub fn set_field(
-		collection: &CollectionHandle<T>,
-		sender: &T::CrossAccountId,
-		field: CollectionField,
-		value: Vec<u8>,
-	) -> DispatchResult {
-		collection.check_is_owner_or_admin(sender)?;
-
-		// =========
-
-		Self::set_field_raw(collection.id, field, value)
-	}
-
 	pub fn toggle_allowlist(
 		collection: &CollectionHandle<T>,
 		sender: &T::CrossAccountId,
@@ -1077,21 +1070,6 @@
 		old_limit: &CollectionLimits,
 		mut new_limit: CollectionLimits,
 	) -> Result<CollectionLimits, DispatchError> {
-		macro_rules! limit_default {
-				($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{
-					$(
-						if let Some($new) = $new.$field {
-							let $old = $old.$field($($arg)?);
-							let _ = $new;
-							let _ = $old;
-							$check
-						} else {
-							$new.$field = $old.$field
-						}
-					)*
-				}};
-			}
-
 		limit_default!(old_limit, new_limit,
 			account_token_ownership_limit => ensure!(
 				new_limit <= MAX_TOKEN_OWNERSHIP,
@@ -1126,6 +1104,15 @@
 		);
 		Ok(new_limit)
 	}
+	pub fn clamp_permissions(
+		mode: CollectionMode,
+		old_limit: &CollectionPermissions,
+		mut new_limit: CollectionPermissions,
+	) -> Result<CollectionPermissions, DispatchError> {
+		limit_default_clone!(old_limit, new_limit,
+		);
+		Ok(new_limit)
+	}
 }
 
 #[macro_export]
@@ -1253,7 +1240,6 @@
 	fn last_token_id(&self) -> TokenId;
 
 	fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId>;
-	fn const_metadata(&self, token: TokenId) -> Vec<u8>;
 	fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;
 	fn token_properties(&self, token_id: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;
 	/// Amount of unique collection tokens
modifiedpallets/fungible/src/common.rsdiffbeforeafterboth
--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -51,27 +51,27 @@
 		<SelfWeightOf<T>>::burn_item()
 	}
 
-	fn set_collection_properties(amount: u32) -> Weight {
+	fn set_collection_properties(_amount: u32) -> Weight {
 		// Error
 		0
 	}
 
-	fn delete_collection_properties(amount: u32) -> Weight {
+	fn delete_collection_properties(_amount: u32) -> Weight {
 		// Error
 		0
 	}
 
-	fn set_token_properties(amount: u32) -> Weight {
+	fn set_token_properties(_amount: u32) -> Weight {
 		// Error
 		0
 	}
 
-	fn delete_token_properties(amount: u32) -> Weight {
+	fn delete_token_properties(_amount: u32) -> Weight {
 		// Error
 		0
 	}
 
-	fn set_property_permissions(amount: u32) -> Weight {
+	fn set_property_permissions(_amount: u32) -> Weight {
 		// Error
 		0
 	}
@@ -320,9 +320,6 @@
 
 	fn token_owner(&self, _token: TokenId) -> Option<T::CrossAccountId> {
 		None
-	}
-	fn const_metadata(&self, _token: TokenId) -> Vec<u8> {
-		Vec::new()
 	}
 
 	fn token_property(&self, _token_id: TokenId, _key: &PropertyKey) -> Option<PropertyValue> {
modifiedpallets/fungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -168,7 +168,7 @@
 			.checked_sub(amount)
 			.ok_or(<CommonError<T>>::TokenValueTooLow)?;
 
-		if collection.access == AccessMode::AllowList {
+		if collection.permissions.access() == AccessMode::AllowList {
 			collection.check_allowlist(owner)?;
 		}
 
@@ -210,7 +210,7 @@
 			<CommonError<T>>::TransferNotAllowed,
 		);
 
-		if collection.access == AccessMode::AllowList {
+		if collection.permissions.access() == AccessMode::AllowList {
 			collection.check_allowlist(from)?;
 			collection.check_allowlist(to)?;
 		}
@@ -280,7 +280,7 @@
 	) -> DispatchResult {
 		if !collection.is_owner_or_admin(sender) {
 			ensure!(
-				collection.mint_mode,
+				collection.permissions.mint_mode(),
 				<CommonError<T>>::PublicMintingNotAllowed
 			);
 			collection.check_allowlist(sender)?;
@@ -380,7 +380,7 @@
 		spender: &T::CrossAccountId,
 		amount: u128,
 	) -> DispatchResult {
-		if collection.access == AccessMode::AllowList {
+		if collection.permissions.access() == AccessMode::AllowList {
 			collection.check_allowlist(owner)?;
 			collection.check_allowlist(spender)?;
 		}
@@ -408,7 +408,7 @@
 		if spender.conv_eq(from) {
 			return Ok(None);
 		}
-		if collection.access == AccessMode::AllowList {
+		if collection.permissions.access() == AccessMode::AllowList {
 			// `from`, `to` checked in [`transfer`]
 			collection.check_allowlist(spender)?;
 		}
modifiedpallets/nonfungible/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/benchmarking.rs
+++ b/pallets/nonfungible/src/benchmarking.rs
@@ -29,9 +29,7 @@
 const SEED: u32 = 1;
 
 fn create_max_item_data<T: Config>(owner: T::CrossAccountId) -> CreateItemData<T> {
-	let const_data = create_data::<CUSTOM_DATA_LIMIT>();
 	CreateItemData::<T> {
-		const_data,
 		owner,
 		properties: Default::default(),
 	}
modifiedpallets/nonfungible/src/common.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -116,7 +116,6 @@
 ) -> Result<CreateItemData<T>, DispatchError> {
 	match data {
 		up_data_structs::CreateItemData::NFT(data) => Ok(CreateItemData::<T> {
-			const_data: data.const_data,
 			properties: data.properties,
 			owner: to.clone(),
 		}),
@@ -376,12 +375,6 @@
 
 	fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId> {
 		<TokenData<T>>::get((self.id, token)).map(|t| t.owner)
-	}
-	fn const_metadata(&self, token: TokenId) -> Vec<u8> {
-		<TokenData<T>>::get((self.id, token))
-			.map(|t| t.const_data)
-			.unwrap_or_default()
-			.into_inner()
 	}
 
 	fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue> {
modifiedpallets/nonfungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -109,15 +109,6 @@
 	}
 }
 
-fn error_unsupported_schema_version() -> Error {
-	alloc::format!(
-		"Unsupported schema version! Support only {:?}",
-		SchemaVersion::ImageURL
-	)
-	.as_str()
-	.into()
-}
-
 #[derive(ToLog)]
 pub enum ERC721Events {
 	Transfer {
@@ -167,16 +158,10 @@
 	/// Returns token's const_metadata
 	#[solidity(rename_selector = "tokenURI")]
 	fn token_uri(&self, token_id: uint256) -> Result<string> {
-		if !matches!(self.schema_version, SchemaVersion::ImageURL) {
-			return Err(error_unsupported_schema_version());
-		}
-
 		self.consume_store_reads(1)?;
-		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;
+		let _token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;
 		Ok(string::from_utf8_lossy(
-			&<TokenData<T>>::get((self.id, token_id))
-				.ok_or("token not found")?
-				.const_data,
+			todo!()
 		)
 		.into())
 	}
@@ -344,7 +329,6 @@
 			self,
 			&caller,
 			CreateItemData::<T> {
-				const_data: BoundedVec::default(),
 				properties: BoundedVec::default(),
 				owner: to,
 			},
@@ -366,10 +350,6 @@
 		token_id: uint256,
 		token_uri: string,
 	) -> Result<bool> {
-		if !matches!(self.schema_version, SchemaVersion::ImageURL) {
-			return Err(error_unsupported_schema_version());
-		}
-
 		let caller = T::CrossAccountId::from_eth(caller);
 		let to = T::CrossAccountId::from_eth(to);
 		let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;
@@ -385,13 +365,12 @@
 			return Err("item id should be next".into());
 		}
 
+		todo!("token uri");
+
 		<Pallet<T>>::create_item(
 			self,
 			&caller,
 			CreateItemData::<T> {
-				const_data: Vec::<u8>::from(token_uri)
-					.try_into()
-					.map_err(|_| "token uri is too long")?,
 				properties: BoundedVec::default(),
 				owner: to,
 			},
@@ -477,7 +456,6 @@
 		}
 		let data = (0..total_tokens)
 			.map(|_| CreateItemData::<T> {
-				const_data: BoundedVec::default(),
 				properties: BoundedVec::default(),
 				owner: to.clone(),
 			})
@@ -496,10 +474,6 @@
 		to: address,
 		tokens: Vec<(uint256, string)>,
 	) -> Result<bool> {
-		if !matches!(self.schema_version, SchemaVersion::ImageURL) {
-			return Err(error_unsupported_schema_version());
-		}
-
 		let caller = T::CrossAccountId::from_eth(caller);
 		let to = T::CrossAccountId::from_eth(to);
 		let mut expected_index = <TokensMinted<T>>::get(self.id)
@@ -517,10 +491,8 @@
 			}
 			expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;
 
+			todo!("token uri");
 			data.push(CreateItemData::<T> {
-				const_data: Vec::<u8>::from(token_uri)
-					.try_into()
-					.map_err(|_| "token uri is too long")?,
 				properties: BoundedVec::default(),
 				owner: to.clone(),
 			});
modifiedpallets/nonfungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -33,7 +33,7 @@
 use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};
 use sp_core::H160;
 use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};
-use sp_std::{vec::Vec, vec};
+use sp_std::{vec::Vec, vec, collections::btree_set::BTreeSet};
 use core::ops::Deref;
 use sp_std::collections::btree_map::BTreeMap;
 use codec::{Encode, Decode, MaxEncodedLen};
@@ -52,6 +52,7 @@
 #[struct_versioning::versioned(version = 2, upper)]
 #[derive(Encode, Decode, TypeInfo, MaxEncodedLen)]
 pub struct ItemData<CrossAccountId> {
+	#[version(..2)]
 	pub const_data: BoundedVec<u8, CustomDataLimit>,
 
 	#[version(..2)]
@@ -148,9 +149,45 @@
 	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
 		fn on_runtime_upgrade() -> Weight {
 			if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {
-				<TokenData<T>>::translate_values::<ItemDataVersion1<T::CrossAccountId>, _>(|v| {
+				let mut had_consts = BTreeSet::new();
+				<TokenData<T>>::translate::<ItemDataVersion1<T::CrossAccountId>, _>(|(collection, token), v| {
+					let mut props = vec![];
+					if !v.const_data.is_empty() {
+						props.push(Property {
+							key: b"_old_constData".to_vec().try_into().unwrap(),
+							value: v.const_data.clone().into_inner().try_into().expect("const too long"),
+						});
+						had_consts.insert(collection);
+					}
+					if !v.variable_data.is_empty() {
+						props.push(Property {
+							key: b"_old_variableData".to_vec().try_into().unwrap(),
+							value: v.variable_data.clone().into_inner().try_into().expect("variable too long"),
+						})
+					}
+					if !props.is_empty() {
+						Self::set_scoped_token_properties(
+							collection,
+							token,
+							PropertyScope::None,
+							props.into_iter(),
+						).expect("existing token data exceeds property storage");
+					}
 					Some(<ItemDataVersion2<T::CrossAccountId>>::from(v))
-				})
+				});
+				for collection in had_consts {
+					<PalletCommon<T>>::set_property_permission_unchecked(
+						collection,
+						PropertyKeyPermission {
+							key: b"_old_constData".to_vec().try_into().unwrap(),
+							permission: PropertyPermission {
+								mutable: false,
+								collection_admin: true,
+								token_owner: false,
+							},
+						}
+					).expect("failed to configure permission");
+				}
 			}
 
 			0
@@ -267,7 +304,7 @@
 			<CommonError<T>>::NoPermission
 		);
 
-		if collection.access == AccessMode::AllowList {
+		if collection.permissions.access() == AccessMode::AllowList {
 			collection.check_allowlist(sender)?;
 		}
 
@@ -493,7 +530,7 @@
 			<CommonError<T>>::NoPermission
 		);
 
-		if collection.access == AccessMode::AllowList {
+		if collection.permissions.access() == AccessMode::AllowList {
 			collection.check_allowlist(from)?;
 			collection.check_allowlist(to)?;
 		}
@@ -579,7 +616,7 @@
 	) -> DispatchResult {
 		if !collection.is_owner_or_admin(sender) {
 			ensure!(
-				collection.mint_mode,
+				collection.permissions.mint_mode(),
 				<CommonError<T>>::PublicMintingNotAllowed
 			);
 			collection.check_allowlist(sender)?;
@@ -639,7 +676,7 @@
 				<TokenData<T>>::insert(
 					(collection.id, token),
 					ItemData {
-						const_data: data.const_data.clone(),
+						// const_data: data.const_data.clone(),
 						owner: data.owner.clone(),
 					},
 				);
@@ -756,7 +793,7 @@
 		token: TokenId,
 		spender: Option<&T::CrossAccountId>,
 	) -> DispatchResult {
-		if collection.access == AccessMode::AllowList {
+		if collection.permissions.access() == AccessMode::AllowList {
 			collection.check_allowlist(sender)?;
 			if let Some(spender) = spender {
 				collection.check_allowlist(spender)?;
@@ -791,7 +828,7 @@
 		if spender.conv_eq(from) {
 			return Ok(());
 		}
-		if collection.access == AccessMode::AllowList {
+		if collection.permissions.access() == AccessMode::AllowList {
 			// `from`, `to` checked in [`transfer`]
 			collection.check_allowlist(spender)?;
 		}
@@ -875,7 +912,7 @@
 			);
 			Ok(())
 		}
-		match handle.limits.nesting_rule() {
+		match handle.permissions.nesting() {
 			NestingRule::Disabled => fail!(<CommonError<T>>::NestingIsDisabled),
 			NestingRule::Owner => {
 				ensure_sender_allowed::<T>(handle.id, under, from, sender, nesting_budget)?
modifiedpallets/proxy-rmrk-core/src/lib.rsdiffbeforeafterboth
--- a/pallets/proxy-rmrk-core/src/lib.rs
+++ b/pallets/proxy-rmrk-core/src/lib.rs
@@ -403,10 +403,8 @@
         nft_type: NftType,
         properties: impl Iterator<Item=Property>
     ) -> Result<TokenId, DispatchError> {
+        todo!("store nft type");
         let data = CreateNftExData {
-            const_data: nft_type.encode()
-                .try_into()
-                .map_err(|_| <Error<T>>::NftTypeEncodeError)?,
             properties: BoundedVec::default(),
             owner: owner.clone(),
         };
@@ -528,13 +526,8 @@
         Ok(nft_property)
     }
 
-    pub fn get_nft_type(collection_id: CollectionId, token_id: TokenId) -> Result<NftType, DispatchError> {
-        let token_data = <TokenData<T>>::get((collection_id, token_id))
-            .ok_or(<Error<T>>::NoAvailableNftId)?;
-
-        let mut const_data = token_data.const_data.as_slice();
-
-        NftType::decode(&mut const_data).map_err(|_| <Error<T>>::NoAvailableNftId.into())
+    pub fn get_nft_type(_collection_id: CollectionId, _token_id: TokenId) -> Result<NftType, DispatchError> {
+        todo!("should get it from properties?")
     }
 
     pub fn ensure_nft_type(collection_id: CollectionId, token_id: TokenId, nft_type: NftType) -> DispatchResult {
modifiedpallets/refungible/src/common.rsdiffbeforeafterboth
--- a/pallets/refungible/src/common.rs
+++ b/pallets/refungible/src/common.rs
@@ -336,11 +336,6 @@
 	fn token_owner(&self, _token: TokenId) -> Option<T::CrossAccountId> {
 		None
 	}
-	fn const_metadata(&self, token: TokenId) -> Vec<u8> {
-		<TokenData<T>>::get((self.id, token))
-			.const_data
-			.into_inner()
-	}
 
 	fn token_property(&self, _token_id: TokenId, _key: &PropertyKey) -> Option<PropertyValue> {
 		None
modifiedpallets/refungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -321,7 +321,7 @@
 			<CommonError<T>>::TransferNotAllowed
 		);
 
-		if collection.access == AccessMode::AllowList {
+		if collection.permissions.access() == AccessMode::AllowList {
 			collection.check_allowlist(from)?;
 			collection.check_allowlist(to)?;
 		}
@@ -424,7 +424,7 @@
 	) -> DispatchResult {
 		if !collection.is_owner_or_admin(sender) {
 			ensure!(
-				collection.mint_mode,
+				collection.permissions.mint_mode(),
 				<CommonError<T>>::PublicMintingNotAllowed
 			);
 			collection.check_allowlist(sender)?;
@@ -566,7 +566,7 @@
 		token: TokenId,
 		amount: u128,
 	) -> DispatchResult {
-		if collection.access == AccessMode::AllowList {
+		if collection.permissions.access() == AccessMode::AllowList {
 			collection.check_allowlist(sender)?;
 			collection.check_allowlist(spender)?;
 		}
@@ -598,7 +598,7 @@
 		if spender.conv_eq(from) {
 			return Ok(None);
 		}
-		if collection.access == AccessMode::AllowList {
+		if collection.permissions.access() == AccessMode::AllowList {
 			// `from`, `to` checked in [`transfer`]
 			collection.check_allowlist(spender)?;
 		}
modifiedpallets/unique/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/unique/src/benchmarking.rs
+++ b/pallets/unique/src/benchmarking.rs
@@ -130,26 +130,6 @@
 		let collection = create_nft_collection::<T>(caller.clone())?;
 	}: _(RawOrigin::Signed(caller.clone()), collection, false)
 
-	set_offchain_schema {
-		let b in 0..OFFCHAIN_SCHEMA_LIMIT;
-
-		let caller: T::AccountId = account("caller", 0, SEED);
-		let collection = create_nft_collection::<T>(caller.clone())?;
-		let data = create_var_data(b);
-	}: set_offchain_schema(RawOrigin::Signed(caller.clone()), collection, data)
-
-	set_const_on_chain_schema {
-		let b in 0..CONST_ON_CHAIN_SCHEMA_LIMIT;
-
-		let caller: T::AccountId = account("caller", 0, SEED);
-		let collection = create_nft_collection::<T>(caller.clone())?;
-		let data = create_var_data(b);
-	}: set_const_on_chain_schema(RawOrigin::Signed(caller.clone()), collection, data)
-
-	set_schema_version {
-		let caller: T::AccountId = account("caller", 0, SEED);
-		let collection = create_nft_collection::<T>(caller.clone())?;
-	}: set_schema_version(RawOrigin::Signed(caller.clone()), collection, SchemaVersion::Unique)
 
 	set_collection_limits{
 		let caller: T::AccountId = account("caller", 0, SEED);
modifiedpallets/unique/src/lib.rsdiffbeforeafterboth
--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -35,10 +35,10 @@
 use frame_system::{self as system, ensure_signed};
 use sp_runtime::{sp_std::prelude::Vec};
 use up_data_structs::{
-	CONST_ON_CHAIN_SCHEMA_LIMIT, OFFCHAIN_SCHEMA_LIMIT, MAX_COLLECTION_NAME_LENGTH,
+	MAX_COLLECTION_NAME_LENGTH,
 	MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH, AccessMode, CreateItemData,
-	CollectionLimits, CollectionId, CollectionMode, TokenId, SchemaVersion, SponsorshipState,
-	CreateCollectionData, CreateItemExData, budget, CollectionField, Property, PropertyKey,
+	CollectionLimits, CollectionPermissions, CollectionId, CollectionMode, TokenId, SponsorshipState,
+	CreateCollectionData, CreateItemExData, budget, Property, PropertyKey,
 	PropertyKeyPermission,
 };
 use pallet_evm::account::CrossAccountId;
@@ -162,6 +162,8 @@
 		/// * collection_id: Globally unique collection identifier.
 		CollectionLimitSet(CollectionId),
 
+		CollectionPermissionSet(CollectionId),
+
 		/// Mint permission	was set
 		///
 		/// # Arguments
@@ -417,67 +419,6 @@
 			));
 
 			Ok(())
-		}
-
-		/// Toggle between normal and allow list access for the methods with access for `Anyone`.
-		///
-		/// # Permissions
-		///
-		/// * Collection Owner.
-		///
-		/// # Arguments
-		///
-		/// * collection_id.
-		///
-		/// * mode: [AccessMode]
-		#[weight = <SelfWeightOf<T>>::set_public_access_mode()]
-		#[transactional]
-		pub fn set_public_access_mode(origin, collection_id: CollectionId, mode: AccessMode) -> DispatchResult
-		{
-			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
-
-			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
-			target_collection.check_is_owner(&sender)?;
-
-			target_collection.access = mode.clone();
-
-			<Pallet<T>>::deposit_event(Event::<T>::PublicAccessModeSet(
-				collection_id,
-				mode
-			));
-
-			target_collection.save()
-		}
-
-		/// Allows Anyone to create tokens if:
-		/// * Allow List is enabled, and
-		/// * Address is added to allow list, and
-		/// * This method was called with True parameter
-		///
-		/// # Permissions
-		/// * Collection Owner
-		///
-		/// # Arguments
-		///
-		/// * collection_id.
-		///
-		/// * mint_permission: Boolean parameter. If True, allows minting to Anyone with conditions above.
-		#[weight = <SelfWeightOf<T>>::set_mint_permission()]
-		#[transactional]
-		pub fn set_mint_permission(origin, collection_id: CollectionId, mint_permission: bool) -> DispatchResult
-		{
-			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
-
-			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
-			target_collection.check_is_owner(&sender)?;
-
-			target_collection.mint_mode = mint_permission;
-
-			<Pallet<T>>::deposit_event(Event::<T>::MintPermissionSet(
-				collection_id
-			));
-
-			target_collection.save()
 		}
 
 		/// Change the owner of the collection.
@@ -941,118 +882,42 @@
 			dispatch_call::<T, _>(collection_id, |d| d.transfer_from(sender, from, recipient, item_id, value, &budget))
 		}
 
-		/// Set schema standard
-		/// ImageURL
-		/// Unique
-		///
-		/// # Permissions
-		///
-		/// * Collection Owner
-		/// * Collection Admin
-		///
-		/// # Arguments
-		///
-		/// * collection_id.
-		///
-		/// * schema: SchemaVersion: enum
-		#[weight = <SelfWeightOf<T>>::set_schema_version()]
+		#[weight = <SelfWeightOf<T>>::set_collection_limits()]
 		#[transactional]
-		pub fn set_schema_version(
+		pub fn set_collection_limits(
 			origin,
 			collection_id: CollectionId,
-			version: SchemaVersion
+			new_limit: CollectionLimits,
 		) -> DispatchResult {
 			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
 			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
-			target_collection.check_is_owner_or_admin(&sender)?;
-			target_collection.schema_version = version;
-
-			<Pallet<T>>::deposit_event(Event::<T>::SchemaVersionSet(
-				collection_id
-			));
-
-			target_collection.save()
-		}
-
-		/// Set off-chain data schema.
-		///
-		/// # Permissions
-		///
-		/// * Collection Owner
-		/// * Collection Admin
-		///
-		/// # Arguments
-		///
-		/// * collection_id.
-		///
-		/// * schema: String representing the offchain data schema.
-		#[weight = <SelfWeightOf<T>>::set_offchain_schema(schema.len() as u32)]
-		#[transactional]
-		pub fn set_offchain_schema(
-			origin,
-			collection_id: CollectionId,
-			schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,
-		) -> DispatchResult {
-			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
-			let collection = <CollectionHandle<T>>::try_get(collection_id)?;
+			target_collection.check_is_owner(&sender)?;
+			let old_limit = &target_collection.limits;
 
-			// =========
+			target_collection.limits = <PalletCommon<T>>::clamp_limits(target_collection.mode.clone(), &old_limit, new_limit)?;
 
-			<PalletCommon<T>>::set_field(&collection, &sender, CollectionField::OffchainSchema, schema.into_inner())?;
-
-			<Pallet<T>>::deposit_event(Event::<T>::OffchainSchemaSet(
+			<Pallet<T>>::deposit_event(Event::<T>::CollectionLimitSet(
 				collection_id
 			));
-			Ok(())
-		}
 
-		/// Set const on-chain data schema.
-		///
-		/// # Permissions
-		///
-		/// * Collection Owner
-		/// * Collection Admin
-		///
-		/// # Arguments
-		///
-		/// * collection_id.
-		///
-		/// * schema: String representing the const on-chain data schema.
-		#[weight = <SelfWeightOf<T>>::set_const_on_chain_schema(schema.len() as u32)]
-		#[transactional]
-		pub fn set_const_on_chain_schema (
-			origin,
-			collection_id: CollectionId,
-			schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>
-		) -> DispatchResult {
-			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
-			let collection = <CollectionHandle<T>>::try_get(collection_id)?;
-
-			// =========
-
-			<PalletCommon<T>>::set_field(&collection, &sender, CollectionField::ConstOnChainSchema, schema.into_inner())?;
-
-			<Pallet<T>>::deposit_event(Event::<T>::ConstOnChainSchemaSet(
-				collection_id
-			));
-			Ok(())
+			target_collection.save()
 		}
 
 		#[weight = <SelfWeightOf<T>>::set_collection_limits()]
 		#[transactional]
-		pub fn set_collection_limits(
+		pub fn set_collection_permissions(
 			origin,
 			collection_id: CollectionId,
-			new_limit: CollectionLimits,
+			new_limit: CollectionPermissions,
 		) -> DispatchResult {
 			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
 			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
 			target_collection.check_is_owner(&sender)?;
-			let old_limit = &target_collection.limits;
+			let old_limit = &target_collection.permissions;
 
-			target_collection.limits = <PalletCommon<T>>::clamp_limits(target_collection.mode.clone(), &old_limit, new_limit)?;
+			target_collection.permissions = <PalletCommon<T>>::clamp_permissions(target_collection.mode.clone(), &old_limit, new_limit)?;
 
-			<Pallet<T>>::deposit_event(Event::<T>::CollectionLimitSet(
+			<Pallet<T>>::deposit_event(Event::<T>::CollectionPermissionSet(
 				collection_id
 			));
 
modifiedprimitives/data-structs/src/lib.rsdiffbeforeafterboth
--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -186,7 +186,6 @@
 #[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]
 #[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
 pub struct TokenData<CrossAccountId> {
-	pub const_data: Vec<u8>,
 	pub properties: Vec<Property>,
 	pub owner: Option<CrossAccountId>,
 }
@@ -223,7 +222,7 @@
 	fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>;
 }
 
-#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]
+#[derive(Encode, Decode, Eq, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]
 #[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
 pub enum AccessMode {
 	Normal,
@@ -296,22 +295,26 @@
 pub struct Collection<AccountId> {
 	pub owner: AccountId,
 	pub mode: CollectionMode,
+	#[version(..2)]
 	pub access: AccessMode,
 	pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,
 	pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,
 	pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,
+
+	#[version(..2)]
 	pub mint_mode: bool,
 
 	#[version(..2)]
 	pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,
 
+	#[version(..2)]
 	pub schema_version: SchemaVersion,
 	pub sponsorship: SponsorshipState<AccountId>,
 
-	#[version(..2)]
-	pub limits: CollectionLimitsVersion1, // Collection private restrictions
-	#[version(2.., upper(limits.into()))]
-	pub limits: CollectionLimitsVersion2,
+	pub limits: CollectionLimits,
+
+	#[version(2.., upper(Default::default()))]
+	pub permissions: CollectionPermissions,
 
 	#[version(..2)]
 	pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,
@@ -329,27 +332,16 @@
 pub struct RpcCollection<AccountId> {
 	pub owner: AccountId,
 	pub mode: CollectionMode,
-	pub access: AccessMode,
 	pub name: Vec<u16>,
 	pub description: Vec<u16>,
 	pub token_prefix: Vec<u8>,
-	pub mint_mode: bool,
-	pub offchain_schema: Vec<u8>,
-	pub schema_version: SchemaVersion,
 	pub sponsorship: SponsorshipState<AccountId>,
 	pub limits: CollectionLimits,
-	pub const_on_chain_schema: Vec<u8>,
+	pub permissions: CollectionPermissions,
 	pub token_property_permissions: Vec<PropertyKeyPermission>,
 	pub properties: Vec<Property>,
 }
 
-#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen)]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
-pub enum CollectionField {
-	ConstOnChainSchema,
-	OffchainSchema,
-}
-
 #[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Derivative, MaxEncodedLen)]
 #[derivative(Debug, Default(bound = ""))]
 pub struct CreateCollectionData<AccountId> {
@@ -359,11 +351,9 @@
 	pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,
 	pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,
 	pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,
-	pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,
-	pub schema_version: Option<SchemaVersion>,
 	pub pending_sponsor: Option<AccountId>,
 	pub limits: Option<CollectionLimits>,
-	pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,
+	pub permissions: Option<CollectionPermissions>,
 	pub token_property_permissions: CollectionPropertiesPermissionsVec,
 	pub properties: CollectionPropertiesVec,
 }
@@ -375,7 +365,6 @@
 	BoundedVec<Property, ConstU32<MAX_PROPERTIES_PER_ITEM>>;
 
 /// All fields are wrapped in `Option`s, where None means chain default
-#[struct_versioning::versioned(version = 2, upper)]
 #[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]
 #[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
 pub struct CollectionLimits {
@@ -395,9 +384,6 @@
 	pub owner_can_transfer: Option<bool>,
 	pub owner_can_destroy: Option<bool>,
 	pub transfers_enabled: Option<bool>,
-
-	#[version(2.., upper(None))]
-	pub nesting_rule: Option<NestingRule>,
 }
 
 impl CollectionLimits {
@@ -444,9 +430,26 @@
 			SponsoringRateLimit::Blocks(v) => Some(v.min(MAX_SPONSOR_TIMEOUT)),
 		}
 	}
-	pub fn nesting_rule(&self) -> &NestingRule {
+}
+
+#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]
+#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+pub struct CollectionPermissions {
+	pub access: Option<AccessMode>,
+	pub mint_mode: Option<bool>,
+	pub nesting: Option<NestingRule>,
+}
+
+impl CollectionPermissions {
+	pub fn access(&self) -> AccessMode {
+		self.access.unwrap_or(AccessMode::Normal)
+	}
+	pub fn mint_mode(&self) -> bool {
+		self.mint_mode.unwrap_or(false)
+	}
+	pub fn nesting(&self) -> &NestingRule {
 		static DEFAULT: NestingRule = NestingRule::Disabled;
-		self.nesting_rule.as_ref().unwrap_or(&DEFAULT)
+		self.nesting.as_ref().unwrap_or(&DEFAULT)
 	}
 }
 
@@ -520,8 +523,6 @@
 #[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]
 #[derivative(Debug)]
 pub struct CreateNftExData<CrossAccountId> {
-	#[derivative(Debug(format_with = "bounded::vec_debug"))]
-	pub const_data: BoundedVec<u8, CustomDataLimit>,
 	#[derivative(Debug(format_with = "bounded::vec_debug"))]
 	pub properties: CollectionPropertiesVec,
 	pub owner: CrossAccountId,
modifiedprimitives/rpc/src/lib.rsdiffbeforeafterboth
--- a/primitives/rpc/src/lib.rs
+++ b/primitives/rpc/src/lib.rs
@@ -41,7 +41,6 @@
 
 		fn token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>>;
 		fn topmost_token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>>;
-		fn const_metadata(collection: CollectionId, token: TokenId) -> Result<Vec<u8>>;
 
 		fn collection_properties(collection: CollectionId, properties: Option<Vec<Vec<u8>>>) -> Result<Vec<Property>>;
 
modifiedruntime/common/src/runtime_apis.rsdiffbeforeafterboth
before · runtime/common/src/runtime_apis.rs
1#[macro_export]2macro_rules! impl_common_runtime_apis {3    (4        $(5            #![custom_apis]67            $($custom_apis:tt)+8        )?9    ) => {10        impl_runtime_apis! {11            $($($custom_apis)+)?1213            impl up_rpc::UniqueApi<Block, CrossAccountId, AccountId> for Runtime {14                fn account_tokens(collection: CollectionId, account: CrossAccountId) -> Result<Vec<TokenId>, DispatchError> {15                    dispatch_unique_runtime!(collection.account_tokens(account))16                }17                fn collection_tokens(collection: CollectionId) -> Result<Vec<TokenId>, DispatchError> {18                    dispatch_unique_runtime!(collection.collection_tokens())19                }20                fn token_exists(collection: CollectionId, token: TokenId) -> Result<bool, DispatchError> {21                    dispatch_unique_runtime!(collection.token_exists(token))22                }2324                fn token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>, DispatchError> {25                    dispatch_unique_runtime!(collection.token_owner(token))26                }27                fn topmost_token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>, DispatchError> {28                    let budget = up_data_structs::budget::Value::new(5);2930                    Ok(Some(<pallet_structure::Pallet<Runtime>>::find_topmost_owner(collection, token, &budget)?))31                }32                fn const_metadata(collection: CollectionId, token: TokenId) -> Result<Vec<u8>, DispatchError> {33                    dispatch_unique_runtime!(collection.const_metadata(token))34                }3536                fn collection_properties(37                    collection: CollectionId,38                    keys: Option<Vec<Vec<u8>>>39                ) -> Result<Vec<Property>, DispatchError> {40                    let keys = keys.map(41                        |keys| Common::bytes_keys_to_property_keys(keys)42                    ).transpose()?;4344                    Common::filter_collection_properties(collection, keys)45                }4647                fn token_properties(48                    collection: CollectionId,49                    token_id: TokenId,50                    keys: Option<Vec<Vec<u8>>>51                ) -> Result<Vec<Property>, DispatchError> {52                    let keys = keys.map(53                        |keys| Common::bytes_keys_to_property_keys(keys)54                    ).transpose()?;5556                    dispatch_unique_runtime!(collection.token_properties(token_id, keys))57                }5859                fn property_permissions(60                    collection: CollectionId,61                    keys: Option<Vec<Vec<u8>>>62                ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {63                    let keys = keys.map(64                        |keys| Common::bytes_keys_to_property_keys(keys)65                    ).transpose()?;6667                    Common::filter_property_permissions(collection, keys)68                }6970                fn token_data(71                    collection: CollectionId,72                    token_id: TokenId,73                    keys: Option<Vec<Vec<u8>>>74                ) -> Result<TokenData<CrossAccountId>, DispatchError> {75                    let token_data = TokenData {76                        const_data: Self::const_metadata(collection, token_id)?,77                        properties: Self::token_properties(collection, token_id, keys)?,78                        owner: Self::token_owner(collection, token_id)?79                    };8081                    Ok(token_data)82                }8384                fn total_supply(collection: CollectionId) -> Result<u32, DispatchError> {85                    dispatch_unique_runtime!(collection.total_supply())86                }87                fn account_balance(collection: CollectionId, account: CrossAccountId) -> Result<u32, DispatchError> {88                    dispatch_unique_runtime!(collection.account_balance(account))89                }90                fn balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<u128, DispatchError> {91                    dispatch_unique_runtime!(collection.balance(account, token))92                }93                fn allowance(94                    collection: CollectionId,95                    sender: CrossAccountId,96                    spender: CrossAccountId,97                    token: TokenId,98                ) -> Result<u128, DispatchError> {99                    dispatch_unique_runtime!(collection.allowance(sender, spender, token))100                }101102                fn adminlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {103                    Ok(<pallet_common::Pallet<Runtime>>::adminlist(collection))104                }105                fn allowlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {106                    Ok(<pallet_common::Pallet<Runtime>>::allowlist(collection))107                }108                fn allowed(collection: CollectionId, user: CrossAccountId) -> Result<bool, DispatchError> {109                    Ok(<pallet_common::Pallet<Runtime>>::allowed(collection, user))110                }111                fn last_token_id(collection: CollectionId) -> Result<TokenId, DispatchError> {112                    dispatch_unique_runtime!(collection.last_token_id())113                }114                fn collection_by_id(collection: CollectionId) -> Result<Option<RpcCollection<AccountId>>, DispatchError> {115                    Ok(<pallet_common::Pallet<Runtime>>::rpc_collection(collection))116                }117                fn collection_stats() -> Result<CollectionStats, DispatchError> {118                    Ok(<pallet_common::Pallet<Runtime>>::collection_stats())119                }120                fn next_sponsored(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<Option<u64>, DispatchError> {121                    Ok(<$crate::sponsoring::UniqueSponsorshipPredict<Runtime> as122                            $crate::sponsoring::SponsorshipPredict<Runtime>>::predict(123                        collection,124                        account,125                        token))126                }127128                fn effective_collection_limits(collection: CollectionId) -> Result<Option<CollectionLimits>, DispatchError> {129                    Ok(<pallet_common::Pallet<Runtime>>::effective_collection_limits(collection))130                }131            }132133            impl rmrk_rpc::RmrkApi<134                Block,135                AccountId,136                RmrkCollectionInfo<AccountId>,137                RmrkInstanceInfo<AccountId>,138                RmrkResourceInfo,139                RmrkPropertyInfo,140                RmrkBaseInfo<AccountId>,141                RmrkPartType,142                RmrkTheme143            > for Runtime {144                fn last_collection_idx() -> Result<RmrkCollectionId, DispatchError> {145                    Ok(RmrkCore::last_collection_idx())146                }147148                fn collection_by_id(collection_id: RmrkCollectionId) -> Result<Option<RmrkCollectionInfo<AccountId>>, DispatchError> {149                    use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, RmrkDecode}};150151                    let collection_id = CollectionId(collection_id);152                    let collection = match RmrkCore::get_typed_nft_collection(collection_id, CollectionType::Regular) {153                        Ok(c) => c,154                        Err(_) => return Ok(None),155                    };156157                    let nfts_count = dispatch_unique_runtime!(collection_id.total_supply())?;158159                    Ok(Some(RmrkCollectionInfo {160                        issuer: collection.owner.clone(),161                        metadata: RmrkCore::get_collection_property(collection_id, RmrkProperty::Metadata)?.decode_or_default(),162                        max: collection.limits.token_limit,163                        symbol: collection.token_prefix.decode_or_default(),164                        nfts_count165                    }))166                }167168                fn nft_by_id(collection_id: RmrkCollectionId, nft_by_id: RmrkNftId) -> Result<Option<RmrkInstanceInfo<AccountId>>, DispatchError> {169                    use up_data_structs::mapping::TokenAddressMapping;170                    use pallet_proxy_rmrk_core::{RmrkProperty, misc::RmrkDecode};171172                    let collection_id = CollectionId(collection_id);173                    let nft_id = TokenId(nft_by_id);174                    if !RmrkCore::nft_exists(collection_id, nft_id) { return Ok(None); }175176                    let owner = match dispatch_unique_runtime!(collection_id.token_owner(nft_id))? {177                        Some(owner) => match <Runtime as pallet_common::Config>::CrossTokenAddressMapping::address_to_token(&owner) {178                            Some((col, tok)) => RmrkAccountIdOrCollectionNftTuple::CollectionAndNftTuple(col.0, tok.0),179                            None => RmrkAccountIdOrCollectionNftTuple::AccountId(owner.as_sub().clone())180                        },181                        None => return Ok(None)182                    };183184                    let allowance = pallet_nonfungible::Allowance::<Runtime>::get((collection_id, nft_id));185186                    Ok(Some(RmrkInstanceInfo {187                        owner: owner,188                        royalty: RmrkCore::get_nft_property(collection_id, nft_id, RmrkProperty::RoyaltyInfo)?.decode_or_default(),189                        metadata: RmrkCore::get_nft_property(collection_id, nft_id, RmrkProperty::Metadata)?.decode_or_default(),190                        equipped: RmrkCore::get_nft_property(collection_id, nft_id, RmrkProperty::Equipped)?.decode_or_default(),191                        pending: allowance.is_some(),192                    }))193                }194195                fn account_tokens(account_id: AccountId, collection_id: RmrkCollectionId) -> Result<Vec<RmrkNftId>, DispatchError> {196                    use pallet_proxy_rmrk_core::misc::CollectionType;197198                    let cross_account_id = CrossAccountId::from_sub(account_id);199                    let collection_id = CollectionId(collection_id);200                    if RmrkCore::ensure_collection_type(collection_id, CollectionType::Regular).is_err() { return Ok(Vec::new()); }201202                    Ok(203                        dispatch_unique_runtime!(collection_id.account_tokens(cross_account_id))?204                            .into_iter()205                            .map(|token| token.0)206                            .collect()207                    )208                }209210                fn nft_children(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Result<Vec<RmrkNftChild>, DispatchError> {211                    use up_data_structs::mapping::TokenAddressMapping;212213                    let collection_id = CollectionId(collection_id);214                    let nft_id = TokenId(nft_id);215                    if !RmrkCore::nft_exists(collection_id, nft_id) { return Ok(Vec::new()); }216217                    let cross_account_id = CrossAccountId::from_eth(218                        EvmTokenAddressMapping::token_to_address(collection_id, nft_id)219                    );220221                    Ok(222                        pallet_nonfungible::Owned::<Runtime>::iter_prefix((collection_id, cross_account_id))223                            .map(|(child_id, _)| RmrkNftChild {224                                collection_id: collection_id.0, // todo make sure they're always from this collection // spoiler: they're not225                                nft_id: child_id.0,226                            }).collect()227                    )228                }229230                fn collection_properties(collection_id: RmrkCollectionId, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Result<Vec<RmrkPropertyInfo>, DispatchError> {231                    use pallet_proxy_rmrk_core::misc::CollectionType;232233                    let collection_id = CollectionId(collection_id);234                    if RmrkCore::ensure_collection_type(collection_id, CollectionType::Regular).is_err() {235                        return Ok(Vec::new());236                    }237238                    let properties = RmrkCore::filter_user_properties(239                        collection_id,240                        /* token_id = */ None,241                        filter_keys,242                        |key, value| RmrkPropertyInfo {243                            key,244                            value245                        }246                    )?;247248                    Ok(properties)249                }250251                fn nft_properties(collection_id: RmrkCollectionId, nft_id: RmrkNftId, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Result<Vec<RmrkPropertyInfo>, DispatchError> {252                    use pallet_proxy_rmrk_core::misc::NftType;253254                    let collection_id = CollectionId(collection_id);255                    let token_id = TokenId(nft_id);256257                    if RmrkCore::ensure_nft_type(collection_id, token_id, NftType::Regular).is_err() {258                        return Ok(Vec::new());259                    }260261		            let properties = RmrkCore::filter_user_properties(262                        collection_id,263                        Some(token_id),264                        filter_keys,265                        |key, value| RmrkPropertyInfo {266                            key,267                            value268                        }269                    )?;270271                    Ok(properties)272                }273274                fn nft_resources(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Result<Vec<RmrkResourceInfo>, DispatchError> {275                    use frame_support::BoundedVec;276                    use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, NftType, RmrkDecode}};277278                    let collection_id = CollectionId(collection_id);279                    if !RmrkCore::collection_exists(collection_id) { return Ok(Vec::new()); } // todo make sure the collection type doesn't matter280281                    let nft_id = TokenId(nft_id);282                    if RmrkCore::ensure_nft_type(collection_id, nft_id, NftType::Resource).is_err() { return Ok(Vec::new()); }283284                    let resource_collection_id: CollectionId = RmrkCore::get_nft_property(collection_id, nft_id, RmrkProperty::ResourceCollection)285                        .unwrap()286                        .decode_or_default();287                    if RmrkCore::ensure_collection_type(collection_id, CollectionType::Resource).is_err() { return Ok(Vec::new()); }288289                    let resources = pallet_nonfungible::TokenProperties::<Runtime>::iter_prefix((resource_collection_id,))290                        .filter_map(|(resource_id, properties)| Some(RmrkResourceInfo {291                            id: BoundedVec::default(), // todo ResourceId property292                            pending: RmrkCore::get_nft_property(resource_collection_id, resource_id, RmrkProperty::PendingResourceAccept).unwrap().decode_or_default(),293                            pending_removal: RmrkCore::get_nft_property(resource_collection_id, resource_id, RmrkProperty::PendingResourceRemoval).unwrap().decode_or_default(),294                            resource: RmrkCore::get_nft_property(resource_collection_id, resource_id, RmrkProperty::ResourceType).unwrap().decode_or_default(),/* {295                                RmrkResourceTypes::Basic(resource) => RmrkResourceTypes::Basic(),/*(RmrkBasicResource {296                                    src: RmrkCore::get_nft_property_inner(properties, RmrkProperty::Src).unwrap().decode_or_default(),297                                    metadata: RmrkCore::get_nft_property_inner(properties, RmrkProperty::Metadata).unwrap().decode_or_default(),298                                    license: RmrkCore::get_nft_property_inner(properties, RmrkProperty::License).unwrap().decode_or_default(),299                                    thumb: RmrkCore::get_nft_property_inner(properties, RmrkProperty::Thumb).unwrap().decode_or_default(),300                                },*///BasicResource<BoundedString>)301                                _ => todo!(), //RmrkResourceTypes::Composable(ComposableResource<BoundedString, BoundedParts>),302                                //RmrkResourceTypes::Slot(SlotResource<BoundedString>),303                            },*/304                        }))305                        .collect();306307                    Ok(resources)308                }309310                fn nft_resource_priorities(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Result<Vec<RmrkResourceId>, DispatchError> {311                    use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, NftType, RmrkDecode}};312313                    let collection_id = CollectionId(collection_id);314                    if !RmrkCore::collection_exists(collection_id) { return Ok(Vec::new()); } // todo ensure the collection type doesn't matter315316                    let nft_id = TokenId(nft_id);317                    if RmrkCore::ensure_nft_type(collection_id, nft_id, NftType::Resource).is_err() { return Ok(Vec::new()); }318319                    /*let resource_collection_id: CollectionId = RmrkCore::get_nft_property(collection_id, nft_id, RmrkProperty::ResourceCollection)320                        .unwrap()321                        .decode_or_default();322                    if RmrkCore::ensure_collection_type(collection_id, CollectionType::Resource).is_err() { return Ok(Vec::new()); }323324                    let resources = pallet_nonfungible::TokenProperties::<Runtime>::iter_prefix((resource_collection_id,))325                        .filter_map(|(resource_id, properties)| Some((326                            resource_id, // ResourceId property327                            RmrkCore::get_nft_property(resource_collection_id, resource_id, RmrkProperty::Priority).unwrap().decode_or_default(),328                        )))329                        .collect()330                        .sort_by_key(|(_, index)| *index)331                        .into_iter().map(|(resource_id, _)| resource_id)*/332                    let priorities = RmrkCore::get_nft_property(collection_id, nft_id, RmrkProperty::ResourcePriorities)?.decode_or_default();333334                    Ok(priorities)335                }336337                fn base(base_id: RmrkBaseId) -> Result<Option<RmrkBaseInfo<AccountId>>, DispatchError> {338                    use pallet_proxy_rmrk_core::{339                        RmrkProperty, misc::{CollectionType, RmrkDecode},340                    };341342                    let collection_id = CollectionId(base_id);343                    let collection = match RmrkCore::get_typed_nft_collection(collection_id, CollectionType::Base) {344                        Ok(c) => c,345                        Err(_) => return Ok(None),346                    };347348                    Ok(Some(RmrkBaseInfo {349                        issuer: collection.owner.clone(),350                        base_type: RmrkCore::get_collection_property(collection_id, RmrkProperty::BaseType)?.decode_or_default(),351                        symbol: collection.token_prefix.decode_or_default(),352                    }))353                }354355                fn base_parts(base_id: RmrkBaseId) -> Result<Vec<RmrkPartType>, DispatchError> {356                    use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, NftType, RmrkDecode}};357358                    let collection_id = CollectionId(base_id);359                    if RmrkCore::ensure_collection_type(collection_id, CollectionType::Base).is_err() { return Ok(Vec::new()); }360361                    let parts = dispatch_unique_runtime!(collection_id.collection_tokens())?362                        .into_iter()363                        .filter_map(|token_id| {364                            let nft_type = RmrkCore::get_nft_type(collection_id, token_id).ok()?;365366                            match nft_type {367                                NftType::FixedPart => Some(RmrkPartType::FixedPart(RmrkFixedPart {368                                    id: RmrkCore::get_nft_property(collection_id, token_id, RmrkProperty::ExternalPartId).ok()?.decode_or_default(),369                                    src: RmrkCore::get_nft_property(collection_id, token_id, RmrkProperty::Src).ok()?.decode_or_default(),370                                    z: RmrkCore::get_nft_property(collection_id, token_id, RmrkProperty::ZIndex).ok()?.decode_or_default(),371                                })),372                                NftType::SlotPart => Some(RmrkPartType::SlotPart(RmrkSlotPart {373                                    id: RmrkCore::get_nft_property(collection_id, token_id, RmrkProperty::ExternalPartId).ok()?.decode_or_default(),374                                    src: RmrkCore::get_nft_property(collection_id, token_id, RmrkProperty::Src).ok()?.decode_or_default(),375                                    z: RmrkCore::get_nft_property(collection_id, token_id, RmrkProperty::ZIndex).ok()?.decode_or_default(),376                                    equippable: RmrkCore::get_nft_property(collection_id, token_id, RmrkProperty::EquippableList).ok()?.decode_or_default(),377                                })),378                                _ => None379                            }380                        })381                        .collect();382383                    Ok(parts)384                }385386                fn theme_names(base_id: RmrkBaseId) -> Result<Vec<RmrkThemeName>, DispatchError> {387                    use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, RmrkDecode}};388389                    let collection_id = CollectionId(base_id);390                    if RmrkCore::ensure_collection_type(collection_id, CollectionType::Base).is_err() {391                        return Ok(Vec::new());392                    }393394                    let theme_names = dispatch_unique_runtime!(collection_id.collection_tokens())?395                        .iter()396                        .filter_map(|token_id| {397                            let nft_type = RmrkCore::get_nft_type(collection_id, *token_id).unwrap();398399                            match nft_type {400                                Theme => Some(401                                    RmrkCore::get_nft_property(collection_id, *token_id, RmrkProperty::ThemeName).unwrap().decode_or_default()402                                ),403                                _ => None404                            }405                        })406                        .collect();407408                    Ok(theme_names)409                }410411                fn theme(base_id: RmrkBaseId, theme_name: RmrkThemeName, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Result<Option<RmrkTheme>, DispatchError> {412                    use pallet_proxy_rmrk_core::{413                        RmrkProperty,414                        misc::{CollectionType, NftType, RmrkDecode}415                    };416417                    let collection_id = CollectionId(base_id);418                    if RmrkCore::ensure_collection_type(collection_id, CollectionType::Base).is_err() {419                        return Ok(None);420                    }421422                    let theme_info = dispatch_unique_runtime!(collection_id.collection_tokens())?423                        .into_iter()424                        .find_map(|token_id| {425                            RmrkCore::ensure_nft_type(collection_id, token_id, NftType::Theme).ok()?;426427                            let name: RmrkString = RmrkCore::get_nft_property(428                                collection_id, token_id, RmrkProperty::ThemeName429                            ).ok()?.decode_or_default();430431                            if name == theme_name {432                                Some((name, token_id))433                            } else {434                                None435                            }436                        });437438                    let (name, theme_id) = match theme_info {439                        Some((name, theme_id)) => (name, theme_id),440                        None => return Ok(None)441                    };442443                    let properties = RmrkCore::filter_user_properties(444                        collection_id,445                        Some(theme_id),446                        filter_keys,447                        |key, value| RmrkThemeProperty {448                            key,449                            value450                        }451                    )?;452453                    let inherit = RmrkCore::get_nft_property(454                        collection_id,455                        theme_id,456                        RmrkProperty::ThemeInherit457                    )?.decode_or_default();458459                    let theme = RmrkTheme {460                        name,461                        properties,462                        inherit,463                    };464465                    Ok(Some(theme))466                }467            }468469            impl sp_api::Core<Block> for Runtime {470                fn version() -> RuntimeVersion {471                    VERSION472                }473474                fn execute_block(block: Block) {475                    Executive::execute_block(block)476                }477478                fn initialize_block(header: &<Block as BlockT>::Header) {479                    Executive::initialize_block(header)480                }481            }482483            impl sp_api::Metadata<Block> for Runtime {484                fn metadata() -> OpaqueMetadata {485                    OpaqueMetadata::new(Runtime::metadata().into())486                }487            }488489            impl sp_block_builder::BlockBuilder<Block> for Runtime {490                fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {491                    Executive::apply_extrinsic(extrinsic)492                }493494                fn finalize_block() -> <Block as BlockT>::Header {495                    Executive::finalize_block()496                }497498                fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {499                    data.create_extrinsics()500                }501502                fn check_inherents(503                    block: Block,504                    data: sp_inherents::InherentData,505                ) -> sp_inherents::CheckInherentsResult {506                    data.check_extrinsics(&block)507                }508509                // fn random_seed() -> <Block as BlockT>::Hash {510                //     RandomnessCollectiveFlip::random_seed().0511                // }512            }513514            impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {515                fn validate_transaction(516                    source: TransactionSource,517                    tx: <Block as BlockT>::Extrinsic,518                    hash: <Block as BlockT>::Hash,519                ) -> TransactionValidity {520                    Executive::validate_transaction(source, tx, hash)521                }522            }523524            impl sp_offchain::OffchainWorkerApi<Block> for Runtime {525                fn offchain_worker(header: &<Block as BlockT>::Header) {526                    Executive::offchain_worker(header)527                }528            }529530            impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {531                fn chain_id() -> u64 {532                    <Runtime as pallet_evm::Config>::ChainId::get()533                }534535                fn account_basic(address: H160) -> EVMAccount {536                    EVM::account_basic(&address)537                }538539                fn gas_price() -> U256 {540                    <Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price()541                }542543                fn account_code_at(address: H160) -> Vec<u8> {544                    EVM::account_codes(address)545                }546547                fn author() -> H160 {548                    <pallet_evm::Pallet<Runtime>>::find_author()549                }550551                fn storage_at(address: H160, index: U256) -> H256 {552                    let mut tmp = [0u8; 32];553                    index.to_big_endian(&mut tmp);554                    EVM::account_storages(address, H256::from_slice(&tmp[..]))555                }556557                #[allow(clippy::redundant_closure)]558                fn call(559                    from: H160,560                    to: H160,561                    data: Vec<u8>,562                    value: U256,563                    gas_limit: U256,564                    max_fee_per_gas: Option<U256>,565                    max_priority_fee_per_gas: Option<U256>,566                    nonce: Option<U256>,567                    estimate: bool,568                    access_list: Option<Vec<(H160, Vec<H256>)>>,569                ) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {570                    let config = if estimate {571                        let mut config = <Runtime as pallet_evm::Config>::config().clone();572                        config.estimate = true;573                        Some(config)574                    } else {575                        None576                    };577578                    let is_transactional = false;579                    <Runtime as pallet_evm::Config>::Runner::call(580                        CrossAccountId::from_eth(from),581                        to,582                        data,583                        value,584                        gas_limit.low_u64(),585                        max_fee_per_gas,586                        max_priority_fee_per_gas,587                        nonce,588                        access_list.unwrap_or_default(),589                        is_transactional,590                        config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),591                    ).map_err(|err| err.into())592                }593594                #[allow(clippy::redundant_closure)]595                fn create(596                    from: H160,597                    data: Vec<u8>,598                    value: U256,599                    gas_limit: U256,600                    max_fee_per_gas: Option<U256>,601                    max_priority_fee_per_gas: Option<U256>,602                    nonce: Option<U256>,603                    estimate: bool,604                    access_list: Option<Vec<(H160, Vec<H256>)>>,605                ) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {606                    let config = if estimate {607                        let mut config = <Runtime as pallet_evm::Config>::config().clone();608                        config.estimate = true;609                        Some(config)610                    } else {611                        None612                    };613614                    let is_transactional = false;615                    <Runtime as pallet_evm::Config>::Runner::create(616                        CrossAccountId::from_eth(from),617                        data,618                        value,619                        gas_limit.low_u64(),620                        max_fee_per_gas,621                        max_priority_fee_per_gas,622                        nonce,623                        access_list.unwrap_or_default(),624                        is_transactional,625                        config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),626                    ).map_err(|err| err.into())627                }628629                fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {630                    Ethereum::current_transaction_statuses()631                }632633                fn current_block() -> Option<pallet_ethereum::Block> {634                    Ethereum::current_block()635                }636637                fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {638                    Ethereum::current_receipts()639                }640641                fn current_all() -> (642                    Option<pallet_ethereum::Block>,643                    Option<Vec<pallet_ethereum::Receipt>>,644                    Option<Vec<TransactionStatus>>645                ) {646                    (647                        Ethereum::current_block(),648                        Ethereum::current_receipts(),649                        Ethereum::current_transaction_statuses()650                    )651                }652653                fn extrinsic_filter(xts: Vec<<Block as sp_api::BlockT>::Extrinsic>) -> Vec<pallet_ethereum::Transaction> {654                    xts.into_iter().filter_map(|xt| match xt.0.function {655                        Call::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction),656                        _ => None657                    }).collect()658                }659660                fn elasticity() -> Option<Permill> {661                    None662                }663            }664665            impl fp_rpc::ConvertTransactionRuntimeApi<Block> for Runtime {666                fn convert_transaction(transaction: pallet_ethereum::Transaction) -> <Block as BlockT>::Extrinsic  {667                    UncheckedExtrinsic::new_unsigned(668                        pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),669                    )670                }671            }672673            impl sp_session::SessionKeys<Block> for Runtime {674                fn decode_session_keys(675                    encoded: Vec<u8>,676                ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {677                    SessionKeys::decode_into_raw_public_keys(&encoded)678                }679680                fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {681                    SessionKeys::generate(seed)682                }683            }684685            impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {686                fn slot_duration() -> sp_consensus_aura::SlotDuration {687                    sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())688                }689690                fn authorities() -> Vec<AuraId> {691                    Aura::authorities().to_vec()692                }693            }694695            impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {696                fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {697                    ParachainSystem::collect_collation_info(header)698                }699            }700701            impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {702                fn account_nonce(account: AccountId) -> Index {703                    System::account_nonce(account)704                }705            }706707            impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {708                fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {709                    TransactionPayment::query_info(uxt, len)710                }711                fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {712                    TransactionPayment::query_fee_details(uxt, len)713                }714            }715716            /*717            impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber, Hash>718                for Runtime719            {720                fn call(721                    origin: AccountId,722                    dest: AccountId,723                    value: Balance,724                    gas_limit: u64,725                    input_data: Vec<u8>,726                ) -> pallet_contracts_primitives::ContractExecResult {727                    Contracts::bare_call(origin, dest, value, gas_limit, input_data, false)728                }729730                fn instantiate(731                    origin: AccountId,732                    endowment: Balance,733                    gas_limit: u64,734                    code: pallet_contracts_primitives::Code<Hash>,735                    data: Vec<u8>,736                    salt: Vec<u8>,737                ) -> pallet_contracts_primitives::ContractInstantiateResult<AccountId, BlockNumber>738                {739                    Contracts::bare_instantiate(origin, endowment, gas_limit, code, data, salt, true, false)740                }741742                fn get_storage(743                    address: AccountId,744                    key: [u8; 32],745                ) -> pallet_contracts_primitives::GetStorageResult {746                    Contracts::get_storage(address, key)747                }748749                fn rent_projection(750                    address: AccountId,751                ) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {752                    Contracts::rent_projection(address)753                }754            }755            */756757            #[cfg(feature = "runtime-benchmarks")]758            impl frame_benchmarking::Benchmark<Block> for Runtime {759                fn benchmark_metadata(extra: bool) -> (760                    Vec<frame_benchmarking::BenchmarkList>,761                    Vec<frame_support::traits::StorageInfo>,762                ) {763                    use frame_benchmarking::{list_benchmark, Benchmarking, BenchmarkList};764                    use frame_support::traits::StorageInfoTrait;765766                    let mut list = Vec::<BenchmarkList>::new();767768                    list_benchmark!(list, extra, pallet_evm_migration, EvmMigration);769                    list_benchmark!(list, extra, pallet_common, Common);770                    list_benchmark!(list, extra, pallet_unique, Unique);771                    list_benchmark!(list, extra, pallet_structure, Structure);772                    list_benchmark!(list, extra, pallet_inflation, Inflation);773                    list_benchmark!(list, extra, pallet_fungible, Fungible);774                    list_benchmark!(list, extra, pallet_refungible, Refungible);775                    list_benchmark!(list, extra, pallet_nonfungible, Nonfungible);776                    // list_benchmark!(list, extra, pallet_evm_coder_substrate, EvmCoderSubstrate);777778                    let storage_info = AllPalletsReversedWithSystemFirst::storage_info();779780                    return (list, storage_info)781                }782783                fn dispatch_benchmark(784                    config: frame_benchmarking::BenchmarkConfig785                ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {786                    use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};787788                    let allowlist: Vec<TrackedStorageKey> = vec![789                        // Total Issuance790                        hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),791792                        // Block Number793                        hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),794                        // Execution Phase795                        hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),796                        // Event Count797                        hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),798                        // System Events799                        hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),800801                        // Evm CurrentLogs802                        hex_literal::hex!("1da53b775b270400e7e61ed5cbc5a146547f210cec367e9af919603343b9cb56").to_vec().into(),803804                        // Transactional depth805                        hex_literal::hex!("3a7472616e73616374696f6e5f6c6576656c3a").to_vec().into(),806                    ];807808                    let mut batches = Vec::<BenchmarkBatch>::new();809                    let params = (&config, &allowlist);810811                    add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);812                    add_benchmark!(params, batches, pallet_common, Common);813                    add_benchmark!(params, batches, pallet_unique, Unique);814                    add_benchmark!(params, batches, pallet_structure, Structure);815                    add_benchmark!(params, batches, pallet_inflation, Inflation);816                    add_benchmark!(params, batches, pallet_fungible, Fungible);817                    add_benchmark!(params, batches, pallet_refungible, Refungible);818                    add_benchmark!(params, batches, pallet_nonfungible, Nonfungible);819                    // add_benchmark!(params, batches, pallet_evm_coder_substrate, EvmCoderSubstrate);820821                    if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }822                    Ok(batches)823                }824            }825826            #[cfg(feature = "try-runtime")]827            impl frame_try_runtime::TryRuntime<Block> for Runtime {828                fn on_runtime_upgrade() -> (Weight, Weight) {829                    log::info!("try-runtime::on_runtime_upgrade unique-chain.");830                    let weight = Executive::try_runtime_upgrade().unwrap();831                    (weight, RuntimeBlockWeights::get().max_block)832                }833834                fn execute_block_no_check(block: Block) -> Weight {835                    Executive::execute_block_no_check(block)836                }837            }838        }839    }840}
after · runtime/common/src/runtime_apis.rs
1#[macro_export]2macro_rules! impl_common_runtime_apis {3    (4        $(5            #![custom_apis]67            $($custom_apis:tt)+8        )?9    ) => {10        impl_runtime_apis! {11            $($($custom_apis)+)?1213            impl up_rpc::UniqueApi<Block, CrossAccountId, AccountId> for Runtime {14                fn account_tokens(collection: CollectionId, account: CrossAccountId) -> Result<Vec<TokenId>, DispatchError> {15                    dispatch_unique_runtime!(collection.account_tokens(account))16                }17                fn collection_tokens(collection: CollectionId) -> Result<Vec<TokenId>, DispatchError> {18                    dispatch_unique_runtime!(collection.collection_tokens())19                }20                fn token_exists(collection: CollectionId, token: TokenId) -> Result<bool, DispatchError> {21                    dispatch_unique_runtime!(collection.token_exists(token))22                }2324                fn token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>, DispatchError> {25                    dispatch_unique_runtime!(collection.token_owner(token))26                }27                fn topmost_token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>, DispatchError> {28                    let budget = up_data_structs::budget::Value::new(5);2930                    Ok(Some(<pallet_structure::Pallet<Runtime>>::find_topmost_owner(collection, token, &budget)?))31                }3233                fn collection_properties(34                    collection: CollectionId,35                    keys: Option<Vec<Vec<u8>>>36                ) -> Result<Vec<Property>, DispatchError> {37                    let keys = keys.map(38                        |keys| Common::bytes_keys_to_property_keys(keys)39                    ).transpose()?;4041                    Common::filter_collection_properties(collection, keys)42                }4344                fn token_properties(45                    collection: CollectionId,46                    token_id: TokenId,47                    keys: Option<Vec<Vec<u8>>>48                ) -> Result<Vec<Property>, DispatchError> {49                    let keys = keys.map(50                        |keys| Common::bytes_keys_to_property_keys(keys)51                    ).transpose()?;5253                    dispatch_unique_runtime!(collection.token_properties(token_id, keys))54                }5556                fn property_permissions(57                    collection: CollectionId,58                    keys: Option<Vec<Vec<u8>>>59                ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {60                    let keys = keys.map(61                        |keys| Common::bytes_keys_to_property_keys(keys)62                    ).transpose()?;6364                    Common::filter_property_permissions(collection, keys)65                }6667                fn token_data(68                    collection: CollectionId,69                    token_id: TokenId,70                    keys: Option<Vec<Vec<u8>>>71                ) -> Result<TokenData<CrossAccountId>, DispatchError> {72                    let token_data = TokenData {73                        properties: Self::token_properties(collection, token_id, keys)?,74                        owner: Self::token_owner(collection, token_id)?75                    };7677                    Ok(token_data)78                }7980                fn total_supply(collection: CollectionId) -> Result<u32, DispatchError> {81                    dispatch_unique_runtime!(collection.total_supply())82                }83                fn account_balance(collection: CollectionId, account: CrossAccountId) -> Result<u32, DispatchError> {84                    dispatch_unique_runtime!(collection.account_balance(account))85                }86                fn balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<u128, DispatchError> {87                    dispatch_unique_runtime!(collection.balance(account, token))88                }89                fn allowance(90                    collection: CollectionId,91                    sender: CrossAccountId,92                    spender: CrossAccountId,93                    token: TokenId,94                ) -> Result<u128, DispatchError> {95                    dispatch_unique_runtime!(collection.allowance(sender, spender, token))96                }9798                fn adminlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {99                    Ok(<pallet_common::Pallet<Runtime>>::adminlist(collection))100                }101                fn allowlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {102                    Ok(<pallet_common::Pallet<Runtime>>::allowlist(collection))103                }104                fn allowed(collection: CollectionId, user: CrossAccountId) -> Result<bool, DispatchError> {105                    Ok(<pallet_common::Pallet<Runtime>>::allowed(collection, user))106                }107                fn last_token_id(collection: CollectionId) -> Result<TokenId, DispatchError> {108                    dispatch_unique_runtime!(collection.last_token_id())109                }110                fn collection_by_id(collection: CollectionId) -> Result<Option<RpcCollection<AccountId>>, DispatchError> {111                    Ok(<pallet_common::Pallet<Runtime>>::rpc_collection(collection))112                }113                fn collection_stats() -> Result<CollectionStats, DispatchError> {114                    Ok(<pallet_common::Pallet<Runtime>>::collection_stats())115                }116                fn next_sponsored(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<Option<u64>, DispatchError> {117                    Ok(<$crate::sponsoring::UniqueSponsorshipPredict<Runtime> as118                            $crate::sponsoring::SponsorshipPredict<Runtime>>::predict(119                        collection,120                        account,121                        token))122                }123124                fn effective_collection_limits(collection: CollectionId) -> Result<Option<CollectionLimits>, DispatchError> {125                    Ok(<pallet_common::Pallet<Runtime>>::effective_collection_limits(collection))126                }127            }128129            impl rmrk_rpc::RmrkApi<130                Block,131                AccountId,132                RmrkCollectionInfo<AccountId>,133                RmrkInstanceInfo<AccountId>,134                RmrkResourceInfo,135                RmrkPropertyInfo,136                RmrkBaseInfo<AccountId>,137                RmrkPartType,138                RmrkTheme139            > for Runtime {140                fn last_collection_idx() -> Result<RmrkCollectionId, DispatchError> {141                    Ok(RmrkCore::last_collection_idx())142                }143144                fn collection_by_id(collection_id: RmrkCollectionId) -> Result<Option<RmrkCollectionInfo<AccountId>>, DispatchError> {145                    use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, RmrkDecode}};146147                    let collection_id = CollectionId(collection_id);148                    let collection = match RmrkCore::get_typed_nft_collection(collection_id, CollectionType::Regular) {149                        Ok(c) => c,150                        Err(_) => return Ok(None),151                    };152153                    let nfts_count = dispatch_unique_runtime!(collection_id.total_supply())?;154155                    Ok(Some(RmrkCollectionInfo {156                        issuer: collection.owner.clone(),157                        metadata: RmrkCore::get_collection_property(collection_id, RmrkProperty::Metadata)?.decode_or_default(),158                        max: collection.limits.token_limit,159                        symbol: collection.token_prefix.decode_or_default(),160                        nfts_count161                    }))162                }163164                fn nft_by_id(collection_id: RmrkCollectionId, nft_by_id: RmrkNftId) -> Result<Option<RmrkInstanceInfo<AccountId>>, DispatchError> {165                    use up_data_structs::mapping::TokenAddressMapping;166                    use pallet_proxy_rmrk_core::{RmrkProperty, misc::RmrkDecode};167168                    let collection_id = CollectionId(collection_id);169                    let nft_id = TokenId(nft_by_id);170                    if !RmrkCore::nft_exists(collection_id, nft_id) { return Ok(None); }171172                    let owner = match dispatch_unique_runtime!(collection_id.token_owner(nft_id))? {173                        Some(owner) => match <Runtime as pallet_common::Config>::CrossTokenAddressMapping::address_to_token(&owner) {174                            Some((col, tok)) => RmrkAccountIdOrCollectionNftTuple::CollectionAndNftTuple(col.0, tok.0),175                            None => RmrkAccountIdOrCollectionNftTuple::AccountId(owner.as_sub().clone())176                        },177                        None => return Ok(None)178                    };179180                    let allowance = pallet_nonfungible::Allowance::<Runtime>::get((collection_id, nft_id));181182                    Ok(Some(RmrkInstanceInfo {183                        owner: owner,184                        royalty: RmrkCore::get_nft_property(collection_id, nft_id, RmrkProperty::RoyaltyInfo)?.decode_or_default(),185                        metadata: RmrkCore::get_nft_property(collection_id, nft_id, RmrkProperty::Metadata)?.decode_or_default(),186                        equipped: RmrkCore::get_nft_property(collection_id, nft_id, RmrkProperty::Equipped)?.decode_or_default(),187                        pending: allowance.is_some(),188                    }))189                }190191                fn account_tokens(account_id: AccountId, collection_id: RmrkCollectionId) -> Result<Vec<RmrkNftId>, DispatchError> {192                    use pallet_proxy_rmrk_core::misc::CollectionType;193194                    let cross_account_id = CrossAccountId::from_sub(account_id);195                    let collection_id = CollectionId(collection_id);196                    if RmrkCore::ensure_collection_type(collection_id, CollectionType::Regular).is_err() { return Ok(Vec::new()); }197198                    Ok(199                        dispatch_unique_runtime!(collection_id.account_tokens(cross_account_id))?200                            .into_iter()201                            .map(|token| token.0)202                            .collect()203                    )204                }205206                fn nft_children(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Result<Vec<RmrkNftChild>, DispatchError> {207                    use up_data_structs::mapping::TokenAddressMapping;208209                    let collection_id = CollectionId(collection_id);210                    let nft_id = TokenId(nft_id);211                    if !RmrkCore::nft_exists(collection_id, nft_id) { return Ok(Vec::new()); }212213                    let cross_account_id = CrossAccountId::from_eth(214                        EvmTokenAddressMapping::token_to_address(collection_id, nft_id)215                    );216217                    Ok(218                        pallet_nonfungible::Owned::<Runtime>::iter_prefix((collection_id, cross_account_id))219                            .map(|(child_id, _)| RmrkNftChild {220                                collection_id: collection_id.0, // todo make sure they're always from this collection // spoiler: they're not221                                nft_id: child_id.0,222                            }).collect()223                    )224                }225226                fn collection_properties(collection_id: RmrkCollectionId, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Result<Vec<RmrkPropertyInfo>, DispatchError> {227                    use pallet_proxy_rmrk_core::misc::CollectionType;228229                    let collection_id = CollectionId(collection_id);230                    if RmrkCore::ensure_collection_type(collection_id, CollectionType::Regular).is_err() {231                        return Ok(Vec::new());232                    }233234                    let properties = RmrkCore::filter_user_properties(235                        collection_id,236                        /* token_id = */ None,237                        filter_keys,238                        |key, value| RmrkPropertyInfo {239                            key,240                            value241                        }242                    )?;243244                    Ok(properties)245                }246247                fn nft_properties(collection_id: RmrkCollectionId, nft_id: RmrkNftId, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Result<Vec<RmrkPropertyInfo>, DispatchError> {248                    use pallet_proxy_rmrk_core::misc::NftType;249250                    let collection_id = CollectionId(collection_id);251                    let token_id = TokenId(nft_id);252253                    if RmrkCore::ensure_nft_type(collection_id, token_id, NftType::Regular).is_err() {254                        return Ok(Vec::new());255                    }256257		            let properties = RmrkCore::filter_user_properties(258                        collection_id,259                        Some(token_id),260                        filter_keys,261                        |key, value| RmrkPropertyInfo {262                            key,263                            value264                        }265                    )?;266267                    Ok(properties)268                }269270                fn nft_resources(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Result<Vec<RmrkResourceInfo>, DispatchError> {271                    use frame_support::BoundedVec;272                    use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, NftType, RmrkDecode}};273274                    let collection_id = CollectionId(collection_id);275                    if !RmrkCore::collection_exists(collection_id) { return Ok(Vec::new()); } // todo make sure the collection type doesn't matter276277                    let nft_id = TokenId(nft_id);278                    if RmrkCore::ensure_nft_type(collection_id, nft_id, NftType::Resource).is_err() { return Ok(Vec::new()); }279280                    let resource_collection_id: CollectionId = RmrkCore::get_nft_property(collection_id, nft_id, RmrkProperty::ResourceCollection)281                        .unwrap()282                        .decode_or_default();283                    if RmrkCore::ensure_collection_type(collection_id, CollectionType::Resource).is_err() { return Ok(Vec::new()); }284285                    let resources = pallet_nonfungible::TokenProperties::<Runtime>::iter_prefix((resource_collection_id,))286                        .filter_map(|(resource_id, properties)| Some(RmrkResourceInfo {287                            id: BoundedVec::default(), // todo ResourceId property288                            pending: RmrkCore::get_nft_property(resource_collection_id, resource_id, RmrkProperty::PendingResourceAccept).unwrap().decode_or_default(),289                            pending_removal: RmrkCore::get_nft_property(resource_collection_id, resource_id, RmrkProperty::PendingResourceRemoval).unwrap().decode_or_default(),290                            resource: RmrkCore::get_nft_property(resource_collection_id, resource_id, RmrkProperty::ResourceType).unwrap().decode_or_default(),/* {291                                RmrkResourceTypes::Basic(resource) => RmrkResourceTypes::Basic(),/*(RmrkBasicResource {292                                    src: RmrkCore::get_nft_property_inner(properties, RmrkProperty::Src).unwrap().decode_or_default(),293                                    metadata: RmrkCore::get_nft_property_inner(properties, RmrkProperty::Metadata).unwrap().decode_or_default(),294                                    license: RmrkCore::get_nft_property_inner(properties, RmrkProperty::License).unwrap().decode_or_default(),295                                    thumb: RmrkCore::get_nft_property_inner(properties, RmrkProperty::Thumb).unwrap().decode_or_default(),296                                },*///BasicResource<BoundedString>)297                                _ => todo!(), //RmrkResourceTypes::Composable(ComposableResource<BoundedString, BoundedParts>),298                                //RmrkResourceTypes::Slot(SlotResource<BoundedString>),299                            },*/300                        }))301                        .collect();302303                    Ok(resources)304                }305306                fn nft_resource_priorities(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Result<Vec<RmrkResourceId>, DispatchError> {307                    use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, NftType, RmrkDecode}};308309                    let collection_id = CollectionId(collection_id);310                    if !RmrkCore::collection_exists(collection_id) { return Ok(Vec::new()); } // todo ensure the collection type doesn't matter311312                    let nft_id = TokenId(nft_id);313                    if RmrkCore::ensure_nft_type(collection_id, nft_id, NftType::Resource).is_err() { return Ok(Vec::new()); }314315                    /*let resource_collection_id: CollectionId = RmrkCore::get_nft_property(collection_id, nft_id, RmrkProperty::ResourceCollection)316                        .unwrap()317                        .decode_or_default();318                    if RmrkCore::ensure_collection_type(collection_id, CollectionType::Resource).is_err() { return Ok(Vec::new()); }319320                    let resources = pallet_nonfungible::TokenProperties::<Runtime>::iter_prefix((resource_collection_id,))321                        .filter_map(|(resource_id, properties)| Some((322                            resource_id, // ResourceId property323                            RmrkCore::get_nft_property(resource_collection_id, resource_id, RmrkProperty::Priority).unwrap().decode_or_default(),324                        )))325                        .collect()326                        .sort_by_key(|(_, index)| *index)327                        .into_iter().map(|(resource_id, _)| resource_id)*/328                    let priorities = RmrkCore::get_nft_property(collection_id, nft_id, RmrkProperty::ResourcePriorities)?.decode_or_default();329330                    Ok(priorities)331                }332333                fn base(base_id: RmrkBaseId) -> Result<Option<RmrkBaseInfo<AccountId>>, DispatchError> {334                    use pallet_proxy_rmrk_core::{335                        RmrkProperty, misc::{CollectionType, RmrkDecode},336                    };337338                    let collection_id = CollectionId(base_id);339                    let collection = match RmrkCore::get_typed_nft_collection(collection_id, CollectionType::Base) {340                        Ok(c) => c,341                        Err(_) => return Ok(None),342                    };343344                    Ok(Some(RmrkBaseInfo {345                        issuer: collection.owner.clone(),346                        base_type: RmrkCore::get_collection_property(collection_id, RmrkProperty::BaseType)?.decode_or_default(),347                        symbol: collection.token_prefix.decode_or_default(),348                    }))349                }350351                fn base_parts(base_id: RmrkBaseId) -> Result<Vec<RmrkPartType>, DispatchError> {352                    use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, NftType, RmrkDecode}};353354                    let collection_id = CollectionId(base_id);355                    if RmrkCore::ensure_collection_type(collection_id, CollectionType::Base).is_err() { return Ok(Vec::new()); }356357                    let parts = dispatch_unique_runtime!(collection_id.collection_tokens())?358                        .into_iter()359                        .filter_map(|token_id| {360                            let nft_type = RmrkCore::get_nft_type(collection_id, token_id).ok()?;361362                            match nft_type {363                                NftType::FixedPart => Some(RmrkPartType::FixedPart(RmrkFixedPart {364                                    id: RmrkCore::get_nft_property(collection_id, token_id, RmrkProperty::ExternalPartId).ok()?.decode_or_default(),365                                    src: RmrkCore::get_nft_property(collection_id, token_id, RmrkProperty::Src).ok()?.decode_or_default(),366                                    z: RmrkCore::get_nft_property(collection_id, token_id, RmrkProperty::ZIndex).ok()?.decode_or_default(),367                                })),368                                NftType::SlotPart => Some(RmrkPartType::SlotPart(RmrkSlotPart {369                                    id: RmrkCore::get_nft_property(collection_id, token_id, RmrkProperty::ExternalPartId).ok()?.decode_or_default(),370                                    src: RmrkCore::get_nft_property(collection_id, token_id, RmrkProperty::Src).ok()?.decode_or_default(),371                                    z: RmrkCore::get_nft_property(collection_id, token_id, RmrkProperty::ZIndex).ok()?.decode_or_default(),372                                    equippable: RmrkCore::get_nft_property(collection_id, token_id, RmrkProperty::EquippableList).ok()?.decode_or_default(),373                                })),374                                _ => None375                            }376                        })377                        .collect();378379                    Ok(parts)380                }381382                fn theme_names(base_id: RmrkBaseId) -> Result<Vec<RmrkThemeName>, DispatchError> {383                    use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, RmrkDecode}};384385                    let collection_id = CollectionId(base_id);386                    if RmrkCore::ensure_collection_type(collection_id, CollectionType::Base).is_err() {387                        return Ok(Vec::new());388                    }389390                    let theme_names = dispatch_unique_runtime!(collection_id.collection_tokens())?391                        .iter()392                        .filter_map(|token_id| {393                            let nft_type = RmrkCore::get_nft_type(collection_id, *token_id).unwrap();394395                            match nft_type {396                                Theme => Some(397                                    RmrkCore::get_nft_property(collection_id, *token_id, RmrkProperty::ThemeName).unwrap().decode_or_default()398                                ),399                                _ => None400                            }401                        })402                        .collect();403404                    Ok(theme_names)405                }406407                fn theme(base_id: RmrkBaseId, theme_name: RmrkThemeName, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Result<Option<RmrkTheme>, DispatchError> {408                    use pallet_proxy_rmrk_core::{409                        RmrkProperty,410                        misc::{CollectionType, NftType, RmrkDecode}411                    };412413                    let collection_id = CollectionId(base_id);414                    if RmrkCore::ensure_collection_type(collection_id, CollectionType::Base).is_err() {415                        return Ok(None);416                    }417418                    let theme_info = dispatch_unique_runtime!(collection_id.collection_tokens())?419                        .into_iter()420                        .find_map(|token_id| {421                            RmrkCore::ensure_nft_type(collection_id, token_id, NftType::Theme).ok()?;422423                            let name: RmrkString = RmrkCore::get_nft_property(424                                collection_id, token_id, RmrkProperty::ThemeName425                            ).ok()?.decode_or_default();426427                            if name == theme_name {428                                Some((name, token_id))429                            } else {430                                None431                            }432                        });433434                    let (name, theme_id) = match theme_info {435                        Some((name, theme_id)) => (name, theme_id),436                        None => return Ok(None)437                    };438439                    let properties = RmrkCore::filter_user_properties(440                        collection_id,441                        Some(theme_id),442                        filter_keys,443                        |key, value| RmrkThemeProperty {444                            key,445                            value446                        }447                    )?;448449                    let inherit = RmrkCore::get_nft_property(450                        collection_id,451                        theme_id,452                        RmrkProperty::ThemeInherit453                    )?.decode_or_default();454455                    let theme = RmrkTheme {456                        name,457                        properties,458                        inherit,459                    };460461                    Ok(Some(theme))462                }463            }464465            impl sp_api::Core<Block> for Runtime {466                fn version() -> RuntimeVersion {467                    VERSION468                }469470                fn execute_block(block: Block) {471                    Executive::execute_block(block)472                }473474                fn initialize_block(header: &<Block as BlockT>::Header) {475                    Executive::initialize_block(header)476                }477            }478479            impl sp_api::Metadata<Block> for Runtime {480                fn metadata() -> OpaqueMetadata {481                    OpaqueMetadata::new(Runtime::metadata().into())482                }483            }484485            impl sp_block_builder::BlockBuilder<Block> for Runtime {486                fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {487                    Executive::apply_extrinsic(extrinsic)488                }489490                fn finalize_block() -> <Block as BlockT>::Header {491                    Executive::finalize_block()492                }493494                fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {495                    data.create_extrinsics()496                }497498                fn check_inherents(499                    block: Block,500                    data: sp_inherents::InherentData,501                ) -> sp_inherents::CheckInherentsResult {502                    data.check_extrinsics(&block)503                }504505                // fn random_seed() -> <Block as BlockT>::Hash {506                //     RandomnessCollectiveFlip::random_seed().0507                // }508            }509510            impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {511                fn validate_transaction(512                    source: TransactionSource,513                    tx: <Block as BlockT>::Extrinsic,514                    hash: <Block as BlockT>::Hash,515                ) -> TransactionValidity {516                    Executive::validate_transaction(source, tx, hash)517                }518            }519520            impl sp_offchain::OffchainWorkerApi<Block> for Runtime {521                fn offchain_worker(header: &<Block as BlockT>::Header) {522                    Executive::offchain_worker(header)523                }524            }525526            impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {527                fn chain_id() -> u64 {528                    <Runtime as pallet_evm::Config>::ChainId::get()529                }530531                fn account_basic(address: H160) -> EVMAccount {532                    EVM::account_basic(&address)533                }534535                fn gas_price() -> U256 {536                    <Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price()537                }538539                fn account_code_at(address: H160) -> Vec<u8> {540                    EVM::account_codes(address)541                }542543                fn author() -> H160 {544                    <pallet_evm::Pallet<Runtime>>::find_author()545                }546547                fn storage_at(address: H160, index: U256) -> H256 {548                    let mut tmp = [0u8; 32];549                    index.to_big_endian(&mut tmp);550                    EVM::account_storages(address, H256::from_slice(&tmp[..]))551                }552553                #[allow(clippy::redundant_closure)]554                fn call(555                    from: H160,556                    to: H160,557                    data: Vec<u8>,558                    value: U256,559                    gas_limit: U256,560                    max_fee_per_gas: Option<U256>,561                    max_priority_fee_per_gas: Option<U256>,562                    nonce: Option<U256>,563                    estimate: bool,564                    access_list: Option<Vec<(H160, Vec<H256>)>>,565                ) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {566                    let config = if estimate {567                        let mut config = <Runtime as pallet_evm::Config>::config().clone();568                        config.estimate = true;569                        Some(config)570                    } else {571                        None572                    };573574                    let is_transactional = false;575                    <Runtime as pallet_evm::Config>::Runner::call(576                        CrossAccountId::from_eth(from),577                        to,578                        data,579                        value,580                        gas_limit.low_u64(),581                        max_fee_per_gas,582                        max_priority_fee_per_gas,583                        nonce,584                        access_list.unwrap_or_default(),585                        is_transactional,586                        config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),587                    ).map_err(|err| err.into())588                }589590                #[allow(clippy::redundant_closure)]591                fn create(592                    from: H160,593                    data: Vec<u8>,594                    value: U256,595                    gas_limit: U256,596                    max_fee_per_gas: Option<U256>,597                    max_priority_fee_per_gas: Option<U256>,598                    nonce: Option<U256>,599                    estimate: bool,600                    access_list: Option<Vec<(H160, Vec<H256>)>>,601                ) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {602                    let config = if estimate {603                        let mut config = <Runtime as pallet_evm::Config>::config().clone();604                        config.estimate = true;605                        Some(config)606                    } else {607                        None608                    };609610                    let is_transactional = false;611                    <Runtime as pallet_evm::Config>::Runner::create(612                        CrossAccountId::from_eth(from),613                        data,614                        value,615                        gas_limit.low_u64(),616                        max_fee_per_gas,617                        max_priority_fee_per_gas,618                        nonce,619                        access_list.unwrap_or_default(),620                        is_transactional,621                        config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),622                    ).map_err(|err| err.into())623                }624625                fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {626                    Ethereum::current_transaction_statuses()627                }628629                fn current_block() -> Option<pallet_ethereum::Block> {630                    Ethereum::current_block()631                }632633                fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {634                    Ethereum::current_receipts()635                }636637                fn current_all() -> (638                    Option<pallet_ethereum::Block>,639                    Option<Vec<pallet_ethereum::Receipt>>,640                    Option<Vec<TransactionStatus>>641                ) {642                    (643                        Ethereum::current_block(),644                        Ethereum::current_receipts(),645                        Ethereum::current_transaction_statuses()646                    )647                }648649                fn extrinsic_filter(xts: Vec<<Block as sp_api::BlockT>::Extrinsic>) -> Vec<pallet_ethereum::Transaction> {650                    xts.into_iter().filter_map(|xt| match xt.0.function {651                        Call::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction),652                        _ => None653                    }).collect()654                }655656                fn elasticity() -> Option<Permill> {657                    None658                }659            }660661            impl fp_rpc::ConvertTransactionRuntimeApi<Block> for Runtime {662                fn convert_transaction(transaction: pallet_ethereum::Transaction) -> <Block as BlockT>::Extrinsic  {663                    UncheckedExtrinsic::new_unsigned(664                        pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),665                    )666                }667            }668669            impl sp_session::SessionKeys<Block> for Runtime {670                fn decode_session_keys(671                    encoded: Vec<u8>,672                ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {673                    SessionKeys::decode_into_raw_public_keys(&encoded)674                }675676                fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {677                    SessionKeys::generate(seed)678                }679            }680681            impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {682                fn slot_duration() -> sp_consensus_aura::SlotDuration {683                    sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())684                }685686                fn authorities() -> Vec<AuraId> {687                    Aura::authorities().to_vec()688                }689            }690691            impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {692                fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {693                    ParachainSystem::collect_collation_info(header)694                }695            }696697            impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {698                fn account_nonce(account: AccountId) -> Index {699                    System::account_nonce(account)700                }701            }702703            impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {704                fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {705                    TransactionPayment::query_info(uxt, len)706                }707                fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {708                    TransactionPayment::query_fee_details(uxt, len)709                }710            }711712            /*713            impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber, Hash>714                for Runtime715            {716                fn call(717                    origin: AccountId,718                    dest: AccountId,719                    value: Balance,720                    gas_limit: u64,721                    input_data: Vec<u8>,722                ) -> pallet_contracts_primitives::ContractExecResult {723                    Contracts::bare_call(origin, dest, value, gas_limit, input_data, false)724                }725726                fn instantiate(727                    origin: AccountId,728                    endowment: Balance,729                    gas_limit: u64,730                    code: pallet_contracts_primitives::Code<Hash>,731                    data: Vec<u8>,732                    salt: Vec<u8>,733                ) -> pallet_contracts_primitives::ContractInstantiateResult<AccountId, BlockNumber>734                {735                    Contracts::bare_instantiate(origin, endowment, gas_limit, code, data, salt, true, false)736                }737738                fn get_storage(739                    address: AccountId,740                    key: [u8; 32],741                ) -> pallet_contracts_primitives::GetStorageResult {742                    Contracts::get_storage(address, key)743                }744745                fn rent_projection(746                    address: AccountId,747                ) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {748                    Contracts::rent_projection(address)749                }750            }751            */752753            #[cfg(feature = "runtime-benchmarks")]754            impl frame_benchmarking::Benchmark<Block> for Runtime {755                fn benchmark_metadata(extra: bool) -> (756                    Vec<frame_benchmarking::BenchmarkList>,757                    Vec<frame_support::traits::StorageInfo>,758                ) {759                    use frame_benchmarking::{list_benchmark, Benchmarking, BenchmarkList};760                    use frame_support::traits::StorageInfoTrait;761762                    let mut list = Vec::<BenchmarkList>::new();763764                    list_benchmark!(list, extra, pallet_evm_migration, EvmMigration);765                    list_benchmark!(list, extra, pallet_common, Common);766                    list_benchmark!(list, extra, pallet_unique, Unique);767                    list_benchmark!(list, extra, pallet_structure, Structure);768                    list_benchmark!(list, extra, pallet_inflation, Inflation);769                    list_benchmark!(list, extra, pallet_fungible, Fungible);770                    list_benchmark!(list, extra, pallet_refungible, Refungible);771                    list_benchmark!(list, extra, pallet_nonfungible, Nonfungible);772                    // list_benchmark!(list, extra, pallet_evm_coder_substrate, EvmCoderSubstrate);773774                    let storage_info = AllPalletsReversedWithSystemFirst::storage_info();775776                    return (list, storage_info)777                }778779                fn dispatch_benchmark(780                    config: frame_benchmarking::BenchmarkConfig781                ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {782                    use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};783784                    let allowlist: Vec<TrackedStorageKey> = vec![785                        // Total Issuance786                        hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),787788                        // Block Number789                        hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),790                        // Execution Phase791                        hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),792                        // Event Count793                        hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),794                        // System Events795                        hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),796797                        // Evm CurrentLogs798                        hex_literal::hex!("1da53b775b270400e7e61ed5cbc5a146547f210cec367e9af919603343b9cb56").to_vec().into(),799800                        // Transactional depth801                        hex_literal::hex!("3a7472616e73616374696f6e5f6c6576656c3a").to_vec().into(),802                    ];803804                    let mut batches = Vec::<BenchmarkBatch>::new();805                    let params = (&config, &allowlist);806807                    add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);808                    add_benchmark!(params, batches, pallet_common, Common);809                    add_benchmark!(params, batches, pallet_unique, Unique);810                    add_benchmark!(params, batches, pallet_structure, Structure);811                    add_benchmark!(params, batches, pallet_inflation, Inflation);812                    add_benchmark!(params, batches, pallet_fungible, Fungible);813                    add_benchmark!(params, batches, pallet_refungible, Refungible);814                    add_benchmark!(params, batches, pallet_nonfungible, Nonfungible);815                    // add_benchmark!(params, batches, pallet_evm_coder_substrate, EvmCoderSubstrate);816817                    if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }818                    Ok(batches)819                }820            }821822            #[cfg(feature = "try-runtime")]823            impl frame_try_runtime::TryRuntime<Block> for Runtime {824                fn on_runtime_upgrade() -> (Weight, Weight) {825                    log::info!("try-runtime::on_runtime_upgrade unique-chain.");826                    let weight = Executive::try_runtime_upgrade().unwrap();827                    (weight, RuntimeBlockWeights::get().max_block)828                }829830                fn execute_block_no_check(block: Block) -> Weight {831                    Executive::execute_block_no_check(block)832                }833            }834        }835    }836}
modifiedruntime/tests/src/tests.rsdiffbeforeafterboth
--- a/runtime/tests/src/tests.rs
+++ b/runtime/tests/src/tests.rs
@@ -2399,28 +2399,6 @@
 // #endregion
 
 #[test]
-fn set_const_on_chain_schema() {
-	new_test_ext().execute_with(|| {
-		let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
-
-		let origin1 = Origin::signed(1);
-		assert_ok!(Unique::set_const_on_chain_schema(
-			origin1,
-			collection_id,
-			b"test const on chain schema".to_vec().try_into().unwrap()
-		));
-
-		assert_eq!(
-			<pallet_common::CollectionData<Test>>::get((
-				collection_id,
-				CollectionField::ConstOnChainSchema
-			)),
-			b"test const on chain schema".to_vec()
-		);
-	});
-}
-
-#[test]
 fn collection_transfer_flag_works() {
 	new_test_ext().execute_with(|| {
 		let origin1 = Origin::signed(1);