difftreelog
fix(preimage-execution) introduce weight expectation + adjust benchmarks + new tests
in: master
6 files changed
pallets/maintenance/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/maintenance/src/benchmarking.rs
+++ b/pallets/maintenance/src/benchmarking.rs
@@ -19,7 +19,7 @@
use frame_benchmarking::benchmarks;
use frame_system::{Call as RuntimeCall, RawOrigin};
-use frame_support::{ensure, traits::StorePreimage};
+use frame_support::{ensure, pallet_prelude::Weight, traits::StorePreimage};
use codec::Encode;
use sp_std::vec;
@@ -40,7 +40,7 @@
execute_preimage {
let call_hash = RuntimeCall::<T>::set_storage { items: vec![] }.encode();
let hash = T::Preimages::note(call_hash.into())?;
- }: _(RawOrigin::Root, hash)
+ }: _(RawOrigin::Root, hash, None, Weight::from_parts(100000000000, 100000000000))
verify {
}
}
pallets/maintenance/src/lib.rsdiffbeforeafterboth--- a/pallets/maintenance/src/lib.rs
+++ b/pallets/maintenance/src/lib.rs
@@ -104,30 +104,48 @@
#[pallet::call_index(2)]
#[pallet::weight(<T as Config>::WeightInfo::execute_preimage())]
- pub fn execute_preimage(_origin: OriginFor<T>, _hash: H256) -> DispatchResult {
- #[cfg(feature = "preimage")]
- {
- let origin = _origin;
- let hash = _hash;
+ pub fn execute_preimage(
+ origin: OriginFor<T>,
+ hash: H256,
+ preimage_length: Option<u32>,
+ weight_bound: Weight,
+ ) -> DispatchResultWithPostInfo {
+ use codec::Decode;
- ensure_root(origin)?;
+ 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 data = T::Preimages::fetch(&hash, preimage_length)?;
+ weight_bound.set_proof_size(
+ weight_bound
+ .proof_size()
+ .checked_sub(
+ data.len()
+ .try_into()
+ .map_err(|_| DispatchError::Corruption)?,
+ )
+ .ok_or(DispatchError::Exhausted)?,
+ );
- let result = match call.dispatch(frame_system::RawOrigin::Root.into()) {
- Ok(_) => Ok(()),
- Err(error_and_info) => Err(error_and_info.error),
- };
+ let call = <T as Config>::RuntimeCall::decode(&mut &data[..])
+ .map_err(|_| DispatchError::Corruption)?;
- result
- }
+ ensure!(
+ call.get_dispatch_info().weight.all_lte(weight_bound),
+ DispatchError::Exhausted
+ );
- #[cfg(not(feature = "preimage"))]
- {
- Err(DispatchError::Unavailable)
+ match call.dispatch(frame_system::RawOrigin::Root.into()) {
+ Ok(post_info) => Ok(PostDispatchInfo {
+ actual_weight: post_info.actual_weight,
+ pays_fee: Pays::No,
+ }),
+ Err(error_and_info) => Err(DispatchErrorWithPostInfo {
+ post_info: PostDispatchInfo {
+ actual_weight: error_and_info.post_info.actual_weight,
+ pays_fee: Pays::No,
+ },
+ error: error_and_info.error,
+ }),
}
}
}
runtime/common/config/pallets/preimage.rsdiffbeforeafterboth--- a/runtime/common/config/pallets/preimage.rs
+++ b/runtime/common/config/pallets/preimage.rs
@@ -20,8 +20,7 @@
use up_common::constants::*;
parameter_types! {
- pub PreimageBaseDeposit: Balance = 1000 * UNIQUE; // deposit(2, 64);
- // pub PreimageByteDeposit: Balance = 1 * CENTIUNIQUE; // deposit(0, 1);
+ pub PreimageBaseDeposit: Balance = 1000 * UNIQUE;
}
impl pallet_preimage::Config for Runtime {
runtime/common/runtime_apis.rsdiffbeforeafterboth1// 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 = "preimage")]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 = "preimage")]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}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 = "foreign-assets")]569 list_benchmark!(list, extra, pallet_foreign_assets, ForeignAssets);570571572 // list_benchmark!(list, extra, pallet_evm_coder_substrate, EvmCoderSubstrate);573574 let storage_info = AllPalletsWithSystem::storage_info();575576 return (list, storage_info)577 }578579 fn dispatch_benchmark(580 config: frame_benchmarking::BenchmarkConfig581 ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {582 use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};583584 let allowlist: Vec<TrackedStorageKey> = vec![585 // Total Issuance586 hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),587588 // Block Number589 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),590 // Execution Phase591 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),592 // Event Count593 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),594 // System Events595 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),596597 // Evm CurrentLogs598 hex_literal::hex!("1da53b775b270400e7e61ed5cbc5a146547f210cec367e9af919603343b9cb56").to_vec().into(),599600 // Transactional depth601 hex_literal::hex!("3a7472616e73616374696f6e5f6c6576656c3a").to_vec().into(),602 ];603604 let mut batches = Vec::<BenchmarkBatch>::new();605 let params = (&config, &allowlist);606607 add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);608 add_benchmark!(params, batches, pallet_common, Common);609 add_benchmark!(params, batches, pallet_unique, Unique);610 add_benchmark!(params, batches, pallet_structure, Structure);611 add_benchmark!(params, batches, pallet_inflation, Inflation);612 add_benchmark!(params, batches, pallet_configuration, Configuration);613614 #[cfg(feature = "app-promotion")]615 add_benchmark!(params, batches, pallet_app_promotion, AppPromotion);616617 add_benchmark!(params, batches, pallet_fungible, Fungible);618 add_benchmark!(params, batches, pallet_nonfungible, Nonfungible);619620 #[cfg(feature = "refungible")]621 add_benchmark!(params, batches, pallet_refungible, Refungible);622623 #[cfg(feature = "scheduler")]624 add_benchmark!(params, batches, pallet_unique_scheduler_v2, Scheduler);625626 #[cfg(feature = "collator-selection")]627 add_benchmark!(params, batches, pallet_collator_selection, CollatorSelection);628629 #[cfg(feature = "collator-selection")]630 add_benchmark!(params, batches, pallet_identity, Identity);631632 #[cfg(feature = "foreign-assets")]633 add_benchmark!(params, batches, pallet_foreign_assets, ForeignAssets);634635 // add_benchmark!(params, batches, pallet_evm_coder_substrate, EvmCoderSubstrate);636637 if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }638 Ok(batches)639 }640 }641642 impl up_pov_estimate_rpc::PovEstimateApi<Block> for Runtime {643 #[allow(unused_variables)]644 fn pov_estimate(uxt: Bytes) -> ApplyExtrinsicResult {645 #[cfg(feature = "pov-estimate")]646 {647 use codec::Decode;648649 let uxt_decode = <<Block as BlockT>::Extrinsic as Decode>::decode(&mut &*uxt)650 .map_err(|_| DispatchError::Other("failed to decode the extrinsic"));651652 let uxt = match uxt_decode {653 Ok(uxt) => uxt,654 Err(err) => return Ok(err.into()),655 };656657 Executive::apply_extrinsic(uxt)658 }659660 #[cfg(not(feature = "pov-estimate"))]661 return Ok(unsupported!());662 }663 }664665 #[cfg(feature = "try-runtime")]666 impl frame_try_runtime::TryRuntime<Block> for Runtime {667 fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (frame_support::pallet_prelude::Weight, frame_support::pallet_prelude::Weight) {668 log::info!("try-runtime::on_runtime_upgrade unique-chain.");669 let weight = Executive::try_runtime_upgrade(checks).unwrap();670 (weight, crate::config::substrate::RuntimeBlockWeights::get().max_block)671 }672673 fn execute_block(674 block: Block,675 state_root_check: bool,676 signature_check: bool,677 select: frame_try_runtime::TryStateSelect678 ) -> frame_support::pallet_prelude::Weight {679 log::info!(680 target: "node-runtime",681 "try-runtime: executing block {:?} / root checks: {:?} / try-state-select: {:?}",682 block.header.hash(),683 state_root_check,684 select,685 );686687 Executive::try_execute_block(block, state_root_check, signature_check, select).unwrap()688 }689 }690 }691 }692}tests/src/maintenance.seqtest.tsdiffbeforeafterboth--- a/tests/src/maintenance.seqtest.ts
+++ b/tests/src/maintenance.seqtest.ts
@@ -18,6 +18,7 @@
import {ApiPromise} from '@polkadot/api';
import {expect, itSched, itSub, Pallets, requirePalletsOrSkip, usingPlaygrounds} from './util';
import {itEth} from './eth/util';
+import {UniqueHelper} from './util/playgrounds/unique';
async function maintenanceEnabled(api: ApiPromise): Promise<boolean> {
return (await api.query.maintenance.enabled()).toJSON() as boolean;
@@ -280,6 +281,13 @@
describe('Preimage Execution', () => {
let preimageHash: string;
+ async function notePreimage(helper: UniqueHelper, preimage: any): Promise<string> {
+ const result = await helper.preimage.notePreimage(bob, preimage);
+ const events = result.result.events.filter(x => x.event.method === 'Noted' && x.event.section === 'preimage');
+ const preimageHash = events[0].event.data[0].toHuman();
+ return preimageHash;
+ }
+
before(async function() {
await usingPlaygrounds(async (helper) => {
requirePalletsOrSkip(this, helper, [Pallets.Preimage, Pallets.Maintenance]);
@@ -298,15 +306,14 @@
},
]);
const preimage = helper.constructApiCall('api.tx.identity.forceInsertIdentities', [randomIdentities]).method.toHex();
- const result = await helper.preimage.notePreimage(bob, preimage);
- const events = result.result.events.filter(x => x.event.method === 'Noted' && x.event.section === 'preimage');
- preimageHash = events[0].event.data[0].toHuman();
+ preimageHash = await notePreimage(helper, preimage);
});
});
itSub('Successfully executes call in a preimage', async ({helper}) => {
- const result = await expect(helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.executePreimage', [preimageHash]))
- .to.be.fulfilled;
+ const result = await expect(helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.executePreimage', [
+ preimageHash, null, {refTime: 10000000000, proofSize: 10000000000},
+ ])).to.be.fulfilled;
// preimage is executed, and an appropriate event is present
const events = result.result.events.filter((x: any) => x.event.method === 'IdentitiesInserted' && x.event.section === 'identity');
@@ -316,17 +323,37 @@
expect(await helper.preimage.getPreimageInfo(preimageHash)).to.have.property('unrequested');
});
+ itSub('Does not allow execution of a preimage that would fail', async ({helper}) => {
+ const [zeroAccount] = await helper.arrange.createAccounts([0n], superuser);
+
+ const preimage = helper.constructApiCall('api.tx.balances.forceTransfer', [
+ {Id: zeroAccount.address}, {Id: superuser.address}, 1000n,
+ ]).method.toHex();
+ const preimageHash = await notePreimage(helper, preimage);
+
+ await expect(helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.executePreimage', [
+ preimageHash, null, {refTime: 100000000000, proofSize: 100000000000},
+ ])).to.be.rejectedWith(/balances\.InsufficientBalance/);
+ });
+
itSub('Does not allow preimage execution with non-root', async ({helper}) => {
- await expect(helper.executeExtrinsic(bob, 'api.tx.maintenance.executePreimage', [preimageHash]))
- .to.be.rejectedWith(/BadOrigin/);
+ await expect(helper.executeExtrinsic(bob, 'api.tx.maintenance.executePreimage', [
+ preimageHash, null, {refTime: 100000000000, proofSize: 100000000000},
+ ])).to.be.rejectedWith(/BadOrigin/);
});
itSub('Does not allow execution of non-existent preimages', async ({helper}) => {
await expect(helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.executePreimage', [
- '0x1010101010101010101010101010101010101010101010101010101010101010',
+ '0x1010101010101010101010101010101010101010101010101010101010101010', null, {refTime: 100000000000, proofSize: 100000000000},
])).to.be.rejectedWith(/Unavailable/);
});
+ itSub('Does not allow preimage execution with less than minimum weights', async ({helper}) => {
+ await expect(helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.executePreimage', [
+ preimageHash, null, {refTime: 1000, proofSize: 1000},
+ ])).to.be.rejectedWith(/Exhausted/);
+ });
+
after(async function() {
await usingPlaygrounds(async (helper) => {
if (helper.fetchMissingPalletNames([Pallets.Preimage, Pallets.Maintenance]).length != 0) return;
tests/src/util/identitySetter.tsdiffbeforeafterboth--- a/tests/src/util/identitySetter.ts
+++ b/tests/src/util/identitySetter.ts
@@ -172,8 +172,6 @@
// identitiesToRemove.push((key as any).toHuman()[0]);
}
- console.log(identitiesToAdd[0][1]);
-
if (identitiesToRemove.length != 0)
await uploadPreimage(
helper,