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

difftreelog

refactor rmrk proxy, add add_theme rmrk proxy

Daniel Shiposha2022-05-25parent: #4186437.patch.diff
in: master

8 files changed

modifiedclient/rpc/src/lib.rsdiffbeforeafterboth
--- a/client/rpc/src/lib.rs
+++ b/client/rpc/src/lib.rs
@@ -30,7 +30,7 @@
 // RMRK
 use rmrk_rpc::RmrkApi as RmrkRuntimeApi;
 use up_data_structs::{
-	RmrkCollectionId, RmrkNftId, RmrkBaseId, RmrkNftChild, RmrkThemeName, RmrkPropertyKey,
+	RmrkCollectionId, RmrkNftId, RmrkBaseId, RmrkNftChild, RmrkThemeName,
 	RmrkResourceId,
 };
 
@@ -248,7 +248,7 @@
 		fn collection_properties(
 			&self,
 			collection_id: RmrkCollectionId,
-			filter_keys: Option<Vec<RmrkPropertyKey>>, //String
+			filter_keys: Option<Vec<String>>,
 			at: Option<BlockHash>,
 		) -> Result<Vec<PropertyInfo>>;
 
@@ -258,7 +258,7 @@
 			&self,
 			collection_id: RmrkCollectionId,
 			nft_id: RmrkNftId,
-			filter_keys: Option<Vec<RmrkPropertyKey>>,
+			filter_keys: Option<Vec<String>>,
 			at: Option<BlockHash>,
 		) -> Result<Vec<PropertyInfo>>;
 
@@ -299,8 +299,8 @@
 		fn theme(
 			&self,
 			base_id: RmrkBaseId,
-			theme_name: RmrkThemeName, // String
-			filter_keys: Option<Vec<RmrkPropertyKey>>,
+			theme_name: String,
+			filter_keys: Option<Vec<String>>,
 			at: Option<BlockHash>,
 		) -> Result<Option<Theme>>;
 	}
