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

difftreelog

fix(preimage) maintenance not working with quantum preimage (due to runtimes)

Fahrrader2023-02-21parent: #c80473f.patch.diff
in: master

9 files changed

modifiedpallets/maintenance/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/maintenance/src/benchmarking.rs
+++ b/pallets/maintenance/src/benchmarking.rs
@@ -23,6 +23,30 @@
 use codec::Encode;
 use sp_std::vec;
 
+#[cfg(not(feature = "governance"))]
+benchmarks! {
+	enable {
+	}: _(RawOrigin::Root)
+	verify {
+		ensure!(<Enabled<T>>::get(), "didn't enable the MM");
+	}
+
+	disable {
+		Maintenance::<T>::enable(RawOrigin::Root.into())?;
+	}: _(RawOrigin::Root)
+	verify {
+		ensure!(!<Enabled<T>>::get(), "didn't disable the MM");
+	}
+
+	execute_preimage {
+		let call_hash = RuntimeCall::<T>::set_storage { items: vec![] }.encode();
+		let hash = T::Preimages::note(call_hash.into())?;
+	}: _(RawOrigin::Root, hash)
+	verify {
+	}
+}
+
+#[cfg(feature = "governance")]
 benchmarks! {
 	enable {
 	}: _(RawOrigin::Root)
modifiedpallets/maintenance/src/lib.rsdiffbeforeafterboth
--- a/pallets/maintenance/src/lib.rs
+++ b/pallets/maintenance/src/lib.rs
@@ -28,6 +28,8 @@
 	use frame_support::{
 		dispatch::*,
 		pallet_prelude::*,
+	};
+	use frame_support::{
 		traits::{QueryPreimage, StorePreimage},
 	};
 	use frame_system::pallet_prelude::*;
@@ -105,20 +107,31 @@
 
 		#[pallet::call_index(2)]
 		#[pallet::weight(<T as Config>::WeightInfo::execute_preimage())]
-		pub fn execute_preimage(origin: OriginFor<T>, hash: H256) -> DispatchResult {
-			ensure_root(origin)?;
+		pub fn execute_preimage(_origin: OriginFor<T>, _hash: H256) -> DispatchResult {
+			#[cfg(feature = "governance")]
+			{
+				let origin = _origin;
+				let hash = _hash;
+				
+				ensure_root(origin)?;
 
-			let len = T::Preimages::len(&hash).ok_or(DispatchError::Unavailable)?;
-			let bounded = T::Preimages::pick::<<T as Config>::RuntimeCall>(hash, len);
-			let (call, _) =
-				T::Preimages::realize(&bounded).map_err(|_| DispatchError::Unavailable)?;
+				let len = T::Preimages::len(&hash).ok_or(DispatchError::Unavailable)?;
+				let bounded = T::Preimages::pick::<<T as Config>::RuntimeCall>(hash, len);
+				let (call, _) =
+					T::Preimages::realize(&bounded).map_err(|_| DispatchError::Unavailable)?;
 
-			let result = match call.dispatch(frame_system::RawOrigin::Root.into()) {
-				Ok(_) => Ok(()),
-				Err(error_and_info) => Err(error_and_info.error),
-			};
+				let result = match call.dispatch(frame_system::RawOrigin::Root.into()) {
+					Ok(_) => Ok(()),
+					Err(error_and_info) => Err(error_and_info.error),
+				};
 
-			result
+				result
+			}
+
+			#[cfg(not(feature = "governance"))]
+			{
+				Err(DispatchError::Unavailable)
+			}
 		}
 	}
 }
modifiedruntime/common/config/pallets/mod.rsdiffbeforeafterboth
--- a/runtime/common/config/pallets/mod.rs
+++ b/runtime/common/config/pallets/mod.rs
@@ -23,7 +23,7 @@
 		weights::CommonWeights,
 		RelayChainBlockNumberProvider,
 	},
