difftreelog
Quartz ss58
in: master
1 file changed
runtime/src/lib.rsdiffbeforeafterboth1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56//! The Substrate Node Template runtime. This can be compiled with `#[no_std]`, ready for Wasm.78#![cfg_attr(not(feature = "std"), no_std)]9// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.10#![recursion_limit = "1024"]11#![allow(clippy::from_over_into, clippy::identity_op)]12#![allow(clippy::fn_to_numeric_cast_with_truncation)]13// Make the WASM binary available.14#[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};19use sp_runtime::DispatchError;20// #[cfg(any(feature = "std", test))]21// pub use sp_runtime::BuildStorage;2223use sp_runtime::{24 Permill, Perbill, Percent, create_runtime_str, generic, impl_opaque_keys,25 traits::{26 AccountIdLookup, BlakeTwo256, Block as BlockT, IdentifyAccount, Verify,27 AccountIdConversion, Zero,28 },29 transaction_validity::{TransactionSource, TransactionValidity},30 ApplyExtrinsicResult, MultiSignature, RuntimeAppPublic,31};3233use sp_std::prelude::*;3435#[cfg(feature = "std")]36use sp_version::NativeVersion;37use sp_version::RuntimeVersion;38pub use pallet_transaction_payment::{39 Multiplier, TargetedFeeAdjustment, FeeDetails, RuntimeDispatchInfo,40};41// A few exports that help ease life for downstream crates.42pub use pallet_balances::Call as BalancesCall;43pub use pallet_evm::{EnsureAddressTruncated, HashedAddressMapping, Runner};44pub use frame_support::{45 construct_runtime, match_type,46 dispatch::DispatchResult,47 PalletId, parameter_types, StorageValue, ConsensusEngineId,48 traits::{49 tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT, Everything,50 Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem, LockIdentifier,51 OnUnbalanced, Randomness, FindAuthor,52 },53 weights::{54 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},55 DispatchClass, DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,56 WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients,57 },58};59use up_data_structs::*;60// use pallet_contracts::weights::WeightInfo;61// #[cfg(any(feature = "std", test))]62use frame_system::{63 self as frame_system, EnsureRoot, EnsureSigned,64 limits::{BlockWeights, BlockLength},65};66use sp_arithmetic::{67 traits::{BaseArithmetic, Unsigned},68};69use smallvec::smallvec;70use codec::{Encode, Decode};71use pallet_evm::{Account as EVMAccount, FeeCalculator, GasWeightMapping, OnMethodCall};72use fp_rpc::TransactionStatus;73use sp_runtime::{74 traits::{BlockNumberProvider, Dispatchable, PostDispatchInfoOf, Saturating},75 transaction_validity::TransactionValidityError,76 SaturatedConversion,77};7879// pub use pallet_timestamp::Call as TimestampCall;80pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;8182// Polkadot imports83use pallet_xcm::XcmPassthrough;84use polkadot_parachain::primitives::Sibling;85use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};86use xcm_builder::{87 AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter,88 EnsureXcmOrigin, FixedWeightBounds, LocationInverter, NativeAsset, ParentAsSuperuser,89 RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia,90 SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit,91 ParentIsPreset,92};93use xcm_executor::{Config, XcmExecutor, Assets};94use sp_std::{marker::PhantomData};9596use xcm::latest::{97 // Xcm,98 AssetId::{Concrete},99 Fungibility::Fungible as XcmFungible,100 MultiAsset,101 Error as XcmError,102};103use xcm_executor::traits::{MatchesFungible, WeightTrader};104//use xcm_executor::traits::MatchesFungible;105use sp_runtime::traits::CheckedConversion;106107// mod chain_extension;108// use crate::chain_extension::{NFTExtension, Imbalance};109110/// An index to a block.111pub type BlockNumber = u32;112113/// Alias to 512-bit hash when used in the context of a transaction signature on the chain.114pub type Signature = MultiSignature;115116/// Some way of identifying an account on the chain. We intentionally make it equivalent117/// to the public key of our transaction signing scheme.118pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;119120pub type CrossAccountId = pallet_common::account::BasicCrossAccountId<Runtime>;121122/// The type for looking up accounts. We don't expect more than 4 billion of them, but you123/// never know...124pub type AccountIndex = u32;125126/// Balance of an account.127pub type Balance = u128;128129/// Index of a transaction in the chain.130pub type Index = u32;131132/// A hash of some data used by the chain.133pub type Hash = sp_core::H256;134135/// Digest item type.136pub type DigestItem = generic::DigestItem;137138/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know139/// the specifics of the runtime. They can then be made to be agnostic over specific formats140/// of data like extrinsics, allowing for them to continue syncing the network through upgrades141/// to even the core data structures.142pub mod opaque {143 use super::*;144145 pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;146147 /// Opaque block type.148 pub type Block = generic::Block<Header, UncheckedExtrinsic>;149150 pub type SessionHandlers = ();151152 impl_opaque_keys! {153 pub struct SessionKeys {154 pub aura: Aura,155 }156 }157}158159/// This runtime version.160pub const VERSION: RuntimeVersion = RuntimeVersion {161 spec_name: create_runtime_str!("quartz"),162 impl_name: create_runtime_str!("quartz"),163 authoring_version: 1,164 spec_version: 917000,165 impl_version: 0,166 apis: RUNTIME_API_VERSIONS,167 transaction_version: 1,168 state_version: 0,169};170171pub const MILLISECS_PER_BLOCK: u64 = 12000;172173pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;174175// These time units are defined in number of blocks.176pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);177pub const HOURS: BlockNumber = MINUTES * 60;178pub const DAYS: BlockNumber = HOURS * 24;179180parameter_types! {181 pub const DefaultSponsoringRateLimit: BlockNumber = 1 * DAYS;182}183184#[derive(codec::Encode, codec::Decode)]185pub enum XCMPMessage<XAccountId, XBalance> {186 /// Transfer tokens to the given account from the Parachain account.187 TransferToken(XAccountId, XBalance),188}189190/// The version information used to identify this runtime when compiled natively.191#[cfg(feature = "std")]192pub fn native_version() -> NativeVersion {193 NativeVersion {194 runtime_version: VERSION,195 can_author_with: Default::default(),196 }197}198199type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;200201pub struct DealWithFees;202impl OnUnbalanced<NegativeImbalance> for DealWithFees {203 fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {204 if let Some(fees) = fees_then_tips.next() {205 // for fees, 100% to treasury206 let mut split = fees.ration(100, 0);207 if let Some(tips) = fees_then_tips.next() {208 // for tips, if any, 100% to treasury209 tips.ration_merge_into(100, 0, &mut split);210 }211 Treasury::on_unbalanced(split.0);212 // Author::on_unbalanced(split.1);213 }214 }215}216217/// We assume that ~10% of the block weight is consumed by `on_initalize` handlers.218/// This is used to limit the maximal weight of a single extrinsic.219const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(10);220/// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used221/// by Operational extrinsics.222const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);223/// We allow for 2 seconds of compute with a 6 second average block time.224const MAXIMUM_BLOCK_WEIGHT: Weight = WEIGHT_PER_SECOND / 2;225226parameter_types! {227 pub const BlockHashCount: BlockNumber = 2400;228 pub RuntimeBlockLength: BlockLength =229 BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);230 pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);231 pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;232 pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()233 .base_block(BlockExecutionWeight::get())234 .for_class(DispatchClass::all(), |weights| {235 weights.base_extrinsic = ExtrinsicBaseWeight::get();236 })237 .for_class(DispatchClass::Normal, |weights| {238 weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);239 })240 .for_class(DispatchClass::Operational, |weights| {241 weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);242 // Operational transactions have some extra reserved space, so that they243 // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.244 weights.reserved = Some(245 MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT246 );247 })248 .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)249 .build_or_panic();250 pub const Version: RuntimeVersion = VERSION;251 pub const SS58Prefix: u8 = 42;252}253254/*2558880 - Unique2568881 - Quartz2578882 - Opal258*/259parameter_types! {260 pub const ChainId: u64 = 8881;261}262263pub struct FixedFee;264impl FeeCalculator for FixedFee {265 fn min_gas_price() -> U256 {266 // Targeting 0.15 UNQ per transfer267 1_018_751_825_264u64.into()268 }269}270271// Assuming slowest ethereum opcode is SSTORE, with gas price of 20000 as our worst case272// (contract, which only writes a lot of data),273// approximating on top of our real store write weight274parameter_types! {275 pub const WritesPerSecond: u64 = WEIGHT_PER_SECOND / <Runtime as frame_system::Config>::DbWeight::get().write;276 pub const GasPerSecond: u64 = WritesPerSecond::get() * 20000;277 pub const WeightPerGas: u64 = WEIGHT_PER_SECOND / GasPerSecond::get();278}279280/// Limiting EVM execution to 50% of block for substrate users and management tasks281/// EVM transaction consumes more weight than substrate's, so we can't rely on them being282/// scheduled fairly283const EVM_DISPATCH_RATIO: Perbill = Perbill::from_percent(50);284parameter_types! {285 pub BlockGasLimit: U256 = U256::from(NORMAL_DISPATCH_RATIO * EVM_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT / WeightPerGas::get());286}287288pub enum FixedGasWeightMapping {}289impl GasWeightMapping for FixedGasWeightMapping {290 fn gas_to_weight(gas: u64) -> Weight {291 gas.saturating_mul(WeightPerGas::get())292 }293 fn weight_to_gas(weight: Weight) -> u64 {294 weight / WeightPerGas::get()295 }296}297298impl pallet_evm::Config for Runtime {299 type BlockGasLimit = BlockGasLimit;300 type FeeCalculator = FixedFee;301 type GasWeightMapping = FixedGasWeightMapping;302 type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;303 type CallOrigin = EnsureAddressTruncated;304 type WithdrawOrigin = EnsureAddressTruncated;305 type AddressMapping = HashedAddressMapping<Self::Hashing>;306 type PrecompilesType = ();307 type PrecompilesValue = ();308 type Currency = Balances;309 type Event = Event;310 type OnMethodCall = (311 pallet_evm_migration::OnMethodCall<Self>,312 pallet_unique::UniqueErcSupport<Self>,313 pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,314 );315 type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;316 type ChainId = ChainId;317 type Runner = pallet_evm::runner::stack::Runner<Self>;318 type OnChargeTransaction = pallet_evm_transaction_payment::OnChargeTransaction<Self>;319 type TransactionValidityHack = pallet_evm_transaction_payment::TransactionValidityHack<Self>;320 type FindAuthor = EthereumFindAuthor<Aura>;321}322323impl pallet_evm_migration::Config for Runtime {324 type WeightInfo = pallet_evm_migration::weights::SubstrateWeight<Self>;325}326327pub struct EthereumFindAuthor<F>(core::marker::PhantomData<F>);328impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F> {329 fn find_author<'a, I>(digests: I) -> Option<H160>330 where331 I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,332 {333 if let Some(author_index) = F::find_author(digests) {334 let authority_id = Aura::authorities()[author_index as usize].clone();335 return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24]));336 }337 None338 }339}340341impl pallet_ethereum::Config for Runtime {342 type Event = Event;343 type StateRoot = pallet_ethereum::IntermediateStateRoot;344}345346impl pallet_randomness_collective_flip::Config for Runtime {}347348impl frame_system::Config for Runtime {349 /// The data to be stored in an account.350 type AccountData = pallet_balances::AccountData<Balance>;351 /// The identifier used to distinguish between accounts.352 type AccountId = AccountId;353 /// The basic call filter to use in dispatchable.354 type BaseCallFilter = Everything;355 /// Maximum number of block number to block hash mappings to keep (oldest pruned first).356 type BlockHashCount = BlockHashCount;357 /// The maximum length of a block (in bytes).358 type BlockLength = RuntimeBlockLength;359 /// The index type for blocks.360 type BlockNumber = BlockNumber;361 /// The weight of the overhead invoked on the block import process, independent of the extrinsics included in that block.362 type BlockWeights = RuntimeBlockWeights;363 /// The aggregated dispatch type that is available for extrinsics.364 type Call = Call;365 /// The weight of database operations that the runtime can invoke.366 type DbWeight = RocksDbWeight;367 /// The ubiquitous event type.368 type Event = Event;369 /// The type for hashing blocks and tries.370 type Hash = Hash;371 /// The hashing algorithm used.372 type Hashing = BlakeTwo256;373 /// The header type.374 type Header = generic::Header<BlockNumber, BlakeTwo256>;375 /// The index type for storing how many extrinsics an account has signed.376 type Index = Index;377 /// The lookup mechanism to get account ID from whatever is passed in dispatchers.378 type Lookup = AccountIdLookup<AccountId, ()>;379 /// What to do if an account is fully reaped from the system.380 type OnKilledAccount = ();381 /// What to do if a new account is created.382 type OnNewAccount = ();383 type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;384 /// The ubiquitous origin type.385 type Origin = Origin;386 /// This type is being generated by `construct_runtime!`.387 type PalletInfo = PalletInfo;388 /// This is used as an identifier of the chain. 42 is the generic substrate prefix.389 type SS58Prefix = SS58Prefix;390 /// Weight information for the extrinsics of this pallet.391 type SystemWeightInfo = frame_system::weights::SubstrateWeight<Self>;392 /// Version of the runtime.393 type Version = Version;394 type MaxConsumers = ConstU32<16>;395}396397parameter_types! {398 pub const MinimumPeriod: u64 = SLOT_DURATION / 2;399}400401impl pallet_timestamp::Config for Runtime {402 /// A timestamp: milliseconds since the unix epoch.403 type Moment = u64;404 type OnTimestampSet = ();405 type MinimumPeriod = MinimumPeriod;406 type WeightInfo = ();407}408409parameter_types! {410 // pub const ExistentialDeposit: u128 = 500;411 pub const ExistentialDeposit: u128 = 0;412 pub const MaxLocks: u32 = 50;413}414415impl pallet_balances::Config for Runtime {416 type MaxLocks = MaxLocks;417 type MaxReserves = ();418 type ReserveIdentifier = [u8; 8];419 /// The type for recording an account's balance.420 type Balance = Balance;421 /// The ubiquitous event type.422 type Event = Event;423 type DustRemoval = Treasury;424 type ExistentialDeposit = ExistentialDeposit;425 type AccountStore = System;426 type WeightInfo = pallet_balances::weights::SubstrateWeight<Self>;427}428429pub const MICROUNIQUE: Balance = 1_000_000_000_000;430pub const MILLIUNIQUE: Balance = 1_000 * MICROUNIQUE;431pub const CENTIUNIQUE: Balance = 10 * MILLIUNIQUE;432pub const UNIQUE: Balance = 100 * CENTIUNIQUE;433434pub const fn deposit(items: u32, bytes: u32) -> Balance {435 items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE436}437438/*439parameter_types! {440 pub TombstoneDeposit: Balance = deposit(441 1,442 sp_std::mem::size_of::<pallet_contracts::Pallet<Runtime>> as u32,443 );444 pub DepositPerContract: Balance = TombstoneDeposit::get();445 pub const DepositPerStorageByte: Balance = deposit(0, 1);446 pub const DepositPerStorageItem: Balance = deposit(1, 0);447 pub RentFraction: Perbill = Perbill::from_rational(1u32, 30 * DAYS);448 pub const SurchargeReward: Balance = 150 * MILLIUNIQUE;449 pub const SignedClaimHandicap: u32 = 2;450 pub const MaxDepth: u32 = 32;451 pub const MaxValueSize: u32 = 16 * 1024;452 pub const MaxCodeSize: u32 = 1024 * 1024 * 25; // 25 Mb453 // The lazy deletion runs inside on_initialize.454 pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO *455 RuntimeBlockWeights::get().max_block;456 // The weight needed for decoding the queue should be less or equal than a fifth457 // of the overall weight dedicated to the lazy deletion.458 pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (459 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -460 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)461 )) / 5) as u32;462 pub Schedule: pallet_contracts::Schedule<Runtime> = Default::default();463}464465impl pallet_contracts::Config for Runtime {466 type Time = Timestamp;467 type Randomness = RandomnessCollectiveFlip;468 type Currency = Balances;469 type Event = Event;470 type RentPayment = ();471 type SignedClaimHandicap = SignedClaimHandicap;472 type TombstoneDeposit = TombstoneDeposit;473 type DepositPerContract = DepositPerContract;474 type DepositPerStorageByte = DepositPerStorageByte;475 type DepositPerStorageItem = DepositPerStorageItem;476 type RentFraction = RentFraction;477 type SurchargeReward = SurchargeReward;478 type WeightPrice = pallet_transaction_payment::Pallet<Self>;479 type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;480 type ChainExtension = NFTExtension;481 type DeletionQueueDepth = DeletionQueueDepth;482 type DeletionWeightLimit = DeletionWeightLimit;483 type Schedule = Schedule;484 type CallStack = [pallet_contracts::Frame<Self>; 31];485}486*/487488parameter_types! {489 pub const TransactionByteFee: Balance = 501 * MICROUNIQUE; // Targeting 0.1 Unique per NFT transfer490 /// This value increases the priority of `Operational` transactions by adding491 /// a "virtual tip" that's equal to the `OperationalFeeMultiplier * final_fee`.492 pub const OperationalFeeMultiplier: u8 = 5;493}494495/// Linear implementor of `WeightToFeePolynomial`496pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);497498impl<T> WeightToFeePolynomial for LinearFee<T>499where500 T: BaseArithmetic + From<u32> + Copy + Unsigned,501{502 type Balance = T;503504 fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {505 smallvec!(WeightToFeeCoefficient {506 // Targeting 0.1 Unique per NFT transfer507 coeff_integer: 142_688_000u32.into(),508 coeff_frac: Perbill::zero(),509 negative: false,510 degree: 1,511 })512 }513}514515impl pallet_transaction_payment::Config for Runtime {516 type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, DealWithFees>;517 type TransactionByteFee = TransactionByteFee;518 type OperationalFeeMultiplier = OperationalFeeMultiplier;519 type WeightToFee = LinearFee<Balance>;520 type FeeMultiplierUpdate = ();521}522523parameter_types! {524 pub const ProposalBond: Permill = Permill::from_percent(5);525 pub const ProposalBondMinimum: Balance = 1 * UNIQUE;526 pub const ProposalBondMaximum: Balance = 1000 * UNIQUE;527 pub const SpendPeriod: BlockNumber = 5 * MINUTES;528 pub const Burn: Permill = Permill::from_percent(0);529 pub const TipCountdown: BlockNumber = 1 * DAYS;530 pub const TipFindersFee: Percent = Percent::from_percent(20);531 pub const TipReportDepositBase: Balance = 1 * UNIQUE;532 pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;533 pub const BountyDepositBase: Balance = 1 * UNIQUE;534 pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;535 pub const TreasuryModuleId: PalletId = PalletId(*b"py/trsry");536 pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;537 pub const MaximumReasonLength: u32 = 16384;538 pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);539 pub const BountyValueMinimum: Balance = 5 * UNIQUE;540 pub const MaxApprovals: u32 = 100;541}542543impl pallet_treasury::Config for Runtime {544 type PalletId = TreasuryModuleId;545 type Currency = Balances;546 type ApproveOrigin = EnsureRoot<AccountId>;547 type RejectOrigin = EnsureRoot<AccountId>;548 type Event = Event;549 type OnSlash = ();550 type ProposalBond = ProposalBond;551 type ProposalBondMinimum = ProposalBondMinimum;552 type ProposalBondMaximum = ProposalBondMaximum;553 type SpendPeriod = SpendPeriod;554 type Burn = Burn;555 type BurnDestination = ();556 type SpendFunds = ();557 type WeightInfo = pallet_treasury::weights::SubstrateWeight<Self>;558 type MaxApprovals = MaxApprovals;559}560561impl pallet_sudo::Config for Runtime {562 type Event = Event;563 type Call = Call;564}565566pub struct RelayChainBlockNumberProvider<T>(sp_std::marker::PhantomData<T>);567568impl<T: cumulus_pallet_parachain_system::Config> BlockNumberProvider569 for RelayChainBlockNumberProvider<T>570{571 type BlockNumber = BlockNumber;572573 fn current_block_number() -> Self::BlockNumber {574 cumulus_pallet_parachain_system::Pallet::<T>::validation_data()575 .map(|d| d.relay_parent_number)576 .unwrap_or_default()577 }578}579580parameter_types! {581 pub const MinVestedTransfer: Balance = 10 * UNIQUE;582 pub const MaxVestingSchedules: u32 = 28;583}584585impl orml_vesting::Config for Runtime {586 type Event = Event;587 type Currency = pallet_balances::Pallet<Runtime>;588 type MinVestedTransfer = MinVestedTransfer;589 type VestedTransferOrigin = EnsureSigned<AccountId>;590 type WeightInfo = ();591 type MaxVestingSchedules = MaxVestingSchedules;592 type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;593}594595parameter_types! {596 pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;597 pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;598}599600impl cumulus_pallet_parachain_system::Config for Runtime {601 type Event = Event;602 type SelfParaId = parachain_info::Pallet<Self>;603 type OnSystemEvent = ();604 // type DownwardMessageHandlers = cumulus_primitives_utility::UnqueuedDmpAsParent<605 // MaxDownwardMessageWeight,606 // XcmExecutor<XcmConfig>,607 // Call,608 // >;609 type OutboundXcmpMessageSource = XcmpQueue;610 type DmpMessageHandler = DmpQueue;611 type ReservedDmpWeight = ReservedDmpWeight;612 type ReservedXcmpWeight = ReservedXcmpWeight;613 type XcmpMessageHandler = XcmpQueue;614}615616impl parachain_info::Config for Runtime {}617618impl cumulus_pallet_aura_ext::Config for Runtime {}619620parameter_types! {621 pub const RelayLocation: MultiLocation = MultiLocation::parent();622 pub const RelayNetwork: NetworkId = NetworkId::Polkadot;623 pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();624 pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();625}626627/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used628/// when determining ownership of accounts for asset transacting and when attempting to use XCM629/// `Transact` in order to determine the dispatch Origin.630pub type LocationToAccountId = (631 // The parent (Relay-chain) origin converts to the default `AccountId`.632 ParentIsPreset<AccountId>,633 // Sibling parachain origins convert to AccountId via the `ParaId::into`.634 SiblingParachainConvertsVia<Sibling, AccountId>,635 // Straight up local `AccountId32` origins just alias directly to `AccountId`.636 AccountId32Aliases<RelayNetwork, AccountId>,637);638639pub struct OnlySelfCurrency;640impl<B: TryFrom<u128>> MatchesFungible<B> for OnlySelfCurrency {641 fn matches_fungible(a: &MultiAsset) -> Option<B> {642 match (&a.id, &a.fun) {643 (Concrete(_), XcmFungible(ref amount)) => CheckedConversion::checked_from(*amount),644 _ => None,645 }646 }647}648649/// Means for transacting assets on this chain.650pub type LocalAssetTransactor = CurrencyAdapter<651 // Use this currency:652 Balances,653 // Use this currency when it is a fungible asset matching the given location or name:654 OnlySelfCurrency,655 // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:656 LocationToAccountId,657 // Our chain's account ID type (we can't get away without mentioning it explicitly):658 AccountId,659 // We don't track any teleports.660 (),661>;662663/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,664/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can665/// biases the kind of local `Origin` it will become.666pub type XcmOriginToTransactDispatchOrigin = (667 // Sovereign account converter; this attempts to derive an `AccountId` from the origin location668 // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for669 // foreign chains who want to have a local sovereign account on this chain which they control.670 SovereignSignedViaLocation<LocationToAccountId, Origin>,671 // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when672 // recognised.673 RelayChainAsNative<RelayOrigin, Origin>,674 // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when675 // recognised.676 SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,677 // Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a678 // transaction from the Root origin.679 ParentAsSuperuser<Origin>,680 // Native signed account converter; this just converts an `AccountId32` origin into a normal681 // `Origin::Signed` origin of the same 32-byte value.682 SignedAccountId32AsNative<RelayNetwork, Origin>,683 // Xcm origins can be represented natively under the Xcm pallet's Xcm origin.684 XcmPassthrough<Origin>,685);686687parameter_types! {688 // One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.689 pub UnitWeightCost: Weight = 1_000_000;690 // 1200 UNIQUEs buy 1 second of weight.691 pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);692 pub const MaxInstructions: u32 = 100;693 pub const MaxAuthorities: u32 = 100_000;694}695696match_type! {697 pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {698 MultiLocation { parents: 1, interior: Here } |699 MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }700 };701}702703pub type Barrier = (704 TakeWeightCredit,705 AllowTopLevelPaidExecutionFrom<Everything>,706 AllowUnpaidExecutionFrom<ParentOrParentsUnitPlurality>,707 // ^^^ Parent & its unit plurality gets free execution708);709710pub struct UsingOnlySelfCurrencyComponents<711 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,712 AssetId: Get<MultiLocation>,713 AccountId,714 Currency: CurrencyT<AccountId>,715 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,716>(717 Weight,718 Currency::Balance,719 PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>,720);721impl<722 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,723 AssetId: Get<MultiLocation>,724 AccountId,725 Currency: CurrencyT<AccountId>,726 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,727 > WeightTrader728 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>729{730 fn new() -> Self {731 Self(0, Zero::zero(), PhantomData)732 }733734 fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {735 let amount = WeightToFee::calc(&weight);736 let u128_amount: u128 = amount.try_into().map_err(|_| XcmError::Overflow)?;737738 // location to this parachain through relay chain739 let option1: xcm::v1::AssetId = Concrete(MultiLocation {740 parents: 1,741 interior: X1(Parachain(ParachainInfo::parachain_id().into())),742 });743 // direct location744 let option2: xcm::v1::AssetId = Concrete(MultiLocation {745 parents: 0,746 interior: Here,747 });748749 let required = if payment.fungible.contains_key(&option1) {750 (option1, u128_amount).into()751 } else if payment.fungible.contains_key(&option2) {752 (option2, u128_amount).into()753 } else {754 (Concrete(MultiLocation::default()), u128_amount).into()755 };756757 let unused = payment758 .checked_sub(required)759 .map_err(|_| XcmError::TooExpensive)?;760 self.0 = self.0.saturating_add(weight);761 self.1 = self.1.saturating_add(amount);762 Ok(unused)763 }764765 fn refund_weight(&mut self, weight: Weight) -> Option<MultiAsset> {766 let weight = weight.min(self.0);767 let amount = WeightToFee::calc(&weight);768 self.0 -= weight;769 self.1 = self.1.saturating_sub(amount);770 let amount: u128 = amount.saturated_into();771 if amount > 0 {772 Some((AssetId::get(), amount).into())773 } else {774 None775 }776 }777}778impl<779 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,780 AssetId: Get<MultiLocation>,781 AccountId,782 Currency: CurrencyT<AccountId>,783 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,784 > Drop785 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>786{787 fn drop(&mut self) {788 OnUnbalanced::on_unbalanced(Currency::issue(self.1));789 }790}791792pub struct XcmConfig;793impl Config for XcmConfig {794 type Call = Call;795 type XcmSender = XcmRouter;796 // How to withdraw and deposit an asset.797 type AssetTransactor = LocalAssetTransactor;798 type OriginConverter = XcmOriginToTransactDispatchOrigin;799 type IsReserve = NativeAsset;800 type IsTeleporter = (); // Teleportation is disabled801 type LocationInverter = LocationInverter<Ancestry>;802 type Barrier = Barrier;803 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;804 type Trader = UsingOnlySelfCurrencyComponents<805 IdentityFee<Balance>,806 RelayLocation,807 AccountId,808 Balances,809 (),810 >;811 type ResponseHandler = (); // Don't handle responses for now.812 type SubscriptionService = PolkadotXcm;813814 type AssetTrap = PolkadotXcm;815 type AssetClaims = PolkadotXcm;816}817818// parameter_types! {819// pub const MaxDownwardMessageWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 10;820// }821822/// No local origins on this chain are allowed to dispatch XCM sends/executions.823pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);824825/// The means for routing XCM messages which are not for local execution into the right message826/// queues.827pub type XcmRouter = (828 // Two routers - use UMP to communicate with the relay chain:829 cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,830 // ..and XCMP to communicate with the sibling chains.831 XcmpQueue,832);833834impl pallet_evm_coder_substrate::Config for Runtime {835 type EthereumTransactionSender = pallet_ethereum::Pallet<Self>;836 type GasWeightMapping = FixedGasWeightMapping;837}838839impl pallet_xcm::Config for Runtime {840 type Event = Event;841 type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;842 type XcmRouter = XcmRouter;843 type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;844 type XcmExecuteFilter = Everything;845 type XcmExecutor = XcmExecutor<XcmConfig>;846 type XcmTeleportFilter = Everything;847 type XcmReserveTransferFilter = Everything;848 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;849 type LocationInverter = LocationInverter<Ancestry>;850 type Origin = Origin;851 type Call = Call;852 const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;853 type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;854}855856impl cumulus_pallet_xcm::Config for Runtime {857 type Event = Event;858 type XcmExecutor = XcmExecutor<XcmConfig>;859}860861impl cumulus_pallet_xcmp_queue::Config for Runtime {862 type Event = Event;863 type XcmExecutor = XcmExecutor<XcmConfig>;864 type ChannelInfo = ParachainSystem;865 type VersionWrapper = ();866 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;867 type ControllerOrigin = EnsureRoot<AccountId>;868 type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;869}870871impl cumulus_pallet_dmp_queue::Config for Runtime {872 type Event = Event;873 type XcmExecutor = XcmExecutor<XcmConfig>;874 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;875}876877impl pallet_aura::Config for Runtime {878 type AuthorityId = AuraId;879 type DisabledValidators = ();880 type MaxAuthorities = MaxAuthorities;881}882883parameter_types! {884 pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();885 pub const CollectionCreationPrice: Balance = 2 * UNIQUE;886}887888impl pallet_common::Config for Runtime {889 type Event = Event;890 type EvmBackwardsAddressMapping = up_evm_mapping::MapBackwardsAddressTruncated;891 type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;892 type CrossAccountId = pallet_common::account::BasicCrossAccountId<Self>;893894 type Currency = Balances;895 type CollectionCreationPrice = CollectionCreationPrice;896 type TreasuryAccountId = TreasuryAccountId;897}898899impl pallet_fungible::Config for Runtime {900 type WeightInfo = pallet_fungible::weights::SubstrateWeight<Self>;901}902impl pallet_refungible::Config for Runtime {903 type WeightInfo = pallet_refungible::weights::SubstrateWeight<Self>;904}905impl pallet_nonfungible::Config for Runtime {906 type WeightInfo = pallet_nonfungible::weights::SubstrateWeight<Self>;907}908909impl pallet_unique::Config for Runtime {910 type Event = Event;911 type WeightInfo = pallet_unique::weights::SubstrateWeight<Self>;912}913914parameter_types! {915 pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied916}917918/// Used for the pallet inflation919impl pallet_inflation::Config for Runtime {920 type Currency = Balances;921 type TreasuryAccountId = TreasuryAccountId;922 type InflationBlockInterval = InflationBlockInterval;923 type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;924}925926// parameter_types! {927// pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *928// RuntimeBlockWeights::get().max_block;929// pub const MaxScheduledPerBlock: u32 = 50;930// }931932type EvmSponsorshipHandler = (933 pallet_unique::UniqueEthSponsorshipHandler<Runtime>,934 pallet_evm_contract_helpers::HelpersContractSponsoring<Runtime>,935);936type SponsorshipHandler = (937 pallet_unique::UniqueSponsorshipHandler<Runtime>,938 //pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,939 pallet_evm_transaction_payment::BridgeSponsorshipHandler<Runtime>,940);941942// impl pallet_unq_scheduler::Config for Runtime {943// type Event = Event;944// type Origin = Origin;945// type PalletsOrigin = OriginCaller;946// type Call = Call;947// type MaximumWeight = MaximumSchedulerWeight;948// type ScheduleOrigin = EnsureSigned<AccountId>;949// type MaxScheduledPerBlock = MaxScheduledPerBlock;950// type SponsorshipHandler = SponsorshipHandler;951// type WeightInfo = ();952// }953954impl pallet_evm_transaction_payment::Config for Runtime {955 type EvmSponsorshipHandler = EvmSponsorshipHandler;956 type Currency = Balances;957 type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;958 type EvmBackwardsAddressMapping = up_evm_mapping::MapBackwardsAddressTruncated;959}960961impl pallet_charge_transaction::Config for Runtime {962 type SponsorshipHandler = SponsorshipHandler;963}964965// impl pallet_contract_helpers::Config for Runtime {966// type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;967// }968969parameter_types! {970 // 0x842899ECF380553E8a4de75bF534cdf6fBF64049971 pub const HelpersContractAddress: H160 = H160([972 0x84, 0x28, 0x99, 0xec, 0xf3, 0x80, 0x55, 0x3e, 0x8a, 0x4d, 0xe7, 0x5b, 0xf5, 0x34, 0xcd, 0xf6, 0xfb, 0xf6, 0x40, 0x49,973 ]);974}975976impl pallet_evm_contract_helpers::Config for Runtime {977 type ContractAddress = HelpersContractAddress;978 type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;979}980981construct_runtime!(982 pub enum Runtime where983 Block = Block,984 NodeBlock = opaque::Block,985 UncheckedExtrinsic = UncheckedExtrinsic986 {987 ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Config, Storage, Inherent, Event<T>, ValidateUnsigned} = 20,988 ParachainInfo: parachain_info::{Pallet, Storage, Config} = 21,989990 Aura: pallet_aura::{Pallet, Config<T>} = 22,991 AuraExt: cumulus_pallet_aura_ext::{Pallet, Config} = 23,992993 Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 30,994 RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage} = 31,995 Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 32,996 TransactionPayment: pallet_transaction_payment::{Pallet, Storage} = 33,997 Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event<T>} = 34,998 Sudo: pallet_sudo::{Pallet, Call, Storage, Config<T>, Event<T>} = 35,999 System: frame_system::{Pallet, Call, Storage, Config, Event<T>} = 36,1000 Vesting: orml_vesting::{Pallet, Storage, Call, Event<T>, Config<T>} = 37,1001 // Vesting: pallet_vesting::{Pallet, Call, Config<T>, Storage, Event<T>} = 37,1002 // Contracts: pallet_contracts::{Pallet, Call, Storage, Event<T>} = 38,10031004 // XCM helpers.1005 XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 50,1006 PolkadotXcm: pallet_xcm::{Pallet, Call, Event<T>, Origin} = 51,1007 CumulusXcm: cumulus_pallet_xcm::{Pallet, Call, Event<T>, Origin} = 52,1008 DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,10091010 // Unique Pallets1011 Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,1012 Unique: pallet_unique::{Pallet, Call, Storage, Event<T>} = 61,1013 // Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,1014 // free = 631015 Charging: pallet_charge_transaction::{Pallet, Call, Storage } = 64,1016 // ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,1017 Common: pallet_common::{Pallet, Storage, Event<T>} = 66,1018 Fungible: pallet_fungible::{Pallet, Storage} = 67,1019 Refungible: pallet_refungible::{Pallet, Storage} = 68,1020 Nonfungible: pallet_nonfungible::{Pallet, Storage} = 69,10211022 // Frontier1023 EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,1024 Ethereum: pallet_ethereum::{Pallet, Config, Call, Storage, Event, Origin} = 101,10251026 EvmCoderSubstrate: pallet_evm_coder_substrate::{Pallet, Storage} = 150,1027 EvmContractHelpers: pallet_evm_contract_helpers::{Pallet, Storage} = 151,1028 EvmTransactionPayment: pallet_evm_transaction_payment::{Pallet} = 152,1029 EvmMigration: pallet_evm_migration::{Pallet, Call, Storage} = 153,1030 }1031);10321033pub struct TransactionConverter;10341035impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {1036 fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {1037 UncheckedExtrinsic::new_unsigned(1038 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1039 )1040 }1041}10421043impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {1044 fn convert_transaction(1045 &self,1046 transaction: pallet_ethereum::Transaction,1047 ) -> opaque::UncheckedExtrinsic {1048 let extrinsic = UncheckedExtrinsic::new_unsigned(1049 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1050 );1051 let encoded = extrinsic.encode();1052 opaque::UncheckedExtrinsic::decode(&mut &encoded[..])1053 .expect("Encoded extrinsic is always valid")1054 }1055}10561057/// The address format for describing accounts.1058pub type Address = sp_runtime::MultiAddress<AccountId, ()>;1059/// Block header type as expected by this runtime.1060pub type Header = generic::Header<BlockNumber, BlakeTwo256>;1061/// Block type as expected by this runtime.1062pub type Block = generic::Block<Header, UncheckedExtrinsic>;1063/// A Block signed with a Justification1064pub type SignedBlock = generic::SignedBlock<Block>;1065/// BlockId type as expected by this runtime.1066pub type BlockId = generic::BlockId<Block>;1067/// The SignedExtension to the basic transaction logic.1068pub type SignedExtra = (1069 frame_system::CheckSpecVersion<Runtime>,1070 // system::CheckTxVersion<Runtime>,1071 frame_system::CheckGenesis<Runtime>,1072 frame_system::CheckEra<Runtime>,1073 frame_system::CheckNonce<Runtime>,1074 frame_system::CheckWeight<Runtime>,1075 pallet_charge_transaction::ChargeTransactionPayment<Runtime>,1076 //pallet_contract_helpers::ContractHelpersExtension<Runtime>,1077);1078/// Unchecked extrinsic type as expected by this runtime.1079pub type UncheckedExtrinsic =1080 fp_self_contained::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;1081/// Extrinsic type that has already been checked.1082pub type CheckedExtrinsic = fp_self_contained::CheckedExtrinsic<AccountId, Call, SignedExtra, H160>;1083/// Executive: handles dispatch to the various modules.1084pub type Executive = frame_executive::Executive<1085 Runtime,1086 Block,1087 frame_system::ChainContext<Runtime>,1088 Runtime,1089 AllPalletsReversedWithSystemFirst,1090>;10911092impl_opaque_keys! {1093 pub struct SessionKeys {1094 pub aura: Aura,1095 }1096}10971098impl fp_self_contained::SelfContainedCall for Call {1099 type SignedInfo = H160;11001101 fn is_self_contained(&self) -> bool {1102 match self {1103 Call::Ethereum(call) => call.is_self_contained(),1104 _ => false,1105 }1106 }11071108 fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {1109 match self {1110 Call::Ethereum(call) => call.check_self_contained(),1111 _ => None,1112 }1113 }11141115 fn validate_self_contained(&self, info: &Self::SignedInfo) -> Option<TransactionValidity> {1116 match self {1117 Call::Ethereum(call) => call.validate_self_contained(info),1118 _ => None,1119 }1120 }11211122 fn pre_dispatch_self_contained(1123 &self,1124 info: &Self::SignedInfo,1125 ) -> Option<Result<(), TransactionValidityError>> {1126 match self {1127 Call::Ethereum(call) => call.pre_dispatch_self_contained(info),1128 _ => None,1129 }1130 }11311132 fn apply_self_contained(1133 self,1134 info: Self::SignedInfo,1135 ) -> Option<sp_runtime::DispatchResultWithInfo<PostDispatchInfoOf<Self>>> {1136 match self {1137 call @ Call::Ethereum(pallet_ethereum::Call::transact { .. }) => Some(call.dispatch(1138 Origin::from(pallet_ethereum::RawOrigin::EthereumTransaction(info)),1139 )),1140 _ => None,1141 }1142 }1143}11441145macro_rules! dispatch_unique_runtime {1146 ($collection:ident.$method:ident($($name:ident),*)) => {{1147 use pallet_unique::dispatch::Dispatched;11481149 let collection = Dispatched::dispatch(<pallet_common::CollectionHandle<Runtime>>::try_get($collection)?);1150 let dispatch = collection.as_dyn();11511152 Ok(dispatch.$method($($name),*))1153 }};1154}1155impl_runtime_apis! {1156 impl up_rpc::UniqueApi<Block, CrossAccountId, AccountId>1157 for Runtime1158 {1159 fn account_tokens(collection: CollectionId, account: CrossAccountId) -> Result<Vec<TokenId>, DispatchError> {1160 dispatch_unique_runtime!(collection.account_tokens(account))1161 }1162 fn token_exists(collection: CollectionId, token: TokenId) -> Result<bool, DispatchError> {1163 dispatch_unique_runtime!(collection.token_exists(token))1164 }11651166 fn token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>, DispatchError> {1167 dispatch_unique_runtime!(collection.token_owner(token))1168 }1169 fn const_metadata(collection: CollectionId, token: TokenId) -> Result<Vec<u8>, DispatchError> {1170 dispatch_unique_runtime!(collection.const_metadata(token))1171 }1172 fn variable_metadata(collection: CollectionId, token: TokenId) -> Result<Vec<u8>, DispatchError> {1173 dispatch_unique_runtime!(collection.variable_metadata(token))1174 }11751176 fn collection_tokens(collection: CollectionId) -> Result<u32, DispatchError> {1177 dispatch_unique_runtime!(collection.collection_tokens())1178 }1179 fn account_balance(collection: CollectionId, account: CrossAccountId) -> Result<u32, DispatchError> {1180 dispatch_unique_runtime!(collection.account_balance(account))1181 }1182 fn balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<u128, DispatchError> {1183 dispatch_unique_runtime!(collection.balance(account, token))1184 }1185 fn allowance(1186 collection: CollectionId,1187 sender: CrossAccountId,1188 spender: CrossAccountId,1189 token: TokenId,1190 ) -> Result<u128, DispatchError> {1191 dispatch_unique_runtime!(collection.allowance(sender, spender, token))1192 }11931194 fn eth_contract_code(account: H160) -> Option<Vec<u8>> {1195 <pallet_unique::UniqueErcSupport<Runtime>>::get_code(&account)1196 .or_else(|| <pallet_evm_migration::OnMethodCall<Runtime>>::get_code(&account))1197 .or_else(|| <pallet_evm_contract_helpers::HelpersOnMethodCall<Self>>::get_code(&account))1198 }1199 fn adminlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {1200 Ok(<pallet_common::Pallet<Runtime>>::adminlist(collection))1201 }1202 fn allowlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {1203 Ok(<pallet_common::Pallet<Runtime>>::allowlist(collection))1204 }1205 fn allowed(collection: CollectionId, user: CrossAccountId) -> Result<bool, DispatchError> {1206 Ok(<pallet_common::Pallet<Runtime>>::allowed(collection, user))1207 }1208 fn last_token_id(collection: CollectionId) -> Result<TokenId, DispatchError> {1209 dispatch_unique_runtime!(collection.last_token_id())1210 }1211 fn collection_by_id(collection: CollectionId) -> Result<Option<Collection<AccountId>>, DispatchError> {1212 Ok(<pallet_common::CollectionById<Runtime>>::get(collection))1213 }1214 fn collection_stats() -> Result<CollectionStats, DispatchError> {1215 Ok(<pallet_common::Pallet<Runtime>>::collection_stats())1216 }1217 }12181219 impl sp_api::Core<Block> for Runtime {1220 fn version() -> RuntimeVersion {1221 VERSION1222 }12231224 fn execute_block(block: Block) {1225 Executive::execute_block(block)1226 }12271228 fn initialize_block(header: &<Block as BlockT>::Header) {1229 Executive::initialize_block(header)1230 }1231 }12321233 impl sp_api::Metadata<Block> for Runtime {1234 fn metadata() -> OpaqueMetadata {1235 OpaqueMetadata::new(Runtime::metadata().into())1236 }1237 }12381239 impl sp_block_builder::BlockBuilder<Block> for Runtime {1240 fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {1241 Executive::apply_extrinsic(extrinsic)1242 }12431244 fn finalize_block() -> <Block as BlockT>::Header {1245 Executive::finalize_block()1246 }12471248 fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {1249 data.create_extrinsics()1250 }12511252 fn check_inherents(1253 block: Block,1254 data: sp_inherents::InherentData,1255 ) -> sp_inherents::CheckInherentsResult {1256 data.check_extrinsics(&block)1257 }12581259 // fn random_seed() -> <Block as BlockT>::Hash {1260 // RandomnessCollectiveFlip::random_seed().01261 // }1262 }12631264 impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {1265 fn validate_transaction(1266 source: TransactionSource,1267 tx: <Block as BlockT>::Extrinsic,1268 hash: <Block as BlockT>::Hash,1269 ) -> TransactionValidity {1270 Executive::validate_transaction(source, tx, hash)1271 }1272 }12731274 impl sp_offchain::OffchainWorkerApi<Block> for Runtime {1275 fn offchain_worker(header: &<Block as BlockT>::Header) {1276 Executive::offchain_worker(header)1277 }1278 }12791280 impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {1281 fn chain_id() -> u64 {1282 <Runtime as pallet_evm::Config>::ChainId::get()1283 }12841285 fn account_basic(address: H160) -> EVMAccount {1286 EVM::account_basic(&address)1287 }12881289 fn gas_price() -> U256 {1290 <Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price()1291 }12921293 fn account_code_at(address: H160) -> Vec<u8> {1294 EVM::account_codes(address)1295 }12961297 fn author() -> H160 {1298 <pallet_evm::Pallet<Runtime>>::find_author()1299 }13001301 fn storage_at(address: H160, index: U256) -> H256 {1302 let mut tmp = [0u8; 32];1303 index.to_big_endian(&mut tmp);1304 EVM::account_storages(address, H256::from_slice(&tmp[..]))1305 }13061307 #[allow(clippy::redundant_closure)]1308 fn call(1309 from: H160,1310 to: H160,1311 data: Vec<u8>,1312 value: U256,1313 gas_limit: U256,1314 max_fee_per_gas: Option<U256>,1315 max_priority_fee_per_gas: Option<U256>,1316 nonce: Option<U256>,1317 estimate: bool,1318 access_list: Option<Vec<(H160, Vec<H256>)>>,1319 ) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {1320 let config = if estimate {1321 let mut config = <Runtime as pallet_evm::Config>::config().clone();1322 config.estimate = true;1323 Some(config)1324 } else {1325 None1326 };13271328 <Runtime as pallet_evm::Config>::Runner::call(1329 from,1330 to,1331 data,1332 value,1333 gas_limit.low_u64(),1334 max_fee_per_gas,1335 max_priority_fee_per_gas,1336 nonce,1337 access_list.unwrap_or_default(),1338 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),1339 ).map_err(|err| err.into())1340 }13411342 #[allow(clippy::redundant_closure)]1343 fn create(1344 from: H160,1345 data: Vec<u8>,1346 value: U256,1347 gas_limit: U256,1348 max_fee_per_gas: Option<U256>,1349 max_priority_fee_per_gas: Option<U256>,1350 nonce: Option<U256>,1351 estimate: bool,1352 access_list: Option<Vec<(H160, Vec<H256>)>>,1353 ) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {1354 let config = if estimate {1355 let mut config = <Runtime as pallet_evm::Config>::config().clone();1356 config.estimate = true;1357 Some(config)1358 } else {1359 None1360 };13611362 <Runtime as pallet_evm::Config>::Runner::create(1363 from,1364 data,1365 value,1366 gas_limit.low_u64(),1367 max_fee_per_gas,1368 max_priority_fee_per_gas,1369 nonce,1370 access_list.unwrap_or_default(),1371 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),1372 ).map_err(|err| err.into())1373 }13741375 fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {1376 Ethereum::current_transaction_statuses()1377 }13781379 fn current_block() -> Option<pallet_ethereum::Block> {1380 Ethereum::current_block()1381 }13821383 fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {1384 Ethereum::current_receipts()1385 }13861387 fn current_all() -> (1388 Option<pallet_ethereum::Block>,1389 Option<Vec<pallet_ethereum::Receipt>>,1390 Option<Vec<TransactionStatus>>1391 ) {1392 (1393 Ethereum::current_block(),1394 Ethereum::current_receipts(),1395 Ethereum::current_transaction_statuses()1396 )1397 }13981399 fn extrinsic_filter(xts: Vec<<Block as sp_api::BlockT>::Extrinsic>) -> Vec<pallet_ethereum::Transaction> {1400 xts.into_iter().filter_map(|xt| match xt.0.function {1401 Call::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction),1402 _ => None1403 }).collect()1404 }14051406 fn elasticity() -> Option<Permill> {1407 None1408 }1409 }14101411 impl sp_session::SessionKeys<Block> for Runtime {1412 fn decode_session_keys(1413 encoded: Vec<u8>,1414 ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {1415 SessionKeys::decode_into_raw_public_keys(&encoded)1416 }14171418 fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {1419 SessionKeys::generate(seed)1420 }1421 }14221423 impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {1424 fn slot_duration() -> sp_consensus_aura::SlotDuration {1425 sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())1426 }14271428 fn authorities() -> Vec<AuraId> {1429 Aura::authorities().to_vec()1430 }1431 }14321433 impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {1434 fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {1435 ParachainSystem::collect_collation_info(header)1436 }1437 }14381439 impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {1440 fn account_nonce(account: AccountId) -> Index {1441 System::account_nonce(account)1442 }1443 }14441445 impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {1446 fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {1447 TransactionPayment::query_info(uxt, len)1448 }1449 fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {1450 TransactionPayment::query_fee_details(uxt, len)1451 }1452 }14531454 /*1455 impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber, Hash>1456 for Runtime1457 {1458 fn call(1459 origin: AccountId,1460 dest: AccountId,1461 value: Balance,1462 gas_limit: u64,1463 input_data: Vec<u8>,1464 ) -> pallet_contracts_primitives::ContractExecResult {1465 Contracts::bare_call(origin, dest, value, gas_limit, input_data, false)1466 }14671468 fn instantiate(1469 origin: AccountId,1470 endowment: Balance,1471 gas_limit: u64,1472 code: pallet_contracts_primitives::Code<Hash>,1473 data: Vec<u8>,1474 salt: Vec<u8>,1475 ) -> pallet_contracts_primitives::ContractInstantiateResult<AccountId, BlockNumber>1476 {1477 Contracts::bare_instantiate(origin, endowment, gas_limit, code, data, salt, true, false)1478 }14791480 fn get_storage(1481 address: AccountId,1482 key: [u8; 32],1483 ) -> pallet_contracts_primitives::GetStorageResult {1484 Contracts::get_storage(address, key)1485 }14861487 fn rent_projection(1488 address: AccountId,1489 ) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {1490 Contracts::rent_projection(address)1491 }1492 }1493 */14941495 #[cfg(feature = "runtime-benchmarks")]1496 impl frame_benchmarking::Benchmark<Block> for Runtime {1497 fn benchmark_metadata(extra: bool) -> (1498 Vec<frame_benchmarking::BenchmarkList>,1499 Vec<frame_support::traits::StorageInfo>,1500 ) {1501 use frame_benchmarking::{list_benchmark, Benchmarking, BenchmarkList};1502 use frame_support::traits::StorageInfoTrait;15031504 let mut list = Vec::<BenchmarkList>::new();15051506 list_benchmark!(list, extra, pallet_evm_migration, EvmMigration);1507 list_benchmark!(list, extra, pallet_unique, Unique);1508 list_benchmark!(list, extra, pallet_inflation, Inflation);1509 list_benchmark!(list, extra, pallet_fungible, Fungible);1510 list_benchmark!(list, extra, pallet_refungible, Refungible);1511 list_benchmark!(list, extra, pallet_nonfungible, Nonfungible);1512 // list_benchmark!(list, extra, pallet_evm_coder_substrate, EvmCoderSubstrate);15131514 let storage_info = AllPalletsReversedWithSystemFirst::storage_info();15151516 return (list, storage_info)1517 }15181519 fn dispatch_benchmark(1520 config: frame_benchmarking::BenchmarkConfig1521 ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {1522 use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};15231524 let allowlist: Vec<TrackedStorageKey> = vec![1525 // Block Number1526 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),1527 // Total Issuance1528 hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),1529 // Execution Phase1530 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),1531 // Event Count1532 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),1533 // System Events1534 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),1535 ];15361537 let mut batches = Vec::<BenchmarkBatch>::new();1538 let params = (&config, &allowlist);15391540 add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);1541 add_benchmark!(params, batches, pallet_unique, Unique);1542 add_benchmark!(params, batches, pallet_inflation, Inflation);1543 add_benchmark!(params, batches, pallet_fungible, Fungible);1544 add_benchmark!(params, batches, pallet_refungible, Refungible);1545 add_benchmark!(params, batches, pallet_nonfungible, Nonfungible);1546 // add_benchmark!(params, batches, pallet_evm_coder_substrate, EvmCoderSubstrate);15471548 if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }1549 Ok(batches)1550 }1551 }1552}15531554struct CheckInherents;15551556impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {1557 fn check_inherents(1558 block: &Block,1559 relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,1560 ) -> sp_inherents::CheckInherentsResult {1561 let relay_chain_slot = relay_state_proof1562 .read_slot()1563 .expect("Could not read the relay chain slot from the proof");15641565 let inherent_data =1566 cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(1567 relay_chain_slot,1568 sp_std::time::Duration::from_secs(6),1569 )1570 .create_inherent_data()1571 .expect("Could not create the timestamp inherent data");15721573 inherent_data.check_extrinsics(block)1574 }1575}15761577cumulus_pallet_parachain_system::register_validate_block!(1578 Runtime = Runtime,1579 BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,1580 CheckInherents = CheckInherents,1581);1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56//! The Substrate Node Template runtime. This can be compiled with `#[no_std]`, ready for Wasm.78#![cfg_attr(not(feature = "std"), no_std)]9// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.10#![recursion_limit = "1024"]11#![allow(clippy::from_over_into, clippy::identity_op)]12#![allow(clippy::fn_to_numeric_cast_with_truncation)]13// Make the WASM binary available.14#[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};19use sp_runtime::DispatchError;20// #[cfg(any(feature = "std", test))]21// pub use sp_runtime::BuildStorage;2223use sp_runtime::{24 Permill, Perbill, Percent, create_runtime_str, generic, impl_opaque_keys,25 traits::{26 AccountIdLookup, BlakeTwo256, Block as BlockT, IdentifyAccount, Verify,27 AccountIdConversion, Zero,28 },29 transaction_validity::{TransactionSource, TransactionValidity},30 ApplyExtrinsicResult, MultiSignature, RuntimeAppPublic,31};3233use sp_std::prelude::*;3435#[cfg(feature = "std")]36use sp_version::NativeVersion;37use sp_version::RuntimeVersion;38pub use pallet_transaction_payment::{39 Multiplier, TargetedFeeAdjustment, FeeDetails, RuntimeDispatchInfo,40};41// A few exports that help ease life for downstream crates.42pub use pallet_balances::Call as BalancesCall;43pub use pallet_evm::{EnsureAddressTruncated, HashedAddressMapping, Runner};44pub use frame_support::{45 construct_runtime, match_type,46 dispatch::DispatchResult,47 PalletId, parameter_types, StorageValue, ConsensusEngineId,48 traits::{49 tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT, Everything,50 Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem, LockIdentifier,51 OnUnbalanced, Randomness, FindAuthor,52 },53 weights::{54 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},55 DispatchClass, DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,56 WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients,57 },58};59use up_data_structs::*;60// use pallet_contracts::weights::WeightInfo;61// #[cfg(any(feature = "std", test))]62use frame_system::{63 self as frame_system, EnsureRoot, EnsureSigned,64 limits::{BlockWeights, BlockLength},65};66use sp_arithmetic::{67 traits::{BaseArithmetic, Unsigned},68};69use smallvec::smallvec;70use codec::{Encode, Decode};71use pallet_evm::{Account as EVMAccount, FeeCalculator, GasWeightMapping, OnMethodCall};72use fp_rpc::TransactionStatus;73use sp_runtime::{74 traits::{BlockNumberProvider, Dispatchable, PostDispatchInfoOf, Saturating},75 transaction_validity::TransactionValidityError,76 SaturatedConversion,77};7879// pub use pallet_timestamp::Call as TimestampCall;80pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;8182// Polkadot imports83use pallet_xcm::XcmPassthrough;84use polkadot_parachain::primitives::Sibling;85use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};86use xcm_builder::{87 AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter,88 EnsureXcmOrigin, FixedWeightBounds, LocationInverter, NativeAsset, ParentAsSuperuser,89 RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia,90 SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit,91 ParentIsPreset,92};93use xcm_executor::{Config, XcmExecutor, Assets};94use sp_std::{marker::PhantomData};9596use xcm::latest::{97 // Xcm,98 AssetId::{Concrete},99 Fungibility::Fungible as XcmFungible,100 MultiAsset,101 Error as XcmError,102};103use xcm_executor::traits::{MatchesFungible, WeightTrader};104//use xcm_executor::traits::MatchesFungible;105use sp_runtime::traits::CheckedConversion;106107// mod chain_extension;108// use crate::chain_extension::{NFTExtension, Imbalance};109110/// An index to a block.111pub type BlockNumber = u32;112113/// Alias to 512-bit hash when used in the context of a transaction signature on the chain.114pub type Signature = MultiSignature;115116/// Some way of identifying an account on the chain. We intentionally make it equivalent117/// to the public key of our transaction signing scheme.118pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;119120pub type CrossAccountId = pallet_common::account::BasicCrossAccountId<Runtime>;121122/// The type for looking up accounts. We don't expect more than 4 billion of them, but you123/// never know...124pub type AccountIndex = u32;125126/// Balance of an account.127pub type Balance = u128;128129/// Index of a transaction in the chain.130pub type Index = u32;131132/// A hash of some data used by the chain.133pub type Hash = sp_core::H256;134135/// Digest item type.136pub type DigestItem = generic::DigestItem;137138/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know139/// the specifics of the runtime. They can then be made to be agnostic over specific formats140/// of data like extrinsics, allowing for them to continue syncing the network through upgrades141/// to even the core data structures.142pub mod opaque {143 use super::*;144145 pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;146147 /// Opaque block type.148 pub type Block = generic::Block<Header, UncheckedExtrinsic>;149150 pub type SessionHandlers = ();151152 impl_opaque_keys! {153 pub struct SessionKeys {154 pub aura: Aura,155 }156 }157}158159/// This runtime version.160pub const VERSION: RuntimeVersion = RuntimeVersion {161 spec_name: create_runtime_str!("quartz"),162 impl_name: create_runtime_str!("quartz"),163 authoring_version: 1,164 spec_version: 917001,165 impl_version: 0,166 apis: RUNTIME_API_VERSIONS,167 transaction_version: 1,168 state_version: 0,169};170171pub const MILLISECS_PER_BLOCK: u64 = 12000;172173pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;174175// These time units are defined in number of blocks.176pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);177pub const HOURS: BlockNumber = MINUTES * 60;178pub const DAYS: BlockNumber = HOURS * 24;179180parameter_types! {181 pub const DefaultSponsoringRateLimit: BlockNumber = 1 * DAYS;182}183184#[derive(codec::Encode, codec::Decode)]185pub enum XCMPMessage<XAccountId, XBalance> {186 /// Transfer tokens to the given account from the Parachain account.187 TransferToken(XAccountId, XBalance),188}189190/// The version information used to identify this runtime when compiled natively.191#[cfg(feature = "std")]192pub fn native_version() -> NativeVersion {193 NativeVersion {194 runtime_version: VERSION,195 can_author_with: Default::default(),196 }197}198199type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;200201pub struct DealWithFees;202impl OnUnbalanced<NegativeImbalance> for DealWithFees {203 fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {204 if let Some(fees) = fees_then_tips.next() {205 // for fees, 100% to treasury206 let mut split = fees.ration(100, 0);207 if let Some(tips) = fees_then_tips.next() {208 // for tips, if any, 100% to treasury209 tips.ration_merge_into(100, 0, &mut split);210 }211 Treasury::on_unbalanced(split.0);212 // Author::on_unbalanced(split.1);213 }214 }215}216217/// We assume that ~10% of the block weight is consumed by `on_initalize` handlers.218/// This is used to limit the maximal weight of a single extrinsic.219const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(10);220/// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used221/// by Operational extrinsics.222const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);223/// We allow for 2 seconds of compute with a 6 second average block time.224const MAXIMUM_BLOCK_WEIGHT: Weight = WEIGHT_PER_SECOND / 2;225226parameter_types! {227 pub const BlockHashCount: BlockNumber = 2400;228 pub RuntimeBlockLength: BlockLength =229 BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);230 pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);231 pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;232 pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()233 .base_block(BlockExecutionWeight::get())234 .for_class(DispatchClass::all(), |weights| {235 weights.base_extrinsic = ExtrinsicBaseWeight::get();236 })237 .for_class(DispatchClass::Normal, |weights| {238 weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);239 })240 .for_class(DispatchClass::Operational, |weights| {241 weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);242 // Operational transactions have some extra reserved space, so that they243 // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.244 weights.reserved = Some(245 MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT246 );247 })248 .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)249 .build_or_panic();250 pub const Version: RuntimeVersion = VERSION;251 /*252 255 - Quartz253 42 - Opal254 */255 pub const SS58Prefix: u8 = 255;256}257258/*2598880 - Unique2608881 - Quartz2618882 - Opal262*/263parameter_types! {264 pub const ChainId: u64 = 8881;265}266267pub struct FixedFee;268impl FeeCalculator for FixedFee {269 fn min_gas_price() -> U256 {270 // Targeting 0.15 UNQ per transfer271 1_018_751_825_264u64.into()272 }273}274275// Assuming slowest ethereum opcode is SSTORE, with gas price of 20000 as our worst case276// (contract, which only writes a lot of data),277// approximating on top of our real store write weight278parameter_types! {279 pub const WritesPerSecond: u64 = WEIGHT_PER_SECOND / <Runtime as frame_system::Config>::DbWeight::get().write;280 pub const GasPerSecond: u64 = WritesPerSecond::get() * 20000;281 pub const WeightPerGas: u64 = WEIGHT_PER_SECOND / GasPerSecond::get();282}283284/// Limiting EVM execution to 50% of block for substrate users and management tasks285/// EVM transaction consumes more weight than substrate's, so we can't rely on them being286/// scheduled fairly287const EVM_DISPATCH_RATIO: Perbill = Perbill::from_percent(50);288parameter_types! {289 pub BlockGasLimit: U256 = U256::from(NORMAL_DISPATCH_RATIO * EVM_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT / WeightPerGas::get());290}291292pub enum FixedGasWeightMapping {}293impl GasWeightMapping for FixedGasWeightMapping {294 fn gas_to_weight(gas: u64) -> Weight {295 gas.saturating_mul(WeightPerGas::get())296 }297 fn weight_to_gas(weight: Weight) -> u64 {298 weight / WeightPerGas::get()299 }300}301302impl pallet_evm::Config for Runtime {303 type BlockGasLimit = BlockGasLimit;304 type FeeCalculator = FixedFee;305 type GasWeightMapping = FixedGasWeightMapping;306 type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;307 type CallOrigin = EnsureAddressTruncated;308 type WithdrawOrigin = EnsureAddressTruncated;309 type AddressMapping = HashedAddressMapping<Self::Hashing>;310 type PrecompilesType = ();311 type PrecompilesValue = ();312 type Currency = Balances;313 type Event = Event;314 type OnMethodCall = (315 pallet_evm_migration::OnMethodCall<Self>,316 pallet_unique::UniqueErcSupport<Self>,317 pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,318 );319 type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;320 type ChainId = ChainId;321 type Runner = pallet_evm::runner::stack::Runner<Self>;322 type OnChargeTransaction = pallet_evm_transaction_payment::OnChargeTransaction<Self>;323 type TransactionValidityHack = pallet_evm_transaction_payment::TransactionValidityHack<Self>;324 type FindAuthor = EthereumFindAuthor<Aura>;325}326327impl pallet_evm_migration::Config for Runtime {328 type WeightInfo = pallet_evm_migration::weights::SubstrateWeight<Self>;329}330331pub struct EthereumFindAuthor<F>(core::marker::PhantomData<F>);332impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F> {333 fn find_author<'a, I>(digests: I) -> Option<H160>334 where335 I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,336 {337 if let Some(author_index) = F::find_author(digests) {338 let authority_id = Aura::authorities()[author_index as usize].clone();339 return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24]));340 }341 None342 }343}344345impl pallet_ethereum::Config for Runtime {346 type Event = Event;347 type StateRoot = pallet_ethereum::IntermediateStateRoot;348}349350impl pallet_randomness_collective_flip::Config for Runtime {}351352impl frame_system::Config for Runtime {353 /// The data to be stored in an account.354 type AccountData = pallet_balances::AccountData<Balance>;355 /// The identifier used to distinguish between accounts.356 type AccountId = AccountId;357 /// The basic call filter to use in dispatchable.358 type BaseCallFilter = Everything;359 /// Maximum number of block number to block hash mappings to keep (oldest pruned first).360 type BlockHashCount = BlockHashCount;361 /// The maximum length of a block (in bytes).362 type BlockLength = RuntimeBlockLength;363 /// The index type for blocks.364 type BlockNumber = BlockNumber;365 /// The weight of the overhead invoked on the block import process, independent of the extrinsics included in that block.366 type BlockWeights = RuntimeBlockWeights;367 /// The aggregated dispatch type that is available for extrinsics.368 type Call = Call;369 /// The weight of database operations that the runtime can invoke.370 type DbWeight = RocksDbWeight;371 /// The ubiquitous event type.372 type Event = Event;373 /// The type for hashing blocks and tries.374 type Hash = Hash;375 /// The hashing algorithm used.376 type Hashing = BlakeTwo256;377 /// The header type.378 type Header = generic::Header<BlockNumber, BlakeTwo256>;379 /// The index type for storing how many extrinsics an account has signed.380 type Index = Index;381 /// The lookup mechanism to get account ID from whatever is passed in dispatchers.382 type Lookup = AccountIdLookup<AccountId, ()>;383 /// What to do if an account is fully reaped from the system.384 type OnKilledAccount = ();385 /// What to do if a new account is created.386 type OnNewAccount = ();387 type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;388 /// The ubiquitous origin type.389 type Origin = Origin;390 /// This type is being generated by `construct_runtime!`.391 type PalletInfo = PalletInfo;392 /// This is used as an identifier of the chain. 42 is the generic substrate prefix.393 type SS58Prefix = SS58Prefix;394 /// Weight information for the extrinsics of this pallet.395 type SystemWeightInfo = frame_system::weights::SubstrateWeight<Self>;396 /// Version of the runtime.397 type Version = Version;398 type MaxConsumers = ConstU32<16>;399}400401parameter_types! {402 pub const MinimumPeriod: u64 = SLOT_DURATION / 2;403}404405impl pallet_timestamp::Config for Runtime {406 /// A timestamp: milliseconds since the unix epoch.407 type Moment = u64;408 type OnTimestampSet = ();409 type MinimumPeriod = MinimumPeriod;410 type WeightInfo = ();411}412413parameter_types! {414 // pub const ExistentialDeposit: u128 = 500;415 pub const ExistentialDeposit: u128 = 0;416 pub const MaxLocks: u32 = 50;417}418419impl pallet_balances::Config for Runtime {420 type MaxLocks = MaxLocks;421 type MaxReserves = ();422 type ReserveIdentifier = [u8; 8];423 /// The type for recording an account's balance.424 type Balance = Balance;425 /// The ubiquitous event type.426 type Event = Event;427 type DustRemoval = Treasury;428 type ExistentialDeposit = ExistentialDeposit;429 type AccountStore = System;430 type WeightInfo = pallet_balances::weights::SubstrateWeight<Self>;431}432433pub const MICROUNIQUE: Balance = 1_000_000_000_000;434pub const MILLIUNIQUE: Balance = 1_000 * MICROUNIQUE;435pub const CENTIUNIQUE: Balance = 10 * MILLIUNIQUE;436pub const UNIQUE: Balance = 100 * CENTIUNIQUE;437438pub const fn deposit(items: u32, bytes: u32) -> Balance {439 items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE440}441442/*443parameter_types! {444 pub TombstoneDeposit: Balance = deposit(445 1,446 sp_std::mem::size_of::<pallet_contracts::Pallet<Runtime>> as u32,447 );448 pub DepositPerContract: Balance = TombstoneDeposit::get();449 pub const DepositPerStorageByte: Balance = deposit(0, 1);450 pub const DepositPerStorageItem: Balance = deposit(1, 0);451 pub RentFraction: Perbill = Perbill::from_rational(1u32, 30 * DAYS);452 pub const SurchargeReward: Balance = 150 * MILLIUNIQUE;453 pub const SignedClaimHandicap: u32 = 2;454 pub const MaxDepth: u32 = 32;455 pub const MaxValueSize: u32 = 16 * 1024;456 pub const MaxCodeSize: u32 = 1024 * 1024 * 25; // 25 Mb457 // The lazy deletion runs inside on_initialize.458 pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO *459 RuntimeBlockWeights::get().max_block;460 // The weight needed for decoding the queue should be less or equal than a fifth461 // of the overall weight dedicated to the lazy deletion.462 pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (463 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -464 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)465 )) / 5) as u32;466 pub Schedule: pallet_contracts::Schedule<Runtime> = Default::default();467}468469impl pallet_contracts::Config for Runtime {470 type Time = Timestamp;471 type Randomness = RandomnessCollectiveFlip;472 type Currency = Balances;473 type Event = Event;474 type RentPayment = ();475 type SignedClaimHandicap = SignedClaimHandicap;476 type TombstoneDeposit = TombstoneDeposit;477 type DepositPerContract = DepositPerContract;478 type DepositPerStorageByte = DepositPerStorageByte;479 type DepositPerStorageItem = DepositPerStorageItem;480 type RentFraction = RentFraction;481 type SurchargeReward = SurchargeReward;482 type WeightPrice = pallet_transaction_payment::Pallet<Self>;483 type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;484 type ChainExtension = NFTExtension;485 type DeletionQueueDepth = DeletionQueueDepth;486 type DeletionWeightLimit = DeletionWeightLimit;487 type Schedule = Schedule;488 type CallStack = [pallet_contracts::Frame<Self>; 31];489}490*/491492parameter_types! {493 pub const TransactionByteFee: Balance = 501 * MICROUNIQUE; // Targeting 0.1 Unique per NFT transfer494 /// This value increases the priority of `Operational` transactions by adding495 /// a "virtual tip" that's equal to the `OperationalFeeMultiplier * final_fee`.496 pub const OperationalFeeMultiplier: u8 = 5;497}498499/// Linear implementor of `WeightToFeePolynomial`500pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);501502impl<T> WeightToFeePolynomial for LinearFee<T>503where504 T: BaseArithmetic + From<u32> + Copy + Unsigned,505{506 type Balance = T;507508 fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {509 smallvec!(WeightToFeeCoefficient {510 // Targeting 0.1 Unique per NFT transfer511 coeff_integer: 142_688_000u32.into(),512 coeff_frac: Perbill::zero(),513 negative: false,514 degree: 1,515 })516 }517}518519impl pallet_transaction_payment::Config for Runtime {520 type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, DealWithFees>;521 type TransactionByteFee = TransactionByteFee;522 type OperationalFeeMultiplier = OperationalFeeMultiplier;523 type WeightToFee = LinearFee<Balance>;524 type FeeMultiplierUpdate = ();525}526527parameter_types! {528 pub const ProposalBond: Permill = Permill::from_percent(5);529 pub const ProposalBondMinimum: Balance = 1 * UNIQUE;530 pub const ProposalBondMaximum: Balance = 1000 * UNIQUE;531 pub const SpendPeriod: BlockNumber = 5 * MINUTES;532 pub const Burn: Permill = Permill::from_percent(0);533 pub const TipCountdown: BlockNumber = 1 * DAYS;534 pub const TipFindersFee: Percent = Percent::from_percent(20);535 pub const TipReportDepositBase: Balance = 1 * UNIQUE;536 pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;537 pub const BountyDepositBase: Balance = 1 * UNIQUE;538 pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;539 pub const TreasuryModuleId: PalletId = PalletId(*b"py/trsry");540 pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;541 pub const MaximumReasonLength: u32 = 16384;542 pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);543 pub const BountyValueMinimum: Balance = 5 * UNIQUE;544 pub const MaxApprovals: u32 = 100;545}546547impl pallet_treasury::Config for Runtime {548 type PalletId = TreasuryModuleId;549 type Currency = Balances;550 type ApproveOrigin = EnsureRoot<AccountId>;551 type RejectOrigin = EnsureRoot<AccountId>;552 type Event = Event;553 type OnSlash = ();554 type ProposalBond = ProposalBond;555 type ProposalBondMinimum = ProposalBondMinimum;556 type ProposalBondMaximum = ProposalBondMaximum;557 type SpendPeriod = SpendPeriod;558 type Burn = Burn;559 type BurnDestination = ();560 type SpendFunds = ();561 type WeightInfo = pallet_treasury::weights::SubstrateWeight<Self>;562 type MaxApprovals = MaxApprovals;563}564565impl pallet_sudo::Config for Runtime {566 type Event = Event;567 type Call = Call;568}569570pub struct RelayChainBlockNumberProvider<T>(sp_std::marker::PhantomData<T>);571572impl<T: cumulus_pallet_parachain_system::Config> BlockNumberProvider573 for RelayChainBlockNumberProvider<T>574{575 type BlockNumber = BlockNumber;576577 fn current_block_number() -> Self::BlockNumber {578 cumulus_pallet_parachain_system::Pallet::<T>::validation_data()579 .map(|d| d.relay_parent_number)580 .unwrap_or_default()581 }582}583584parameter_types! {585 pub const MinVestedTransfer: Balance = 10 * UNIQUE;586 pub const MaxVestingSchedules: u32 = 28;587}588589impl orml_vesting::Config for Runtime {590 type Event = Event;591 type Currency = pallet_balances::Pallet<Runtime>;592 type MinVestedTransfer = MinVestedTransfer;593 type VestedTransferOrigin = EnsureSigned<AccountId>;594 type WeightInfo = ();595 type MaxVestingSchedules = MaxVestingSchedules;596 type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;597}598599parameter_types! {600 pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;601 pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;602}603604impl cumulus_pallet_parachain_system::Config for Runtime {605 type Event = Event;606 type SelfParaId = parachain_info::Pallet<Self>;607 type OnSystemEvent = ();608 // type DownwardMessageHandlers = cumulus_primitives_utility::UnqueuedDmpAsParent<609 // MaxDownwardMessageWeight,610 // XcmExecutor<XcmConfig>,611 // Call,612 // >;613 type OutboundXcmpMessageSource = XcmpQueue;614 type DmpMessageHandler = DmpQueue;615 type ReservedDmpWeight = ReservedDmpWeight;616 type ReservedXcmpWeight = ReservedXcmpWeight;617 type XcmpMessageHandler = XcmpQueue;618}619620impl parachain_info::Config for Runtime {}621622impl cumulus_pallet_aura_ext::Config for Runtime {}623624parameter_types! {625 pub const RelayLocation: MultiLocation = MultiLocation::parent();626 pub const RelayNetwork: NetworkId = NetworkId::Polkadot;627 pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();628 pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();629}630631/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used632/// when determining ownership of accounts for asset transacting and when attempting to use XCM633/// `Transact` in order to determine the dispatch Origin.634pub type LocationToAccountId = (635 // The parent (Relay-chain) origin converts to the default `AccountId`.636 ParentIsPreset<AccountId>,637 // Sibling parachain origins convert to AccountId via the `ParaId::into`.638 SiblingParachainConvertsVia<Sibling, AccountId>,639 // Straight up local `AccountId32` origins just alias directly to `AccountId`.640 AccountId32Aliases<RelayNetwork, AccountId>,641);642643pub struct OnlySelfCurrency;644impl<B: TryFrom<u128>> MatchesFungible<B> for OnlySelfCurrency {645 fn matches_fungible(a: &MultiAsset) -> Option<B> {646 match (&a.id, &a.fun) {647 (Concrete(_), XcmFungible(ref amount)) => CheckedConversion::checked_from(*amount),648 _ => None,649 }650 }651}652653/// Means for transacting assets on this chain.654pub type LocalAssetTransactor = CurrencyAdapter<655 // Use this currency:656 Balances,657 // Use this currency when it is a fungible asset matching the given location or name:658 OnlySelfCurrency,659 // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:660 LocationToAccountId,661 // Our chain's account ID type (we can't get away without mentioning it explicitly):662 AccountId,663 // We don't track any teleports.664 (),665>;666667/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,668/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can669/// biases the kind of local `Origin` it will become.670pub type XcmOriginToTransactDispatchOrigin = (671 // Sovereign account converter; this attempts to derive an `AccountId` from the origin location672 // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for673 // foreign chains who want to have a local sovereign account on this chain which they control.674 SovereignSignedViaLocation<LocationToAccountId, Origin>,675 // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when676 // recognised.677 RelayChainAsNative<RelayOrigin, Origin>,678 // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when679 // recognised.680 SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,681 // Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a682 // transaction from the Root origin.683 ParentAsSuperuser<Origin>,684 // Native signed account converter; this just converts an `AccountId32` origin into a normal685 // `Origin::Signed` origin of the same 32-byte value.686 SignedAccountId32AsNative<RelayNetwork, Origin>,687 // Xcm origins can be represented natively under the Xcm pallet's Xcm origin.688 XcmPassthrough<Origin>,689);690691parameter_types! {692 // One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.693 pub UnitWeightCost: Weight = 1_000_000;694 // 1200 UNIQUEs buy 1 second of weight.695 pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);696 pub const MaxInstructions: u32 = 100;697 pub const MaxAuthorities: u32 = 100_000;698}699700match_type! {701 pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {702 MultiLocation { parents: 1, interior: Here } |703 MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }704 };705}706707pub type Barrier = (708 TakeWeightCredit,709 AllowTopLevelPaidExecutionFrom<Everything>,710 AllowUnpaidExecutionFrom<ParentOrParentsUnitPlurality>,711 // ^^^ Parent & its unit plurality gets free execution712);713714pub struct UsingOnlySelfCurrencyComponents<715 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,716 AssetId: Get<MultiLocation>,717 AccountId,718 Currency: CurrencyT<AccountId>,719 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,720>(721 Weight,722 Currency::Balance,723 PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>,724);725impl<726 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,727 AssetId: Get<MultiLocation>,728 AccountId,729 Currency: CurrencyT<AccountId>,730 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,731 > WeightTrader732 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>733{734 fn new() -> Self {735 Self(0, Zero::zero(), PhantomData)736 }737738 fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {739 let amount = WeightToFee::calc(&weight);740 let u128_amount: u128 = amount.try_into().map_err(|_| XcmError::Overflow)?;741742 // location to this parachain through relay chain743 let option1: xcm::v1::AssetId = Concrete(MultiLocation {744 parents: 1,745 interior: X1(Parachain(ParachainInfo::parachain_id().into())),746 });747 // direct location748 let option2: xcm::v1::AssetId = Concrete(MultiLocation {749 parents: 0,750 interior: Here,751 });752753 let required = if payment.fungible.contains_key(&option1) {754 (option1, u128_amount).into()755 } else if payment.fungible.contains_key(&option2) {756 (option2, u128_amount).into()757 } else {758 (Concrete(MultiLocation::default()), u128_amount).into()759 };760761 let unused = payment762 .checked_sub(required)763 .map_err(|_| XcmError::TooExpensive)?;764 self.0 = self.0.saturating_add(weight);765 self.1 = self.1.saturating_add(amount);766 Ok(unused)767 }768769 fn refund_weight(&mut self, weight: Weight) -> Option<MultiAsset> {770 let weight = weight.min(self.0);771 let amount = WeightToFee::calc(&weight);772 self.0 -= weight;773 self.1 = self.1.saturating_sub(amount);774 let amount: u128 = amount.saturated_into();775 if amount > 0 {776 Some((AssetId::get(), amount).into())777 } else {778 None779 }780 }781}782impl<783 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,784 AssetId: Get<MultiLocation>,785 AccountId,786 Currency: CurrencyT<AccountId>,787 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,788 > Drop789 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>790{791 fn drop(&mut self) {792 OnUnbalanced::on_unbalanced(Currency::issue(self.1));793 }794}795796pub struct XcmConfig;797impl Config for XcmConfig {798 type Call = Call;799 type XcmSender = XcmRouter;800 // How to withdraw and deposit an asset.801 type AssetTransactor = LocalAssetTransactor;802 type OriginConverter = XcmOriginToTransactDispatchOrigin;803 type IsReserve = NativeAsset;804 type IsTeleporter = (); // Teleportation is disabled805 type LocationInverter = LocationInverter<Ancestry>;806 type Barrier = Barrier;807 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;808 type Trader = UsingOnlySelfCurrencyComponents<809 IdentityFee<Balance>,810 RelayLocation,811 AccountId,812 Balances,813 (),814 >;815 type ResponseHandler = (); // Don't handle responses for now.816 type SubscriptionService = PolkadotXcm;817818 type AssetTrap = PolkadotXcm;819 type AssetClaims = PolkadotXcm;820}821822// parameter_types! {823// pub const MaxDownwardMessageWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 10;824// }825826/// No local origins on this chain are allowed to dispatch XCM sends/executions.827pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);828829/// The means for routing XCM messages which are not for local execution into the right message830/// queues.831pub type XcmRouter = (832 // Two routers - use UMP to communicate with the relay chain:833 cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,834 // ..and XCMP to communicate with the sibling chains.835 XcmpQueue,836);837838impl pallet_evm_coder_substrate::Config for Runtime {839 type EthereumTransactionSender = pallet_ethereum::Pallet<Self>;840 type GasWeightMapping = FixedGasWeightMapping;841}842843impl pallet_xcm::Config for Runtime {844 type Event = Event;845 type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;846 type XcmRouter = XcmRouter;847 type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;848 type XcmExecuteFilter = Everything;849 type XcmExecutor = XcmExecutor<XcmConfig>;850 type XcmTeleportFilter = Everything;851 type XcmReserveTransferFilter = Everything;852 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;853 type LocationInverter = LocationInverter<Ancestry>;854 type Origin = Origin;855 type Call = Call;856 const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;857 type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;858}859860impl cumulus_pallet_xcm::Config for Runtime {861 type Event = Event;862 type XcmExecutor = XcmExecutor<XcmConfig>;863}864865impl cumulus_pallet_xcmp_queue::Config for Runtime {866 type Event = Event;867 type XcmExecutor = XcmExecutor<XcmConfig>;868 type ChannelInfo = ParachainSystem;869 type VersionWrapper = ();870 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;871 type ControllerOrigin = EnsureRoot<AccountId>;872 type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;873}874875impl cumulus_pallet_dmp_queue::Config for Runtime {876 type Event = Event;877 type XcmExecutor = XcmExecutor<XcmConfig>;878 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;879}880881impl pallet_aura::Config for Runtime {882 type AuthorityId = AuraId;883 type DisabledValidators = ();884 type MaxAuthorities = MaxAuthorities;885}886887parameter_types! {888 pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();889 pub const CollectionCreationPrice: Balance = 2 * UNIQUE;890}891892impl pallet_common::Config for Runtime {893 type Event = Event;894 type EvmBackwardsAddressMapping = up_evm_mapping::MapBackwardsAddressTruncated;895 type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;896 type CrossAccountId = pallet_common::account::BasicCrossAccountId<Self>;897898 type Currency = Balances;899 type CollectionCreationPrice = CollectionCreationPrice;900 type TreasuryAccountId = TreasuryAccountId;901}902903impl pallet_fungible::Config for Runtime {904 type WeightInfo = pallet_fungible::weights::SubstrateWeight<Self>;905}906impl pallet_refungible::Config for Runtime {907 type WeightInfo = pallet_refungible::weights::SubstrateWeight<Self>;908}909impl pallet_nonfungible::Config for Runtime {910 type WeightInfo = pallet_nonfungible::weights::SubstrateWeight<Self>;911}912913impl pallet_unique::Config for Runtime {914 type Event = Event;915 type WeightInfo = pallet_unique::weights::SubstrateWeight<Self>;916}917918parameter_types! {919 pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied920}921922/// Used for the pallet inflation923impl pallet_inflation::Config for Runtime {924 type Currency = Balances;925 type TreasuryAccountId = TreasuryAccountId;926 type InflationBlockInterval = InflationBlockInterval;927 type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;928}929930// parameter_types! {931// pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *932// RuntimeBlockWeights::get().max_block;933// pub const MaxScheduledPerBlock: u32 = 50;934// }935936type EvmSponsorshipHandler = (937 pallet_unique::UniqueEthSponsorshipHandler<Runtime>,938 pallet_evm_contract_helpers::HelpersContractSponsoring<Runtime>,939);940type SponsorshipHandler = (941 pallet_unique::UniqueSponsorshipHandler<Runtime>,942 //pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,943 pallet_evm_transaction_payment::BridgeSponsorshipHandler<Runtime>,944);945946// impl pallet_unq_scheduler::Config for Runtime {947// type Event = Event;948// type Origin = Origin;949// type PalletsOrigin = OriginCaller;950// type Call = Call;951// type MaximumWeight = MaximumSchedulerWeight;952// type ScheduleOrigin = EnsureSigned<AccountId>;953// type MaxScheduledPerBlock = MaxScheduledPerBlock;954// type SponsorshipHandler = SponsorshipHandler;955// type WeightInfo = ();956// }957958impl pallet_evm_transaction_payment::Config for Runtime {959 type EvmSponsorshipHandler = EvmSponsorshipHandler;960 type Currency = Balances;961 type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;962 type EvmBackwardsAddressMapping = up_evm_mapping::MapBackwardsAddressTruncated;963}964965impl pallet_charge_transaction::Config for Runtime {966 type SponsorshipHandler = SponsorshipHandler;967}968969// impl pallet_contract_helpers::Config for Runtime {970// type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;971// }972973parameter_types! {974 // 0x842899ECF380553E8a4de75bF534cdf6fBF64049975 pub const HelpersContractAddress: H160 = H160([976 0x84, 0x28, 0x99, 0xec, 0xf3, 0x80, 0x55, 0x3e, 0x8a, 0x4d, 0xe7, 0x5b, 0xf5, 0x34, 0xcd, 0xf6, 0xfb, 0xf6, 0x40, 0x49,977 ]);978}979980impl pallet_evm_contract_helpers::Config for Runtime {981 type ContractAddress = HelpersContractAddress;982 type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;983}984985construct_runtime!(986 pub enum Runtime where987 Block = Block,988 NodeBlock = opaque::Block,989 UncheckedExtrinsic = UncheckedExtrinsic990 {991 ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Config, Storage, Inherent, Event<T>, ValidateUnsigned} = 20,992 ParachainInfo: parachain_info::{Pallet, Storage, Config} = 21,993994 Aura: pallet_aura::{Pallet, Config<T>} = 22,995 AuraExt: cumulus_pallet_aura_ext::{Pallet, Config} = 23,996997 Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 30,998 RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage} = 31,999 Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 32,1000 TransactionPayment: pallet_transaction_payment::{Pallet, Storage} = 33,1001 Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event<T>} = 34,1002 Sudo: pallet_sudo::{Pallet, Call, Storage, Config<T>, Event<T>} = 35,1003 System: frame_system::{Pallet, Call, Storage, Config, Event<T>} = 36,1004 Vesting: orml_vesting::{Pallet, Storage, Call, Event<T>, Config<T>} = 37,1005 // Vesting: pallet_vesting::{Pallet, Call, Config<T>, Storage, Event<T>} = 37,1006 // Contracts: pallet_contracts::{Pallet, Call, Storage, Event<T>} = 38,10071008 // XCM helpers.1009 XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 50,1010 PolkadotXcm: pallet_xcm::{Pallet, Call, Event<T>, Origin} = 51,1011 CumulusXcm: cumulus_pallet_xcm::{Pallet, Call, Event<T>, Origin} = 52,1012 DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,10131014 // Unique Pallets1015 Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,1016 Unique: pallet_unique::{Pallet, Call, Storage, Event<T>} = 61,1017 // Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,1018 // free = 631019 Charging: pallet_charge_transaction::{Pallet, Call, Storage } = 64,1020 // ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,1021 Common: pallet_common::{Pallet, Storage, Event<T>} = 66,1022 Fungible: pallet_fungible::{Pallet, Storage} = 67,1023 Refungible: pallet_refungible::{Pallet, Storage} = 68,1024 Nonfungible: pallet_nonfungible::{Pallet, Storage} = 69,10251026 // Frontier1027 EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,1028 Ethereum: pallet_ethereum::{Pallet, Config, Call, Storage, Event, Origin} = 101,10291030 EvmCoderSubstrate: pallet_evm_coder_substrate::{Pallet, Storage} = 150,1031 EvmContractHelpers: pallet_evm_contract_helpers::{Pallet, Storage} = 151,1032 EvmTransactionPayment: pallet_evm_transaction_payment::{Pallet} = 152,1033 EvmMigration: pallet_evm_migration::{Pallet, Call, Storage} = 153,1034 }1035);10361037pub struct TransactionConverter;10381039impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {1040 fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {1041 UncheckedExtrinsic::new_unsigned(1042 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1043 )1044 }1045}10461047impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {1048 fn convert_transaction(1049 &self,1050 transaction: pallet_ethereum::Transaction,1051 ) -> opaque::UncheckedExtrinsic {1052 let extrinsic = UncheckedExtrinsic::new_unsigned(1053 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1054 );1055 let encoded = extrinsic.encode();1056 opaque::UncheckedExtrinsic::decode(&mut &encoded[..])1057 .expect("Encoded extrinsic is always valid")1058 }1059}10601061/// The address format for describing accounts.1062pub type Address = sp_runtime::MultiAddress<AccountId, ()>;1063/// Block header type as expected by this runtime.1064pub type Header = generic::Header<BlockNumber, BlakeTwo256>;1065/// Block type as expected by this runtime.1066pub type Block = generic::Block<Header, UncheckedExtrinsic>;1067/// A Block signed with a Justification1068pub type SignedBlock = generic::SignedBlock<Block>;1069/// BlockId type as expected by this runtime.1070pub type BlockId = generic::BlockId<Block>;1071/// The SignedExtension to the basic transaction logic.1072pub type SignedExtra = (1073 frame_system::CheckSpecVersion<Runtime>,1074 // system::CheckTxVersion<Runtime>,1075 frame_system::CheckGenesis<Runtime>,1076 frame_system::CheckEra<Runtime>,1077 frame_system::CheckNonce<Runtime>,1078 frame_system::CheckWeight<Runtime>,1079 pallet_charge_transaction::ChargeTransactionPayment<Runtime>,1080 //pallet_contract_helpers::ContractHelpersExtension<Runtime>,1081);1082/// Unchecked extrinsic type as expected by this runtime.1083pub type UncheckedExtrinsic =1084 fp_self_contained::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;1085/// Extrinsic type that has already been checked.1086pub type CheckedExtrinsic = fp_self_contained::CheckedExtrinsic<AccountId, Call, SignedExtra, H160>;1087/// Executive: handles dispatch to the various modules.1088pub type Executive = frame_executive::Executive<1089 Runtime,1090 Block,1091 frame_system::ChainContext<Runtime>,1092 Runtime,1093 AllPalletsReversedWithSystemFirst,1094>;10951096impl_opaque_keys! {1097 pub struct SessionKeys {1098 pub aura: Aura,1099 }1100}11011102impl fp_self_contained::SelfContainedCall for Call {1103 type SignedInfo = H160;11041105 fn is_self_contained(&self) -> bool {1106 match self {1107 Call::Ethereum(call) => call.is_self_contained(),1108 _ => false,1109 }1110 }11111112 fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {1113 match self {1114 Call::Ethereum(call) => call.check_self_contained(),1115 _ => None,1116 }1117 }11181119 fn validate_self_contained(&self, info: &Self::SignedInfo) -> Option<TransactionValidity> {1120 match self {1121 Call::Ethereum(call) => call.validate_self_contained(info),1122 _ => None,1123 }1124 }11251126 fn pre_dispatch_self_contained(1127 &self,1128 info: &Self::SignedInfo,1129 ) -> Option<Result<(), TransactionValidityError>> {1130 match self {1131 Call::Ethereum(call) => call.pre_dispatch_self_contained(info),1132 _ => None,1133 }1134 }11351136 fn apply_self_contained(1137 self,1138 info: Self::SignedInfo,1139 ) -> Option<sp_runtime::DispatchResultWithInfo<PostDispatchInfoOf<Self>>> {1140 match self {1141 call @ Call::Ethereum(pallet_ethereum::Call::transact { .. }) => Some(call.dispatch(1142 Origin::from(pallet_ethereum::RawOrigin::EthereumTransaction(info)),1143 )),1144 _ => None,1145 }1146 }1147}11481149macro_rules! dispatch_unique_runtime {1150 ($collection:ident.$method:ident($($name:ident),*)) => {{1151 use pallet_unique::dispatch::Dispatched;11521153 let collection = Dispatched::dispatch(<pallet_common::CollectionHandle<Runtime>>::try_get($collection)?);1154 let dispatch = collection.as_dyn();11551156 Ok(dispatch.$method($($name),*))1157 }};1158}1159impl_runtime_apis! {1160 impl up_rpc::UniqueApi<Block, CrossAccountId, AccountId>1161 for Runtime1162 {1163 fn account_tokens(collection: CollectionId, account: CrossAccountId) -> Result<Vec<TokenId>, DispatchError> {1164 dispatch_unique_runtime!(collection.account_tokens(account))1165 }1166 fn token_exists(collection: CollectionId, token: TokenId) -> Result<bool, DispatchError> {1167 dispatch_unique_runtime!(collection.token_exists(token))1168 }11691170 fn token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>, DispatchError> {1171 dispatch_unique_runtime!(collection.token_owner(token))1172 }1173 fn const_metadata(collection: CollectionId, token: TokenId) -> Result<Vec<u8>, DispatchError> {1174 dispatch_unique_runtime!(collection.const_metadata(token))1175 }1176 fn variable_metadata(collection: CollectionId, token: TokenId) -> Result<Vec<u8>, DispatchError> {1177 dispatch_unique_runtime!(collection.variable_metadata(token))1178 }11791180 fn collection_tokens(collection: CollectionId) -> Result<u32, DispatchError> {1181 dispatch_unique_runtime!(collection.collection_tokens())1182 }1183 fn account_balance(collection: CollectionId, account: CrossAccountId) -> Result<u32, DispatchError> {1184 dispatch_unique_runtime!(collection.account_balance(account))1185 }1186 fn balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<u128, DispatchError> {1187 dispatch_unique_runtime!(collection.balance(account, token))1188 }1189 fn allowance(1190 collection: CollectionId,1191 sender: CrossAccountId,1192 spender: CrossAccountId,1193 token: TokenId,1194 ) -> Result<u128, DispatchError> {1195 dispatch_unique_runtime!(collection.allowance(sender, spender, token))1196 }11971198 fn eth_contract_code(account: H160) -> Option<Vec<u8>> {1199 <pallet_unique::UniqueErcSupport<Runtime>>::get_code(&account)1200 .or_else(|| <pallet_evm_migration::OnMethodCall<Runtime>>::get_code(&account))1201 .or_else(|| <pallet_evm_contract_helpers::HelpersOnMethodCall<Self>>::get_code(&account))1202 }1203 fn adminlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {1204 Ok(<pallet_common::Pallet<Runtime>>::adminlist(collection))1205 }1206 fn allowlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {1207 Ok(<pallet_common::Pallet<Runtime>>::allowlist(collection))1208 }1209 fn allowed(collection: CollectionId, user: CrossAccountId) -> Result<bool, DispatchError> {1210 Ok(<pallet_common::Pallet<Runtime>>::allowed(collection, user))1211 }1212 fn last_token_id(collection: CollectionId) -> Result<TokenId, DispatchError> {1213 dispatch_unique_runtime!(collection.last_token_id())1214 }1215 fn collection_by_id(collection: CollectionId) -> Result<Option<Collection<AccountId>>, DispatchError> {1216 Ok(<pallet_common::CollectionById<Runtime>>::get(collection))1217 }1218 fn collection_stats() -> Result<CollectionStats, DispatchError> {1219 Ok(<pallet_common::Pallet<Runtime>>::collection_stats())1220 }1221 }12221223 impl sp_api::Core<Block> for Runtime {1224 fn version() -> RuntimeVersion {1225 VERSION1226 }12271228 fn execute_block(block: Block) {1229 Executive::execute_block(block)1230 }12311232 fn initialize_block(header: &<Block as BlockT>::Header) {1233 Executive::initialize_block(header)1234 }1235 }12361237 impl sp_api::Metadata<Block> for Runtime {1238 fn metadata() -> OpaqueMetadata {1239 OpaqueMetadata::new(Runtime::metadata().into())1240 }1241 }12421243 impl sp_block_builder::BlockBuilder<Block> for Runtime {1244 fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {1245 Executive::apply_extrinsic(extrinsic)1246 }12471248 fn finalize_block() -> <Block as BlockT>::Header {1249 Executive::finalize_block()1250 }12511252 fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {1253 data.create_extrinsics()1254 }12551256 fn check_inherents(1257 block: Block,1258 data: sp_inherents::InherentData,1259 ) -> sp_inherents::CheckInherentsResult {1260 data.check_extrinsics(&block)1261 }12621263 // fn random_seed() -> <Block as BlockT>::Hash {1264 // RandomnessCollectiveFlip::random_seed().01265 // }1266 }12671268 impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {1269 fn validate_transaction(1270 source: TransactionSource,1271 tx: <Block as BlockT>::Extrinsic,1272 hash: <Block as BlockT>::Hash,1273 ) -> TransactionValidity {1274 Executive::validate_transaction(source, tx, hash)1275 }1276 }12771278 impl sp_offchain::OffchainWorkerApi<Block> for Runtime {1279 fn offchain_worker(header: &<Block as BlockT>::Header) {1280 Executive::offchain_worker(header)1281 }1282 }12831284 impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {1285 fn chain_id() -> u64 {1286 <Runtime as pallet_evm::Config>::ChainId::get()1287 }12881289 fn account_basic(address: H160) -> EVMAccount {1290 EVM::account_basic(&address)1291 }12921293 fn gas_price() -> U256 {1294 <Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price()1295 }12961297 fn account_code_at(address: H160) -> Vec<u8> {1298 EVM::account_codes(address)1299 }13001301 fn author() -> H160 {1302 <pallet_evm::Pallet<Runtime>>::find_author()1303 }13041305 fn storage_at(address: H160, index: U256) -> H256 {1306 let mut tmp = [0u8; 32];1307 index.to_big_endian(&mut tmp);1308 EVM::account_storages(address, H256::from_slice(&tmp[..]))1309 }13101311 #[allow(clippy::redundant_closure)]1312 fn call(1313 from: H160,1314 to: H160,1315 data: Vec<u8>,1316 value: U256,1317 gas_limit: U256,1318 max_fee_per_gas: Option<U256>,1319 max_priority_fee_per_gas: Option<U256>,1320 nonce: Option<U256>,1321 estimate: bool,1322 access_list: Option<Vec<(H160, Vec<H256>)>>,1323 ) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {1324 let config = if estimate {1325 let mut config = <Runtime as pallet_evm::Config>::config().clone();1326 config.estimate = true;1327 Some(config)1328 } else {1329 None1330 };13311332 <Runtime as pallet_evm::Config>::Runner::call(1333 from,1334 to,1335 data,1336 value,1337 gas_limit.low_u64(),1338 max_fee_per_gas,1339 max_priority_fee_per_gas,1340 nonce,1341 access_list.unwrap_or_default(),1342 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),1343 ).map_err(|err| err.into())1344 }13451346 #[allow(clippy::redundant_closure)]1347 fn create(1348 from: H160,1349 data: Vec<u8>,1350 value: U256,1351 gas_limit: U256,1352 max_fee_per_gas: Option<U256>,1353 max_priority_fee_per_gas: Option<U256>,1354 nonce: Option<U256>,1355 estimate: bool,1356 access_list: Option<Vec<(H160, Vec<H256>)>>,1357 ) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {1358 let config = if estimate {1359 let mut config = <Runtime as pallet_evm::Config>::config().clone();1360 config.estimate = true;1361 Some(config)1362 } else {1363 None1364 };13651366 <Runtime as pallet_evm::Config>::Runner::create(1367 from,1368 data,1369 value,1370 gas_limit.low_u64(),1371 max_fee_per_gas,1372 max_priority_fee_per_gas,1373 nonce,1374 access_list.unwrap_or_default(),1375 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),1376 ).map_err(|err| err.into())1377 }13781379 fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {1380 Ethereum::current_transaction_statuses()1381 }13821383 fn current_block() -> Option<pallet_ethereum::Block> {1384 Ethereum::current_block()1385 }13861387 fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {1388 Ethereum::current_receipts()1389 }13901391 fn current_all() -> (1392 Option<pallet_ethereum::Block>,1393 Option<Vec<pallet_ethereum::Receipt>>,1394 Option<Vec<TransactionStatus>>1395 ) {1396 (1397 Ethereum::current_block(),1398 Ethereum::current_receipts(),1399 Ethereum::current_transaction_statuses()1400 )1401 }14021403 fn extrinsic_filter(xts: Vec<<Block as sp_api::BlockT>::Extrinsic>) -> Vec<pallet_ethereum::Transaction> {1404 xts.into_iter().filter_map(|xt| match xt.0.function {1405 Call::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction),1406 _ => None1407 }).collect()1408 }14091410 fn elasticity() -> Option<Permill> {1411 None1412 }1413 }14141415 impl sp_session::SessionKeys<Block> for Runtime {1416 fn decode_session_keys(1417 encoded: Vec<u8>,1418 ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {1419 SessionKeys::decode_into_raw_public_keys(&encoded)1420 }14211422 fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {1423 SessionKeys::generate(seed)1424 }1425 }14261427 impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {1428 fn slot_duration() -> sp_consensus_aura::SlotDuration {1429 sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())1430 }14311432 fn authorities() -> Vec<AuraId> {1433 Aura::authorities().to_vec()1434 }1435 }14361437 impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {1438 fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {1439 ParachainSystem::collect_collation_info(header)1440 }1441 }14421443 impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {1444 fn account_nonce(account: AccountId) -> Index {1445 System::account_nonce(account)1446 }1447 }14481449 impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {1450 fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {1451 TransactionPayment::query_info(uxt, len)1452 }1453 fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {1454 TransactionPayment::query_fee_details(uxt, len)1455 }1456 }14571458 /*1459 impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber, Hash>1460 for Runtime1461 {1462 fn call(1463 origin: AccountId,1464 dest: AccountId,1465 value: Balance,1466 gas_limit: u64,1467 input_data: Vec<u8>,1468 ) -> pallet_contracts_primitives::ContractExecResult {1469 Contracts::bare_call(origin, dest, value, gas_limit, input_data, false)1470 }14711472 fn instantiate(1473 origin: AccountId,1474 endowment: Balance,1475 gas_limit: u64,1476 code: pallet_contracts_primitives::Code<Hash>,1477 data: Vec<u8>,1478 salt: Vec<u8>,1479 ) -> pallet_contracts_primitives::ContractInstantiateResult<AccountId, BlockNumber>1480 {1481 Contracts::bare_instantiate(origin, endowment, gas_limit, code, data, salt, true, false)1482 }14831484 fn get_storage(1485 address: AccountId,1486 key: [u8; 32],1487 ) -> pallet_contracts_primitives::GetStorageResult {1488 Contracts::get_storage(address, key)1489 }14901491 fn rent_projection(1492 address: AccountId,1493 ) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {1494 Contracts::rent_projection(address)1495 }1496 }1497 */14981499 #[cfg(feature = "runtime-benchmarks")]1500 impl frame_benchmarking::Benchmark<Block> for Runtime {1501 fn benchmark_metadata(extra: bool) -> (1502 Vec<frame_benchmarking::BenchmarkList>,1503 Vec<frame_support::traits::StorageInfo>,1504 ) {1505 use frame_benchmarking::{list_benchmark, Benchmarking, BenchmarkList};1506 use frame_support::traits::StorageInfoTrait;15071508 let mut list = Vec::<BenchmarkList>::new();15091510 list_benchmark!(list, extra, pallet_evm_migration, EvmMigration);1511 list_benchmark!(list, extra, pallet_unique, Unique);1512 list_benchmark!(list, extra, pallet_inflation, Inflation);1513 list_benchmark!(list, extra, pallet_fungible, Fungible);1514 list_benchmark!(list, extra, pallet_refungible, Refungible);1515 list_benchmark!(list, extra, pallet_nonfungible, Nonfungible);1516 // list_benchmark!(list, extra, pallet_evm_coder_substrate, EvmCoderSubstrate);15171518 let storage_info = AllPalletsReversedWithSystemFirst::storage_info();15191520 return (list, storage_info)1521 }15221523 fn dispatch_benchmark(1524 config: frame_benchmarking::BenchmarkConfig1525 ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {1526 use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};15271528 let allowlist: Vec<TrackedStorageKey> = vec![1529 // Block Number1530 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),1531 // Total Issuance1532 hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),1533 // Execution Phase1534 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),1535 // Event Count1536 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),1537 // System Events1538 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),1539 ];15401541 let mut batches = Vec::<BenchmarkBatch>::new();1542 let params = (&config, &allowlist);15431544 add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);1545 add_benchmark!(params, batches, pallet_unique, Unique);1546 add_benchmark!(params, batches, pallet_inflation, Inflation);1547 add_benchmark!(params, batches, pallet_fungible, Fungible);1548 add_benchmark!(params, batches, pallet_refungible, Refungible);1549 add_benchmark!(params, batches, pallet_nonfungible, Nonfungible);1550 // add_benchmark!(params, batches, pallet_evm_coder_substrate, EvmCoderSubstrate);15511552 if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }1553 Ok(batches)1554 }1555 }1556}15571558struct CheckInherents;15591560impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {1561 fn check_inherents(1562 block: &Block,1563 relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,1564 ) -> sp_inherents::CheckInherentsResult {1565 let relay_chain_slot = relay_state_proof1566 .read_slot()1567 .expect("Could not read the relay chain slot from the proof");15681569 let inherent_data =1570 cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(1571 relay_chain_slot,1572 sp_std::time::Duration::from_secs(6),1573 )1574 .create_inherent_data()1575 .expect("Could not create the timestamp inherent data");15761577 inherent_data.check_extrinsics(block)1578 }1579}15801581cumulus_pallet_parachain_system::register_validate_block!(1582 Runtime = Runtime,1583 BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,1584 CheckInherents = CheckInherents,1585);