git.delta.rocks / unique-network / refs/commits / 7e0ba1d9645e

difftreelog

source

runtime/quartz/src/lib.rs51.8 KiBsourcehistory
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,27		AccountIdConversion, Zero,28	},29	transaction_validity::{TransactionSource, TransactionValidity},30	ApplyExtrinsicResult, 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	ParentIsDefault, RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia,90	SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit,91};92use xcm_executor::{Config, XcmExecutor, Assets};93use sp_std::{marker::PhantomData};9495use xcm::latest::{96	//	Xcm,97	AssetId::{Concrete},98	Fungibility::Fungible as XcmFungible,99	MultiAsset,100	Error as XcmError,101};102use xcm_executor::traits::{MatchesFungible, WeightTrader};103//use xcm_executor::traits::MatchesFungible;104use sp_runtime::traits::CheckedConversion;105106use unique_runtime_common::{107	types::*,108	constants::*,109};110111// mod chain_extension;112// use crate::chain_extension::{NFTExtension, Imbalance};113114pub const RUNTIME_NAME: &'static str = "Quartz";115116pub type CrossAccountId = pallet_common::account::BasicCrossAccountId<Runtime>;117118/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know119/// the specifics of the runtime. They can then be made to be agnostic over specific formats120/// of data like extrinsics, allowing for them to continue syncing the network through upgrades121/// to even the core data structures.122pub mod opaque {123	use sp_std::prelude::*;124	use sp_runtime::impl_opaque_keys;125	use super::Aura;126127	pub use unique_runtime_common::types::*;128	pub use super::CrossAccountId;129130	impl_opaque_keys! {131		pub struct SessionKeys {132			pub aura: Aura,133		}134	}135}136137/// This runtime version.138pub const VERSION: RuntimeVersion = RuntimeVersion {139	spec_name: create_runtime_str!("quartz"),140	impl_name: create_runtime_str!("quartz"),141	authoring_version: 1,142	spec_version: 916001,143	impl_version: 0,144	apis: RUNTIME_API_VERSIONS,145	transaction_version: 1,146	state_version: 0,147};148149#[derive(codec::Encode, codec::Decode)]150pub enum XCMPMessage<XAccountId, XBalance> {151	/// Transfer tokens to the given account from the Parachain account.152	TransferToken(XAccountId, XBalance),153}154155/// The version information used to identify this runtime when compiled natively.156#[cfg(feature = "std")]157pub fn native_version() -> NativeVersion {158	NativeVersion {159		runtime_version: VERSION,160		can_author_with: Default::default(),161	}162}163164type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;165166pub struct DealWithFees;167impl OnUnbalanced<NegativeImbalance> for DealWithFees {168	fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {169		if let Some(fees) = fees_then_tips.next() {170			// for fees, 100% to treasury171			let mut split = fees.ration(100, 0);172			if let Some(tips) = fees_then_tips.next() {173				// for tips, if any, 100% to treasury174				tips.ration_merge_into(100, 0, &mut split);175			}176			Treasury::on_unbalanced(split.0);177			// Author::on_unbalanced(split.1);178		}179	}180}181182parameter_types! {183	pub const BlockHashCount: BlockNumber = 2400;184	pub RuntimeBlockLength: BlockLength =185		BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);186	pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);187	pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;188	pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()189		.base_block(BlockExecutionWeight::get())190		.for_class(DispatchClass::all(), |weights| {191			weights.base_extrinsic = ExtrinsicBaseWeight::get();192		})193		.for_class(DispatchClass::Normal, |weights| {194			weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);195		})196		.for_class(DispatchClass::Operational, |weights| {197			weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);198			// Operational transactions have some extra reserved space, so that they199			// are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.200			weights.reserved = Some(201				MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT202			);203		})204		.avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)205		.build_or_panic();206	pub const Version: RuntimeVersion = VERSION;207	pub const SS58Prefix: u8 = 255;208}209210parameter_types! {211	pub const ChainId: u64 = 8888;212}213214pub struct FixedFee;215impl FeeCalculator for FixedFee {216	fn min_gas_price() -> U256 {217		// Targeting 0.15 UNQ per transfer218		1_024_947_215_000u64.into()219	}220}221222// Assuming slowest ethereum opcode is SSTORE, with gas price of 20000 as our worst case223// (contract, which only writes a lot of data),224// approximating on top of our real store write weight225parameter_types! {226	pub const WritesPerSecond: u64 = WEIGHT_PER_SECOND / <Runtime as frame_system::Config>::DbWeight::get().write;227	pub const GasPerSecond: u64 = WritesPerSecond::get() * 20000;228	pub const WeightPerGas: u64 = WEIGHT_PER_SECOND / GasPerSecond::get();229}230231/// Limiting EVM execution to 50% of block for substrate users and management tasks232/// EVM transaction consumes more weight than substrate's, so we can't rely on them being233/// scheduled fairly234const EVM_DISPATCH_RATIO: Perbill = Perbill::from_percent(50);235parameter_types! {236	pub BlockGasLimit: U256 = U256::from(NORMAL_DISPATCH_RATIO * EVM_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT / WeightPerGas::get());237}238239pub enum FixedGasWeightMapping {}240impl GasWeightMapping for FixedGasWeightMapping {241	fn gas_to_weight(gas: u64) -> Weight {242		gas.saturating_mul(WeightPerGas::get())243	}244	fn weight_to_gas(weight: Weight) -> u64 {245		weight / WeightPerGas::get()246	}247}248249impl pallet_evm::Config for Runtime {250	type BlockGasLimit = BlockGasLimit;251	type FeeCalculator = FixedFee;252	type GasWeightMapping = FixedGasWeightMapping;253	type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;254	type CallOrigin = EnsureAddressTruncated;255	type WithdrawOrigin = EnsureAddressTruncated;256	type AddressMapping = HashedAddressMapping<Self::Hashing>;257	type PrecompilesType = ();258	type PrecompilesValue = ();259	type Currency = Balances;260	type Event = Event;261	type OnMethodCall = (262		pallet_evm_migration::OnMethodCall<Self>,263		pallet_unique::UniqueErcSupport<Self>,264		pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,265	);266	type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;267	type ChainId = ChainId;268	type Runner = pallet_evm::runner::stack::Runner<Self>;269	type OnChargeTransaction = pallet_evm_transaction_payment::OnChargeTransaction<Self>;270	type TransactionValidityHack = pallet_evm_transaction_payment::TransactionValidityHack<Self>;271	type FindAuthor = EthereumFindAuthor<Aura>;272}273274impl pallet_evm_migration::Config for Runtime {275	type WeightInfo = pallet_evm_migration::weights::SubstrateWeight<Self>;276}277278pub struct EthereumFindAuthor<F>(core::marker::PhantomData<F>);279impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F> {280	fn find_author<'a, I>(digests: I) -> Option<H160>281	where282		I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,283	{284		if let Some(author_index) = F::find_author(digests) {285			let authority_id = Aura::authorities()[author_index as usize].clone();286			return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24]));287		}288		None289	}290}291292impl pallet_ethereum::Config for Runtime {293	type Event = Event;294	type StateRoot = pallet_ethereum::IntermediateStateRoot;295}296297impl pallet_randomness_collective_flip::Config for Runtime {}298299impl frame_system::Config for Runtime {300	/// The data to be stored in an account.301	type AccountData = pallet_balances::AccountData<Balance>;302	/// The identifier used to distinguish between accounts.303	type AccountId = AccountId;304	/// The basic call filter to use in dispatchable.305	type BaseCallFilter = Everything;306	/// Maximum number of block number to block hash mappings to keep (oldest pruned first).307	type BlockHashCount = BlockHashCount;308	/// The maximum length of a block (in bytes).309	type BlockLength = RuntimeBlockLength;310	/// The index type for blocks.311	type BlockNumber = BlockNumber;312	/// The weight of the overhead invoked on the block import process, independent of the extrinsics included in that block.313	type BlockWeights = RuntimeBlockWeights;314	/// The aggregated dispatch type that is available for extrinsics.315	type Call = Call;316	/// The weight of database operations that the runtime can invoke.317	type DbWeight = RocksDbWeight;318	/// The ubiquitous event type.319	type Event = Event;320	/// The type for hashing blocks and tries.321	type Hash = Hash;322	/// The hashing algorithm used.323	type Hashing = BlakeTwo256;324	/// The header type.325	type Header = generic::Header<BlockNumber, BlakeTwo256>;326	/// The index type for storing how many extrinsics an account has signed.327	type Index = Index;328	/// The lookup mechanism to get account ID from whatever is passed in dispatchers.329	type Lookup = AccountIdLookup<AccountId, ()>;330	/// What to do if an account is fully reaped from the system.331	type OnKilledAccount = ();332	/// What to do if a new account is created.333	type OnNewAccount = ();334	type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;335	/// The ubiquitous origin type.336	type Origin = Origin;337	/// This type is being generated by `construct_runtime!`.338	type PalletInfo = PalletInfo;339	/// This is used as an identifier of the chain. 42 is the generic substrate prefix.340	type SS58Prefix = SS58Prefix;341	/// Weight information for the extrinsics of this pallet.342	type SystemWeightInfo = frame_system::weights::SubstrateWeight<Self>;343	/// Version of the runtime.344	type Version = Version;345	type MaxConsumers = ConstU32<16>;346}347348parameter_types! {349	pub const MinimumPeriod: u64 = SLOT_DURATION / 2;350}351352impl pallet_timestamp::Config for Runtime {353	/// A timestamp: milliseconds since the unix epoch.354	type Moment = u64;355	type OnTimestampSet = ();356	type MinimumPeriod = MinimumPeriod;357	type WeightInfo = ();358}359360parameter_types! {361	// pub const ExistentialDeposit: u128 = 500;362	pub const ExistentialDeposit: u128 = 0;363	pub const MaxLocks: u32 = 50;364}365366impl pallet_balances::Config for Runtime {367	type MaxLocks = MaxLocks;368	type MaxReserves = ();369	type ReserveIdentifier = [u8; 8];370	/// The type for recording an account's balance.371	type Balance = Balance;372	/// The ubiquitous event type.373	type Event = Event;374	type DustRemoval = Treasury;375	type ExistentialDeposit = ExistentialDeposit;376	type AccountStore = System;377	type WeightInfo = pallet_balances::weights::SubstrateWeight<Self>;378}379380pub const MICROUNIQUE: Balance = 1_000_000_000_000;381pub const MILLIUNIQUE: Balance = 1_000 * MICROUNIQUE;382pub const CENTIUNIQUE: Balance = 10 * MILLIUNIQUE;383pub const UNIQUE: Balance = 100 * CENTIUNIQUE;384385pub const fn deposit(items: u32, bytes: u32) -> Balance {386	items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE387}388389/*390parameter_types! {391	pub TombstoneDeposit: Balance = deposit(392		1,393		sp_std::mem::size_of::<pallet_contracts::Pallet<Runtime>> as u32,394	);395	pub DepositPerContract: Balance = TombstoneDeposit::get();396	pub const DepositPerStorageByte: Balance = deposit(0, 1);397	pub const DepositPerStorageItem: Balance = deposit(1, 0);398	pub RentFraction: Perbill = Perbill::from_rational(1u32, 30 * DAYS);399	pub const SurchargeReward: Balance = 150 * MILLIUNIQUE;400	pub const SignedClaimHandicap: u32 = 2;401	pub const MaxDepth: u32 = 32;402	pub const MaxValueSize: u32 = 16 * 1024;403	pub const MaxCodeSize: u32 = 1024 * 1024 * 25; // 25 Mb404	// The lazy deletion runs inside on_initialize.405	pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO *406		RuntimeBlockWeights::get().max_block;407	// The weight needed for decoding the queue should be less or equal than a fifth408	// of the overall weight dedicated to the lazy deletion.409	pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (410			<Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -411			<Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)412		)) / 5) as u32;413	pub Schedule: pallet_contracts::Schedule<Runtime> = Default::default();414}415416impl pallet_contracts::Config for Runtime {417	type Time = Timestamp;418	type Randomness = RandomnessCollectiveFlip;419	type Currency = Balances;420	type Event = Event;421	type RentPayment = ();422	type SignedClaimHandicap = SignedClaimHandicap;423	type TombstoneDeposit = TombstoneDeposit;424	type DepositPerContract = DepositPerContract;425	type DepositPerStorageByte = DepositPerStorageByte;426	type DepositPerStorageItem = DepositPerStorageItem;427	type RentFraction = RentFraction;428	type SurchargeReward = SurchargeReward;429	type WeightPrice = pallet_transaction_payment::Pallet<Self>;430	type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;431	type ChainExtension = NFTExtension;432	type DeletionQueueDepth = DeletionQueueDepth;433	type DeletionWeightLimit = DeletionWeightLimit;434	type Schedule = Schedule;435	type CallStack = [pallet_contracts::Frame<Self>; 31];436}437*/438439parameter_types! {440	pub const TransactionByteFee: Balance = 501 * MICROUNIQUE; // Targeting 0.1 Unique per NFT transfer441	/// This value increases the priority of `Operational` transactions by adding442	/// a "virtual tip" that's equal to the `OperationalFeeMultiplier * final_fee`.443	pub const OperationalFeeMultiplier: u8 = 5;444}445446/// Linear implementor of `WeightToFeePolynomial`447pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);448449impl<T> WeightToFeePolynomial for LinearFee<T>450where451	T: BaseArithmetic + From<u32> + Copy + Unsigned,452{453	type Balance = T;454455	fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {456		smallvec!(WeightToFeeCoefficient {457			// Targeting 0.1 Unique per NFT transfer458			coeff_integer: 142_688_000u32.into(),459			coeff_frac: Perbill::zero(),460			negative: false,461			degree: 1,462		})463	}464}465466impl pallet_transaction_payment::Config for Runtime {467	type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, DealWithFees>;468	type TransactionByteFee = TransactionByteFee;469	type OperationalFeeMultiplier = OperationalFeeMultiplier;470	type WeightToFee = LinearFee<Balance>;471	type FeeMultiplierUpdate = ();472}473474parameter_types! {475	pub const ProposalBond: Permill = Permill::from_percent(5);476	pub const ProposalBondMinimum: Balance = 1 * UNIQUE;477	pub const ProposalBondMaximum: Balance = 1000 * UNIQUE;478	pub const SpendPeriod: BlockNumber = 5 * MINUTES;479	pub const Burn: Permill = Permill::from_percent(0);480	pub const TipCountdown: BlockNumber = 1 * DAYS;481	pub const TipFindersFee: Percent = Percent::from_percent(20);482	pub const TipReportDepositBase: Balance = 1 * UNIQUE;483	pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;484	pub const BountyDepositBase: Balance = 1 * UNIQUE;485	pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;486	pub const TreasuryModuleId: PalletId = PalletId(*b"py/trsry");487	pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;488	pub const MaximumReasonLength: u32 = 16384;489	pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);490	pub const BountyValueMinimum: Balance = 5 * UNIQUE;491	pub const MaxApprovals: u32 = 100;492}493494impl pallet_treasury::Config for Runtime {495	type PalletId = TreasuryModuleId;496	type Currency = Balances;497	type ApproveOrigin = EnsureRoot<AccountId>;498	type RejectOrigin = EnsureRoot<AccountId>;499	type Event = Event;500	type OnSlash = ();501	type ProposalBond = ProposalBond;502	type ProposalBondMinimum = ProposalBondMinimum;503	type ProposalBondMaximum = ProposalBondMaximum;504	type SpendPeriod = SpendPeriod;505	type Burn = Burn;506	type BurnDestination = ();507	type SpendFunds = ();508	type WeightInfo = pallet_treasury::weights::SubstrateWeight<Self>;509	type MaxApprovals = MaxApprovals;510}511512impl pallet_sudo::Config for Runtime {513	type Event = Event;514	type Call = Call;515}516517pub struct RelayChainBlockNumberProvider<T>(sp_std::marker::PhantomData<T>);518519impl<T: cumulus_pallet_parachain_system::Config> BlockNumberProvider520	for RelayChainBlockNumberProvider<T>521{522	type BlockNumber = BlockNumber;523524	fn current_block_number() -> Self::BlockNumber {525		cumulus_pallet_parachain_system::Pallet::<T>::validation_data()526			.map(|d| d.relay_parent_number)527			.unwrap_or_default()528	}529}530531parameter_types! {532	pub const MinVestedTransfer: Balance = 10 * UNIQUE;533	pub const MaxVestingSchedules: u32 = 28;534}535536impl orml_vesting::Config for Runtime {537	type Event = Event;538	type Currency = pallet_balances::Pallet<Runtime>;539	type MinVestedTransfer = MinVestedTransfer;540	type VestedTransferOrigin = EnsureSigned<AccountId>;541	type WeightInfo = ();542	type MaxVestingSchedules = MaxVestingSchedules;543	type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;544}545546parameter_types! {547	pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;548	pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;549}550551impl cumulus_pallet_parachain_system::Config for Runtime {552	type Event = Event;553	type SelfParaId = parachain_info::Pallet<Self>;554	type OnSystemEvent = ();555	// type DownwardMessageHandlers = cumulus_primitives_utility::UnqueuedDmpAsParent<556	// 	MaxDownwardMessageWeight,557	// 	XcmExecutor<XcmConfig>,558	// 	Call,559	// >;560	type OutboundXcmpMessageSource = XcmpQueue;561	type DmpMessageHandler = DmpQueue;562	type ReservedDmpWeight = ReservedDmpWeight;563	type ReservedXcmpWeight = ReservedXcmpWeight;564	type XcmpMessageHandler = XcmpQueue;565}566567impl parachain_info::Config for Runtime {}568569impl cumulus_pallet_aura_ext::Config for Runtime {}570571parameter_types! {572	pub const RelayLocation: MultiLocation = MultiLocation::parent();573	pub const RelayNetwork: NetworkId = NetworkId::Polkadot;574	pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();575	pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();576}577578/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used579/// when determining ownership of accounts for asset transacting and when attempting to use XCM580/// `Transact` in order to determine the dispatch Origin.581pub type LocationToAccountId = (582	// The parent (Relay-chain) origin converts to the default `AccountId`.583	ParentIsDefault<AccountId>,584	// Sibling parachain origins convert to AccountId via the `ParaId::into`.585	SiblingParachainConvertsVia<Sibling, AccountId>,586	// Straight up local `AccountId32` origins just alias directly to `AccountId`.587	AccountId32Aliases<RelayNetwork, AccountId>,588);589590pub struct OnlySelfCurrency;591impl<B: TryFrom<u128>> MatchesFungible<B> for OnlySelfCurrency {592	fn matches_fungible(a: &MultiAsset) -> Option<B> {593		match (&a.id, &a.fun) {594			(Concrete(_), XcmFungible(ref amount)) => CheckedConversion::checked_from(*amount),595			_ => None,596		}597	}598}599600/// Means for transacting assets on this chain.601pub type LocalAssetTransactor = CurrencyAdapter<602	// Use this currency:603	Balances,604	// Use this currency when it is a fungible asset matching the given location or name:605	OnlySelfCurrency,606	// Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:607	LocationToAccountId,608	// Our chain's account ID type (we can't get away without mentioning it explicitly):609	AccountId,610	// We don't track any teleports.611	(),612>;613614/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,615/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can616/// biases the kind of local `Origin` it will become.617pub type XcmOriginToTransactDispatchOrigin = (618	// Sovereign account converter; this attempts to derive an `AccountId` from the origin location619	// using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for620	// foreign chains who want to have a local sovereign account on this chain which they control.621	SovereignSignedViaLocation<LocationToAccountId, Origin>,622	// Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when623	// recognised.624	RelayChainAsNative<RelayOrigin, Origin>,625	// Native converter for sibling Parachains; will convert to a `SiblingPara` origin when626	// recognised.627	SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,628	// Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a629	// transaction from the Root origin.630	ParentAsSuperuser<Origin>,631	// Native signed account converter; this just converts an `AccountId32` origin into a normal632	// `Origin::Signed` origin of the same 32-byte value.633	SignedAccountId32AsNative<RelayNetwork, Origin>,634	// Xcm origins can be represented natively under the Xcm pallet's Xcm origin.635	XcmPassthrough<Origin>,636);637638parameter_types! {639	// One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.640	pub UnitWeightCost: Weight = 1_000_000;641	// 1200 UNIQUEs buy 1 second of weight.642	pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);643	pub const MaxInstructions: u32 = 100;644	pub const MaxAuthorities: u32 = 100_000;645}646647match_type! {648	pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {649		MultiLocation { parents: 1, interior: Here } |650		MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }651	};652}653654pub type Barrier = (655	TakeWeightCredit,656	AllowTopLevelPaidExecutionFrom<Everything>,657	AllowUnpaidExecutionFrom<ParentOrParentsUnitPlurality>,658	// ^^^ Parent & its unit plurality gets free execution659);660661pub struct UsingOnlySelfCurrencyComponents<662	WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,663	AssetId: Get<MultiLocation>,664	AccountId,665	Currency: CurrencyT<AccountId>,666	OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,667>(668	Weight,669	Currency::Balance,670	PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>,671);672impl<673		WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,674		AssetId: Get<MultiLocation>,675		AccountId,676		Currency: CurrencyT<AccountId>,677		OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,678	> WeightTrader679	for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>680{681	fn new() -> Self {682		Self(0, Zero::zero(), PhantomData)683	}684685	fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {686		let amount = WeightToFee::calc(&weight);687		let u128_amount: u128 = amount.try_into().map_err(|_| XcmError::Overflow)?;688689		// location to this parachain through relay chain690		let option1: xcm::v1::AssetId = Concrete(MultiLocation {691			parents: 1,692			interior: X1(Parachain(ParachainInfo::parachain_id().into())),693		});694		// direct location695		let option2: xcm::v1::AssetId = Concrete(MultiLocation {696			parents: 0,697			interior: Here,698		});699700		let required = if payment.fungible.contains_key(&option1) {701			(option1, u128_amount).into()702		} else if payment.fungible.contains_key(&option2) {703			(option2, u128_amount).into()704		} else {705			(Concrete(MultiLocation::default()), u128_amount).into()706		};707708		let unused = payment709			.checked_sub(required)710			.map_err(|_| XcmError::TooExpensive)?;711		self.0 = self.0.saturating_add(weight);712		self.1 = self.1.saturating_add(amount);713		Ok(unused)714	}715716	fn refund_weight(&mut self, weight: Weight) -> Option<MultiAsset> {717		let weight = weight.min(self.0);718		let amount = WeightToFee::calc(&weight);719		self.0 -= weight;720		self.1 = self.1.saturating_sub(amount);721		let amount: u128 = amount.saturated_into();722		if amount > 0 {723			Some((AssetId::get(), amount).into())724		} else {725			None726		}727	}728}729impl<730		WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,731		AssetId: Get<MultiLocation>,732		AccountId,733		Currency: CurrencyT<AccountId>,734		OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,735	> Drop736	for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>737{738	fn drop(&mut self) {739		OnUnbalanced::on_unbalanced(Currency::issue(self.1));740	}741}742743pub struct XcmConfig;744impl Config for XcmConfig {745	type Call = Call;746	type XcmSender = XcmRouter;747	// How to withdraw and deposit an asset.748	type AssetTransactor = LocalAssetTransactor;749	type OriginConverter = XcmOriginToTransactDispatchOrigin;750	type IsReserve = NativeAsset;751	type IsTeleporter = (); // Teleportation is disabled752	type LocationInverter = LocationInverter<Ancestry>;753	type Barrier = Barrier;754	type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;755	type Trader = UsingOnlySelfCurrencyComponents<756		IdentityFee<Balance>,757		RelayLocation,758		AccountId,759		Balances,760		(),761	>;762	type ResponseHandler = (); // Don't handle responses for now.763	type SubscriptionService = PolkadotXcm;764765	type AssetTrap = PolkadotXcm;766	type AssetClaims = PolkadotXcm;767}768769// parameter_types! {770// 	pub const MaxDownwardMessageWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 10;771// }772773/// No local origins on this chain are allowed to dispatch XCM sends/executions.774pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);775776/// The means for routing XCM messages which are not for local execution into the right message777/// queues.778pub type XcmRouter = (779	// Two routers - use UMP to communicate with the relay chain:780	cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,781	// ..and XCMP to communicate with the sibling chains.782	XcmpQueue,783);784785impl pallet_evm_coder_substrate::Config for Runtime {786	type EthereumTransactionSender = pallet_ethereum::Pallet<Self>;787	type GasWeightMapping = FixedGasWeightMapping;788}789790impl pallet_xcm::Config for Runtime {791	type Event = Event;792	type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;793	type XcmRouter = XcmRouter;794	type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;795	type XcmExecuteFilter = Everything;796	type XcmExecutor = XcmExecutor<XcmConfig>;797	type XcmTeleportFilter = Everything;798	type XcmReserveTransferFilter = Everything;799	type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;800	type LocationInverter = LocationInverter<Ancestry>;801	type Origin = Origin;802	type Call = Call;803	const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;804	type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;805}806807impl cumulus_pallet_xcm::Config for Runtime {808	type Event = Event;809	type XcmExecutor = XcmExecutor<XcmConfig>;810}811812impl cumulus_pallet_xcmp_queue::Config for Runtime {813	type Event = Event;814	type XcmExecutor = XcmExecutor<XcmConfig>;815	type ChannelInfo = ParachainSystem;816	type VersionWrapper = ();817	type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;818}819820impl cumulus_pallet_dmp_queue::Config for Runtime {821	type Event = Event;822	type XcmExecutor = XcmExecutor<XcmConfig>;823	type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;824}825826impl pallet_aura::Config for Runtime {827	type AuthorityId = AuraId;828	type DisabledValidators = ();829	type MaxAuthorities = MaxAuthorities;830}831832parameter_types! {833	pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();834	pub const CollectionCreationPrice: Balance = 100 * UNIQUE;835}836837impl pallet_common::Config for Runtime {838	type Event = Event;839	type EvmBackwardsAddressMapping = up_evm_mapping::MapBackwardsAddressTruncated;840	type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;841	type CrossAccountId = pallet_common::account::BasicCrossAccountId<Self>;842843	type Currency = Balances;844	type CollectionCreationPrice = CollectionCreationPrice;845	type TreasuryAccountId = TreasuryAccountId;846}847848impl pallet_fungible::Config for Runtime {849	type WeightInfo = pallet_fungible::weights::SubstrateWeight<Self>;850}851impl pallet_refungible::Config for Runtime {852	type WeightInfo = pallet_refungible::weights::SubstrateWeight<Self>;853}854impl pallet_nonfungible::Config for Runtime {855	type WeightInfo = pallet_nonfungible::weights::SubstrateWeight<Self>;856}857858impl pallet_unique::Config for Runtime {859	type Event = Event;860	type WeightInfo = pallet_unique::weights::SubstrateWeight<Self>;861}862863parameter_types! {864	pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied865}866867/// Used for the pallet inflation868impl pallet_inflation::Config for Runtime {869	type Currency = Balances;870	type TreasuryAccountId = TreasuryAccountId;871	type InflationBlockInterval = InflationBlockInterval;872	type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;873}874875// parameter_types! {876// 	pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *877// 		RuntimeBlockWeights::get().max_block;878// 	pub const MaxScheduledPerBlock: u32 = 50;879// }880881type EvmSponsorshipHandler = (882	pallet_unique::UniqueEthSponsorshipHandler<Runtime>,883	pallet_evm_contract_helpers::HelpersContractSponsoring<Runtime>,884);885type SponsorshipHandler = (886	pallet_unique::UniqueSponsorshipHandler<Runtime>,887	//pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,888	pallet_evm_transaction_payment::BridgeSponsorshipHandler<Runtime>,889);890891// impl pallet_unq_scheduler::Config for Runtime {892// 	type Event = Event;893// 	type Origin = Origin;894// 	type PalletsOrigin = OriginCaller;895// 	type Call = Call;896// 	type MaximumWeight = MaximumSchedulerWeight;897// 	type ScheduleOrigin = EnsureSigned<AccountId>;898// 	type MaxScheduledPerBlock = MaxScheduledPerBlock;899// 	type SponsorshipHandler = SponsorshipHandler;900// 	type WeightInfo = ();901// }902903impl pallet_evm_transaction_payment::Config for Runtime {904	type EvmSponsorshipHandler = EvmSponsorshipHandler;905	type Currency = Balances;906	type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;907	type EvmBackwardsAddressMapping = up_evm_mapping::MapBackwardsAddressTruncated;908}909910impl pallet_charge_transaction::Config for Runtime {911	type SponsorshipHandler = SponsorshipHandler;912}913914// impl pallet_contract_helpers::Config for Runtime {915//	 type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;916// }917918parameter_types! {919	// 0x842899ECF380553E8a4de75bF534cdf6fBF64049920	pub const HelpersContractAddress: H160 = H160([921		0x84, 0x28, 0x99, 0xec, 0xf3, 0x80, 0x55, 0x3e, 0x8a, 0x4d, 0xe7, 0x5b, 0xf5, 0x34, 0xcd, 0xf6, 0xfb, 0xf6, 0x40, 0x49,922	]);923}924925impl pallet_evm_contract_helpers::Config for Runtime {926	type ContractAddress = HelpersContractAddress;927	type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;928}929930construct_runtime!(931	pub enum Runtime where932		Block = Block,933		NodeBlock = opaque::Block,934		UncheckedExtrinsic = UncheckedExtrinsic935	{936		ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Config, Storage, Inherent, Event<T>, ValidateUnsigned} = 20,937		ParachainInfo: parachain_info::{Pallet, Storage, Config} = 21,938939		Aura: pallet_aura::{Pallet, Config<T>} = 22,940		AuraExt: cumulus_pallet_aura_ext::{Pallet, Config} = 23,941942		Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 30,943		RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage} = 31,944		Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 32,945		TransactionPayment: pallet_transaction_payment::{Pallet, Storage} = 33,946		Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event<T>} = 34,947		Sudo: pallet_sudo::{Pallet, Call, Storage, Config<T>, Event<T>} = 35,948		System: frame_system::{Pallet, Call, Storage, Config, Event<T>} = 36,949		Vesting: orml_vesting::{Pallet, Storage, Call, Event<T>, Config<T>} = 37,950		// Vesting: pallet_vesting::{Pallet, Call, Config<T>, Storage, Event<T>} = 37,951		// Contracts: pallet_contracts::{Pallet, Call, Storage, Event<T>} = 38,952953		// XCM helpers.954		XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 50,955		PolkadotXcm: pallet_xcm::{Pallet, Call, Event<T>, Origin} = 51,956		CumulusXcm: cumulus_pallet_xcm::{Pallet, Call, Event<T>, Origin} = 52,957		DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,958959		// Unique Pallets960		Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,961		Unique: pallet_unique::{Pallet, Call, Storage, Event<T>} = 61,962		// Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,963		// free = 63964		Charging: pallet_charge_transaction::{Pallet, Call, Storage } = 64,965		// ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,966		Common: pallet_common::{Pallet, Storage, Event<T>} = 66,967		Fungible: pallet_fungible::{Pallet, Storage} = 67,968		Refungible: pallet_refungible::{Pallet, Storage} = 68,969		Nonfungible: pallet_nonfungible::{Pallet, Storage} = 69,970971		// Frontier972		EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,973		Ethereum: pallet_ethereum::{Pallet, Config, Call, Storage, Event, Origin} = 101,974975		EvmCoderSubstrate: pallet_evm_coder_substrate::{Pallet, Storage} = 150,976		EvmContractHelpers: pallet_evm_contract_helpers::{Pallet, Storage} = 151,977		EvmTransactionPayment: pallet_evm_transaction_payment::{Pallet} = 152,978		EvmMigration: pallet_evm_migration::{Pallet, Call, Storage} = 153,979	}980);981982pub struct TransactionConverter;983984impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {985	fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {986		UncheckedExtrinsic::new_unsigned(987			pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),988		)989	}990}991992impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {993	fn convert_transaction(994		&self,995		transaction: pallet_ethereum::Transaction,996	) -> opaque::UncheckedExtrinsic {997		let extrinsic = UncheckedExtrinsic::new_unsigned(998			pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),999		);1000		let encoded = extrinsic.encode();1001		opaque::UncheckedExtrinsic::decode(&mut &encoded[..])1002			.expect("Encoded extrinsic is always valid")1003	}1004}10051006/// The address format for describing accounts.1007pub type Address = sp_runtime::MultiAddress<AccountId, ()>;1008/// Block header type as expected by this runtime.1009pub type Header = generic::Header<BlockNumber, BlakeTwo256>;1010/// Block type as expected by this runtime.1011pub type Block = generic::Block<Header, UncheckedExtrinsic>;1012/// A Block signed with a Justification1013pub type SignedBlock = generic::SignedBlock<Block>;1014/// BlockId type as expected by this runtime.1015pub type BlockId = generic::BlockId<Block>;1016/// The SignedExtension to the basic transaction logic.1017pub type SignedExtra = (1018	frame_system::CheckSpecVersion<Runtime>,1019	// system::CheckTxVersion<Runtime>,1020	frame_system::CheckGenesis<Runtime>,1021	frame_system::CheckEra<Runtime>,1022	frame_system::CheckNonce<Runtime>,1023	frame_system::CheckWeight<Runtime>,1024	pallet_charge_transaction::ChargeTransactionPayment<Runtime>,1025	//pallet_contract_helpers::ContractHelpersExtension<Runtime>,1026);1027/// Unchecked extrinsic type as expected by this runtime.1028pub type UncheckedExtrinsic =1029	fp_self_contained::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;1030/// Extrinsic type that has already been checked.1031pub type CheckedExtrinsic = fp_self_contained::CheckedExtrinsic<AccountId, Call, SignedExtra, H160>;1032/// Executive: handles dispatch to the various modules.1033pub type Executive = frame_executive::Executive<1034	Runtime,1035	Block,1036	frame_system::ChainContext<Runtime>,1037	Runtime,1038	AllPalletsReversedWithSystemFirst,1039>;10401041impl_opaque_keys! {1042	pub struct SessionKeys {1043		pub aura: Aura,1044	}1045}10461047impl fp_self_contained::SelfContainedCall for Call {1048	type SignedInfo = H160;10491050	fn is_self_contained(&self) -> bool {1051		match self {1052			Call::Ethereum(call) => call.is_self_contained(),1053			_ => false,1054		}1055	}10561057	fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {1058		match self {1059			Call::Ethereum(call) => call.check_self_contained(),1060			_ => None,1061		}1062	}10631064	fn validate_self_contained(&self, info: &Self::SignedInfo) -> Option<TransactionValidity> {1065		match self {1066			Call::Ethereum(call) => call.validate_self_contained(info),1067			_ => None,1068		}1069	}10701071	fn pre_dispatch_self_contained(1072		&self,1073		info: &Self::SignedInfo,1074	) -> Option<Result<(), TransactionValidityError>> {1075		match self {1076			Call::Ethereum(call) => call.pre_dispatch_self_contained(info),1077			_ => None,1078		}1079	}10801081	fn apply_self_contained(1082		self,1083		info: Self::SignedInfo,1084	) -> Option<sp_runtime::DispatchResultWithInfo<PostDispatchInfoOf<Self>>> {1085		match self {1086			call @ Call::Ethereum(pallet_ethereum::Call::transact { .. }) => Some(call.dispatch(1087				Origin::from(pallet_ethereum::RawOrigin::EthereumTransaction(info)),1088			)),1089			_ => None,1090		}1091	}1092}10931094macro_rules! dispatch_unique_runtime {1095	($collection:ident.$method:ident($($name:ident),*)) => {{1096		use pallet_unique::dispatch::Dispatched;10971098		let collection = Dispatched::dispatch(<pallet_common::CollectionHandle<Runtime>>::try_get($collection)?);1099		let dispatch = collection.as_dyn();11001101		Ok(dispatch.$method($($name),*))1102	}};1103}1104impl_runtime_apis! {1105	impl up_rpc::UniqueApi<Block, CrossAccountId, AccountId>1106		for Runtime1107	{1108		fn account_tokens(collection: CollectionId, account: CrossAccountId) -> Result<Vec<TokenId>, DispatchError> {1109			dispatch_unique_runtime!(collection.account_tokens(account))1110		}1111		fn token_exists(collection: CollectionId, token: TokenId) -> Result<bool, DispatchError> {1112			dispatch_unique_runtime!(collection.token_exists(token))1113		}11141115		fn token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>, DispatchError> {1116			dispatch_unique_runtime!(collection.token_owner(token))1117		}1118		fn const_metadata(collection: CollectionId, token: TokenId) -> Result<Vec<u8>, DispatchError> {1119			dispatch_unique_runtime!(collection.const_metadata(token))1120		}1121		fn variable_metadata(collection: CollectionId, token: TokenId) -> Result<Vec<u8>, DispatchError> {1122			dispatch_unique_runtime!(collection.variable_metadata(token))1123		}11241125		fn collection_tokens(collection: CollectionId) -> Result<u32, DispatchError> {1126			dispatch_unique_runtime!(collection.collection_tokens())1127		}1128		fn account_balance(collection: CollectionId, account: CrossAccountId) -> Result<u32, DispatchError> {1129			dispatch_unique_runtime!(collection.account_balance(account))1130		}1131		fn balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<u128, DispatchError> {1132			dispatch_unique_runtime!(collection.balance(account, token))1133		}1134		fn allowance(1135			collection: CollectionId,1136			sender: CrossAccountId,1137			spender: CrossAccountId,1138			token: TokenId,1139		) -> Result<u128, DispatchError> {1140			dispatch_unique_runtime!(collection.allowance(sender, spender, token))1141		}11421143		fn eth_contract_code(account: H160) -> Option<Vec<u8>> {1144			<pallet_unique::UniqueErcSupport<Runtime>>::get_code(&account)1145				.or_else(|| <pallet_evm_migration::OnMethodCall<Runtime>>::get_code(&account))1146				.or_else(|| <pallet_evm_contract_helpers::HelpersOnMethodCall<Self>>::get_code(&account))1147		}1148		fn adminlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {1149			Ok(<pallet_common::Pallet<Runtime>>::adminlist(collection))1150		}1151		fn allowlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {1152			Ok(<pallet_common::Pallet<Runtime>>::allowlist(collection))1153		}1154		fn allowed(collection: CollectionId, user: CrossAccountId) -> Result<bool, DispatchError> {1155			Ok(<pallet_common::Pallet<Runtime>>::allowed(collection, user))1156		}1157		fn last_token_id(collection: CollectionId) -> Result<TokenId, DispatchError> {1158			dispatch_unique_runtime!(collection.last_token_id())1159		}1160		fn collection_by_id(collection: CollectionId) -> Result<Option<Collection<AccountId>>, DispatchError> {1161			Ok(<pallet_common::CollectionById<Runtime>>::get(collection))1162		}1163		fn collection_stats() -> Result<CollectionStats, DispatchError> {1164			Ok(<pallet_common::Pallet<Runtime>>::collection_stats())1165		}1166	}11671168	impl sp_api::Core<Block> for Runtime {1169		fn version() -> RuntimeVersion {1170			VERSION1171		}11721173		fn execute_block(block: Block) {1174			Executive::execute_block(block)1175		}11761177		fn initialize_block(header: &<Block as BlockT>::Header) {1178			Executive::initialize_block(header)1179		}1180	}11811182	impl sp_api::Metadata<Block> for Runtime {1183		fn metadata() -> OpaqueMetadata {1184			OpaqueMetadata::new(Runtime::metadata().into())1185		}1186	}11871188	impl sp_block_builder::BlockBuilder<Block> for Runtime {1189		fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {1190			Executive::apply_extrinsic(extrinsic)1191		}11921193		fn finalize_block() -> <Block as BlockT>::Header {1194			Executive::finalize_block()1195		}11961197		fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {1198			data.create_extrinsics()1199		}12001201		fn check_inherents(1202			block: Block,1203			data: sp_inherents::InherentData,1204		) -> sp_inherents::CheckInherentsResult {1205			data.check_extrinsics(&block)1206		}12071208		// fn random_seed() -> <Block as BlockT>::Hash {1209		//     RandomnessCollectiveFlip::random_seed().01210		// }1211	}12121213	impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {1214		fn validate_transaction(1215			source: TransactionSource,1216			tx: <Block as BlockT>::Extrinsic,1217			hash: <Block as BlockT>::Hash,1218		) -> TransactionValidity {1219			Executive::validate_transaction(source, tx, hash)1220		}1221	}12221223	impl sp_offchain::OffchainWorkerApi<Block> for Runtime {1224		fn offchain_worker(header: &<Block as BlockT>::Header) {1225			Executive::offchain_worker(header)1226		}1227	}12281229	impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {1230		fn chain_id() -> u64 {1231			<Runtime as pallet_evm::Config>::ChainId::get()1232		}12331234		fn account_basic(address: H160) -> EVMAccount {1235			EVM::account_basic(&address)1236		}12371238		fn gas_price() -> U256 {1239			<Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price()1240		}12411242		fn account_code_at(address: H160) -> Vec<u8> {1243			EVM::account_codes(address)1244		}12451246		fn author() -> H160 {1247			<pallet_evm::Pallet<Runtime>>::find_author()1248		}12491250		fn storage_at(address: H160, index: U256) -> H256 {1251			let mut tmp = [0u8; 32];1252			index.to_big_endian(&mut tmp);1253			EVM::account_storages(address, H256::from_slice(&tmp[..]))1254		}12551256		#[allow(clippy::redundant_closure)]1257		fn call(1258			from: H160,1259			to: H160,1260			data: Vec<u8>,1261			value: U256,1262			gas_limit: U256,1263			max_fee_per_gas: Option<U256>,1264			max_priority_fee_per_gas: Option<U256>,1265			nonce: Option<U256>,1266			estimate: bool,1267			access_list: Option<Vec<(H160, Vec<H256>)>>,1268		) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {1269			let config = if estimate {1270				let mut config = <Runtime as pallet_evm::Config>::config().clone();1271				config.estimate = true;1272				Some(config)1273			} else {1274				None1275			};12761277			<Runtime as pallet_evm::Config>::Runner::call(1278				from,1279				to,1280				data,1281				value,1282				gas_limit.low_u64(),1283				max_fee_per_gas,1284				max_priority_fee_per_gas,1285				nonce,1286				access_list.unwrap_or_default(),1287				config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),1288			).map_err(|err| err.into())1289		}12901291		#[allow(clippy::redundant_closure)]1292		fn create(1293			from: H160,1294			data: Vec<u8>,1295			value: U256,1296			gas_limit: U256,1297			max_fee_per_gas: Option<U256>,1298			max_priority_fee_per_gas: Option<U256>,1299			nonce: Option<U256>,1300			estimate: bool,1301			access_list: Option<Vec<(H160, Vec<H256>)>>,1302		) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {1303			let config = if estimate {1304				let mut config = <Runtime as pallet_evm::Config>::config().clone();1305				config.estimate = true;1306				Some(config)1307			} else {1308				None1309			};13101311			<Runtime as pallet_evm::Config>::Runner::create(1312				from,1313				data,1314				value,1315				gas_limit.low_u64(),1316				max_fee_per_gas,1317				max_priority_fee_per_gas,1318				nonce,1319				access_list.unwrap_or_default(),1320				config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),1321			).map_err(|err| err.into())1322		}13231324		fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {1325			Ethereum::current_transaction_statuses()1326		}13271328		fn current_block() -> Option<pallet_ethereum::Block> {1329			Ethereum::current_block()1330		}13311332		fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {1333			Ethereum::current_receipts()1334		}13351336		fn current_all() -> (1337			Option<pallet_ethereum::Block>,1338			Option<Vec<pallet_ethereum::Receipt>>,1339			Option<Vec<TransactionStatus>>1340		) {1341			(1342				Ethereum::current_block(),1343				Ethereum::current_receipts(),1344				Ethereum::current_transaction_statuses()1345			)1346		}13471348		fn extrinsic_filter(xts: Vec<<Block as sp_api::BlockT>::Extrinsic>) -> Vec<pallet_ethereum::Transaction> {1349			xts.into_iter().filter_map(|xt| match xt.0.function {1350				Call::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction),1351				_ => None1352			}).collect()1353		}13541355		fn elasticity() -> Option<Permill> {1356			None1357		}1358	}13591360	impl sp_session::SessionKeys<Block> for Runtime {1361		fn decode_session_keys(1362			encoded: Vec<u8>,1363		) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {1364			SessionKeys::decode_into_raw_public_keys(&encoded)1365		}13661367		fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {1368			SessionKeys::generate(seed)1369		}1370	}13711372	impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {1373		fn slot_duration() -> sp_consensus_aura::SlotDuration {1374			sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())1375		}13761377		fn authorities() -> Vec<AuraId> {1378			Aura::authorities().to_vec()1379		}1380	}13811382	impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {1383		fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {1384			ParachainSystem::collect_collation_info(header)1385		}1386	}13871388	impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {1389		fn account_nonce(account: AccountId) -> Index {1390			System::account_nonce(account)1391		}1392	}13931394	impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {1395		fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {1396			TransactionPayment::query_info(uxt, len)1397		}1398		fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {1399			TransactionPayment::query_fee_details(uxt, len)1400		}1401	}14021403	/*1404	impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber, Hash>1405		for Runtime1406	{1407		fn call(1408			origin: AccountId,1409			dest: AccountId,1410			value: Balance,1411			gas_limit: u64,1412			input_data: Vec<u8>,1413		) -> pallet_contracts_primitives::ContractExecResult {1414			Contracts::bare_call(origin, dest, value, gas_limit, input_data, false)1415		}14161417		fn instantiate(1418			origin: AccountId,1419			endowment: Balance,1420			gas_limit: u64,1421			code: pallet_contracts_primitives::Code<Hash>,1422			data: Vec<u8>,1423			salt: Vec<u8>,1424		) -> pallet_contracts_primitives::ContractInstantiateResult<AccountId, BlockNumber>1425		{1426			Contracts::bare_instantiate(origin, endowment, gas_limit, code, data, salt, true, false)1427		}14281429		fn get_storage(1430			address: AccountId,1431			key: [u8; 32],1432		) -> pallet_contracts_primitives::GetStorageResult {1433			Contracts::get_storage(address, key)1434		}14351436		fn rent_projection(1437			address: AccountId,1438		) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {1439			Contracts::rent_projection(address)1440		}1441	}1442	*/14431444	#[cfg(feature = "runtime-benchmarks")]1445	impl frame_benchmarking::Benchmark<Block> for Runtime {1446		fn benchmark_metadata(extra: bool) -> (1447			Vec<frame_benchmarking::BenchmarkList>,1448			Vec<frame_support::traits::StorageInfo>,1449		) {1450			use frame_benchmarking::{list_benchmark, Benchmarking, BenchmarkList};1451			use frame_support::traits::StorageInfoTrait;14521453			let mut list = Vec::<BenchmarkList>::new();14541455			list_benchmark!(list, extra, pallet_evm_migration, EvmMigration);1456			list_benchmark!(list, extra, pallet_unique, Unique);1457			list_benchmark!(list, extra, pallet_inflation, Inflation);1458			list_benchmark!(list, extra, pallet_fungible, Fungible);1459			list_benchmark!(list, extra, pallet_refungible, Refungible);1460			list_benchmark!(list, extra, pallet_nonfungible, Nonfungible);1461			// list_benchmark!(list, extra, pallet_evm_coder_substrate, EvmCoderSubstrate);14621463			let storage_info = AllPalletsReversedWithSystemFirst::storage_info();14641465			return (list, storage_info)1466		}14671468		fn dispatch_benchmark(1469			config: frame_benchmarking::BenchmarkConfig1470		) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {1471			use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};14721473			let allowlist: Vec<TrackedStorageKey> = vec![1474				// Block Number1475				hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),1476				// Total Issuance1477				hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),1478				// Execution Phase1479				hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),1480				// Event Count1481				hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),1482				// System Events1483				hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),1484			];14851486			let mut batches = Vec::<BenchmarkBatch>::new();1487			let params = (&config, &allowlist);14881489			add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);1490			add_benchmark!(params, batches, pallet_unique, Unique);1491			add_benchmark!(params, batches, pallet_inflation, Inflation);1492			add_benchmark!(params, batches, pallet_fungible, Fungible);1493			add_benchmark!(params, batches, pallet_refungible, Refungible);1494			add_benchmark!(params, batches, pallet_nonfungible, Nonfungible);1495			// add_benchmark!(params, batches, pallet_evm_coder_substrate, EvmCoderSubstrate);14961497			if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }1498			Ok(batches)1499		}1500	}1501}15021503struct CheckInherents;15041505impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {1506	fn check_inherents(1507		block: &Block,1508		relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,1509	) -> sp_inherents::CheckInherentsResult {1510		let relay_chain_slot = relay_state_proof1511			.read_slot()1512			.expect("Could not read the relay chain slot from the proof");15131514		let inherent_data =1515			cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(1516				relay_chain_slot,1517				sp_std::time::Duration::from_secs(6),1518			)1519			.create_inherent_data()1520			.expect("Could not create the timestamp inherent data");15211522		inherent_data.check_extrinsics(block)1523	}1524}15251526cumulus_pallet_parachain_system::register_validate_block!(1527	Runtime = Runtime,1528	BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,1529	CheckInherents = CheckInherents,1530);