git.delta.rocks / unique-network / refs/commits / 4657e257e343

difftreelog

source

runtime/quartz/src/lib.rs51.7 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 type CrossAccountId = pallet_common::account::BasicCrossAccountId<Runtime>;115116/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know117/// the specifics of the runtime. They can then be made to be agnostic over specific formats118/// of data like extrinsics, allowing for them to continue syncing the network through upgrades119/// to even the core data structures.120pub mod opaque {121	use sp_std::prelude::*;122	use sp_runtime::impl_opaque_keys;123	use super::Aura;124125	pub use unique_runtime_common::types::*;126	pub use super::CrossAccountId;127128	impl_opaque_keys! {129		pub struct SessionKeys {130			pub aura: Aura,131		}132	}133}134135/// This runtime version.136pub const VERSION: RuntimeVersion = RuntimeVersion {137	spec_name: create_runtime_str!("quartz"),138	impl_name: create_runtime_str!("quartz"),139	authoring_version: 1,140	spec_version: 916001,141	impl_version: 0,142	apis: RUNTIME_API_VERSIONS,143	transaction_version: 1,144	state_version: 0,145};146147#[derive(codec::Encode, codec::Decode)]148pub enum XCMPMessage<XAccountId, XBalance> {149	/// Transfer tokens to the given account from the Parachain account.150	TransferToken(XAccountId, XBalance),151}152153/// The version information used to identify this runtime when compiled natively.154#[cfg(feature = "std")]155pub fn native_version() -> NativeVersion {156	NativeVersion {157		runtime_version: VERSION,158		can_author_with: Default::default(),159	}160}161162type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;163164pub struct DealWithFees;165impl OnUnbalanced<NegativeImbalance> for DealWithFees {166	fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {167		if let Some(fees) = fees_then_tips.next() {168			// for fees, 100% to treasury169			let mut split = fees.ration(100, 0);170			if let Some(tips) = fees_then_tips.next() {171				// for tips, if any, 100% to treasury172				tips.ration_merge_into(100, 0, &mut split);173			}174			Treasury::on_unbalanced(split.0);175			// Author::on_unbalanced(split.1);176		}177	}178}179180parameter_types! {181	pub const BlockHashCount: BlockNumber = 2400;182	pub RuntimeBlockLength: BlockLength =183		BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);184	pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);185	pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;186	pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()187		.base_block(BlockExecutionWeight::get())188		.for_class(DispatchClass::all(), |weights| {189			weights.base_extrinsic = ExtrinsicBaseWeight::get();190		})191		.for_class(DispatchClass::Normal, |weights| {192			weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);193		})194		.for_class(DispatchClass::Operational, |weights| {195			weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);196			// Operational transactions have some extra reserved space, so that they197			// are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.198			weights.reserved = Some(199				MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT200			);201		})202		.avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)203		.build_or_panic();204	pub const Version: RuntimeVersion = VERSION;205	pub const SS58Prefix: u8 = 255;206}207208parameter_types! {209	pub const ChainId: u64 = 8888;210}211212pub struct FixedFee;213impl FeeCalculator for FixedFee {214	fn min_gas_price() -> U256 {215		// Targeting 0.15 UNQ per transfer216		1_024_947_215_000u64.into()217	}218}219220// Assuming slowest ethereum opcode is SSTORE, with gas price of 20000 as our worst case221// (contract, which only writes a lot of data),222// approximating on top of our real store write weight223parameter_types! {224	pub const WritesPerSecond: u64 = WEIGHT_PER_SECOND / <Runtime as frame_system::Config>::DbWeight::get().write;225	pub const GasPerSecond: u64 = WritesPerSecond::get() * 20000;226	pub const WeightPerGas: u64 = WEIGHT_PER_SECOND / GasPerSecond::get();227}228229/// Limiting EVM execution to 50% of block for substrate users and management tasks230/// EVM transaction consumes more weight than substrate's, so we can't rely on them being231/// scheduled fairly232const EVM_DISPATCH_RATIO: Perbill = Perbill::from_percent(50);233parameter_types! {234	pub BlockGasLimit: U256 = U256::from(NORMAL_DISPATCH_RATIO * EVM_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT / WeightPerGas::get());235}236237pub enum FixedGasWeightMapping {}238impl GasWeightMapping for FixedGasWeightMapping {239	fn gas_to_weight(gas: u64) -> Weight {240		gas.saturating_mul(WeightPerGas::get())241	}242	fn weight_to_gas(weight: Weight) -> u64 {243		weight / WeightPerGas::get()244	}245}246247impl pallet_evm::Config for Runtime {248	type BlockGasLimit = BlockGasLimit;249	type FeeCalculator = FixedFee;250	type GasWeightMapping = FixedGasWeightMapping;251	type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;252	type CallOrigin = EnsureAddressTruncated;253	type WithdrawOrigin = EnsureAddressTruncated;254	type AddressMapping = HashedAddressMapping<Self::Hashing>;255	type PrecompilesType = ();256	type PrecompilesValue = ();257	type Currency = Balances;258	type Event = Event;259	type OnMethodCall = (260		pallet_evm_migration::OnMethodCall<Self>,261		pallet_unique::UniqueErcSupport<Self>,262		pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,263	);264	type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;265	type ChainId = ChainId;266	type Runner = pallet_evm::runner::stack::Runner<Self>;267	type OnChargeTransaction = pallet_evm_transaction_payment::OnChargeTransaction<Self>;268	type TransactionValidityHack = pallet_evm_transaction_payment::TransactionValidityHack<Self>;269	type FindAuthor = EthereumFindAuthor<Aura>;270}271272impl pallet_evm_migration::Config for Runtime {273	type WeightInfo = pallet_evm_migration::weights::SubstrateWeight<Self>;274}275276pub struct EthereumFindAuthor<F>(core::marker::PhantomData<F>);277impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F> {278	fn find_author<'a, I>(digests: I) -> Option<H160>279	where280		I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,281	{282		if let Some(author_index) = F::find_author(digests) {283			let authority_id = Aura::authorities()[author_index as usize].clone();284			return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24]));285		}286		None287	}288}289290impl pallet_ethereum::Config for Runtime {291	type Event = Event;292	type StateRoot = pallet_ethereum::IntermediateStateRoot;293}294295impl pallet_randomness_collective_flip::Config for Runtime {}296297impl frame_system::Config for Runtime {298	/// The data to be stored in an account.299	type AccountData = pallet_balances::AccountData<Balance>;300	/// The identifier used to distinguish between accounts.301	type AccountId = AccountId;302	/// The basic call filter to use in dispatchable.303	type BaseCallFilter = Everything;304	/// Maximum number of block number to block hash mappings to keep (oldest pruned first).305	type BlockHashCount = BlockHashCount;306	/// The maximum length of a block (in bytes).307	type BlockLength = RuntimeBlockLength;308	/// The index type for blocks.309	type BlockNumber = BlockNumber;310	/// The weight of the overhead invoked on the block import process, independent of the extrinsics included in that block.311	type BlockWeights = RuntimeBlockWeights;312	/// The aggregated dispatch type that is available for extrinsics.313	type Call = Call;314	/// The weight of database operations that the runtime can invoke.315	type DbWeight = RocksDbWeight;316	/// The ubiquitous event type.317	type Event = Event;318	/// The type for hashing blocks and tries.319	type Hash = Hash;320	/// The hashing algorithm used.321	type Hashing = BlakeTwo256;322	/// The header type.323	type Header = generic::Header<BlockNumber, BlakeTwo256>;324	/// The index type for storing how many extrinsics an account has signed.325	type Index = Index;326	/// The lookup mechanism to get account ID from whatever is passed in dispatchers.327	type Lookup = AccountIdLookup<AccountId, ()>;328	/// What to do if an account is fully reaped from the system.329	type OnKilledAccount = ();330	/// What to do if a new account is created.331	type OnNewAccount = ();332	type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;333	/// The ubiquitous origin type.334	type Origin = Origin;335	/// This type is being generated by `construct_runtime!`.336	type PalletInfo = PalletInfo;337	/// This is used as an identifier of the chain. 42 is the generic substrate prefix.338	type SS58Prefix = SS58Prefix;339	/// Weight information for the extrinsics of this pallet.340	type SystemWeightInfo = frame_system::weights::SubstrateWeight<Self>;341	/// Version of the runtime.342	type Version = Version;343	type MaxConsumers = ConstU32<16>;344}345346parameter_types! {347	pub const MinimumPeriod: u64 = SLOT_DURATION / 2;348}349350impl pallet_timestamp::Config for Runtime {351	/// A timestamp: milliseconds since the unix epoch.352	type Moment = u64;353	type OnTimestampSet = ();354	type MinimumPeriod = MinimumPeriod;355	type WeightInfo = ();356}357358parameter_types! {359	// pub const ExistentialDeposit: u128 = 500;360	pub const ExistentialDeposit: u128 = 0;361	pub const MaxLocks: u32 = 50;362}363364impl pallet_balances::Config for Runtime {365	type MaxLocks = MaxLocks;366	type MaxReserves = ();367	type ReserveIdentifier = [u8; 8];368	/// The type for recording an account's balance.369	type Balance = Balance;370	/// The ubiquitous event type.371	type Event = Event;372	type DustRemoval = Treasury;373	type ExistentialDeposit = ExistentialDeposit;374	type AccountStore = System;375	type WeightInfo = pallet_balances::weights::SubstrateWeight<Self>;376}377378pub const MICROUNIQUE: Balance = 1_000_000_000_000;379pub const MILLIUNIQUE: Balance = 1_000 * MICROUNIQUE;380pub const CENTIUNIQUE: Balance = 10 * MILLIUNIQUE;381pub const UNIQUE: Balance = 100 * CENTIUNIQUE;382383pub const fn deposit(items: u32, bytes: u32) -> Balance {384	items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE385}386387/*388parameter_types! {389	pub TombstoneDeposit: Balance = deposit(390		1,391		sp_std::mem::size_of::<pallet_contracts::Pallet<Runtime>> as u32,392	);393	pub DepositPerContract: Balance = TombstoneDeposit::get();394	pub const DepositPerStorageByte: Balance = deposit(0, 1);395	pub const DepositPerStorageItem: Balance = deposit(1, 0);396	pub RentFraction: Perbill = Perbill::from_rational(1u32, 30 * DAYS);397	pub const SurchargeReward: Balance = 150 * MILLIUNIQUE;398	pub const SignedClaimHandicap: u32 = 2;399	pub const MaxDepth: u32 = 32;400	pub const MaxValueSize: u32 = 16 * 1024;401	pub const MaxCodeSize: u32 = 1024 * 1024 * 25; // 25 Mb402	// The lazy deletion runs inside on_initialize.403	pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO *404		RuntimeBlockWeights::get().max_block;405	// The weight needed for decoding the queue should be less or equal than a fifth406	// of the overall weight dedicated to the lazy deletion.407	pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (408			<Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -409			<Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)410		)) / 5) as u32;411	pub Schedule: pallet_contracts::Schedule<Runtime> = Default::default();412}413414impl pallet_contracts::Config for Runtime {415	type Time = Timestamp;416	type Randomness = RandomnessCollectiveFlip;417	type Currency = Balances;418	type Event = Event;419	type RentPayment = ();420	type SignedClaimHandicap = SignedClaimHandicap;421	type TombstoneDeposit = TombstoneDeposit;422	type DepositPerContract = DepositPerContract;423	type DepositPerStorageByte = DepositPerStorageByte;424	type DepositPerStorageItem = DepositPerStorageItem;425	type RentFraction = RentFraction;426	type SurchargeReward = SurchargeReward;427	type WeightPrice = pallet_transaction_payment::Pallet<Self>;428	type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;429	type ChainExtension = NFTExtension;430	type DeletionQueueDepth = DeletionQueueDepth;431	type DeletionWeightLimit = DeletionWeightLimit;432	type Schedule = Schedule;433	type CallStack = [pallet_contracts::Frame<Self>; 31];434}435*/436437parameter_types! {438	pub const TransactionByteFee: Balance = 501 * MICROUNIQUE; // Targeting 0.1 Unique per NFT transfer439	/// This value increases the priority of `Operational` transactions by adding440	/// a "virtual tip" that's equal to the `OperationalFeeMultiplier * final_fee`.441	pub const OperationalFeeMultiplier: u8 = 5;442}443444/// Linear implementor of `WeightToFeePolynomial`445pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);446447impl<T> WeightToFeePolynomial for LinearFee<T>448where449	T: BaseArithmetic + From<u32> + Copy + Unsigned,450{451	type Balance = T;452453	fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {454		smallvec!(WeightToFeeCoefficient {455			// Targeting 0.1 Unique per NFT transfer456			coeff_integer: 142_688_000u32.into(),457			coeff_frac: Perbill::zero(),458			negative: false,459			degree: 1,460		})461	}462}463464impl pallet_transaction_payment::Config for Runtime {465	type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, DealWithFees>;466	type TransactionByteFee = TransactionByteFee;467	type OperationalFeeMultiplier = OperationalFeeMultiplier;468	type WeightToFee = LinearFee<Balance>;469	type FeeMultiplierUpdate = ();470}471472parameter_types! {473	pub const ProposalBond: Permill = Permill::from_percent(5);474	pub const ProposalBondMinimum: Balance = 1 * UNIQUE;475	pub const ProposalBondMaximum: Balance = 1000 * UNIQUE;476	pub const SpendPeriod: BlockNumber = 5 * MINUTES;477	pub const Burn: Permill = Permill::from_percent(0);478	pub const TipCountdown: BlockNumber = 1 * DAYS;479	pub const TipFindersFee: Percent = Percent::from_percent(20);480	pub const TipReportDepositBase: Balance = 1 * UNIQUE;481	pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;482	pub const BountyDepositBase: Balance = 1 * UNIQUE;483	pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;484	pub const TreasuryModuleId: PalletId = PalletId(*b"py/trsry");485	pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;486	pub const MaximumReasonLength: u32 = 16384;487	pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);488	pub const BountyValueMinimum: Balance = 5 * UNIQUE;489	pub const MaxApprovals: u32 = 100;490}491492impl pallet_treasury::Config for Runtime {493	type PalletId = TreasuryModuleId;494	type Currency = Balances;495	type ApproveOrigin = EnsureRoot<AccountId>;496	type RejectOrigin = EnsureRoot<AccountId>;497	type Event = Event;498	type OnSlash = ();499	type ProposalBond = ProposalBond;500	type ProposalBondMinimum = ProposalBondMinimum;501	type ProposalBondMaximum = ProposalBondMaximum;502	type SpendPeriod = SpendPeriod;503	type Burn = Burn;504	type BurnDestination = ();505	type SpendFunds = ();506	type WeightInfo = pallet_treasury::weights::SubstrateWeight<Self>;507	type MaxApprovals = MaxApprovals;508}509510impl pallet_sudo::Config for Runtime {511	type Event = Event;512	type Call = Call;513}514515pub struct RelayChainBlockNumberProvider<T>(sp_std::marker::PhantomData<T>);516517impl<T: cumulus_pallet_parachain_system::Config> BlockNumberProvider518	for RelayChainBlockNumberProvider<T>519{520	type BlockNumber = BlockNumber;521522	fn current_block_number() -> Self::BlockNumber {523		cumulus_pallet_parachain_system::Pallet::<T>::validation_data()524			.map(|d| d.relay_parent_number)525			.unwrap_or_default()526	}527}528529parameter_types! {530	pub const MinVestedTransfer: Balance = 10 * UNIQUE;531	pub const MaxVestingSchedules: u32 = 28;532}533534impl orml_vesting::Config for Runtime {535	type Event = Event;536	type Currency = pallet_balances::Pallet<Runtime>;537	type MinVestedTransfer = MinVestedTransfer;538	type VestedTransferOrigin = EnsureSigned<AccountId>;539	type WeightInfo = ();540	type MaxVestingSchedules = MaxVestingSchedules;541	type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;542}543544parameter_types! {545	pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;546	pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;547}548549impl cumulus_pallet_parachain_system::Config for Runtime {550	type Event = Event;551	type SelfParaId = parachain_info::Pallet<Self>;552	type OnSystemEvent = ();553	// type DownwardMessageHandlers = cumulus_primitives_utility::UnqueuedDmpAsParent<554	// 	MaxDownwardMessageWeight,555	// 	XcmExecutor<XcmConfig>,556	// 	Call,557	// >;558	type OutboundXcmpMessageSource = XcmpQueue;559	type DmpMessageHandler = DmpQueue;560	type ReservedDmpWeight = ReservedDmpWeight;561	type ReservedXcmpWeight = ReservedXcmpWeight;562	type XcmpMessageHandler = XcmpQueue;563}564565impl parachain_info::Config for Runtime {}566567impl cumulus_pallet_aura_ext::Config for Runtime {}568569parameter_types! {570	pub const RelayLocation: MultiLocation = MultiLocation::parent();571	pub const RelayNetwork: NetworkId = NetworkId::Polkadot;572	pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();573	pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();574}575576/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used577/// when determining ownership of accounts for asset transacting and when attempting to use XCM578/// `Transact` in order to determine the dispatch Origin.579pub type LocationToAccountId = (580	// The parent (Relay-chain) origin converts to the default `AccountId`.581	ParentIsDefault<AccountId>,582	// Sibling parachain origins convert to AccountId via the `ParaId::into`.583	SiblingParachainConvertsVia<Sibling, AccountId>,584	// Straight up local `AccountId32` origins just alias directly to `AccountId`.585	AccountId32Aliases<RelayNetwork, AccountId>,586);587588pub struct OnlySelfCurrency;589impl<B: TryFrom<u128>> MatchesFungible<B> for OnlySelfCurrency {590	fn matches_fungible(a: &MultiAsset) -> Option<B> {591		match (&a.id, &a.fun) {592			(Concrete(_), XcmFungible(ref amount)) => CheckedConversion::checked_from(*amount),593			_ => None,594		}595	}596}597598/// Means for transacting assets on this chain.599pub type LocalAssetTransactor = CurrencyAdapter<600	// Use this currency:601	Balances,602	// Use this currency when it is a fungible asset matching the given location or name:603	OnlySelfCurrency,604	// Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:605	LocationToAccountId,606	// Our chain's account ID type (we can't get away without mentioning it explicitly):607	AccountId,608	// We don't track any teleports.609	(),610>;611612/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,613/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can614/// biases the kind of local `Origin` it will become.615pub type XcmOriginToTransactDispatchOrigin = (616	// Sovereign account converter; this attempts to derive an `AccountId` from the origin location617	// using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for618	// foreign chains who want to have a local sovereign account on this chain which they control.619	SovereignSignedViaLocation<LocationToAccountId, Origin>,620	// Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when621	// recognised.622	RelayChainAsNative<RelayOrigin, Origin>,623	// Native converter for sibling Parachains; will convert to a `SiblingPara` origin when624	// recognised.625	SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,626	// Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a627	// transaction from the Root origin.628	ParentAsSuperuser<Origin>,629	// Native signed account converter; this just converts an `AccountId32` origin into a normal630	// `Origin::Signed` origin of the same 32-byte value.631	SignedAccountId32AsNative<RelayNetwork, Origin>,632	// Xcm origins can be represented natively under the Xcm pallet's Xcm origin.633	XcmPassthrough<Origin>,634);635636parameter_types! {637	// One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.638	pub UnitWeightCost: Weight = 1_000_000;639	// 1200 UNIQUEs buy 1 second of weight.640	pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);641	pub const MaxInstructions: u32 = 100;642	pub const MaxAuthorities: u32 = 100_000;643}644645match_type! {646	pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {647		MultiLocation { parents: 1, interior: Here } |648		MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }649	};650}651652pub type Barrier = (653	TakeWeightCredit,654	AllowTopLevelPaidExecutionFrom<Everything>,655	AllowUnpaidExecutionFrom<ParentOrParentsUnitPlurality>,656	// ^^^ Parent & its unit plurality gets free execution657);658659pub struct UsingOnlySelfCurrencyComponents<660	WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,661	AssetId: Get<MultiLocation>,662	AccountId,663	Currency: CurrencyT<AccountId>,664	OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,665>(666	Weight,667	Currency::Balance,668	PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>,669);670impl<671		WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,672		AssetId: Get<MultiLocation>,673		AccountId,674		Currency: CurrencyT<AccountId>,675		OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,676	> WeightTrader677	for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>678{679	fn new() -> Self {680		Self(0, Zero::zero(), PhantomData)681	}682683	fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {684		let amount = WeightToFee::calc(&weight);685		let u128_amount: u128 = amount.try_into().map_err(|_| XcmError::Overflow)?;686687		// location to this parachain through relay chain688		let option1: xcm::v1::AssetId = Concrete(MultiLocation {689			parents: 1,690			interior: X1(Parachain(ParachainInfo::parachain_id().into())),691		});692		// direct location693		let option2: xcm::v1::AssetId = Concrete(MultiLocation {694			parents: 0,695			interior: Here,696		});697698		let required = if payment.fungible.contains_key(&option1) {699			(option1, u128_amount).into()700		} else if payment.fungible.contains_key(&option2) {701			(option2, u128_amount).into()702		} else {703			(Concrete(MultiLocation::default()), u128_amount).into()704		};705706		let unused = payment707			.checked_sub(required)708			.map_err(|_| XcmError::TooExpensive)?;709		self.0 = self.0.saturating_add(weight);710		self.1 = self.1.saturating_add(amount);711		Ok(unused)712	}713714	fn refund_weight(&mut self, weight: Weight) -> Option<MultiAsset> {715		let weight = weight.min(self.0);716		let amount = WeightToFee::calc(&weight);717		self.0 -= weight;718		self.1 = self.1.saturating_sub(amount);719		let amount: u128 = amount.saturated_into();720		if amount > 0 {721			Some((AssetId::get(), amount).into())722		} else {723			None724		}725	}726}727impl<728		WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,729		AssetId: Get<MultiLocation>,730		AccountId,731		Currency: CurrencyT<AccountId>,732		OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,733	> Drop734	for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>735{736	fn drop(&mut self) {737		OnUnbalanced::on_unbalanced(Currency::issue(self.1));738	}739}740741pub struct XcmConfig;742impl Config for XcmConfig {743	type Call = Call;744	type XcmSender = XcmRouter;745	// How to withdraw and deposit an asset.746	type AssetTransactor = LocalAssetTransactor;747	type OriginConverter = XcmOriginToTransactDispatchOrigin;748	type IsReserve = NativeAsset;749	type IsTeleporter = (); // Teleportation is disabled750	type LocationInverter = LocationInverter<Ancestry>;751	type Barrier = Barrier;752	type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;753	type Trader = UsingOnlySelfCurrencyComponents<754		IdentityFee<Balance>,755		RelayLocation,756		AccountId,757		Balances,758		(),759	>;760	type ResponseHandler = (); // Don't handle responses for now.761	type SubscriptionService = PolkadotXcm;762763	type AssetTrap = PolkadotXcm;764	type AssetClaims = PolkadotXcm;765}766767// parameter_types! {768// 	pub const MaxDownwardMessageWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 10;769// }770771/// No local origins on this chain are allowed to dispatch XCM sends/executions.772pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);773774/// The means for routing XCM messages which are not for local execution into the right message775/// queues.776pub type XcmRouter = (777	// Two routers - use UMP to communicate with the relay chain:778	cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,779	// ..and XCMP to communicate with the sibling chains.780	XcmpQueue,781);782783impl pallet_evm_coder_substrate::Config for Runtime {784	type EthereumTransactionSender = pallet_ethereum::Pallet<Self>;785	type GasWeightMapping = FixedGasWeightMapping;786}787788impl pallet_xcm::Config for Runtime {789	type Event = Event;790	type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;791	type XcmRouter = XcmRouter;792	type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;793	type XcmExecuteFilter = Everything;794	type XcmExecutor = XcmExecutor<XcmConfig>;795	type XcmTeleportFilter = Everything;796	type XcmReserveTransferFilter = Everything;797	type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;798	type LocationInverter = LocationInverter<Ancestry>;799	type Origin = Origin;800	type Call = Call;801	const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;802	type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;803}804805impl cumulus_pallet_xcm::Config for Runtime {806	type Event = Event;807	type XcmExecutor = XcmExecutor<XcmConfig>;808}809810impl cumulus_pallet_xcmp_queue::Config for Runtime {811	type Event = Event;812	type XcmExecutor = XcmExecutor<XcmConfig>;813	type ChannelInfo = ParachainSystem;814	type VersionWrapper = ();815	type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;816}817818impl cumulus_pallet_dmp_queue::Config for Runtime {819	type Event = Event;820	type XcmExecutor = XcmExecutor<XcmConfig>;821	type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;822}823824impl pallet_aura::Config for Runtime {825	type AuthorityId = AuraId;826	type DisabledValidators = ();827	type MaxAuthorities = MaxAuthorities;828}829830parameter_types! {831	pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();832	pub const CollectionCreationPrice: Balance = 100 * UNIQUE;833}834835impl pallet_common::Config for Runtime {836	type Event = Event;837	type EvmBackwardsAddressMapping = up_evm_mapping::MapBackwardsAddressTruncated;838	type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;839	type CrossAccountId = pallet_common::account::BasicCrossAccountId<Self>;840841	type Currency = Balances;842	type CollectionCreationPrice = CollectionCreationPrice;843	type TreasuryAccountId = TreasuryAccountId;844}845846impl pallet_fungible::Config for Runtime {847	type WeightInfo = pallet_fungible::weights::SubstrateWeight<Self>;848}849impl pallet_refungible::Config for Runtime {850	type WeightInfo = pallet_refungible::weights::SubstrateWeight<Self>;851}852impl pallet_nonfungible::Config for Runtime {853	type WeightInfo = pallet_nonfungible::weights::SubstrateWeight<Self>;854}855856impl pallet_unique::Config for Runtime {857	type Event = Event;858	type WeightInfo = pallet_unique::weights::SubstrateWeight<Self>;859}860861parameter_types! {862	pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied863}864865/// Used for the pallet inflation866impl pallet_inflation::Config for Runtime {867	type Currency = Balances;868	type TreasuryAccountId = TreasuryAccountId;869	type InflationBlockInterval = InflationBlockInterval;870	type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;871}872873// parameter_types! {874// 	pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *875// 		RuntimeBlockWeights::get().max_block;876// 	pub const MaxScheduledPerBlock: u32 = 50;877// }878879type EvmSponsorshipHandler = (880	pallet_unique::UniqueEthSponsorshipHandler<Runtime>,881	pallet_evm_contract_helpers::HelpersContractSponsoring<Runtime>,882);883type SponsorshipHandler = (884	pallet_unique::UniqueSponsorshipHandler<Runtime>,885	//pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,886	pallet_evm_transaction_payment::BridgeSponsorshipHandler<Runtime>,887);888889// impl pallet_unq_scheduler::Config for Runtime {890// 	type Event = Event;891// 	type Origin = Origin;892// 	type PalletsOrigin = OriginCaller;893// 	type Call = Call;894// 	type MaximumWeight = MaximumSchedulerWeight;895// 	type ScheduleOrigin = EnsureSigned<AccountId>;896// 	type MaxScheduledPerBlock = MaxScheduledPerBlock;897// 	type SponsorshipHandler = SponsorshipHandler;898// 	type WeightInfo = ();899// }900901impl pallet_evm_transaction_payment::Config for Runtime {902	type EvmSponsorshipHandler = EvmSponsorshipHandler;903	type Currency = Balances;904	type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;905	type EvmBackwardsAddressMapping = up_evm_mapping::MapBackwardsAddressTruncated;906}907908impl pallet_charge_transaction::Config for Runtime {909	type SponsorshipHandler = SponsorshipHandler;910}911912// impl pallet_contract_helpers::Config for Runtime {913//	 type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;914// }915916parameter_types! {917	// 0x842899ECF380553E8a4de75bF534cdf6fBF64049918	pub const HelpersContractAddress: H160 = H160([919		0x84, 0x28, 0x99, 0xec, 0xf3, 0x80, 0x55, 0x3e, 0x8a, 0x4d, 0xe7, 0x5b, 0xf5, 0x34, 0xcd, 0xf6, 0xfb, 0xf6, 0x40, 0x49,920	]);921}922923impl pallet_evm_contract_helpers::Config for Runtime {924	type ContractAddress = HelpersContractAddress;925	type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;926}927928construct_runtime!(929	pub enum Runtime where930		Block = Block,931		NodeBlock = opaque::Block,932		UncheckedExtrinsic = UncheckedExtrinsic933	{934		ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Config, Storage, Inherent, Event<T>, ValidateUnsigned} = 20,935		ParachainInfo: parachain_info::{Pallet, Storage, Config} = 21,936937		Aura: pallet_aura::{Pallet, Config<T>} = 22,938		AuraExt: cumulus_pallet_aura_ext::{Pallet, Config} = 23,939940		Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 30,941		RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage} = 31,942		Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 32,943		TransactionPayment: pallet_transaction_payment::{Pallet, Storage} = 33,944		Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event<T>} = 34,945		Sudo: pallet_sudo::{Pallet, Call, Storage, Config<T>, Event<T>} = 35,946		System: frame_system::{Pallet, Call, Storage, Config, Event<T>} = 36,947		Vesting: orml_vesting::{Pallet, Storage, Call, Event<T>, Config<T>} = 37,948		// Vesting: pallet_vesting::{Pallet, Call, Config<T>, Storage, Event<T>} = 37,949		// Contracts: pallet_contracts::{Pallet, Call, Storage, Event<T>} = 38,950951		// XCM helpers.952		XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 50,953		PolkadotXcm: pallet_xcm::{Pallet, Call, Event<T>, Origin} = 51,954		CumulusXcm: cumulus_pallet_xcm::{Pallet, Call, Event<T>, Origin} = 52,955		DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,956957		// Unique Pallets958		Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,959		Unique: pallet_unique::{Pallet, Call, Storage, Event<T>} = 61,960		// Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,961		// free = 63962		Charging: pallet_charge_transaction::{Pallet, Call, Storage } = 64,963		// ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,964		Common: pallet_common::{Pallet, Storage, Event<T>} = 66,965		Fungible: pallet_fungible::{Pallet, Storage} = 67,966		Refungible: pallet_refungible::{Pallet, Storage} = 68,967		Nonfungible: pallet_nonfungible::{Pallet, Storage} = 69,968969		// Frontier970		EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,971		Ethereum: pallet_ethereum::{Pallet, Config, Call, Storage, Event, Origin} = 101,972973		EvmCoderSubstrate: pallet_evm_coder_substrate::{Pallet, Storage} = 150,974		EvmContractHelpers: pallet_evm_contract_helpers::{Pallet, Storage} = 151,975		EvmTransactionPayment: pallet_evm_transaction_payment::{Pallet} = 152,976		EvmMigration: pallet_evm_migration::{Pallet, Call, Storage} = 153,977	}978);979980pub struct TransactionConverter;981982impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {983	fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {984		UncheckedExtrinsic::new_unsigned(985			pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),986		)987	}988}989990impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {991	fn convert_transaction(992		&self,993		transaction: pallet_ethereum::Transaction,994	) -> opaque::UncheckedExtrinsic {995		let extrinsic = UncheckedExtrinsic::new_unsigned(996			pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),997		);998		let encoded = extrinsic.encode();999		opaque::UncheckedExtrinsic::decode(&mut &encoded[..])1000			.expect("Encoded extrinsic is always valid")1001	}1002}10031004/// The address format for describing accounts.1005pub type Address = sp_runtime::MultiAddress<AccountId, ()>;1006/// Block header type as expected by this runtime.1007pub type Header = generic::Header<BlockNumber, BlakeTwo256>;1008/// Block type as expected by this runtime.1009pub type Block = generic::Block<Header, UncheckedExtrinsic>;1010/// A Block signed with a Justification1011pub type SignedBlock = generic::SignedBlock<Block>;1012/// BlockId type as expected by this runtime.1013pub type BlockId = generic::BlockId<Block>;1014/// The SignedExtension to the basic transaction logic.1015pub type SignedExtra = (1016	frame_system::CheckSpecVersion<Runtime>,1017	// system::CheckTxVersion<Runtime>,1018	frame_system::CheckGenesis<Runtime>,1019	frame_system::CheckEra<Runtime>,1020	frame_system::CheckNonce<Runtime>,1021	frame_system::CheckWeight<Runtime>,1022	pallet_charge_transaction::ChargeTransactionPayment<Runtime>,1023	//pallet_contract_helpers::ContractHelpersExtension<Runtime>,1024);1025/// Unchecked extrinsic type as expected by this runtime.1026pub type UncheckedExtrinsic =1027	fp_self_contained::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;1028/// Extrinsic type that has already been checked.1029pub type CheckedExtrinsic = fp_self_contained::CheckedExtrinsic<AccountId, Call, SignedExtra, H160>;1030/// Executive: handles dispatch to the various modules.1031pub type Executive = frame_executive::Executive<1032	Runtime,1033	Block,1034	frame_system::ChainContext<Runtime>,1035	Runtime,1036	AllPalletsReversedWithSystemFirst,1037>;10381039impl_opaque_keys! {1040	pub struct SessionKeys {1041		pub aura: Aura,1042	}1043}10441045impl fp_self_contained::SelfContainedCall for Call {1046	type SignedInfo = H160;10471048	fn is_self_contained(&self) -> bool {1049		match self {1050			Call::Ethereum(call) => call.is_self_contained(),1051			_ => false,1052		}1053	}10541055	fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {1056		match self {1057			Call::Ethereum(call) => call.check_self_contained(),1058			_ => None,1059		}1060	}10611062	fn validate_self_contained(&self, info: &Self::SignedInfo) -> Option<TransactionValidity> {1063		match self {1064			Call::Ethereum(call) => call.validate_self_contained(info),1065			_ => None,1066		}1067	}10681069	fn pre_dispatch_self_contained(1070		&self,1071		info: &Self::SignedInfo,1072	) -> Option<Result<(), TransactionValidityError>> {1073		match self {1074			Call::Ethereum(call) => call.pre_dispatch_self_contained(info),1075			_ => None,1076		}1077	}10781079	fn apply_self_contained(1080		self,1081		info: Self::SignedInfo,1082	) -> Option<sp_runtime::DispatchResultWithInfo<PostDispatchInfoOf<Self>>> {1083		match self {1084			call @ Call::Ethereum(pallet_ethereum::Call::transact { .. }) => Some(call.dispatch(1085				Origin::from(pallet_ethereum::RawOrigin::EthereumTransaction(info)),1086			)),1087			_ => None,1088		}1089	}1090}10911092macro_rules! dispatch_unique_runtime {1093	($collection:ident.$method:ident($($name:ident),*)) => {{1094		use pallet_unique::dispatch::Dispatched;10951096		let collection = Dispatched::dispatch(<pallet_common::CollectionHandle<Runtime>>::try_get($collection)?);1097		let dispatch = collection.as_dyn();10981099		Ok(dispatch.$method($($name),*))1100	}};1101}1102impl_runtime_apis! {1103	impl up_rpc::UniqueApi<Block, CrossAccountId, AccountId>1104		for Runtime1105	{1106		fn account_tokens(collection: CollectionId, account: CrossAccountId) -> Result<Vec<TokenId>, DispatchError> {1107			dispatch_unique_runtime!(collection.account_tokens(account))1108		}1109		fn token_exists(collection: CollectionId, token: TokenId) -> Result<bool, DispatchError> {1110			dispatch_unique_runtime!(collection.token_exists(token))1111		}11121113		fn token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>, DispatchError> {1114			dispatch_unique_runtime!(collection.token_owner(token))1115		}1116		fn const_metadata(collection: CollectionId, token: TokenId) -> Result<Vec<u8>, DispatchError> {1117			dispatch_unique_runtime!(collection.const_metadata(token))1118		}1119		fn variable_metadata(collection: CollectionId, token: TokenId) -> Result<Vec<u8>, DispatchError> {1120			dispatch_unique_runtime!(collection.variable_metadata(token))1121		}11221123		fn collection_tokens(collection: CollectionId) -> Result<u32, DispatchError> {1124			dispatch_unique_runtime!(collection.collection_tokens())1125		}1126		fn account_balance(collection: CollectionId, account: CrossAccountId) -> Result<u32, DispatchError> {1127			dispatch_unique_runtime!(collection.account_balance(account))1128		}1129		fn balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<u128, DispatchError> {1130			dispatch_unique_runtime!(collection.balance(account, token))1131		}1132		fn allowance(1133			collection: CollectionId,1134			sender: CrossAccountId,1135			spender: CrossAccountId,1136			token: TokenId,1137		) -> Result<u128, DispatchError> {1138			dispatch_unique_runtime!(collection.allowance(sender, spender, token))1139		}11401141		fn eth_contract_code(account: H160) -> Option<Vec<u8>> {1142			<pallet_unique::UniqueErcSupport<Runtime>>::get_code(&account)1143				.or_else(|| <pallet_evm_migration::OnMethodCall<Runtime>>::get_code(&account))1144				.or_else(|| <pallet_evm_contract_helpers::HelpersOnMethodCall<Self>>::get_code(&account))1145		}1146		fn adminlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {1147			Ok(<pallet_common::Pallet<Runtime>>::adminlist(collection))1148		}1149		fn allowlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {1150			Ok(<pallet_common::Pallet<Runtime>>::allowlist(collection))1151		}1152		fn allowed(collection: CollectionId, user: CrossAccountId) -> Result<bool, DispatchError> {1153			Ok(<pallet_common::Pallet<Runtime>>::allowed(collection, user))1154		}1155		fn last_token_id(collection: CollectionId) -> Result<TokenId, DispatchError> {1156			dispatch_unique_runtime!(collection.last_token_id())1157		}1158		fn collection_by_id(collection: CollectionId) -> Result<Option<Collection<AccountId>>, DispatchError> {1159			Ok(<pallet_common::CollectionById<Runtime>>::get(collection))1160		}1161		fn collection_stats() -> Result<CollectionStats, DispatchError> {1162			Ok(<pallet_common::Pallet<Runtime>>::collection_stats())1163		}1164	}11651166	impl sp_api::Core<Block> for Runtime {1167		fn version() -> RuntimeVersion {1168			VERSION1169		}11701171		fn execute_block(block: Block) {1172			Executive::execute_block(block)1173		}11741175		fn initialize_block(header: &<Block as BlockT>::Header) {1176			Executive::initialize_block(header)1177		}1178	}11791180	impl sp_api::Metadata<Block> for Runtime {1181		fn metadata() -> OpaqueMetadata {1182			OpaqueMetadata::new(Runtime::metadata().into())1183		}1184	}11851186	impl sp_block_builder::BlockBuilder<Block> for Runtime {1187		fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {1188			Executive::apply_extrinsic(extrinsic)1189		}11901191		fn finalize_block() -> <Block as BlockT>::Header {1192			Executive::finalize_block()1193		}11941195		fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {1196			data.create_extrinsics()1197		}11981199		fn check_inherents(1200			block: Block,1201			data: sp_inherents::InherentData,1202		) -> sp_inherents::CheckInherentsResult {1203			data.check_extrinsics(&block)1204		}12051206		// fn random_seed() -> <Block as BlockT>::Hash {1207		//     RandomnessCollectiveFlip::random_seed().01208		// }1209	}12101211	impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {1212		fn validate_transaction(1213			source: TransactionSource,1214			tx: <Block as BlockT>::Extrinsic,1215			hash: <Block as BlockT>::Hash,1216		) -> TransactionValidity {1217			Executive::validate_transaction(source, tx, hash)1218		}1219	}12201221	impl sp_offchain::OffchainWorkerApi<Block> for Runtime {1222		fn offchain_worker(header: &<Block as BlockT>::Header) {1223			Executive::offchain_worker(header)1224		}1225	}12261227	impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {1228		fn chain_id() -> u64 {1229			<Runtime as pallet_evm::Config>::ChainId::get()1230		}12311232		fn account_basic(address: H160) -> EVMAccount {1233			EVM::account_basic(&address)1234		}12351236		fn gas_price() -> U256 {1237			<Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price()1238		}12391240		fn account_code_at(address: H160) -> Vec<u8> {1241			EVM::account_codes(address)1242		}12431244		fn author() -> H160 {1245			<pallet_evm::Pallet<Runtime>>::find_author()1246		}12471248		fn storage_at(address: H160, index: U256) -> H256 {1249			let mut tmp = [0u8; 32];1250			index.to_big_endian(&mut tmp);1251			EVM::account_storages(address, H256::from_slice(&tmp[..]))1252		}12531254		#[allow(clippy::redundant_closure)]1255		fn call(1256			from: H160,1257			to: H160,1258			data: Vec<u8>,1259			value: U256,1260			gas_limit: U256,1261			max_fee_per_gas: Option<U256>,1262			max_priority_fee_per_gas: Option<U256>,1263			nonce: Option<U256>,1264			estimate: bool,1265			access_list: Option<Vec<(H160, Vec<H256>)>>,1266		) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {1267			let config = if estimate {1268				let mut config = <Runtime as pallet_evm::Config>::config().clone();1269				config.estimate = true;1270				Some(config)1271			} else {1272				None1273			};12741275			<Runtime as pallet_evm::Config>::Runner::call(1276				from,1277				to,1278				data,1279				value,1280				gas_limit.low_u64(),1281				max_fee_per_gas,1282				max_priority_fee_per_gas,1283				nonce,1284				access_list.unwrap_or_default(),1285				config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),1286			).map_err(|err| err.into())1287		}12881289		#[allow(clippy::redundant_closure)]1290		fn create(1291			from: H160,1292			data: Vec<u8>,1293			value: U256,1294			gas_limit: U256,1295			max_fee_per_gas: Option<U256>,1296			max_priority_fee_per_gas: Option<U256>,1297			nonce: Option<U256>,1298			estimate: bool,1299			access_list: Option<Vec<(H160, Vec<H256>)>>,1300		) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {1301			let config = if estimate {1302				let mut config = <Runtime as pallet_evm::Config>::config().clone();1303				config.estimate = true;1304				Some(config)1305			} else {1306				None1307			};13081309			<Runtime as pallet_evm::Config>::Runner::create(1310				from,1311				data,1312				value,1313				gas_limit.low_u64(),1314				max_fee_per_gas,1315				max_priority_fee_per_gas,1316				nonce,1317				access_list.unwrap_or_default(),1318				config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),1319			).map_err(|err| err.into())1320		}13211322		fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {1323			Ethereum::current_transaction_statuses()1324		}13251326		fn current_block() -> Option<pallet_ethereum::Block> {1327			Ethereum::current_block()1328		}13291330		fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {1331			Ethereum::current_receipts()1332		}13331334		fn current_all() -> (1335			Option<pallet_ethereum::Block>,1336			Option<Vec<pallet_ethereum::Receipt>>,1337			Option<Vec<TransactionStatus>>1338		) {1339			(1340				Ethereum::current_block(),1341				Ethereum::current_receipts(),1342				Ethereum::current_transaction_statuses()1343			)1344		}13451346		fn extrinsic_filter(xts: Vec<<Block as sp_api::BlockT>::Extrinsic>) -> Vec<pallet_ethereum::Transaction> {1347			xts.into_iter().filter_map(|xt| match xt.0.function {1348				Call::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction),1349				_ => None1350			}).collect()1351		}13521353		fn elasticity() -> Option<Permill> {1354			None1355		}1356	}13571358	impl sp_session::SessionKeys<Block> for Runtime {1359		fn decode_session_keys(1360			encoded: Vec<u8>,1361		) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {1362			SessionKeys::decode_into_raw_public_keys(&encoded)1363		}13641365		fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {1366			SessionKeys::generate(seed)1367		}1368	}13691370	impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {1371		fn slot_duration() -> sp_consensus_aura::SlotDuration {1372			sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())1373		}13741375		fn authorities() -> Vec<AuraId> {1376			Aura::authorities().to_vec()1377		}1378	}13791380	impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {1381		fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {1382			ParachainSystem::collect_collation_info(header)1383		}1384	}13851386	impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {1387		fn account_nonce(account: AccountId) -> Index {1388			System::account_nonce(account)1389		}1390	}13911392	impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {1393		fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {1394			TransactionPayment::query_info(uxt, len)1395		}1396		fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {1397			TransactionPayment::query_fee_details(uxt, len)1398		}1399	}14001401	/*1402	impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber, Hash>1403		for Runtime1404	{1405		fn call(1406			origin: AccountId,1407			dest: AccountId,1408			value: Balance,1409			gas_limit: u64,1410			input_data: Vec<u8>,1411		) -> pallet_contracts_primitives::ContractExecResult {1412			Contracts::bare_call(origin, dest, value, gas_limit, input_data, false)1413		}14141415		fn instantiate(1416			origin: AccountId,1417			endowment: Balance,1418			gas_limit: u64,1419			code: pallet_contracts_primitives::Code<Hash>,1420			data: Vec<u8>,1421			salt: Vec<u8>,1422		) -> pallet_contracts_primitives::ContractInstantiateResult<AccountId, BlockNumber>1423		{1424			Contracts::bare_instantiate(origin, endowment, gas_limit, code, data, salt, true, false)1425		}14261427		fn get_storage(1428			address: AccountId,1429			key: [u8; 32],1430		) -> pallet_contracts_primitives::GetStorageResult {1431			Contracts::get_storage(address, key)1432		}14331434		fn rent_projection(1435			address: AccountId,1436		) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {1437			Contracts::rent_projection(address)1438		}1439	}1440	*/14411442	#[cfg(feature = "runtime-benchmarks")]1443	impl frame_benchmarking::Benchmark<Block> for Runtime {1444		fn benchmark_metadata(extra: bool) -> (1445			Vec<frame_benchmarking::BenchmarkList>,1446			Vec<frame_support::traits::StorageInfo>,1447		) {1448			use frame_benchmarking::{list_benchmark, Benchmarking, BenchmarkList};1449			use frame_support::traits::StorageInfoTrait;14501451			let mut list = Vec::<BenchmarkList>::new();14521453			list_benchmark!(list, extra, pallet_evm_migration, EvmMigration);1454			list_benchmark!(list, extra, pallet_unique, Unique);1455			list_benchmark!(list, extra, pallet_inflation, Inflation);1456			list_benchmark!(list, extra, pallet_fungible, Fungible);1457			list_benchmark!(list, extra, pallet_refungible, Refungible);1458			list_benchmark!(list, extra, pallet_nonfungible, Nonfungible);1459			// list_benchmark!(list, extra, pallet_evm_coder_substrate, EvmCoderSubstrate);14601461			let storage_info = AllPalletsReversedWithSystemFirst::storage_info();14621463			return (list, storage_info)1464		}14651466		fn dispatch_benchmark(1467			config: frame_benchmarking::BenchmarkConfig1468		) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {1469			use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};14701471			let allowlist: Vec<TrackedStorageKey> = vec![1472				// Block Number1473				hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),1474				// Total Issuance1475				hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),1476				// Execution Phase1477				hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),1478				// Event Count1479				hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),1480				// System Events1481				hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),1482			];14831484			let mut batches = Vec::<BenchmarkBatch>::new();1485			let params = (&config, &allowlist);14861487			add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);1488			add_benchmark!(params, batches, pallet_unique, Unique);1489			add_benchmark!(params, batches, pallet_inflation, Inflation);1490			add_benchmark!(params, batches, pallet_fungible, Fungible);1491			add_benchmark!(params, batches, pallet_refungible, Refungible);1492			add_benchmark!(params, batches, pallet_nonfungible, Nonfungible);1493			// add_benchmark!(params, batches, pallet_evm_coder_substrate, EvmCoderSubstrate);14941495			if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }1496			Ok(batches)1497		}1498	}1499}15001501struct CheckInherents;15021503impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {1504	fn check_inherents(1505		block: &Block,1506		relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,1507	) -> sp_inherents::CheckInherentsResult {1508		let relay_chain_slot = relay_state_proof1509			.read_slot()1510			.expect("Could not read the relay chain slot from the proof");15111512		let inherent_data =1513			cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(1514				relay_chain_slot,1515				sp_std::time::Duration::from_secs(6),1516			)1517			.create_inherent_data()1518			.expect("Could not create the timestamp inherent data");15191520		inherent_data.check_extrinsics(block)1521	}1522}15231524cumulus_pallet_parachain_system::register_validate_block!(1525	Runtime = Runtime,1526	BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,1527	CheckInherents = CheckInherents,1528);