-	Runtime, RuntimeEvent, RuntimeCall, RuntimeOrigin, Balances, Preimage,
+	Runtime, RuntimeEvent, RuntimeCall, RuntimeOrigin, Balances,
 };
 use frame_support::traits::{ConstU32, ConstU64};
 use up_common::{
@@ -47,8 +47,7 @@
 #[cfg(feature = "collator-selection")]
 pub mod collator_selection;
 
-// todo:governance replace the feature with governance
-#[cfg(feature = "collator-selection")]
+#[cfg(feature = "governance")]
 pub mod governance;
 
 parameter_types! {
@@ -129,6 +128,9 @@
 	type RuntimeEvent = RuntimeEvent;
 	type RuntimeOrigin = RuntimeOrigin;
 	type RuntimeCall = RuntimeCall;
-	type Preimages = Preimage;
+	#[cfg(feature = "governance")]
+	type Preimages = crate::Preimage;
+	#[cfg(not(feature = "governance"))]
+	type Preimages = ();
 	type WeightInfo = pallet_maintenance::weights::SubstrateWeight<Self>;
 }
modifiedruntime/common/construct_runtime.rsdiffbeforeafterboth
--- a/runtime/common/construct_runtime.rs
+++ b/runtime/common/construct_runtime.rs
@@ -56,8 +56,7 @@
                 #[cfg(feature = "collator-selection")]
                 Identity: pallet_identity::{Pallet, Call, Storage, Event<T>} = 40,
 
-                // todo:governance switch feature to governance
-                #[cfg(feature = "collator-selection")]
+                #[cfg(feature = "governance")]
                 Preimage: pallet_preimage::{Pallet, Call, Storage, Event<T>} = 41,
 
                 // XCM helpers.
modifiedruntime/common/maintenance.rsdiffbeforeafterboth
--- a/runtime/common/maintenance.rs
+++ b/runtime/common/maintenance.rs
@@ -86,8 +86,7 @@
 				| RuntimeCall::Session(_)
 				| RuntimeCall::Identity(_) => Err(TransactionValidityError::Invalid(InvalidTransaction::Call)),
 
-				// todo:governance switch the feature to governance
-				#[cfg(feature = "collator-selection")]
+				#[cfg(feature = "governance")]
 				RuntimeCall::Preimage(_) => Err(TransactionValidityError::Invalid(InvalidTransaction::Call)),
 
 				#[cfg(feature = "pallet-test-utils")]
modifiedruntime/common/runtime_apis.rsdiffbeforeafterboth
before · runtime/common/runtime_apis.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617#[macro_export]18macro_rules! dispatch_unique_runtime {19	($collection:ident.$method:ident($($name:ident),*) $($rest:tt)*) => {{20		let collection = <Runtime as pallet_common::Config>::CollectionDispatch::dispatch(<pallet_common::CollectionHandle<Runtime>>::try_get($collection)?);21		let dispatch = collection.as_dyn();2223		Ok::<_, DispatchError>(dispatch.$method($($name),*) $($rest)*)24	}};25}2627#[macro_export]28macro_rules! impl_common_runtime_apis {29    (30        $(31            #![custom_apis]3233            $($custom_apis:tt)+34        )?35    ) => {36        use sp_std::prelude::*;37        use sp_api::impl_runtime_apis;38        use sp_core::{crypto::KeyTypeId, OpaqueMetadata, H256, U256, H160, Bytes};39        use sp_runtime::{40            Permill,41            traits::Block as BlockT,42            transaction_validity::{TransactionSource, TransactionValidity},43            ApplyExtrinsicResult, DispatchError,44        };45        use fp_rpc::TransactionStatus;46        use pallet_transaction_payment::{47            FeeDetails, RuntimeDispatchInfo,48        };49        use pallet_evm::{50            Runner, account::CrossAccountId as _,51            Account as EVMAccount, FeeCalculator,52        };53        use runtime_common::{54            sponsoring::{SponsorshipPredict, UniqueSponsorshipPredict},55            dispatch::CollectionDispatch,56            config::ethereum::CrossAccountId,57        };58        use up_data_structs::*;596061        impl_runtime_apis! {62            $($($custom_apis)+)?6364            impl up_rpc::UniqueApi<Block, CrossAccountId, AccountId> for Runtime {65                fn account_tokens(collection: CollectionId, account: CrossAccountId) -> Result<Vec<TokenId>, DispatchError> {66                    dispatch_unique_runtime!(collection.account_tokens(account))67                }68                fn collection_tokens(collection: CollectionId) -> Result<Vec<TokenId>, DispatchError> {69                    dispatch_unique_runtime!(collection.collection_tokens())70                }71                fn token_exists(collection: CollectionId, token: TokenId) -> Result<bool, DispatchError> {72                    dispatch_unique_runtime!(collection.token_exists(token))73                }7475                fn token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>, DispatchError> {76                    dispatch_unique_runtime!(collection.token_owner(token).ok())77                }7879                fn token_owners(collection: CollectionId, token: TokenId) -> Result<Vec::<CrossAccountId>, DispatchError>  {80                   dispatch_unique_runtime!(collection.token_owners(token))81                }8283                fn topmost_token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>, DispatchError> {84                    let budget = up_data_structs::budget::Value::new(10);8586                    Ok(<pallet_structure::Pallet<Runtime>>::find_topmost_owner(collection, token, &budget)?)87                }88                fn token_children(collection: CollectionId, token: TokenId) -> Result<Vec<TokenChild>, DispatchError> {89                    Ok(<pallet_nonfungible::Pallet<Runtime>>::token_children_ids(collection, token))90                }91                fn collection_properties(92                    collection: CollectionId,93                    keys: Option<Vec<Vec<u8>>>94                ) -> Result<Vec<Property>, DispatchError> {95                    let keys = keys.map(96                        |keys| Common::bytes_keys_to_property_keys(keys)97                    ).transpose()?;9899                    Common::filter_collection_properties(collection, keys)100                }101102                fn token_properties(103                    collection: CollectionId,104                    token_id: TokenId,105                    keys: Option<Vec<Vec<u8>>>106                ) -> Result<Vec<Property>, DispatchError> {107                    let keys = keys.map(108                        |keys| Common::bytes_keys_to_property_keys(keys)109                    ).transpose()?;110111                    dispatch_unique_runtime!(collection.token_properties(token_id, keys))112                }113114                fn property_permissions(115                    collection: CollectionId,116                    keys: Option<Vec<Vec<u8>>>117                ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {118                    let keys = keys.map(119                        |keys| Common::bytes_keys_to_property_keys(keys)120                    ).transpose()?;121122                    Common::filter_property_permissions(collection, keys)123                }124125                fn token_data(126                    collection: CollectionId,127                    token_id: TokenId,128                    keys: Option<Vec<Vec<u8>>>129                ) -> Result<TokenData<CrossAccountId>, DispatchError> {130                    let token_data = TokenData {131                        properties: Self::token_properties(collection, token_id, keys)?,132                        owner: Self::token_owner(collection, token_id)?,133                        pieces: Self::total_pieces(collection, token_id)?.unwrap_or(0),134                    };135136                    Ok(token_data)137                }138139                fn total_supply(collection: CollectionId) -> Result<u32, DispatchError> {140                    dispatch_unique_runtime!(collection.total_supply())141                }142                fn account_balance(collection: CollectionId, account: CrossAccountId) -> Result<u32, DispatchError> {143                    dispatch_unique_runtime!(collection.account_balance(account))144                }145                fn balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<u128, DispatchError> {146                    dispatch_unique_runtime!(collection.balance(account, token))147                }148                fn allowance(149                    collection: CollectionId,150                    sender: CrossAccountId,151                    spender: CrossAccountId,152                    token: TokenId,153                ) -> Result<u128, DispatchError> {154                    dispatch_unique_runtime!(collection.allowance(sender, spender, token))155                }156157                fn adminlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {158                    Ok(<pallet_common::Pallet<Runtime>>::adminlist(collection))159                }160                fn allowlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {161                    Ok(<pallet_common::Pallet<Runtime>>::allowlist(collection))162                }163                fn allowed(collection: CollectionId, user: CrossAccountId) -> Result<bool, DispatchError> {164                    Ok(<pallet_common::Pallet<Runtime>>::allowed(collection, user))165                }166                fn last_token_id(collection: CollectionId) -> Result<TokenId, DispatchError> {167                    dispatch_unique_runtime!(collection.last_token_id())168                }169                fn collection_by_id(collection: CollectionId) -> Result<Option<RpcCollection<AccountId>>, DispatchError> {170                    Ok(<pallet_common::Pallet<Runtime>>::rpc_collection(collection))171                }172                fn collection_stats() -> Result<CollectionStats, DispatchError> {173                    Ok(<pallet_common::Pallet<Runtime>>::collection_stats())174                }175                fn next_sponsored(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<Option<u64>, DispatchError> {176                    Ok(<UniqueSponsorshipPredict<Runtime> as SponsorshipPredict<Runtime>>::predict(177                        collection,178                        account,179                        token180                    ))181                }182183                fn effective_collection_limits(collection: CollectionId) -> Result<Option<CollectionLimits>, DispatchError> {184                    Ok(<pallet_common::Pallet<Runtime>>::effective_collection_limits(collection))185                }186187                fn total_pieces(collection: CollectionId, token_id: TokenId) -> Result<Option<u128>, DispatchError> {188                    dispatch_unique_runtime!(collection.total_pieces(token_id))189                }190191		        fn allowance_for_all(collection: CollectionId, owner: CrossAccountId, operator: CrossAccountId) -> Result<bool, DispatchError> {192                    dispatch_unique_runtime!(collection.allowance_for_all(owner, operator))193                }194            }195196            impl app_promotion_rpc::AppPromotionApi<Block, BlockNumber, CrossAccountId, AccountId> for Runtime {197                #[allow(unused_variables)]198                fn total_staked(staker: Option<CrossAccountId>) -> Result<u128, DispatchError> {199                    #[cfg(not(feature = "app-promotion"))]200                    return unsupported!();201202                    #[cfg(feature = "app-promotion")]203                    return Ok(<pallet_app_promotion::Pallet<Runtime>>::cross_id_total_staked(staker).unwrap_or_default());204                }205206                #[allow(unused_variables)]207                fn total_staked_per_block(staker: CrossAccountId) -> Result<Vec<(BlockNumber, u128)>, DispatchError> {208                    #[cfg(not(feature = "app-promotion"))]209                    return unsupported!();210211                    #[cfg(feature = "app-promotion")]212                    return Ok(<pallet_app_promotion::Pallet<Runtime>>::cross_id_total_staked_per_block(staker));213                }214215                #[allow(unused_variables)]216                fn pending_unstake(staker: Option<CrossAccountId>) -> Result<u128, DispatchError> {217                    #[cfg(not(feature = "app-promotion"))]218                    return unsupported!();219220                    #[cfg(feature = "app-promotion")]221                    return Ok(<pallet_app_promotion::Pallet<Runtime>>::cross_id_pending_unstake(staker));222                }223224                #[allow(unused_variables)]225                fn pending_unstake_per_block(staker: CrossAccountId) -> Result<Vec<(BlockNumber, u128)>, DispatchError> {226                    #[cfg(not(feature = "app-promotion"))]227                    return unsupported!();228229                    #[cfg(feature = "app-promotion")]230                    return Ok(<pallet_app_promotion::Pallet<Runtime>>::cross_id_pending_unstake_per_block(staker))231                }232            }233234            impl sp_api::Core<Block> for Runtime {235                fn version() -> RuntimeVersion {236                    VERSION237                }238239                fn execute_block(block: Block) {240                    Executive::execute_block(block)241                }242243                fn initialize_block(header: &<Block as BlockT>::Header) {244                    Executive::initialize_block(header)245                }246            }247248            impl sp_api::Metadata<Block> for Runtime {249                fn metadata() -> OpaqueMetadata {250                    OpaqueMetadata::new(Runtime::metadata().into())251                }252            }253254            impl sp_block_builder::BlockBuilder<Block> for Runtime {255                fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {256                    Executive::apply_extrinsic(extrinsic)257                }258259                fn finalize_block() -> <Block as BlockT>::Header {260                    Executive::finalize_block()261                }262263                fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {264                    data.create_extrinsics()265                }266267                fn check_inherents(268                    block: Block,269                    data: sp_inherents::InherentData,270                ) -> sp_inherents::CheckInherentsResult {271                    data.check_extrinsics(&block)272                }273274                // fn random_seed() -> <Block as BlockT>::Hash {275                //     RandomnessCollectiveFlip::random_seed().0276                // }277            }278279            impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {280                fn validate_transaction(281                    source: TransactionSource,282                    tx: <Block as BlockT>::Extrinsic,283                    hash: <Block as BlockT>::Hash,284                ) -> TransactionValidity {285                    Executive::validate_transaction(source, tx, hash)286                }287            }288289            impl sp_offchain::OffchainWorkerApi<Block> for Runtime {290                fn offchain_worker(header: &<Block as BlockT>::Header) {291                    Executive::offchain_worker(header)292                }293            }294295            impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {296                fn chain_id() -> u64 {297                    <Runtime as pallet_evm::Config>::ChainId::get()298                }299300                fn account_basic(address: H160) -> EVMAccount {301                    let (account, _) = EVM::account_basic(&address);302                    account303                }304305                fn gas_price() -> U256 {306                    let (price, _) = <Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price();307                    price308                }309310                fn account_code_at(address: H160) -> Vec<u8> {311                    use pallet_evm::OnMethodCall;312                    <Runtime as pallet_evm::Config>::OnMethodCall::get_code(&address)313                        .unwrap_or_else(|| EVM::account_codes(address))314                }315316                fn author() -> H160 {317                    <pallet_evm::Pallet<Runtime>>::find_author()318                }319320                fn storage_at(address: H160, index: U256) -> H256 {321                    let mut tmp = [0u8; 32];322                    index.to_big_endian(&mut tmp);323                    EVM::account_storages(address, H256::from_slice(&tmp[..]))324                }325326                #[allow(clippy::redundant_closure)]327                fn call(328                    from: H160,329                    to: H160,330                    data: Vec<u8>,331                    value: U256,332                    gas_limit: U256,333                    max_fee_per_gas: Option<U256>,334                    max_priority_fee_per_gas: Option<U256>,335                    nonce: Option<U256>,336                    estimate: bool,337                    access_list: Option<Vec<(H160, Vec<H256>)>>,338                ) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {339                    let config = if estimate {340                        let mut config = <Runtime as pallet_evm::Config>::config().clone();341                        config.estimate = true;342                        Some(config)343                    } else {344                        None345                    };346347                    let is_transactional = false;348                    let validate = false;349                    <Runtime as pallet_evm::Config>::Runner::call(350                        CrossAccountId::from_eth(from),351                        to,352                        data,353                        value,354                        gas_limit.low_u64(),355                        max_fee_per_gas,356                        max_priority_fee_per_gas,357                        nonce,358                        access_list.unwrap_or_default(),359                        is_transactional,360                        validate,361                        config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),362                    ).map_err(|err| err.error.into())363                }364365                #[allow(clippy::redundant_closure)]366                fn create(367                    from: H160,368                    data: Vec<u8>,369                    value: U256,370                    gas_limit: U256,371                    max_fee_per_gas: Option<U256>,372                    max_priority_fee_per_gas: Option<U256>,373                    nonce: Option<U256>,374                    estimate: bool,375                    access_list: Option<Vec<(H160, Vec<H256>)>>,376                ) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {377                    let config = if estimate {378                        let mut config = <Runtime as pallet_evm::Config>::config().clone();379                        config.estimate = true;380                        Some(config)381                    } else {382                        None383                    };384385                    let is_transactional = false;386                    let validate = false;387                    <Runtime as pallet_evm::Config>::Runner::create(388                        CrossAccountId::from_eth(from),389                        data,390                        value,391                        gas_limit.low_u64(),392                        max_fee_per_gas,393                        max_priority_fee_per_gas,394                        nonce,395                        access_list.unwrap_or_default(),396                        is_transactional,397                        validate,398                        config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),399                    ).map_err(|err| err.error.into())400                }401402                fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {403                    Ethereum::current_transaction_statuses()404                }405406                fn current_block() -> Option<pallet_ethereum::Block> {407                    Ethereum::current_block()408                }409410                fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {411                    Ethereum::current_receipts()412                }413414                fn current_all() -> (415                    Option<pallet_ethereum::Block>,416                    Option<Vec<pallet_ethereum::Receipt>>,417                    Option<Vec<TransactionStatus>>418                ) {419                    (420                        Ethereum::current_block(),421                        Ethereum::current_receipts(),422                        Ethereum::current_transaction_statuses()423                    )424                }425426                fn extrinsic_filter(xts: Vec<<Block as sp_api::BlockT>::Extrinsic>) -> Vec<pallet_ethereum::Transaction> {427                    xts.into_iter().filter_map(|xt| match xt.0.function {428                        RuntimeCall::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction),429                        _ => None430                    }).collect()431                }432433                fn elasticity() -> Option<Permill> {434                    None435                }436437                fn gas_limit_multiplier_support() {}438            }439440            impl fp_rpc::ConvertTransactionRuntimeApi<Block> for Runtime {441                fn convert_transaction(transaction: pallet_ethereum::Transaction) -> <Block as BlockT>::Extrinsic  {442                    UncheckedExtrinsic::new_unsigned(443                        pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),444                    )445                }446            }447448            impl sp_session::SessionKeys<Block> for Runtime {449                fn decode_session_keys(450                    encoded: Vec<u8>,451                ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {452                    SessionKeys::decode_into_raw_public_keys(&encoded)453                }454455                fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {456                    SessionKeys::generate(seed)457                }458            }459460            impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {461                fn slot_duration() -> sp_consensus_aura::SlotDuration {462                    sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())463                }464465                fn authorities() -> Vec<AuraId> {466                    Aura::authorities().to_vec()467                }468            }469470            impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {471                fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {472                    ParachainSystem::collect_collation_info(header)473                }474            }475476            impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {477                fn account_nonce(account: AccountId) -> Index {478                    System::account_nonce(account)479                }480            }481482            impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {483                fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {484                    TransactionPayment::query_info(uxt, len)485                }486                fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {487                    TransactionPayment::query_fee_details(uxt, len)488                }489            }490491            /*492            impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber, Hash>493                for Runtime494            {495                fn call(496                    origin: AccountId,497                    dest: AccountId,498                    value: Balance,499                    gas_limit: u64,500                    input_data: Vec<u8>,501                ) -> pallet_contracts_primitives::ContractExecResult {502                    Contracts::bare_call(origin, dest, value, gas_limit, input_data, false)503                }504505                fn instantiate(506                    origin: AccountId,507                    endowment: Balance,508                    gas_limit: u64,509                    code: pallet_contracts_primitives::Code<Hash>,510                    data: Vec<u8>,511                    salt: Vec<u8>,512                ) -> pallet_contracts_primitives::ContractInstantiateResult<AccountId, BlockNumber>513                {514                    Contracts::bare_instantiate(origin, endowment, gas_limit, code, data, salt, true, false)515                }516517                fn get_storage(518                    address: AccountId,519                    key: [u8; 32],520                ) -> pallet_contracts_primitives::GetStorageResult {521                    Contracts::get_storage(address, key)522                }523524                fn rent_projection(525                    address: AccountId,526                ) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {527                    Contracts::rent_projection(address)528                }529            }530            */531532            #[cfg(feature = "runtime-benchmarks")]533            impl frame_benchmarking::Benchmark<Block> for Runtime {534                fn benchmark_metadata(extra: bool) -> (535                    Vec<frame_benchmarking::BenchmarkList>,536                    Vec<frame_support::traits::StorageInfo>,537                ) {538                    use frame_benchmarking::{list_benchmark, Benchmarking, BenchmarkList};539                    use frame_support::traits::StorageInfoTrait;540541                    let mut list = Vec::<BenchmarkList>::new();542543                    list_benchmark!(list, extra, pallet_evm_migration, EvmMigration);544                    list_benchmark!(list, extra, pallet_common, Common);545                    list_benchmark!(list, extra, pallet_unique, Unique);546                    list_benchmark!(list, extra, pallet_structure, Structure);547                    list_benchmark!(list, extra, pallet_inflation, Inflation);548                    list_benchmark!(list, extra, pallet_configuration, Configuration);549550                    #[cfg(feature = "app-promotion")]551                    list_benchmark!(list, extra, pallet_app_promotion, AppPromotion);552553                    list_benchmark!(list, extra, pallet_fungible, Fungible);554                    list_benchmark!(list, extra, pallet_nonfungible, Nonfungible);555556                    #[cfg(feature = "refungible")]557                    list_benchmark!(list, extra, pallet_refungible, Refungible);558559                    #[cfg(feature = "scheduler")]560                    list_benchmark!(list, extra, pallet_unique_scheduler_v2, Scheduler);561562                    #[cfg(feature = "collator-selection")]563                    list_benchmark!(list, extra, pallet_collator_selection, CollatorSelection);564565                    #[cfg(feature = "collator-selection")]566                    list_benchmark!(list, extra, pallet_identity, Identity);567568                    // todo:governance switch feature to governance569                    #[cfg(feature = "collator-selection")]570                    list_benchmark!(list, extra, pallet_preimage, Preimage);571572                    #[cfg(feature = "foreign-assets")]573                    list_benchmark!(list, extra, pallet_foreign_assets, ForeignAssets);574575576                    // list_benchmark!(list, extra, pallet_evm_coder_substrate, EvmCoderSubstrate);577578                    let storage_info = AllPalletsWithSystem::storage_info();579580                    return (list, storage_info)581                }582583                fn dispatch_benchmark(584                    config: frame_benchmarking::BenchmarkConfig585                ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {586                    use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};587588                    let allowlist: Vec<TrackedStorageKey> = vec![589                        // Total Issuance590                        hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),591592                        // Block Number593                        hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),594                        // Execution Phase595                        hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),596                        // Event Count597                        hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),598                        // System Events599                        hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),600601                        // Evm CurrentLogs602                        hex_literal::hex!("1da53b775b270400e7e61ed5cbc5a146547f210cec367e9af919603343b9cb56").to_vec().into(),603604                        // Transactional depth605                        hex_literal::hex!("3a7472616e73616374696f6e5f6c6576656c3a").to_vec().into(),606                    ];607608                    let mut batches = Vec::<BenchmarkBatch>::new();609                    let params = (&config, &allowlist);610611                    add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);612                    add_benchmark!(params, batches, pallet_common, Common);613                    add_benchmark!(params, batches, pallet_unique, Unique);614                    add_benchmark!(params, batches, pallet_structure, Structure);615                    add_benchmark!(params, batches, pallet_inflation, Inflation);616                    add_benchmark!(params, batches, pallet_configuration, Configuration);617618                    #[cfg(feature = "app-promotion")]619                    add_benchmark!(params, batches, pallet_app_promotion, AppPromotion);620621                    add_benchmark!(params, batches, pallet_fungible, Fungible);622                    add_benchmark!(params, batches, pallet_nonfungible, Nonfungible);623624                    #[cfg(feature = "refungible")]625                    add_benchmark!(params, batches, pallet_refungible, Refungible);626627                    #[cfg(feature = "scheduler")]628                    add_benchmark!(params, batches, pallet_unique_scheduler_v2, Scheduler);629630                    #[cfg(feature = "collator-selection")]631                    add_benchmark!(params, batches, pallet_collator_selection, CollatorSelection);632633                    #[cfg(feature = "collator-selection")]634                    add_benchmark!(params, batches, pallet_identity, Identity);635636                    // todo:governance switch feature to governance637                    #[cfg(feature = "collator-selection")]638                    add_benchmark!(params, batches, pallet_preimage, Preimage);639640                    #[cfg(feature = "foreign-assets")]641                    add_benchmark!(params, batches, pallet_foreign_assets, ForeignAssets);642643                    // add_benchmark!(params, batches, pallet_evm_coder_substrate, EvmCoderSubstrate);644645                    if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }646                    Ok(batches)647                }648            }649650            impl up_pov_estimate_rpc::PovEstimateApi<Block> for Runtime {651                #[allow(unused_variables)]652                fn pov_estimate(uxt: Bytes) -> ApplyExtrinsicResult {653                    #[cfg(feature = "pov-estimate")]654                    {655                        use codec::Decode;656657                        let uxt_decode = <<Block as BlockT>::Extrinsic as Decode>::decode(&mut &*uxt)658                            .map_err(|_| DispatchError::Other("failed to decode the extrinsic"));659660                        let uxt = match uxt_decode {661                            Ok(uxt) => uxt,662                            Err(err) => return Ok(err.into()),663                        };664665                        Executive::apply_extrinsic(uxt)666                    }667668                    #[cfg(not(feature = "pov-estimate"))]669                    return Ok(unsupported!());670                }671            }672673            #[cfg(feature = "try-runtime")]674            impl frame_try_runtime::TryRuntime<Block> for Runtime {675                fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (frame_support::pallet_prelude::Weight, frame_support::pallet_prelude::Weight) {676                    log::info!("try-runtime::on_runtime_upgrade unique-chain.");677                    let weight = Executive::try_runtime_upgrade(checks).unwrap();678                    (weight, crate::config::substrate::RuntimeBlockWeights::get().max_block)679                }680681                fn execute_block(682                    block: Block,683                    state_root_check: bool,684                    signature_check: bool,685                    select: frame_try_runtime::TryStateSelect686                ) -> frame_support::pallet_prelude::Weight {687                    log::info!(688                        target: "node-runtime",689                        "try-runtime: executing block {:?} / root checks: {:?} / try-state-select: {:?}",690                        block.header.hash(),691                        state_root_check,692                        select,693                    );694695                    Executive::try_execute_block(block, state_root_check, signature_check, select).unwrap()696                }697            }698        }699    }700}
after · runtime/common/runtime_apis.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617#[macro_export]18macro_rules! dispatch_unique_runtime {19	($collection:ident.$method:ident($($name:ident),*) $($rest:tt)*) => {{20		let collection = <Runtime as pallet_common::Config>::CollectionDispatch::dispatch(<pallet_common::CollectionHandle<Runtime>>::try_get($collection)?);21		let dispatch = collection.as_dyn();2223		Ok::<_, DispatchError>(dispatch.$method($($name),*) $($rest)*)24	}};25}2627#[macro_export]28macro_rules! impl_common_runtime_apis {29    (30        $(31            #![custom_apis]3233            $($custom_apis:tt)+34        )?35    ) => {36        use sp_std::prelude::*;37        use sp_api::impl_runtime_apis;38        use sp_core::{crypto::KeyTypeId, OpaqueMetadata, H256, U256, H160, Bytes};39        use sp_runtime::{40            Permill,41            traits::Block as BlockT,42            transaction_validity::{TransactionSource, TransactionValidity},43            ApplyExtrinsicResult, DispatchError,44        };45        use fp_rpc::TransactionStatus;46        use pallet_transaction_payment::{47            FeeDetails, RuntimeDispatchInfo,48        };49        use pallet_evm::{50            Runner, account::CrossAccountId as _,51            Account as EVMAccount, FeeCalculator,52        };53        use runtime_common::{54            sponsoring::{SponsorshipPredict, UniqueSponsorshipPredict},55            dispatch::CollectionDispatch,56            config::ethereum::CrossAccountId,57        };58        use up_data_structs::*;596061        impl_runtime_apis! {62            $($($custom_apis)+)?6364            impl up_rpc::UniqueApi<Block, CrossAccountId, AccountId> for Runtime {65                fn account_tokens(collection: CollectionId, account: CrossAccountId) -> Result<Vec<TokenId>, DispatchError> {66                    dispatch_unique_runtime!(collection.account_tokens(account))67                }68                fn collection_tokens(collection: CollectionId) -> Result<Vec<TokenId>, DispatchError> {69                    dispatch_unique_runtime!(collection.collection_tokens())70                }71                fn token_exists(collection: CollectionId, token: TokenId) -> Result<bool, DispatchError> {72                    dispatch_unique_runtime!(collection.token_exists(token))73                }7475                fn token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>, DispatchError> {76                    dispatch_unique_runtime!(collection.token_owner(token).ok())77                }7879                fn token_owners(collection: CollectionId, token: TokenId) -> Result<Vec::<CrossAccountId>, DispatchError>  {80                   dispatch_unique_runtime!(collection.token_owners(token))81                }8283                fn topmost_token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>, DispatchError> {84                    let budget = up_data_structs::budget::Value::new(10);8586                    Ok(<pallet_structure::Pallet<Runtime>>::find_topmost_owner(collection, token, &budget)?)87                }88                fn token_children(collection: CollectionId, token: TokenId) -> Result<Vec<TokenChild>, DispatchError> {89                    Ok(<pallet_nonfungible::Pallet<Runtime>>::token_children_ids(collection, token))90                }91                fn collection_properties(92                    collection: CollectionId,93                    keys: Option<Vec<Vec<u8>>>94                ) -> Result<Vec<Property>, DispatchError> {95                    let keys = keys.map(96                        |keys| Common::bytes_keys_to_property_keys(keys)97                    ).transpose()?;9899                    Common::filter_collection_properties(collection, keys)100                }101102                fn token_properties(103                    collection: CollectionId,104                    token_id: TokenId,105                    keys: Option<Vec<Vec<u8>>>106                ) -> Result<Vec<Property>, DispatchError> {107                    let keys = keys.map(108                        |keys| Common::bytes_keys_to_property_keys(keys)109                    ).transpose()?;110111                    dispatch_unique_runtime!(collection.token_properties(token_id, keys))112                }113114                fn property_permissions(115                    collection: CollectionId,116                    keys: Option<Vec<Vec<u8>>>117                ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {118                    let keys = keys.map(119                        |keys| Common::bytes_keys_to_property_keys(keys)120                    ).transpose()?;121122                    Common::filter_property_permissions(collection, keys)123                }124125                fn token_data(126                    collection: CollectionId,127                    token_id: TokenId,128                    keys: Option<Vec<Vec<u8>>>129                ) -> Result<TokenData<CrossAccountId>, DispatchError> {130                    let token_data = TokenData {131                        properties: Self::token_properties(collection, token_id, keys)?,132                        owner: Self::token_owner(collection, token_id)?,133                        pieces: Self::total_pieces(collection, token_id)?.unwrap_or(0),134                    };135136                    Ok(token_data)137                }138139                fn total_supply(collection: CollectionId) -> Result<u32, DispatchError> {140                    dispatch_unique_runtime!(collection.total_supply())141                }142                fn account_balance(collection: CollectionId, account: CrossAccountId) -> Result<u32, DispatchError> {143                    dispatch_unique_runtime!(collection.account_balance(account))144                }145                fn balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<u128, DispatchError> {146                    dispatch_unique_runtime!(collection.balance(account, token))147                }148                fn allowance(149                    collection: CollectionId,150                    sender: CrossAccountId,151                    spender: CrossAccountId,152                    token: TokenId,153                ) -> Result<u128, DispatchError> {154                    dispatch_unique_runtime!(collection.allowance(sender, spender, token))155                }156157                fn adminlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {158                    Ok(<pallet_common::Pallet<Runtime>>::adminlist(collection))159                }160                fn allowlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {161                    Ok(<pallet_common::Pallet<Runtime>>::allowlist(collection))162                }163                fn allowed(collection: CollectionId, user: CrossAccountId) -> Result<bool, DispatchError> {164                    Ok(<pallet_common::Pallet<Runtime>>::allowed(collection, user))165                }166                fn last_token_id(collection: CollectionId) -> Result<TokenId, DispatchError> {167                    dispatch_unique_runtime!(collection.last_token_id())168                }169                fn collection_by_id(collection: CollectionId) -> Result<Option<RpcCollection<AccountId>>, DispatchError> {170                    Ok(<pallet_common::Pallet<Runtime>>::rpc_collection(collection))171                }172                fn collection_stats() -> Result<CollectionStats, DispatchError> {173                    Ok(<pallet_common::Pallet<Runtime>>::collection_stats())174                }175                fn next_sponsored(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<Option<u64>, DispatchError> {176                    Ok(<UniqueSponsorshipPredict<Runtime> as SponsorshipPredict<Runtime>>::predict(177                        collection,178                        account,179                        token180                    ))181                }182183                fn effective_collection_limits(collection: CollectionId) -> Result<Option<CollectionLimits>, DispatchError> {184                    Ok(<pallet_common::Pallet<Runtime>>::effective_collection_limits(collection))185                }186187                fn total_pieces(collection: CollectionId, token_id: TokenId) -> Result<Option<u128>, DispatchError> {188                    dispatch_unique_runtime!(collection.total_pieces(token_id))189                }190191		        fn allowance_for_all(collection: CollectionId, owner: CrossAccountId, operator: CrossAccountId) -> Result<bool, DispatchError> {192                    dispatch_unique_runtime!(collection.allowance_for_all(owner, operator))193                }194            }195196            impl app_promotion_rpc::AppPromotionApi<Block, BlockNumber, CrossAccountId, AccountId> for Runtime {197                #[allow(unused_variables)]198                fn total_staked(staker: Option<CrossAccountId>) -> Result<u128, DispatchError> {199                    #[cfg(not(feature = "app-promotion"))]200                    return unsupported!();201202                    #[cfg(feature = "app-promotion")]203                    return Ok(<pallet_app_promotion::Pallet<Runtime>>::cross_id_total_staked(staker).unwrap_or_default());204                }205206                #[allow(unused_variables)]207                fn total_staked_per_block(staker: CrossAccountId) -> Result<Vec<(BlockNumber, u128)>, DispatchError> {208                    #[cfg(not(feature = "app-promotion"))]209                    return unsupported!();210211                    #[cfg(feature = "app-promotion")]212                    return Ok(<pallet_app_promotion::Pallet<Runtime>>::cross_id_total_staked_per_block(staker));213                }214215                #[allow(unused_variables)]216                fn pending_unstake(staker: Option<CrossAccountId>) -> Result<u128, DispatchError> {217                    #[cfg(not(feature = "app-promotion"))]218                    return unsupported!();219220                    #[cfg(feature = "app-promotion")]221                    return Ok(<pallet_app_promotion::Pallet<Runtime>>::cross_id_pending_unstake(staker));222                }223224                #[allow(unused_variables)]225                fn pending_unstake_per_block(staker: CrossAccountId) -> Result<Vec<(BlockNumber, u128)>, DispatchError> {226                    #[cfg(not(feature = "app-promotion"))]227                    return unsupported!();228229                    #[cfg(feature = "app-promotion")]230                    return Ok(<pallet_app_promotion::Pallet<Runtime>>::cross_id_pending_unstake_per_block(staker))231                }232            }233234            impl sp_api::Core<Block> for Runtime {235                fn version() -> RuntimeVersion {236                    VERSION237                }238239                fn execute_block(block: Block) {240                    Executive::execute_block(block)241                }242243                fn initialize_block(header: &<Block as BlockT>::Header) {244                    Executive::initialize_block(header)245                }246            }247248            impl sp_api::Metadata<Block> for Runtime {249                fn metadata() -> OpaqueMetadata {250                    OpaqueMetadata::new(Runtime::metadata().into())251                }252            }253254            impl sp_block_builder::BlockBuilder<Block> for Runtime {255                fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {256                    Executive::apply_extrinsic(extrinsic)257                }258259                fn finalize_block() -> <Block as BlockT>::Header {260                    Executive::finalize_block()261                }262263                fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {264                    data.create_extrinsics()265                }266267                fn check_inherents(268                    block: Block,269                    data: sp_inherents::InherentData,270                ) -> sp_inherents::CheckInherentsResult {271                    data.check_extrinsics(&block)272                }273274                // fn random_seed() -> <Block as BlockT>::Hash {275                //     RandomnessCollectiveFlip::random_seed().0276                // }277            }278279            impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {280                fn validate_transaction(281                    source: TransactionSource,282                    tx: <Block as BlockT>::Extrinsic,283                    hash: <Block as BlockT>::Hash,284                ) -> TransactionValidity {285                    Executive::validate_transaction(source, tx, hash)286                }287            }288289            impl sp_offchain::OffchainWorkerApi<Block> for Runtime {290                fn offchain_worker(header: &<Block as BlockT>::Header) {291                    Executive::offchain_worker(header)292                }293            }294295            impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {296                fn chain_id() -> u64 {297                    <Runtime as pallet_evm::Config>::ChainId::get()298                }299300                fn account_basic(address: H160) -> EVMAccount {301                    let (account, _) = EVM::account_basic(&address);302                    account303                }304305                fn gas_price() -> U256 {306                    let (price, _) = <Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price();307                    price308                }309310                fn account_code_at(address: H160) -> Vec<u8> {311                    use pallet_evm::OnMethodCall;312                    <Runtime as pallet_evm::Config>::OnMethodCall::get_code(&address)313                        .unwrap_or_else(|| EVM::account_codes(address))314                }315316                fn author() -> H160 {317                    <pallet_evm::Pallet<Runtime>>::find_author()318                }319320                fn storage_at(address: H160, index: U256) -> H256 {321                    let mut tmp = [0u8; 32];322                    index.to_big_endian(&mut tmp);323                    EVM::account_storages(address, H256::from_slice(&tmp[..]))324                }325326                #[allow(clippy::redundant_closure)]327                fn call(328                    from: H160,329                    to: H160,330                    data: Vec<u8>,331                    value: U256,332                    gas_limit: U256,333                    max_fee_per_gas: Option<U256>,334                    max_priority_fee_per_gas: Option<U256>,335                    nonce: Option<U256>,336                    estimate: bool,337                    access_list: Option<Vec<(H160, Vec<H256>)>>,338                ) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {339                    let config = if estimate {340                        let mut config = <Runtime as pallet_evm::Config>::config().clone();341                        config.estimate = true;342                        Some(config)343                    } else {344                        None345                    };346347                    let is_transactional = false;348                    let validate = false;349                    <Runtime as pallet_evm::Config>::Runner::call(350                        CrossAccountId::from_eth(from),351                        to,352                        data,353                        value,354                        gas_limit.low_u64(),355                        max_fee_per_gas,356                        max_priority_fee_per_gas,357                        nonce,358                        access_list.unwrap_or_default(),359                        is_transactional,360                        validate,361                        config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),362                    ).map_err(|err| err.error.into())363                }364365                #[allow(clippy::redundant_closure)]366                fn create(367                    from: H160,368                    data: Vec<u8>,369                    value: U256,370                    gas_limit: U256,371                    max_fee_per_gas: Option<U256>,372                    max_priority_fee_per_gas: Option<U256>,373                    nonce: Option<U256>,374                    estimate: bool,375                    access_list: Option<Vec<(H160, Vec<H256>)>>,376                ) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {377                    let config = if estimate {378                        let mut config = <Runtime as pallet_evm::Config>::config().clone();379                        config.estimate = true;380                        Some(config)381                    } else {382                        None383                    };384385                    let is_transactional = false;386                    let validate = false;387                    <Runtime as pallet_evm::Config>::Runner::create(388                        CrossAccountId::from_eth(from),389                        data,390                        value,391                        gas_limit.low_u64(),392                        max_fee_per_gas,393                        max_priority_fee_per_gas,394                        nonce,395                        access_list.unwrap_or_default(),396                        is_transactional,397                        validate,398                        config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),399                    ).map_err(|err| err.error.into())400                }401402                fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {403                    Ethereum::current_transaction_statuses()404                }405406                fn current_block() -> Option<pallet_ethereum::Block> {407                    Ethereum::current_block()408                }409410                fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {411                    Ethereum::current_receipts()412                }413414                fn current_all() -> (415                    Option<pallet_ethereum::Block>,416                    Option<Vec<pallet_ethereum::Receipt>>,417                    Option<Vec<TransactionStatus>>418                ) {419                    (420                        Ethereum::current_block(),421                        Ethereum::current_receipts(),422                        Ethereum::current_transaction_statuses()423                    )424                }425426                fn extrinsic_filter(xts: Vec<<Block as sp_api::BlockT>::Extrinsic>) -> Vec<pallet_ethereum::Transaction> {427                    xts.into_iter().filter_map(|xt| match xt.0.function {428                        RuntimeCall::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction),429                        _ => None430                    }).collect()431                }432433                fn elasticity() -> Option<Permill> {434                    None435                }436437                fn gas_limit_multiplier_support() {}438            }439440            impl fp_rpc::ConvertTransactionRuntimeApi<Block> for Runtime {441                fn convert_transaction(transaction: pallet_ethereum::Transaction) -> <Block as BlockT>::Extrinsic  {442                    UncheckedExtrinsic::new_unsigned(443                        pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),444                    )445                }446            }447448            impl sp_session::SessionKeys<Block> for Runtime {449                fn decode_session_keys(450                    encoded: Vec<u8>,451                ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {452                    SessionKeys::decode_into_raw_public_keys(&encoded)453                }454455                fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {456                    SessionKeys::generate(seed)457                }458            }459460            impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {461                fn slot_duration() -> sp_consensus_aura::SlotDuration {462                    sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())463                }464465                fn authorities() -> Vec<AuraId> {466                    Aura::authorities().to_vec()467                }468            }469470            impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {471                fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {472                    ParachainSystem::collect_collation_info(header)473                }474            }475476            impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {477                fn account_nonce(account: AccountId) -> Index {478                    System::account_nonce(account)479                }480            }481482            impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {483                fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {484                    TransactionPayment::query_info(uxt, len)485                }486                fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {487                    TransactionPayment::query_fee_details(uxt, len)488                }489            }490491            /*492            impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber, Hash>493                for Runtime494            {495                fn call(496                    origin: AccountId,497                    dest: AccountId,498                    value: Balance,499                    gas_limit: u64,500                    input_data: Vec<u8>,501                ) -> pallet_contracts_primitives::ContractExecResult {502                    Contracts::bare_call(origin, dest, value, gas_limit, input_data, false)503                }504505                fn instantiate(506                    origin: AccountId,507                    endowment: Balance,508                    gas_limit: u64,509                    code: pallet_contracts_primitives::Code<Hash>,510                    data: Vec<u8>,511                    salt: Vec<u8>,512                ) -> pallet_contracts_primitives::ContractInstantiateResult<AccountId, BlockNumber>513                {514                    Contracts::bare_instantiate(origin, endowment, gas_limit, code, data, salt, true, false)515                }516517                fn get_storage(518                    address: AccountId,519                    key: [u8; 32],520                ) -> pallet_contracts_primitives::GetStorageResult {521                    Contracts::get_storage(address, key)522                }523524                fn rent_projection(525                    address: AccountId,526                ) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {527                    Contracts::rent_projection(address)528                }529            }530            */531532            #[cfg(feature = "runtime-benchmarks")]533            impl frame_benchmarking::Benchmark<Block> for Runtime {534                fn benchmark_metadata(extra: bool) -> (535                    Vec<frame_benchmarking::BenchmarkList>,536                    Vec<frame_support::traits::StorageInfo>,537                ) {538                    use frame_benchmarking::{list_benchmark, Benchmarking, BenchmarkList};539                    use frame_support::traits::StorageInfoTrait;540541                    let mut list = Vec::<BenchmarkList>::new();542543                    list_benchmark!(list, extra, pallet_evm_migration, EvmMigration);544                    list_benchmark!(list, extra, pallet_common, Common);545                    list_benchmark!(list, extra, pallet_unique, Unique);546                    list_benchmark!(list, extra, pallet_structure, Structure);547                    list_benchmark!(list, extra, pallet_inflation, Inflation);548                    list_benchmark!(list, extra, pallet_configuration, Configuration);549550                    #[cfg(feature = "app-promotion")]551                    list_benchmark!(list, extra, pallet_app_promotion, AppPromotion);552553                    list_benchmark!(list, extra, pallet_fungible, Fungible);554                    list_benchmark!(list, extra, pallet_nonfungible, Nonfungible);555556                    #[cfg(feature = "refungible")]557                    list_benchmark!(list, extra, pallet_refungible, Refungible);558559                    #[cfg(feature = "scheduler")]560                    list_benchmark!(list, extra, pallet_unique_scheduler_v2, Scheduler);561562                    #[cfg(feature = "collator-selection")]563                    list_benchmark!(list, extra, pallet_collator_selection, CollatorSelection);564565                    #[cfg(feature = "collator-selection")]566                    list_benchmark!(list, extra, pallet_identity, Identity);567568                    #[cfg(feature = "governance")]569                    list_benchmark!(list, extra, pallet_preimage, Preimage);570571                    #[cfg(feature = "foreign-assets")]572                    list_benchmark!(list, extra, pallet_foreign_assets, ForeignAssets);573574575                    // list_benchmark!(list, extra, pallet_evm_coder_substrate, EvmCoderSubstrate);576577                    let storage_info = AllPalletsWithSystem::storage_info();578579                    return (list, storage_info)580                }581582                fn dispatch_benchmark(583                    config: frame_benchmarking::BenchmarkConfig584                ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {585                    use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};586587                    let allowlist: Vec<TrackedStorageKey> = vec![588                        // Total Issuance589                        hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),590591                        // Block Number592                        hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),593                        // Execution Phase594                        hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),595                        // Event Count596                        hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),597                        // System Events598                        hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),599600                        // Evm CurrentLogs601                        hex_literal::hex!("1da53b775b270400e7e61ed5cbc5a146547f210cec367e9af919603343b9cb56").to_vec().into(),602603                        // Transactional depth604                        hex_literal::hex!("3a7472616e73616374696f6e5f6c6576656c3a").to_vec().into(),605                    ];606607                    let mut batches = Vec::<BenchmarkBatch>::new();608                    let params = (&config, &allowlist);609610                    add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);611                    add_benchmark!(params, batches, pallet_common, Common);612                    add_benchmark!(params, batches, pallet_unique, Unique);613                    add_benchmark!(params, batches, pallet_structure, Structure);614                    add_benchmark!(params, batches, pallet_inflation, Inflation);615                    add_benchmark!(params, batches, pallet_configuration, Configuration);616617                    #[cfg(feature = "app-promotion")]618                    add_benchmark!(params, batches, pallet_app_promotion, AppPromotion);619620                    add_benchmark!(params, batches, pallet_fungible, Fungible);621                    add_benchmark!(params, batches, pallet_nonfungible, Nonfungible);622623                    #[cfg(feature = "refungible")]624                    add_benchmark!(params, batches, pallet_refungible, Refungible);625626                    #[cfg(feature = "scheduler")]627                    add_benchmark!(params, batches, pallet_unique_scheduler_v2, Scheduler);628629                    #[cfg(feature = "collator-selection")]630                    add_benchmark!(params, batches, pallet_collator_selection, CollatorSelection);631632                    #[cfg(feature = "collator-selection")]633                    add_benchmark!(params, batches, pallet_identity, Identity);634635                    #[cfg(feature = "governance")]636                    add_benchmark!(params, batches, pallet_preimage, Preimage);637638                    #[cfg(feature = "foreign-assets")]639                    add_benchmark!(params, batches, pallet_foreign_assets, ForeignAssets);640641                    // add_benchmark!(params, batches, pallet_evm_coder_substrate, EvmCoderSubstrate);642643                    if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }644                    Ok(batches)645                }646            }647648            impl up_pov_estimate_rpc::PovEstimateApi<Block> for Runtime {649                #[allow(unused_variables)]650                fn pov_estimate(uxt: Bytes) -> ApplyExtrinsicResult {651                    #[cfg(feature = "pov-estimate")]652                    {653                        use codec::Decode;654655                        let uxt_decode = <<Block as BlockT>::Extrinsic as Decode>::decode(&mut &*uxt)656                            .map_err(|_| DispatchError::Other("failed to decode the extrinsic"));657658                        let uxt = match uxt_decode {659                            Ok(uxt) => uxt,660                            Err(err) => return Ok(err.into()),661                        };662663                        Executive::apply_extrinsic(uxt)664                    }665666                    #[cfg(not(feature = "pov-estimate"))]667                    return Ok(unsupported!());668                }669            }670671            #[cfg(feature = "try-runtime")]672            impl frame_try_runtime::TryRuntime<Block> for Runtime {673                fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (frame_support::pallet_prelude::Weight, frame_support::pallet_prelude::Weight) {674                    log::info!("try-runtime::on_runtime_upgrade unique-chain.");675                    let weight = Executive::try_runtime_upgrade(checks).unwrap();676                    (weight, crate::config::substrate::RuntimeBlockWeights::get().max_block)677                }678679                fn execute_block(680                    block: Block,681                    state_root_check: bool,682                    signature_check: bool,683                    select: frame_try_runtime::TryStateSelect684                ) -> frame_support::pallet_prelude::Weight {685                    log::info!(686                        target: "node-runtime",687                        "try-runtime: executing block {:?} / root checks: {:?} / try-state-select: {:?}",688                        block.header.hash(),689                        state_root_check,690                        select,691                    );692693                    Executive::try_execute_block(block, state_root_check, signature_check, select).unwrap()694                }695            }696        }697    }698}
modifiedruntime/opal/Cargo.tomldiffbeforeafterboth
--- a/runtime/opal/Cargo.toml
+++ b/runtime/opal/Cargo.toml
@@ -18,7 +18,7 @@
 [features]
 default = ['opal-runtime', 'std']
 limit-testing = ['pallet-unique/limit-testing', 'up-data-structs/limit-testing']
-opal-runtime = ['app-promotion', 'collator-selection', 'foreign-assets', 'pallet-test-utils', 'refungible']
+opal-runtime = ['app-promotion', 'collator-selection', 'foreign-assets', 'governance', 'pallet-test-utils', 'refungible']
 pov-estimate = []
 runtime-benchmarks = [
 	'cumulus-pallet-parachain-system/runtime-benchmarks',
@@ -191,6 +191,7 @@
 app-promotion = []
 collator-selection = []
 foreign-assets = []
+governance = []
 pallet-test-utils = []
 refungible = []
 scheduler = []
modifiedruntime/quartz/Cargo.tomldiffbeforeafterboth
--- a/runtime/quartz/Cargo.toml
+++ b/runtime/quartz/Cargo.toml
@@ -20,7 +20,7 @@
 default = ['quartz-runtime', 'std']
 limit-testing = ['pallet-unique/limit-testing', 'up-data-structs/limit-testing']
 pov-estimate = []
-quartz-runtime = ['app-promotion', 'collator-selection', 'foreign-assets', 'refungible']
+quartz-runtime = ['app-promotion', 'collator-selection', 'foreign-assets', 'governance', 'refungible']
 runtime-benchmarks = [
 	'cumulus-pallet-parachain-system/runtime-benchmarks',
 	'frame-benchmarking',
@@ -184,6 +184,7 @@
 app-promotion = []
 collator-selection = []
 foreign-assets = []
+governance = []
 refungible = []
 scheduler = []
 
modifiedruntime/unique/Cargo.tomldiffbeforeafterboth
--- a/runtime/unique/Cargo.toml
+++ b/runtime/unique/Cargo.toml
@@ -183,6 +183,7 @@
 app-promotion = []
 collator-selection = []
 foreign-assets = []
+governance = []
 refungible = []
 scheduler = []