git.delta.rocks / unique-network / refs/commits / 3db00dc56ee4

difftreelog

source

runtime/common/src/runtime_apis.rs21.9 KiBsourcehistory
1#[macro_export]2macro_rules! impl_common_runtime_apis {3    (4        $(5            #![custom_apis]67            $($custom_apis:tt)+8        )?9    ) => {10        impl_runtime_apis! {11            $($($custom_apis)+)?1213            impl up_rpc::UniqueApi<Block, CrossAccountId, AccountId> for Runtime {14                fn account_tokens(collection: CollectionId, account: CrossAccountId) -> Result<Vec<TokenId>, DispatchError> {15                    dispatch_unique_runtime!(collection.account_tokens(account))16                }17                fn collection_tokens(collection: CollectionId) -> Result<Vec<TokenId>, DispatchError> {18                    dispatch_unique_runtime!(collection.collection_tokens())19                }20                fn token_exists(collection: CollectionId, token: TokenId) -> Result<bool, DispatchError> {21                    dispatch_unique_runtime!(collection.token_exists(token))22                }2324                fn token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>, DispatchError> {25                    dispatch_unique_runtime!(collection.token_owner(token))26                }27                fn topmost_token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>, DispatchError> {28                    let budget = up_data_structs::budget::Value::new(5);2930                    Ok(Some(<pallet_structure::Pallet<Runtime>>::find_topmost_owner(collection, token, &budget)?))31                }32                fn const_metadata(collection: CollectionId, token: TokenId) -> Result<Vec<u8>, DispatchError> {33                    dispatch_unique_runtime!(collection.const_metadata(token))34                }3536                fn collection_properties(37                    collection: CollectionId,38                    keys: Vec<Vec<u8>>39                ) -> Result<Vec<Property>, DispatchError> {40                    let keys = pallet_common::Pallet::<Runtime>::bytes_keys_to_property_keys(keys)?;4142                    pallet_common::Pallet::<Runtime>::filter_collection_properties(collection, keys)43                }4445                fn token_properties(46                    collection: CollectionId,47                    token_id: TokenId,48                    keys: Vec<Vec<u8>>49                ) -> Result<Vec<Property>, DispatchError> {50                    let keys = pallet_common::Pallet::<Runtime>::bytes_keys_to_property_keys(keys)?;51                    dispatch_unique_runtime!(collection.token_properties(token_id, keys))52                }5354                fn property_permissions(55                    collection: CollectionId,56                    keys: Vec<Vec<u8>>57                ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {58                    let keys = pallet_common::Pallet::<Runtime>::bytes_keys_to_property_keys(keys)?;5960                    pallet_common::Pallet::<Runtime>::filter_property_permissions(collection, keys)61                }6263                fn token_data(64                    collection: CollectionId,65                    token_id: TokenId,66                    keys: Vec<Vec<u8>>67                ) -> Result<TokenData<CrossAccountId>, DispatchError> {68                    let token_data = TokenData {69                        const_data: Self::const_metadata(collection, token_id)?,70                        properties: Self::token_properties(collection, token_id, keys)?,71                        owner: Self::token_owner(collection, token_id)?72                    };7374                    Ok(token_data)75                }7677                fn total_supply(collection: CollectionId) -> Result<u32, DispatchError> {78                    dispatch_unique_runtime!(collection.total_supply())79                }80                fn account_balance(collection: CollectionId, account: CrossAccountId) -> Result<u32, DispatchError> {81                    dispatch_unique_runtime!(collection.account_balance(account))82                }83                fn balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<u128, DispatchError> {84                    dispatch_unique_runtime!(collection.balance(account, token))85                }86                fn allowance(87                    collection: CollectionId,88                    sender: CrossAccountId,89                    spender: CrossAccountId,90                    token: TokenId,91                ) -> Result<u128, DispatchError> {92                    dispatch_unique_runtime!(collection.allowance(sender, spender, token))93                }9495                fn adminlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {96                    Ok(<pallet_common::Pallet<Runtime>>::adminlist(collection))97                }98                fn allowlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {99                    Ok(<pallet_common::Pallet<Runtime>>::allowlist(collection))100                }101                fn allowed(collection: CollectionId, user: CrossAccountId) -> Result<bool, DispatchError> {102                    Ok(<pallet_common::Pallet<Runtime>>::allowed(collection, user))103                }104                fn last_token_id(collection: CollectionId) -> Result<TokenId, DispatchError> {105                    dispatch_unique_runtime!(collection.last_token_id())106                }107                fn collection_by_id(collection: CollectionId) -> Result<Option<RpcCollection<AccountId>>, DispatchError> {108                    Ok(<pallet_common::Pallet<Runtime>>::rpc_collection(collection))109                }110                fn collection_stats() -> Result<CollectionStats, DispatchError> {111                    Ok(<pallet_common::Pallet<Runtime>>::collection_stats())112                }113                fn next_sponsored(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<Option<u64>, DispatchError> {114                    Ok(<$crate::sponsoring::UniqueSponsorshipPredict<Runtime> as115                            $crate::sponsoring::SponsorshipPredict<Runtime>>::predict(116                        collection,117                        account,118                        token))119                }120121                fn effective_collection_limits(collection: CollectionId) -> Result<Option<CollectionLimits>, DispatchError> {122                    Ok(<pallet_common::Pallet<Runtime>>::effective_collection_limits(collection))123                }124            }125126            impl sp_api::Core<Block> for Runtime {127                fn version() -> RuntimeVersion {128                    VERSION129                }130131                fn execute_block(block: Block) {132                    Executive::execute_block(block)133                }134135                fn initialize_block(header: &<Block as BlockT>::Header) {136                    Executive::initialize_block(header)137                }138            }139140            impl sp_api::Metadata<Block> for Runtime {141                fn metadata() -> OpaqueMetadata {142                    OpaqueMetadata::new(Runtime::metadata().into())143                }144            }145146            impl sp_block_builder::BlockBuilder<Block> for Runtime {147                fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {148                    Executive::apply_extrinsic(extrinsic)149                }150151                fn finalize_block() -> <Block as BlockT>::Header {152                    Executive::finalize_block()153                }154155                fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {156                    data.create_extrinsics()157                }158159                fn check_inherents(160                    block: Block,161                    data: sp_inherents::InherentData,162                ) -> sp_inherents::CheckInherentsResult {163                    data.check_extrinsics(&block)164                }165166                // fn random_seed() -> <Block as BlockT>::Hash {167                //     RandomnessCollectiveFlip::random_seed().0168                // }169            }170171            impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {172                fn validate_transaction(173                    source: TransactionSource,174                    tx: <Block as BlockT>::Extrinsic,175                    hash: <Block as BlockT>::Hash,176                ) -> TransactionValidity {177                    Executive::validate_transaction(source, tx, hash)178                }179            }180181            impl sp_offchain::OffchainWorkerApi<Block> for Runtime {182                fn offchain_worker(header: &<Block as BlockT>::Header) {183                    Executive::offchain_worker(header)184                }185            }186187            impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {188                fn chain_id() -> u64 {189                    <Runtime as pallet_evm::Config>::ChainId::get()190                }191192                fn account_basic(address: H160) -> EVMAccount {193                    EVM::account_basic(&address)194                }195196                fn gas_price() -> U256 {197                    <Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price()198                }199200                fn account_code_at(address: H160) -> Vec<u8> {201                    EVM::account_codes(address)202                }203204                fn author() -> H160 {205                    <pallet_evm::Pallet<Runtime>>::find_author()206                }207208                fn storage_at(address: H160, index: U256) -> H256 {209                    let mut tmp = [0u8; 32];210                    index.to_big_endian(&mut tmp);211                    EVM::account_storages(address, H256::from_slice(&tmp[..]))212                }213214                #[allow(clippy::redundant_closure)]215                fn call(216                    from: H160,217                    to: H160,218                    data: Vec<u8>,219                    value: U256,220                    gas_limit: U256,221                    max_fee_per_gas: Option<U256>,222                    max_priority_fee_per_gas: Option<U256>,223                    nonce: Option<U256>,224                    estimate: bool,225                    access_list: Option<Vec<(H160, Vec<H256>)>>,226                ) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {227                    let config = if estimate {228                        let mut config = <Runtime as pallet_evm::Config>::config().clone();229                        config.estimate = true;230                        Some(config)231                    } else {232                        None233                    };234235                    let is_transactional = false;236                    <Runtime as pallet_evm::Config>::Runner::call(237                        CrossAccountId::from_eth(from),238                        to,239                        data,240                        value,241                        gas_limit.low_u64(),242                        max_fee_per_gas,243                        max_priority_fee_per_gas,244                        nonce,245                        access_list.unwrap_or_default(),246                        is_transactional,247                        config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),248                    ).map_err(|err| err.into())249                }250251                #[allow(clippy::redundant_closure)]252                fn create(253                    from: H160,254                    data: Vec<u8>,255                    value: U256,256                    gas_limit: U256,257                    max_fee_per_gas: Option<U256>,258                    max_priority_fee_per_gas: Option<U256>,259                    nonce: Option<U256>,260                    estimate: bool,261                    access_list: Option<Vec<(H160, Vec<H256>)>>,262                ) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {263                    let config = if estimate {264                        let mut config = <Runtime as pallet_evm::Config>::config().clone();265                        config.estimate = true;266                        Some(config)267                    } else {268                        None269                    };270271                    let is_transactional = false;272                    <Runtime as pallet_evm::Config>::Runner::create(273                        CrossAccountId::from_eth(from),274                        data,275                        value,276                        gas_limit.low_u64(),277                        max_fee_per_gas,278                        max_priority_fee_per_gas,279                        nonce,280                        access_list.unwrap_or_default(),281                        is_transactional,282                        config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),283                    ).map_err(|err| err.into())284                }285286                fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {287                    Ethereum::current_transaction_statuses()288                }289290                fn current_block() -> Option<pallet_ethereum::Block> {291                    Ethereum::current_block()292                }293294                fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {295                    Ethereum::current_receipts()296                }297298                fn current_all() -> (299                    Option<pallet_ethereum::Block>,300                    Option<Vec<pallet_ethereum::Receipt>>,301                    Option<Vec<TransactionStatus>>302                ) {303                    (304                        Ethereum::current_block(),305                        Ethereum::current_receipts(),306                        Ethereum::current_transaction_statuses()307                    )308                }309310                fn extrinsic_filter(xts: Vec<<Block as sp_api::BlockT>::Extrinsic>) -> Vec<pallet_ethereum::Transaction> {311                    xts.into_iter().filter_map(|xt| match xt.0.function {312                        Call::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction),313                        _ => None314                    }).collect()315                }316317                fn elasticity() -> Option<Permill> {318                    None319                }320            }321322            impl fp_rpc::ConvertTransactionRuntimeApi<Block> for Runtime {323                fn convert_transaction(transaction: pallet_ethereum::Transaction) -> <Block as BlockT>::Extrinsic  {324                    UncheckedExtrinsic::new_unsigned(325                        pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),326                    )327                }328            }329330            impl sp_session::SessionKeys<Block> for Runtime {331                fn decode_session_keys(332                    encoded: Vec<u8>,333                ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {334                    SessionKeys::decode_into_raw_public_keys(&encoded)335                }336337                fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {338                    SessionKeys::generate(seed)339                }340            }341342            impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {343                fn slot_duration() -> sp_consensus_aura::SlotDuration {344                    sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())345                }346347                fn authorities() -> Vec<AuraId> {348                    Aura::authorities().to_vec()349                }350            }351352            impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {353                fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {354                    ParachainSystem::collect_collation_info(header)355                }356            }357358            impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {359                fn account_nonce(account: AccountId) -> Index {360                    System::account_nonce(account)361                }362            }363364            impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {365                fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {366                    TransactionPayment::query_info(uxt, len)367                }368                fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {369                    TransactionPayment::query_fee_details(uxt, len)370                }371            }372373            /*374            impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber, Hash>375                for Runtime376            {377                fn call(378                    origin: AccountId,379                    dest: AccountId,380                    value: Balance,381                    gas_limit: u64,382                    input_data: Vec<u8>,383                ) -> pallet_contracts_primitives::ContractExecResult {384                    Contracts::bare_call(origin, dest, value, gas_limit, input_data, false)385                }386387                fn instantiate(388                    origin: AccountId,389                    endowment: Balance,390                    gas_limit: u64,391                    code: pallet_contracts_primitives::Code<Hash>,392                    data: Vec<u8>,393                    salt: Vec<u8>,394                ) -> pallet_contracts_primitives::ContractInstantiateResult<AccountId, BlockNumber>395                {396                    Contracts::bare_instantiate(origin, endowment, gas_limit, code, data, salt, true, false)397                }398399                fn get_storage(400                    address: AccountId,401                    key: [u8; 32],402                ) -> pallet_contracts_primitives::GetStorageResult {403                    Contracts::get_storage(address, key)404                }405406                fn rent_projection(407                    address: AccountId,408                ) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {409                    Contracts::rent_projection(address)410                }411            }412            */413414            #[cfg(feature = "runtime-benchmarks")]415            impl frame_benchmarking::Benchmark<Block> for Runtime {416                fn benchmark_metadata(extra: bool) -> (417                    Vec<frame_benchmarking::BenchmarkList>,418                    Vec<frame_support::traits::StorageInfo>,419                ) {420                    use frame_benchmarking::{list_benchmark, Benchmarking, BenchmarkList};421                    use frame_support::traits::StorageInfoTrait;422423                    let mut list = Vec::<BenchmarkList>::new();424425                    list_benchmark!(list, extra, pallet_evm_migration, EvmMigration);426                    list_benchmark!(list, extra, pallet_unique, Unique);427                    list_benchmark!(list, extra, pallet_structure, Structure);428                    list_benchmark!(list, extra, pallet_inflation, Inflation);429                    list_benchmark!(list, extra, pallet_fungible, Fungible);430                    list_benchmark!(list, extra, pallet_refungible, Refungible);431                    list_benchmark!(list, extra, pallet_nonfungible, Nonfungible);432                    // list_benchmark!(list, extra, pallet_evm_coder_substrate, EvmCoderSubstrate);433434                    let storage_info = AllPalletsReversedWithSystemFirst::storage_info();435436                    return (list, storage_info)437                }438439                fn dispatch_benchmark(440                    config: frame_benchmarking::BenchmarkConfig441                ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {442                    use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};443444                    let allowlist: Vec<TrackedStorageKey> = vec![445                        // Block Number446                        hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),447                        // Total Issuance448                        hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),449                        // Execution Phase450                        hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),451                        // Event Count452                        hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),453                        // System Events454                        hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),455456                        // Transactional depth457                        hex_literal::hex!("3a7472616e73616374696f6e5f6c6576656c3a").to_vec().into(),458                    ];459460                    let mut batches = Vec::<BenchmarkBatch>::new();461                    let params = (&config, &allowlist);462463                    add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);464                    add_benchmark!(params, batches, pallet_unique, Unique);465                    add_benchmark!(params, batches, pallet_structure, Structure);466                    add_benchmark!(params, batches, pallet_inflation, Inflation);467                    add_benchmark!(params, batches, pallet_fungible, Fungible);468                    add_benchmark!(params, batches, pallet_refungible, Refungible);469                    add_benchmark!(params, batches, pallet_nonfungible, Nonfungible);470                    // add_benchmark!(params, batches, pallet_evm_coder_substrate, EvmCoderSubstrate);471472                    if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }473                    Ok(batches)474                }475            }476477            #[cfg(feature = "try-runtime")]478            impl frame_try_runtime::TryRuntime<Block> for Runtime {479                fn on_runtime_upgrade() -> (Weight, Weight) {480                    log::info!("try-runtime::on_runtime_upgrade unique-chain.");481                    let weight = Executive::try_runtime_upgrade().unwrap();482                    (weight, RuntimeBlockWeights::get().max_block)483                }484485                fn execute_block_no_check(block: Block) -> Weight {486                    Executive::execute_block_no_check(block)487                }488            }489        }490    }491}