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 frame_support::pallet_prelude::Weight;46 use fp_rpc::TransactionStatus;47 use pallet_transaction_payment::{48 FeeDetails, RuntimeDispatchInfo,49 };50 use pallet_evm::{51 Runner, account::CrossAccountId as _,52 Account as EVMAccount, FeeCalculator,53 };54 use runtime_common::{55 sponsoring::{SponsorshipPredict, UniqueSponsorshipPredict},56 dispatch::CollectionDispatch,57 config::ethereum::CrossAccountId,58 };59 use up_data_structs::*;606162 impl_runtime_apis! {63 $($($custom_apis)+)?6465 impl up_rpc::UniqueApi<Block, CrossAccountId, AccountId> for Runtime {66 fn account_tokens(collection: CollectionId, account: CrossAccountId) -> Result<Vec<TokenId>, DispatchError> {67 dispatch_unique_runtime!(collection.account_tokens(account))68 }69 fn collection_tokens(collection: CollectionId) -> Result<Vec<TokenId>, DispatchError> {70 dispatch_unique_runtime!(collection.collection_tokens())71 }72 fn token_exists(collection: CollectionId, token: TokenId) -> Result<bool, DispatchError> {73 dispatch_unique_runtime!(collection.token_exists(token))74 }7576 fn token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>, DispatchError> {77 dispatch_unique_runtime!(collection.token_owner(token).ok())78 }7980 fn token_owners(collection: CollectionId, token: TokenId) -> Result<Vec::<CrossAccountId>, DispatchError> {81 dispatch_unique_runtime!(collection.token_owners(token))82 }8384 fn topmost_token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>, DispatchError> {85 let budget = up_data_structs::budget::Value::new(10);8687 Ok(<pallet_structure::Pallet<Runtime>>::find_topmost_owner(collection, token, &budget)?)88 }89 fn token_children(collection: CollectionId, token: TokenId) -> Result<Vec<TokenChild>, DispatchError> {90 Ok(<pallet_nonfungible::Pallet<Runtime>>::token_children_ids(collection, token))91 }92 fn collection_properties(93 collection: CollectionId,94 keys: Option<Vec<Vec<u8>>>95 ) -> Result<Vec<Property>, DispatchError> {96 let keys = keys.map(97 |keys| Common::bytes_keys_to_property_keys(keys)98 ).transpose()?;99100 Common::filter_collection_properties(collection, keys)101 }102103 fn token_properties(104 collection: CollectionId,105 token_id: TokenId,106 keys: Option<Vec<Vec<u8>>>107 ) -> Result<Vec<Property>, DispatchError> {108 let keys = keys.map(109 |keys| Common::bytes_keys_to_property_keys(keys)110 ).transpose()?;111112 dispatch_unique_runtime!(collection.token_properties(token_id, keys))113 }114115 fn property_permissions(116 collection: CollectionId,117 keys: Option<Vec<Vec<u8>>>118 ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {119 let keys = keys.map(120 |keys| Common::bytes_keys_to_property_keys(keys)121 ).transpose()?;122123 Common::filter_property_permissions(collection, keys)124 }125126 fn token_data(127 collection: CollectionId,128 token_id: TokenId,129 keys: Option<Vec<Vec<u8>>>130 ) -> Result<TokenData<CrossAccountId>, DispatchError> {131 let token_data = TokenData {132 properties: Self::token_properties(collection, token_id, keys)?,133 owner: Self::token_owner(collection, token_id)?,134 pieces: Self::total_pieces(collection, token_id)?.unwrap_or(0),135 };136137 Ok(token_data)138 }139140 fn total_supply(collection: CollectionId) -> Result<u32, DispatchError> {141 dispatch_unique_runtime!(collection.total_supply())142 }143 fn account_balance(collection: CollectionId, account: CrossAccountId) -> Result<u32, DispatchError> {144 dispatch_unique_runtime!(collection.account_balance(account))145 }146 fn balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<u128, DispatchError> {147 dispatch_unique_runtime!(collection.balance(account, token))148 }149 fn allowance(150 collection: CollectionId,151 sender: CrossAccountId,152 spender: CrossAccountId,153 token: TokenId,154 ) -> Result<u128, DispatchError> {155 dispatch_unique_runtime!(collection.allowance(sender, spender, token))156 }157158 fn adminlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {159 Ok(<pallet_common::Pallet<Runtime>>::adminlist(collection))160 }161 fn allowlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {162 Ok(<pallet_common::Pallet<Runtime>>::allowlist(collection))163 }164 fn allowed(collection: CollectionId, user: CrossAccountId) -> Result<bool, DispatchError> {165 Ok(<pallet_common::Pallet<Runtime>>::allowed(collection, user))166 }167 fn last_token_id(collection: CollectionId) -> Result<TokenId, DispatchError> {168 dispatch_unique_runtime!(collection.last_token_id())169 }170 fn collection_by_id(collection: CollectionId) -> Result<Option<RpcCollection<AccountId>>, DispatchError> {171 Ok(<pallet_common::Pallet<Runtime>>::rpc_collection(collection))172 }173 fn collection_stats() -> Result<CollectionStats, DispatchError> {174 Ok(<pallet_common::Pallet<Runtime>>::collection_stats())175 }176 fn next_sponsored(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<Option<u64>, DispatchError> {177 Ok(<UniqueSponsorshipPredict<Runtime> as SponsorshipPredict<Runtime>>::predict(178 collection,179 account,180 token181 ))182 }183184 fn effective_collection_limits(collection: CollectionId) -> Result<Option<CollectionLimits>, DispatchError> {185 Ok(<pallet_common::Pallet<Runtime>>::effective_collection_limits(collection))186 }187188 fn total_pieces(collection: CollectionId, token_id: TokenId) -> Result<Option<u128>, DispatchError> {189 dispatch_unique_runtime!(collection.total_pieces(token_id))190 }191192 fn allowance_for_all(collection: CollectionId, owner: CrossAccountId, operator: CrossAccountId) -> Result<bool, DispatchError> {193 dispatch_unique_runtime!(collection.allowance_for_all(owner, operator))194 }195 }196197 impl app_promotion_rpc::AppPromotionApi<Block, BlockNumber, CrossAccountId, AccountId> for Runtime {198 #[allow(unused_variables)]199 fn total_staked(staker: Option<CrossAccountId>) -> Result<u128, DispatchError> {200 #[cfg(not(feature = "app-promotion"))]201 return unsupported!();202203 #[cfg(feature = "app-promotion")]204 return Ok(<pallet_app_promotion::Pallet<Runtime>>::cross_id_total_staked(staker).unwrap_or_default());205 }206207 #[allow(unused_variables)]208 fn total_staked_per_block(staker: CrossAccountId) -> Result<Vec<(BlockNumber, u128)>, DispatchError> {209 #[cfg(not(feature = "app-promotion"))]210 return unsupported!();211212 #[cfg(feature = "app-promotion")]213 return Ok(<pallet_app_promotion::Pallet<Runtime>>::cross_id_total_staked_per_block(staker));214 }215216 #[allow(unused_variables)]217 fn pending_unstake(staker: Option<CrossAccountId>) -> Result<u128, DispatchError> {218 #[cfg(not(feature = "app-promotion"))]219 return unsupported!();220221 #[cfg(feature = "app-promotion")]222 return Ok(<pallet_app_promotion::Pallet<Runtime>>::cross_id_pending_unstake(staker));223 }224225 #[allow(unused_variables)]226 fn pending_unstake_per_block(staker: CrossAccountId) -> Result<Vec<(BlockNumber, u128)>, DispatchError> {227 #[cfg(not(feature = "app-promotion"))]228 return unsupported!();229230 #[cfg(feature = "app-promotion")]231 return Ok(<pallet_app_promotion::Pallet<Runtime>>::cross_id_pending_unstake_per_block(staker))232 }233 }234235 impl sp_api::Core<Block> for Runtime {236 fn version() -> RuntimeVersion {237 VERSION238 }239240 fn execute_block(block: Block) {241 Executive::execute_block(block)242 }243244 fn initialize_block(header: &<Block as BlockT>::Header) {245 Executive::initialize_block(header)246 }247 }248249 impl sp_api::Metadata<Block> for Runtime {250 fn metadata() -> OpaqueMetadata {251 OpaqueMetadata::new(Runtime::metadata().into())252 }253 }254255 impl sp_block_builder::BlockBuilder<Block> for Runtime {256 fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {257 Executive::apply_extrinsic(extrinsic)258 }259260 fn finalize_block() -> <Block as BlockT>::Header {261 Executive::finalize_block()262 }263264 fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {265 data.create_extrinsics()266 }267268 fn check_inherents(269 block: Block,270 data: sp_inherents::InherentData,271 ) -> sp_inherents::CheckInherentsResult {272 data.check_extrinsics(&block)273 }274275 276 277 278 }279280 impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {281 fn validate_transaction(282 source: TransactionSource,283 tx: <Block as BlockT>::Extrinsic,284 hash: <Block as BlockT>::Hash,285 ) -> TransactionValidity {286 Executive::validate_transaction(source, tx, hash)287 }288 }289290 impl sp_offchain::OffchainWorkerApi<Block> for Runtime {291 fn offchain_worker(header: &<Block as BlockT>::Header) {292 Executive::offchain_worker(header)293 }294 }295296 impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {297 fn chain_id() -> u64 {298 <Runtime as pallet_evm::Config>::ChainId::get()299 }300301 fn account_basic(address: H160) -> EVMAccount {302 let (account, _) = EVM::account_basic(&address);303 account304 }305306 fn gas_price() -> U256 {307 let (price, _) = <Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price();308 price309 }310311 fn account_code_at(address: H160) -> Vec<u8> {312 use pallet_evm::OnMethodCall;313 <Runtime as pallet_evm::Config>::OnMethodCall::get_code(&address)314 .unwrap_or_else(|| EVM::account_codes(address))315 }316317 fn author() -> H160 {318 <pallet_evm::Pallet<Runtime>>::find_author()319 }320321 fn storage_at(address: H160, index: U256) -> H256 {322 let mut tmp = [0u8; 32];323 index.to_big_endian(&mut tmp);324 EVM::account_storages(address, H256::from_slice(&tmp[..]))325 }326327 #[allow(clippy::redundant_closure)]328 fn call(329 from: H160,330 to: H160,331 data: Vec<u8>,332 value: U256,333 gas_limit: U256,334 max_fee_per_gas: Option<U256>,335 max_priority_fee_per_gas: Option<U256>,336 nonce: Option<U256>,337 estimate: bool,338 access_list: Option<Vec<(H160, Vec<H256>)>>,339 ) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {340 let config = if estimate {341 let mut config = <Runtime as pallet_evm::Config>::config().clone();342 config.estimate = true;343 Some(config)344 } else {345 None346 };347348 let is_transactional = false;349 let validate = false;350 <Runtime as pallet_evm::Config>::Runner::call(351 CrossAccountId::from_eth(from),352 to,353 data,354 value,355 gas_limit.low_u64(),356 max_fee_per_gas,357 max_priority_fee_per_gas,358 nonce,359 access_list.unwrap_or_default(),360 is_transactional,361 validate,362 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),363 ).map_err(|err| err.error.into())364 }365366 #[allow(clippy::redundant_closure)]367 fn create(368 from: H160,369 data: Vec<u8>,370 value: U256,371 gas_limit: U256,372 max_fee_per_gas: Option<U256>,373 max_priority_fee_per_gas: Option<U256>,374 nonce: Option<U256>,375 estimate: bool,376 access_list: Option<Vec<(H160, Vec<H256>)>>,377 ) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {378 let config = if estimate {379 let mut config = <Runtime as pallet_evm::Config>::config().clone();380 config.estimate = true;381 Some(config)382 } else {383 None384 };385386 let is_transactional = false;387 let validate = false;388 <Runtime as pallet_evm::Config>::Runner::create(389 CrossAccountId::from_eth(from),390 data,391 value,392 gas_limit.low_u64(),393 max_fee_per_gas,394 max_priority_fee_per_gas,395 nonce,396 access_list.unwrap_or_default(),397 is_transactional,398 validate,399 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),400 ).map_err(|err| err.error.into())401 }402403 fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {404 Ethereum::current_transaction_statuses()405 }406407 fn current_block() -> Option<pallet_ethereum::Block> {408 Ethereum::current_block()409 }410411 fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {412 Ethereum::current_receipts()413 }414415 fn current_all() -> (416 Option<pallet_ethereum::Block>,417 Option<Vec<pallet_ethereum::Receipt>>,418 Option<Vec<TransactionStatus>>419 ) {420 (421 Ethereum::current_block(),422 Ethereum::current_receipts(),423 Ethereum::current_transaction_statuses()424 )425 }426427 fn extrinsic_filter(xts: Vec<<Block as sp_api::BlockT>::Extrinsic>) -> Vec<pallet_ethereum::Transaction> {428 xts.into_iter().filter_map(|xt| match xt.0.function {429 RuntimeCall::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction),430 _ => None431 }).collect()432 }433434 fn elasticity() -> Option<Permill> {435 None436 }437438 fn gas_limit_multiplier_support() {}439 }440441 impl fp_rpc::ConvertTransactionRuntimeApi<Block> for Runtime {442 fn convert_transaction(transaction: pallet_ethereum::Transaction) -> <Block as BlockT>::Extrinsic {443 UncheckedExtrinsic::new_unsigned(444 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),445 )446 }447 }448449 impl sp_session::SessionKeys<Block> for Runtime {450 fn decode_session_keys(451 encoded: Vec<u8>,452 ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {453 SessionKeys::decode_into_raw_public_keys(&encoded)454 }455456 fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {457 SessionKeys::generate(seed)458 }459 }460461 impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {462 fn slot_duration() -> sp_consensus_aura::SlotDuration {463 sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())464 }465466 fn authorities() -> Vec<AuraId> {467 Aura::authorities().to_vec()468 }469 }470471 impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {472 fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {473 ParachainSystem::collect_collation_info(header)474 }475 }476477 impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {478 fn account_nonce(account: AccountId) -> Index {479 System::account_nonce(account)480 }481 }482483 impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {484 fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {485 TransactionPayment::query_info(uxt, len)486 }487 fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {488 TransactionPayment::query_fee_details(uxt, len)489 }490 fn query_weight_to_fee(weight: Weight) -> Balance {491 TransactionPayment::weight_to_fee(weight)492 }493 fn query_length_to_fee(length: u32) -> Balance {494 TransactionPayment::length_to_fee(length)495 }496 }497498 499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539 #[cfg(feature = "runtime-benchmarks")]540 impl frame_benchmarking::Benchmark<Block> for Runtime {541 fn benchmark_metadata(extra: bool) -> (542 Vec<frame_benchmarking::BenchmarkList>,543 Vec<frame_support::traits::StorageInfo>,544 ) {545 use frame_benchmarking::{list_benchmark, Benchmarking, BenchmarkList};546 use frame_support::traits::StorageInfoTrait;547548 let mut list = Vec::<BenchmarkList>::new();549 list_benchmark!(list, extra, pallet_xcm, PolkadotXcm);550551 list_benchmark!(list, extra, pallet_evm_migration, EvmMigration);552 list_benchmark!(list, extra, pallet_common, Common);553 list_benchmark!(list, extra, pallet_unique, Unique);554 list_benchmark!(list, extra, pallet_structure, Structure);555 list_benchmark!(list, extra, pallet_inflation, Inflation);556 list_benchmark!(list, extra, pallet_configuration, Configuration);557558 #[cfg(feature = "app-promotion")]559 list_benchmark!(list, extra, pallet_app_promotion, AppPromotion);560561 list_benchmark!(list, extra, pallet_fungible, Fungible);562 list_benchmark!(list, extra, pallet_nonfungible, Nonfungible);563564 #[cfg(feature = "refungible")]565 list_benchmark!(list, extra, pallet_refungible, Refungible);566567 #[cfg(feature = "scheduler")]568 list_benchmark!(list, extra, pallet_unique_scheduler_v2, Scheduler);569570 #[cfg(feature = "collator-selection")]571 list_benchmark!(list, extra, pallet_collator_selection, CollatorSelection);572573 #[cfg(feature = "collator-selection")]574 list_benchmark!(list, extra, pallet_identity, Identity);575576 #[cfg(feature = "foreign-assets")]577 list_benchmark!(list, extra, pallet_foreign_assets, ForeignAssets);578579 list_benchmark!(list, extra, pallet_maintenance, Maintenance);580581 582583 let storage_info = AllPalletsWithSystem::storage_info();584585 return (list, storage_info)586 }587588 fn dispatch_benchmark(589 config: frame_benchmarking::BenchmarkConfig590 ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {591 use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};592593 let allowlist: Vec<TrackedStorageKey> = vec![594 595 hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),596597 598 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),599 600 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),601 602 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),603 604 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),605606 607 hex_literal::hex!("1da53b775b270400e7e61ed5cbc5a146547f210cec367e9af919603343b9cb56").to_vec().into(),608609 610 hex_literal::hex!("3a7472616e73616374696f6e5f6c6576656c3a").to_vec().into(),611 ];612613 let mut batches = Vec::<BenchmarkBatch>::new();614 let params = (&config, &allowlist);615 add_benchmark!(params, batches, pallet_xcm, PolkadotXcm);616617 add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);618 add_benchmark!(params, batches, pallet_common, Common);619 add_benchmark!(params, batches, pallet_unique, Unique);620 add_benchmark!(params, batches, pallet_structure, Structure);621 add_benchmark!(params, batches, pallet_inflation, Inflation);622 add_benchmark!(params, batches, pallet_configuration, Configuration);623624 #[cfg(feature = "app-promotion")]625 add_benchmark!(params, batches, pallet_app_promotion, AppPromotion);626627 add_benchmark!(params, batches, pallet_fungible, Fungible);628 add_benchmark!(params, batches, pallet_nonfungible, Nonfungible);629630 #[cfg(feature = "refungible")]631 add_benchmark!(params, batches, pallet_refungible, Refungible);632633 #[cfg(feature = "scheduler")]634 add_benchmark!(params, batches, pallet_unique_scheduler_v2, Scheduler);635636 #[cfg(feature = "collator-selection")]637 add_benchmark!(params, batches, pallet_collator_selection, CollatorSelection);638639 #[cfg(feature = "collator-selection")]640 add_benchmark!(params, batches, pallet_identity, Identity);641642 #[cfg(feature = "foreign-assets")]643 add_benchmark!(params, batches, pallet_foreign_assets, ForeignAssets);644645 add_benchmark!(params, batches, pallet_maintenance, Maintenance);646647 648649 if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }650 Ok(batches)651 }652 }653654 impl up_pov_estimate_rpc::PovEstimateApi<Block> for Runtime {655 #[allow(unused_variables)]656 fn pov_estimate(uxt: Bytes) -> ApplyExtrinsicResult {657 #[cfg(feature = "pov-estimate")]658 {659 use codec::Decode;660661 let uxt_decode = <<Block as BlockT>::Extrinsic as Decode>::decode(&mut &*uxt)662 .map_err(|_| DispatchError::Other("failed to decode the extrinsic"));663664 let uxt = match uxt_decode {665 Ok(uxt) => uxt,666 Err(err) => return Ok(err.into()),667 };668669 Executive::apply_extrinsic(uxt)670 }671672 #[cfg(not(feature = "pov-estimate"))]673 return Ok(unsupported!());674 }675 }676677 #[cfg(feature = "try-runtime")]678 impl frame_try_runtime::TryRuntime<Block> for Runtime {679 fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) {680 log::info!("try-runtime::on_runtime_upgrade unique-chain.");681 let weight = Executive::try_runtime_upgrade(checks).unwrap();682 (weight, crate::config::substrate::RuntimeBlockWeights::get().max_block)683 }684685 fn execute_block(686 block: Block,687 state_root_check: bool,688 signature_check: bool,689 select: frame_try_runtime::TryStateSelect690 ) -> Weight {691 log::info!(692 target: "node-runtime",693 "try-runtime: executing block {:?} / root checks: {:?} / try-state-select: {:?}",694 block.header.hash(),695 state_root_check,696 select,697 );698699 Executive::try_execute_block(block, state_root_check, signature_check, select).unwrap()700 }701 }702 }703 }704}