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

difftreelog

source

runtime/common/src/runtime_apis.rs26.4 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                }35                fn variable_metadata(collection: CollectionId, token: TokenId) -> Result<Vec<u8>, DispatchError> {36                    dispatch_unique_runtime!(collection.variable_metadata(token))37                }3839                fn collection_properties(40                    collection: CollectionId,41                    keys: Vec<Vec<u8>>42                ) -> Result<Vec<Property>, DispatchError> {43                    let keys = pallet_common::Pallet::<Runtime>::bytes_keys_to_property_keys(keys)?;4445                    pallet_common::Pallet::<Runtime>::filter_collection_properties(collection, keys)46                }4748                fn token_properties(49                    collection: CollectionId,50                    token_id: TokenId,51                    keys: Vec<Vec<u8>>52                ) -> Result<Vec<Property>, DispatchError> {53                    let keys = pallet_common::Pallet::<Runtime>::bytes_keys_to_property_keys(keys)?;54                    dispatch_unique_runtime!(collection.token_properties(token_id, keys))55                }5657                fn property_permissions(58                    collection: CollectionId,59                    keys: Vec<Vec<u8>>60                ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {61                    let keys = pallet_common::Pallet::<Runtime>::bytes_keys_to_property_keys(keys)?;6263                    pallet_common::Pallet::<Runtime>::filter_property_permissions(collection, keys)64                }6566                fn token_data(67                    collection: CollectionId,68                    token_id: TokenId,69                    keys: Vec<Vec<u8>>70                ) -> Result<TokenData<CrossAccountId>, DispatchError> {71                    let token_data = TokenData {72                        const_data: Self::const_metadata(collection, token_id)?,73                        properties: Self::token_properties(collection, token_id, keys)?,74                        owner: Self::token_owner(collection, token_id)?75                    };7677                    Ok(token_data)78                }7980                fn total_supply(collection: CollectionId) -> Result<u32, DispatchError> {81                    dispatch_unique_runtime!(collection.total_supply())82                }83                fn account_balance(collection: CollectionId, account: CrossAccountId) -> Result<u32, DispatchError> {84                    dispatch_unique_runtime!(collection.account_balance(account))85                }86                fn balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<u128, DispatchError> {87                    dispatch_unique_runtime!(collection.balance(account, token))88                }89                fn allowance(90                    collection: CollectionId,91                    sender: CrossAccountId,92                    spender: CrossAccountId,93                    token: TokenId,94                ) -> Result<u128, DispatchError> {95                    dispatch_unique_runtime!(collection.allowance(sender, spender, token))96                }9798                fn adminlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {99                    Ok(<pallet_common::Pallet<Runtime>>::adminlist(collection))100                }101                fn allowlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {102                    Ok(<pallet_common::Pallet<Runtime>>::allowlist(collection))103                }104                fn allowed(collection: CollectionId, user: CrossAccountId) -> Result<bool, DispatchError> {105                    Ok(<pallet_common::Pallet<Runtime>>::allowed(collection, user))106                }107                fn last_token_id(collection: CollectionId) -> Result<TokenId, DispatchError> {108                    dispatch_unique_runtime!(collection.last_token_id())109                }110                fn collection_by_id(collection: CollectionId) -> Result<Option<RpcCollection<AccountId>>, DispatchError> {111                    Ok(<pallet_common::Pallet<Runtime>>::rpc_collection(collection))112                }113                fn collection_stats() -> Result<CollectionStats, DispatchError> {114                    Ok(<pallet_common::Pallet<Runtime>>::collection_stats())115                }116                fn next_sponsored(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<Option<u64>, DispatchError> {117                    Ok(<$crate::sponsoring::UniqueSponsorshipPredict<Runtime> as118                            $crate::sponsoring::SponsorshipPredict<Runtime>>::predict(119                        collection,120                        account,121                        token))122                }123124                fn effective_collection_limits(collection: CollectionId) -> Result<Option<CollectionLimits>, DispatchError> {125                    Ok(<pallet_common::Pallet<Runtime>>::effective_collection_limits(collection))126                }127            }128129            impl rmrk_rpc::RmrkApi<130                Block,131                AccountId,132                RmrkCollectionInfo,133                RmrkInstanceInfo,134                RmrkResourceInfo,135                RmrkPropertyInfo,136                RmrkBaseInfo,137                RmrkPartType,138                RmrkTheme139            > for Runtime {140                fn last_collection_idx() -> Result<RmrkCollectionId, DispatchError> {141                    Ok(<pallet_common::CreatedCollectionCount<Runtime>>::get().0)142                }143                fn collection_by_id(collection_id: RmrkCollectionId) -> Result<Option<RmrkCollectionInfo>, DispatchError> {144                    use frame_support::BoundedVec;145146                    let collection_id = CollectionId(collection_id);147                    let collection = match <pallet_common::CollectionById<Runtime>>::get(collection_id) {148                        Some(c) => c,149                        None => return Ok(None)150                    };151                    let nfts_count: Result<u32, DispatchError> = dispatch_unique_runtime!(collection_id.total_supply());152                    Ok(Some(RmrkCollectionInfo {153                        issuer: collection.owner,154                        metadata: BoundedVec::<u8, RmrkStringLimit>::default(), // todo take from Properties, not implemented yet155                        max: Some(collection.limits.token_limit()), // must have some effective limits156                        symbol: BoundedVec::<u8, RmrkCollectionSymbolLimit>::try_from(collection.token_prefix.into_inner()).unwrap_or_default() /*{157                            Ok(s) => s,158                            Err(_) => return Err(pallet_common::Error::<Runtime>::CollectionTokenPrefixLimitExceeded)159                        }*/,160                        nfts_count: nfts_count? // todo <Runtime>::total_supply(collection_id)161                    }))162                }163                fn nft_by_id(collection_id: RmrkCollectionId, nft_by_id: RmrkNftId) -> Result<Option<RmrkInstanceInfo>, DispatchError> {164                    todo!()165                }166                fn account_tokens(account_id: AccountId, collection_id: RmrkCollectionId) -> Result<Vec<RmrkNftId>, DispatchError> {167                    let cross_account_id = CrossAccountId::from_sub(account_id);168                    let collection_id = CollectionId(collection_id);169                    Ok(170                        (dispatch_unique_runtime!(collection_id.account_tokens(cross_account_id)) as Result<Vec<TokenId>, DispatchError>)?171                        // todo <Runtime>::account_tokens(collection_id, cross_account_id)172                        .into_iter()173                        .map(|token| token.0)174                        .collect::<Vec<_>>()175                    )176                }177                fn nft_children(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Result<Vec<RmrkNftChild>, DispatchError> {178                    todo!()179                }180                fn collection_properties(collection_id: RmrkCollectionId, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Result<Vec<RmrkPropertyInfo>, DispatchError> {181                    todo!()182                }183                fn nft_properties(collection_id: RmrkCollectionId, nft_id: RmrkNftId, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Result<Vec<RmrkPropertyInfo>, DispatchError> {184                    todo!()185                }186                fn nft_resources(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Result<Vec<RmrkResourceInfo>, DispatchError> {187                    todo!()188                }189                fn nft_resource_priorities(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Result<Vec<RmrkResourceId>, DispatchError> {190                    todo!()191                }192                fn base(base_id: RmrkBaseId) -> Result<Option<RmrkBaseInfo>, DispatchError> {193                    todo!()194                }195                fn base_parts(base_id: RmrkBaseId) -> Result<Vec<RmrkPartType>, DispatchError> {196                    todo!()197                }198                fn theme_names(base_id: RmrkBaseId) -> Result<Vec<RmrkThemeName>, DispatchError> {199                    todo!()200                }201                fn theme(base_id: RmrkBaseId, theme_name: RmrkThemeName, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Result<Option<RmrkTheme>, DispatchError> {202                    todo!()203                }204            }205206            impl sp_api::Core<Block> for Runtime {207                fn version() -> RuntimeVersion {208                    VERSION209                }210211                fn execute_block(block: Block) {212                    Executive::execute_block(block)213                }214215                fn initialize_block(header: &<Block as BlockT>::Header) {216                    Executive::initialize_block(header)217                }218            }219220            impl sp_api::Metadata<Block> for Runtime {221                fn metadata() -> OpaqueMetadata {222                    OpaqueMetadata::new(Runtime::metadata().into())223                }224            }225226            impl sp_block_builder::BlockBuilder<Block> for Runtime {227                fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {228                    Executive::apply_extrinsic(extrinsic)229                }230231                fn finalize_block() -> <Block as BlockT>::Header {232                    Executive::finalize_block()233                }234235                fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {236                    data.create_extrinsics()237                }238239                fn check_inherents(240                    block: Block,241                    data: sp_inherents::InherentData,242                ) -> sp_inherents::CheckInherentsResult {243                    data.check_extrinsics(&block)244                }245246                // fn random_seed() -> <Block as BlockT>::Hash {247                //     RandomnessCollectiveFlip::random_seed().0248                // }249            }250251            impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {252                fn validate_transaction(253                    source: TransactionSource,254                    tx: <Block as BlockT>::Extrinsic,255                    hash: <Block as BlockT>::Hash,256                ) -> TransactionValidity {257                    Executive::validate_transaction(source, tx, hash)258                }259            }260261            impl sp_offchain::OffchainWorkerApi<Block> for Runtime {262                fn offchain_worker(header: &<Block as BlockT>::Header) {263                    Executive::offchain_worker(header)264                }265            }266267            impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {268                fn chain_id() -> u64 {269                    <Runtime as pallet_evm::Config>::ChainId::get()270                }271272                fn account_basic(address: H160) -> EVMAccount {273                    EVM::account_basic(&address)274                }275276                fn gas_price() -> U256 {277                    <Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price()278                }279280                fn account_code_at(address: H160) -> Vec<u8> {281                    EVM::account_codes(address)282                }283284                fn author() -> H160 {285                    <pallet_evm::Pallet<Runtime>>::find_author()286                }287288                fn storage_at(address: H160, index: U256) -> H256 {289                    let mut tmp = [0u8; 32];290                    index.to_big_endian(&mut tmp);291                    EVM::account_storages(address, H256::from_slice(&tmp[..]))292                }293294                #[allow(clippy::redundant_closure)]295                fn call(296                    from: H160,297                    to: H160,298                    data: Vec<u8>,299                    value: U256,300                    gas_limit: U256,301                    max_fee_per_gas: Option<U256>,302                    max_priority_fee_per_gas: Option<U256>,303                    nonce: Option<U256>,304                    estimate: bool,305                    access_list: Option<Vec<(H160, Vec<H256>)>>,306                ) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {307                    let config = if estimate {308                        let mut config = <Runtime as pallet_evm::Config>::config().clone();309                        config.estimate = true;310                        Some(config)311                    } else {312                        None313                    };314315                    let is_transactional = false;316                    <Runtime as pallet_evm::Config>::Runner::call(317                        CrossAccountId::from_eth(from),318                        to,319                        data,320                        value,321                        gas_limit.low_u64(),322                        max_fee_per_gas,323                        max_priority_fee_per_gas,324                        nonce,325                        access_list.unwrap_or_default(),326                        is_transactional,327                        config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),328                    ).map_err(|err| err.into())329                }330331                #[allow(clippy::redundant_closure)]332                fn create(333                    from: H160,334                    data: Vec<u8>,335                    value: U256,336                    gas_limit: U256,337                    max_fee_per_gas: Option<U256>,338                    max_priority_fee_per_gas: Option<U256>,339                    nonce: Option<U256>,340                    estimate: bool,341                    access_list: Option<Vec<(H160, Vec<H256>)>>,342                ) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {343                    let config = if estimate {344                        let mut config = <Runtime as pallet_evm::Config>::config().clone();345                        config.estimate = true;346                        Some(config)347                    } else {348                        None349                    };350351                    let is_transactional = false;352                    <Runtime as pallet_evm::Config>::Runner::create(353                        CrossAccountId::from_eth(from),354                        data,355                        value,356                        gas_limit.low_u64(),357                        max_fee_per_gas,358                        max_priority_fee_per_gas,359                        nonce,360                        access_list.unwrap_or_default(),361                        is_transactional,362                        config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),363                    ).map_err(|err| err.into())364                }365366                fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {367                    Ethereum::current_transaction_statuses()368                }369370                fn current_block() -> Option<pallet_ethereum::Block> {371                    Ethereum::current_block()372                }373374                fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {375                    Ethereum::current_receipts()376                }377378                fn current_all() -> (379                    Option<pallet_ethereum::Block>,380                    Option<Vec<pallet_ethereum::Receipt>>,381                    Option<Vec<TransactionStatus>>382                ) {383                    (384                        Ethereum::current_block(),385                        Ethereum::current_receipts(),386                        Ethereum::current_transaction_statuses()387                    )388                }389390                fn extrinsic_filter(xts: Vec<<Block as sp_api::BlockT>::Extrinsic>) -> Vec<pallet_ethereum::Transaction> {391                    xts.into_iter().filter_map(|xt| match xt.0.function {392                        Call::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction),393                        _ => None394                    }).collect()395                }396397                fn elasticity() -> Option<Permill> {398                    None399                }400            }401402            impl fp_rpc::ConvertTransactionRuntimeApi<Block> for Runtime {403                fn convert_transaction(transaction: pallet_ethereum::Transaction) -> <Block as BlockT>::Extrinsic  {404                    UncheckedExtrinsic::new_unsigned(405                        pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),406                    )407                }408            }409410            impl sp_session::SessionKeys<Block> for Runtime {411                fn decode_session_keys(412                    encoded: Vec<u8>,413                ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {414                    SessionKeys::decode_into_raw_public_keys(&encoded)415                }416417                fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {418                    SessionKeys::generate(seed)419                }420            }421422            impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {423                fn slot_duration() -> sp_consensus_aura::SlotDuration {424                    sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())425                }426427                fn authorities() -> Vec<AuraId> {428                    Aura::authorities().to_vec()429                }430            }431432            impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {433                fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {434                    ParachainSystem::collect_collation_info(header)435                }436            }437438            impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {439                fn account_nonce(account: AccountId) -> Index {440                    System::account_nonce(account)441                }442            }443444            impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {445                fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {446                    TransactionPayment::query_info(uxt, len)447                }448                fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {449                    TransactionPayment::query_fee_details(uxt, len)450                }451            }452453            /*454            impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber, Hash>455                for Runtime456            {457                fn call(458                    origin: AccountId,459                    dest: AccountId,460                    value: Balance,461                    gas_limit: u64,462                    input_data: Vec<u8>,463                ) -> pallet_contracts_primitives::ContractExecResult {464                    Contracts::bare_call(origin, dest, value, gas_limit, input_data, false)465                }466467                fn instantiate(468                    origin: AccountId,469                    endowment: Balance,470                    gas_limit: u64,471                    code: pallet_contracts_primitives::Code<Hash>,472                    data: Vec<u8>,473                    salt: Vec<u8>,474                ) -> pallet_contracts_primitives::ContractInstantiateResult<AccountId, BlockNumber>475                {476                    Contracts::bare_instantiate(origin, endowment, gas_limit, code, data, salt, true, false)477                }478479                fn get_storage(480                    address: AccountId,481                    key: [u8; 32],482                ) -> pallet_contracts_primitives::GetStorageResult {483                    Contracts::get_storage(address, key)484                }485486                fn rent_projection(487                    address: AccountId,488                ) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {489                    Contracts::rent_projection(address)490                }491            }492            */493494            #[cfg(feature = "runtime-benchmarks")]495            impl frame_benchmarking::Benchmark<Block> for Runtime {496                fn benchmark_metadata(extra: bool) -> (497                    Vec<frame_benchmarking::BenchmarkList>,498                    Vec<frame_support::traits::StorageInfo>,499                ) {500                    use frame_benchmarking::{list_benchmark, Benchmarking, BenchmarkList};501                    use frame_support::traits::StorageInfoTrait;502503                    let mut list = Vec::<BenchmarkList>::new();504505                    list_benchmark!(list, extra, pallet_evm_migration, EvmMigration);506                    list_benchmark!(list, extra, pallet_unique, Unique);507                    list_benchmark!(list, extra, pallet_structure, Structure);508                    list_benchmark!(list, extra, pallet_inflation, Inflation);509                    list_benchmark!(list, extra, pallet_fungible, Fungible);510                    list_benchmark!(list, extra, pallet_refungible, Refungible);511                    list_benchmark!(list, extra, pallet_nonfungible, Nonfungible);512                    // list_benchmark!(list, extra, pallet_evm_coder_substrate, EvmCoderSubstrate);513514                    let storage_info = AllPalletsReversedWithSystemFirst::storage_info();515516                    return (list, storage_info)517                }518519                fn dispatch_benchmark(520                    config: frame_benchmarking::BenchmarkConfig521                ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {522                    use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};523524                    let allowlist: Vec<TrackedStorageKey> = vec![525                        // Block Number526                        hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),527                        // Total Issuance528                        hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),529                        // Execution Phase530                        hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),531                        // Event Count532                        hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),533                        // System Events534                        hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),535536                        // Transactional depth537                        hex_literal::hex!("3a7472616e73616374696f6e5f6c6576656c3a").to_vec().into(),538                    ];539540                    let mut batches = Vec::<BenchmarkBatch>::new();541                    let params = (&config, &allowlist);542543                    add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);544                    add_benchmark!(params, batches, pallet_unique, Unique);545                    add_benchmark!(params, batches, pallet_structure, Structure);546                    add_benchmark!(params, batches, pallet_inflation, Inflation);547                    add_benchmark!(params, batches, pallet_fungible, Fungible);548                    add_benchmark!(params, batches, pallet_refungible, Refungible);549                    add_benchmark!(params, batches, pallet_nonfungible, Nonfungible);550                    // add_benchmark!(params, batches, pallet_evm_coder_substrate, EvmCoderSubstrate);551552                    if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }553                    Ok(batches)554                }555            }556557            #[cfg(feature = "try-runtime")]558            impl frame_try_runtime::TryRuntime<Block> for Runtime {559                fn on_runtime_upgrade() -> (Weight, Weight) {560                    log::info!("try-runtime::on_runtime_upgrade unique-chain.");561                    let weight = Executive::try_runtime_upgrade().unwrap();562                    (weight, RuntimeBlockWeights::get().max_block)563                }564565                fn execute_block_no_check(block: Block) -> Weight {566                    Executive::execute_block_no_check(block)567                }568            }569        }570    }571}