git.delta.rocks / unique-network / refs/commits / 12cd6cb586e3

difftreelog

source

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