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

difftreelog

source

runtime/common/src/runtime_apis.rs24.4 KiBsourcehistory
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! impl_common_runtime_apis {19    (20        $(21            #![custom_apis]2223            $($custom_apis:tt)+24        )?25    ) => {26        impl_runtime_apis! {27            $($($custom_apis)+)?2829            impl up_rpc::UniqueApi<Block, CrossAccountId, AccountId> for Runtime {30                fn account_tokens(collection: CollectionId, account: CrossAccountId) -> Result<Vec<TokenId>, DispatchError> {31                    dispatch_unique_runtime!(collection.account_tokens(account))32                }33                fn collection_tokens(collection: CollectionId) -> Result<Vec<TokenId>, DispatchError> {34                    dispatch_unique_runtime!(collection.collection_tokens())35                }36                fn token_exists(collection: CollectionId, token: TokenId) -> Result<bool, DispatchError> {37                    dispatch_unique_runtime!(collection.token_exists(token))38                }3940                fn token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>, DispatchError> {41                    dispatch_unique_runtime!(collection.token_owner(token))42                }4344                fn token_owners(collection: CollectionId, token: TokenId) -> Result<Vec::<CrossAccountId>, DispatchError>  {45                   dispatch_unique_runtime!(collection.token_owners(token))46                }4748                fn topmost_token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>, DispatchError> {49                    let budget = up_data_structs::budget::Value::new(10);5051                    Ok(Some(<pallet_structure::Pallet<Runtime>>::find_topmost_owner(collection, token, &budget)?))52                }53                fn token_children(collection: CollectionId, token: TokenId) -> Result<Vec<TokenChild>, DispatchError> {54                    Ok(<pallet_nonfungible::Pallet<Runtime>>::token_children_ids(collection, token))55                }56                fn collection_properties(57                    collection: CollectionId,58                    keys: Option<Vec<Vec<u8>>>59                ) -> Result<Vec<Property>, DispatchError> {60                    let keys = keys.map(61                        |keys| Common::bytes_keys_to_property_keys(keys)62                    ).transpose()?;6364                    Common::filter_collection_properties(collection, keys)65                }6667                fn token_properties(68                    collection: CollectionId,69                    token_id: TokenId,70                    keys: Option<Vec<Vec<u8>>>71                ) -> Result<Vec<Property>, DispatchError> {72                    let keys = keys.map(73                        |keys| Common::bytes_keys_to_property_keys(keys)74                    ).transpose()?;7576                    dispatch_unique_runtime!(collection.token_properties(token_id, keys))77                }7879                fn property_permissions(80                    collection: CollectionId,81                    keys: Option<Vec<Vec<u8>>>82                ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {83                    let keys = keys.map(84                        |keys| Common::bytes_keys_to_property_keys(keys)85                    ).transpose()?;8687                    Common::filter_property_permissions(collection, keys)88                }8990                fn token_data(91                    collection: CollectionId,92                    token_id: TokenId,93                    keys: Option<Vec<Vec<u8>>>94                ) -> Result<TokenData<CrossAccountId>, DispatchError> {95                    let token_data = TokenData {96                        properties: Self::token_properties(collection, token_id, keys)?,97                        owner: Self::token_owner(collection, token_id)?,98                        pieces: Self::total_pieces(collection, token_id)?.unwrap_or(0),99                    };100101                    Ok(token_data)102                }103104                fn total_supply(collection: CollectionId) -> Result<u32, DispatchError> {105                    dispatch_unique_runtime!(collection.total_supply())106                }107                fn account_balance(collection: CollectionId, account: CrossAccountId) -> Result<u32, DispatchError> {108                    dispatch_unique_runtime!(collection.account_balance(account))109                }110                fn balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<u128, DispatchError> {111                    dispatch_unique_runtime!(collection.balance(account, token))112                }113                fn allowance(114                    collection: CollectionId,115                    sender: CrossAccountId,116                    spender: CrossAccountId,117                    token: TokenId,118                ) -> Result<u128, DispatchError> {119                    dispatch_unique_runtime!(collection.allowance(sender, spender, token))120                }121122                fn adminlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {123                    Ok(<pallet_common::Pallet<Runtime>>::adminlist(collection))124                }125                fn allowlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {126                    Ok(<pallet_common::Pallet<Runtime>>::allowlist(collection))127                }128                fn allowed(collection: CollectionId, user: CrossAccountId) -> Result<bool, DispatchError> {129                    Ok(<pallet_common::Pallet<Runtime>>::allowed(collection, user))130                }131                fn last_token_id(collection: CollectionId) -> Result<TokenId, DispatchError> {132                    dispatch_unique_runtime!(collection.last_token_id())133                }134                fn collection_by_id(collection: CollectionId) -> Result<Option<RpcCollection<AccountId>>, DispatchError> {135                    Ok(<pallet_common::Pallet<Runtime>>::rpc_collection(collection))136                }137                fn collection_stats() -> Result<CollectionStats, DispatchError> {138                    Ok(<pallet_common::Pallet<Runtime>>::collection_stats())139                }140                fn next_sponsored(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<Option<u64>, DispatchError> {141                    Ok(<$crate::sponsoring::UniqueSponsorshipPredict<Runtime> as142                            $crate::sponsoring::SponsorshipPredict<Runtime>>::predict(143                        collection,144                        account,145                        token))146                }147148                fn effective_collection_limits(collection: CollectionId) -> Result<Option<CollectionLimits>, DispatchError> {149                    Ok(<pallet_common::Pallet<Runtime>>::effective_collection_limits(collection))150                }151152                fn total_pieces(collection: CollectionId, token_id: TokenId) -> Result<Option<u128>, DispatchError> {153                    dispatch_unique_runtime!(collection.total_pieces(token_id))154                }155            }156157            impl sp_api::Core<Block> for Runtime {158                fn version() -> RuntimeVersion {159                    VERSION160                }161162                fn execute_block(block: Block) {163                    Executive::execute_block(block)164                }165166                fn initialize_block(header: &<Block as BlockT>::Header) {167                    Executive::initialize_block(header)168                }169            }170171            impl sp_api::Metadata<Block> for Runtime {172                fn metadata() -> OpaqueMetadata {173                    OpaqueMetadata::new(Runtime::metadata().into())174                }175            }176177            impl sp_block_builder::BlockBuilder<Block> for Runtime {178                fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {179                    Executive::apply_extrinsic(extrinsic)180                }181182                fn finalize_block() -> <Block as BlockT>::Header {183                    Executive::finalize_block()184                }185186                fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {187                    data.create_extrinsics()188                }189190                fn check_inherents(191                    block: Block,192                    data: sp_inherents::InherentData,193                ) -> sp_inherents::CheckInherentsResult {194                    data.check_extrinsics(&block)195                }196197                // fn random_seed() -> <Block as BlockT>::Hash {198                //     RandomnessCollectiveFlip::random_seed().0199                // }200            }201202            impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {203                fn validate_transaction(204                    source: TransactionSource,205                    tx: <Block as BlockT>::Extrinsic,206                    hash: <Block as BlockT>::Hash,207                ) -> TransactionValidity {208                    Executive::validate_transaction(source, tx, hash)209                }210            }211212            impl sp_offchain::OffchainWorkerApi<Block> for Runtime {213                fn offchain_worker(header: &<Block as BlockT>::Header) {214                    Executive::offchain_worker(header)215                }216            }217218            impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {219                fn chain_id() -> u64 {220                    <Runtime as pallet_evm::Config>::ChainId::get()221                }222223                fn account_basic(address: H160) -> EVMAccount {224                    let (account, _) = EVM::account_basic(&address);225                    account226                }227228                fn gas_price() -> U256 {229                    let (price, _) = <Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price();230                    price231                }232233                fn account_code_at(address: H160) -> Vec<u8> {234                    EVM::account_codes(address)235                }236237                fn author() -> H160 {238                    <pallet_evm::Pallet<Runtime>>::find_author()239                }240241                fn storage_at(address: H160, index: U256) -> H256 {242                    let mut tmp = [0u8; 32];243                    index.to_big_endian(&mut tmp);244                    EVM::account_storages(address, H256::from_slice(&tmp[..]))245                }246247                #[allow(clippy::redundant_closure)]248                fn call(249                    from: H160,250                    to: H160,251                    data: Vec<u8>,252                    value: U256,253                    gas_limit: U256,254                    max_fee_per_gas: Option<U256>,255                    max_priority_fee_per_gas: Option<U256>,256                    nonce: Option<U256>,257                    estimate: bool,258                    access_list: Option<Vec<(H160, Vec<H256>)>>,259                ) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {260                    let config = if estimate {261                        let mut config = <Runtime as pallet_evm::Config>::config().clone();262                        config.estimate = true;263                        Some(config)264                    } else {265                        None266                    };267268                    let is_transactional = false;269                    <Runtime as pallet_evm::Config>::Runner::call(270                        CrossAccountId::from_eth(from),271                        to,272                        data,273                        value,274                        gas_limit.low_u64(),275                        max_fee_per_gas,276                        max_priority_fee_per_gas,277                        nonce,278                        access_list.unwrap_or_default(),279                        is_transactional,280                        config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),281                    ).map_err(|err| err.error.into())282                }283284                #[allow(clippy::redundant_closure)]285                fn create(286                    from: H160,287                    data: Vec<u8>,288                    value: U256,289                    gas_limit: U256,290                    max_fee_per_gas: Option<U256>,291                    max_priority_fee_per_gas: Option<U256>,292                    nonce: Option<U256>,293                    estimate: bool,294                    access_list: Option<Vec<(H160, Vec<H256>)>>,295                ) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {296                    let config = if estimate {297                        let mut config = <Runtime as pallet_evm::Config>::config().clone();298                        config.estimate = true;299                        Some(config)300                    } else {301                        None302                    };303304                    let is_transactional = false;305                    <Runtime as pallet_evm::Config>::Runner::create(306                        CrossAccountId::from_eth(from),307                        data,308                        value,309                        gas_limit.low_u64(),310                        max_fee_per_gas,311                        max_priority_fee_per_gas,312                        nonce,313                        access_list.unwrap_or_default(),314                        is_transactional,315                        config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),316                    ).map_err(|err| err.error.into())317                }318319                fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {320                    Ethereum::current_transaction_statuses()321                }322323                fn current_block() -> Option<pallet_ethereum::Block> {324                    Ethereum::current_block()325                }326327                fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {328                    Ethereum::current_receipts()329                }330331                fn current_all() -> (332                    Option<pallet_ethereum::Block>,333                    Option<Vec<pallet_ethereum::Receipt>>,334                    Option<Vec<TransactionStatus>>335                ) {336                    (337                        Ethereum::current_block(),338                        Ethereum::current_receipts(),339                        Ethereum::current_transaction_statuses()340                    )341                }342343                fn extrinsic_filter(xts: Vec<<Block as sp_api::BlockT>::Extrinsic>) -> Vec<pallet_ethereum::Transaction> {344                    xts.into_iter().filter_map(|xt| match xt.0.function {345                        Call::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction),346                        _ => None347                    }).collect()348                }349350                fn elasticity() -> Option<Permill> {351                    None352                }353            }354355            impl fp_rpc::ConvertTransactionRuntimeApi<Block> for Runtime {356                fn convert_transaction(transaction: pallet_ethereum::Transaction) -> <Block as BlockT>::Extrinsic  {357                    UncheckedExtrinsic::new_unsigned(358                        pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),359                    )360                }361            }362363            impl sp_session::SessionKeys<Block> for Runtime {364                fn decode_session_keys(365                    encoded: Vec<u8>,366                ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {367                    SessionKeys::decode_into_raw_public_keys(&encoded)368                }369370                fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {371                    SessionKeys::generate(seed)372                }373            }374375            impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {376                fn slot_duration() -> sp_consensus_aura::SlotDuration {377                    sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())378                }379380                fn authorities() -> Vec<AuraId> {381                    Aura::authorities().to_vec()382                }383            }384385            impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {386                fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {387                    ParachainSystem::collect_collation_info(header)388                }389            }390391            impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {392                fn account_nonce(account: AccountId) -> Index {393                    System::account_nonce(account)394                }395            }396397            impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {398                fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {399                    TransactionPayment::query_info(uxt, len)400                }401                fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {402                    TransactionPayment::query_fee_details(uxt, len)403                }404            }405406            /*407            impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber, Hash>408                for Runtime409            {410                fn call(411                    origin: AccountId,412                    dest: AccountId,413                    value: Balance,414                    gas_limit: u64,415                    input_data: Vec<u8>,416                ) -> pallet_contracts_primitives::ContractExecResult {417                    Contracts::bare_call(origin, dest, value, gas_limit, input_data, false)418                }419420                fn instantiate(421                    origin: AccountId,422                    endowment: Balance,423                    gas_limit: u64,424                    code: pallet_contracts_primitives::Code<Hash>,425                    data: Vec<u8>,426                    salt: Vec<u8>,427                ) -> pallet_contracts_primitives::ContractInstantiateResult<AccountId, BlockNumber>428                {429                    Contracts::bare_instantiate(origin, endowment, gas_limit, code, data, salt, true, false)430                }431432                fn get_storage(433                    address: AccountId,434                    key: [u8; 32],435                ) -> pallet_contracts_primitives::GetStorageResult {436                    Contracts::get_storage(address, key)437                }438439                fn rent_projection(440                    address: AccountId,441                ) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {442                    Contracts::rent_projection(address)443                }444            }445            */446447            #[cfg(feature = "runtime-benchmarks")]448            impl frame_benchmarking::Benchmark<Block> for Runtime {449                fn benchmark_metadata(extra: bool) -> (450                    Vec<frame_benchmarking::BenchmarkList>,451                    Vec<frame_support::traits::StorageInfo>,452                ) {453                    use frame_benchmarking::{list_benchmark, Benchmarking, BenchmarkList};454                    use frame_support::traits::StorageInfoTrait;455456                    let mut list = Vec::<BenchmarkList>::new();457458                    list_benchmark!(list, extra, pallet_evm_migration, EvmMigration);459                    list_benchmark!(list, extra, pallet_common, Common);460                    list_benchmark!(list, extra, pallet_unique, Unique);461                    list_benchmark!(list, extra, pallet_structure, Structure);462                    list_benchmark!(list, extra, pallet_inflation, Inflation);463                    list_benchmark!(list, extra, pallet_fungible, Fungible);464                    list_benchmark!(list, extra, pallet_refungible, Refungible);465                    list_benchmark!(list, extra, pallet_nonfungible, Nonfungible);466                    list_benchmark!(list, extra, pallet_unique_scheduler, Scheduler);467468                    #[cfg(not(feature = "unique-runtime"))]469                    list_benchmark!(list, extra, pallet_proxy_rmrk_core, RmrkCore);470471                    #[cfg(not(feature = "unique-runtime"))]472                    list_benchmark!(list, extra, pallet_proxy_rmrk_equip, RmrkEquip);473474                    // list_benchmark!(list, extra, pallet_evm_coder_substrate, EvmCoderSubstrate);475476                    let storage_info = AllPalletsReversedWithSystemFirst::storage_info();477478                    return (list, storage_info)479                }480481                fn dispatch_benchmark(482                    config: frame_benchmarking::BenchmarkConfig483                ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {484                    use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};485486                    let allowlist: Vec<TrackedStorageKey> = vec![487                        // Total Issuance488                        hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),489490                        // Block Number491                        hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),492                        // Execution Phase493                        hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),494                        // Event Count495                        hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),496                        // System Events497                        hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),498499                        // Evm CurrentLogs500                        hex_literal::hex!("1da53b775b270400e7e61ed5cbc5a146547f210cec367e9af919603343b9cb56").to_vec().into(),501502                        // Transactional depth503                        hex_literal::hex!("3a7472616e73616374696f6e5f6c6576656c3a").to_vec().into(),504                    ];505506                    let mut batches = Vec::<BenchmarkBatch>::new();507                    let params = (&config, &allowlist);508509                    add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);510                    add_benchmark!(params, batches, pallet_common, Common);511                    add_benchmark!(params, batches, pallet_unique, Unique);512                    add_benchmark!(params, batches, pallet_structure, Structure);513                    add_benchmark!(params, batches, pallet_inflation, Inflation);514                    add_benchmark!(params, batches, pallet_fungible, Fungible);515                    add_benchmark!(params, batches, pallet_refungible, Refungible);516                    add_benchmark!(params, batches, pallet_nonfungible, Nonfungible);517                    add_benchmark!(params, batches, pallet_unique_scheduler, Scheduler);518519                    #[cfg(not(feature = "unique-runtime"))]520                    add_benchmark!(params, batches, pallet_proxy_rmrk_core, RmrkCore);521522                    #[cfg(not(feature = "unique-runtime"))]523                    add_benchmark!(params, batches, pallet_proxy_rmrk_equip, RmrkEquip);524525                    // add_benchmark!(params, batches, pallet_evm_coder_substrate, EvmCoderSubstrate);526527                    if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }528                    Ok(batches)529                }530            }531532            #[cfg(feature = "try-runtime")]533            impl frame_try_runtime::TryRuntime<Block> for Runtime {534                fn on_runtime_upgrade() -> (Weight, Weight) {535                    log::info!("try-runtime::on_runtime_upgrade unique-chain.");536                    let weight = Executive::try_runtime_upgrade().unwrap();537                    (weight, RuntimeBlockWeights::get().max_block)538                }539540                fn execute_block_no_check(block: Block) -> Weight {541                    Executive::execute_block_no_check(block)542                }543            }544        }545    }546}