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 {792 type SponsorshipHandler = pallet_nft::NftSponsorshipHandler<Runtime>;793}794795796797798799parameter_types! {800 801 pub const HelpersContractAddress: H160 = H160([802 0x84, 0x28, 0x99, 0xec, 0xf3, 0x80, 0x55, 0x3e, 0x8a, 0x4d, 0xe7, 0x5b, 0xf5, 0x34, 0xcd, 0xf6, 0xfb, 0xf6, 0x40, 0x49,803 ]);804}805806impl pallet_evm_contract_helpers::Config for Runtime {807 type ContractAddress = HelpersContractAddress;808 type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;809}810811construct_runtime!(812 pub enum Runtime where813 Block = Block,814 NodeBlock = opaque::Block,815 UncheckedExtrinsic = UncheckedExtrinsic816 {817 ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Storage, Inherent, Event<T>, ValidateUnsigned} = 20,818 ParachainInfo: parachain_info::{Pallet, Storage, Config} = 21,819820 Aura: pallet_aura::{Pallet, Config<T>} = 22,821 AuraExt: cumulus_pallet_aura_ext::{Pallet, Config} = 23,822823 Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 30,824 RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage} = 31,825 Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 32,826 TransactionPayment: pallet_transaction_payment::{Pallet, Storage} = 33,827 Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event<T>} = 34,828 Sudo: pallet_sudo::{Pallet, Call, Storage, Config<T>, Event<T>} = 35,829 System: system::{Pallet, Call, Storage, Config, Event<T>} = 36,830 Vesting: pallet_vesting::{Pallet, Call, Config<T>, Storage, Event<T>} = 37,831 832833 834 XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 50,835 PolkadotXcm: pallet_xcm::{Pallet, Call, Event<T>, Origin} = 51,836 CumulusXcm: cumulus_pallet_xcm::{Pallet, Call, Event<T>, Origin} = 52,837 DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,838839 840 Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,841 Nft: pallet_nft::{Pallet, Call, Config<T>, Storage, Event<T>} = 61,842 Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,843 NftPayment: pallet_nft_transaction_payment::{Pallet, Call, Storage} = 63,844 Charging: pallet_nft_charge_transaction::{Pallet, Call, Storage } = 64,845 846847 848 EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,849 Ethereum: pallet_ethereum::{Pallet, Config, Call, Storage, Event, Origin} = 101,850851 EvmCoderSubstrate: pallet_evm_coder_substrate::{Pallet, Storage} = 150,852 EvmContractHelpers: pallet_evm_contract_helpers::{Pallet, Storage} = 151,853 EvmTransactionPayment: pallet_evm_transaction_payment::{Pallet} = 152,854 EvmMigration: pallet_evm_migration::{Pallet, Call, Storage} = 153,855 }856);857858pub struct TransactionConverter;859860impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {861 fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {862 UncheckedExtrinsic::new_unsigned(863 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),864 )865 }866}867868impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {869 fn convert_transaction(870 &self,871 transaction: pallet_ethereum::Transaction,872 ) -> opaque::UncheckedExtrinsic {873 let extrinsic = UncheckedExtrinsic::new_unsigned(874 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),875 );876 let encoded = extrinsic.encode();877 opaque::UncheckedExtrinsic::decode(&mut &encoded[..])878 .expect("Encoded extrinsic is always valid")879 }880}881882883pub type Address = sp_runtime::MultiAddress<AccountId, ()>;884885pub type Header = generic::Header<BlockNumber, BlakeTwo256>;886887pub type Block = generic::Block<Header, UncheckedExtrinsic>;888889pub type SignedBlock = generic::SignedBlock<Block>;890891pub type BlockId = generic::BlockId<Block>;892893pub type SignedExtra = (894 system::CheckSpecVersion<Runtime>,895 896 system::CheckGenesis<Runtime>,897 system::CheckEra<Runtime>,898 system::CheckNonce<Runtime>,899 system::CheckWeight<Runtime>,900 pallet_nft_charge_transaction::ChargeTransactionPayment<Runtime>,901 902);903904pub type UncheckedExtrinsic =905 fp_self_contained::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;906907pub type CheckedExtrinsic = fp_self_contained::CheckedExtrinsic<AccountId, Call, SignedExtra, H160>;908909pub type Executive = frame_executive::Executive<910 Runtime,911 Block,912 frame_system::ChainContext<Runtime>,913 Runtime,914 AllPallets,915>;916917impl_opaque_keys! {918 pub struct SessionKeys {919 pub aura: Aura,920 }921}922923impl fp_self_contained::SelfContainedCall for Call {924 type SignedInfo = H160;925926 fn is_self_contained(&self) -> bool {927 match self {928 Call::Ethereum(call) => call.is_self_contained(),929 _ => false,930 }931 }932933 fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {934 match self {935 Call::Ethereum(call) => call.check_self_contained(),936 _ => None,937 }938 }939940 fn validate_self_contained(&self, info: &Self::SignedInfo) -> Option<TransactionValidity> {941 match self {942 Call::Ethereum(call) => call.validate_self_contained(info),943 _ => None,944 }945 }946947 fn pre_dispatch_self_contained(948 &self,949 info: &Self::SignedInfo,950 ) -> Option<Result<(), TransactionValidityError>> {951 match self {952 Call::Ethereum(call) => call.pre_dispatch_self_contained(info),953 _ => None,954 }955 }956957 fn apply_self_contained(958 self,959 info: Self::SignedInfo,960 ) -> Option<sp_runtime::DispatchResultWithInfo<PostDispatchInfoOf<Self>>> {961 match self {962 call @ Call::Ethereum(pallet_ethereum::Call::transact { .. }) => Some(call.dispatch(963 Origin::from(pallet_ethereum::RawOrigin::EthereumTransaction(info)),964 )),965 _ => None,966 }967 }968}969970impl_runtime_apis! {971 impl pallet_nft::NftApi<Block>972 for Runtime973 {974 fn eth_contract_code(account: H160) -> Option<Vec<u8>> {975 <pallet_nft::NftErcSupport<Runtime>>::get_code(&account)976 }977 }978979 impl sp_api::Core<Block> for Runtime {980 fn version() -> RuntimeVersion {981 VERSION982 }983984 fn execute_block(block: Block) {985 Executive::execute_block(block)986 }987988 fn initialize_block(header: &<Block as BlockT>::Header) {989 Executive::initialize_block(header)990 }991 }992993 impl sp_api::Metadata<Block> for Runtime {994 fn metadata() -> OpaqueMetadata {995 OpaqueMetadata::new(Runtime::metadata().into())996 }997 }998999 impl sp_block_builder::BlockBuilder<Block> for Runtime {1000 fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {1001 Executive::apply_extrinsic(extrinsic)1002 }10031004 fn finalize_block() -> <Block as BlockT>::Header {1005 Executive::finalize_block()1006 }10071008 fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {1009 data.create_extrinsics()1010 }10111012 fn check_inherents(1013 block: Block,1014 data: sp_inherents::InherentData,1015 ) -> sp_inherents::CheckInherentsResult {1016 data.check_extrinsics(&block)1017 }10181019 1020 1021 1022 }10231024 impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {1025 fn validate_transaction(1026 source: TransactionSource,1027 tx: <Block as BlockT>::Extrinsic,1028 hash: <Block as BlockT>::Hash,1029 ) -> TransactionValidity {1030 Executive::validate_transaction(source, tx, hash)1031 }1032 }10331034 impl sp_offchain::OffchainWorkerApi<Block> for Runtime {1035 fn offchain_worker(header: &<Block as BlockT>::Header) {1036 Executive::offchain_worker(header)1037 }1038 }10391040 impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {1041 fn chain_id() -> u64 {1042 <Runtime as pallet_evm::Config>::ChainId::get()1043 }10441045 fn account_basic(address: H160) -> EVMAccount {1046 EVM::account_basic(&address)1047 }10481049 fn gas_price() -> U256 {1050 <Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price()1051 }10521053 fn account_code_at(address: H160) -> Vec<u8> {1054 EVM::account_codes(address)1055 }10561057 fn author() -> H160 {1058 <pallet_evm::Pallet<Runtime>>::find_author()1059 }10601061 fn storage_at(address: H160, index: U256) -> H256 {1062 let mut tmp = [0u8; 32];1063 index.to_big_endian(&mut tmp);1064 EVM::account_storages(address, H256::from_slice(&tmp[..]))1065 }10661067 fn call(1068 from: H160,1069 to: H160,1070 data: Vec<u8>,1071 value: U256,1072 gas_limit: U256,1073 gas_price: Option<U256>,1074 nonce: Option<U256>,1075 estimate: bool,1076 ) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {1077 let config = if estimate {1078 let mut config = <Runtime as pallet_evm::Config>::config().clone();1079 config.estimate = true;1080 Some(config)1081 } else {1082 None1083 };10841085 <Runtime as pallet_evm::Config>::Runner::call(1086 from,1087 to,1088 data,1089 value,1090 gas_limit.low_u64(),1091 gas_price,1092 nonce,1093 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),1094 ).map_err(|err| err.into())1095 }10961097 fn create(1098 from: H160,1099 data: Vec<u8>,1100 value: U256,1101 gas_limit: U256,1102 gas_price: Option<U256>,1103 nonce: Option<U256>,1104 estimate: bool,1105 ) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {1106 let config = if estimate {1107 let mut config = <Runtime as pallet_evm::Config>::config().clone();1108 config.estimate = true;1109 Some(config)1110 } else {1111 None1112 };11131114 <Runtime as pallet_evm::Config>::Runner::create(1115 from,1116 data,1117 value,1118 gas_limit.low_u64(),1119 gas_price,1120 nonce,1121 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),1122 ).map_err(|err| err.into())1123 }11241125 fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {1126 Ethereum::current_transaction_statuses()1127 }11281129 fn current_block() -> Option<pallet_ethereum::Block> {1130 Ethereum::current_block()1131 }11321133 fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {1134 Ethereum::current_receipts()1135 }11361137 fn current_all() -> (1138 Option<pallet_ethereum::Block>,1139 Option<Vec<pallet_ethereum::Receipt>>,1140 Option<Vec<TransactionStatus>>1141 ) {1142 (1143 Ethereum::current_block(),1144 Ethereum::current_receipts(),1145 Ethereum::current_transaction_statuses()1146 )1147 }11481149 fn extrinsic_filter(xts: Vec<<Block as sp_api::BlockT>::Extrinsic>) -> Vec<pallet_ethereum::Transaction> {1150 xts.into_iter().filter_map(|xt| match xt.0.function {1151 Call::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction),1152 _ => None1153 }).collect()1154 }1155 }11561157 impl sp_session::SessionKeys<Block> for Runtime {1158 fn decode_session_keys(1159 encoded: Vec<u8>,1160 ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {1161 SessionKeys::decode_into_raw_public_keys(&encoded)1162 }11631164 fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {1165 SessionKeys::generate(seed)1166 }1167 }11681169 impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {1170 fn slot_duration() -> sp_consensus_aura::SlotDuration {1171 sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())1172 }11731174 fn authorities() -> Vec<AuraId> {1175 Aura::authorities().to_vec()1176 }1177 }11781179 impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {1180 fn collect_collation_info() -> cumulus_primitives_core::CollationInfo {1181 ParachainSystem::collect_collation_info()1182 }1183 }11841185 impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {1186 fn account_nonce(account: AccountId) -> Index {1187 System::account_nonce(account)1188 }1189 }11901191 impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {1192 fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {1193 TransactionPayment::query_info(uxt, len)1194 }1195 fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {1196 TransactionPayment::query_fee_details(uxt, len)1197 }1198 }11991200 12011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241 #[cfg(feature = "runtime-benchmarks")]1242 impl frame_benchmarking::Benchmark<Block> for Runtime {1243 fn dispatch_benchmark(1244 config: frame_benchmarking::BenchmarkConfig1245 ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {1246 use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};12471248 let whitelist: Vec<TrackedStorageKey> = vec![1249 1250 hex_literal::hex!("d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d").to_vec().into(),1251 1252 1253 1254 1255 1256 1257 1258 1259 ];12601261 let mut batches = Vec::<BenchmarkBatch>::new();1262 let params = (&config, &whitelist);12631264 add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);1265 add_benchmark!(params, batches, pallet_nft, Nft);1266 add_benchmark!(params, batches, pallet_inflation, Inflation);12671268 if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }1269 Ok(batches)1270 }1271 }1272}12731274struct CheckInherents;12751276impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {1277 fn check_inherents(1278 block: &Block,1279 relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,1280 ) -> sp_inherents::CheckInherentsResult {1281 let relay_chain_slot = relay_state_proof1282 .read_slot()1283 .expect("Could not read the relay chain slot from the proof");12841285 let inherent_data =1286 cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(1287 relay_chain_slot,1288 sp_std::time::Duration::from_secs(6),1289 )1290 .create_inherent_data()1291 .expect("Could not create the timestamp inherent data");12921293 inherent_data.check_extrinsics(block)1294 }1295}12961297cumulus_pallet_parachain_system::register_validate_block!(1298 Runtime = Runtime,1299 BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,1300 CheckInherents = CheckInherents,1301);