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, PostDispatchInfoOf},74 transaction_validity::TransactionValidityError,75};767778pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;798081use pallet_xcm::XcmPassthrough;82use polkadot_parachain::primitives::Sibling;83use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};84use xcm_builder::{85 AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter,86 EnsureXcmOrigin, FixedWeightBounds, IsConcrete, LocationInverter, NativeAsset,87 ParentAsSuperuser, ParentIsDefault, RelayChainAsNative, SiblingParachainAsNative,88 SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32,89 SovereignSignedViaLocation, TakeWeightCredit, UsingComponents,90};91use xcm_executor::{Config, XcmExecutor};929394959697pub type BlockNumber = u32;9899100pub type Signature = MultiSignature;101102103104pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;105106107108pub type AccountIndex = u32;109110111pub type Balance = u128;112113114pub type Index = u32;115116117pub type Hash = sp_core::H256;118119120pub type DigestItem = generic::DigestItem<Hash>;121122123124125126pub mod opaque {127 use super::*;128129 pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;130131 132 pub type Block = generic::Block<Header, UncheckedExtrinsic>;133134 pub type SessionHandlers = ();135136 impl_opaque_keys! {137 pub struct SessionKeys {138 pub aura: Aura,139 }140 }141}142143144pub const VERSION: RuntimeVersion = RuntimeVersion {145 spec_name: create_runtime_str!("opal"),146 impl_name: create_runtime_str!("opal"),147 authoring_version: 1,148 spec_version: 912200,149 impl_version: 1,150 apis: RUNTIME_API_VERSIONS,151 transaction_version: 1,152};153154pub const MILLISECS_PER_BLOCK: u64 = 12000;155156pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;157158159pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);160pub const HOURS: BlockNumber = MINUTES * 60;161pub const DAYS: BlockNumber = HOURS * 24;162163parameter_types! {164 pub const DefaultSponsoringRateLimit: BlockNumber = 1 * DAYS;165}166167#[derive(codec::Encode, codec::Decode)]168pub enum XCMPMessage<XAccountId, XBalance> {169 170 TransferToken(XAccountId, XBalance),171}172173174#[cfg(feature = "std")]175pub fn native_version() -> NativeVersion {176 NativeVersion {177 runtime_version: VERSION,178 can_author_with: Default::default(),179 }180}181182type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;183184pub struct DealWithFees;185impl OnUnbalanced<NegativeImbalance> for DealWithFees {186 fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {187 if let Some(fees) = fees_then_tips.next() {188 189 let mut split = fees.ration(100, 0);190 if let Some(tips) = fees_then_tips.next() {191 192 tips.ration_merge_into(100, 0, &mut split);193 }194 Treasury::on_unbalanced(split.0);195 196 }197 }198}199200201202const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(10);203204205const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);206207const MAXIMUM_BLOCK_WEIGHT: Weight = WEIGHT_PER_SECOND / 2;208209parameter_types! {210 pub const BlockHashCount: BlockNumber = 2400;211 pub RuntimeBlockLength: BlockLength =212 BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);213 pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);214 pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;215 pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()216 .base_block(BlockExecutionWeight::get())217 .for_class(DispatchClass::all(), |weights| {218 weights.base_extrinsic = ExtrinsicBaseWeight::get();219 })220 .for_class(DispatchClass::Normal, |weights| {221 weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);222 })223 .for_class(DispatchClass::Operational, |weights| {224 weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);225 226 227 weights.reserved = Some(228 MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT229 );230 })231 .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)232 .build_or_panic();233 pub const Version: RuntimeVersion = VERSION;234 pub const SS58Prefix: u8 = 42;235}236237parameter_types! {238 pub const ChainId: u64 = 8888;239}240241pub struct FixedFee;242impl FeeCalculator for FixedFee {243 fn min_gas_price() -> U256 {244 1.into()245 }246}247248impl pallet_evm::Config for Runtime {249 type BlockGasLimit = BlockGasLimit;250 type FeeCalculator = FixedFee;251 type GasWeightMapping = ();252 type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;253 type CallOrigin = EnsureAddressTruncated;254 type WithdrawOrigin = EnsureAddressTruncated;255 type AddressMapping = HashedAddressMapping<Self::Hashing>;256 type Precompiles = ();257 type Currency = Balances;258 type Event = Event;259 type OnMethodCall = (260 pallet_evm_migration::OnMethodCall<Self>,261 pallet_nft::NftErcSupport<Self>,262 pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,263 );264 type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;265 type ChainId = ChainId;266 type Runner = pallet_evm::runner::stack::Runner<Self>;267 type OnChargeTransaction = pallet_evm_transaction_payment::OnChargeTransaction<Self>;268 type TransactionValidityHack = pallet_evm_transaction_payment::TransactionValidityHack<Self>;269 type FindAuthor = EthereumFindAuthor<Aura>;270}271272impl pallet_evm_migration::Config for Runtime {273 type WeightInfo = pallet_evm_migration::weights::SubstrateWeight<Self>;274}275276pub struct EthereumFindAuthor<F>(core::marker::PhantomData<F>);277impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F> {278 fn find_author<'a, I>(digests: I) -> Option<H160>279 where280 I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,281 {282 if let Some(author_index) = F::find_author(digests) {283 let authority_id = Aura::authorities()[author_index as usize].clone();284 return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24]));285 }286 None287 }288}289290parameter_types! {291 pub BlockGasLimit: U256 = U256::from(u32::max_value());292}293294impl pallet_ethereum::Config for Runtime {295 type Event = Event;296 type StateRoot = pallet_ethereum::IntermediateStateRoot;297 type EvmSubmitLog = pallet_evm::Pallet<Self>;298}299300impl pallet_randomness_collective_flip::Config for Runtime {}301302impl system::Config for Runtime {303 304 type AccountData = pallet_balances::AccountData<Balance>;305 306 type AccountId = AccountId;307 308 type BaseCallFilter = Everything;309 310 type BlockHashCount = BlockHashCount;311 312 type BlockLength = RuntimeBlockLength;313 314 type BlockNumber = BlockNumber;315 316 type BlockWeights = RuntimeBlockWeights;317 318 type Call = Call;319 320 type DbWeight = RocksDbWeight;321 322 type Event = Event;323 324 type Hash = Hash;325 326 type Hashing = BlakeTwo256;327 328 type Header = generic::Header<BlockNumber, BlakeTwo256>;329 330 type Index = Index;331 332 type Lookup = AccountIdLookup<AccountId, ()>;333 334 type OnKilledAccount = ();335 336 type OnNewAccount = ();337 type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;338 339 type Origin = Origin;340 341 type PalletInfo = PalletInfo;342 343 type SS58Prefix = SS58Prefix;344 345 type SystemWeightInfo = system::weights::SubstrateWeight<Self>;346 347 type Version = Version;348}349350parameter_types! {351 pub const MinimumPeriod: u64 = SLOT_DURATION / 2;352}353354impl pallet_timestamp::Config for Runtime {355 356 type Moment = u64;357 type OnTimestampSet = ();358 type MinimumPeriod = MinimumPeriod;359 type WeightInfo = ();360}361362parameter_types! {363 364 pub const ExistentialDeposit: u128 = 0;365 pub const MaxLocks: u32 = 50;366}367368impl pallet_balances::Config for Runtime {369 type MaxLocks = MaxLocks;370 type MaxReserves = ();371 type ReserveIdentifier = [u8; 8];372 373 type Balance = Balance;374 375 type Event = Event;376 type DustRemoval = Treasury;377 type ExistentialDeposit = ExistentialDeposit;378 type AccountStore = System;379 type WeightInfo = pallet_balances::weights::SubstrateWeight<Self>;380}381382pub const MICROUNIQUE: Balance = 1_000_000_000;383pub const MILLIUNIQUE: Balance = 1_000 * MICROUNIQUE;384pub const CENTIUNIQUE: Balance = 10 * MILLIUNIQUE;385pub const UNIQUE: Balance = 100 * CENTIUNIQUE;386387pub const fn deposit(items: u32, bytes: u32) -> Balance {388 items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE389}390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441parameter_types! {442 pub const TransactionByteFee: Balance = 501 * MICROUNIQUE; 443 444 445 pub const OperationalFeeMultiplier: u8 = 5;446}447448449pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);450451impl<T> WeightToFeePolynomial for LinearFee<T>452where453 T: BaseArithmetic + From<u32> + Copy + Unsigned,454{455 type Balance = T;456457 fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {458 smallvec!(WeightToFeeCoefficient {459 coeff_integer: 146_700u32.into(), 460 coeff_frac: Perbill::zero(),461 negative: false,462 degree: 1,463 })464 }465}466467impl pallet_transaction_payment::Config for Runtime {468 type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, DealWithFees>;469 type TransactionByteFee = TransactionByteFee;470 type OperationalFeeMultiplier = OperationalFeeMultiplier;471 type WeightToFee = LinearFee<Balance>;472 type FeeMultiplierUpdate = ();473}474475parameter_types! {476 pub const ProposalBond: Permill = Permill::from_percent(5);477 pub const ProposalBondMinimum: Balance = 1 * UNIQUE;478 pub const SpendPeriod: BlockNumber = 5 * MINUTES;479 pub const Burn: Permill = Permill::from_percent(0);480 pub const TipCountdown: BlockNumber = 1 * DAYS;481 pub const TipFindersFee: Percent = Percent::from_percent(20);482 pub const TipReportDepositBase: Balance = 1 * UNIQUE;483 pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;484 pub const BountyDepositBase: Balance = 1 * UNIQUE;485 pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;486 pub const TreasuryModuleId: PalletId = PalletId(*b"py/trsry");487 pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;488 pub const MaximumReasonLength: u32 = 16384;489 pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);490 pub const BountyValueMinimum: Balance = 5 * UNIQUE;491 pub const MaxApprovals: u32 = 100;492}493494impl pallet_treasury::Config for Runtime {495 type PalletId = TreasuryModuleId;496 type Currency = Balances;497 type ApproveOrigin = EnsureRoot<AccountId>;498 type RejectOrigin = EnsureRoot<AccountId>;499 type Event = Event;500 type OnSlash = ();501 type ProposalBond = ProposalBond;502 type ProposalBondMinimum = ProposalBondMinimum;503 type SpendPeriod = SpendPeriod;504 type Burn = Burn;505 type BurnDestination = ();506 type SpendFunds = ();507 type WeightInfo = pallet_treasury::weights::SubstrateWeight<Self>;508 type MaxApprovals = MaxApprovals;509}510511impl pallet_sudo::Config for Runtime {512 type Event = Event;513 type Call = Call;514}515516parameter_types! {517 pub const MinVestedTransfer: Balance = 10 * UNIQUE;518}519520impl pallet_vesting::Config for Runtime {521 type Event = Event;522 type Currency = Balances;523 type BlockNumberToBalance = ConvertInto;524 type MinVestedTransfer = MinVestedTransfer;525 type WeightInfo = ();526 const MAX_VESTING_SCHEDULES: u32 = 28;527}528529parameter_types! {530 pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;531 pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;532}533534impl cumulus_pallet_parachain_system::Config for Runtime {535 type Event = Event;536 type OnValidationData = ();537 type SelfParaId = parachain_info::Pallet<Self>;538 539 540 541 542 543 type OutboundXcmpMessageSource = XcmpQueue;544 type DmpMessageHandler = DmpQueue;545 type ReservedDmpWeight = ReservedDmpWeight;546 type ReservedXcmpWeight = ReservedXcmpWeight;547 type XcmpMessageHandler = XcmpQueue;548}549550impl parachain_info::Config for Runtime {}551552impl cumulus_pallet_aura_ext::Config for Runtime {}553554parameter_types! {555 pub const RelayLocation: MultiLocation = MultiLocation::parent();556 pub const RelayNetwork: NetworkId = NetworkId::Polkadot;557 pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();558 pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();559}560561562563564pub type LocationToAccountId = (565 566 ParentIsDefault<AccountId>,567 568 SiblingParachainConvertsVia<Sibling, AccountId>,569 570 AccountId32Aliases<RelayNetwork, AccountId>,571);572573574pub type LocalAssetTransactor = CurrencyAdapter<575 576 Balances,577 578 IsConcrete<RelayLocation>,579 580 LocationToAccountId,581 582 AccountId,583 584 (),585>;586587588589590pub type XcmOriginToTransactDispatchOrigin = (591 592 593 594 SovereignSignedViaLocation<LocationToAccountId, Origin>,595 596 597 RelayChainAsNative<RelayOrigin, Origin>,598 599 600 SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,601 602 603 ParentAsSuperuser<Origin>,604 605 606 SignedAccountId32AsNative<RelayNetwork, Origin>,607 608 XcmPassthrough<Origin>,609);610611parameter_types! {612 613 pub UnitWeightCost: Weight = 1_000_000;614 615 pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);616 pub const MaxInstructions: u32 = 100;617 pub const MaxAuthorities: u32 = 100_000;618}619620match_type! {621 pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {622 MultiLocation { parents: 1, interior: Here } |623 MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }624 };625}626627pub type Barrier = (628 TakeWeightCredit,629 AllowTopLevelPaidExecutionFrom<Everything>,630 AllowUnpaidExecutionFrom<ParentOrParentsUnitPlurality>,631 632);633634pub struct XcmConfig;635impl Config for XcmConfig {636 type Call = Call;637 type XcmSender = XcmRouter;638 639 type AssetTransactor = LocalAssetTransactor;640 type OriginConverter = XcmOriginToTransactDispatchOrigin;641 type IsReserve = NativeAsset;642 type IsTeleporter = (); 643 type LocationInverter = LocationInverter<Ancestry>;644 type Barrier = Barrier;645 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;646 type Trader = UsingComponents<IdentityFee<Balance>, RelayLocation, AccountId, Balances, ()>;647 type ResponseHandler = (); 648 type SubscriptionService = PolkadotXcm;649650 type AssetTrap = PolkadotXcm;651 type AssetClaims = PolkadotXcm;652}653654655656657658659pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);660661662663pub type XcmRouter = (664 665 cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,666 667 XcmpQueue,668);669670impl pallet_evm_coder_substrate::Config for Runtime {671 type EthereumTransactionSender = pallet_ethereum::Pallet<Self>;672}673674impl pallet_xcm::Config for Runtime {675 type Event = Event;676 type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;677 type XcmRouter = XcmRouter;678 type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;679 type XcmExecuteFilter = Everything;680 type XcmExecutor = XcmExecutor<XcmConfig>;681 type XcmTeleportFilter = Everything;682 type XcmReserveTransferFilter = Everything;683 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;684 type LocationInverter = LocationInverter<Ancestry>;685 type Origin = Origin;686 type Call = Call;687 const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;688 type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;689}690691impl cumulus_pallet_xcm::Config for Runtime {692 type Event = Event;693 type XcmExecutor = XcmExecutor<XcmConfig>;694}695696impl cumulus_pallet_xcmp_queue::Config for Runtime {697 type Event = Event;698 type XcmExecutor = XcmExecutor<XcmConfig>;699 type ChannelInfo = ParachainSystem;700 type VersionWrapper = ();701}702703impl cumulus_pallet_dmp_queue::Config for Runtime {704 type Event = Event;705 type XcmExecutor = XcmExecutor<XcmConfig>;706 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;707}708709impl pallet_aura::Config for Runtime {710 type AuthorityId = AuraId;711 type DisabledValidators = ();712 type MaxAuthorities = MaxAuthorities;713}714715parameter_types! {716 pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();717 pub const CollectionCreationPrice: Balance = 100 * UNIQUE;718}719720721impl pallet_nft::Config for Runtime {722 type Event = Event;723 type WeightInfo = pallet_nft::weights::SubstrateWeight<Self>;724725 type EvmBackwardsAddressMapping = pallet_nft::MapBackwardsAddressTruncated;726 type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;727 type CrossAccountId = pallet_nft::BasicCrossAccountId<Self>;728729 type Currency = Balances;730 type CollectionCreationPrice = CollectionCreationPrice;731 type TreasuryAccountId = TreasuryAccountId;732}733734parameter_types! {735 pub const InflationBlockInterval: BlockNumber = 100; 736}737738739impl pallet_inflation::Config for Runtime {740 type Currency = Balances;741 type TreasuryAccountId = TreasuryAccountId;742 type InflationBlockInterval = InflationBlockInterval;743}744745parameter_types! {746 pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *747 RuntimeBlockWeights::get().max_block;748 pub const MaxScheduledPerBlock: u32 = 50;749}750751pub struct Sponsoring;752impl SponsoringResolve<AccountId, Call> for Sponsoring {753 fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>754 where755 Call: Dispatchable<Info = DispatchInfo>,756 AccountId: AsRef<[u8]>,757 {758 pallet_nft_transaction_payment::Module::<Runtime>::withdraw_type(who, call)759 }760}761762type SponsorshipHandler = (763 pallet_nft::NftSponsorshipHandler<Runtime>,764 765);766767impl pallet_unq_scheduler::Config for Runtime {768 type Event = Event;769 type Origin = Origin;770 type PalletsOrigin = OriginCaller;771 type Call = Call;772 type MaximumWeight = MaximumSchedulerWeight;773 type ScheduleOrigin = EnsureSigned<AccountId>;774 type MaxScheduledPerBlock = MaxScheduledPerBlock;775 type SponsorshipHandler = SponsorshipHandler;776 type WeightInfo = ();777}778779impl pallet_nft_transaction_payment::Config for Runtime {780 type SponsorshipHandler = SponsorshipHandler;781}782783impl pallet_evm_transaction_payment::Config for Runtime {784 type SponsorshipHandler = (785 pallet_nft::NftEthSponsorshipHandler<Self>,786 pallet_evm_contract_helpers::HelpersContractSponsoring<Self>,787 );788 type Currency = Balances;789}790791impl pallet_nft_charge_transaction::Config for Runtime {}792793794795796797parameter_types! {798 799 pub const HelpersContractAddress: H160 = H160([800 0x84, 0x28, 0x99, 0xec, 0xf3, 0x80, 0x55, 0x3e, 0x8a, 0x4d, 0xe7, 0x5b, 0xf5, 0x34, 0xcd, 0xf6, 0xfb, 0xf6, 0x40, 0x49,801 ]);802}803804impl pallet_evm_contract_helpers::Config for Runtime {805 type ContractAddress = HelpersContractAddress;806 type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;807}808809construct_runtime!(810 pub enum Runtime where811 Block = Block,812 NodeBlock = opaque::Block,813 UncheckedExtrinsic = UncheckedExtrinsic814 {815 ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Storage, Inherent, Event<T>, ValidateUnsigned} = 20,816 ParachainInfo: parachain_info::{Pallet, Storage, Config} = 21,817818 Aura: pallet_aura::{Pallet, Config<T>} = 22,819 AuraExt: cumulus_pallet_aura_ext::{Pallet, Config} = 23,820821 Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 30,822 RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage} = 31,823 Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 32,824 TransactionPayment: pallet_transaction_payment::{Pallet, Storage} = 33,825 Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event<T>} = 34,826 Sudo: pallet_sudo::{Pallet, Call, Storage, Config<T>, Event<T>} = 35,827 System: system::{Pallet, Call, Storage, Config, Event<T>} = 36,828 Vesting: pallet_vesting::{Pallet, Call, Config<T>, Storage, Event<T>} = 37,829 830831 832 XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 50,833 PolkadotXcm: pallet_xcm::{Pallet, Call, Event<T>, Origin} = 51,834 CumulusXcm: cumulus_pallet_xcm::{Pallet, Call, Event<T>, Origin} = 52,835 DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,836837 838 Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,839 Nft: pallet_nft::{Pallet, Call, Config<T>, Storage, Event<T>} = 61,840 Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,841 NftPayment: pallet_nft_transaction_payment::{Pallet, Call, Storage} = 63,842 Charging: pallet_nft_charge_transaction::{Pallet, Call, Storage } = 64,843 844845 846 EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,847 Ethereum: pallet_ethereum::{Pallet, Config, Call, Storage, Event, Origin} = 101,848849 EvmCoderSubstrate: pallet_evm_coder_substrate::{Pallet, Storage} = 150,850 EvmContractHelpers: pallet_evm_contract_helpers::{Pallet, Storage} = 151,851 EvmTransactionPayment: pallet_evm_transaction_payment::{Pallet} = 152,852 EvmMigration: pallet_evm_migration::{Pallet, Call, Storage} = 153,853 }854);855856pub struct TransactionConverter;857858impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {859 fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {860 UncheckedExtrinsic::new_unsigned(861 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),862 )863 }864}865866impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {867 fn convert_transaction(868 &self,869 transaction: pallet_ethereum::Transaction,870 ) -> opaque::UncheckedExtrinsic {871 let extrinsic = UncheckedExtrinsic::new_unsigned(872 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),873 );874 let encoded = extrinsic.encode();875 opaque::UncheckedExtrinsic::decode(&mut &encoded[..])876 .expect("Encoded extrinsic is always valid")877 }878}879880881pub type Address = sp_runtime::MultiAddress<AccountId, ()>;882883pub type Header = generic::Header<BlockNumber, BlakeTwo256>;884885pub type Block = generic::Block<Header, UncheckedExtrinsic>;886887pub type SignedBlock = generic::SignedBlock<Block>;888889pub type BlockId = generic::BlockId<Block>;890891pub type SignedExtra = (892 system::CheckSpecVersion<Runtime>,893 894 system::CheckGenesis<Runtime>,895 system::CheckEra<Runtime>,896 system::CheckNonce<Runtime>,897 system::CheckWeight<Runtime>,898 pallet_nft_charge_transaction::ChargeTransactionPayment<Runtime>,899 900);901902pub type UncheckedExtrinsic =903 fp_self_contained::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;904905pub type CheckedExtrinsic = fp_self_contained::CheckedExtrinsic<AccountId, Call, SignedExtra, H160>;906907pub type Executive = frame_executive::Executive<908 Runtime,909 Block,910 frame_system::ChainContext<Runtime>,911 Runtime,912 AllPallets,913>;914915impl_opaque_keys! {916 pub struct SessionKeys {917 pub aura: Aura,918 }919}920921impl fp_self_contained::SelfContainedCall for Call {922 type SignedInfo = H160;923924 fn is_self_contained(&self) -> bool {925 match self {926 Call::Ethereum(call) => call.is_self_contained(),927 _ => false,928 }929 }930931 fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {932 match self {933 Call::Ethereum(call) => call.check_self_contained(),934 _ => None,935 }936 }937938 fn validate_self_contained(&self, info: &Self::SignedInfo) -> Option<TransactionValidity> {939 match self {940 Call::Ethereum(call) => call.validate_self_contained(info),941 _ => None,942 }943 }944945 fn pre_dispatch_self_contained(946 &self,947 info: &Self::SignedInfo,948 ) -> Option<Result<(), TransactionValidityError>> {949 match self {950 Call::Ethereum(call) => call.pre_dispatch_self_contained(info),951 _ => None,952 }953 }954955 fn apply_self_contained(956 self,957 info: Self::SignedInfo,958 ) -> Option<sp_runtime::DispatchResultWithInfo<PostDispatchInfoOf<Self>>> {959 match self {960 call @ Call::Ethereum(pallet_ethereum::Call::transact { .. }) => Some(call.dispatch(961 Origin::from(pallet_ethereum::RawOrigin::EthereumTransaction(info)),962 )),963 _ => None,964 }965 }966}967968impl_runtime_apis! {969 impl pallet_nft::NftApi<Block>970 for Runtime971 {972 fn eth_contract_code(account: H160) -> Option<Vec<u8>> {973 <pallet_nft::NftErcSupport<Runtime>>::get_code(&account).or_else(|| <pallet_evm_migration::OnMethodCall<Runtime>>::get_code(&account)).or_else(|| <pallet_evm_contract_helpers::HelpersOnMethodCall<Self>>::get_code(&account))974 }975 }976977 impl sp_api::Core<Block> for Runtime {978 fn version() -> RuntimeVersion {979 VERSION980 }981982 fn execute_block(block: Block) {983 Executive::execute_block(block)984 }985986 fn initialize_block(header: &<Block as BlockT>::Header) {987 Executive::initialize_block(header)988 }989 }990991 impl sp_api::Metadata<Block> for Runtime {992 fn metadata() -> OpaqueMetadata {993 OpaqueMetadata::new(Runtime::metadata().into())994 }995 }996997 impl sp_block_builder::BlockBuilder<Block> for Runtime {998 fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {999 Executive::apply_extrinsic(extrinsic)1000 }10011002 fn finalize_block() -> <Block as BlockT>::Header {1003 Executive::finalize_block()1004 }10051006 fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {1007 data.create_extrinsics()1008 }10091010 fn check_inherents(1011 block: Block,1012 data: sp_inherents::InherentData,1013 ) -> sp_inherents::CheckInherentsResult {1014 data.check_extrinsics(&block)1015 }10161017 1018 1019 1020 }10211022 impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {1023 fn validate_transaction(1024 source: TransactionSource,1025 tx: <Block as BlockT>::Extrinsic,1026 hash: <Block as BlockT>::Hash,1027 ) -> TransactionValidity {1028 Executive::validate_transaction(source, tx, hash)1029 }1030 }10311032 impl sp_offchain::OffchainWorkerApi<Block> for Runtime {1033 fn offchain_worker(header: &<Block as BlockT>::Header) {1034 Executive::offchain_worker(header)1035 }1036 }10371038 impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {1039 fn chain_id() -> u64 {1040 <Runtime as pallet_evm::Config>::ChainId::get()1041 }10421043 fn account_basic(address: H160) -> EVMAccount {1044 EVM::account_basic(&address)1045 }10461047 fn gas_price() -> U256 {1048 <Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price()1049 }10501051 fn account_code_at(address: H160) -> Vec<u8> {1052 EVM::account_codes(address)1053 }10541055 fn author() -> H160 {1056 <pallet_evm::Pallet<Runtime>>::find_author()1057 }10581059 fn storage_at(address: H160, index: U256) -> H256 {1060 let mut tmp = [0u8; 32];1061 index.to_big_endian(&mut tmp);1062 EVM::account_storages(address, H256::from_slice(&tmp[..]))1063 }10641065 fn call(1066 from: H160,1067 to: H160,1068 data: Vec<u8>,1069 value: U256,1070 gas_limit: U256,1071 gas_price: Option<U256>,1072 nonce: Option<U256>,1073 estimate: bool,1074 ) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {1075 let config = if estimate {1076 let mut config = <Runtime as pallet_evm::Config>::config().clone();1077 config.estimate = true;1078 Some(config)1079 } else {1080 None1081 };10821083 <Runtime as pallet_evm::Config>::Runner::call(1084 from,1085 to,1086 data,1087 value,1088 gas_limit.low_u64(),1089 gas_price,1090 nonce,1091 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),1092 ).map_err(|err| err.into())1093 }10941095 fn create(1096 from: H160,1097 data: Vec<u8>,1098 value: U256,1099 gas_limit: U256,1100 gas_price: Option<U256>,1101 nonce: Option<U256>,1102 estimate: bool,1103 ) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {1104 let config = if estimate {1105 let mut config = <Runtime as pallet_evm::Config>::config().clone();1106 config.estimate = true;1107 Some(config)1108 } else {1109 None1110 };11111112 <Runtime as pallet_evm::Config>::Runner::create(1113 from,1114 data,1115 value,1116 gas_limit.low_u64(),1117 gas_price,1118 nonce,1119 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),1120 ).map_err(|err| err.into())1121 }11221123 fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {1124 Ethereum::current_transaction_statuses()1125 }11261127 fn current_block() -> Option<pallet_ethereum::Block> {1128 Ethereum::current_block()1129 }11301131 fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {1132 Ethereum::current_receipts()1133 }11341135 fn current_all() -> (1136 Option<pallet_ethereum::Block>,1137 Option<Vec<pallet_ethereum::Receipt>>,1138 Option<Vec<TransactionStatus>>1139 ) {1140 (1141 Ethereum::current_block(),1142 Ethereum::current_receipts(),1143 Ethereum::current_transaction_statuses()1144 )1145 }11461147 fn extrinsic_filter(xts: Vec<<Block as sp_api::BlockT>::Extrinsic>) -> Vec<pallet_ethereum::Transaction> {1148 xts.into_iter().filter_map(|xt| match xt.0.function {1149 Call::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction),1150 _ => None1151 }).collect()1152 }1153 }11541155 impl sp_session::SessionKeys<Block> for Runtime {1156 fn decode_session_keys(1157 encoded: Vec<u8>,1158 ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {1159 SessionKeys::decode_into_raw_public_keys(&encoded)1160 }11611162 fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {1163 SessionKeys::generate(seed)1164 }1165 }11661167 impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {1168 fn slot_duration() -> sp_consensus_aura::SlotDuration {1169 sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())1170 }11711172 fn authorities() -> Vec<AuraId> {1173 Aura::authorities().to_vec()1174 }1175 }11761177 impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {1178 fn collect_collation_info() -> cumulus_primitives_core::CollationInfo {1179 ParachainSystem::collect_collation_info()1180 }1181 }11821183 impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {1184 fn account_nonce(account: AccountId) -> Index {1185 System::account_nonce(account)1186 }1187 }11881189 impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {1190 fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {1191 TransactionPayment::query_info(uxt, len)1192 }1193 fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {1194 TransactionPayment::query_fee_details(uxt, len)1195 }1196 }11971198 11991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239 #[cfg(feature = "runtime-benchmarks")]1240 impl frame_benchmarking::Benchmark<Block> for Runtime {1241 fn dispatch_benchmark(1242 config: frame_benchmarking::BenchmarkConfig1243 ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {1244 use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};12451246 let whitelist: Vec<TrackedStorageKey> = vec![1247 1248 hex_literal::hex!("d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d").to_vec().into(),1249 1250 1251 1252 1253 1254 1255 1256 1257 ];12581259 let mut batches = Vec::<BenchmarkBatch>::new();1260 let params = (&config, &whitelist);12611262 add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);1263 add_benchmark!(params, batches, pallet_nft, Nft);1264 add_benchmark!(params, batches, pallet_inflation, Inflation);12651266 if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }1267 Ok(batches)1268 }1269 }1270}12711272struct CheckInherents;12731274impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {1275 fn check_inherents(1276 block: &Block,1277 relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,1278 ) -> sp_inherents::CheckInherentsResult {1279 let relay_chain_slot = relay_state_proof1280 .read_slot()1281 .expect("Could not read the relay chain slot from the proof");12821283 let inherent_data =1284 cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(1285 relay_chain_slot,1286 sp_std::time::Duration::from_secs(6),1287 )1288 .create_inherent_data()1289 .expect("Could not create the timestamp inherent data");12901291 inherent_data.check_extrinsics(block)1292 }1293}12941295cumulus_pallet_parachain_system::register_validate_block!(1296 Runtime = Runtime,1297 BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,1298 CheckInherents = CheckInherents,1299);