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

difftreelog

source

runtime/common/src/runtime_apis.rs41.1 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| pallet_common::Pallet::<Runtime>::bytes_keys_to_property_keys(keys)42                    ).transpose()?;4344                    pallet_common::Pallet::<Runtime>::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| pallet_common::Pallet::<Runtime>::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| pallet_common::Pallet::<Runtime>::bytes_keys_to_property_keys(keys)65                    ).transpose()?;6667                    pallet_common::Pallet::<Runtime>::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(<pallet_common::CreatedCollectionCount<Runtime>>::get().0) // todo storage from proxy pallet146                }147                fn collection_by_id(collection_id: RmrkCollectionId) -> Result<Option<RmrkCollectionInfo<AccountId>>, DispatchError> {148                    // TODO decide on displacement to palettes -- does RMRK belong there, spread across common and nonfungible?149                    use frame_support::BoundedVec;150                    use scale_info::prelude::string::String;151                    use pallet_proxy_rmrk_core::RmrkProperty;152153                    // todo check if this is a rmrk collection? or simply trust and provide anyway?154                    // client-is-always-right / enforce authority and order ?155156                    let collection_id = CollectionId(collection_id);157                    let collection = <pallet_proxy_rmrk_core::Pallet<Runtime>>::get_nft_collection(collection_id)?;158                    // todo Vec::from(["rmrk:metadata", "rmrk:collection-type"])159                    let metadata = BoundedVec::try_from(160                        <pallet_proxy_rmrk_core::Pallet<Runtime>>::get_collection_property(collection_id, RmrkProperty::Metadata)?.into_inner()161                    ).map_err(|_| <pallet_common::Error<Runtime>>::PropertyKeyIsTooLong)?;//unwrap_or_default();162                    let nfts_count = (dispatch_unique_runtime!(collection_id.total_supply()) as Result<u32, DispatchError>)?; // todo? <Runtime>::total_supply(collection_id)163164                    Ok(Some(RmrkCollectionInfo {165                        issuer: collection.owner.clone(),166                        metadata,167                        max: collection.limits.token_limit,168                        symbol: BoundedVec::try_from(169                            collection.token_prefix.clone().into_inner()170                        ).map_err(|_| <pallet_common::Error<Runtime>>::PropertyKeyIsTooLong)?,171                        nfts_count172                    }))173                }174                fn nft_by_id(collection_id: RmrkCollectionId, nft_by_id: RmrkNftId) -> Result<Option<RmrkInstanceInfo<AccountId>>, DispatchError> {175                    use frame_support::BoundedVec;176                    use up_data_structs::mapping::TokenAddressMapping;177                    use pallet_proxy_rmrk_core::RmrkProperty;178179                    let collection_id = CollectionId(collection_id);180                    let nft_id = TokenId(nft_by_id);181182                    let owner = match (dispatch_unique_runtime!(collection_id.token_owner(nft_id)) as Result<Option<CrossAccountId>, DispatchError>)? {183                        Some(owner) => match <Runtime as pallet_common::Config>::CrossTokenAddressMapping::address_to_token(&owner) {184                            Some((col, tok)) => RmrkAccountIdOrCollectionNftTuple::CollectionAndNftTuple(col.0, tok.0),185                            None => RmrkAccountIdOrCollectionNftTuple::AccountId(owner.as_sub().clone())186                        },187                        None => return Ok(None)188                    };189190                    let keys = [191                        RmrkProperty::RoyaltyInfo,192                        RmrkProperty::Metadata,193                        RmrkProperty::Equipped,194                        // ?? "rmrk:recipient", "rmrk:nft-type", "rmrk:resource-collection", "rmrk:resource-priorities"195                    ];196197                    let properties = keys.into_iter().map(198                        |key| BoundedVec::try_from(199                            // todo nft property, not collection200                            <pallet_proxy_rmrk_core::Pallet<Runtime>>::get_nft_property(collection_id, nft_id, key).unwrap().into_inner()201                        ).unwrap()202                    )203                    .collect::<Vec<RmrkString>>();204205                    Ok(Some(RmrkInstanceInfo {206                        owner: owner,207                        //recipient: , // prop?208                        royalty: None,//Permill::from_percent(0), // prop, decode209                        metadata: properties[1].clone(),210                        equipped: false, // prop, decode211                        pending: false, // prop, decode212                    }))213                }214                fn account_tokens(account_id: AccountId, collection_id: RmrkCollectionId) -> Result<Vec<RmrkNftId>, DispatchError> {215                    let cross_account_id = CrossAccountId::from_sub(account_id);216                    let collection_id = CollectionId(collection_id);217                    Ok(218                        (dispatch_unique_runtime!(collection_id.account_tokens(cross_account_id)) as Result<Vec<TokenId>, DispatchError>)?219                        //<Runtime as up_rpc::UniqueApi<Block, CrossAccountId, AccountId>>::account_tokens(collection_id, cross_account_id)?220                            .into_iter()221                            .map(|token| token.0)222                            .collect::<Vec<_>>()223                    )224                }225                fn nft_children(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Result<Vec<RmrkNftChild>, DispatchError> {226                    use up_data_structs::mapping::TokenAddressMapping;227228                    let collection_id = CollectionId(collection_id);229                    let nft_id = TokenId(nft_id);230                    let cross_account_id = CrossAccountId::from_eth(231                        EvmTokenAddressMapping::token_to_address(collection_id, nft_id)232                    );233234                    Ok(235                        pallet_nonfungible::Owned::<Runtime>::iter_prefix((collection_id, cross_account_id))236                            .map(|(child_id, _)| RmrkNftChild {237                                collection_id: collection_id.0, // todo make sure they're always from this collection238                                nft_id: child_id.0,239                            })240                            .collect()241                    )242                }243                fn collection_properties(collection_id: RmrkCollectionId, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Result<Vec<RmrkPropertyInfo>, DispatchError> {244                    use frame_support::BoundedVec;245246                    let collection_id = CollectionId(collection_id);247                    let properties = pallet_common::Pallet::<Runtime>::collection_properties(collection_id);248249                    return Ok(match filter_keys {250                        Some(keys) => {251                            let keys = pallet_common::Pallet::<Runtime>::bytes_keys_to_property_keys(keys)?;252                            let properties = keys253                                .into_iter()254                                .filter_map(|key| {255                                    properties.get(&key).map(|value| RmrkPropertyInfo {256                                        key: BoundedVec::try_from(key.into_inner()).unwrap(),257                                        value: BoundedVec::try_from(value.clone().into_inner()).unwrap(),258                                    })259                                })260                                .collect();261262                            properties263                        }264                        None => {265                            properties266                                .iter()267                                .filter_map(|(key, value)| Some(RmrkPropertyInfo {268                                    key: BoundedVec::try_from(key.clone().into_inner()).unwrap(),269                                    value: BoundedVec::try_from(value.clone().into_inner()).unwrap(),270                                }))271                                .collect()272                        }273                    });274                }275                fn nft_properties(collection_id: RmrkCollectionId, nft_id: RmrkNftId, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Result<Vec<RmrkPropertyInfo>, DispatchError> {276                    use frame_support::BoundedVec;277278                    let collection_id = CollectionId(collection_id);279                    let token_id = TokenId(nft_id);280281		            let properties = pallet_nonfungible::Pallet::<Runtime>::token_properties((collection_id, token_id)); // todo look into usage of pallet_nonfungible282283                    // todo displace to a function? redundant code piece with collection props284                    return Ok(match filter_keys {285                        Some(keys) => {286                            let keys = pallet_common::Pallet::<Runtime>::bytes_keys_to_property_keys(keys)?;287                            let properties = keys288                                .into_iter()289                                .filter_map(|key| {290                                    properties.get(&key).map(|value| RmrkPropertyInfo {291                                        key: BoundedVec::try_from(key.into_inner()).unwrap(),292                                        value: BoundedVec::try_from(value.clone().into_inner()).unwrap(),293                                    })294                                })295                                .collect();296297                            properties298                        }299                        None => {300                            properties301                                .iter()302                                .filter_map(|(key, value)| Some(RmrkPropertyInfo {303                                    key: BoundedVec::try_from(key.clone().into_inner()).unwrap(),304                                    value: BoundedVec::try_from(value.clone().into_inner()).unwrap(),305                                }))306                                .collect()307                        }308                    });309                }310                fn nft_resources(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Result<Vec<RmrkResourceInfo>, DispatchError> {311                    use frame_support::BoundedVec;312                    use pallet_proxy_rmrk_core::RmrkProperty;313314                    let collection_id = CollectionId(collection_id);315                    let nft_id = TokenId(nft_id);316317                    // let keys = [318                    //     RmrkProperty::Royalty,319                    //     RmrkProperty::Metadata,320                    //     RmrkProperty::Equipped,321                    //     RmrkProperty::Pending,322                    //     // ?? "rmrk:recipient", "rmrk:nft-type", "rmrk:resource-collection", "rmrk:resource-priorities"323                    // ];324325                    /*let resources = keys.into_iter().map(326                        |key| BoundedVec::try_from(327                            <pallet_proxy_rmrk_core::Pallet<Runtime>>::get_nft_property(collection_id, nft_id, key).unwrap().into_inner()328                        ).unwrap()329                    )330                    .collect::<Vec<RmrkString>>();*/331332                    Ok(Vec::new(/*[RmrkResourceInfo {333334                    }]*/))335                }336                fn nft_resource_priorities(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Result<Vec<RmrkResourceId>, DispatchError> {337                    todo!()338                }339                fn base(base_id: RmrkBaseId) -> Result<Option<RmrkBaseInfo<AccountId>>, DispatchError> {340                    use frame_support::BoundedVec;341                    use scale_info::prelude::string::String;342                    use pallet_proxy_rmrk_core::RmrkProperty;343344                    let collection_id = CollectionId(base_id);345                    let collection = <pallet_proxy_rmrk_core::Pallet<Runtime>>::get_nft_collection(collection_id)?;346347                    // todo export to macro? redundancy348                    let keys = [349                        RmrkProperty::BaseType,350                    ];351352                    let properties = keys.into_iter().map(353                        |key| BoundedVec::try_from(354                            <pallet_proxy_rmrk_core::Pallet<Runtime>>::get_collection_property(collection_id, key).unwrap().into_inner()355                        )356                    )357                    // todo not-a-rmrk-collection error358                    .collect::<Result<Vec<_>, _>>()359                    .map_err(|_| <pallet_proxy_rmrk_core::Error<Runtime>>::CollectionUnknown)?;360361                    Ok(Some(RmrkBaseInfo {362                        issuer: collection.owner.clone(),363                        base_type: properties[0].clone(),364                        symbol: BoundedVec::try_from(365                            collection.token_prefix.clone().into_inner()366                        ).map_err(|_| <pallet_common::Error<Runtime>>::PropertyKeyIsTooLong)?,367                    }))368                }369                fn base_parts(base_id: RmrkBaseId) -> Result<Vec<RmrkPartType>, DispatchError> {370                    use frame_support::BoundedVec;371                    use pallet_proxy_rmrk_core::RmrkProperty;372373                    let collection_id = CollectionId(base_id);374375                    let keys = [376                        //RmrkProperty::NftType)?,377                        //RmrkProperty::PartId)?,378                        RmrkProperty::Src,379                        RmrkProperty::ZIndex,380                        RmrkProperty::EquippableList,381                    ];382383                    let parts = (dispatch_unique_runtime!(collection_id.collection_tokens()) as Result<Vec<TokenId>, DispatchError>)?384                        .iter()385                        .filter_map(|token_id| {386                            /*let properties = keys.into_iter().map(387                                |key| BoundedVec::try_from(388                                    <pallet_proxy_rmrk_core::Pallet<Runtime>>::get_nft_property(collection_id, *token_id, key).unwrap().into_inner()389                                ).unwrap()390                            ).collect::<Vec<RmrkString>>();*/391392                            // todo ping properties for "rmrk:nft-type"393                            // if none, skip, None394                            let nft_type = "fixed-part";395396                            match nft_type {397                                "fixed-part" => Some(RmrkPartType::FixedPart(RmrkFixedPart {398                                    id: token_id.0,399                                    src: BoundedVec::default(), // "rmrk:src"400                                    z: 0, // "rmrk:z-index"401                                })),402                                "slot-part" => Some(RmrkPartType::SlotPart(RmrkSlotPart {403                                    id: token_id.0,404                                    equippable: RmrkEquippableList::Empty, // "rmrk:equippable-list" ?405                                    src: BoundedVec::default(), // "rmrk:src"406                                    z: 0, // "rmrk:z-index"407                                })),408                                _ => None409                            }410411                        })412                        .collect();413414                    Ok(parts)415                }416                fn theme_names(base_id: RmrkBaseId) -> Result<Vec<RmrkThemeName>, DispatchError> {417                    use frame_support::BoundedVec;418419                    let collection_id = CollectionId(base_id);420421                    let theme_names = (dispatch_unique_runtime!(collection_id.collection_tokens()) as Result<Vec<TokenId>, DispatchError>)?422                        .iter()423                        .filter_map(|token_id| {424                            let properties = pallet_nonfungible::Pallet::<Runtime>::token_properties((collection_id, token_id));425426                            // todo ping property for "rmrk:nft-type"427                            // if none or not "theme", skip, None428                            let nft_type = "theme";429                            // can't call dispatch_unique_runtime! from here??430                            <pallet_nonfungible::TokenData<Runtime>>::get((collection_id, token_id))431                                .map(|t| t.const_data.into_inner())432                                //.unwrap_or_default()433                            // todo rework to reduce independence434                        })435                        .collect();436437                    Ok(theme_names)438                }439                fn theme(base_id: RmrkBaseId, theme_name: RmrkThemeName, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Result<Option<RmrkTheme>, DispatchError> {440                    use frame_support::BoundedVec;441442                    let collection_id = CollectionId(base_id);443444                    // todo one theme. filter collection tokens according to theme name, should result in one445                    // (is it possible to search with iter_prefix for part of a struct that satisfies?..)446                    // filter properties according to filter_keys and load them into resulting theme.properties447                    let themes = (dispatch_unique_runtime!(collection_id.collection_tokens()) as Result<Vec<TokenId>, DispatchError>)?448                        .iter()449                        .filter_map(|token_id| {450                            let properties = pallet_nonfungible::Pallet::<Runtime>::token_properties((collection_id, token_id));451452                            // todo ping properties for "rmrk:nft-type"453                            // if none, skip, None454                            // ugh gonna go through ALL properties, searching for matches for "rmrk:theme-property-<key>"455                            let nft_type = "theme";456                            match nft_type {457                                "theme" => Some(RmrkTheme {458                                    name: BoundedVec::try_from(459                                        <pallet_nonfungible::TokenData<Runtime>>::get((collection_id, token_id))460                                            .map(|t| t.const_data)461                                            .unwrap_or_default()462                                            .into_inner()463                                    ).unwrap(),464                                    // todo? (dispatch_unique_runtime!(collection_id.const_metadata(token_id)) as Result<Vec<u8>, DispatchError>)?,465                                    properties: Vec::new(), // pain in the ass466                                    inherit: false, // "rmrk:theme-inherit"467                                }),468                                _ => None469                            }470                        })471                        .collect::<Vec<_>>();472473                    // todo474                    Ok(Some(themes[0].clone()))475                }476            }477478            impl sp_api::Core<Block> for Runtime {479                fn version() -> RuntimeVersion {480                    VERSION481                }482483                fn execute_block(block: Block) {484                    Executive::execute_block(block)485                }486487                fn initialize_block(header: &<Block as BlockT>::Header) {488                    Executive::initialize_block(header)489                }490            }491492            impl sp_api::Metadata<Block> for Runtime {493                fn metadata() -> OpaqueMetadata {494                    OpaqueMetadata::new(Runtime::metadata().into())495                }496            }497498            impl sp_block_builder::BlockBuilder<Block> for Runtime {499                fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {500                    Executive::apply_extrinsic(extrinsic)501                }502503                fn finalize_block() -> <Block as BlockT>::Header {504                    Executive::finalize_block()505                }506507                fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {508                    data.create_extrinsics()509                }510511                fn check_inherents(512                    block: Block,513                    data: sp_inherents::InherentData,514                ) -> sp_inherents::CheckInherentsResult {515                    data.check_extrinsics(&block)516                }517518                // fn random_seed() -> <Block as BlockT>::Hash {519                //     RandomnessCollectiveFlip::random_seed().0520                // }521            }522523            impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {524                fn validate_transaction(525                    source: TransactionSource,526                    tx: <Block as BlockT>::Extrinsic,527                    hash: <Block as BlockT>::Hash,528                ) -> TransactionValidity {529                    Executive::validate_transaction(source, tx, hash)530                }531            }532533            impl sp_offchain::OffchainWorkerApi<Block> for Runtime {534                fn offchain_worker(header: &<Block as BlockT>::Header) {535                    Executive::offchain_worker(header)536                }537            }538539            impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {540                fn chain_id() -> u64 {541                    <Runtime as pallet_evm::Config>::ChainId::get()542                }543544                fn account_basic(address: H160) -> EVMAccount {545                    EVM::account_basic(&address)546                }547548                fn gas_price() -> U256 {549                    <Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price()550                }551552                fn account_code_at(address: H160) -> Vec<u8> {553                    EVM::account_codes(address)554                }555556                fn author() -> H160 {557                    <pallet_evm::Pallet<Runtime>>::find_author()558                }559560                fn storage_at(address: H160, index: U256) -> H256 {561                    let mut tmp = [0u8; 32];562                    index.to_big_endian(&mut tmp);563                    EVM::account_storages(address, H256::from_slice(&tmp[..]))564                }565566                #[allow(clippy::redundant_closure)]567                fn call(568                    from: H160,569                    to: H160,570                    data: Vec<u8>,571                    value: U256,572                    gas_limit: U256,573                    max_fee_per_gas: Option<U256>,574                    max_priority_fee_per_gas: Option<U256>,575                    nonce: Option<U256>,576                    estimate: bool,577                    access_list: Option<Vec<(H160, Vec<H256>)>>,578                ) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {579                    let config = if estimate {580                        let mut config = <Runtime as pallet_evm::Config>::config().clone();581                        config.estimate = true;582                        Some(config)583                    } else {584                        None585                    };586587                    let is_transactional = false;588                    <Runtime as pallet_evm::Config>::Runner::call(589                        CrossAccountId::from_eth(from),590                        to,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                #[allow(clippy::redundant_closure)]604                fn create(605                    from: H160,606                    data: Vec<u8>,607                    value: U256,608                    gas_limit: U256,609                    max_fee_per_gas: Option<U256>,610                    max_priority_fee_per_gas: Option<U256>,611                    nonce: Option<U256>,612                    estimate: bool,613                    access_list: Option<Vec<(H160, Vec<H256>)>>,614                ) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {615                    let config = if estimate {616                        let mut config = <Runtime as pallet_evm::Config>::config().clone();617                        config.estimate = true;618                        Some(config)619                    } else {620                        None621                    };622623                    let is_transactional = false;624                    <Runtime as pallet_evm::Config>::Runner::create(625                        CrossAccountId::from_eth(from),626                        data,627                        value,628                        gas_limit.low_u64(),629                        max_fee_per_gas,630                        max_priority_fee_per_gas,631                        nonce,632                        access_list.unwrap_or_default(),633                        is_transactional,634                        config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),635                    ).map_err(|err| err.into())636                }637638                fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {639                    Ethereum::current_transaction_statuses()640                }641642                fn current_block() -> Option<pallet_ethereum::Block> {643                    Ethereum::current_block()644                }645646                fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {647                    Ethereum::current_receipts()648                }649650                fn current_all() -> (651                    Option<pallet_ethereum::Block>,652                    Option<Vec<pallet_ethereum::Receipt>>,653                    Option<Vec<TransactionStatus>>654                ) {655                    (656                        Ethereum::current_block(),657                        Ethereum::current_receipts(),658                        Ethereum::current_transaction_statuses()659                    )660                }661662                fn extrinsic_filter(xts: Vec<<Block as sp_api::BlockT>::Extrinsic>) -> Vec<pallet_ethereum::Transaction> {663                    xts.into_iter().filter_map(|xt| match xt.0.function {664                        Call::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction),665                        _ => None666                    }).collect()667                }668669                fn elasticity() -> Option<Permill> {670                    None671                }672            }673674            impl fp_rpc::ConvertTransactionRuntimeApi<Block> for Runtime {675                fn convert_transaction(transaction: pallet_ethereum::Transaction) -> <Block as BlockT>::Extrinsic  {676                    UncheckedExtrinsic::new_unsigned(677                        pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),678                    )679                }680            }681682            impl sp_session::SessionKeys<Block> for Runtime {683                fn decode_session_keys(684                    encoded: Vec<u8>,685                ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {686                    SessionKeys::decode_into_raw_public_keys(&encoded)687                }688689                fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {690                    SessionKeys::generate(seed)691                }692            }693694            impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {695                fn slot_duration() -> sp_consensus_aura::SlotDuration {696                    sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())697                }698699                fn authorities() -> Vec<AuraId> {700                    Aura::authorities().to_vec()701                }702            }703704            impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {705                fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {706                    ParachainSystem::collect_collation_info(header)707                }708            }709710            impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {711                fn account_nonce(account: AccountId) -> Index {712                    System::account_nonce(account)713                }714            }715716            impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {717                fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {718                    TransactionPayment::query_info(uxt, len)719                }720                fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {721                    TransactionPayment::query_fee_details(uxt, len)722                }723            }724725            /*726            impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber, Hash>727                for Runtime728            {729                fn call(730                    origin: AccountId,731                    dest: AccountId,732                    value: Balance,733                    gas_limit: u64,734                    input_data: Vec<u8>,735                ) -> pallet_contracts_primitives::ContractExecResult {736                    Contracts::bare_call(origin, dest, value, gas_limit, input_data, false)737                }738739                fn instantiate(740                    origin: AccountId,741                    endowment: Balance,742                    gas_limit: u64,743                    code: pallet_contracts_primitives::Code<Hash>,744                    data: Vec<u8>,745                    salt: Vec<u8>,746                ) -> pallet_contracts_primitives::ContractInstantiateResult<AccountId, BlockNumber>747                {748                    Contracts::bare_instantiate(origin, endowment, gas_limit, code, data, salt, true, false)749                }750751                fn get_storage(752                    address: AccountId,753                    key: [u8; 32],754                ) -> pallet_contracts_primitives::GetStorageResult {755                    Contracts::get_storage(address, key)756                }757758                fn rent_projection(759                    address: AccountId,760                ) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {761                    Contracts::rent_projection(address)762                }763            }764            */765766            #[cfg(feature = "runtime-benchmarks")]767            impl frame_benchmarking::Benchmark<Block> for Runtime {768                fn benchmark_metadata(extra: bool) -> (769                    Vec<frame_benchmarking::BenchmarkList>,770                    Vec<frame_support::traits::StorageInfo>,771                ) {772                    use frame_benchmarking::{list_benchmark, Benchmarking, BenchmarkList};773                    use frame_support::traits::StorageInfoTrait;774775                    let mut list = Vec::<BenchmarkList>::new();776777                    list_benchmark!(list, extra, pallet_evm_migration, EvmMigration);778                    list_benchmark!(list, extra, pallet_common, Common);779                    list_benchmark!(list, extra, pallet_unique, Unique);780                    list_benchmark!(list, extra, pallet_structure, Structure);781                    list_benchmark!(list, extra, pallet_inflation, Inflation);782                    list_benchmark!(list, extra, pallet_fungible, Fungible);783                    list_benchmark!(list, extra, pallet_refungible, Refungible);784                    list_benchmark!(list, extra, pallet_nonfungible, Nonfungible);785                    // list_benchmark!(list, extra, pallet_evm_coder_substrate, EvmCoderSubstrate);786787                    let storage_info = AllPalletsReversedWithSystemFirst::storage_info();788789                    return (list, storage_info)790                }791792                fn dispatch_benchmark(793                    config: frame_benchmarking::BenchmarkConfig794                ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {795                    use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};796797                    let allowlist: Vec<TrackedStorageKey> = vec![798                        // Total Issuance799                        hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),800801                        // Block Number802                        hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),803                        // Execution Phase804                        hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),805                        // Event Count806                        hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),807                        // System Events808                        hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),809810                        // Evm CurrentLogs811                        hex_literal::hex!("1da53b775b270400e7e61ed5cbc5a146547f210cec367e9af919603343b9cb56").to_vec().into(),812813                        // Transactional depth814                        hex_literal::hex!("3a7472616e73616374696f6e5f6c6576656c3a").to_vec().into(),815                    ];816817                    let mut batches = Vec::<BenchmarkBatch>::new();818                    let params = (&config, &allowlist);819820                    add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);821                    add_benchmark!(params, batches, pallet_common, Common);822                    add_benchmark!(params, batches, pallet_unique, Unique);823                    add_benchmark!(params, batches, pallet_structure, Structure);824                    add_benchmark!(params, batches, pallet_inflation, Inflation);825                    add_benchmark!(params, batches, pallet_fungible, Fungible);826                    add_benchmark!(params, batches, pallet_refungible, Refungible);827                    add_benchmark!(params, batches, pallet_nonfungible, Nonfungible);828                    // add_benchmark!(params, batches, pallet_evm_coder_substrate, EvmCoderSubstrate);829830                    if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }831                    Ok(batches)832                }833            }834835            #[cfg(feature = "try-runtime")]836            impl frame_try_runtime::TryRuntime<Block> for Runtime {837                fn on_runtime_upgrade() -> (Weight, Weight) {838                    log::info!("try-runtime::on_runtime_upgrade unique-chain.");839                    let weight = Executive::try_runtime_upgrade().unwrap();840                    (weight, RuntimeBlockWeights::get().max_block)841                }842843                fn execute_block_no_check(block: Block) -> Weight {844                    Executive::execute_block_no_check(block)845                }846            }847        }848    }849}