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

difftreelog

refactor(rmrk-proxy) better decoding

Fahrrader2022-06-02parent: #71b4dea.patch.diff
in: master

3 files changed

modifiedpallets/proxy-rmrk-core/src/lib.rsdiffbeforeafterboth
--- a/pallets/proxy-rmrk-core/src/lib.rs
+++ b/pallets/proxy-rmrk-core/src/lib.rs
@@ -111,7 +111,7 @@
 		CorruptedCollectionType,
 		NftTypeEncodeError,
 		RmrkPropertyKeyIsTooLong,
-		RmrkPropertyValueIsTooLong, // todo utilize that in RPCs
+		RmrkPropertyValueIsTooLong,
 
 		/* RMRK compatible events */
 		CollectionNotEmpty,
@@ -518,7 +518,7 @@
 		Ok(scoped_key)
 	}
 
-	pub fn rmrk_property<E: Encode>(
+	pub fn rmrk_property<E: Encode>( // todo think about renaming this
 		rmrk_key: RmrkProperty,
 		value: &E,
 	) -> Result<Property, DispatchError> {
@@ -533,6 +533,21 @@
 
 		Ok(property)
 	}
+	
+	pub fn decode_property<D: Decode>(
+		vec: PropertyValue,
+	) -> Result<D, DispatchError> {
+		vec.decode().map_err(|_| <Error<T>>::RmrkPropertyValueIsTooLong.into())
+	}
+
+	pub fn rebind<L, S>(
+		vec: &BoundedVec<u8, L>,
+	) -> Result<BoundedVec<u8, S>, DispatchError> 
+	where 
+		BoundedVec<u8, S>: TryFrom<Vec<u8>> 
+	{
+		vec.rebind().map_err(|_| <Error<T>>::RmrkPropertyValueIsTooLong.into())
+	}
 
 	fn init_collection(
 		sender: T::CrossAccountId,
@@ -619,8 +634,7 @@
 		)?;
 
 		let resource_collection_id: CollectionId =
-			Self::get_nft_property(collection_id, token_id, ResourceCollection)?
-				.decode_or_default();
+			Self::get_nft_property_decoded(collection_id, token_id, ResourceCollection)?;
 		let resource_collection =
 			Self::get_typed_nft_collection(resource_collection_id, misc::CollectionType::Resource)?;
 
@@ -709,14 +723,19 @@
 		Ok(collection_property)
 	}
 
+	pub fn get_collection_property_decoded<V: Decode>(
+		collection_id: CollectionId,
+		key: RmrkProperty,
+	) -> Result<V, DispatchError> {
+		Self::decode_property(
+			Self::get_collection_property(collection_id, key)?
+		)
+	}
+
 	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();
-
-		misc::CollectionType::decode(&mut value)
+		Self::get_collection_property_decoded(collection_id, CollectionType)
 			.map_err(|_| <Error<T>>::CorruptedCollectionType.into())
 	}
 
@@ -749,12 +768,22 @@
 	) -> Result<PropertyValue, DispatchError> {
 		let nft_property = <PalletNft<T>>::token_properties((collection_id, nft_id))
 			.get(&Self::rmrk_property_key(key)?)
-			.ok_or(<Error<T>>::NoAvailableNftId)? // todo replace with better error
+			.ok_or(<Error<T>>::NoAvailableNftId)? // todo replace with better error?
 			.clone();
 
 		Ok(nft_property)
 	}
 
+	pub fn get_nft_property_decoded<V: Decode>(
+		collection_id: CollectionId,
+		nft_id: TokenId,
+		key: RmrkProperty,
+	) -> Result<V, DispatchError> {
+		Self::decode_property(
+			Self::get_nft_property(collection_id, nft_id, key)?
+		)
+	}
+
 	pub fn nft_exists(collection_id: CollectionId, nft_id: TokenId) -> bool {
 		<TokenData<T>>::contains_key((collection_id, nft_id))
 	}
@@ -763,9 +792,8 @@
 		collection_id: CollectionId,
 		token_id: TokenId,
 	) -> Result<NftType, DispatchError> {
-		Ok(Self::get_nft_property(collection_id, token_id, TokenType)?.decode_or_default())
-		// todo throw error
-		// NftTypeEncodeError?
+		Self::get_nft_property_decoded(collection_id, token_id, TokenType)
+			.map_err(|_| <Error<T>>::NftTypeEncodeError.into())
 	}
 
 	pub fn ensure_nft_type(
@@ -814,18 +842,17 @@
 						let key: Key = key.try_into().ok()?;
 
 						let value = match token_id {
-							Some(token_id) => Self::get_nft_property(
+							Some(token_id) => Self::get_nft_property_decoded(
 								collection_id,
 								token_id,
 								UserProperty(key.as_ref()),
 							),
-							None => Self::get_collection_property(
+							None => Self::get_collection_property_decoded(
 								collection_id,
 								UserProperty(key.as_ref()),
 							),
 						}
-						.ok()?
-						.decode_or_default();
+						.ok()?;
 
 						Some(mapper(key, value))
 					})
@@ -862,7 +889,7 @@
 			let key = key.as_slice().strip_prefix(key_prefix.as_slice())?;
 
 			let key: Key = key.to_vec().try_into().ok()?;
-			let value: Value = value.decode_or_default();
+			let value: Value = value.decode().ok()?;
 
 			Some(mapper(key, value))
 		});
modifiedpallets/proxy-rmrk-core/src/misc.rsdiffbeforeafterboth
--- a/pallets/proxy-rmrk-core/src/misc.rs
+++ b/pallets/proxy-rmrk-core/src/misc.rs
@@ -1,6 +1,5 @@
 use super::*;
-use codec::{Encode, Decode};
-use derivative::Derivative;
+use codec::{Encode, Decode, Error};
 
 #[macro_export]
 macro_rules! map_common_err_to_proxy {
@@ -15,30 +14,30 @@
     };
 }
 