@@ -523,11 +523,22 @@
 	pass_method!(account_tokens(account_id: AccountId, collection_id: RmrkCollectionId) -> Vec<RmrkNftId>, rmrk_api);
 	pass_method!(nft_children(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Vec<RmrkNftChild>, rmrk_api);
 	pass_method!(
-		collection_properties(collection_id: RmrkCollectionId, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Vec<PropertyInfo>,
+		collection_properties(
+			collection_id: RmrkCollectionId,
+
+			#[map(|keys| string_keys_to_bytes_keys(keys))]
+			filter_keys: Option<Vec<String>>
+		) -> Vec<PropertyInfo>,
 		rmrk_api
 	);
 	pass_method!(
-		nft_properties(collection_id: RmrkCollectionId, nft_id: RmrkNftId, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Vec<PropertyInfo>,
+		nft_properties(
+			collection_id: RmrkCollectionId,
+			nft_id: RmrkNftId,
+
+			#[map(|keys| string_keys_to_bytes_keys(keys))]
+			filter_keys: Option<Vec<String>>
+		) -> Vec<PropertyInfo>,
 		rmrk_api
 	);
 	pass_method!(nft_resources(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Vec<ResourceInfo>, rmrk_api);
@@ -535,7 +546,16 @@
 	pass_method!(base(base_id: RmrkBaseId) -> Option<BaseInfo>, rmrk_api);
 	pass_method!(base_parts(base_id: RmrkBaseId) -> Vec<PartType>, rmrk_api);
 	pass_method!(theme_names(base_id: RmrkBaseId) -> Vec<RmrkThemeName>, rmrk_api);
-	pass_method!(theme(base_id: RmrkBaseId, theme_name: RmrkThemeName, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Option<Theme>, rmrk_api);
+	pass_method!(
+		theme(
+			base_id: RmrkBaseId,
+
+			#[map(|n| n.into_bytes())]
+			theme_name: String,
+
+			#[map(|keys| string_keys_to_bytes_keys(keys))]
+			filter_keys: Option<Vec<String>>
+		) -> Option<Theme>, rmrk_api);
 }
 
 fn string_keys_to_bytes_keys(keys: Option<Vec<String>>) -> Option<Vec<Vec<u8>>> {
modifiedpallets/common/src/lib.rsdiffbeforeafterboth
--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -795,11 +795,11 @@
 	}
 
 	pub fn set_scoped_collection_property(
-		collection: &CollectionHandle<T>,
+		collection_id: CollectionId,
 		scope: PropertyScope,
 		property: Property,
 	) -> DispatchResult {
-		CollectionProperties::<T>::try_mutate(collection.id, |properties| {
+		CollectionProperties::<T>::try_mutate(collection_id, |properties| {
 			properties.try_scoped_set(scope, property.key, property.value)
 		})
 		.map_err(<Error<T>>::from)?;
@@ -807,13 +807,12 @@
 		Ok(())
 	}
 
-	#[transactional]
 	pub fn set_scoped_collection_properties(
-		collection: &CollectionHandle<T>,
+		collection_id: CollectionId,
 		scope: PropertyScope,
 		properties: impl Iterator<Item = Property>,
 	) -> DispatchResult {
-		CollectionProperties::<T>::try_mutate(collection.id, |stored_properties| {
+		CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {
 			stored_properties.try_scoped_set_from_iter(scope, properties)
 		})
 		.map_err(<Error<T>>::from)?;
modifiedpallets/nonfungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -195,12 +195,12 @@
 	}
 
 	pub fn set_scoped_token_property(
-		collection: &CollectionHandle<T>,
+		collection_id: CollectionId,
 		token_id: TokenId,
 		scope: PropertyScope,
 		property: Property,
 	) -> DispatchResult {
-		TokenProperties::<T>::try_mutate((collection.id, token_id), |properties| {
+		TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {
 			properties.try_scoped_set(scope, property.key, property.value)
 		})
 		.map_err(<CommonError<T>>::from)?;
@@ -209,12 +209,12 @@
 	}
 
 	pub fn set_scoped_token_properties(
-		collection: &CollectionHandle<T>,
+		collection_id: CollectionId,
 		token_id: TokenId,
 		scope: PropertyScope,
 		properties: impl Iterator<Item=Property>,
 	) -> DispatchResult {
-		TokenProperties::<T>::try_mutate((collection.id, token_id), |stored_properties| {
+		TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {
 			stored_properties.try_scoped_set_from_iter(scope, properties)
 		})
 		.map_err(<CommonError<T>>::from)?;
@@ -222,8 +222,8 @@
 		Ok(())
 	}
 
-	pub fn current_token_id(collection: &CollectionHandle<T>) -> TokenId {
-		TokenId(<TokensMinted<T>>::get(collection.id))
+	pub fn current_token_id(collection_id: CollectionId) -> TokenId {
+		TokenId(<TokensMinted<T>>::get(collection_id))
 	}
 }
 
modifiedpallets/proxy-rmrk-core/src/lib.rsdiffbeforeafterboth
--- a/pallets/proxy-rmrk-core/src/lib.rs
+++ b/pallets/proxy-rmrk-core/src/lib.rs
@@ -33,6 +33,8 @@
 use misc::*;
 pub use property::*;
 
+use RmrkProperty::*;
+
 #[frame_support::pallet]
 pub mod pallet {
     use super::*;
@@ -135,15 +137,13 @@
             }
 
             let collection_id = collection_id_res?;
-
-            let collection = Self::get_nft_collection(collection_id)?.into_inner();
 
             <PalletCommon<T>>::set_scoped_collection_properties(
-                &collection,
+                collection_id,
                 PropertyScope::Rmrk,
                 [
-                    rmrk_property!(Config=T, Metadata: metadata)?,
-                    rmrk_property!(Config=T, CollectionType: CollectionType::Regular)?,
+                    Self::rmrk_property(Metadata, &metadata)?,
+                    Self::rmrk_property(CollectionType, &misc::CollectionType::Regular)?,
                 ].into_iter()
             )?;
 
@@ -168,7 +168,7 @@
 
             let unique_collection_id = collection_id.into();
 
-            let collection = Self::get_typed_nft_collection(unique_collection_id, CollectionType::Regular)?;
+            let collection = Self::get_typed_nft_collection(unique_collection_id, misc::CollectionType::Regular)?;
 
             ensure!(collection.total_supply() == 0, <Error<T>>::CollectionNotEmpty);
 
@@ -193,7 +193,7 @@
 
             Self::change_collection_owner(
                 collection_id.into(),
-                CollectionType::Regular,
+                misc::CollectionType::Regular,
                 sender.clone(),
                 new_issuer.clone()
             )?;
@@ -218,7 +218,7 @@
 
             let collection = Self::get_typed_nft_collection(
                 collection_id.into(),
-                CollectionType::Regular
+                misc::CollectionType::Regular
             )?;
 
             Self::check_collection_owner(&collection, &cross_sender)?;
@@ -253,20 +253,27 @@
                 amount
             });
 
+            let collection = Self::get_typed_nft_collection(
+                collection_id.into(),
+                misc::CollectionType::Regular,
+            )?;
+
             let nft_id = Self::create_nft(
                 &sender,
                 &cross_owner,
-                collection_id.into(),
-                CollectionType::Regular,
+                &collection,
                 NftType::Regular,
                 [
-                    rmrk_property!(Config=T, RoyaltyInfo: royalty_info)?,
-                    rmrk_property!(Config=T, Metadata: metadata)?,
-                    rmrk_property!(Config=T, Equipped: false)?,
-                    rmrk_property!(Config=T, ResourceCollection: None::<CollectionId>)?,
-                    rmrk_property!(Config=T, ResourcePriorities: <Vec<u8>>::new())?,
+                    Self::rmrk_property(RoyaltyInfo, &royalty_info)?,
+                    Self::rmrk_property(Metadata, &metadata)?,
+                    Self::rmrk_property(Equipped, &false)?,
+                    Self::rmrk_property(ResourceCollection, &None::<CollectionId>)?,
+                    Self::rmrk_property(ResourcePriorities, &<Vec<u8>>::new())?,
                 ].into_iter()
-            )?;
+            ).map_err(|err| match err {
+                DispatchError::Arithmetic(_) => <Error<T>>::NoAvailableNftId.into(),
+                err => Self::map_common_err_to_proxy(err)
+            })?;
 
             Self::deposit_event(Event::NftMinted {
                 owner,
@@ -290,7 +297,7 @@
             Self::destroy_nft(
                 cross_sender,
                 collection_id.into(),
-                CollectionType::Regular,
+                misc::CollectionType::Regular,
                 nft_id.into()
             )?;
 
@@ -302,19 +309,37 @@
 }
 
 impl<T: Config> Pallet<T> {
+    pub fn rmrk_property_key(rmrk_key: RmrkProperty) -> Result<PropertyKey, DispatchError> {
+        let key = rmrk_key.to_key::<T>()?;
+
+        let scoped_key = PropertyScope::Rmrk.apply(key)
+            .map_err(|_| <Error<T>>::RmrkPropertyKeyIsTooLong)?;
+
+        Ok(scoped_key)
+    }
+
+    pub fn rmrk_property<E: Encode>(rmrk_key: RmrkProperty, value: &E) -> Result<Property, DispatchError> {
+        let key = rmrk_key.to_key::<T>()?;
+
+        let value = value.encode()
+            .try_into()
+            .map_err(|_| <Error<T>>::RmrkPropertyValueIsTooLong)?;
+
+        let property = Property {
+            key,
+            value,
+        };
+
+        Ok(property)
+    }
+
     pub fn create_nft(
         sender: &T::CrossAccountId,
         owner: &T::CrossAccountId,
-        collection_id: CollectionId,
-        collection_type: CollectionType,
+        collection: &NonfungibleHandle<T>,
         nft_type: NftType,
         properties: impl Iterator<Item=Property>
     ) -> Result<TokenId, DispatchError> {
-        let collection = Self::get_typed_nft_collection(
-            collection_id,
-            collection_type
-        )?;
-
         let data = CreateNftExData {
             const_data: nft_type.encode()
                 .try_into()
@@ -326,16 +351,16 @@
         let budget = budget::Value::new(2);
 
         <PalletNft<T>>::create_item(
-            &collection,
+            collection,
             sender,
             data,
             &budget,
-        ).map_err(Self::map_common_err_to_proxy)?;
+        )?;
 
-        let nft_id = <PalletNft<T>>::current_token_id(&collection);
+        let nft_id = <PalletNft<T>>::current_token_id(collection.id);
 
         <PalletNft<T>>::set_scoped_token_properties(
-            &collection,
+            collection.id,
             nft_id,
             PropertyScope::Rmrk,
             properties
@@ -347,7 +372,7 @@
     fn destroy_nft(
         sender: T::CrossAccountId,
         collection_id: CollectionId,
-        collection_type: CollectionType,
+        collection_type: misc::CollectionType,
         token_id: TokenId
     ) -> DispatchResult {
         let collection = Self::get_typed_nft_collection(
@@ -363,7 +388,7 @@
 
     fn change_collection_owner(
         collection_id: CollectionId,
-        collection_type: CollectionType,
+        collection_type: misc::CollectionType,
         sender: T::AccountId,
         new_owner: T::AccountId,
     ) -> DispatchResult {
@@ -390,10 +415,12 @@
 
     pub fn get_nft_collection(collection_id: CollectionId) -> Result<NonfungibleHandle<T>, DispatchError> {
         let collection = <CollectionHandle<T>>::try_get(collection_id)
-            .map_err(|_| <Error<T>>::CollectionUnknown)?
-            .into_nft_collection()?;
+            .map_err(|_| <Error<T>>::CollectionUnknown)?;
 
-        Ok(collection)
+        match collection.mode {
+            CollectionMode::NFT => Ok(NonfungibleHandle::cast(collection)),
+            _ => Err(<Error<T>>::CollectionUnknown.into())
+        }
     }
 
     // should this even be here, might displace it to common/nonfungible -- but they did not need it, only rmrk does
@@ -407,23 +434,23 @@
 
     pub fn get_collection_property(collection_id: CollectionId, key: RmrkProperty) -> Result<PropertyValue, DispatchError> {
         let collection_property = <PalletCommon<T>>::collection_properties(collection_id)
-            .get(&rmrk_property!(Config=T, key)?)
+            .get(&Self::rmrk_property_key(key)?)
             .ok_or(<Error<T>>::CollectionUnknown)?
             .clone();
 
         Ok(collection_property)
     }
 
-    pub fn get_collection_type(collection_id: CollectionId) -> Result<CollectionType, DispatchError> {
-        let value = Self::get_collection_property(collection_id, RmrkProperty::CollectionType)?;
-        let collection_type: CollectionType = (&value)
-            .try_into()
-            .map_err(<Error<T>>::from)?;
+    pub fn get_collection_type(collection_id: CollectionId) -> Result<misc::CollectionType, DispatchError> {
+        let value = Self::get_collection_property(collection_id, CollectionType)?;
+
+        let mut value = value.as_slice();
 
-        Ok(collection_type)
+        misc::CollectionType::decode(&mut value)
+            .map_err(|_| <Error<T>>::CorruptedCollectionType.into())
     }
 
-    pub fn ensure_collection_type(collection_id: CollectionId, collection_type: CollectionType) -> DispatchResult {
+    pub fn ensure_collection_type(collection_id: CollectionId, collection_type: misc::CollectionType) -> DispatchResult {
         let actual_type = Self::get_collection_type(collection_id)?;
         ensure!(actual_type == collection_type, <CommonError<T>>::NoPermission);
 
@@ -432,7 +459,7 @@
 
     pub fn get_nft_property(collection_id: CollectionId, nft_id: TokenId, key: RmrkProperty) -> Result<PropertyValue, DispatchError> {
         let nft_property = <PalletNft<T>>::token_properties((collection_id, nft_id))
-            .get(&rmrk_property!(Config=T, key)?)
+            .get(&Self::rmrk_property_key(key)?)
             .ok_or(<Error<T>>::NoAvailableNftId)?
             .clone();
 
@@ -440,10 +467,12 @@
     }
 
     pub fn get_nft_type(collection_id: CollectionId, token_id: TokenId) -> Result<NftType, DispatchError> {
-        <TokenData<T>>::get((collection_id, token_id))
-            .unwrap()
-            .rmrk_nft_type()
-            .ok_or_else(|| <Error<T>>::NoAvailableNftId.into())
+        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 ensure_nft_type(collection_id: CollectionId, token_id: TokenId, nft_type: NftType) -> DispatchResult {
@@ -466,7 +495,7 @@
                     let value = Self::get_nft_property(
                         collection_id,
                         token_id,
-                        RmrkProperty::ThemeProperty(&key)
+                        ThemeProperty(&key)
                     ).ok()?.decode_or_default();
 
                     let property = RmrkThemeProperty {
@@ -491,7 +520,7 @@
         collection_id: CollectionId,
         token_id: TokenId
     ) -> Result<impl Iterator<Item=RmrkThemeProperty>, DispatchError> {
-        let key_prefix = rmrk_property!(Config=T, key: ThemeProperty(&RmrkString::default()))?;
+        let key_prefix = Self::rmrk_property_key(ThemeProperty(&RmrkString::default()))?;
 
         let properties = <PalletNft<T>>::token_properties((collection_id, token_id))
             .into_iter()
@@ -514,7 +543,7 @@
 
     pub fn get_typed_nft_collection(
         collection_id: CollectionId,
-        collection_type: CollectionType
+        collection_type: misc::CollectionType
     ) -> Result<NonfungibleHandle<T>, DispatchError> {
         Self::ensure_collection_type(collection_id, collection_type)?;
 
modifiedpallets/proxy-rmrk-core/src/misc.rsdiffbeforeafterboth
--- a/pallets/proxy-rmrk-core/src/misc.rs
+++ b/pallets/proxy-rmrk-core/src/misc.rs
@@ -1,23 +1,6 @@
 use super::*;
 use codec::{Encode, Decode};
-use pallet_nonfungible::{NonfungibleHandle, ItemData};
-
-macro_rules! impl_rmrk_value {
-    ($enum_name:path, decode_error: $error:ident) => {
-        impl TryFrom<&PropertyValue> for $enum_name {
-            type Error = MiscError;
-
-            fn try_from(value: &PropertyValue) -> Result<Self, Self::Error> {
-                let mut value = value.as_slice();
 
-                <$enum_name>::decode(&mut value)
-                    .map_err(|_| MiscError::$error)
-            }
-        }
-
-    };
-}
-
 #[macro_export]
 macro_rules! map_common_err_to_proxy {
     (match $err:ident { $($common_err:ident => $proxy_err:ident),+ }) => {
@@ -29,59 +12,8 @@
             $err
         }
     };
-}
-
-pub enum MiscError {
-    RmrkPropertyValueIsTooLong,
-    CorruptedCollectionType,
-}
-
-impl<T: Config> From<MiscError> for Error<T> {
-    fn from(error: MiscError) -> Self {
-        match error {
-            MiscError::RmrkPropertyValueIsTooLong => Self::RmrkPropertyValueIsTooLong,
-            MiscError::CorruptedCollectionType => Self::CorruptedCollectionType,
-        }
-    }
-}
-
-pub trait IntoNftCollection<T: Config> {
-    fn into_nft_collection(self) -> Result<NonfungibleHandle<T>, Error<T>>;
 }
 
-impl<T: Config> IntoNftCollection<T> for CollectionHandle<T> {
-    fn into_nft_collection(self) -> Result<NonfungibleHandle<T>, Error<T>> {
-        match self.mode {
-            CollectionMode::NFT => Ok(NonfungibleHandle::cast(self)),
-            _ => Err(<Error<T>>::CollectionUnknown)
-        }
-    }
-}
-
-pub trait IntoPropertyValue {
-    fn into_property_value(self) -> Result<PropertyValue, MiscError>;
-}
-
-impl<T: Encode> IntoPropertyValue for T {
-    fn into_property_value(self) -> Result<PropertyValue, MiscError> {
-        self.encode()
-            .try_into()
-            .map_err(|_| MiscError::RmrkPropertyValueIsTooLong)
-    }
-}
-
-pub trait RmrkNft {
-    fn rmrk_nft_type(&self) -> Option<NftType>;
-}
-
-impl<CrossAccountId> RmrkNft for ItemData<CrossAccountId> {
-    fn rmrk_nft_type(&self) -> Option<NftType> {
-        let mut value = self.const_data.as_slice();
-
-        NftType::decode(&mut value).ok()
-    }
-}
-
 pub trait RmrkDecode<T: Decode + Default, S> {
     fn decode_or_default(&self) -> T;
 }
@@ -121,5 +53,3 @@
     SlotPart,
     Theme
 }
-
-impl_rmrk_value!(CollectionType, decode_error: CorruptedCollectionType);
modifiedpallets/proxy-rmrk-core/src/property.rsdiffbeforeafterboth
--- a/pallets/proxy-rmrk-core/src/property.rs
+++ b/pallets/proxy-rmrk-core/src/property.rs
@@ -71,31 +71,3 @@
         }
     }
 }
-
-#[macro_export]
-macro_rules! rmrk_property {
-    (Config=$cfg:ty, key: $key:ident $(($key_ext:expr))?) => {
-        rmrk_property!(Config=$cfg, $crate::RmrkProperty::$key $(($key_ext))?)
-    };
-
-    (Config=$cfg:ty, $key:ident $(($key_ext:expr))?: $value:expr) => {{
-        let key = rmrk_property!(@$cfg, $crate::RmrkProperty::$key $(($key_ext))?)?;
-
-        let value = $value.into_property_value()
-            .map_err(<$crate::Error<$cfg>>::from)?;
-
-        Ok::<_, $crate::Error<$cfg>>(Property {
-            key,
-            value,
-        })
-    }};
-
-    (@$cfg:ty, $key_enum:expr) => {
-        $key_enum.to_key::<$cfg>()
-    };
-
-    (Config=$cfg:ty, $key_enum:expr) => {
-        PropertyScope::Rmrk.apply(rmrk_property!(@$cfg, $key_enum)?)
-            .map_err(|_| <$crate::Error<$cfg>>::RmrkPropertyKeyIsTooLong)
-    };
-}
modifiedpallets/proxy-rmrk-equip/src/lib.rsdiffbeforeafterboth
--- a/pallets/proxy-rmrk-equip/src/lib.rs
+++ b/pallets/proxy-rmrk-equip/src/lib.rs
@@ -20,9 +20,9 @@
 use frame_system::{pallet_prelude::*, ensure_signed};
 use sp_runtime::DispatchError;
 use up_data_structs::*;
-use pallet_common::{Pallet as PalletCommon, Error as CommonError, CollectionHandle};
-use pallet_rmrk_core::{Pallet as PalletCore, rmrk_property, misc::*};
-use pallet_nonfungible::{Pallet as PalletNft};
+use pallet_common::{Pallet as PalletCommon, Error as CommonError};
+use pallet_rmrk_core::{Pallet as PalletCore, misc::{self, *}, property::RmrkProperty::*};
+use pallet_nonfungible::{Pallet as PalletNft, NonfungibleHandle};
 use pallet_evm::account::CrossAccountId;
 
 pub use pallet::*;
@@ -48,6 +48,16 @@
         TokenId
     >;
 
+    #[pallet::storage]
+	#[pallet::getter(fn base_has_default_theme)]
+    pub type BaseHasDefaultTheme<T: Config> = StorageMap<
+        _,
+        Twox64Concat,
+        CollectionId,
+        bool,
+        ValueQuery
+    >;
+
     #[pallet::pallet]
 	#[pallet::generate_store(pub(super) trait Store)]
 	pub struct Pallet<T>(_);
@@ -63,7 +73,11 @@
 
     #[pallet::error]
 	pub enum Error<T> {
+        PermissionError,
         NoAvailableBaseId,
+        NoAvailablePartId,
+        BaseDoesntExist,
+        NeedsDefaultThemeFirst,
     }
 
     #[pallet::call]
@@ -95,17 +109,17 @@
 
             let collection_id = collection_id_res?;
 
-            let collection = <PalletCore<T>>::get_nft_collection(collection_id)?.into_inner();
-
             <PalletCommon<T>>::set_scoped_collection_properties(
-                &collection,
+                collection_id,
                 PropertyScope::Rmrk,
                 [
-                    rmrk_property!(Config=T, CollectionType: CollectionType::Base)?,
-                    rmrk_property!(Config=T, BaseType: base_type)?,
+                    <PalletCore<T>>::rmrk_property(CollectionType, &misc::CollectionType::Base)?,
+                    <PalletCore<T>>::rmrk_property(BaseType, &base_type)?,
                 ].into_iter()
             )?;
 
+            let collection = <PalletCore<T>>::get_nft_collection(collection_id)?;
+
             for part in parts {
                 let part_id = part.id();
                 let part_token_id = Self::create_part(
@@ -117,10 +131,10 @@
                 <InernalPartId<T>>::insert(collection_id, part_id, part_token_id);
 
                 <PalletNft<T>>::set_scoped_token_property(
-                    &collection,
+                    collection_id,
                     part_token_id,
                     PropertyScope::Rmrk,
-                    rmrk_property!(Config=T, ExternalPartId: part_id)?
+                    <PalletCore<T>>::rmrk_property(ExternalPartId, &part_id)?
                 )?;
             }
 
@@ -128,13 +142,64 @@
 
             Ok(())
         }
+
+        #[pallet::weight(10_000 + T::DbWeight::get().reads_writes(1,1))]
+        #[transactional]
+		pub fn theme_add(
+			origin: OriginFor<T>,
+			base_id: RmrkBaseId,
+			theme: RmrkTheme,
+		) -> DispatchResult {
+            let sender = ensure_signed(origin)?;
+
+            let sender = T::CrossAccountId::from_sub(sender);
+            let owner = &sender;
+
+            let collection_id: CollectionId = base_id.into();
+
+            let collection = <PalletCore<T>>::get_typed_nft_collection(
+                collection_id,
+                misc::CollectionType::Base
+            ).map_err(|_| <Error<T>>::BaseDoesntExist)?;
+
+            if theme.name.as_slice() == b"default" {
+                <BaseHasDefaultTheme<T>>::insert(collection_id, true);
+            } else if !Self::base_has_default_theme(collection_id) {
+                return Err(<Error<T>>::NeedsDefaultThemeFirst.into());
+            }
+
+            let token_id = <PalletCore<T>>::create_nft(
+                &sender,
+                owner,
+                &collection,
+                NftType::Theme,
+                [
+                    <PalletCore<T>>::rmrk_property(ThemeName, &theme.name)?,
+                    <PalletCore<T>>::rmrk_property(ThemeInherit, &theme.inherit)?
+                ].into_iter()
+            ).map_err(|_| <Error<T>>::PermissionError)?;
+
+            for property in theme.properties {
+                <PalletNft<T>>::set_scoped_token_property(
+                    collection_id,
+                    token_id,
+                    PropertyScope::Rmrk,
+                    <PalletCore<T>>::rmrk_property(
+                        ThemeProperty(&property.key),
+                        &property.value
+                    )?
+                )?;
+            }
+
+            Ok(())
+        }
     }
 }
 
 impl<T: Config> Pallet<T> {
     fn create_part(
         sender: &T::CrossAccountId,
-        collection: &CollectionHandle<T>,
+        collection: &NonfungibleHandle<T>,
         part: RmrkPartType
     ) -> Result<TokenId, DispatchError> {
         let owner = sender;
@@ -150,21 +215,23 @@
         let token_id = <PalletCore<T>>::create_nft(
             sender,
             owner,
-            collection.id,
-            CollectionType::Base,
+            collection,
             nft_type,
             [
-                rmrk_property!(Config=T, Src: src)?,
-                rmrk_property!(Config=T, ZIndex: z_index)?
+                <PalletCore<T>>::rmrk_property(Src, &src)?,
+                <PalletCore<T>>::rmrk_property(ZIndex, &z_index)?
             ].into_iter()
-        )?;
+        ).map_err(|err| match err {
+            DispatchError::Arithmetic(_) => <Error<T>>::NoAvailablePartId.into(),
+            err => err
+        })?;
 
         if let RmrkPartType::SlotPart(part) = part {
             <PalletNft<T>>::set_scoped_token_property(
-                collection,
+                collection.id,
                 token_id,
                 PropertyScope::Rmrk,
-                rmrk_property!(Config=T, EquippableList: part.equippable)?
+                <PalletCore<T>>::rmrk_property(EquippableList, &part.equippable)?
             )?;
         }
 
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 frame_support::BoundedVec;150                    use scale_info::prelude::string::String;151                    use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, RmrkRebind, RmrkDecode}};152153                    let collection_id = CollectionId(collection_id);154                    let collection = match RmrkCore::get_typed_nft_collection(collection_id, CollectionType::Regular) {155                        Ok(c) => c,156                        Err(_) => return Ok(None),157                    };158159                    let nfts_count = (dispatch_unique_runtime!(collection_id.total_supply()) as Result<u32, DispatchError>)?;160                    //<Runtime as up_rpc::UniqueApi>::total_supply(collection_id); // todo can't find UniqueApi with disabled default features161162                    Ok(Some(RmrkCollectionInfo {163                        issuer: collection.owner.clone(),164                        metadata: RmrkCore::get_collection_property(collection_id, RmrkProperty::Metadata)?.decode_or_default(),165                        max: collection.limits.token_limit,166                        symbol: collection.token_prefix.rebind(), // change167                        nfts_count168                    }))169                }170171                fn nft_by_id(collection_id: RmrkCollectionId, nft_by_id: RmrkNftId) -> Result<Option<RmrkInstanceInfo<AccountId>>, DispatchError> {172                    use frame_support::BoundedVec;173                    use up_data_structs::mapping::TokenAddressMapping;174                    use pallet_proxy_rmrk_core::{RmrkProperty, misc::RmrkDecode};175176                    let collection_id = CollectionId(collection_id);177                    let nft_id = TokenId(nft_by_id);178                    if !RmrkCore::nft_exists(collection_id, nft_id) { return Ok(None); }179180                    let owner = match (dispatch_unique_runtime!(collection_id.token_owner(nft_id)) as Result<Option<CrossAccountId>, DispatchError>)? {181                        Some(owner) => match <Runtime as pallet_common::Config>::CrossTokenAddressMapping::address_to_token(&owner) {182                            Some((col, tok)) => RmrkAccountIdOrCollectionNftTuple::CollectionAndNftTuple(col.0, tok.0),183                            None => RmrkAccountIdOrCollectionNftTuple::AccountId(owner.as_sub().clone())184                        },185                        None => return Ok(None)186                    };187188                    let allowance = pallet_nonfungible::Allowance::<Runtime>::get((collection_id, nft_id));189190                    Ok(Some(RmrkInstanceInfo {191                        owner: owner,192                        royalty: RmrkCore::get_nft_property(collection_id, nft_id, RmrkProperty::RoyaltyInfo)?.decode_or_default(),193                        metadata: RmrkCore::get_nft_property(collection_id, nft_id, RmrkProperty::Metadata)?.decode_or_default(),194                        equipped: RmrkCore::get_nft_property(collection_id, nft_id, RmrkProperty::Equipped)?.decode_or_default(),195                        pending: allowance.is_some(),196                    }))197                }198199                fn account_tokens(account_id: AccountId, collection_id: RmrkCollectionId) -> Result<Vec<RmrkNftId>, DispatchError> {200                    let cross_account_id = CrossAccountId::from_sub(account_id);201                    let collection_id = CollectionId(collection_id);202                    if !RmrkCore::collection_exists(collection_id) { return Ok(Vec::new()); }203204                    Ok(205                        (dispatch_unique_runtime!(collection_id.account_tokens(cross_account_id)) as Result<Vec<TokenId>, DispatchError>)?206                        //<Runtime as up_rpc::UniqueApi<Block, CrossAccountId, AccountId>>::account_tokens(collection_id, cross_account_id)?207                            .into_iter()208                            .map(|token| token.0)209                            .collect::<Vec<_>>()210                    )211                }212213                fn nft_children(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Result<Vec<RmrkNftChild>, DispatchError> {214                    use up_data_structs::mapping::TokenAddressMapping;215216                    let collection_id = CollectionId(collection_id);217                    let nft_id = TokenId(nft_id);218                    if !RmrkCore::nft_exists(collection_id, nft_id) { return Ok(Vec::new()); }219220                    let cross_account_id = CrossAccountId::from_eth(221                        EvmTokenAddressMapping::token_to_address(collection_id, nft_id)222                    );223224                    Ok(225                        pallet_nonfungible::Owned::<Runtime>::iter_prefix((collection_id, cross_account_id))226                            .map(|(child_id, _)| RmrkNftChild {227                                collection_id: collection_id.0, // todo make sure they're always from this collection // spoiler: they're not228                                nft_id: child_id.0,229                            })230                            .collect()231                    )232                }233234                fn collection_properties(collection_id: RmrkCollectionId, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Result<Vec<RmrkPropertyInfo>, DispatchError> {235                    use pallet_proxy_rmrk_core::misc::RmrkDecode;236237                    let collection_id = CollectionId(collection_id);238                    if !RmrkCore::collection_exists(collection_id) { return Ok(Vec::new()); }239240                    let properties = Common::collection_properties(collection_id);241242                    // todo repeated code243                    return Ok(match filter_keys {244                        Some(keys) => {245                            let keys = Common::bytes_keys_to_property_keys(keys)?;246                            let properties = keys247                                .into_iter()248                                .filter_map(|key| {249                                    properties.get(&key).map(|value| RmrkPropertyInfo {250                                        key: key.decode_or_default(),251                                        value: value.decode_or_default(),252                                    })253                                })254                                .collect();255256                            properties257                        }258                        None => {259                            properties260                                .into_iter()261                                .filter_map(|(key, value)| Some(RmrkPropertyInfo {262                                    key: key.decode_or_default(),263                                    value: value.decode_or_default(),264                                }))265                                .collect()266                        }267                    });268                }269270                fn nft_properties(collection_id: RmrkCollectionId, nft_id: RmrkNftId, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Result<Vec<RmrkPropertyInfo>, DispatchError> {271                    use frame_support::BoundedVec;272                    use pallet_proxy_rmrk_core::misc::RmrkDecode;273274                    let collection_id = CollectionId(collection_id);275                    let token_id = TokenId(nft_id);276                    if !RmrkCore::nft_exists(collection_id, token_id) { return Ok(Vec::new()); }277278		            let properties = Nonfungible::token_properties((collection_id, token_id));279                    // todo look into this usage of pallet_nonfungible280281                    // todo displace to a function? redundant code piece with collection props282                    return Ok(match filter_keys {283                        Some(keys) => {284                            let keys = Common::bytes_keys_to_property_keys(keys)?;285                            let properties = keys286                                .into_iter()287                                .filter_map(|key| {288                                    properties.get(&key).map(|value| RmrkPropertyInfo {289                                        key: key.decode_or_default(),290                                        value: value.decode_or_default(),291                                    })292                                })293                                .collect();294295                            properties296                        }297                        None => {298                            properties299                                .into_iter()300                                .filter_map(|(key, value)| Some(RmrkPropertyInfo {301                                    key: key.decode_or_default(),302                                    value: value.decode_or_default(),303                                }))304                                .collect()305                        }306                    });307                }308309                fn nft_resources(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Result<Vec<RmrkResourceInfo>, DispatchError> {310                    use frame_support::BoundedVec;311                    use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, NftType}};312313                    let collection_id = CollectionId(collection_id);314                    if RmrkCore::ensure_collection_type(collection_id, CollectionType::Resource).is_err() { return Ok(Vec::new()); }315316                    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                    Ok(Vec::new(/*[RmrkResourceInfo {320321                    }]*/))322                }323324                fn nft_resource_priorities(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Result<Vec<RmrkResourceId>, DispatchError> {325                    todo!()326                }327328                fn base(base_id: RmrkBaseId) -> Result<Option<RmrkBaseInfo<AccountId>>, DispatchError> {329                    use frame_support::BoundedVec;330                    use scale_info::prelude::string::String;331                    use pallet_proxy_rmrk_core::{332                        RmrkProperty, misc::{CollectionType, RmrkRebind, RmrkDecode},333                    };334335                    let collection_id = CollectionId(base_id);336                    let collection = match RmrkCore::get_typed_nft_collection(collection_id, CollectionType::Base) {337                        Ok(c) => c,338                        Err(_) => return Ok(None),339                    };340341                    Ok(Some(RmrkBaseInfo {342                        issuer: collection.owner.clone(),343                        base_type: RmrkCore::get_collection_property(collection_id, RmrkProperty::BaseType)?.decode_or_default(),344                        symbol: collection.token_prefix.rebind(),345                    }))346                }347348                fn base_parts(base_id: RmrkBaseId) -> Result<Vec<RmrkPartType>, DispatchError> {349                    use frame_support::BoundedVec;350                    use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, NftType, RmrkNft, RmrkDecode}};351352                    let collection_id = CollectionId(base_id);353                    if RmrkCore::ensure_collection_type(collection_id, CollectionType::Base).is_err() { return Ok(Vec::new()); }354355                    let parts = (dispatch_unique_runtime!(collection_id.collection_tokens()))?356                        .into_iter()357                        .filter_map(|token_id| {358                            let nft_type = RmrkCore::get_nft_type(collection_id, token_id).ok()?;359360                            match nft_type {361                                NftType::FixedPart => Some(RmrkPartType::FixedPart(RmrkFixedPart {362                                    id: RmrkCore::get_nft_property(collection_id, token_id, RmrkProperty::ExternalPartId).ok()?.decode_or_default(),363                                    src: RmrkCore::get_nft_property(collection_id, token_id, RmrkProperty::Src).ok()?.decode_or_default(),364                                    z: RmrkCore::get_nft_property(collection_id, token_id, RmrkProperty::ZIndex).ok()?.decode_or_default(),365                                })),366                                NftType::SlotPart => Some(RmrkPartType::SlotPart(RmrkSlotPart {367                                    id: RmrkCore::get_nft_property(collection_id, token_id, RmrkProperty::ExternalPartId).ok()?.decode_or_default(),368                                    src: RmrkCore::get_nft_property(collection_id, token_id, RmrkProperty::Src).ok()?.decode_or_default(),369                                    z: RmrkCore::get_nft_property(collection_id, token_id, RmrkProperty::ZIndex).ok()?.decode_or_default(),370                                    equippable: RmrkCore::get_nft_property(collection_id, token_id, RmrkProperty::EquippableList).ok()?.decode_or_default(),371                                })),372                                _ => None373                            }374                        })375                        .collect();376377                    Ok(parts)378                }379380                fn theme_names(base_id: RmrkBaseId) -> Result<Vec<RmrkThemeName>, DispatchError> {381                    use frame_support::BoundedVec;382                    use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, RmrkNft, RmrkDecode}};383384                    let collection_id = CollectionId(base_id);385                    if RmrkCore::ensure_collection_type(collection_id, CollectionType::Base).is_err() {386                        return Ok(Vec::new());387                    }388389                    let theme_names = (dispatch_unique_runtime!(collection_id.collection_tokens()))?390                        .iter()391                        .filter_map(|token_id| {392                            let nft_type = RmrkCore::get_nft_type(collection_id, *token_id).unwrap();393394                            match nft_type {395                                Theme => Some(396                                    RmrkCore::get_nft_property(collection_id, *token_id, RmrkProperty::ThemeName).unwrap().decode_or_default()397                                ),398                                _ => None399                            }400                        })401                        .collect();402403                    Ok(theme_names)404                }405406                fn theme(base_id: RmrkBaseId, theme_name: RmrkThemeName, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Result<Option<RmrkTheme>, DispatchError> {407                    use frame_support::BoundedVec;408                    use pallet_proxy_rmrk_core::{409                        RmrkProperty,410                        misc::{CollectionType, NftType, RmrkNft, 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_theme_properties(collection_id, theme_id, filter_keys)?;440441                    let inherit = RmrkCore::get_nft_property(442                        collection_id,443                        theme_id,444                        RmrkProperty::ThemeInherit445                    )?.decode_or_default();446447                    let theme = RmrkTheme {448                        name,449                        properties,450                        inherit,451                    };452453                    Ok(Some(theme))454                }455            }456457            impl sp_api::Core<Block> for Runtime {458                fn version() -> RuntimeVersion {459                    VERSION460                }461462                fn execute_block(block: Block) {463                    Executive::execute_block(block)464                }465466                fn initialize_block(header: &<Block as BlockT>::Header) {467                    Executive::initialize_block(header)468                }469            }470471            impl sp_api::Metadata<Block> for Runtime {472                fn metadata() -> OpaqueMetadata {473                    OpaqueMetadata::new(Runtime::metadata().into())474                }475            }476477            impl sp_block_builder::BlockBuilder<Block> for Runtime {478                fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {479                    Executive::apply_extrinsic(extrinsic)480                }481482                fn finalize_block() -> <Block as BlockT>::Header {483                    Executive::finalize_block()484                }485486                fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {487                    data.create_extrinsics()488                }489490                fn check_inherents(491                    block: Block,492                    data: sp_inherents::InherentData,493                ) -> sp_inherents::CheckInherentsResult {494                    data.check_extrinsics(&block)495                }496497                // fn random_seed() -> <Block as BlockT>::Hash {498                //     RandomnessCollectiveFlip::random_seed().0499                // }500            }501502            impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {503                fn validate_transaction(504                    source: TransactionSource,505                    tx: <Block as BlockT>::Extrinsic,506                    hash: <Block as BlockT>::Hash,507                ) -> TransactionValidity {508                    Executive::validate_transaction(source, tx, hash)509                }510            }511512            impl sp_offchain::OffchainWorkerApi<Block> for Runtime {513                fn offchain_worker(header: &<Block as BlockT>::Header) {514                    Executive::offchain_worker(header)515                }516            }517518            impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {519                fn chain_id() -> u64 {520                    <Runtime as pallet_evm::Config>::ChainId::get()521                }522523                fn account_basic(address: H160) -> EVMAccount {524                    EVM::account_basic(&address)525                }526527                fn gas_price() -> U256 {528                    <Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price()529                }530531                fn account_code_at(address: H160) -> Vec<u8> {532                    EVM::account_codes(address)533                }534535                fn author() -> H160 {536                    <pallet_evm::Pallet<Runtime>>::find_author()537                }538539                fn storage_at(address: H160, index: U256) -> H256 {540                    let mut tmp = [0u8; 32];541                    index.to_big_endian(&mut tmp);542                    EVM::account_storages(address, H256::from_slice(&tmp[..]))543                }544545                #[allow(clippy::redundant_closure)]546                fn call(547                    from: H160,548                    to: H160,549                    data: Vec<u8>,550                    value: U256,551                    gas_limit: U256,552                    max_fee_per_gas: Option<U256>,553                    max_priority_fee_per_gas: Option<U256>,554                    nonce: Option<U256>,555                    estimate: bool,556                    access_list: Option<Vec<(H160, Vec<H256>)>>,557                ) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {558                    let config = if estimate {559                        let mut config = <Runtime as pallet_evm::Config>::config().clone();560                        config.estimate = true;561                        Some(config)562                    } else {563                        None564                    };565566                    let is_transactional = false;567                    <Runtime as pallet_evm::Config>::Runner::call(568                        CrossAccountId::from_eth(from),569                        to,570                        data,571                        value,572                        gas_limit.low_u64(),573                        max_fee_per_gas,574                        max_priority_fee_per_gas,575                        nonce,576                        access_list.unwrap_or_default(),577                        is_transactional,578                        config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),579                    ).map_err(|err| err.into())580                }581582                #[allow(clippy::redundant_closure)]583                fn create(584                    from: H160,585                    data: Vec<u8>,586                    value: U256,587                    gas_limit: U256,588                    max_fee_per_gas: Option<U256>,589                    max_priority_fee_per_gas: Option<U256>,590                    nonce: Option<U256>,591                    estimate: bool,592                    access_list: Option<Vec<(H160, Vec<H256>)>>,593                ) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {594                    let config = if estimate {595                        let mut config = <Runtime as pallet_evm::Config>::config().clone();596                        config.estimate = true;597                        Some(config)598                    } else {599                        None600                    };601602                    let is_transactional = false;603                    <Runtime as pallet_evm::Config>::Runner::create(604                        CrossAccountId::from_eth(from),605                        data,606                        value,607                        gas_limit.low_u64(),608                        max_fee_per_gas,609                        max_priority_fee_per_gas,610                        nonce,611                        access_list.unwrap_or_default(),612                        is_transactional,613                        config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),614                    ).map_err(|err| err.into())615                }616617                fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {618                    Ethereum::current_transaction_statuses()619                }620621                fn current_block() -> Option<pallet_ethereum::Block> {622                    Ethereum::current_block()623                }624625                fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {626                    Ethereum::current_receipts()627                }628629                fn current_all() -> (630                    Option<pallet_ethereum::Block>,631                    Option<Vec<pallet_ethereum::Receipt>>,632                    Option<Vec<TransactionStatus>>633                ) {634                    (635                        Ethereum::current_block(),636                        Ethereum::current_receipts(),637                        Ethereum::current_transaction_statuses()638                    )639                }640641                fn extrinsic_filter(xts: Vec<<Block as sp_api::BlockT>::Extrinsic>) -> Vec<pallet_ethereum::Transaction> {642                    xts.into_iter().filter_map(|xt| match xt.0.function {643                        Call::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction),644                        _ => None645                    }).collect()646                }647648                fn elasticity() -> Option<Permill> {649                    None650                }651            }652653            impl fp_rpc::ConvertTransactionRuntimeApi<Block> for Runtime {654                fn convert_transaction(transaction: pallet_ethereum::Transaction) -> <Block as BlockT>::Extrinsic  {655                    UncheckedExtrinsic::new_unsigned(656                        pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),657                    )658                }659            }660661            impl sp_session::SessionKeys<Block> for Runtime {662                fn decode_session_keys(663                    encoded: Vec<u8>,664                ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {665                    SessionKeys::decode_into_raw_public_keys(&encoded)666                }667668                fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {669                    SessionKeys::generate(seed)670                }671            }672673            impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {674                fn slot_duration() -> sp_consensus_aura::SlotDuration {675                    sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())676                }677678                fn authorities() -> Vec<AuraId> {679                    Aura::authorities().to_vec()680                }681            }682683            impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {684                fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {685                    ParachainSystem::collect_collation_info(header)686                }687            }688689            impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {690                fn account_nonce(account: AccountId) -> Index {691                    System::account_nonce(account)692                }693            }694695            impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {696                fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {697                    TransactionPayment::query_info(uxt, len)698                }699                fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {700                    TransactionPayment::query_fee_details(uxt, len)701                }702            }703704            /*705            impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber, Hash>706                for Runtime707            {708                fn call(709                    origin: AccountId,710                    dest: AccountId,711                    value: Balance,712                    gas_limit: u64,713                    input_data: Vec<u8>,714                ) -> pallet_contracts_primitives::ContractExecResult {715                    Contracts::bare_call(origin, dest, value, gas_limit, input_data, false)716                }717718                fn instantiate(719                    origin: AccountId,720                    endowment: Balance,721                    gas_limit: u64,722                    code: pallet_contracts_primitives::Code<Hash>,723                    data: Vec<u8>,724                    salt: Vec<u8>,725                ) -> pallet_contracts_primitives::ContractInstantiateResult<AccountId, BlockNumber>726                {727                    Contracts::bare_instantiate(origin, endowment, gas_limit, code, data, salt, true, false)728                }729730                fn get_storage(731                    address: AccountId,732                    key: [u8; 32],733                ) -> pallet_contracts_primitives::GetStorageResult {734                    Contracts::get_storage(address, key)735                }736737                fn rent_projection(738                    address: AccountId,739                ) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {740                    Contracts::rent_projection(address)741                }742            }743            */744745            #[cfg(feature = "runtime-benchmarks")]746            impl frame_benchmarking::Benchmark<Block> for Runtime {747                fn benchmark_metadata(extra: bool) -> (748                    Vec<frame_benchmarking::BenchmarkList>,749                    Vec<frame_support::traits::StorageInfo>,750                ) {751                    use frame_benchmarking::{list_benchmark, Benchmarking, BenchmarkList};752                    use frame_support::traits::StorageInfoTrait;753754                    let mut list = Vec::<BenchmarkList>::new();755756                    list_benchmark!(list, extra, pallet_evm_migration, EvmMigration);757                    list_benchmark!(list, extra, pallet_common, Common);758                    list_benchmark!(list, extra, pallet_unique, Unique);759                    list_benchmark!(list, extra, pallet_structure, Structure);760                    list_benchmark!(list, extra, pallet_inflation, Inflation);761                    list_benchmark!(list, extra, pallet_fungible, Fungible);762                    list_benchmark!(list, extra, pallet_refungible, Refungible);763                    list_benchmark!(list, extra, pallet_nonfungible, Nonfungible);764                    // list_benchmark!(list, extra, pallet_evm_coder_substrate, EvmCoderSubstrate);765766                    let storage_info = AllPalletsReversedWithSystemFirst::storage_info();767768                    return (list, storage_info)769                }770771                fn dispatch_benchmark(772                    config: frame_benchmarking::BenchmarkConfig773                ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {774                    use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};775776                    let allowlist: Vec<TrackedStorageKey> = vec![777                        // Total Issuance778                        hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),779780                        // Block Number781                        hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),782                        // Execution Phase783                        hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),784                        // Event Count785                        hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),786                        // System Events787                        hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),788789                        // Evm CurrentLogs790                        hex_literal::hex!("1da53b775b270400e7e61ed5cbc5a146547f210cec367e9af919603343b9cb56").to_vec().into(),791792                        // Transactional depth793                        hex_literal::hex!("3a7472616e73616374696f6e5f6c6576656c3a").to_vec().into(),794                    ];795796                    let mut batches = Vec::<BenchmarkBatch>::new();797                    let params = (&config, &allowlist);798799                    add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);800                    add_benchmark!(params, batches, pallet_common, Common);801                    add_benchmark!(params, batches, pallet_unique, Unique);802                    add_benchmark!(params, batches, pallet_structure, Structure);803                    add_benchmark!(params, batches, pallet_inflation, Inflation);804                    add_benchmark!(params, batches, pallet_fungible, Fungible);805                    add_benchmark!(params, batches, pallet_refungible, Refungible);806                    add_benchmark!(params, batches, pallet_nonfungible, Nonfungible);807                    // add_benchmark!(params, batches, pallet_evm_coder_substrate, EvmCoderSubstrate);808809                    if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }810                    Ok(batches)811                }812            }813814            #[cfg(feature = "try-runtime")]815            impl frame_try_runtime::TryRuntime<Block> for Runtime {816                fn on_runtime_upgrade() -> (Weight, Weight) {817                    log::info!("try-runtime::on_runtime_upgrade unique-chain.");818                    let weight = Executive::try_runtime_upgrade().unwrap();819                    (weight, RuntimeBlockWeights::get().max_block)820                }821822                fn execute_block_no_check(block: Block) -> Weight {823                    Executive::execute_block_no_check(block)824                }825            }826        }827    }828}
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                }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 frame_support::BoundedVec;150                    use scale_info::prelude::string::String;151                    use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, RmrkRebind, RmrkDecode}};152153                    let collection_id = CollectionId(collection_id);154                    let collection = match RmrkCore::get_typed_nft_collection(collection_id, CollectionType::Regular) {155                        Ok(c) => c,156                        Err(_) => return Ok(None),157                    };158159                    let nfts_count = (dispatch_unique_runtime!(collection_id.total_supply()) as Result<u32, DispatchError>)?;160                    //<Runtime as up_rpc::UniqueApi>::total_supply(collection_id); // todo can't find UniqueApi with disabled default features161162                    Ok(Some(RmrkCollectionInfo {163                        issuer: collection.owner.clone(),164                        metadata: RmrkCore::get_collection_property(collection_id, RmrkProperty::Metadata)?.decode_or_default(),165                        max: collection.limits.token_limit,166                        symbol: collection.token_prefix.rebind(), // change167                        nfts_count168                    }))169                }170171                fn nft_by_id(collection_id: RmrkCollectionId, nft_by_id: RmrkNftId) -> Result<Option<RmrkInstanceInfo<AccountId>>, DispatchError> {172                    use frame_support::BoundedVec;173                    use up_data_structs::mapping::TokenAddressMapping;174                    use pallet_proxy_rmrk_core::{RmrkProperty, misc::RmrkDecode};175176                    let collection_id = CollectionId(collection_id);177                    let nft_id = TokenId(nft_by_id);178                    if !RmrkCore::nft_exists(collection_id, nft_id) { return Ok(None); }179180                    let owner = match (dispatch_unique_runtime!(collection_id.token_owner(nft_id)) as Result<Option<CrossAccountId>, DispatchError>)? {181                        Some(owner) => match <Runtime as pallet_common::Config>::CrossTokenAddressMapping::address_to_token(&owner) {182                            Some((col, tok)) => RmrkAccountIdOrCollectionNftTuple::CollectionAndNftTuple(col.0, tok.0),183                            None => RmrkAccountIdOrCollectionNftTuple::AccountId(owner.as_sub().clone())184                        },185                        None => return Ok(None)186                    };187188                    let allowance = pallet_nonfungible::Allowance::<Runtime>::get((collection_id, nft_id));189190                    Ok(Some(RmrkInstanceInfo {191                        owner: owner,192                        royalty: RmrkCore::get_nft_property(collection_id, nft_id, RmrkProperty::RoyaltyInfo)?.decode_or_default(),193                        metadata: RmrkCore::get_nft_property(collection_id, nft_id, RmrkProperty::Metadata)?.decode_or_default(),194                        equipped: RmrkCore::get_nft_property(collection_id, nft_id, RmrkProperty::Equipped)?.decode_or_default(),195                        pending: allowance.is_some(),196                    }))197                }198199                fn account_tokens(account_id: AccountId, collection_id: RmrkCollectionId) -> Result<Vec<RmrkNftId>, DispatchError> {200                    let cross_account_id = CrossAccountId::from_sub(account_id);201                    let collection_id = CollectionId(collection_id);202                    if !RmrkCore::collection_exists(collection_id) { return Ok(Vec::new()); }203204                    Ok(205                        (dispatch_unique_runtime!(collection_id.account_tokens(cross_account_id)) as Result<Vec<TokenId>, DispatchError>)?206                        //<Runtime as up_rpc::UniqueApi<Block, CrossAccountId, AccountId>>::account_tokens(collection_id, cross_account_id)?207                            .into_iter()208                            .map(|token| token.0)209                            .collect::<Vec<_>>()210                    )211                }212213                fn nft_children(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Result<Vec<RmrkNftChild>, DispatchError> {214                    use up_data_structs::mapping::TokenAddressMapping;215216                    let collection_id = CollectionId(collection_id);217                    let nft_id = TokenId(nft_id);218                    if !RmrkCore::nft_exists(collection_id, nft_id) { return Ok(Vec::new()); }219220                    let cross_account_id = CrossAccountId::from_eth(221                        EvmTokenAddressMapping::token_to_address(collection_id, nft_id)222                    );223224                    Ok(225                        pallet_nonfungible::Owned::<Runtime>::iter_prefix((collection_id, cross_account_id))226                            .map(|(child_id, _)| RmrkNftChild {227                                collection_id: collection_id.0, // todo make sure they're always from this collection // spoiler: they're not228                                nft_id: child_id.0,229                            })230                            .collect()231                    )232                }233234                fn collection_properties(collection_id: RmrkCollectionId, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Result<Vec<RmrkPropertyInfo>, DispatchError> {235                    use pallet_proxy_rmrk_core::misc::RmrkDecode;236237                    let collection_id = CollectionId(collection_id);238                    if !RmrkCore::collection_exists(collection_id) { return Ok(Vec::new()); }239240                    let properties = Common::collection_properties(collection_id);241242                    // todo repeated code243                    return Ok(match filter_keys {244                        Some(keys) => {245                            let keys = Common::bytes_keys_to_property_keys(keys)?;246                            let properties = keys247                                .into_iter()248                                .filter_map(|key| {249                                    properties.get(&key).map(|value| RmrkPropertyInfo {250                                        key: key.decode_or_default(),251                                        value: value.decode_or_default(),252                                    })253                                })254                                .collect();255256                            properties257                        }258                        None => {259                            properties260                                .into_iter()261                                .filter_map(|(key, value)| Some(RmrkPropertyInfo {262                                    key: key.decode_or_default(),263                                    value: value.decode_or_default(),264                                }))265                                .collect()266                        }267                    });268                }269270                fn nft_properties(collection_id: RmrkCollectionId, nft_id: RmrkNftId, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Result<Vec<RmrkPropertyInfo>, DispatchError> {271                    use frame_support::BoundedVec;272                    use pallet_proxy_rmrk_core::misc::RmrkDecode;273274                    let collection_id = CollectionId(collection_id);275                    let token_id = TokenId(nft_id);276                    if !RmrkCore::nft_exists(collection_id, token_id) { return Ok(Vec::new()); }277278		            let properties = Nonfungible::token_properties((collection_id, token_id));279                    // todo look into this usage of pallet_nonfungible280281                    // todo displace to a function? redundant code piece with collection props282                    return Ok(match filter_keys {283                        Some(keys) => {284                            let keys = Common::bytes_keys_to_property_keys(keys)?;285                            let properties = keys286                                .into_iter()287                                .filter_map(|key| {288                                    properties.get(&key).map(|value| RmrkPropertyInfo {289                                        key: key.decode_or_default(),290                                        value: value.decode_or_default(),291                                    })292                                })293                                .collect();294295                            properties296                        }297                        None => {298                            properties299                                .into_iter()300                                .filter_map(|(key, value)| Some(RmrkPropertyInfo {301                                    key: key.decode_or_default(),302                                    value: value.decode_or_default(),303                                }))304                                .collect()305                        }306                    });307                }308309                fn nft_resources(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Result<Vec<RmrkResourceInfo>, DispatchError> {310                    use frame_support::BoundedVec;311                    use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, NftType}};312313                    let collection_id = CollectionId(collection_id);314                    if RmrkCore::ensure_collection_type(collection_id, CollectionType::Resource).is_err() { return Ok(Vec::new()); }315316                    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                    Ok(Vec::new(/*[RmrkResourceInfo {320321                    }]*/))322                }323324                fn nft_resource_priorities(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Result<Vec<RmrkResourceId>, DispatchError> {325                    todo!()326                }327328                fn base(base_id: RmrkBaseId) -> Result<Option<RmrkBaseInfo<AccountId>>, DispatchError> {329                    use frame_support::BoundedVec;330                    use scale_info::prelude::string::String;331                    use pallet_proxy_rmrk_core::{332                        RmrkProperty, misc::{CollectionType, RmrkRebind, RmrkDecode},333                    };334335                    let collection_id = CollectionId(base_id);336                    let collection = match RmrkCore::get_typed_nft_collection(collection_id, CollectionType::Base) {337                        Ok(c) => c,338                        Err(_) => return Ok(None),339                    };340341                    Ok(Some(RmrkBaseInfo {342                        issuer: collection.owner.clone(),343                        base_type: RmrkCore::get_collection_property(collection_id, RmrkProperty::BaseType)?.decode_or_default(),344                        symbol: collection.token_prefix.rebind(),345                    }))346                }347348                fn base_parts(base_id: RmrkBaseId) -> Result<Vec<RmrkPartType>, DispatchError> {349                    use frame_support::BoundedVec;350                    use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, NftType, RmrkDecode}};351352                    let collection_id = CollectionId(base_id);353                    if RmrkCore::ensure_collection_type(collection_id, CollectionType::Base).is_err() { return Ok(Vec::new()); }354355                    let parts = (dispatch_unique_runtime!(collection_id.collection_tokens()))?356                        .into_iter()357                        .filter_map(|token_id| {358                            let nft_type = RmrkCore::get_nft_type(collection_id, token_id).ok()?;359360                            match nft_type {361                                NftType::FixedPart => Some(RmrkPartType::FixedPart(RmrkFixedPart {362                                    id: RmrkCore::get_nft_property(collection_id, token_id, RmrkProperty::ExternalPartId).ok()?.decode_or_default(),363                                    src: RmrkCore::get_nft_property(collection_id, token_id, RmrkProperty::Src).ok()?.decode_or_default(),364                                    z: RmrkCore::get_nft_property(collection_id, token_id, RmrkProperty::ZIndex).ok()?.decode_or_default(),365                                })),366                                NftType::SlotPart => Some(RmrkPartType::SlotPart(RmrkSlotPart {367                                    id: RmrkCore::get_nft_property(collection_id, token_id, RmrkProperty::ExternalPartId).ok()?.decode_or_default(),368                                    src: RmrkCore::get_nft_property(collection_id, token_id, RmrkProperty::Src).ok()?.decode_or_default(),369                                    z: RmrkCore::get_nft_property(collection_id, token_id, RmrkProperty::ZIndex).ok()?.decode_or_default(),370                                    equippable: RmrkCore::get_nft_property(collection_id, token_id, RmrkProperty::EquippableList).ok()?.decode_or_default(),371                                })),372                                _ => None373                            }374                        })375                        .collect();376377                    Ok(parts)378                }379380                fn theme_names(base_id: RmrkBaseId) -> Result<Vec<RmrkThemeName>, DispatchError> {381                    use frame_support::BoundedVec;382                    use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, RmrkDecode}};383384                    let collection_id = CollectionId(base_id);385                    if RmrkCore::ensure_collection_type(collection_id, CollectionType::Base).is_err() {386                        return Ok(Vec::new());387                    }388389                    let theme_names = (dispatch_unique_runtime!(collection_id.collection_tokens()))?390                        .iter()391                        .filter_map(|token_id| {392                            let nft_type = RmrkCore::get_nft_type(collection_id, *token_id).unwrap();393394                            match nft_type {395                                Theme => Some(396                                    RmrkCore::get_nft_property(collection_id, *token_id, RmrkProperty::ThemeName).unwrap().decode_or_default()397                                ),398                                _ => None399                            }400                        })401                        .collect();402403                    Ok(theme_names)404                }405406                fn theme(base_id: RmrkBaseId, theme_name: RmrkThemeName, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Result<Option<RmrkTheme>, DispatchError> {407                    use frame_support::BoundedVec;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_theme_properties(collection_id, theme_id, filter_keys)?;440441                    let inherit = RmrkCore::get_nft_property(442                        collection_id,443                        theme_id,444                        RmrkProperty::ThemeInherit445                    )?.decode_or_default();446447                    let theme = RmrkTheme {448                        name,449                        properties,450                        inherit,451                    };452453                    Ok(Some(theme))454                }455            }456457            impl sp_api::Core<Block> for Runtime {458                fn version() -> RuntimeVersion {459                    VERSION460                }461462                fn execute_block(block: Block) {463                    Executive::execute_block(block)464                }465466                fn initialize_block(header: &<Block as BlockT>::Header) {467                    Executive::initialize_block(header)468                }469            }470471            impl sp_api::Metadata<Block> for Runtime {472                fn metadata() -> OpaqueMetadata {473                    OpaqueMetadata::new(Runtime::metadata().into())474                }475            }476477            impl sp_block_builder::BlockBuilder<Block> for Runtime {478                fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {479                    Executive::apply_extrinsic(extrinsic)480                }481482                fn finalize_block() -> <Block as BlockT>::Header {483                    Executive::finalize_block()484                }485486                fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {487                    data.create_extrinsics()488                }489490                fn check_inherents(491                    block: Block,492                    data: sp_inherents::InherentData,493                ) -> sp_inherents::CheckInherentsResult {494                    data.check_extrinsics(&block)495                }496497                // fn random_seed() -> <Block as BlockT>::Hash {498                //     RandomnessCollectiveFlip::random_seed().0499                // }500            }501502            impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {503                fn validate_transaction(504                    source: TransactionSource,505                    tx: <Block as BlockT>::Extrinsic,506                    hash: <Block as BlockT>::Hash,507                ) -> TransactionValidity {508                    Executive::validate_transaction(source, tx, hash)509                }510            }511512            impl sp_offchain::OffchainWorkerApi<Block> for Runtime {513                fn offchain_worker(header: &<Block as BlockT>::Header) {514                    Executive::offchain_worker(header)515                }516            }517518            impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {519                fn chain_id() -> u64 {520                    <Runtime as pallet_evm::Config>::ChainId::get()521                }522523                fn account_basic(address: H160) -> EVMAccount {524                    EVM::account_basic(&address)525                }526527                fn gas_price() -> U256 {528                    <Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price()529                }530531                fn account_code_at(address: H160) -> Vec<u8> {532                    EVM::account_codes(address)533                }534535                fn author() -> H160 {536                    <pallet_evm::Pallet<Runtime>>::find_author()537                }538539                fn storage_at(address: H160, index: U256) -> H256 {540                    let mut tmp = [0u8; 32];541                    index.to_big_endian(&mut tmp);542                    EVM::account_storages(address, H256::from_slice(&tmp[..]))543                }544545                #[allow(clippy::redundant_closure)]546                fn call(547                    from: H160,548                    to: H160,549                    data: Vec<u8>,550                    value: U256,551                    gas_limit: U256,552                    max_fee_per_gas: Option<U256>,553                    max_priority_fee_per_gas: Option<U256>,554                    nonce: Option<U256>,555                    estimate: bool,556                    access_list: Option<Vec<(H160, Vec<H256>)>>,557                ) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {558                    let config = if estimate {559                        let mut config = <Runtime as pallet_evm::Config>::config().clone();560                        config.estimate = true;561                        Some(config)562                    } else {563                        None564                    };565566                    let is_transactional = false;567                    <Runtime as pallet_evm::Config>::Runner::call(568                        CrossAccountId::from_eth(from),569                        to,570                        data,571                        value,572                        gas_limit.low_u64(),573                        max_fee_per_gas,574                        max_priority_fee_per_gas,575                        nonce,576                        access_list.unwrap_or_default(),577                        is_transactional,578                        config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),579                    ).map_err(|err| err.into())580                }581582                #[allow(clippy::redundant_closure)]583                fn create(584                    from: H160,585                    data: Vec<u8>,586                    value: U256,587                    gas_limit: U256,588                    max_fee_per_gas: Option<U256>,589                    max_priority_fee_per_gas: Option<U256>,590                    nonce: Option<U256>,591                    estimate: bool,592                    access_list: Option<Vec<(H160, Vec<H256>)>>,593                ) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {594                    let config = if estimate {595                        let mut config = <Runtime as pallet_evm::Config>::config().clone();596                        config.estimate = true;597                        Some(config)598                    } else {599                        None600                    };601602                    let is_transactional = false;603                    <Runtime as pallet_evm::Config>::Runner::create(604                        CrossAccountId::from_eth(from),605                        data,606                        value,607                        gas_limit.low_u64(),608                        max_fee_per_gas,609                        max_priority_fee_per_gas,610                        nonce,611                        access_list.unwrap_or_default(),612                        is_transactional,613                        config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),614                    ).map_err(|err| err.into())615                }616617                fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {618                    Ethereum::current_transaction_statuses()619                }620621                fn current_block() -> Option<pallet_ethereum::Block> {622                    Ethereum::current_block()623                }624625                fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {626                    Ethereum::current_receipts()627                }628629                fn current_all() -> (630                    Option<pallet_ethereum::Block>,631                    Option<Vec<pallet_ethereum::Receipt>>,632                    Option<Vec<TransactionStatus>>633                ) {634                    (635                        Ethereum::current_block(),636                        Ethereum::current_receipts(),637                        Ethereum::current_transaction_statuses()638                    )639                }640641                fn extrinsic_filter(xts: Vec<<Block as sp_api::BlockT>::Extrinsic>) -> Vec<pallet_ethereum::Transaction> {642                    xts.into_iter().filter_map(|xt| match xt.0.function {643                        Call::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction),644                        _ => None645                    }).collect()646                }647648                fn elasticity() -> Option<Permill> {649                    None650                }651            }652653            impl fp_rpc::ConvertTransactionRuntimeApi<Block> for Runtime {654                fn convert_transaction(transaction: pallet_ethereum::Transaction) -> <Block as BlockT>::Extrinsic  {655                    UncheckedExtrinsic::new_unsigned(656                        pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),657                    )658                }659            }660661            impl sp_session::SessionKeys<Block> for Runtime {662                fn decode_session_keys(663                    encoded: Vec<u8>,664                ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {665                    SessionKeys::decode_into_raw_public_keys(&encoded)666                }667668                fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {669                    SessionKeys::generate(seed)670                }671            }672673            impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {674                fn slot_duration() -> sp_consensus_aura::SlotDuration {675                    sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())676                }677678                fn authorities() -> Vec<AuraId> {679                    Aura::authorities().to_vec()680                }681            }682683            impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {684                fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {685                    ParachainSystem::collect_collation_info(header)686                }687            }688689            impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {690                fn account_nonce(account: AccountId) -> Index {691                    System::account_nonce(account)692                }693            }694695            impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {696                fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {697                    TransactionPayment::query_info(uxt, len)698                }699                fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {700                    TransactionPayment::query_fee_details(uxt, len)701                }702            }703704            /*705            impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber, Hash>706                for Runtime707            {708                fn call(709                    origin: AccountId,710                    dest: AccountId,711                    value: Balance,712                    gas_limit: u64,713                    input_data: Vec<u8>,714                ) -> pallet_contracts_primitives::ContractExecResult {715                    Contracts::bare_call(origin, dest, value, gas_limit, input_data, false)716                }717718                fn instantiate(719                    origin: AccountId,720                    endowment: Balance,721                    gas_limit: u64,722                    code: pallet_contracts_primitives::Code<Hash>,723                    data: Vec<u8>,724                    salt: Vec<u8>,725                ) -> pallet_contracts_primitives::ContractInstantiateResult<AccountId, BlockNumber>726                {727                    Contracts::bare_instantiate(origin, endowment, gas_limit, code, data, salt, true, false)728                }729730                fn get_storage(731                    address: AccountId,732                    key: [u8; 32],733                ) -> pallet_contracts_primitives::GetStorageResult {734                    Contracts::get_storage(address, key)735                }736737                fn rent_projection(738                    address: AccountId,739                ) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {740                    Contracts::rent_projection(address)741                }742            }743            */744745            #[cfg(feature = "runtime-benchmarks")]746            impl frame_benchmarking::Benchmark<Block> for Runtime {747                fn benchmark_metadata(extra: bool) -> (748                    Vec<frame_benchmarking::BenchmarkList>,749                    Vec<frame_support::traits::StorageInfo>,750                ) {751                    use frame_benchmarking::{list_benchmark, Benchmarking, BenchmarkList};752                    use frame_support::traits::StorageInfoTrait;753754                    let mut list = Vec::<BenchmarkList>::new();755756                    list_benchmark!(list, extra, pallet_evm_migration, EvmMigration);757                    list_benchmark!(list, extra, pallet_common, Common);758                    list_benchmark!(list, extra, pallet_unique, Unique);759                    list_benchmark!(list, extra, pallet_structure, Structure);760                    list_benchmark!(list, extra, pallet_inflation, Inflation);761                    list_benchmark!(list, extra, pallet_fungible, Fungible);762                    list_benchmark!(list, extra, pallet_refungible, Refungible);763                    list_benchmark!(list, extra, pallet_nonfungible, Nonfungible);764                    // list_benchmark!(list, extra, pallet_evm_coder_substrate, EvmCoderSubstrate);765766                    let storage_info = AllPalletsReversedWithSystemFirst::storage_info();767768                    return (list, storage_info)769                }770771                fn dispatch_benchmark(772                    config: frame_benchmarking::BenchmarkConfig773                ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {774                    use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};775776                    let allowlist: Vec<TrackedStorageKey> = vec![777                        // Total Issuance778                        hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),779780                        // Block Number781                        hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),782                        // Execution Phase783                        hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),784                        // Event Count785                        hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),786                        // System Events787                        hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),788789                        // Evm CurrentLogs790                        hex_literal::hex!("1da53b775b270400e7e61ed5cbc5a146547f210cec367e9af919603343b9cb56").to_vec().into(),791792                        // Transactional depth793                        hex_literal::hex!("3a7472616e73616374696f6e5f6c6576656c3a").to_vec().into(),794                    ];795796                    let mut batches = Vec::<BenchmarkBatch>::new();797                    let params = (&config, &allowlist);798799                    add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);800                    add_benchmark!(params, batches, pallet_common, Common);801                    add_benchmark!(params, batches, pallet_unique, Unique);802                    add_benchmark!(params, batches, pallet_structure, Structure);803                    add_benchmark!(params, batches, pallet_inflation, Inflation);804                    add_benchmark!(params, batches, pallet_fungible, Fungible);805                    add_benchmark!(params, batches, pallet_refungible, Refungible);806                    add_benchmark!(params, batches, pallet_nonfungible, Nonfungible);807                    // add_benchmark!(params, batches, pallet_evm_coder_substrate, EvmCoderSubstrate);808809                    if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }810                    Ok(batches)811                }812            }813814            #[cfg(feature = "try-runtime")]815            impl frame_try_runtime::TryRuntime<Block> for Runtime {816                fn on_runtime_upgrade() -> (Weight, Weight) {817                    log::info!("try-runtime::on_runtime_upgrade unique-chain.");818                    let weight = Executive::try_runtime_upgrade().unwrap();819                    (weight, RuntimeBlockWeights::get().max_block)820                }821822                fn execute_block_no_check(block: Block) -> Weight {823                    Executive::execute_block_no_check(block)824                }825            }826        }827    }828}