git.delta.rocks / unique-network / refs/commits / 980a35f96807

difftreelog

source

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