1234567891011121314151617#[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 275 276 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 492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532 #[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);570571 list_benchmark!(list, extra, pallet_maintenance, Maintenance);572573 574575 let storage_info = AllPalletsWithSystem::storage_info();576577 return (list, storage_info)578 }579580 fn dispatch_benchmark(581 config: frame_benchmarking::BenchmarkConfig582 ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {583 use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};584585 let allowlist: Vec<TrackedStorageKey> = vec![586 587 hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),588589 590 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),591 592 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),593 594 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),595 596 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),597598 599 hex_literal::hex!("1da53b775b270400e7e61ed5cbc5a146547f210cec367e9af919603343b9cb56").to_vec().into(),600601 602 hex_literal::hex!("3a7472616e73616374696f6e5f6c6576656c3a").to_vec().into(),603 ];604605 let mut batches = Vec::<BenchmarkBatch>::new();606 let params = (&config, &allowlist);607608 add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);609 add_benchmark!(params, batches, pallet_common, Common);610 add_benchmark!(params, batches, pallet_unique, Unique);611 add_benchmark!(params, batches, pallet_structure, Structure);612 add_benchmark!(params, batches, pallet_inflation, Inflation);613 add_benchmark!(params, batches, pallet_configuration, Configuration);614615 #[cfg(feature = "app-promotion")]616 add_benchmark!(params, batches, pallet_app_promotion, AppPromotion);617618 add_benchmark!(params, batches, pallet_fungible, Fungible);619 add_benchmark!(params, batches, pallet_nonfungible, Nonfungible);620621 #[cfg(feature = "refungible")]622 add_benchmark!(params, batches, pallet_refungible, Refungible);623624 #[cfg(feature = "scheduler")]625 add_benchmark!(params, batches, pallet_unique_scheduler_v2, Scheduler);626627 #[cfg(feature = "collator-selection")]628 add_benchmark!(params, batches, pallet_collator_selection, CollatorSelection);629630 #[cfg(feature = "collator-selection")]631 add_benchmark!(params, batches, pallet_identity, Identity);632633 #[cfg(feature = "foreign-assets")]634 add_benchmark!(params, batches, pallet_foreign_assets, ForeignAssets);635636 add_benchmark!(params, batches, pallet_maintenance, Maintenance);637638 639640 if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }641 Ok(batches)642 }643 }644645 impl up_pov_estimate_rpc::PovEstimateApi<Block> for Runtime {646 #[allow(unused_variables)]647 fn pov_estimate(uxt: Bytes) -> ApplyExtrinsicResult {648 #[cfg(feature = "pov-estimate")]649 {650 use codec::Decode;651652 let uxt_decode = <<Block as BlockT>::Extrinsic as Decode>::decode(&mut &*uxt)653 .map_err(|_| DispatchError::Other("failed to decode the extrinsic"));654655 let uxt = match uxt_decode {656 Ok(uxt) => uxt,657 Err(err) => return Ok(err.into()),658 };659660 Executive::apply_extrinsic(uxt)661 }662663 #[cfg(not(feature = "pov-estimate"))]664 return Ok(unsupported!());665 }666 }667668 #[cfg(feature = "try-runtime")]669 impl frame_try_runtime::TryRuntime<Block> for Runtime {670 fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (frame_support::pallet_prelude::Weight, frame_support::pallet_prelude::Weight) {671 log::info!("try-runtime::on_runtime_upgrade unique-chain.");672 let weight = Executive::try_runtime_upgrade(checks).unwrap();673 (weight, crate::config::substrate::RuntimeBlockWeights::get().max_block)674 }675676 fn execute_block(677 block: Block,678 state_root_check: bool,679 signature_check: bool,680 select: frame_try_runtime::TryStateSelect681 ) -> frame_support::pallet_prelude::Weight {682 log::info!(683 target: "node-runtime",684 "try-runtime: executing block {:?} / root checks: {:?} / try-state-select: {:?}",685 block.header.hash(),686 state_root_check,687 select,688 );689690 Executive::try_execute_block(block, state_root_check, signature_check, select).unwrap()691 }692 }693 }694 }695}