12345678#![cfg_attr(not(feature = "std"), no_std)]910#![recursion_limit = "1024"]11#![allow(clippy::from_over_into, clippy::identity_op)]12#![allow(clippy::fn_to_numeric_cast_with_truncation)]1314#[cfg(feature = "std")]15include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));1617use sp_api::impl_runtime_apis;18use sp_core::{crypto::KeyTypeId, OpaqueMetadata, H256, U256, H160};19202122use sp_runtime::{23 Permill, Perbill, Percent, create_runtime_str, generic, impl_opaque_keys,24 traits::{25 AccountIdLookup, ConvertInto, BlakeTwo256, Block as BlockT, IdentifyAccount, Verify,26 AccountIdConversion,27 },28 transaction_validity::{TransactionSource, TransactionValidity},29 ApplyExtrinsicResult, MultiSignature,30};3132use sp_std::prelude::*;3334#[cfg(feature = "std")]35use sp_version::NativeVersion;36use sp_version::RuntimeVersion;37pub use pallet_transaction_payment::{38 Multiplier, TargetedFeeAdjustment, FeeDetails, RuntimeDispatchInfo,39};4041pub use pallet_balances::Call as BalancesCall;42pub use pallet_evm::{EnsureAddressTruncated, HashedAddressMapping, Runner};43pub use frame_support::{44 construct_runtime, match_type,45 dispatch::DispatchResult,46 PalletId, parameter_types, StorageValue, ConsensusEngineId,47 traits::{48 Everything, Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem,49 LockIdentifier, OnUnbalanced, Randomness, FindAuthor,50 },51 weights::{52 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},53 DispatchClass, DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,54 WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients,55 },56};57use nft_data_structs::*;585960use frame_system::{61 self as system, EnsureRoot, EnsureSigned,62 limits::{BlockWeights, BlockLength},63};64use sp_arithmetic::{65 traits::{BaseArithmetic, Unsigned},66};67use smallvec::smallvec;68use codec::{Encode, Decode};69use pallet_evm::{Account as EVMAccount, FeeCalculator, OnMethodCall};70use fp_rpc::TransactionStatus;71use sp_core::crypto::Public;72use sp_runtime::{73 traits::{Dispatchable},74};757677pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;787980use pallet_xcm::XcmPassthrough;81use polkadot_parachain::primitives::Sibling;82use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};83use xcm_builder::{84 AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter,85 EnsureXcmOrigin, FixedWeightBounds, IsConcrete, LocationInverter, NativeAsset,86 ParentAsSuperuser, ParentIsDefault, RelayChainAsNative, SiblingParachainAsNative,87 SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32,88 SovereignSignedViaLocation, TakeWeightCredit, UsingComponents,89};90use xcm_executor::{Config, XcmExecutor};919293949596pub type BlockNumber = u32;979899pub type Signature = MultiSignature;100101102103pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;104105106107pub type AccountIndex = u32;108109110pub type Balance = u128;111112113pub type Index = u32;114115116pub type Hash = sp_core::H256;117118119pub type DigestItem = generic::DigestItem<Hash>;120121122123124125pub mod opaque {126 use super::*;127128 pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;129130 131 pub type Block = generic::Block<Header, UncheckedExtrinsic>;132133 pub type SessionHandlers = ();134135 impl_opaque_keys! {136 pub struct SessionKeys {137 pub aura: Aura,138 }139 }140}141142143pub const VERSION: RuntimeVersion = RuntimeVersion {144 spec_name: create_runtime_str!("opal"),145 impl_name: create_runtime_str!("opal"),146 authoring_version: 1,147 spec_version: 910000,148 impl_version: 1,149 apis: RUNTIME_API_VERSIONS,150 transaction_version: 1,151};152153pub const MILLISECS_PER_BLOCK: u64 = 12000;154155pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;156157158pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);159pub const HOURS: BlockNumber = MINUTES * 60;160pub const DAYS: BlockNumber = HOURS * 24;161162parameter_types! {163 pub const DefaultSponsoringRateLimit: BlockNumber = 1 * DAYS;164}165166#[derive(codec::Encode, codec::Decode)]167pub enum XCMPMessage<XAccountId, XBalance> {168 169 TransferToken(XAccountId, XBalance),170}171172173#[cfg(feature = "std")]174pub fn native_version() -> NativeVersion {175 NativeVersion {176 runtime_version: VERSION,177 can_author_with: Default::default(),178 }179}180181type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;182183pub struct DealWithFees;184impl OnUnbalanced<NegativeImbalance> for DealWithFees {185 fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {186 if let Some(fees) = fees_then_tips.next() {187 188 let mut split = fees.ration(100, 0);189 if let Some(tips) = fees_then_tips.next() {190 191 tips.ration_merge_into(100, 0, &mut split);192 }193 Treasury::on_unbalanced(split.0);194 195 }196 }197}198199200201const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(10);202203204const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);205206const MAXIMUM_BLOCK_WEIGHT: Weight = WEIGHT_PER_SECOND / 2;207208parameter_types! {209 pub const BlockHashCount: BlockNumber = 2400;210 pub RuntimeBlockLength: BlockLength =211 BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);212 pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);213 pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;214 pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()215 .base_block(BlockExecutionWeight::get())216 .for_class(DispatchClass::all(), |weights| {217 weights.base_extrinsic = ExtrinsicBaseWeight::get();218 })219 .for_class(DispatchClass::Normal, |weights| {220 weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);221 })222 .for_class(DispatchClass::Operational, |weights| {223 weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);224 225 226 weights.reserved = Some(227 MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT228 );229 })230 .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)231 .build_or_panic();232 pub const Version: RuntimeVersion = VERSION;233 pub const SS58Prefix: u8 = 42;234}235236parameter_types! {237 pub const ChainId: u64 = 8888;238}239240pub struct FixedFee;241impl FeeCalculator for FixedFee {242 fn min_gas_price() -> U256 {243 1.into()244 }245}246247impl pallet_evm::Config for Runtime {248 type BlockGasLimit = BlockGasLimit;249 type FeeCalculator = FixedFee;250 type GasWeightMapping = ();251 type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;252 type CallOrigin = EnsureAddressTruncated;253 type WithdrawOrigin = EnsureAddressTruncated;254 type AddressMapping = HashedAddressMapping<Self::Hashing>;255 type Precompiles = ();256 type Currency = Balances;257 type Event = Event;258 type OnMethodCall = (259 pallet_evm_migration::OnMethodCall<Self>,260 pallet_nft::NftErcSupport<Self>,261 pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,262 );263 type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;264 type ChainId = ChainId;265 type Runner = pallet_evm::runner::stack::Runner<Self>;266 type OnChargeTransaction = pallet_evm_transaction_payment::OnChargeTransaction<Self>;267 type TransactionValidityHack = pallet_evm_transaction_payment::TransactionValidityHack<Self>;268 type FindAuthor = EthereumFindAuthor<Aura>;269}270271impl pallet_evm_migration::Config for Runtime {272 type WeightInfo = pallet_evm_migration::weights::SubstrateWeight<Self>;273}274275pub struct EthereumFindAuthor<F>(core::marker::PhantomData<F>);276impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F> {277 fn find_author<'a, I>(digests: I) -> Option<H160>278 where279 I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,280 {281 if let Some(author_index) = F::find_author(digests) {282 let authority_id = Aura::authorities()[author_index as usize].clone();283 return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24]));284 }285 None286 }287}288289parameter_types! {290 pub BlockGasLimit: U256 = U256::from(u32::max_value());291}292293impl pallet_ethereum::Config for Runtime {294 type Event = Event;295 type StateRoot = pallet_ethereum::IntermediateStateRoot;296 type EvmSubmitLog = pallet_evm::Pallet<Self>;297}298299impl pallet_randomness_collective_flip::Config for Runtime {}300301impl system::Config for Runtime {302 303 type AccountData = pallet_balances::AccountData<Balance>;304 305 type AccountId = AccountId;306 307 type BaseCallFilter = Everything;308 309 type BlockHashCount = BlockHashCount;310 311 type BlockLength = RuntimeBlockLength;312 313 type BlockNumber = BlockNumber;314 315 type BlockWeights = RuntimeBlockWeights;316 317 type Call = Call;318 319 type DbWeight = RocksDbWeight;320 321 type Event = Event;322 323 type Hash = Hash;324 325 type Hashing = BlakeTwo256;326 327 type Header = generic::Header<BlockNumber, BlakeTwo256>;328 329 type Index = Index;330 331 type Lookup = AccountIdLookup<AccountId, ()>;332 333 type OnKilledAccount = ();334 335 type OnNewAccount = ();336 type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;337 338 type Origin = Origin;339 340 type PalletInfo = PalletInfo;341 342 type SS58Prefix = SS58Prefix;343 344 type SystemWeightInfo = system::weights::SubstrateWeight<Self>;345 346 type Version = Version;347}348349parameter_types! {350 pub const MinimumPeriod: u64 = SLOT_DURATION / 2;351}352353impl pallet_timestamp::Config for Runtime {354 355 type Moment = u64;356 type OnTimestampSet = ();357 type MinimumPeriod = MinimumPeriod;358 type WeightInfo = ();359}360361parameter_types! {362 363 pub const ExistentialDeposit: u128 = 0;364 pub const MaxLocks: u32 = 50;365}366367impl pallet_balances::Config for Runtime {368 type MaxLocks = MaxLocks;369 type MaxReserves = ();370 type ReserveIdentifier = [u8; 8];371 372 type Balance = Balance;373 374 type Event = Event;375 type DustRemoval = Treasury;376 type ExistentialDeposit = ExistentialDeposit;377 type AccountStore = System;378 type WeightInfo = pallet_balances::weights::SubstrateWeight<Self>;379}380381pub const MICROUNIQUE: Balance = 1_000_000_000;382pub const MILLIUNIQUE: Balance = 1_000 * MICROUNIQUE;383pub const CENTIUNIQUE: Balance = 10 * MILLIUNIQUE;384pub const UNIQUE: Balance = 100 * CENTIUNIQUE;385386pub const fn deposit(items: u32, bytes: u32) -> Balance {387 items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE388}389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440parameter_types! {441 pub const TransactionByteFee: Balance = 501 * MICROUNIQUE; 442 443 444 pub const OperationalFeeMultiplier: u8 = 5;445}446447448pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);449450impl<T> WeightToFeePolynomial for LinearFee<T>451where452 T: BaseArithmetic + From<u32> + Copy + Unsigned,453{454 type Balance = T;455456 fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {457 smallvec!(WeightToFeeCoefficient {458 coeff_integer: 146_700u32.into(), 459 coeff_frac: Perbill::zero(),460 negative: false,461 degree: 1,462 })463 }464}465466impl pallet_transaction_payment::Config for Runtime {467 type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, DealWithFees>;468 type TransactionByteFee = TransactionByteFee;469 type OperationalFeeMultiplier = OperationalFeeMultiplier;470 type WeightToFee = LinearFee<Balance>;471 type FeeMultiplierUpdate = ();472}473474parameter_types! {475 pub const ProposalBond: Permill = Permill::from_percent(5);476 pub const ProposalBondMinimum: Balance = 1 * UNIQUE;477 pub const SpendPeriod: BlockNumber = 5 * MINUTES;478 pub const Burn: Permill = Permill::from_percent(0);479 pub const TipCountdown: BlockNumber = 1 * DAYS;480 pub const TipFindersFee: Percent = Percent::from_percent(20);481 pub const TipReportDepositBase: Balance = 1 * UNIQUE;482 pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;483 pub const BountyDepositBase: Balance = 1 * UNIQUE;484 pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;485 pub const TreasuryModuleId: PalletId = PalletId(*b"py/trsry");486 pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;487 pub const MaximumReasonLength: u32 = 16384;488 pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);489 pub const BountyValueMinimum: Balance = 5 * UNIQUE;490 pub const MaxApprovals: u32 = 100;491}492493impl pallet_treasury::Config for Runtime {494 type PalletId = TreasuryModuleId;495 type Currency = Balances;496 type ApproveOrigin = EnsureRoot<AccountId>;497 type RejectOrigin = EnsureRoot<AccountId>;498 type Event = Event;499 type OnSlash = ();500 type ProposalBond = ProposalBond;501 type ProposalBondMinimum = ProposalBondMinimum;502 type SpendPeriod = SpendPeriod;503 type Burn = Burn;504 type BurnDestination = ();505 type SpendFunds = ();506 type WeightInfo = pallet_treasury::weights::SubstrateWeight<Self>;507 type MaxApprovals = MaxApprovals;508}509510impl pallet_sudo::Config for Runtime {511 type Event = Event;512 type Call = Call;513}514515parameter_types! {516 pub const MinVestedTransfer: Balance = 10 * UNIQUE;517}518519impl pallet_vesting::Config for Runtime {520 type Event = Event;521 type Currency = Balances;522 type BlockNumberToBalance = ConvertInto;523 type MinVestedTransfer = MinVestedTransfer;524 type WeightInfo = ();525 const MAX_VESTING_SCHEDULES: u32 = 28;526}527528parameter_types! {529 pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;530 pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;531}532533impl cumulus_pallet_parachain_system::Config for Runtime {534 type Event = Event;535 type OnValidationData = ();536 type SelfParaId = parachain_info::Pallet<Self>;537 538 539 540 541 542 type OutboundXcmpMessageSource = XcmpQueue;543 type DmpMessageHandler = DmpQueue;544 type ReservedDmpWeight = ReservedDmpWeight;545 type ReservedXcmpWeight = ReservedXcmpWeight;546 type XcmpMessageHandler = XcmpQueue;547}548549impl parachain_info::Config for Runtime {}550551impl cumulus_pallet_aura_ext::Config for Runtime {}552553parameter_types! {554 pub const RelayLocation: MultiLocation = MultiLocation::parent();555 pub const RelayNetwork: NetworkId = NetworkId::Polkadot;556 pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();557 pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();558}559560561562563pub type LocationToAccountId = (564 565 ParentIsDefault<AccountId>,566 567 SiblingParachainConvertsVia<Sibling, AccountId>,568 569 AccountId32Aliases<RelayNetwork, AccountId>,570);571572573pub type LocalAssetTransactor = CurrencyAdapter<574 575 Balances,576 577 IsConcrete<RelayLocation>,578 579 LocationToAccountId,580 581 AccountId,582 583 (),584>;585586587588589pub type XcmOriginToTransactDispatchOrigin = (590 591 592 593 SovereignSignedViaLocation<LocationToAccountId, Origin>,594 595 596 RelayChainAsNative<RelayOrigin, Origin>,597 598 599 SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,600 601 602 ParentAsSuperuser<Origin>,603 604 605 SignedAccountId32AsNative<RelayNetwork, Origin>,606 607 XcmPassthrough<Origin>,608);609610parameter_types! {611 612 pub UnitWeightCost: Weight = 1_000_000;613 614 pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);615 pub const MaxInstructions: u32 = 100;616 pub const MaxAuthorities: u32 = 100_000;617}618619match_type! {620 pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {621 MultiLocation { parents: 1, interior: Here } |622 MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }623 };624}625626pub type Barrier = (627 TakeWeightCredit,628 AllowTopLevelPaidExecutionFrom<Everything>,629 AllowUnpaidExecutionFrom<ParentOrParentsUnitPlurality>,630 631);632633pub struct XcmConfig;634impl Config for XcmConfig {635 type Call = Call;636 type XcmSender = XcmRouter;637 638 type AssetTransactor = LocalAssetTransactor;639 type OriginConverter = XcmOriginToTransactDispatchOrigin;640 type IsReserve = NativeAsset;641 type IsTeleporter = (); 642 type LocationInverter = LocationInverter<Ancestry>;643 type Barrier = Barrier;644 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;645 type Trader = UsingComponents<IdentityFee<Balance>, RelayLocation, AccountId, Balances, ()>;646 type ResponseHandler = (); 647 type SubscriptionService = PolkadotXcm;648649 type AssetTrap = PolkadotXcm;650 type AssetClaims = PolkadotXcm;651}652653654655656657658pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);659660661662pub type XcmRouter = (663 664 cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,665 666 XcmpQueue,667);668669impl pallet_evm_coder_substrate::Config for Runtime {670 type EthereumTransactionSender = pallet_ethereum::Pallet<Self>;671}672673impl pallet_xcm::Config for Runtime {674 type Event = Event;675 type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;676 type XcmRouter = XcmRouter;677 type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;678 type XcmExecuteFilter = Everything;679 type XcmExecutor = XcmExecutor<XcmConfig>;680 type XcmTeleportFilter = Everything;681 type XcmReserveTransferFilter = Everything;682 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;683 type LocationInverter = LocationInverter<Ancestry>;684 type Origin = Origin;685 type Call = Call;686 const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;687 type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;688}689690impl cumulus_pallet_xcm::Config for Runtime {691 type Event = Event;692 type XcmExecutor = XcmExecutor<XcmConfig>;693}694695impl cumulus_pallet_xcmp_queue::Config for Runtime {696 type Event = Event;697 type XcmExecutor = XcmExecutor<XcmConfig>;698 type ChannelInfo = ParachainSystem;699 type VersionWrapper = ();700}701702impl cumulus_pallet_dmp_queue::Config for Runtime {703 type Event = Event;704 type XcmExecutor = XcmExecutor<XcmConfig>;705 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;706}707708impl pallet_aura::Config for Runtime {709 type AuthorityId = AuraId;710 type DisabledValidators = ();711 type MaxAuthorities = MaxAuthorities;712}713714parameter_types! {715 pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();716 pub const CollectionCreationPrice: Balance = 100 * UNIQUE;717}718719720impl pallet_nft::Config for Runtime {721 type Event = Event;722 type WeightInfo = pallet_nft::weights::SubstrateWeight<Self>;723724 type EvmBackwardsAddressMapping = pallet_nft::MapBackwardsAddressTruncated;725 type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;726 type CrossAccountId = pallet_nft::BasicCrossAccountId<Self>;727728 type Currency = Balances;729 type CollectionCreationPrice = CollectionCreationPrice;730 type TreasuryAccountId = TreasuryAccountId;731}732733parameter_types! {734 pub const InflationBlockInterval: BlockNumber = 100; 735}736737738impl pallet_inflation::Config for Runtime {739 type Currency = Balances;740 type TreasuryAccountId = TreasuryAccountId;741 type InflationBlockInterval = InflationBlockInterval;742}743744parameter_types! {745 pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *746 RuntimeBlockWeights::get().max_block;747 pub const MaxScheduledPerBlock: u32 = 50;748}749750pub struct Sponsoring;751impl SponsoringResolve<AccountId, Call> for Sponsoring {752 fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>753 where754 Call: Dispatchable<Info = DispatchInfo>,755 AccountId: AsRef<[u8]>,756 {757 pallet_nft_transaction_payment::Module::<Runtime>::withdraw_type(who, call)758 }759}760761type SponsorshipHandler = (762 pallet_nft::NftSponsorshipHandler<Runtime>,763 764);765766impl pallet_scheduler::Config for Runtime {767 type Event = Event;768 type Origin = Origin;769 type PalletsOrigin = OriginCaller;770 type Call = Call;771 type MaximumWeight = MaximumSchedulerWeight;772 type ScheduleOrigin = EnsureSigned<AccountId>;773 type MaxScheduledPerBlock = MaxScheduledPerBlock;774 type SponsorshipHandler = SponsorshipHandler;775 type WeightInfo = ();776}777778impl pallet_nft_transaction_payment::Config for Runtime {779 type SponsorshipHandler = SponsorshipHandler;780}781782impl pallet_evm_transaction_payment::Config for Runtime {783 type SponsorshipHandler = (784 pallet_nft::NftEthSponsorshipHandler<Self>,785 pallet_evm_contract_helpers::HelpersContractSponsoring<Self>,786 );787 type Currency = Balances;788}789790impl pallet_nft_charge_transaction::Config for Runtime {}791792793794795796parameter_types! {797 798 pub const HelpersContractAddress: H160 = H160([799 0x84, 0x28, 0x99, 0xec, 0xf3, 0x80, 0x55, 0x3e, 0x8a, 0x4d, 0xe7, 0x5b, 0xf5, 0x34, 0xcd, 0xf6, 0xfb, 0xf6, 0x40, 0x49,800 ]);801}802803impl pallet_evm_contract_helpers::Config for Runtime {804 type ContractAddress = HelpersContractAddress;805 type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;806}807808construct_runtime!(809 pub enum Runtime where810 Block = Block,811 NodeBlock = opaque::Block,812 UncheckedExtrinsic = UncheckedExtrinsic813 {814 ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Storage, Inherent, Event<T>, ValidateUnsigned} = 20,815 ParachainInfo: parachain_info::{Pallet, Storage, Config} = 21,816817 Aura: pallet_aura::{Pallet, Config<T>} = 22,818 AuraExt: cumulus_pallet_aura_ext::{Pallet, Config} = 23,819820 Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 30,821 RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage} = 31,822 Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 32,823 TransactionPayment: pallet_transaction_payment::{Pallet, Storage} = 33,824 Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event<T>} = 34,825 Sudo: pallet_sudo::{Pallet, Call, Storage, Config<T>, Event<T>} = 35,826 System: system::{Pallet, Call, Storage, Config, Event<T>} = 36,827 Vesting: pallet_vesting::{Pallet, Call, Config<T>, Storage, Event<T>} = 37,828 829830 831 XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 50,832 PolkadotXcm: pallet_xcm::{Pallet, Call, Event<T>, Origin} = 51,833 CumulusXcm: cumulus_pallet_xcm::{Pallet, Call, Event<T>, Origin} = 52,834 DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,835836 837 Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,838 Nft: pallet_nft::{Pallet, Call, Config<T>, Storage, Event<T>} = 61,839 Scheduler: pallet_scheduler::{Pallet, Call, Storage, Event<T>} = 62,840 NftPayment: pallet_nft_transaction_payment::{Pallet, Call, Storage} = 63,841 Charging: pallet_nft_charge_transaction::{Pallet, Call, Storage } = 64,842 843844 845 EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,846 Ethereum: pallet_ethereum::{Pallet, Config, Call, Storage, Event, ValidateUnsigned} = 101,847848 EvmCoderSubstrate: pallet_evm_coder_substrate::{Pallet, Storage} = 150,849 EvmContractHelpers: pallet_evm_contract_helpers::{Pallet, Storage} = 151,850 EvmTransactionPayment: pallet_evm_transaction_payment::{Pallet} = 152,851 EvmMigration: pallet_evm_migration::{Pallet, Call, Storage} = 153,852 }853);854855pub struct TransactionConverter;856857impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {858 fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {859 UncheckedExtrinsic::new_unsigned(860 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),861 )862 }863}864865impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {866 fn convert_transaction(867 &self,868 transaction: pallet_ethereum::Transaction,869 ) -> opaque::UncheckedExtrinsic {870 let extrinsic = UncheckedExtrinsic::new_unsigned(871 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),872 );873 let encoded = extrinsic.encode();874 opaque::UncheckedExtrinsic::decode(&mut &encoded[..])875 .expect("Encoded extrinsic is always valid")876 }877}878879880pub type Address = sp_runtime::MultiAddress<AccountId, ()>;881882pub type Header = generic::Header<BlockNumber, BlakeTwo256>;883884pub type Block = generic::Block<Header, UncheckedExtrinsic>;885886pub type SignedBlock = generic::SignedBlock<Block>;887888pub type BlockId = generic::BlockId<Block>;889890pub type SignedExtra = (891 system::CheckSpecVersion<Runtime>,892 893 system::CheckGenesis<Runtime>,894 system::CheckEra<Runtime>,895 system::CheckNonce<Runtime>,896 system::CheckWeight<Runtime>,897 pallet_nft_charge_transaction::ChargeTransactionPayment<Runtime>,898 899);900901pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;902903pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, Call, SignedExtra>;904905pub type Executive = frame_executive::Executive<906 Runtime,907 Block,908 frame_system::ChainContext<Runtime>,909 Runtime,910 AllPallets,911>;912913impl_opaque_keys! {914 pub struct SessionKeys {915 pub aura: Aura,916 }917}918919impl_runtime_apis! {920 impl pallet_nft::NftApi<Block>921 for Runtime922 {923 fn eth_contract_code(account: H160) -> Option<Vec<u8>> {924 <pallet_nft::NftErcSupport<Runtime>>::get_code(&account)925 }926 }927928 impl sp_api::Core<Block> for Runtime {929 fn version() -> RuntimeVersion {930 VERSION931 }932933 fn execute_block(block: Block) {934 Executive::execute_block(block)935 }936937 fn initialize_block(header: &<Block as BlockT>::Header) {938 Executive::initialize_block(header)939 }940 }941942 impl sp_api::Metadata<Block> for Runtime {943 fn metadata() -> OpaqueMetadata {944 OpaqueMetadata::new(Runtime::metadata().into())945 }946 }947948 impl sp_block_builder::BlockBuilder<Block> for Runtime {949 fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {950 Executive::apply_extrinsic(extrinsic)951 }952953 fn finalize_block() -> <Block as BlockT>::Header {954 Executive::finalize_block()955 }956957 fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {958 data.create_extrinsics()959 }960961 fn check_inherents(962 block: Block,963 data: sp_inherents::InherentData,964 ) -> sp_inherents::CheckInherentsResult {965 data.check_extrinsics(&block)966 }967968 969 970 971 }972973 impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {974 fn validate_transaction(975 source: TransactionSource,976 tx: <Block as BlockT>::Extrinsic,977 hash: <Block as BlockT>::Hash,978 ) -> TransactionValidity {979 Executive::validate_transaction(source, tx, hash)980 }981 }982983 impl sp_offchain::OffchainWorkerApi<Block> for Runtime {984 fn offchain_worker(header: &<Block as BlockT>::Header) {985 Executive::offchain_worker(header)986 }987 }988989 impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {990 fn chain_id() -> u64 {991 <Runtime as pallet_evm::Config>::ChainId::get()992 }993994 fn account_basic(address: H160) -> EVMAccount {995 EVM::account_basic(&address)996 }997998 fn gas_price() -> U256 {999 <Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price()1000 }10011002 fn account_code_at(address: H160) -> Vec<u8> {1003 EVM::account_codes(address)1004 }10051006 fn author() -> H160 {1007 <pallet_evm::Pallet<Runtime>>::find_author()1008 }10091010 fn storage_at(address: H160, index: U256) -> H256 {1011 let mut tmp = [0u8; 32];1012 index.to_big_endian(&mut tmp);1013 EVM::account_storages(address, H256::from_slice(&tmp[..]))1014 }10151016 fn call(1017 from: H160,1018 to: H160,1019 data: Vec<u8>,1020 value: U256,1021 gas_limit: U256,1022 gas_price: Option<U256>,1023 nonce: Option<U256>,1024 estimate: bool,1025 ) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {1026 let config = if estimate {1027 let mut config = <Runtime as pallet_evm::Config>::config().clone();1028 config.estimate = true;1029 Some(config)1030 } else {1031 None1032 };10331034 <Runtime as pallet_evm::Config>::Runner::call(1035 from,1036 to,1037 data,1038 value,1039 gas_limit.low_u64(),1040 gas_price,1041 nonce,1042 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),1043 ).map_err(|err| err.into())1044 }10451046 fn create(1047 from: H160,1048 data: Vec<u8>,1049 value: U256,1050 gas_limit: U256,1051 gas_price: Option<U256>,1052 nonce: Option<U256>,1053 estimate: bool,1054 ) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {1055 let config = if estimate {1056 let mut config = <Runtime as pallet_evm::Config>::config().clone();1057 config.estimate = true;1058 Some(config)1059 } else {1060 None1061 };10621063 <Runtime as pallet_evm::Config>::Runner::create(1064 from,1065 data,1066 value,1067 gas_limit.low_u64(),1068 gas_price,1069 nonce,1070 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),1071 ).map_err(|err| err.into())1072 }10731074 fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {1075 Ethereum::current_transaction_statuses()1076 }10771078 fn current_block() -> Option<pallet_ethereum::Block> {1079 Ethereum::current_block()1080 }10811082 fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {1083 Ethereum::current_receipts()1084 }10851086 fn current_all() -> (1087 Option<pallet_ethereum::Block>,1088 Option<Vec<pallet_ethereum::Receipt>>,1089 Option<Vec<TransactionStatus>>1090 ) {1091 (1092 Ethereum::current_block(),1093 Ethereum::current_receipts(),1094 Ethereum::current_transaction_statuses()1095 )1096 }10971098 fn extrinsic_filter(xts: Vec<<Block as sp_api::BlockT>::Extrinsic>) -> Vec<pallet_ethereum::Transaction> {1099 xts.into_iter().filter_map(|xt| match xt.function {1100 Call::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction),1101 _ => None1102 }).collect()1103 }1104 }11051106 impl sp_session::SessionKeys<Block> for Runtime {1107 fn decode_session_keys(1108 encoded: Vec<u8>,1109 ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {1110 SessionKeys::decode_into_raw_public_keys(&encoded)1111 }11121113 fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {1114 SessionKeys::generate(seed)1115 }1116 }11171118 impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {1119 fn slot_duration() -> sp_consensus_aura::SlotDuration {1120 sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())1121 }11221123 fn authorities() -> Vec<AuraId> {1124 Aura::authorities().to_vec()1125 }1126 }11271128 impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {1129 fn collect_collation_info() -> cumulus_primitives_core::CollationInfo {1130 ParachainSystem::collect_collation_info()1131 }1132 }11331134 impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {1135 fn account_nonce(account: AccountId) -> Index {1136 System::account_nonce(account)1137 }1138 }11391140 impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {1141 fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {1142 TransactionPayment::query_info(uxt, len)1143 }1144 fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {1145 TransactionPayment::query_fee_details(uxt, len)1146 }1147 }11481149 11501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190 #[cfg(feature = "runtime-benchmarks")]1191 impl frame_benchmarking::Benchmark<Block> for Runtime {1192 fn dispatch_benchmark(1193 config: frame_benchmarking::BenchmarkConfig1194 ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {1195 use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};11961197 let whitelist: Vec<TrackedStorageKey> = vec![1198 1199 hex_literal::hex!("d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d").to_vec().into(),1200 1201 1202 1203 1204 1205 1206 1207 1208 ];12091210 let mut batches = Vec::<BenchmarkBatch>::new();1211 let params = (&config, &whitelist);12121213 add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);1214 add_benchmark!(params, batches, pallet_nft, Nft);1215 add_benchmark!(params, batches, pallet_inflation, Inflation);12161217 if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }1218 Ok(batches)1219 }1220 }1221}12221223struct CheckInherents;12241225impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {1226 fn check_inherents(1227 block: &Block,1228 relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,1229 ) -> sp_inherents::CheckInherentsResult {1230 let relay_chain_slot = relay_state_proof1231 .read_slot()1232 .expect("Could not read the relay chain slot from the proof");12331234 let inherent_data =1235 cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(1236 relay_chain_slot,1237 sp_std::time::Duration::from_secs(6),1238 )1239 .create_inherent_data()1240 .expect("Could not create the timestamp inherent data");12411242 inherent_data.check_extrinsics(block)1243 }1244}12451246cumulus_pallet_parachain_system::register_validate_block!(1247 Runtime = Runtime,1248 BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,1249 CheckInherents = CheckInherents,1250);