12345678#![cfg_attr(not(feature = "std"), no_std)]910#![recursion_limit = "256"]111213#[cfg(feature = "std")]14include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));1516use pallet_grandpa::fg_primitives;17use pallet_grandpa::{AuthorityId as GrandpaId, AuthorityList as GrandpaAuthorityList};18use sp_api::impl_runtime_apis;19use sp_consensus_aura::sr25519::AuthorityId as AuraId;20use sp_core::{ crypto::KeyTypeId, crypto::Public, OpaqueMetadata, H160, U256 };21use sp_runtime::{22 Permill, Perbill, Percent,23 ModuleId,24 create_runtime_str, generic, impl_opaque_keys,25 traits::{26 Convert, ConvertInto, BlakeTwo256, Block as BlockT, IdentifyAccount,27 IdentityLookup, NumberFor, Verify, AccountIdConversion,28 },29 transaction_validity::{TransactionSource, TransactionValidity},30 ApplyExtrinsicResult, MultiSignature,31};32#[cfg(feature = "std")]33use sp_version::NativeVersion;34use sp_version::RuntimeVersion;35pub use pallet_transaction_payment::{Multiplier, TargetedFeeAdjustment, CurrencyAdapter, FeeDetails, RuntimeDispatchInfo};3637pub use pallet_balances::Call as BalancesCall;38pub use pallet_evm::{EnsureAddressTruncated, HashedAddressMapping, Runner};39pub use pallet_contracts::{Schedule as ContractsSchedule };40pub use frame_support::{41 construct_runtime,42 dispatch::DispatchResult,43 parameter_types,44 StorageValue,45 traits::{46 Currency, ExistenceRequirement, Get, KeyOwnerProofSystem, OnUnbalanced, Randomness,47 LockIdentifier, FindAuthor,48 },49 weights::{50 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},51 DispatchClass, DispatchInfo, GetDispatchInfo, Pays, PostDispatchInfo, Weight,52 WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients53 },54 ConsensusEngineId,55};56use pallet_contracts::weights::WeightInfo;5758use frame_system::{59 self as system,60 EnsureRoot,61 limits::{BlockWeights, BlockLength},62};63use sp_std::{prelude::*, marker::PhantomData};64use sp_arithmetic::{traits::{BaseArithmetic, Unsigned}};65use smallvec::smallvec;66use codec::{Encode, Decode};67use pallet_evm::{Account as EVMAccount, FeeCalculator, OnMethodCall};68use fp_rpc::TransactionStatus;69use sp_core::H256;7071pub use pallet_timestamp::Call as TimestampCall;7273mod chain_extension;74use crate::chain_extension::{ NFTExtension, Imbalance };75767778pub struct CurrencyToVoteHandler;7980impl CurrencyToVoteHandler {81 fn factor() -> Balance {82 (Balances::total_issuance() / u64::max_value() as Balance).max(1)83 }84}8586impl Convert<Balance, u64> for CurrencyToVoteHandler {87 fn convert(x: Balance) -> u64 {88 (x / Self::factor()) as u6489 }90}9192impl Convert<u128, Balance> for CurrencyToVoteHandler {93 fn convert(x: u128) -> Balance {94 x * Self::factor()95 }96}979899100extern crate pallet_nft;101pub use pallet_nft::*;102103104pub type BlockNumber = u32;105106107pub type Signature = MultiSignature;108109110111pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;112113114115pub type AccountIndex = u32;116117118pub type Balance = u128;119120121pub type Index = u32;122123124pub type Hash = sp_core::H256;125126127pub type DigestItem = generic::DigestItem<Hash>;128129mod nft_weights;130131132133134135pub mod opaque {136 use super::*;137138 pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;139140 141 pub type Header = generic::Header<BlockNumber, BlakeTwo256>;142 143 pub type Block = generic::Block<Header, UncheckedExtrinsic>;144 145 pub type BlockId = generic::BlockId<Block>;146147 impl_opaque_keys! {148 pub struct SessionKeys {149 pub aura: Aura,150 pub grandpa: Grandpa,151 }152 }153}154155156pub const VERSION: RuntimeVersion = RuntimeVersion {157 spec_name: create_runtime_str!("nft"),158 impl_name: create_runtime_str!("nft"),159 authoring_version: 1,160 spec_version: 3,161 impl_version: 1,162 apis: RUNTIME_API_VERSIONS,163 transaction_version: 1,164};165166pub const MILLISECS_PER_BLOCK: u64 = 6000;167168pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;169170171pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);172pub const HOURS: BlockNumber = MINUTES * 60;173pub const DAYS: BlockNumber = HOURS * 24;174175176#[cfg(feature = "std")]177pub fn native_version() -> NativeVersion {178 NativeVersion {179 runtime_version: VERSION,180 can_author_with: Default::default(),181 }182}183184185pub struct ValiudatorsOnly<Runtime: pallet_aura::Config>(PhantomData<Runtime>);186impl frame_support::traits::Contains<AccountId> for ValiudatorsOnly<Runtime> {187 fn contains(t: &AccountId) -> bool {188 let arr: [u8; 32] = *t.as_ref();189 let raw_key: Vec<u8> = Vec::from(arr);190191 match pallet_aura::Module::<Runtime>::authorities().iter().find(|auth| auth.to_raw_vec() == raw_key) {192 Some(_) => true,193 None => false,194 }195 }196 fn sorted_members() -> Vec<AccountId> {197 let mut members: Vec<AccountId> = Vec::new();198 for auth in pallet_aura::Module::<Runtime>::authorities() {199 let mut arr: [u8; 32] = Default::default();200 let bor_arr = auth.clone().to_raw_vec();201 let slice = bor_arr.as_slice();202 arr.copy_from_slice(slice);203 members.push(AccountId::from(arr));204 }205 members206 }207 fn count() -> usize {208 pallet_aura::Module::<Runtime>::authorities().len()209 }210}211212impl frame_support::traits::ContainsLengthBound for ValiudatorsOnly<Runtime> {213 fn min_len() -> usize {214 1215 }216 fn max_len() -> usize {217 100218 }219}220221type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;222223pub struct DealWithFees;224impl OnUnbalanced<NegativeImbalance> for DealWithFees {225 fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item=NegativeImbalance>) {226 if let Some(fees) = fees_then_tips.next() {227 228 let mut split = fees.ration(100, 0);229 if let Some(tips) = fees_then_tips.next() {230 231 tips.ration_merge_into(100, 0, &mut split);232 }233 Treasury::on_unbalanced(split.0);234 235 }236 }237}238239240241242243244245246247248249250251252253254255256const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(10);257258259const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);260261const MAXIMUM_BLOCK_WEIGHT: Weight = 2 * WEIGHT_PER_SECOND;262263parameter_types! {264 pub const BlockHashCount: BlockNumber = 2400;265 pub RuntimeBlockLength: BlockLength =266 BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);267 pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);268 pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;269 pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()270 .base_block(BlockExecutionWeight::get())271 .for_class(DispatchClass::all(), |weights| {272 weights.base_extrinsic = ExtrinsicBaseWeight::get();273 })274 .for_class(DispatchClass::Normal, |weights| {275 weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);276 })277 .for_class(DispatchClass::Operational, |weights| {278 weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);279 280 281 weights.reserved = Some(282 MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT283 );284 })285 .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)286 .build_or_panic();287 pub const Version: RuntimeVersion = VERSION;288 pub const SS58Prefix: u8 = 42;289}290291impl system::Config for Runtime {292 293 type BaseCallFilter = ();294 295 type AccountId = AccountId;296 297 type Call = Call;298 299 type Lookup = IdentityLookup<AccountId>;300 301 type Index = Index;302 303 type BlockNumber = BlockNumber;304 305 type Hash = Hash;306 307 type Hashing = BlakeTwo256;308 309 type Header = generic::Header<BlockNumber, BlakeTwo256>;310 311 type Event = Event;312 313 type Origin = Origin;314 315 type BlockHashCount = BlockHashCount;316 317 type DbWeight = RocksDbWeight;318 319 320 type BlockWeights = RuntimeBlockWeights;321 322 type Version = Version;323 324 type PalletInfo = PalletInfo;325 326 type OnNewAccount = ();327 328 type OnKilledAccount = ();329 330 type AccountData = pallet_balances::AccountData<Balance>;331 332 type SystemWeightInfo = system::weights::SubstrateWeight<Runtime>;333334 type BlockLength = RuntimeBlockLength;335 type SS58Prefix = SS58Prefix;336}337338impl pallet_aura::Config for Runtime {339 type AuthorityId = AuraId;340}341342parameter_types! {343 pub const ChainId: u64 = 8888;344}345346impl pallet_evm::Config for Runtime {347 type BlockGasLimit = BlockGasLimit;348 type FeeCalculator = ();349 type GasWeightMapping = ();350 type CallOrigin = EnsureAddressTruncated;351 type WithdrawOrigin = EnsureAddressTruncated;352 type AddressMapping = HashedAddressMapping<Self::Hashing>;353 type Precompiles = ();354 type Currency = Balances;355 type Event = Event;356 type OnMethodCall = pallet_nft::NftErcSupport<Self>;357 type ChainId = ChainId;358 type Runner = pallet_evm::runner::stack::Runner<Self>;359 type OnChargeTransaction = ();360}361362pub struct EthereumFindAuthor<F>(PhantomData<F>);363impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F>364{365 fn find_author<'a, I>(digests: I) -> Option<H160> where366 I: 'a + IntoIterator<Item=(ConsensusEngineId, &'a [u8])>367 {368 if let Some(author_index) = F::find_author(digests) {369 let authority_id = Aura::authorities()[author_index as usize].clone();370 return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24]));371 }372 None373 }374}375376parameter_types! {377 pub BlockGasLimit: U256 = U256::from(u32::max_value());378}379380impl pallet_ethereum::Config for Runtime {381 type Event = Event;382 type FindAuthor = EthereumFindAuthor<Aura>;383 type StateRoot = pallet_ethereum::IntermediateStateRoot;384 type EvmSubmitLog = pallet_evm::Module<Runtime>;385}386387impl pallet_grandpa::Config for Runtime {388 type Event = Event;389 type Call = Call;390391 type KeyOwnerProofSystem = ();392393 type KeyOwnerProof =394 <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, GrandpaId)>>::Proof;395396 type KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(397 KeyTypeId,398 GrandpaId,399 )>>::IdentificationTuple;400401 type HandleEquivocation = ();402403 type WeightInfo = ();404}405406parameter_types! {407 pub const MinimumPeriod: u64 = SLOT_DURATION / 2;408}409410impl pallet_timestamp::Config for Runtime {411 412 type Moment = u64;413 type OnTimestampSet = Aura;414 type MinimumPeriod = MinimumPeriod;415 type WeightInfo = ();416}417418parameter_types! {419 420 pub const ExistentialDeposit: u128 = 0;421 pub const MaxLocks: u32 = 50;422}423424impl pallet_balances::Config for Runtime {425 type MaxLocks = MaxLocks;426 427 type Balance = Balance;428 429 type Event = Event;430 type DustRemoval = Treasury;431 type ExistentialDeposit = ExistentialDeposit;432 type AccountStore = System;433 type WeightInfo = ();434}435436pub const MICROUNIQUE: Balance = 1_000_000_000;437pub const MILLIUNIQUE: Balance = 1_000 * MICROUNIQUE;438pub const CENTIUNIQUE: Balance = 10 * MILLIUNIQUE;439pub const UNIQUE: Balance = 100 * CENTIUNIQUE;440441pub const fn deposit(items: u32, bytes: u32) -> Balance {442 items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE443}444445parameter_types! {446 pub const TombstoneDeposit: Balance = deposit(447 0,448 sp_std::mem::size_of::<pallet_contracts::ContractInfo<Runtime>>() as u32449 );450 pub const DepositPerContract: Balance = TombstoneDeposit::get();451 pub const DepositPerStorageByte: Balance = deposit(0, 1);452 pub const DepositPerStorageItem: Balance = deposit(1, 0);453 pub RentFraction: Perbill = Perbill::from_rational(1u32, 30 * DAYS);454 pub const SurchargeReward: Balance = 150 * MILLIUNIQUE;455 pub const SignedClaimHandicap: u32 = 2;456 pub const MaxDepth: u32 = 32;457 pub const MaxValueSize: u32 = 16 * 1024;458 pub const MaxCodeSize: u32 = 1024 * 1024 * 25; 459 460 pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO *461 RuntimeBlockWeights::get().max_block;462 463 464 pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (465 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -466 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)467 )) / 5) as u32;468}469470471impl pallet_contracts::Config for Runtime {472 type Time = Timestamp;473 type Randomness = RandomnessCollectiveFlip;474 type Currency = Balances;475 type Event = Event;476 type RentPayment = ();477 type SignedClaimHandicap = SignedClaimHandicap;478 type TombstoneDeposit = TombstoneDeposit;479 type DepositPerContract = DepositPerContract;480 type DepositPerStorageByte = DepositPerStorageByte;481 type DepositPerStorageItem = DepositPerStorageItem;482 type RentFraction = RentFraction;483 type SurchargeReward = SurchargeReward;484 type MaxDepth = MaxDepth;485 type MaxValueSize = MaxValueSize;486 type WeightPrice = pallet_transaction_payment::Module<Self>;487 type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;488 type ChainExtension = NFTExtension;489 type DeletionQueueDepth = DeletionQueueDepth;490 type DeletionWeightLimit = DeletionWeightLimit;491 type MaxCodeSize = MaxCodeSize;492}493494parameter_types! {495 pub const TransactionByteFee: Balance = 501 * MICROUNIQUE; 496}497498499pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);500501impl<T> WeightToFeePolynomial for LinearFee<T> where502 T: BaseArithmetic + From<u32> + Copy + Unsigned503{504 type Balance = T;505506 fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {507 smallvec!(WeightToFeeCoefficient {508 coeff_integer: 146_700u32.into(), 509 coeff_frac: Perbill::zero(),510 negative: false,511 degree: 1,512 })513 }514}515516impl pallet_transaction_payment::Config for Runtime {517 type OnChargeTransaction = CurrencyAdapter<Balances, DealWithFees>;518 type TransactionByteFee = TransactionByteFee;519 type WeightToFee = LinearFee<Balance>;520 type FeeMultiplierUpdate = ();521}522523parameter_types! {524 pub const ProposalBond: Permill = Permill::from_percent(5);525 pub const ProposalBondMinimum: Balance = 1 * UNIQUE;526 pub const SpendPeriod: BlockNumber = 5 * MINUTES;527 pub const Burn: Permill = Permill::from_percent(0);528 pub const TipCountdown: BlockNumber = 1 * DAYS;529 pub const TipFindersFee: Percent = Percent::from_percent(20);530 pub const TipReportDepositBase: Balance = 1 * UNIQUE;531 pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;532 pub const BountyDepositBase: Balance = 1 * UNIQUE;533 pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;534 pub const TreasuryModuleId: ModuleId = ModuleId(*b"py/trsry");535 pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;536 pub const MaximumReasonLength: u32 = 16384;537 pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);538 pub const BountyValueMinimum: Balance = 5 * UNIQUE;539}540541impl pallet_treasury::Config for Runtime {542 type ModuleId = TreasuryModuleId;543 type Currency = Balances;544 type ApproveOrigin = EnsureRoot<AccountId>;545 type RejectOrigin = EnsureRoot<AccountId>;546 type Event = Event;547 type OnSlash = ();548 type ProposalBond = ProposalBond;549 type ProposalBondMinimum = ProposalBondMinimum;550 type SpendPeriod = SpendPeriod;551 type Burn = Burn;552 type BurnDestination = ();553 type SpendFunds = ();554 type WeightInfo = pallet_treasury::weights::SubstrateWeight<Runtime>;555}556557impl pallet_sudo::Config for Runtime {558 type Event = Event;559 type Call = Call;560}561562parameter_types! {563 pub const MinVestedTransfer: Balance = 10 * UNIQUE;564}565566impl pallet_vesting::Config for Runtime {567 type Event = Event;568 type Currency = Balances;569 type BlockNumberToBalance = ConvertInto;570 type MinVestedTransfer = MinVestedTransfer;571 type WeightInfo = ();572}573574parameter_types! {575 pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();576 pub const CollectionCreationPrice: Balance = 100 * UNIQUE;577}578579580impl pallet_nft::Config for Runtime {581 type Event = Event;582 type WeightInfo = nft_weights::WeightInfo;583584 type EvmWithdrawOrigin = EnsureAddressTruncated;585 type EvmBackwardsAddressMapping = pallet_nft::MapBackwardsAddressTruncated;586 type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;587 type CrossAccountId = pallet_nft::BasicCrossAccountId<Self>;588589 type Currency = Balances;590 type CollectionCreationPrice = CollectionCreationPrice;591 type TreasuryAccountId = TreasuryAccountId;592593 type EthereumChainId = ChainId;594 type EthereumTransactionSender = pallet_ethereum::Module<Runtime>;595}596597598extern crate pallet_inflation;599pub use pallet_inflation::*;600601parameter_types! {602 pub const InflationBlockInterval: BlockNumber = 100; 603}604605606impl pallet_inflation::Config for Runtime {607 type Currency = Balances;608 type TreasuryAccountId = TreasuryAccountId;609 type InflationBlockInterval = InflationBlockInterval;610}611612construct_runtime!(613 pub enum Runtime where614 Block = Block,615 NodeBlock = opaque::Block,616 UncheckedExtrinsic = UncheckedExtrinsic617 {618 System: system::{Module, Call, Config, Storage, Event<T>},619 RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Module, Call, Storage},620 Contracts: pallet_contracts::{Module, Call, Config<T>, Storage, Event<T>},621 Timestamp: pallet_timestamp::{Module, Call, Storage, Inherent},622 Aura: pallet_aura::{Module, Config<T> },623 EVM: pallet_evm::{Module, Config, Call, Storage, Event<T>},624 Ethereum: pallet_ethereum::{Module, Config, Call, Storage, Event, ValidateUnsigned},625 Grandpa: pallet_grandpa::{Module, Call, Storage, Config, Event},626 Balances: pallet_balances::{Module, Call, Storage, Config<T>, Event<T>},627 TransactionPayment: pallet_transaction_payment::{Module, Storage},628 Sudo: pallet_sudo::{Module, Call, Config<T>, Storage, Event<T>},629 Inflation: pallet_inflation::{Module, Call, Storage},630 Nft: pallet_nft::{Module, Call, Config<T>, Storage, Event<T>},631 Treasury: pallet_treasury::{Module, Call, Storage, Config, Event<T>},632 Vesting: pallet_vesting::{Module, Call, Config<T>, Storage, Event<T>},633 }634);635636pub struct TransactionConverter;637638impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {639 fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {640 UncheckedExtrinsic::new_unsigned(pallet_ethereum::Call::<Runtime>::transact(transaction).into())641 }642}643644impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {645 fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> opaque::UncheckedExtrinsic {646 let extrinsic = UncheckedExtrinsic::new_unsigned(pallet_ethereum::Call::<Runtime>::transact(transaction).into());647 let encoded = extrinsic.encode();648 opaque::UncheckedExtrinsic::decode(&mut &encoded[..]).expect("Encoded extrinsic is always valid")649 }650}651652653pub type Address = AccountId;654655pub type Header = generic::Header<BlockNumber, BlakeTwo256>;656657pub type Block = generic::Block<Header, UncheckedExtrinsic>;658659pub type SignedBlock = generic::SignedBlock<Block>;660661pub type BlockId = generic::BlockId<Block>;662663pub type SignedExtra = (664 system::CheckSpecVersion<Runtime>,665 system::CheckTxVersion<Runtime>,666 system::CheckGenesis<Runtime>,667 system::CheckEra<Runtime>,668 system::CheckNonce<Runtime>,669 system::CheckWeight<Runtime>,670 pallet_nft::ChargeTransactionPayment<Runtime>,671);672673pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;674675pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, Call, SignedExtra>;676677pub type Executive =678 frame_executive::Executive<Runtime, Block, system::ChainContext<Runtime>, Runtime, AllModules>;679680impl_runtime_apis! {681 impl pallet_nft::NftApi<Block>682 for Runtime683 {684 fn eth_contract_code(account: H160) -> Option<Vec<u8>> {685 <pallet_nft::NftErcSupport<Runtime>>::get_code(&account)686 }687 }688689 impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber>690 for Runtime691 {692 fn call(693 origin: AccountId,694 dest: AccountId,695 value: Balance,696 gas_limit: u64,697 input_data: Vec<u8>,698 ) -> pallet_contracts_primitives::ContractExecResult {699 Contracts::bare_call(origin, dest, value, gas_limit, input_data)700 }701702 fn get_storage(703 address: AccountId,704 key: [u8; 32],705 ) -> pallet_contracts_primitives::GetStorageResult {706 Contracts::get_storage(address, key)707 }708709 fn rent_projection(710 address: AccountId,711 ) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {712 Contracts::rent_projection(address)713 }714 }715716 impl sp_api::Core<Block> for Runtime {717 fn version() -> RuntimeVersion {718 VERSION719 }720721 fn execute_block(block: Block) {722 Executive::execute_block(block)723 }724725 fn initialize_block(header: &<Block as BlockT>::Header) {726 Executive::initialize_block(header)727 }728 }729730 impl sp_api::Metadata<Block> for Runtime {731 fn metadata() -> OpaqueMetadata {732 Runtime::metadata().into()733 }734 }735736 impl sp_block_builder::BlockBuilder<Block> for Runtime {737 fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {738 Executive::apply_extrinsic(extrinsic)739 }740741 fn finalize_block() -> <Block as BlockT>::Header {742 Executive::finalize_block()743 }744745 fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {746 data.create_extrinsics()747 }748749 fn check_inherents(750 block: Block,751 data: sp_inherents::InherentData,752 ) -> sp_inherents::CheckInherentsResult {753 data.check_extrinsics(&block)754 }755756 fn random_seed() -> <Block as BlockT>::Hash {757 RandomnessCollectiveFlip::random_seed().0758 }759 }760761 impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {762 fn validate_transaction(763 source: TransactionSource,764 tx: <Block as BlockT>::Extrinsic,765 ) -> TransactionValidity {766 Executive::validate_transaction(source, tx)767 }768 }769770 impl sp_offchain::OffchainWorkerApi<Block> for Runtime {771 fn offchain_worker(header: &<Block as BlockT>::Header) {772 Executive::offchain_worker(header)773 }774 }775776 impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {777 fn slot_duration() -> u64 {778 Aura::slot_duration()779 }780781 fn authorities() -> Vec<AuraId> {782 Aura::authorities()783 }784 }785786 impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {787 fn chain_id() -> u64 {788 <Runtime as pallet_evm::Config>::ChainId::get()789 }790791 fn account_basic(address: H160) -> EVMAccount {792 EVM::account_basic(&address)793 }794795 fn gas_price() -> U256 {796 <Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price()797 }798799 fn account_code_at(address: H160) -> Vec<u8> {800 EVM::account_codes(address)801 }802803 fn author() -> H160 {804 <pallet_ethereum::Module<Runtime>>::find_author()805 }806807 fn storage_at(address: H160, index: U256) -> H256 {808 let mut tmp = [0u8; 32];809 index.to_big_endian(&mut tmp);810 EVM::account_storages(address, H256::from_slice(&tmp[..]))811 }812813 fn call(814 from: H160,815 to: H160,816 data: Vec<u8>,817 value: U256,818 gas_limit: U256,819 gas_price: Option<U256>,820 nonce: Option<U256>,821 estimate: bool,822 ) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {823 let config = if estimate {824 let mut config = <Runtime as pallet_evm::Config>::config().clone();825 config.estimate = true;826 Some(config)827 } else {828 None829 };830831 <Runtime as pallet_evm::Config>::Runner::call(832 from,833 to,834 data,835 value,836 gas_limit.low_u64(),837 gas_price,838 nonce,839 config.as_ref().unwrap_or(<Runtime as pallet_evm::Config>::config()),840 ).map_err(|err| err.into())841 }842843 fn create(844 from: H160,845 data: Vec<u8>,846 value: U256,847 gas_limit: U256,848 gas_price: Option<U256>,849 nonce: Option<U256>,850 estimate: bool,851 ) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {852 let config = if estimate {853 let mut config = <Runtime as pallet_evm::Config>::config().clone();854 config.estimate = true;855 Some(config)856 } else {857 None858 };859860 <Runtime as pallet_evm::Config>::Runner::create(861 from,862 data,863 value,864 gas_limit.low_u64(),865 gas_price,866 nonce,867 config.as_ref().unwrap_or(<Runtime as pallet_evm::Config>::config()),868 ).map_err(|err| err.into())869 }870871 fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {872 Ethereum::current_transaction_statuses()873 }874875 fn current_block() -> Option<pallet_ethereum::Block> {876 Ethereum::current_block()877 }878879 fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {880 Ethereum::current_receipts()881 }882883 fn current_all() -> (884 Option<pallet_ethereum::Block>,885 Option<Vec<pallet_ethereum::Receipt>>,886 Option<Vec<TransactionStatus>>887 ) {888 (889 Ethereum::current_block(),890 Ethereum::current_receipts(),891 Ethereum::current_transaction_statuses()892 )893 }894 }895896 impl sp_session::SessionKeys<Block> for Runtime {897 fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {898 opaque::SessionKeys::generate(seed)899 }900901 fn decode_session_keys(902 encoded: Vec<u8>,903 ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {904 opaque::SessionKeys::decode_into_raw_public_keys(&encoded)905 }906 }907908 impl fg_primitives::GrandpaApi<Block> for Runtime {909 fn grandpa_authorities() -> GrandpaAuthorityList {910 Grandpa::grandpa_authorities()911 }912913 fn submit_report_equivocation_unsigned_extrinsic(914 _equivocation_proof: fg_primitives::EquivocationProof<915 <Block as BlockT>::Hash,916 NumberFor<Block>,917 >,918 _key_owner_proof: fg_primitives::OpaqueKeyOwnershipProof,919 ) -> Option<()> {920 None921 }922923 fn generate_key_ownership_proof(924 _set_id: fg_primitives::SetId,925 _authority_id: GrandpaId,926 ) -> Option<fg_primitives::OpaqueKeyOwnershipProof> {927 928 929 930 None931 }932 }933934 impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {935 fn account_nonce(account: AccountId) -> Index {936 System::account_nonce(account)937 }938 }939940 impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {941 fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {942 TransactionPayment::query_info(uxt, len)943 }944 fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {945 TransactionPayment::query_fee_details(uxt, len)946 }947 }948949 #[cfg(feature = "runtime-benchmarks")]950 impl frame_benchmarking::Benchmark<Block> for Runtime {951 fn dispatch_benchmark(952 config: frame_benchmarking::BenchmarkConfig953 ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {954 use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};955956 let whitelist: Vec<TrackedStorageKey> = vec![957 958 hex_literal::hex!("d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d").to_vec().into(),959 960 961 962 963 964 965 966 967 ];968969 let mut batches = Vec::<BenchmarkBatch>::new();970 let params = (&config, &whitelist);971972 add_benchmark!(params, batches, pallet_nft, Nft);973 add_benchmark!(params, batches, pallet_inflation, Inflation);974975 if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }976 Ok(batches)977 }978 }979}