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

difftreelog

source

runtime/common/src/runtime_apis.rs39.0 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: Option<Vec<Vec<u8>>>39                ) -> Result<Vec<Property>, DispatchError> {40                    let keys = keys.map(41                        |keys| Common::bytes_keys_to_property_keys(keys)42                    ).transpose()?;4344                    Common::filter_collection_properties(collection, keys)45                }4647                fn token_properties(48                    collection: CollectionId,49                    token_id: TokenId,50                    keys: Option<Vec<Vec<u8>>>51                ) -> Result<Vec<Property>, DispatchError> {52                    let keys = keys.map(53                        |keys| Common::bytes_keys_to_property_keys(keys)54                    ).transpose()?;5556                    dispatch_unique_runtime!(collection.token_properties(token_id, keys))57                }5859                fn property_permissions(60                    collection: CollectionId,61                    keys: Option<Vec<Vec<u8>>>62                ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {63                    let keys = keys.map(64                        |keys| Common::bytes_keys_to_property_keys(keys)65                    ).transpose()?;6667                    Common::filter_property_permissions(collection, keys)68                }6970                fn token_data(71                    collection: CollectionId,72                    token_id: TokenId,73                    keys: Option<Vec<Vec<u8>>>74                ) -> Result<TokenData<CrossAccountId>, DispatchError> {75                    let token_data = TokenData {76                        const_data: Self::const_metadata(collection, token_id)?,77                        properties: Self::token_properties(collection, token_id, keys)?,78                        owner: Self::token_owner(collection, token_id)?79                    };8081                    Ok(token_data)82                }8384                fn total_supply(collection: CollectionId) -> Result<u32, DispatchError> {85                    dispatch_unique_runtime!(collection.total_supply())86                }87                fn account_balance(collection: CollectionId, account: CrossAccountId) -> Result<u32, DispatchError> {88                    dispatch_unique_runtime!(collection.account_balance(account))89                }90                fn balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<u128, DispatchError> {91                    dispatch_unique_runtime!(collection.balance(account, token))92                }93                fn allowance(94                    collection: CollectionId,95                    sender: CrossAccountId,96                    spender: CrossAccountId,97                    token: TokenId,98                ) -> Result<u128, DispatchError> {99                    dispatch_unique_runtime!(collection.allowance(sender, spender, token))100                }101102                fn adminlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {103                    Ok(<pallet_common::Pallet<Runtime>>::adminlist(collection))104                }105                fn allowlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {106                    Ok(<pallet_common::Pallet<Runtime>>::allowlist(collection))107                }108                fn allowed(collection: CollectionId, user: CrossAccountId) -> Result<bool, DispatchError> {109                    Ok(<pallet_common::Pallet<Runtime>>::allowed(collection, user))110                }111                fn last_token_id(collection: CollectionId) -> Result<TokenId, DispatchError> {112                    dispatch_unique_runtime!(collection.last_token_id())113                }114                fn collection_by_id(collection: CollectionId) -> Result<Option<RpcCollection<AccountId>>, DispatchError> {115                    Ok(<pallet_common::Pallet<Runtime>>::rpc_collection(collection))116                }117                fn collection_stats() -> Result<CollectionStats, DispatchError> {118                    Ok(<pallet_common::Pallet<Runtime>>::collection_stats())119                }120                fn next_sponsored(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<Option<u64>, DispatchError> {121                    Ok(<$crate::sponsoring::UniqueSponsorshipPredict<Runtime> as122                            $crate::sponsoring::SponsorshipPredict<Runtime>>::predict(123                        collection,124                        account,125                        token))126                }127128                fn effective_collection_limits(collection: CollectionId) -> Result<Option<CollectionLimits>, DispatchError> {129                    Ok(<pallet_common::Pallet<Runtime>>::effective_collection_limits(collection))130                }131            }132133            impl rmrk_rpc::RmrkApi<134                Block,135                AccountId,136                RmrkCollectionInfo<AccountId>,137                RmrkInstanceInfo<AccountId>,138                RmrkResourceInfo,139                RmrkPropertyInfo,140                RmrkBaseInfo<AccountId>,141                RmrkPartType,142                RmrkTheme143            > for Runtime {144                fn last_collection_idx() -> Result<RmrkCollectionId, DispatchError> {145                    Ok(RmrkCore::last_collection_idx())146                }147148                fn collection_by_id(collection_id: RmrkCollectionId) -> Result<Option<RmrkCollectionInfo<AccountId>>, DispatchError> {149                    use frame_support::BoundedVec;150                    use scale_info::prelude::string::String;151                    use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, RmrkRebind, RmrkDecode}};152153                    let collection_id = CollectionId(collection_id);154                    let collection = match RmrkCore::get_typed_nft_collection(collection_id, CollectionType::Regular) {155                        Ok(c) => c,156                        Err(_) => return Ok(None),157                    };158159                    let nfts_count = (dispatch_unique_runtime!(collection_id.total_supply()) as Result<u32, DispatchError>)?;160                    //<Runtime as up_rpc::UniqueApi>::total_supply(collection_id); // todo can't find UniqueApi with disabled default features161162                    Ok(Some(RmrkCollectionInfo {163                        issuer: collection.owner.clone(),164                        metadata: RmrkCore::get_collection_property(collection_id, RmrkProperty::Metadata)?.decode_or_default(),165                        max: collection.limits.token_limit,166                        symbol: collection.token_prefix.rebind(), // change167                        nfts_count168                    }))169                }170171                fn nft_by_id(collection_id: RmrkCollectionId, nft_by_id: RmrkNftId) -> Result<Option<RmrkInstanceInfo<AccountId>>, DispatchError> {172                    use frame_support::BoundedVec;173                    use up_data_structs::mapping::TokenAddressMapping;174                    use pallet_proxy_rmrk_core::{RmrkProperty, misc::RmrkDecode};175176                    let collection_id = CollectionId(collection_id);177                    let nft_id = TokenId(nft_by_id);178                    if !RmrkCore::nft_exists(collection_id, nft_id) { return Ok(None); }179180                    let owner = match (dispatch_unique_runtime!(collection_id.token_owner(nft_id)) as Result<Option<CrossAccountId>, DispatchError>)? {181                        Some(owner) => match <Runtime as pallet_common::Config>::CrossTokenAddressMapping::address_to_token(&owner) {182                            Some((col, tok)) => RmrkAccountIdOrCollectionNftTuple::CollectionAndNftTuple(col.0, tok.0),183                            None => RmrkAccountIdOrCollectionNftTuple::AccountId(owner.as_sub().clone())184                        },185                        None => return Ok(None)186                    };187                    188                    let allowance = pallet_nonfungible::Allowance::<Runtime>::get((collection_id, nft_id));189190                    Ok(Some(RmrkInstanceInfo {191                        owner: owner,192                        royalty: RmrkCore::get_nft_property(collection_id, nft_id, RmrkProperty::RoyaltyInfo)?.decode_or_default(),193                        metadata: RmrkCore::get_nft_property(collection_id, nft_id, RmrkProperty::Metadata)?.decode_or_default(),194                        equipped: RmrkCore::get_nft_property(collection_id, nft_id, RmrkProperty::Equipped)?.decode_or_default(),195                        pending: allowance.is_some(),196                    }))197                }198199                fn account_tokens(account_id: AccountId, collection_id: RmrkCollectionId) -> Result<Vec<RmrkNftId>, DispatchError> {200                    let cross_account_id = CrossAccountId::from_sub(account_id);201                    let collection_id = CollectionId(collection_id);202                    if !RmrkCore::collection_exists(collection_id) { return Ok(Vec::new()); }203204                    Ok(205                        (dispatch_unique_runtime!(collection_id.account_tokens(cross_account_id)) as Result<Vec<TokenId>, DispatchError>)?206                        //<Runtime as up_rpc::UniqueApi<Block, CrossAccountId, AccountId>>::account_tokens(collection_id, cross_account_id)?207                            .into_iter()208                            .map(|token| token.0)209                            .collect::<Vec<_>>()210                    )211                }212213                fn nft_children(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Result<Vec<RmrkNftChild>, DispatchError> {214                    use up_data_structs::mapping::TokenAddressMapping;215216                    let collection_id = CollectionId(collection_id);217                    let nft_id = TokenId(nft_id);218                    if !RmrkCore::nft_exists(collection_id, nft_id) { return Ok(Vec::new()); }219220                    let cross_account_id = CrossAccountId::from_eth(221                        EvmTokenAddressMapping::token_to_address(collection_id, nft_id)222                    );223224                    Ok(225                        pallet_nonfungible::Owned::<Runtime>::iter_prefix((collection_id, cross_account_id))226                            .map(|(child_id, _)| RmrkNftChild {227                                collection_id: collection_id.0, // todo make sure they're always from this collection // spoiler: they're not228                                nft_id: child_id.0,229                            })230                            .collect()231                    )232                }233234                fn collection_properties(collection_id: RmrkCollectionId, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Result<Vec<RmrkPropertyInfo>, DispatchError> {235                    use pallet_proxy_rmrk_core::misc::RmrkDecode;236237                    let collection_id = CollectionId(collection_id);238                    if !RmrkCore::collection_exists(collection_id) { return Ok(Vec::new()); }239240                    let properties = Common::collection_properties(collection_id);241242                    // todo repeated code243                    return Ok(match filter_keys {244                        Some(keys) => {245                            let keys = Common::bytes_keys_to_property_keys(keys)?;246                            let properties = keys247                                .into_iter()248                                .filter_map(|key| {249                                    properties.get(&key).map(|value| RmrkPropertyInfo {250                                        key: key.decode_or_default(),251                                        value: value.decode_or_default(),252                                    })253                                })254                                .collect();255256                            properties257                        }258                        None => {259                            properties260                                .iter()261                                .filter_map(|(key, value)| Some(RmrkPropertyInfo {262                                    key: key.decode_or_default(),263                                    value: value.decode_or_default(),264                                }))265                                .collect()266                        }267                    });268                }269270                fn nft_properties(collection_id: RmrkCollectionId, nft_id: RmrkNftId, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Result<Vec<RmrkPropertyInfo>, DispatchError> {271                    use frame_support::BoundedVec;272                    use pallet_proxy_rmrk_core::misc::RmrkDecode;273274                    let collection_id = CollectionId(collection_id);275                    let token_id = TokenId(nft_id);276                    if !RmrkCore::nft_exists(collection_id, token_id) { return Ok(Vec::new()); }277278		            let properties = Nonfungible::token_properties((collection_id, token_id));279                    // todo look into this usage of pallet_nonfungible280281                    // todo displace to a function? redundant code piece with collection props282                    return Ok(match filter_keys {283                        Some(keys) => {284                            let keys = Common::bytes_keys_to_property_keys(keys)?;285                            let properties = keys286                                .into_iter()287                                .filter_map(|key| {288                                    properties.get(&key).map(|value| RmrkPropertyInfo {289                                        key: key.decode_or_default(),290                                        value: value.decode_or_default(),291                                    })292                                })293                                .collect();294295                            properties296                        }297                        None => {298                            properties299                                .iter()300                                .filter_map(|(key, value)| Some(RmrkPropertyInfo {301                                    key: key.decode_or_default(),302                                    value: value.decode_or_default(),303                                }))304                                .collect()305                        }306                    });307                }308309                fn nft_resources(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Result<Vec<RmrkResourceInfo>, DispatchError> {310                    use frame_support::BoundedVec;311                    use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, NftType}};312313                    let collection_id = CollectionId(collection_id);314                    if RmrkCore::ensure_collection_type(collection_id, CollectionType::Resource).is_err() { return Ok(Vec::new()); }315316                    let nft_id = TokenId(nft_id);317                    if RmrkCore::ensure_nft_type(collection_id, nft_id, NftType::Resource).is_err() { return Ok(Vec::new()); }318319                    Ok(Vec::new(/*[RmrkResourceInfo {320                        321                    }]*/))322                }323324                fn nft_resource_priorities(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Result<Vec<RmrkResourceId>, DispatchError> {325                    todo!()326                }327328                fn base(base_id: RmrkBaseId) -> Result<Option<RmrkBaseInfo<AccountId>>, DispatchError> {329                    use frame_support::BoundedVec;330                    use scale_info::prelude::string::String;331                    use pallet_proxy_rmrk_core::{332                        RmrkProperty, misc::{CollectionType, RmrkRebind, RmrkDecode},333                    };334335                    let collection_id = CollectionId(base_id);336                    let collection = match RmrkCore::get_typed_nft_collection(collection_id, CollectionType::Base) {337                        Ok(c) => c,338                        Err(_) => return Ok(None),339                    };340341                    Ok(Some(RmrkBaseInfo {342                        issuer: collection.owner.clone(),343                        base_type: RmrkCore::get_collection_property(collection_id, RmrkProperty::BaseType)?.decode_or_default(),344                        symbol: collection.token_prefix.rebind(),345                    }))346                }347348                fn base_parts(base_id: RmrkBaseId) -> Result<Vec<RmrkPartType>, DispatchError> {349                    use frame_support::BoundedVec;350                    use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, RmrkNft, RmrkDecode}};351352                    let collection_id = CollectionId(base_id);353                    if RmrkCore::ensure_collection_type(collection_id, CollectionType::Base).is_err() { return Ok(Vec::new()); }354355                    let parts = (dispatch_unique_runtime!(collection_id.collection_tokens()) as Result<Vec<TokenId>, DispatchError>)?356                        .iter()357                        .filter_map(|token_id| {358                            let nft_type = RmrkCore::get_nft_type(collection_id, *token_id).unwrap();359360                            match nft_type {361                                FixedPart => Some(RmrkPartType::FixedPart(RmrkFixedPart {362                                    id: token_id.0,363                                    src: RmrkCore::get_nft_property(collection_id, *token_id, RmrkProperty::Src).unwrap().decode_or_default(),364                                    z: RmrkCore::get_nft_property(collection_id, *token_id, RmrkProperty::ZIndex).unwrap().decode_or_default(),365                                })),366                                SlotPart => Some(RmrkPartType::SlotPart(RmrkSlotPart {367                                    id: token_id.0,368                                    src: RmrkCore::get_nft_property(collection_id, *token_id, RmrkProperty::Src).unwrap().decode_or_default(),369                                    z: RmrkCore::get_nft_property(collection_id, *token_id, RmrkProperty::ZIndex).unwrap().decode_or_default(),370                                    equippable: RmrkCore::get_nft_property(collection_id, *token_id, RmrkProperty::EquippableList).unwrap().decode_or_default(),371                                })),372                                _ => None373                            }374                        })375                        .collect();376377                    Ok(parts)378                }379380                fn theme_names(base_id: RmrkBaseId) -> Result<Vec<RmrkThemeName>, DispatchError> {381                    use frame_support::BoundedVec;382                    use pallet_proxy_rmrk_core::{RmrkProperty, misc::{RmrkNft, RmrkDecode}};383384                    let collection_id = CollectionId(base_id);385                    // todo make sure this is theme386387                    let theme_names = (dispatch_unique_runtime!(collection_id.collection_tokens()) as Result<Vec<TokenId>, DispatchError>)?388                        .iter()389                        .filter_map(|token_id| {390                            let nft_type = RmrkCore::get_nft_type(collection_id, *token_id).unwrap();391                            392                            match nft_type {393                                Theme => Some(394                                    RmrkCore::get_nft_property(collection_id, *token_id, RmrkProperty::ThemeName).unwrap().decode_or_default()395                                ),396                                _ => None397                            }398                        })399                        .collect::<Vec<RmrkThemeName>>();400401                    Ok(theme_names)402                }403404                fn theme(base_id: RmrkBaseId, theme_name: RmrkThemeName, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Result<Option<RmrkTheme>, DispatchError> {405                    use frame_support::BoundedVec;406407                    let collection_id = CollectionId(base_id);408409                    // todo one theme. filter collection tokens according to theme name, should result in one410                    // (is it possible to search with iter_prefix for part of a struct that satisfies?..)411                    // filter properties according to filter_keys and load them into resulting theme.properties412                    let themes = (dispatch_unique_runtime!(collection_id.collection_tokens()) as Result<Vec<TokenId>, DispatchError>)?413                        .iter()414                        .filter_map(|token_id| {415                            let properties = Nonfungible::token_properties((collection_id, token_id));416417                            // todo ping properties for "rmrk:nft-type"418                            // if none, skip, None419                            // ugh gonna go through ALL properties, searching for matches for "rmrk:theme-property-<key>"420                            let nft_type = "theme";421                            match nft_type {422                                "theme" => Some(RmrkTheme {423                                    name: BoundedVec::try_from(424                                        <pallet_nonfungible::TokenData<Runtime>>::get((collection_id, token_id))425                                            .map(|t| t.const_data)426                                            .unwrap_or_default()427                                            .into_inner()428                                    ).unwrap(),429                                    // todo? (dispatch_unique_runtime!(collection_id.const_metadata(token_id)) as Result<Vec<u8>, DispatchError>)?,430                                    properties: Vec::new(), // pain in the ass431                                    inherit: false, // "rmrk:theme-inherit"432                                }),433                                _ => None434                            }435                        })436                        .collect::<Vec<_>>();437438                    // todo439                    Ok(Some(themes[0].clone()))440                }441            }442443            impl sp_api::Core<Block> for Runtime {444                fn version() -> RuntimeVersion {445                    VERSION446                }447448                fn execute_block(block: Block) {449                    Executive::execute_block(block)450                }451452                fn initialize_block(header: &<Block as BlockT>::Header) {453                    Executive::initialize_block(header)454                }455            }456457            impl sp_api::Metadata<Block> for Runtime {458                fn metadata() -> OpaqueMetadata {459                    OpaqueMetadata::new(Runtime::metadata().into())460                }461            }462463            impl sp_block_builder::BlockBuilder<Block> for Runtime {464                fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {465                    Executive::apply_extrinsic(extrinsic)466                }467468                fn finalize_block() -> <Block as BlockT>::Header {469                    Executive::finalize_block()470                }471472                fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {473                    data.create_extrinsics()474                }475476                fn check_inherents(477                    block: Block,478                    data: sp_inherents::InherentData,479                ) -> sp_inherents::CheckInherentsResult {480                    data.check_extrinsics(&block)481                }482483                // fn random_seed() -> <Block as BlockT>::Hash {484                //     RandomnessCollectiveFlip::random_seed().0485                // }486            }487488            impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {489                fn validate_transaction(490                    source: TransactionSource,491                    tx: <Block as BlockT>::Extrinsic,492                    hash: <Block as BlockT>::Hash,493                ) -> TransactionValidity {494                    Executive::validate_transaction(source, tx, hash)495                }496            }497498            impl sp_offchain::OffchainWorkerApi<Block> for Runtime {499                fn offchain_worker(header: &<Block as BlockT>::Header) {500                    Executive::offchain_worker(header)501                }502            }503504            impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {505                fn chain_id() -> u64 {506                    <Runtime as pallet_evm::Config>::ChainId::get()507                }508509                fn account_basic(address: H160) -> EVMAccount {510                    EVM::account_basic(&address)511                }512513                fn gas_price() -> U256 {514                    <Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price()515                }516517                fn account_code_at(address: H160) -> Vec<u8> {518                    EVM::account_codes(address)519                }520521                fn author() -> H160 {522                    <pallet_evm::Pallet<Runtime>>::find_author()523                }524525                fn storage_at(address: H160, index: U256) -> H256 {526                    let mut tmp = [0u8; 32];527                    index.to_big_endian(&mut tmp);528                    EVM::account_storages(address, H256::from_slice(&tmp[..]))529                }530531                #[allow(clippy::redundant_closure)]532                fn call(533                    from: H160,534                    to: H160,535                    data: Vec<u8>,536                    value: U256,537                    gas_limit: U256,538                    max_fee_per_gas: Option<U256>,539                    max_priority_fee_per_gas: Option<U256>,540                    nonce: Option<U256>,541                    estimate: bool,542                    access_list: Option<Vec<(H160, Vec<H256>)>>,543                ) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {544                    let config = if estimate {545                        let mut config = <Runtime as pallet_evm::Config>::config().clone();546                        config.estimate = true;547                        Some(config)548                    } else {549                        None550                    };551552                    let is_transactional = false;553                    <Runtime as pallet_evm::Config>::Runner::call(554                        CrossAccountId::from_eth(from),555                        to,556                        data,557                        value,558                        gas_limit.low_u64(),559                        max_fee_per_gas,560                        max_priority_fee_per_gas,561                        nonce,562                        access_list.unwrap_or_default(),563                        is_transactional,564                        config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),565                    ).map_err(|err| err.into())566                }567568                #[allow(clippy::redundant_closure)]569                fn create(570                    from: H160,571                    data: Vec<u8>,572                    value: U256,573                    gas_limit: U256,574                    max_fee_per_gas: Option<U256>,575                    max_priority_fee_per_gas: Option<U256>,576                    nonce: Option<U256>,577                    estimate: bool,578                    access_list: Option<Vec<(H160, Vec<H256>)>>,579                ) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {580                    let config = if estimate {581                        let mut config = <Runtime as pallet_evm::Config>::config().clone();582                        config.estimate = true;583                        Some(config)584                    } else {585                        None586                    };587588                    let is_transactional = false;589                    <Runtime as pallet_evm::Config>::Runner::create(590                        CrossAccountId::from_eth(from),591                        data,592                        value,593                        gas_limit.low_u64(),594                        max_fee_per_gas,595                        max_priority_fee_per_gas,596                        nonce,597                        access_list.unwrap_or_default(),598                        is_transactional,599                        config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),600                    ).map_err(|err| err.into())601                }602603                fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {604                    Ethereum::current_transaction_statuses()605                }606607                fn current_block() -> Option<pallet_ethereum::Block> {608                    Ethereum::current_block()609                }610611                fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {612                    Ethereum::current_receipts()613                }614615                fn current_all() -> (616                    Option<pallet_ethereum::Block>,617                    Option<Vec<pallet_ethereum::Receipt>>,618                    Option<Vec<TransactionStatus>>619                ) {620                    (621                        Ethereum::current_block(),622                        Ethereum::current_receipts(),623                        Ethereum::current_transaction_statuses()624                    )625                }626627                fn extrinsic_filter(xts: Vec<<Block as sp_api::BlockT>::Extrinsic>) -> Vec<pallet_ethereum::Transaction> {628                    xts.into_iter().filter_map(|xt| match xt.0.function {629                        Call::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction),630                        _ => None631                    }).collect()632                }633634                fn elasticity() -> Option<Permill> {635                    None636                }637            }638639            impl fp_rpc::ConvertTransactionRuntimeApi<Block> for Runtime {640                fn convert_transaction(transaction: pallet_ethereum::Transaction) -> <Block as BlockT>::Extrinsic  {641                    UncheckedExtrinsic::new_unsigned(642                        pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),643                    )644                }645            }646647            impl sp_session::SessionKeys<Block> for Runtime {648                fn decode_session_keys(649                    encoded: Vec<u8>,650                ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {651                    SessionKeys::decode_into_raw_public_keys(&encoded)652                }653654                fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {655                    SessionKeys::generate(seed)656                }657            }658659            impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {660                fn slot_duration() -> sp_consensus_aura::SlotDuration {661                    sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())662                }663664                fn authorities() -> Vec<AuraId> {665                    Aura::authorities().to_vec()666                }667            }668669            impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {670                fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {671                    ParachainSystem::collect_collation_info(header)672                }673            }674675            impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {676                fn account_nonce(account: AccountId) -> Index {677                    System::account_nonce(account)678                }679            }680681            impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {682                fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {683                    TransactionPayment::query_info(uxt, len)684                }685                fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {686                    TransactionPayment::query_fee_details(uxt, len)687                }688            }689690            /*691            impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber, Hash>692                for Runtime693            {694                fn call(695                    origin: AccountId,696                    dest: AccountId,697                    value: Balance,698                    gas_limit: u64,699                    input_data: Vec<u8>,700                ) -> pallet_contracts_primitives::ContractExecResult {701                    Contracts::bare_call(origin, dest, value, gas_limit, input_data, false)702                }703704                fn instantiate(705                    origin: AccountId,706                    endowment: Balance,707                    gas_limit: u64,708                    code: pallet_contracts_primitives::Code<Hash>,709                    data: Vec<u8>,710                    salt: Vec<u8>,711                ) -> pallet_contracts_primitives::ContractInstantiateResult<AccountId, BlockNumber>712                {713                    Contracts::bare_instantiate(origin, endowment, gas_limit, code, data, salt, true, false)714                }715716                fn get_storage(717                    address: AccountId,718                    key: [u8; 32],719                ) -> pallet_contracts_primitives::GetStorageResult {720                    Contracts::get_storage(address, key)721                }722723                fn rent_projection(724                    address: AccountId,725                ) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {726                    Contracts::rent_projection(address)727                }728            }729            */730731            #[cfg(feature = "runtime-benchmarks")]732            impl frame_benchmarking::Benchmark<Block> for Runtime {733                fn benchmark_metadata(extra: bool) -> (734                    Vec<frame_benchmarking::BenchmarkList>,735                    Vec<frame_support::traits::StorageInfo>,736                ) {737                    use frame_benchmarking::{list_benchmark, Benchmarking, BenchmarkList};738                    use frame_support::traits::StorageInfoTrait;739740                    let mut list = Vec::<BenchmarkList>::new();741742                    list_benchmark!(list, extra, pallet_evm_migration, EvmMigration);743                    list_benchmark!(list, extra, pallet_common, Common);744                    list_benchmark!(list, extra, pallet_unique, Unique);745                    list_benchmark!(list, extra, pallet_structure, Structure);746                    list_benchmark!(list, extra, pallet_inflation, Inflation);747                    list_benchmark!(list, extra, pallet_fungible, Fungible);748                    list_benchmark!(list, extra, pallet_refungible, Refungible);749                    list_benchmark!(list, extra, pallet_nonfungible, Nonfungible);750                    // list_benchmark!(list, extra, pallet_evm_coder_substrate, EvmCoderSubstrate);751752                    let storage_info = AllPalletsReversedWithSystemFirst::storage_info();753754                    return (list, storage_info)755                }756757                fn dispatch_benchmark(758                    config: frame_benchmarking::BenchmarkConfig759                ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {760                    use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};761762                    let allowlist: Vec<TrackedStorageKey> = vec![763                        // Total Issuance764                        hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),765766                        // Block Number767                        hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),768                        // Execution Phase769                        hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),770                        // Event Count771                        hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),772                        // System Events773                        hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),774775                        // Evm CurrentLogs776                        hex_literal::hex!("1da53b775b270400e7e61ed5cbc5a146547f210cec367e9af919603343b9cb56").to_vec().into(),777778                        // Transactional depth779                        hex_literal::hex!("3a7472616e73616374696f6e5f6c6576656c3a").to_vec().into(),780                    ];781782                    let mut batches = Vec::<BenchmarkBatch>::new();783                    let params = (&config, &allowlist);784785                    add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);786                    add_benchmark!(params, batches, pallet_common, Common);787                    add_benchmark!(params, batches, pallet_unique, Unique);788                    add_benchmark!(params, batches, pallet_structure, Structure);789                    add_benchmark!(params, batches, pallet_inflation, Inflation);790                    add_benchmark!(params, batches, pallet_fungible, Fungible);791                    add_benchmark!(params, batches, pallet_refungible, Refungible);792                    add_benchmark!(params, batches, pallet_nonfungible, Nonfungible);793                    // add_benchmark!(params, batches, pallet_evm_coder_substrate, EvmCoderSubstrate);794795                    if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }796                    Ok(batches)797                }798            }799800            #[cfg(feature = "try-runtime")]801            impl frame_try_runtime::TryRuntime<Block> for Runtime {802                fn on_runtime_upgrade() -> (Weight, Weight) {803                    log::info!("try-runtime::on_runtime_upgrade unique-chain.");804                    let weight = Executive::try_runtime_upgrade().unwrap();805                    (weight, RuntimeBlockWeights::get().max_block)806                }807808                fn execute_block_no_check(block: Block) -> Weight {809                    Executive::execute_block_no_check(block)810                }811            }812        }813    }814}