-pub trait RmrkDecode<T: Decode + Default, S> {
-	fn decode_or_default(&self) -> T;
+// Utilize the RmrkCore pallet for access to Runtime errors.
+pub trait RmrkDecode<T: Decode, S> {
+	fn decode(&self) -> Result<T, Error>;
 }
 
-// todo fail if unwrap doesn't work
-impl<T: Decode + Default, S> RmrkDecode<T, S> for BoundedVec<u8, S> {
-	fn decode_or_default(&self) -> T {
+impl<T: Decode, S> RmrkDecode<T, S> for BoundedVec<u8, S> {
+	fn decode(&self) -> Result<T, Error> {
 		let mut value = self.as_slice();
 
-		T::decode(&mut value).unwrap_or_default()
+		T::decode(&mut value)
 	}
 }
 
+// Utilize the RmrkCore pallet for access to Runtime errors.
 pub trait RmrkRebind<T, S> {
-	fn rebind(&self) -> BoundedVec<u8, S>;
+	fn rebind(&self) -> Result<BoundedVec<u8, S>, Error>;
 }
 
-// todo fail if unwrap doesn't work
 impl<T, S> RmrkRebind<T, S> for BoundedVec<u8, T>
 where
 	BoundedVec<u8, S>: TryFrom<Vec<u8>>,
 {
-	fn rebind(&self) -> BoundedVec<u8, S> {
-		BoundedVec::<u8, S>::try_from(self.clone().into_inner()).unwrap_or_default()
+	fn rebind(&self) -> Result<BoundedVec<u8, S>, Error> {
+		BoundedVec::<u8, S>::try_from(self.clone().into_inner()).map_err(|_| "BoundedVec exceeds its limit".into())
 	}
 }
 
@@ -49,11 +48,8 @@
 	Base,
 }
 
-// todo remove default?
-#[derive(Encode, Decode, PartialEq, Eq, Derivative)]
-#[derivative(Default(bound = ""))]
+#[derive(Encode, Decode, PartialEq, Eq)]
 pub enum NftType {
-	#[derivative(Default)]
 	Regular,
 	Resource,
 	FixedPart,
@@ -61,11 +57,8 @@
 	Theme,
 }
 
-// todo remove default?
-#[derive(Encode, Decode, PartialEq, Eq, Derivative)]
-#[derivative(Default(bound = ""))]
+#[derive(Encode, Decode, PartialEq, Eq)]
 pub enum ResourceType {
-	#[derivative(Default)]
 	Basic,
 	Composable,
 	Slot,
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(10);2930                    Ok(Some(<pallet_structure::Pallet<Runtime>>::find_topmost_owner(collection, token, &budget)?))31                }32                fn token_children(collection: CollectionId, token: TokenId) -> Result<Vec<TokenChild>, DispatchError> {33                    Ok(<pallet_nonfungible::Pallet<Runtime>>::token_children_ids(collection, token))34                }35                fn collection_properties(36                    collection: CollectionId,37                    keys: Option<Vec<Vec<u8>>>38                ) -> Result<Vec<Property>, DispatchError> {39                    let keys = keys.map(40                        |keys| Common::bytes_keys_to_property_keys(keys)41                    ).transpose()?;4243                    Common::filter_collection_properties(collection, keys)44                }4546                fn token_properties(47                    collection: CollectionId,48                    token_id: TokenId,49                    keys: Option<Vec<Vec<u8>>>50                ) -> Result<Vec<Property>, DispatchError> {51                    let keys = keys.map(52                        |keys| Common::bytes_keys_to_property_keys(keys)53                    ).transpose()?;5455                    dispatch_unique_runtime!(collection.token_properties(token_id, keys))56                }5758                fn property_permissions(59                    collection: CollectionId,60                    keys: Option<Vec<Vec<u8>>>61                ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {62                    let keys = keys.map(63                        |keys| Common::bytes_keys_to_property_keys(keys)64                    ).transpose()?;6566                    Common::filter_property_permissions(collection, keys)67                }6869                fn token_data(70                    collection: CollectionId,71                    token_id: TokenId,72                    keys: Option<Vec<Vec<u8>>>73                ) -> Result<TokenData<CrossAccountId>, DispatchError> {74                    let token_data = TokenData {75                        properties: Self::token_properties(collection, token_id, keys)?,76                        owner: Self::token_owner(collection, token_id)?77                    };7879                    Ok(token_data)80                }8182                fn total_supply(collection: CollectionId) -> Result<u32, DispatchError> {83                    dispatch_unique_runtime!(collection.total_supply())84                }85                fn account_balance(collection: CollectionId, account: CrossAccountId) -> Result<u32, DispatchError> {86                    dispatch_unique_runtime!(collection.account_balance(account))87                }88                fn balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<u128, DispatchError> {89                    dispatch_unique_runtime!(collection.balance(account, token))90                }91                fn allowance(92                    collection: CollectionId,93                    sender: CrossAccountId,94                    spender: CrossAccountId,95                    token: TokenId,96                ) -> Result<u128, DispatchError> {97                    dispatch_unique_runtime!(collection.allowance(sender, spender, token))98                }99100                fn adminlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {101                    Ok(<pallet_common::Pallet<Runtime>>::adminlist(collection))102                }103                fn allowlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {104                    Ok(<pallet_common::Pallet<Runtime>>::allowlist(collection))105                }106                fn allowed(collection: CollectionId, user: CrossAccountId) -> Result<bool, DispatchError> {107                    Ok(<pallet_common::Pallet<Runtime>>::allowed(collection, user))108                }109                fn last_token_id(collection: CollectionId) -> Result<TokenId, DispatchError> {110                    dispatch_unique_runtime!(collection.last_token_id())111                }112                fn collection_by_id(collection: CollectionId) -> Result<Option<RpcCollection<AccountId>>, DispatchError> {113                    Ok(<pallet_common::Pallet<Runtime>>::rpc_collection(collection))114                }115                fn collection_stats() -> Result<CollectionStats, DispatchError> {116                    Ok(<pallet_common::Pallet<Runtime>>::collection_stats())117                }118                fn next_sponsored(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<Option<u64>, DispatchError> {119                    Ok(<$crate::sponsoring::UniqueSponsorshipPredict<Runtime> as120                            $crate::sponsoring::SponsorshipPredict<Runtime>>::predict(121                        collection,122                        account,123                        token))124                }125126                fn effective_collection_limits(collection: CollectionId) -> Result<Option<CollectionLimits>, DispatchError> {127                    Ok(<pallet_common::Pallet<Runtime>>::effective_collection_limits(collection))128                }129            }130131            impl rmrk_rpc::RmrkApi<132                Block,133                AccountId,134                RmrkCollectionInfo<AccountId>,135                RmrkInstanceInfo<AccountId>,136                RmrkResourceInfo,137                RmrkPropertyInfo,138                RmrkBaseInfo<AccountId>,139                RmrkPartType,140                RmrkTheme141            > for Runtime {142                fn last_collection_idx() -> Result<RmrkCollectionId, DispatchError> {143                    Ok(RmrkCore::last_collection_idx())144                }145146                fn collection_by_id(collection_id: RmrkCollectionId) -> Result<Option<RmrkCollectionInfo<AccountId>>, DispatchError> {147                    use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, RmrkDecode, RmrkRebind}};148149                    let collection_id = RmrkCore::unique_collection_id(collection_id)?;150                    let collection = match RmrkCore::get_typed_nft_collection(collection_id, CollectionType::Regular) {151                        Ok(c) => c,152                        Err(_) => return Ok(None),153                    };154155                    // todo replace dispatch... calls with calls to rmrkcore and NFT collection. There's no point trying non-NFT collections156                    let nfts_count = dispatch_unique_runtime!(collection_id.total_supply())?;157158                    Ok(Some(RmrkCollectionInfo {159                        issuer: collection.owner.clone(),160                        metadata: RmrkCore::get_collection_property(collection_id, RmrkProperty::Metadata)?.decode_or_default(),161                        max: collection.limits.token_limit,162                        symbol: collection.token_prefix.rebind(),163                        nfts_count164                    }))165                }166167                fn nft_by_id(collection_id: RmrkCollectionId, nft_by_id: RmrkNftId) -> Result<Option<RmrkInstanceInfo<AccountId>>, DispatchError> {168                    use up_data_structs::mapping::TokenAddressMapping;169                    use pallet_proxy_rmrk_core::{RmrkProperty, misc::RmrkDecode};170171                    let collection_id = RmrkCore::unique_collection_id(collection_id)?;172                    let nft_id = TokenId(nft_by_id);173                    if !RmrkCore::nft_exists(collection_id, nft_id) { return Ok(None); }174175                    // todo replace dispatch with collection176                    let owner = match dispatch_unique_runtime!(collection_id.token_owner(nft_id))? {177                        Some(owner) => match <Runtime as pallet_common::Config>::CrossTokenAddressMapping::address_to_token(&owner) {178                            Some((col, tok)) => RmrkAccountIdOrCollectionNftTuple::CollectionAndNftTuple(col.0, tok.0),179                            None => RmrkAccountIdOrCollectionNftTuple::AccountId(owner.as_sub().clone())180                        },181                        None => return Ok(None)182                    };183184                    let allowance = pallet_nonfungible::Allowance::<Runtime>::get((collection_id, nft_id));185186                    Ok(Some(RmrkInstanceInfo {187                        owner: owner,188                        royalty: RmrkCore::get_nft_property(collection_id, nft_id, RmrkProperty::RoyaltyInfo)?.decode_or_default(),189                        metadata: RmrkCore::get_nft_property(collection_id, nft_id, RmrkProperty::Metadata)?.decode_or_default(),190                        equipped: RmrkCore::get_nft_property(collection_id, nft_id, RmrkProperty::Equipped)?.decode_or_default(),191                        pending: allowance.is_some(),192                    }))193                }194195                fn account_tokens(account_id: AccountId, collection_id: RmrkCollectionId) -> Result<Vec<RmrkNftId>, DispatchError> {196                    use pallet_proxy_rmrk_core::misc::CollectionType;197198                    let cross_account_id = CrossAccountId::from_sub(account_id);199                    let collection_id = RmrkCore::unique_collection_id(collection_id)?;200                    if RmrkCore::ensure_collection_type(collection_id, CollectionType::Regular).is_err() { return Ok(Vec::new()); }201202                    Ok(203                        dispatch_unique_runtime!(collection_id.account_tokens(cross_account_id))?204                            .into_iter()205                            .map(|token| token.0)206                            .collect()207                    )208                }209210                fn nft_children(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Result<Vec<RmrkNftChild>, DispatchError> {211                    let collection_id = RmrkCore::unique_collection_id(collection_id)?;212                    let nft_id = TokenId(nft_id);213                    if !RmrkCore::nft_exists(collection_id, nft_id) { return Ok(Vec::new()); }214215                    Ok(216                        pallet_nonfungible::TokenChildren::<Runtime>::iter_prefix((collection_id, nft_id))217                            .filter_map(|(child_id, is_child)|218                                match is_child {219                                    true => Some(RmrkNftChild {220                                        collection_id: child_id.0.0,221                                        nft_id: child_id.1.0,222                                    }),223                                    false => None,224                                }225                            ).collect()226                    )227                }228229                fn collection_properties(collection_id: RmrkCollectionId, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Result<Vec<RmrkPropertyInfo>, DispatchError> {230                    use pallet_proxy_rmrk_core::misc::CollectionType;231232                    let collection_id = RmrkCore::unique_collection_id(collection_id)?;233                    if RmrkCore::ensure_collection_type(collection_id, CollectionType::Regular).is_err() {234                        return Ok(Vec::new());235                    }236237                    let properties = RmrkCore::filter_user_properties(238                        collection_id,239                        /* token_id = */ None,240                        filter_keys,241                        |key, value| RmrkPropertyInfo {242                            key,243                            value244                        }245                    )?;246247                    Ok(properties)248                }249250                fn nft_properties(collection_id: RmrkCollectionId, nft_id: RmrkNftId, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Result<Vec<RmrkPropertyInfo>, DispatchError> {251                    use pallet_proxy_rmrk_core::misc::NftType;252253                    let collection_id = RmrkCore::unique_collection_id(collection_id)?;254                    let token_id = TokenId(nft_id);255256                    if RmrkCore::ensure_nft_type(collection_id, token_id, NftType::Regular).is_err() {257                        return Ok(Vec::new());258                    }259260		            let properties = RmrkCore::filter_user_properties(261                        collection_id,262                        Some(token_id),263                        filter_keys,264                        |key, value| RmrkPropertyInfo {265                            key,266                            value267                        }268                    )?;269270                    Ok(properties)271                }272273                fn nft_resources(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Result<Vec<RmrkResourceInfo>, DispatchError> {274                    use frame_support::BoundedVec;275                    use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, NftType, ResourceType, RmrkDecode}};276                    use pallet_common::CommonCollectionOperations;277278                    let collection_id = RmrkCore::unique_collection_id(collection_id)?;279                    if RmrkCore::ensure_collection_type(collection_id, CollectionType::Regular).is_err() { return Ok(Vec::new()); }280281                    let nft_id = TokenId(nft_id);282                    if RmrkCore::ensure_nft_type(collection_id, nft_id, NftType::Regular).is_err() { return Ok(Vec::new()); }283284                    let res_collection_id: CollectionId = RmrkCore::get_nft_property(collection_id, nft_id, RmrkProperty::ResourceCollection)?285                        .decode_or_default();286                    let resource_collection = RmrkCore::get_typed_nft_collection(res_collection_id, CollectionType::Resource)?;287288                    let resources = resource_collection289                        .collection_tokens()290                        .iter()291                        .filter_map(|(res_id)| Some(RmrkResourceInfo {292                            id: res_id.0,293                            pending: RmrkCore::get_nft_property(res_collection_id, *res_id, RmrkProperty::PendingResourceAccept).unwrap().decode_or_default(),294                            pending_removal: RmrkCore::get_nft_property(res_collection_id, *res_id, RmrkProperty::PendingResourceRemoval).unwrap().decode_or_default(),295                            resource: match RmrkCore::get_nft_property(res_collection_id, *res_id, RmrkProperty::ResourceType).unwrap().decode_or_default() {296                                ResourceType::Basic => RmrkResourceTypes::Basic(RmrkBasicResource {297                                    src: RmrkCore::get_nft_property(res_collection_id, *res_id, RmrkProperty::Src).unwrap().decode_or_default(),298                                    metadata: RmrkCore::get_nft_property(res_collection_id, *res_id, RmrkProperty::Metadata).unwrap().decode_or_default(),299                                    license: RmrkCore::get_nft_property(res_collection_id, *res_id, RmrkProperty::License).unwrap().decode_or_default(),300                                    thumb: RmrkCore::get_nft_property(res_collection_id, *res_id, RmrkProperty::Thumb).unwrap().decode_or_default(),301                                }),302                                ResourceType::Composable => RmrkResourceTypes::Composable(RmrkComposableResource {303                                    parts: RmrkCore::get_nft_property(res_collection_id, *res_id, RmrkProperty::Parts).unwrap().decode_or_default(),304                                    base: RmrkCore::get_nft_property(res_collection_id, *res_id, RmrkProperty::Base).unwrap().decode_or_default(),305                                    src: RmrkCore::get_nft_property(res_collection_id, *res_id, RmrkProperty::Src).unwrap().decode_or_default(),306                                    metadata: RmrkCore::get_nft_property(res_collection_id, *res_id, RmrkProperty::Metadata).unwrap().decode_or_default(),307                                    license: RmrkCore::get_nft_property(res_collection_id, *res_id, RmrkProperty::License).unwrap().decode_or_default(),308                                    thumb: RmrkCore::get_nft_property(res_collection_id, *res_id, RmrkProperty::Thumb).unwrap().decode_or_default(),309                                }),310                                ResourceType::Slot => RmrkResourceTypes::Slot(RmrkSlotResource {311                                    base: RmrkCore::get_nft_property(res_collection_id, *res_id, RmrkProperty::Base).unwrap().decode_or_default(),312                                    src: RmrkCore::get_nft_property(res_collection_id, *res_id, RmrkProperty::Src).unwrap().decode_or_default(),313                                    metadata: RmrkCore::get_nft_property(res_collection_id, *res_id, RmrkProperty::Metadata).unwrap().decode_or_default(),314                                    slot: RmrkCore::get_nft_property(res_collection_id, *res_id, RmrkProperty::Slot).unwrap().decode_or_default(),315                                    license: RmrkCore::get_nft_property(res_collection_id, *res_id, RmrkProperty::License).unwrap().decode_or_default(),316                                    thumb: RmrkCore::get_nft_property(res_collection_id, *res_id, RmrkProperty::Thumb).unwrap().decode_or_default(),317                                }),318                                // todo refactor :|319                            },320                        }))321                        .collect();322323                    Ok(resources)324                }325326                fn nft_resource_priorities(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Result<Vec<RmrkResourceId>, DispatchError> {327                    use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, NftType, RmrkDecode}};328329                    let collection_id = RmrkCore::unique_collection_id(collection_id)?;330                    if RmrkCore::ensure_collection_type(collection_id, CollectionType::Regular).is_err() { return Ok(Vec::new()); }331332                    let nft_id = TokenId(nft_id);333                    if RmrkCore::ensure_nft_type(collection_id, nft_id, NftType::Regular).is_err() { return Ok(Vec::new()); }334335                    /*let resource_collection_id: CollectionId = RmrkCore::get_nft_property(collection_id, nft_id, RmrkProperty::ResourceCollection)336                        .unwrap()337                        .decode_or_default();338                    if RmrkCore::ensure_collection_type(collection_id, CollectionType::Resource).is_err() { return Ok(Vec::new()); }339340                    let resources = pallet_nonfungible::TokenProperties::<Runtime>::iter_prefix((resource_collection_id,))341                        .filter_map(|(resource_id, properties)| Some((342                            resource_id, // ResourceId property343                            RmrkCore::get_nft_property(resource_collection_id, resource_id, RmrkProperty::Priority).unwrap().decode_or_default(),344                        )))345                        .collect()346                        .sort_by_key(|(_, index)| *index)347                        .into_iter().map(|(resource_id, _)| resource_id)*/348                    let priorities = RmrkCore::get_nft_property(collection_id, nft_id, RmrkProperty::ResourcePriorities)?.decode_or_default();349                    // todo let it simply be default here after removing default from decode350351                    Ok(priorities)352                }353354                fn base(base_id: RmrkBaseId) -> Result<Option<RmrkBaseInfo<AccountId>>, DispatchError> {355                    use pallet_proxy_rmrk_core::{356                        RmrkProperty, misc::{CollectionType, RmrkDecode, RmrkRebind},357                    };358359                    let collection_id = RmrkCore::unique_collection_id(base_id)?;360                    let collection = match RmrkCore::get_typed_nft_collection(collection_id, CollectionType::Base) {361                        Ok(c) => c,362                        Err(_) => return Ok(None),363                    };364365                    Ok(Some(RmrkBaseInfo {366                        issuer: collection.owner.clone(),367                        base_type: RmrkCore::get_collection_property(collection_id, RmrkProperty::BaseType)?.decode_or_default(),368                        symbol: collection.token_prefix.rebind(),369                    }))370                }371372                fn base_parts(base_id: RmrkBaseId) -> Result<Vec<RmrkPartType>, DispatchError> {373                    use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, NftType, RmrkDecode}};374375                    let collection_id = RmrkCore::unique_collection_id(base_id)?;376                    if RmrkCore::ensure_collection_type(collection_id, CollectionType::Base).is_err() { return Ok(Vec::new()); }377378                    let parts = dispatch_unique_runtime!(collection_id.collection_tokens())?379                        .into_iter()380                        .filter_map(|token_id| {381                            let nft_type = RmrkCore::get_nft_type(collection_id, token_id).ok()?;382383                            match nft_type {384                                NftType::FixedPart => Some(RmrkPartType::FixedPart(RmrkFixedPart {385                                    id: RmrkCore::get_nft_property(collection_id, token_id, RmrkProperty::ExternalPartId).ok()?.decode_or_default(),386                                    src: RmrkCore::get_nft_property(collection_id, token_id, RmrkProperty::Src).ok()?.decode_or_default(),387                                    z: RmrkCore::get_nft_property(collection_id, token_id, RmrkProperty::ZIndex).ok()?.decode_or_default(),388                                })),389                                NftType::SlotPart => Some(RmrkPartType::SlotPart(RmrkSlotPart {390                                    id: RmrkCore::get_nft_property(collection_id, token_id, RmrkProperty::ExternalPartId).ok()?.decode_or_default(),391                                    src: RmrkCore::get_nft_property(collection_id, token_id, RmrkProperty::Src).ok()?.decode_or_default(),392                                    z: RmrkCore::get_nft_property(collection_id, token_id, RmrkProperty::ZIndex).ok()?.decode_or_default(),393                                    equippable: RmrkCore::get_nft_property(collection_id, token_id, RmrkProperty::EquippableList).ok()?.decode_or_default(),394                                })),395                                _ => None396                            }397                        })398                        .collect();399400                    Ok(parts)401                }402403                fn theme_names(base_id: RmrkBaseId) -> Result<Vec<RmrkThemeName>, DispatchError> {404                    use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, RmrkDecode}};405406                    let collection_id = RmrkCore::unique_collection_id(base_id)?;407                    if RmrkCore::ensure_collection_type(collection_id, CollectionType::Base).is_err() {408                        return Ok(Vec::new());409                    }410411                    let theme_names = dispatch_unique_runtime!(collection_id.collection_tokens())?412                        .iter()413                        .filter_map(|token_id| {414                            let nft_type = RmrkCore::get_nft_type(collection_id, *token_id).unwrap();415416                            match nft_type {417                                Theme => Some(418                                    RmrkCore::get_nft_property(collection_id, *token_id, RmrkProperty::ThemeName).unwrap().decode_or_default()419                                ),420                                _ => None421                            }422                        })423                        .collect();424425                    Ok(theme_names)426                }427428                fn theme(base_id: RmrkBaseId, theme_name: RmrkThemeName, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Result<Option<RmrkTheme>, DispatchError> {429                    use pallet_proxy_rmrk_core::{430                        RmrkProperty,431                        misc::{CollectionType, NftType, RmrkDecode}432                    };433434                    let collection_id = RmrkCore::unique_collection_id(base_id)?;435                    if RmrkCore::ensure_collection_type(collection_id, CollectionType::Base).is_err() {436                        return Ok(None);437                    }438439                    let theme_info = dispatch_unique_runtime!(collection_id.collection_tokens())?440                        .into_iter()441                        .find_map(|token_id| {442                            RmrkCore::ensure_nft_type(collection_id, token_id, NftType::Theme).ok()?;443444                            let name: RmrkString = RmrkCore::get_nft_property(445                                collection_id, token_id, RmrkProperty::ThemeName446                            ).ok()?.decode_or_default();447448                            if name == theme_name {449                                Some((name, token_id))450                            } else {451                                None452                            }453                        });454455                    let (name, theme_id) = match theme_info {456                        Some((name, theme_id)) => (name, theme_id),457                        None => return Ok(None)458                    };459460                    let properties = RmrkCore::filter_user_properties(461                        collection_id,462                        Some(theme_id),463                        filter_keys,464                        |key, value| RmrkThemeProperty {465                            key,466                            value467                        }468                    )?;469470                    let inherit = RmrkCore::get_nft_property(471                        collection_id,472                        theme_id,473                        RmrkProperty::ThemeInherit474                    )?.decode_or_default();475476                    let theme = RmrkTheme {477                        name,478                        properties,479                        inherit,480                    };481482                    Ok(Some(theme))483                }484            }485486            impl sp_api::Core<Block> for Runtime {487                fn version() -> RuntimeVersion {488                    VERSION489                }490491                fn execute_block(block: Block) {492                    Executive::execute_block(block)493                }494495                fn initialize_block(header: &<Block as BlockT>::Header) {496                    Executive::initialize_block(header)497                }498            }499500            impl sp_api::Metadata<Block> for Runtime {501                fn metadata() -> OpaqueMetadata {502                    OpaqueMetadata::new(Runtime::metadata().into())503                }504            }505506            impl sp_block_builder::BlockBuilder<Block> for Runtime {507                fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {508                    Executive::apply_extrinsic(extrinsic)509                }510511                fn finalize_block() -> <Block as BlockT>::Header {512                    Executive::finalize_block()513                }514515                fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {516                    data.create_extrinsics()517                }518519                fn check_inherents(520                    block: Block,521                    data: sp_inherents::InherentData,522                ) -> sp_inherents::CheckInherentsResult {523                    data.check_extrinsics(&block)524                }525526                // fn random_seed() -> <Block as BlockT>::Hash {527                //     RandomnessCollectiveFlip::random_seed().0528                // }529            }530531            impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {532                fn validate_transaction(533                    source: TransactionSource,534                    tx: <Block as BlockT>::Extrinsic,535                    hash: <Block as BlockT>::Hash,536                ) -> TransactionValidity {537                    Executive::validate_transaction(source, tx, hash)538                }539            }540541            impl sp_offchain::OffchainWorkerApi<Block> for Runtime {542                fn offchain_worker(header: &<Block as BlockT>::Header) {543                    Executive::offchain_worker(header)544                }545            }546547            impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {548                fn chain_id() -> u64 {549                    <Runtime as pallet_evm::Config>::ChainId::get()550                }551552                fn account_basic(address: H160) -> EVMAccount {553                    let (account, _) = EVM::account_basic(&address);554                    account555                }556557                fn gas_price() -> U256 {558                    let (price, _) = <Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price();559                    price560                }561562                fn account_code_at(address: H160) -> Vec<u8> {563                    EVM::account_codes(address)564                }565566                fn author() -> H160 {567                    <pallet_evm::Pallet<Runtime>>::find_author()568                }569570                fn storage_at(address: H160, index: U256) -> H256 {571                    let mut tmp = [0u8; 32];572                    index.to_big_endian(&mut tmp);573                    EVM::account_storages(address, H256::from_slice(&tmp[..]))574                }575576                #[allow(clippy::redundant_closure)]577                fn call(578                    from: H160,579                    to: H160,580                    data: Vec<u8>,581                    value: U256,582                    gas_limit: U256,583                    max_fee_per_gas: Option<U256>,584                    max_priority_fee_per_gas: Option<U256>,585                    nonce: Option<U256>,586                    estimate: bool,587                    access_list: Option<Vec<(H160, Vec<H256>)>>,588                ) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {589                    let config = if estimate {590                        let mut config = <Runtime as pallet_evm::Config>::config().clone();591                        config.estimate = true;592                        Some(config)593                    } else {594                        None595                    };596597                    let is_transactional = false;598                    <Runtime as pallet_evm::Config>::Runner::call(599                        CrossAccountId::from_eth(from),600                        to,601                        data,602                        value,603                        gas_limit.low_u64(),604                        max_fee_per_gas,605                        max_priority_fee_per_gas,606                        nonce,607                        access_list.unwrap_or_default(),608                        is_transactional,609                        config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),610                    ).map_err(|err| err.error.into())611                }612613                #[allow(clippy::redundant_closure)]614                fn create(615                    from: H160,616                    data: Vec<u8>,617                    value: U256,618                    gas_limit: U256,619                    max_fee_per_gas: Option<U256>,620                    max_priority_fee_per_gas: Option<U256>,621                    nonce: Option<U256>,622                    estimate: bool,623                    access_list: Option<Vec<(H160, Vec<H256>)>>,624                ) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {625                    let config = if estimate {626                        let mut config = <Runtime as pallet_evm::Config>::config().clone();627                        config.estimate = true;628                        Some(config)629                    } else {630                        None631                    };632633                    let is_transactional = false;634                    <Runtime as pallet_evm::Config>::Runner::create(635                        CrossAccountId::from_eth(from),636                        data,637                        value,638                        gas_limit.low_u64(),639                        max_fee_per_gas,640                        max_priority_fee_per_gas,641                        nonce,642                        access_list.unwrap_or_default(),643                        is_transactional,644                        config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),645                    ).map_err(|err| err.error.into())646                }647648                fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {649                    Ethereum::current_transaction_statuses()650                }651652                fn current_block() -> Option<pallet_ethereum::Block> {653                    Ethereum::current_block()654                }655656                fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {657                    Ethereum::current_receipts()658                }659660                fn current_all() -> (661                    Option<pallet_ethereum::Block>,662                    Option<Vec<pallet_ethereum::Receipt>>,663                    Option<Vec<TransactionStatus>>664                ) {665                    (666                        Ethereum::current_block(),667                        Ethereum::current_receipts(),668                        Ethereum::current_transaction_statuses()669                    )670                }671672                fn extrinsic_filter(xts: Vec<<Block as sp_api::BlockT>::Extrinsic>) -> Vec<pallet_ethereum::Transaction> {673                    xts.into_iter().filter_map(|xt| match xt.0.function {674                        Call::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction),675                        _ => None676                    }).collect()677                }678679                fn elasticity() -> Option<Permill> {680                    None681                }682            }683684            impl fp_rpc::ConvertTransactionRuntimeApi<Block> for Runtime {685                fn convert_transaction(transaction: pallet_ethereum::Transaction) -> <Block as BlockT>::Extrinsic  {686                    UncheckedExtrinsic::new_unsigned(687                        pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),688                    )689                }690            }691692            impl sp_session::SessionKeys<Block> for Runtime {693                fn decode_session_keys(694                    encoded: Vec<u8>,695                ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {696                    SessionKeys::decode_into_raw_public_keys(&encoded)697                }698699                fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {700                    SessionKeys::generate(seed)701                }702            }703704            impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {705                fn slot_duration() -> sp_consensus_aura::SlotDuration {706                    sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())707                }708709                fn authorities() -> Vec<AuraId> {710                    Aura::authorities().to_vec()711                }712            }713714            impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {715                fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {716                    ParachainSystem::collect_collation_info(header)717                }718            }719720            impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {721                fn account_nonce(account: AccountId) -> Index {722                    System::account_nonce(account)723                }724            }725726            impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {727                fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {728                    TransactionPayment::query_info(uxt, len)729                }730                fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {731                    TransactionPayment::query_fee_details(uxt, len)732                }733            }734735            /*736            impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber, Hash>737                for Runtime738            {739                fn call(740                    origin: AccountId,741                    dest: AccountId,742                    value: Balance,743                    gas_limit: u64,744                    input_data: Vec<u8>,745                ) -> pallet_contracts_primitives::ContractExecResult {746                    Contracts::bare_call(origin, dest, value, gas_limit, input_data, false)747                }748749                fn instantiate(750                    origin: AccountId,751                    endowment: Balance,752                    gas_limit: u64,753                    code: pallet_contracts_primitives::Code<Hash>,754                    data: Vec<u8>,755                    salt: Vec<u8>,756                ) -> pallet_contracts_primitives::ContractInstantiateResult<AccountId, BlockNumber>757                {758                    Contracts::bare_instantiate(origin, endowment, gas_limit, code, data, salt, true, false)759                }760761                fn get_storage(762                    address: AccountId,763                    key: [u8; 32],764                ) -> pallet_contracts_primitives::GetStorageResult {765                    Contracts::get_storage(address, key)766                }767768                fn rent_projection(769                    address: AccountId,770                ) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {771                    Contracts::rent_projection(address)772                }773            }774            */775776            #[cfg(feature = "runtime-benchmarks")]777            impl frame_benchmarking::Benchmark<Block> for Runtime {778                fn benchmark_metadata(extra: bool) -> (779                    Vec<frame_benchmarking::BenchmarkList>,780                    Vec<frame_support::traits::StorageInfo>,781                ) {782                    use frame_benchmarking::{list_benchmark, Benchmarking, BenchmarkList};783                    use frame_support::traits::StorageInfoTrait;784785                    let mut list = Vec::<BenchmarkList>::new();786787                    list_benchmark!(list, extra, pallet_evm_migration, EvmMigration);788                    list_benchmark!(list, extra, pallet_common, Common);789                    list_benchmark!(list, extra, pallet_unique, Unique);790                    list_benchmark!(list, extra, pallet_structure, Structure);791                    list_benchmark!(list, extra, pallet_inflation, Inflation);792                    list_benchmark!(list, extra, pallet_fungible, Fungible);793                    list_benchmark!(list, extra, pallet_refungible, Refungible);794                    list_benchmark!(list, extra, pallet_nonfungible, Nonfungible);795                    // list_benchmark!(list, extra, pallet_evm_coder_substrate, EvmCoderSubstrate);796797                    let storage_info = AllPalletsReversedWithSystemFirst::storage_info();798799                    return (list, storage_info)800                }801802                fn dispatch_benchmark(803                    config: frame_benchmarking::BenchmarkConfig804                ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {805                    use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};806807                    let allowlist: Vec<TrackedStorageKey> = vec![808                        // Total Issuance809                        hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),810811                        // Block Number812                        hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),813                        // Execution Phase814                        hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),815                        // Event Count816                        hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),817                        // System Events818                        hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),819820                        // Evm CurrentLogs821                        hex_literal::hex!("1da53b775b270400e7e61ed5cbc5a146547f210cec367e9af919603343b9cb56").to_vec().into(),822823                        // Transactional depth824                        hex_literal::hex!("3a7472616e73616374696f6e5f6c6576656c3a").to_vec().into(),825                    ];826827                    let mut batches = Vec::<BenchmarkBatch>::new();828                    let params = (&config, &allowlist);829830                    add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);831                    add_benchmark!(params, batches, pallet_common, Common);832                    add_benchmark!(params, batches, pallet_unique, Unique);833                    add_benchmark!(params, batches, pallet_structure, Structure);834                    add_benchmark!(params, batches, pallet_inflation, Inflation);835                    add_benchmark!(params, batches, pallet_fungible, Fungible);836                    add_benchmark!(params, batches, pallet_refungible, Refungible);837                    add_benchmark!(params, batches, pallet_nonfungible, Nonfungible);838                    // add_benchmark!(params, batches, pallet_evm_coder_substrate, EvmCoderSubstrate);839840                    if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }841                    Ok(batches)842                }843            }844845            #[cfg(feature = "try-runtime")]846            impl frame_try_runtime::TryRuntime<Block> for Runtime {847                fn on_runtime_upgrade() -> (Weight, Weight) {848                    log::info!("try-runtime::on_runtime_upgrade unique-chain.");849                    let weight = Executive::try_runtime_upgrade().unwrap();850                    (weight, RuntimeBlockWeights::get().max_block)851                }852853                fn execute_block_no_check(block: Block) -> Weight {854                    Executive::execute_block_no_check(block)855                }856            }857        }858    }859}
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(10);2930                    Ok(Some(<pallet_structure::Pallet<Runtime>>::find_topmost_owner(collection, token, &budget)?))31                }32                fn token_children(collection: CollectionId, token: TokenId) -> Result<Vec<TokenChild>, DispatchError> {33                    Ok(<pallet_nonfungible::Pallet<Runtime>>::token_children_ids(collection, token))34                }35                fn collection_properties(36                    collection: CollectionId,37                    keys: Option<Vec<Vec<u8>>>38                ) -> Result<Vec<Property>, DispatchError> {39                    let keys = keys.map(40                        |keys| Common::bytes_keys_to_property_keys(keys)41                    ).transpose()?;4243                    Common::filter_collection_properties(collection, keys)44                }4546                fn token_properties(47                    collection: CollectionId,48                    token_id: TokenId,49                    keys: Option<Vec<Vec<u8>>>50                ) -> Result<Vec<Property>, DispatchError> {51                    let keys = keys.map(52                        |keys| Common::bytes_keys_to_property_keys(keys)53                    ).transpose()?;5455                    dispatch_unique_runtime!(collection.token_properties(token_id, keys))56                }5758                fn property_permissions(59                    collection: CollectionId,60                    keys: Option<Vec<Vec<u8>>>61                ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {62                    let keys = keys.map(63                        |keys| Common::bytes_keys_to_property_keys(keys)64                    ).transpose()?;6566                    Common::filter_property_permissions(collection, keys)67                }6869                fn token_data(70                    collection: CollectionId,71                    token_id: TokenId,72                    keys: Option<Vec<Vec<u8>>>73                ) -> Result<TokenData<CrossAccountId>, DispatchError> {74                    let token_data = TokenData {75                        properties: Self::token_properties(collection, token_id, keys)?,76                        owner: Self::token_owner(collection, token_id)?77                    };7879                    Ok(token_data)80                }8182                fn total_supply(collection: CollectionId) -> Result<u32, DispatchError> {83                    dispatch_unique_runtime!(collection.total_supply())84                }85                fn account_balance(collection: CollectionId, account: CrossAccountId) -> Result<u32, DispatchError> {86                    dispatch_unique_runtime!(collection.account_balance(account))87                }88                fn balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<u128, DispatchError> {89                    dispatch_unique_runtime!(collection.balance(account, token))90                }91                fn allowance(92                    collection: CollectionId,93                    sender: CrossAccountId,94                    spender: CrossAccountId,95                    token: TokenId,96                ) -> Result<u128, DispatchError> {97                    dispatch_unique_runtime!(collection.allowance(sender, spender, token))98                }99100                fn adminlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {101                    Ok(<pallet_common::Pallet<Runtime>>::adminlist(collection))102                }103                fn allowlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {104                    Ok(<pallet_common::Pallet<Runtime>>::allowlist(collection))105                }106                fn allowed(collection: CollectionId, user: CrossAccountId) -> Result<bool, DispatchError> {107                    Ok(<pallet_common::Pallet<Runtime>>::allowed(collection, user))108                }109                fn last_token_id(collection: CollectionId) -> Result<TokenId, DispatchError> {110                    dispatch_unique_runtime!(collection.last_token_id())111                }112                fn collection_by_id(collection: CollectionId) -> Result<Option<RpcCollection<AccountId>>, DispatchError> {113                    Ok(<pallet_common::Pallet<Runtime>>::rpc_collection(collection))114                }115                fn collection_stats() -> Result<CollectionStats, DispatchError> {116                    Ok(<pallet_common::Pallet<Runtime>>::collection_stats())117                }118                fn next_sponsored(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<Option<u64>, DispatchError> {119                    Ok(<$crate::sponsoring::UniqueSponsorshipPredict<Runtime> as120                            $crate::sponsoring::SponsorshipPredict<Runtime>>::predict(121                        collection,122                        account,123                        token))124                }125126                fn effective_collection_limits(collection: CollectionId) -> Result<Option<CollectionLimits>, DispatchError> {127                    Ok(<pallet_common::Pallet<Runtime>>::effective_collection_limits(collection))128                }129            }130131            impl rmrk_rpc::RmrkApi<132                Block,133                AccountId,134                RmrkCollectionInfo<AccountId>,135                RmrkInstanceInfo<AccountId>,136                RmrkResourceInfo,137                RmrkPropertyInfo,138                RmrkBaseInfo<AccountId>,139                RmrkPartType,140                RmrkTheme141            > for Runtime {142                fn last_collection_idx() -> Result<RmrkCollectionId, DispatchError> {143                    Ok(RmrkCore::last_collection_idx())144                }145146                fn collection_by_id(collection_id: RmrkCollectionId) -> Result<Option<RmrkCollectionInfo<AccountId>>, DispatchError> {147                    use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType}};148149                    let collection_id = RmrkCore::unique_collection_id(collection_id)?;150                    let collection = match RmrkCore::get_typed_nft_collection(collection_id, CollectionType::Regular) {151                        Ok(c) => c,152                        Err(_) => return Ok(None),153                    };154155                    // todo replace dispatch... calls with calls to rmrkcore and NFT collection. There's no point trying non-NFT collections156                    let nfts_count = dispatch_unique_runtime!(collection_id.total_supply())?;157158                    Ok(Some(RmrkCollectionInfo {159                        issuer: collection.owner.clone(),160                        metadata: RmrkCore::get_collection_property_decoded(collection_id, RmrkProperty::Metadata)?,161                        max: collection.limits.token_limit,162                        symbol: RmrkCore::rebind(&collection.token_prefix)?,163                        nfts_count164                    }))165                }166167                fn nft_by_id(collection_id: RmrkCollectionId, nft_by_id: RmrkNftId) -> Result<Option<RmrkInstanceInfo<AccountId>>, DispatchError> {168                    use up_data_structs::mapping::TokenAddressMapping;169                    use pallet_proxy_rmrk_core::{RmrkProperty, misc::RmrkDecode};170171                    let collection_id = RmrkCore::unique_collection_id(collection_id)?;172                    let nft_id = TokenId(nft_by_id);173                    if !RmrkCore::nft_exists(collection_id, nft_id) { return Ok(None); }174175                    // todo replace dispatch with collection176                    let owner = match dispatch_unique_runtime!(collection_id.token_owner(nft_id))? {177                        Some(owner) => match <Runtime as pallet_common::Config>::CrossTokenAddressMapping::address_to_token(&owner) {178                            Some((col, tok)) => RmrkAccountIdOrCollectionNftTuple::CollectionAndNftTuple(col.0, tok.0),179                            None => RmrkAccountIdOrCollectionNftTuple::AccountId(owner.as_sub().clone())180                        },181                        None => return Ok(None)182                    };183184                    let allowance = pallet_nonfungible::Allowance::<Runtime>::get((collection_id, nft_id));185186                    Ok(Some(RmrkInstanceInfo {187                        owner: owner,188                        royalty: RmrkCore::get_nft_property_decoded(collection_id, nft_id, RmrkProperty::RoyaltyInfo)?,189                        metadata: RmrkCore::get_nft_property_decoded(collection_id, nft_id, RmrkProperty::Metadata)?,190                        equipped: RmrkCore::get_nft_property_decoded(collection_id, nft_id, RmrkProperty::Equipped)?,191                        pending: allowance.is_some(),192                    }))193                }194195                fn account_tokens(account_id: AccountId, collection_id: RmrkCollectionId) -> Result<Vec<RmrkNftId>, DispatchError> {196                    use pallet_proxy_rmrk_core::misc::CollectionType;197198                    let cross_account_id = CrossAccountId::from_sub(account_id);199                    let collection_id = RmrkCore::unique_collection_id(collection_id)?;200                    if RmrkCore::ensure_collection_type(collection_id, CollectionType::Regular).is_err() { return Ok(Vec::new()); }201202                    Ok(203                        dispatch_unique_runtime!(collection_id.account_tokens(cross_account_id))?204                            .into_iter()205                            .map(|token| token.0)206                            .collect()207                    )208                }209210                fn nft_children(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Result<Vec<RmrkNftChild>, DispatchError> {211                    let collection_id = RmrkCore::unique_collection_id(collection_id)?;212                    let nft_id = TokenId(nft_id);213                    if !RmrkCore::nft_exists(collection_id, nft_id) { return Ok(Vec::new()); }214215                    Ok(216                        pallet_nonfungible::TokenChildren::<Runtime>::iter_prefix((collection_id, nft_id))217                            .filter_map(|(child_id, is_child)|218                                match is_child {219                                    true => Some(RmrkNftChild {220                                        collection_id: child_id.0.0,221                                        nft_id: child_id.1.0,222                                    }),223                                    false => None,224                                }225                            ).collect()226                    )227                }228229                fn collection_properties(collection_id: RmrkCollectionId, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Result<Vec<RmrkPropertyInfo>, DispatchError> {230                    use pallet_proxy_rmrk_core::misc::CollectionType;231232                    let collection_id = RmrkCore::unique_collection_id(collection_id)?;233                    if RmrkCore::ensure_collection_type(collection_id, CollectionType::Regular).is_err() {234                        return Ok(Vec::new());235                    }236237                    let properties = RmrkCore::filter_user_properties(238                        collection_id,239                        /* token_id = */ None,240                        filter_keys,241                        |key, value| RmrkPropertyInfo {242                            key,243                            value244                        }245                    )?;246247                    Ok(properties)248                }249250                fn nft_properties(collection_id: RmrkCollectionId, nft_id: RmrkNftId, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Result<Vec<RmrkPropertyInfo>, DispatchError> {251                    use pallet_proxy_rmrk_core::misc::NftType;252253                    let collection_id = RmrkCore::unique_collection_id(collection_id)?;254                    let token_id = TokenId(nft_id);255256                    if RmrkCore::ensure_nft_type(collection_id, token_id, NftType::Regular).is_err() {257                        return Ok(Vec::new());258                    }259260		            let properties = RmrkCore::filter_user_properties(261                        collection_id,262                        Some(token_id),263                        filter_keys,264                        |key, value| RmrkPropertyInfo {265                            key,266                            value267                        }268                    )?;269270                    Ok(properties)271                }272273                fn nft_resources(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Result<Vec<RmrkResourceInfo>, DispatchError> {274                    use frame_support::BoundedVec;275                    use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, NftType, ResourceType, RmrkDecode}};276                    use pallet_common::CommonCollectionOperations;277278                    let collection_id = RmrkCore::unique_collection_id(collection_id)?;279                    if RmrkCore::ensure_collection_type(collection_id, CollectionType::Regular).is_err() { return Ok(Vec::new()); }280281                    let nft_id = TokenId(nft_id);282                    if RmrkCore::ensure_nft_type(collection_id, nft_id, NftType::Regular).is_err() { return Ok(Vec::new()); }283284                    let res_collection_id: CollectionId = RmrkCore::get_nft_property_decoded(collection_id, nft_id, RmrkProperty::ResourceCollection)?;285                    let resource_collection = RmrkCore::get_typed_nft_collection(res_collection_id, CollectionType::Resource)?;286287                    let resources = resource_collection288                        .collection_tokens()289                        .iter()290                        .filter_map(|(res_id)| Some(RmrkResourceInfo {291                            id: res_id.0,292                            pending: RmrkCore::get_nft_property_decoded(res_collection_id, *res_id, RmrkProperty::PendingResourceAccept).unwrap(),293                            pending_removal: RmrkCore::get_nft_property_decoded(res_collection_id, *res_id, RmrkProperty::PendingResourceRemoval).unwrap(),294                            resource: match RmrkCore::get_nft_property_decoded(res_collection_id, *res_id, RmrkProperty::ResourceType).unwrap() {295                                ResourceType::Basic => RmrkResourceTypes::Basic(RmrkBasicResource {296                                    src: RmrkCore::get_nft_property_decoded(res_collection_id, *res_id, RmrkProperty::Src).unwrap(),297                                    metadata: RmrkCore::get_nft_property_decoded(res_collection_id, *res_id, RmrkProperty::Metadata).unwrap(),298                                    license: RmrkCore::get_nft_property_decoded(res_collection_id, *res_id, RmrkProperty::License).unwrap(),299                                    thumb: RmrkCore::get_nft_property_decoded(res_collection_id, *res_id, RmrkProperty::Thumb).unwrap(),300                                }),301                                ResourceType::Composable => RmrkResourceTypes::Composable(RmrkComposableResource {302                                    parts: RmrkCore::get_nft_property_decoded(res_collection_id, *res_id, RmrkProperty::Parts).unwrap(),303                                    base: RmrkCore::get_nft_property_decoded(res_collection_id, *res_id, RmrkProperty::Base).unwrap(),304                                    src: RmrkCore::get_nft_property_decoded(res_collection_id, *res_id, RmrkProperty::Src).unwrap(),305                                    metadata: RmrkCore::get_nft_property_decoded(res_collection_id, *res_id, RmrkProperty::Metadata).unwrap(),306                                    license: RmrkCore::get_nft_property_decoded(res_collection_id, *res_id, RmrkProperty::License).unwrap(),307                                    thumb: RmrkCore::get_nft_property_decoded(res_collection_id, *res_id, RmrkProperty::Thumb).unwrap(),308                                }),309                                ResourceType::Slot => RmrkResourceTypes::Slot(RmrkSlotResource {310                                    base: RmrkCore::get_nft_property_decoded(res_collection_id, *res_id, RmrkProperty::Base).unwrap(),311                                    src: RmrkCore::get_nft_property_decoded(res_collection_id, *res_id, RmrkProperty::Src).unwrap(),312                                    metadata: RmrkCore::get_nft_property_decoded(res_collection_id, *res_id, RmrkProperty::Metadata).unwrap(),313                                    slot: RmrkCore::get_nft_property_decoded(res_collection_id, *res_id, RmrkProperty::Slot).unwrap(),314                                    license: RmrkCore::get_nft_property_decoded(res_collection_id, *res_id, RmrkProperty::License).unwrap(),315                                    thumb: RmrkCore::get_nft_property_decoded(res_collection_id, *res_id, RmrkProperty::Thumb).unwrap(),316                                }),317                            },318                        }))319                        .collect();320321                    Ok(resources)322                }323324                fn nft_resource_priorities(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Result<Vec<RmrkResourceId>, DispatchError> {325                    use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, NftType, RmrkDecode}};326327                    let collection_id = RmrkCore::unique_collection_id(collection_id)?;328                    if RmrkCore::ensure_collection_type(collection_id, CollectionType::Regular).is_err() { return Ok(Vec::new()); }329330                    let nft_id = TokenId(nft_id);331                    if RmrkCore::ensure_nft_type(collection_id, nft_id, NftType::Regular).is_err() { return Ok(Vec::new()); }332333                    /*let resource_collection_id: CollectionId = RmrkCore::get_nft_property_decoded(collection_id, nft_id, RmrkProperty::ResourceCollection)334                        .unwrap();335                    if RmrkCore::ensure_collection_type(collection_id, CollectionType::Resource).is_err() { return Ok(Vec::new()); }336337                    let resources = pallet_nonfungible::TokenProperties::<Runtime>::iter_prefix((resource_collection_id,))338                        .filter_map(|(resource_id, properties)| Some((339                            resource_id, // ResourceId property340                            RmrkCore::get_nft_property_decoded(resource_collection_id, resource_id, RmrkProperty::Priority).unwrap(),341                        )))342                        .collect()343                        .sort_by_key(|(_, index)| *index)344                        .into_iter().map(|(resource_id, _)| resource_id)*/345                    let priorities = RmrkCore::get_nft_property_decoded(collection_id, nft_id, RmrkProperty::ResourcePriorities)?;346347                    Ok(priorities)348                }349350                fn base(base_id: RmrkBaseId) -> Result<Option<RmrkBaseInfo<AccountId>>, DispatchError> {351                    use pallet_proxy_rmrk_core::{352                        RmrkProperty, misc::{CollectionType},353                    };354355                    let collection_id = RmrkCore::unique_collection_id(base_id)?;356                    let collection = match RmrkCore::get_typed_nft_collection(collection_id, CollectionType::Base) {357                        Ok(c) => c,358                        Err(_) => return Ok(None),359                    };360361                    Ok(Some(RmrkBaseInfo {362                        issuer: collection.owner.clone(),363                        base_type: RmrkCore::get_collection_property_decoded(collection_id, RmrkProperty::BaseType)?,364                        symbol: RmrkCore::rebind(&collection.token_prefix)?,365                    }))366                }367368                fn base_parts(base_id: RmrkBaseId) -> Result<Vec<RmrkPartType>, DispatchError> {369                    use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, NftType, RmrkDecode}};370371                    let collection_id = RmrkCore::unique_collection_id(base_id)?;372                    if RmrkCore::ensure_collection_type(collection_id, CollectionType::Base).is_err() { return Ok(Vec::new()); }373374                    let parts = dispatch_unique_runtime!(collection_id.collection_tokens())?375                        .into_iter()376                        .filter_map(|token_id| {377                            let nft_type = RmrkCore::get_nft_type(collection_id, token_id).ok()?;378379                            match nft_type {380                                NftType::FixedPart => Some(RmrkPartType::FixedPart(RmrkFixedPart {381                                    id: RmrkCore::get_nft_property_decoded(collection_id, token_id, RmrkProperty::ExternalPartId).ok()?,382                                    src: RmrkCore::get_nft_property_decoded(collection_id, token_id, RmrkProperty::Src).ok()?,383                                    z: RmrkCore::get_nft_property_decoded(collection_id, token_id, RmrkProperty::ZIndex).ok()?,384                                })),385                                NftType::SlotPart => Some(RmrkPartType::SlotPart(RmrkSlotPart {386                                    id: RmrkCore::get_nft_property_decoded(collection_id, token_id, RmrkProperty::ExternalPartId).ok()?,387                                    src: RmrkCore::get_nft_property_decoded(collection_id, token_id, RmrkProperty::Src).ok()?,388                                    z: RmrkCore::get_nft_property_decoded(collection_id, token_id, RmrkProperty::ZIndex).ok()?,389                                    equippable: RmrkCore::get_nft_property_decoded(collection_id, token_id, RmrkProperty::EquippableList).ok()?,390                                })),391                                _ => None392                            }393                        })394                        .collect();395396                    Ok(parts)397                }398399                fn theme_names(base_id: RmrkBaseId) -> Result<Vec<RmrkThemeName>, DispatchError> {400                    use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, RmrkDecode}};401402                    let collection_id = RmrkCore::unique_collection_id(base_id)?;403                    if RmrkCore::ensure_collection_type(collection_id, CollectionType::Base).is_err() {404                        return Ok(Vec::new());405                    }406407                    let theme_names = dispatch_unique_runtime!(collection_id.collection_tokens())?408                        .iter()409                        .filter_map(|token_id| {410                            let nft_type = RmrkCore::get_nft_type(collection_id, *token_id).unwrap();411412                            match nft_type {413                                Theme => Some(414                                    RmrkCore::get_nft_property_decoded(collection_id, *token_id, RmrkProperty::ThemeName).unwrap()415                                ),416                                _ => None417                            }418                        })419                        .collect();420421                    Ok(theme_names)422                }423424                fn theme(base_id: RmrkBaseId, theme_name: RmrkThemeName, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Result<Option<RmrkTheme>, DispatchError> {425                    use pallet_proxy_rmrk_core::{426                        RmrkProperty,427                        misc::{CollectionType, NftType, RmrkDecode}428                    };429430                    let collection_id = RmrkCore::unique_collection_id(base_id)?;431                    if RmrkCore::ensure_collection_type(collection_id, CollectionType::Base).is_err() {432                        return Ok(None);433                    }434435                    let theme_info = dispatch_unique_runtime!(collection_id.collection_tokens())?436                        .into_iter()437                        .find_map(|token_id| {438                            RmrkCore::ensure_nft_type(collection_id, token_id, NftType::Theme).ok()?;439440                            let name: RmrkString = RmrkCore::get_nft_property_decoded(441                                collection_id, token_id, RmrkProperty::ThemeName442                            ).ok()?;443444                            if name == theme_name {445                                Some((name, token_id))446                            } else {447                                None448                            }449                        });450451                    let (name, theme_id) = match theme_info {452                        Some((name, theme_id)) => (name, theme_id),453                        None => return Ok(None)454                    };455456                    let properties = RmrkCore::filter_user_properties(457                        collection_id,458                        Some(theme_id),459                        filter_keys,460                        |key, value| RmrkThemeProperty {461                            key,462                            value463                        }464                    )?;465466                    let inherit = RmrkCore::get_nft_property_decoded(467                        collection_id,468                        theme_id,469                        RmrkProperty::ThemeInherit470                    )?;471472                    let theme = RmrkTheme {473                        name,474                        properties,475                        inherit,476                    };477478                    Ok(Some(theme))479                }480            }481482            impl sp_api::Core<Block> for Runtime {483                fn version() -> RuntimeVersion {484                    VERSION485                }486487                fn execute_block(block: Block) {488                    Executive::execute_block(block)489                }490491                fn initialize_block(header: &<Block as BlockT>::Header) {492                    Executive::initialize_block(header)493                }494            }495496            impl sp_api::Metadata<Block> for Runtime {497                fn metadata() -> OpaqueMetadata {498                    OpaqueMetadata::new(Runtime::metadata().into())499                }500            }501502            impl sp_block_builder::BlockBuilder<Block> for Runtime {503                fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {504                    Executive::apply_extrinsic(extrinsic)505                }506507                fn finalize_block() -> <Block as BlockT>::Header {508                    Executive::finalize_block()509                }510511                fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {512                    data.create_extrinsics()513                }514515                fn check_inherents(516                    block: Block,517                    data: sp_inherents::InherentData,518                ) -> sp_inherents::CheckInherentsResult {519                    data.check_extrinsics(&block)520                }521522                // fn random_seed() -> <Block as BlockT>::Hash {523                //     RandomnessCollectiveFlip::random_seed().0524                // }525            }526527            impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {528                fn validate_transaction(529                    source: TransactionSource,530                    tx: <Block as BlockT>::Extrinsic,531                    hash: <Block as BlockT>::Hash,532                ) -> TransactionValidity {533                    Executive::validate_transaction(source, tx, hash)534                }535            }536537            impl sp_offchain::OffchainWorkerApi<Block> for Runtime {538                fn offchain_worker(header: &<Block as BlockT>::Header) {539                    Executive::offchain_worker(header)540                }541            }542543            impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {544                fn chain_id() -> u64 {545                    <Runtime as pallet_evm::Config>::ChainId::get()546                }547548                fn account_basic(address: H160) -> EVMAccount {549                    let (account, _) = EVM::account_basic(&address);550                    account551                }552553                fn gas_price() -> U256 {554                    let (price, _) = <Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price();555                    price556                }557558                fn account_code_at(address: H160) -> Vec<u8> {559                    EVM::account_codes(address)560                }561562                fn author() -> H160 {563                    <pallet_evm::Pallet<Runtime>>::find_author()564                }565566                fn storage_at(address: H160, index: U256) -> H256 {567                    let mut tmp = [0u8; 32];568                    index.to_big_endian(&mut tmp);569                    EVM::account_storages(address, H256::from_slice(&tmp[..]))570                }571572                #[allow(clippy::redundant_closure)]573                fn call(574                    from: H160,575                    to: H160,576                    data: Vec<u8>,577                    value: U256,578                    gas_limit: U256,579                    max_fee_per_gas: Option<U256>,580                    max_priority_fee_per_gas: Option<U256>,581                    nonce: Option<U256>,582                    estimate: bool,583                    access_list: Option<Vec<(H160, Vec<H256>)>>,584                ) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {585                    let config = if estimate {586                        let mut config = <Runtime as pallet_evm::Config>::config().clone();587                        config.estimate = true;588                        Some(config)589                    } else {590                        None591                    };592593                    let is_transactional = false;594                    <Runtime as pallet_evm::Config>::Runner::call(595                        CrossAccountId::from_eth(from),596                        to,597                        data,598                        value,599                        gas_limit.low_u64(),600                        max_fee_per_gas,601                        max_priority_fee_per_gas,602                        nonce,603                        access_list.unwrap_or_default(),604                        is_transactional,605                        config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),606                    ).map_err(|err| err.error.into())607                }608609                #[allow(clippy::redundant_closure)]610                fn create(611                    from: H160,612                    data: Vec<u8>,613                    value: U256,614                    gas_limit: U256,615                    max_fee_per_gas: Option<U256>,616                    max_priority_fee_per_gas: Option<U256>,617                    nonce: Option<U256>,618                    estimate: bool,619                    access_list: Option<Vec<(H160, Vec<H256>)>>,620                ) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {621                    let config = if estimate {622                        let mut config = <Runtime as pallet_evm::Config>::config().clone();623                        config.estimate = true;624                        Some(config)625                    } else {626                        None627                    };628629                    let is_transactional = false;630                    <Runtime as pallet_evm::Config>::Runner::create(631                        CrossAccountId::from_eth(from),632                        data,633                        value,634                        gas_limit.low_u64(),635                        max_fee_per_gas,636                        max_priority_fee_per_gas,637                        nonce,638                        access_list.unwrap_or_default(),639                        is_transactional,640                        config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),641                    ).map_err(|err| err.error.into())642                }643644                fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {645                    Ethereum::current_transaction_statuses()646                }647648                fn current_block() -> Option<pallet_ethereum::Block> {649                    Ethereum::current_block()650                }651652                fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {653                    Ethereum::current_receipts()654                }655656                fn current_all() -> (657                    Option<pallet_ethereum::Block>,658                    Option<Vec<pallet_ethereum::Receipt>>,659                    Option<Vec<TransactionStatus>>660                ) {661                    (662                        Ethereum::current_block(),663                        Ethereum::current_receipts(),664                        Ethereum::current_transaction_statuses()665                    )666                }667668                fn extrinsic_filter(xts: Vec<<Block as sp_api::BlockT>::Extrinsic>) -> Vec<pallet_ethereum::Transaction> {669                    xts.into_iter().filter_map(|xt| match xt.0.function {670                        Call::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction),671                        _ => None672                    }).collect()673                }674675                fn elasticity() -> Option<Permill> {676                    None677                }678            }679680            impl fp_rpc::ConvertTransactionRuntimeApi<Block> for Runtime {681                fn convert_transaction(transaction: pallet_ethereum::Transaction) -> <Block as BlockT>::Extrinsic  {682                    UncheckedExtrinsic::new_unsigned(683                        pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),684                    )685                }686            }687688            impl sp_session::SessionKeys<Block> for Runtime {689                fn decode_session_keys(690                    encoded: Vec<u8>,691                ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {692                    SessionKeys::decode_into_raw_public_keys(&encoded)693                }694695                fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {696                    SessionKeys::generate(seed)697                }698            }699700            impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {701                fn slot_duration() -> sp_consensus_aura::SlotDuration {702                    sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())703                }704705                fn authorities() -> Vec<AuraId> {706                    Aura::authorities().to_vec()707                }708            }709710            impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {711                fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {712                    ParachainSystem::collect_collation_info(header)713                }714            }715716            impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {717                fn account_nonce(account: AccountId) -> Index {718                    System::account_nonce(account)719                }720            }721722            impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {723                fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {724                    TransactionPayment::query_info(uxt, len)725                }726                fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {727                    TransactionPayment::query_fee_details(uxt, len)728                }729            }730731            /*732            impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber, Hash>733                for Runtime734            {735                fn call(736                    origin: AccountId,737                    dest: AccountId,738                    value: Balance,739                    gas_limit: u64,740                    input_data: Vec<u8>,741                ) -> pallet_contracts_primitives::ContractExecResult {742                    Contracts::bare_call(origin, dest, value, gas_limit, input_data, false)743                }744745                fn instantiate(746                    origin: AccountId,747                    endowment: Balance,748                    gas_limit: u64,749                    code: pallet_contracts_primitives::Code<Hash>,750                    data: Vec<u8>,751                    salt: Vec<u8>,752                ) -> pallet_contracts_primitives::ContractInstantiateResult<AccountId, BlockNumber>753                {754                    Contracts::bare_instantiate(origin, endowment, gas_limit, code, data, salt, true, false)755                }756757                fn get_storage(758                    address: AccountId,759                    key: [u8; 32],760                ) -> pallet_contracts_primitives::GetStorageResult {761                    Contracts::get_storage(address, key)762                }763764                fn rent_projection(765                    address: AccountId,766                ) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {767                    Contracts::rent_projection(address)768                }769            }770            */771772            #[cfg(feature = "runtime-benchmarks")]773            impl frame_benchmarking::Benchmark<Block> for Runtime {774                fn benchmark_metadata(extra: bool) -> (775                    Vec<frame_benchmarking::BenchmarkList>,776                    Vec<frame_support::traits::StorageInfo>,777                ) {778                    use frame_benchmarking::{list_benchmark, Benchmarking, BenchmarkList};779                    use frame_support::traits::StorageInfoTrait;780781                    let mut list = Vec::<BenchmarkList>::new();782783                    list_benchmark!(list, extra, pallet_evm_migration, EvmMigration);784                    list_benchmark!(list, extra, pallet_common, Common);785                    list_benchmark!(list, extra, pallet_unique, Unique);786                    list_benchmark!(list, extra, pallet_structure, Structure);787                    list_benchmark!(list, extra, pallet_inflation, Inflation);788                    list_benchmark!(list, extra, pallet_fungible, Fungible);789                    list_benchmark!(list, extra, pallet_refungible, Refungible);790                    list_benchmark!(list, extra, pallet_nonfungible, Nonfungible);791                    // list_benchmark!(list, extra, pallet_evm_coder_substrate, EvmCoderSubstrate);792793                    let storage_info = AllPalletsReversedWithSystemFirst::storage_info();794795                    return (list, storage_info)796                }797798                fn dispatch_benchmark(799                    config: frame_benchmarking::BenchmarkConfig800                ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {801                    use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};802803                    let allowlist: Vec<TrackedStorageKey> = vec![804                        // Total Issuance805                        hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),806807                        // Block Number808                        hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),809                        // Execution Phase810                        hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),811                        // Event Count812                        hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),813                        // System Events814                        hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),815816                        // Evm CurrentLogs817                        hex_literal::hex!("1da53b775b270400e7e61ed5cbc5a146547f210cec367e9af919603343b9cb56").to_vec().into(),818819                        // Transactional depth820                        hex_literal::hex!("3a7472616e73616374696f6e5f6c6576656c3a").to_vec().into(),821                    ];822823                    let mut batches = Vec::<BenchmarkBatch>::new();824                    let params = (&config, &allowlist);825826                    add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);827                    add_benchmark!(params, batches, pallet_common, Common);828                    add_benchmark!(params, batches, pallet_unique, Unique);829                    add_benchmark!(params, batches, pallet_structure, Structure);830                    add_benchmark!(params, batches, pallet_inflation, Inflation);831                    add_benchmark!(params, batches, pallet_fungible, Fungible);832                    add_benchmark!(params, batches, pallet_refungible, Refungible);833                    add_benchmark!(params, batches, pallet_nonfungible, Nonfungible);834                    // add_benchmark!(params, batches, pallet_evm_coder_substrate, EvmCoderSubstrate);835836                    if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }837                    Ok(batches)838                }839            }840841            #[cfg(feature = "try-runtime")]842            impl frame_try_runtime::TryRuntime<Block> for Runtime {843                fn on_runtime_upgrade() -> (Weight, Weight) {844                    log::info!("try-runtime::on_runtime_upgrade unique-chain.");845                    let weight = Executive::try_runtime_upgrade().unwrap();846                    (weight, RuntimeBlockWeights::get().max_block)847                }848849                fn execute_block_no_check(block: Block) -> Weight {850                    Executive::execute_block_no_check(block)851                }852            }853        }854    }855}