git.delta.rocks / unique-network / refs/commits / fcefd819ab8c

difftreelog

source

runtime/quartz/src/lib.rs39.8 KiBsourcehistory
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! The Substrate Node Template runtime. This can be compiled with `#[no_std]`, ready for Wasm.1819#![cfg_attr(not(feature = "std"), no_std)]20// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.21#![recursion_limit = "1024"]22#![allow(clippy::from_over_into, clippy::identity_op)]23#![allow(clippy::fn_to_numeric_cast_with_truncation)]24// Make the WASM binary available.25#[cfg(feature = "std")]26include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));2728use sp_api::impl_runtime_apis;29use sp_core::{crypto::KeyTypeId, OpaqueMetadata, H256, U256, H160};30use sp_runtime::DispatchError;31// #[cfg(any(feature = "std", test))]32// pub use sp_runtime::BuildStorage;3334use sp_runtime::{35	Permill, Perbill, Percent, create_runtime_str, generic, impl_opaque_keys,36	traits::{AccountIdLookup, BlakeTwo256, Block as BlockT, AccountIdConversion, Zero},37	transaction_validity::{TransactionSource, TransactionValidity},38	ApplyExtrinsicResult, RuntimeAppPublic,39};4041use sp_std::prelude::*;4243#[cfg(feature = "std")]44use sp_version::NativeVersion;45use sp_version::RuntimeVersion;46pub use pallet_transaction_payment::{47	Multiplier, TargetedFeeAdjustment, FeeDetails, RuntimeDispatchInfo,48};49// A few exports that help ease life for downstream crates.50pub use pallet_balances::Call as BalancesCall;51pub use pallet_evm::{52	EnsureAddressTruncated, HashedAddressMapping, Runner, account::CrossAccountId as _,53};54pub use frame_support::{55	construct_runtime, match_types,56	dispatch::DispatchResult,57	PalletId, parameter_types, StorageValue, ConsensusEngineId,58	traits::{59		tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT, Everything,60		Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem, LockIdentifier,61		OnUnbalanced, Randomness, FindAuthor,62	},63	weights::{64		constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},65		DispatchClass, DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,66		WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients, ConstantMultiplier,67	},68};69use up_data_structs::*;70// use pallet_contracts::weights::WeightInfo;71// #[cfg(any(feature = "std", test))]72use frame_system::{73	self as frame_system, EnsureRoot, EnsureSigned,74	limits::{BlockWeights, BlockLength},75};76use sp_arithmetic::{77	traits::{BaseArithmetic, Unsigned},78};79use smallvec::smallvec;80use codec::{Encode, Decode};81use pallet_evm::{Account as EVMAccount, FeeCalculator, GasWeightMapping};82use fp_rpc::TransactionStatus;83use sp_runtime::{84	traits::{BlockNumberProvider, Dispatchable, PostDispatchInfoOf, Saturating},85	transaction_validity::TransactionValidityError,86	SaturatedConversion,87};8889// pub use pallet_timestamp::Call as TimestampCall;90pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;9192// Polkadot imports93use pallet_xcm::XcmPassthrough;94use polkadot_parachain::primitives::Sibling;95use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};96use xcm_builder::{97	AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter,98	EnsureXcmOrigin, FixedWeightBounds, LocationInverter, NativeAsset, ParentAsSuperuser,99	RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia,100	SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit,101	ParentIsPreset,102};103use xcm_executor::{Config, XcmExecutor, Assets};104use sp_std::{marker::PhantomData};105106use xcm::latest::{107	//	Xcm,108	AssetId::{Concrete},109	Fungibility::Fungible as XcmFungible,110	MultiAsset,111	Error as XcmError,112};113use xcm_executor::traits::{MatchesFungible, WeightTrader};114//use xcm_executor::traits::MatchesFungible;115use sp_runtime::traits::CheckedConversion;116117use unique_runtime_common::{impl_common_runtime_apis, types::*, constants::*};118119pub const RUNTIME_NAME: &str = "quartz";120pub const TOKEN_SYMBOL: &str = "QTZ";121122type CrossAccountId = pallet_evm::account::BasicCrossAccountId<Runtime>;123124impl RuntimeInstance for Runtime {125	type CrossAccountId = self::CrossAccountId;126127	type TransactionConverter = self::TransactionConverter;128129	fn get_transaction_converter() -> TransactionConverter {130		TransactionConverter131	}132}133134/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know135/// the specifics of the runtime. They can then be made to be agnostic over specific formats136/// of data like extrinsics, allowing for them to continue syncing the network through upgrades137/// to even the core data structures.138pub mod opaque {139	use sp_std::prelude::*;140	use sp_runtime::impl_opaque_keys;141	use super::Aura;142143	pub use unique_runtime_common::types::*;144145	impl_opaque_keys! {146		pub struct SessionKeys {147			pub aura: Aura,148		}149	}150}151152/// This runtime version.153pub const VERSION: RuntimeVersion = RuntimeVersion {154	spec_name: create_runtime_str!(RUNTIME_NAME),155	impl_name: create_runtime_str!(RUNTIME_NAME),156	authoring_version: 1,157	spec_version: 920000,158	impl_version: 0,159	apis: RUNTIME_API_VERSIONS,160	transaction_version: 1,161	state_version: 0,162};163164#[derive(codec::Encode, codec::Decode)]165pub enum XCMPMessage<XAccountId, XBalance> {166	/// Transfer tokens to the given account from the Parachain account.167	TransferToken(XAccountId, XBalance),168}169170/// The version information used to identify this runtime when compiled natively.171#[cfg(feature = "std")]172pub fn native_version() -> NativeVersion {173	NativeVersion {174		runtime_version: VERSION,175		can_author_with: Default::default(),176	}177}178179type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;180181pub struct DealWithFees;182impl OnUnbalanced<NegativeImbalance> for DealWithFees {183	fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {184		if let Some(fees) = fees_then_tips.next() {185			// for fees, 100% to treasury186			let mut split = fees.ration(100, 0);187			if let Some(tips) = fees_then_tips.next() {188				// for tips, if any, 100% to treasury189				tips.ration_merge_into(100, 0, &mut split);190			}191			Treasury::on_unbalanced(split.0);192			// Author::on_unbalanced(split.1);193		}194	}195}196197parameter_types! {198	pub const BlockHashCount: BlockNumber = 2400;199	pub RuntimeBlockLength: BlockLength =200		BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);201	pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);202	pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;203	pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()204		.base_block(BlockExecutionWeight::get())205		.for_class(DispatchClass::all(), |weights| {206			weights.base_extrinsic = ExtrinsicBaseWeight::get();207		})208		.for_class(DispatchClass::Normal, |weights| {209			weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);210		})211		.for_class(DispatchClass::Operational, |weights| {212			weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);213			// Operational transactions have some extra reserved space, so that they214			// are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.215			weights.reserved = Some(216				MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT217			);218		})219		.avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)220		.build_or_panic();221	pub const Version: RuntimeVersion = VERSION;222	pub const SS58Prefix: u8 = 255;223}224225parameter_types! {226	pub const ChainId: u64 = 8881;227}228229pub struct FixedFee;230impl FeeCalculator for FixedFee {231	fn min_gas_price() -> U256 {232		MIN_GAS_PRICE.into()233	}234}235236// Assuming slowest ethereum opcode is SSTORE, with gas price of 20000 as our worst case237// (contract, which only writes a lot of data),238// approximating on top of our real store write weight239parameter_types! {240	pub const WritesPerSecond: u64 = WEIGHT_PER_SECOND / <Runtime as frame_system::Config>::DbWeight::get().write;241	pub const GasPerSecond: u64 = WritesPerSecond::get() * 20000;242	pub const WeightPerGas: u64 = WEIGHT_PER_SECOND / GasPerSecond::get();243}244245/// Limiting EVM execution to 50% of block for substrate users and management tasks246/// EVM transaction consumes more weight than substrate's, so we can't rely on them being247/// scheduled fairly248const EVM_DISPATCH_RATIO: Perbill = Perbill::from_percent(50);249parameter_types! {250	pub BlockGasLimit: U256 = U256::from(NORMAL_DISPATCH_RATIO * EVM_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT / WeightPerGas::get());251}252253pub enum FixedGasWeightMapping {}254impl GasWeightMapping for FixedGasWeightMapping {255	fn gas_to_weight(gas: u64) -> Weight {256		gas.saturating_mul(WeightPerGas::get())257	}258	fn weight_to_gas(weight: Weight) -> u64 {259		weight / WeightPerGas::get()260	}261}262263impl pallet_evm::Config for Runtime {264	type BlockGasLimit = BlockGasLimit;265	type FeeCalculator = FixedFee;266	type GasWeightMapping = FixedGasWeightMapping;267	type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;268	type CallOrigin = EnsureAddressTruncated<Self>;269	type WithdrawOrigin = EnsureAddressTruncated<Self>;270	type AddressMapping = HashedAddressMapping<Self::Hashing>;271	type PrecompilesType = ();272	type PrecompilesValue = ();273	type Currency = Balances;274	type Event = Event;275	type OnMethodCall = (276		pallet_evm_migration::OnMethodCall<Self>,277		pallet_unique::UniqueErcSupport<Self>,278		pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,279	);280	type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;281	type ChainId = ChainId;282	type Runner = pallet_evm::runner::stack::Runner<Self>;283	type OnChargeTransaction = pallet_evm::EVMCurrencyAdapter<Balances, DealWithFees>;284	type TransactionValidityHack = pallet_evm_transaction_payment::TransactionValidityHack<Self>;285	type FindAuthor = EthereumFindAuthor<Aura>;286}287288impl pallet_evm_migration::Config for Runtime {289	type WeightInfo = pallet_evm_migration::weights::SubstrateWeight<Self>;290}291292pub struct EthereumFindAuthor<F>(core::marker::PhantomData<F>);293impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F> {294	fn find_author<'a, I>(digests: I) -> Option<H160>295	where296		I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,297	{298		if let Some(author_index) = F::find_author(digests) {299			let authority_id = Aura::authorities()[author_index as usize].clone();300			return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24]));301		}302		None303	}304}305306impl pallet_ethereum::Config for Runtime {307	type Event = Event;308	type StateRoot = pallet_ethereum::IntermediateStateRoot<Self>;309}310311impl pallet_randomness_collective_flip::Config for Runtime {}312313impl frame_system::Config for Runtime {314	/// The data to be stored in an account.315	type AccountData = pallet_balances::AccountData<Balance>;316	/// The identifier used to distinguish between accounts.317	type AccountId = AccountId;318	/// The basic call filter to use in dispatchable.319	type BaseCallFilter = Everything;320	/// Maximum number of block number to block hash mappings to keep (oldest pruned first).321	type BlockHashCount = BlockHashCount;322	/// The maximum length of a block (in bytes).323	type BlockLength = RuntimeBlockLength;324	/// The index type for blocks.325	type BlockNumber = BlockNumber;326	/// The weight of the overhead invoked on the block import process, independent of the extrinsics included in that block.327	type BlockWeights = RuntimeBlockWeights;328	/// The aggregated dispatch type that is available for extrinsics.329	type Call = Call;330	/// The weight of database operations that the runtime can invoke.331	type DbWeight = RocksDbWeight;332	/// The ubiquitous event type.333	type Event = Event;334	/// The type for hashing blocks and tries.335	type Hash = Hash;336	/// The hashing algorithm used.337	type Hashing = BlakeTwo256;338	/// The header type.339	type Header = generic::Header<BlockNumber, BlakeTwo256>;340	/// The index type for storing how many extrinsics an account has signed.341	type Index = Index;342	/// The lookup mechanism to get account ID from whatever is passed in dispatchers.343	type Lookup = AccountIdLookup<AccountId, ()>;344	/// What to do if an account is fully reaped from the system.345	type OnKilledAccount = ();346	/// What to do if a new account is created.347	type OnNewAccount = ();348	type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;349	/// The ubiquitous origin type.350	type Origin = Origin;351	/// This type is being generated by `construct_runtime!`.352	type PalletInfo = PalletInfo;353	/// This is used as an identifier of the chain. 42 is the generic substrate prefix.354	type SS58Prefix = SS58Prefix;355	/// Weight information for the extrinsics of this pallet.356	type SystemWeightInfo = frame_system::weights::SubstrateWeight<Self>;357	/// Version of the runtime.358	type Version = Version;359	type MaxConsumers = ConstU32<16>;360}361362parameter_types! {363	pub const MinimumPeriod: u64 = SLOT_DURATION / 2;364}365366impl pallet_timestamp::Config for Runtime {367	/// A timestamp: milliseconds since the unix epoch.368	type Moment = u64;369	type OnTimestampSet = ();370	type MinimumPeriod = MinimumPeriod;371	type WeightInfo = ();372}373374parameter_types! {375	// pub const ExistentialDeposit: u128 = 500;376	pub const ExistentialDeposit: u128 = 0;377	pub const MaxLocks: u32 = 50;378}379380impl pallet_balances::Config for Runtime {381	type MaxLocks = MaxLocks;382	type MaxReserves = ();383	type ReserveIdentifier = [u8; 8];384	/// The type for recording an account's balance.385	type Balance = Balance;386	/// The ubiquitous event type.387	type Event = Event;388	type DustRemoval = Treasury;389	type ExistentialDeposit = ExistentialDeposit;390	type AccountStore = System;391	type WeightInfo = pallet_balances::weights::SubstrateWeight<Self>;392}393394pub const fn deposit(items: u32, bytes: u32) -> Balance {395	items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE396}397398/*399parameter_types! {400	pub TombstoneDeposit: Balance = deposit(401		1,402		sp_std::mem::size_of::<pallet_contracts::Pallet<Runtime>> as u32,403	);404	pub DepositPerContract: Balance = TombstoneDeposit::get();405	pub const DepositPerStorageByte: Balance = deposit(0, 1);406	pub const DepositPerStorageItem: Balance = deposit(1, 0);407	pub RentFraction: Perbill = Perbill::from_rational(1u32, 30 * DAYS);408	pub const SurchargeReward: Balance = 150 * MILLIUNIQUE;409	pub const SignedClaimHandicap: u32 = 2;410	pub const MaxDepth: u32 = 32;411	pub const MaxValueSize: u32 = 16 * 1024;412	pub const MaxCodeSize: u32 = 1024 * 1024 * 25; // 25 Mb413	// The lazy deletion runs inside on_initialize.414	pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO *415		RuntimeBlockWeights::get().max_block;416	// The weight needed for decoding the queue should be less or equal than a fifth417	// of the overall weight dedicated to the lazy deletion.418	pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (419			<Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -420			<Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)421		)) / 5) as u32;422	pub Schedule: pallet_contracts::Schedule<Runtime> = Default::default();423}424425impl pallet_contracts::Config for Runtime {426	type Time = Timestamp;427	type Randomness = RandomnessCollectiveFlip;428	type Currency = Balances;429	type Event = Event;430	type RentPayment = ();431	type SignedClaimHandicap = SignedClaimHandicap;432	type TombstoneDeposit = TombstoneDeposit;433	type DepositPerContract = DepositPerContract;434	type DepositPerStorageByte = DepositPerStorageByte;435	type DepositPerStorageItem = DepositPerStorageItem;436	type RentFraction = RentFraction;437	type SurchargeReward = SurchargeReward;438	type WeightPrice = pallet_transaction_payment::Pallet<Self>;439	type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;440	type ChainExtension = NFTExtension;441	type DeletionQueueDepth = DeletionQueueDepth;442	type DeletionWeightLimit = DeletionWeightLimit;443	type Schedule = Schedule;444	type CallStack = [pallet_contracts::Frame<Self>; 31];445}446*/447448parameter_types! {449	/// This value increases the priority of `Operational` transactions by adding450	/// a "virtual tip" that's equal to the `OperationalFeeMultiplier * final_fee`.451	pub const OperationalFeeMultiplier: u8 = 5;452}453454/// Linear implementor of `WeightToFeePolynomial`455pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);456457impl<T> WeightToFeePolynomial for LinearFee<T>458where459	T: BaseArithmetic + From<u32> + Copy + Unsigned,460{461	type Balance = T;462463	fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {464		smallvec!(WeightToFeeCoefficient {465			// Targeting 0.1 Unique per NFT transfer466			coeff_integer: WEIGHT_TO_FEE_COEFF.into(),467			coeff_frac: Perbill::zero(),468			negative: false,469			degree: 1,470		})471	}472}473474impl pallet_transaction_payment::Config for Runtime {475	type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, DealWithFees>;476	type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;477	type OperationalFeeMultiplier = OperationalFeeMultiplier;478	type WeightToFee = LinearFee<Balance>;479	type FeeMultiplierUpdate = ();480}481482parameter_types! {483	pub const ProposalBond: Permill = Permill::from_percent(5);484	pub const ProposalBondMinimum: Balance = 1 * UNIQUE;485	pub const ProposalBondMaximum: Balance = 1000 * UNIQUE;486	pub const SpendPeriod: BlockNumber = 5 * MINUTES;487	pub const Burn: Permill = Permill::from_percent(0);488	pub const TipCountdown: BlockNumber = 1 * DAYS;489	pub const TipFindersFee: Percent = Percent::from_percent(20);490	pub const TipReportDepositBase: Balance = 1 * UNIQUE;491	pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;492	pub const BountyDepositBase: Balance = 1 * UNIQUE;493	pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;494	pub const TreasuryModuleId: PalletId = PalletId(*b"py/trsry");495	pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;496	pub const MaximumReasonLength: u32 = 16384;497	pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);498	pub const BountyValueMinimum: Balance = 5 * UNIQUE;499	pub const MaxApprovals: u32 = 100;500}501502impl pallet_treasury::Config for Runtime {503	type PalletId = TreasuryModuleId;504	type Currency = Balances;505	type ApproveOrigin = EnsureRoot<AccountId>;506	type RejectOrigin = EnsureRoot<AccountId>;507	type Event = Event;508	type OnSlash = ();509	type ProposalBond = ProposalBond;510	type ProposalBondMinimum = ProposalBondMinimum;511	type ProposalBondMaximum = ProposalBondMaximum;512	type SpendPeriod = SpendPeriod;513	type Burn = Burn;514	type BurnDestination = ();515	type SpendFunds = ();516	type WeightInfo = pallet_treasury::weights::SubstrateWeight<Self>;517	type MaxApprovals = MaxApprovals;518}519520impl pallet_sudo::Config for Runtime {521	type Event = Event;522	type Call = Call;523}524525pub struct RelayChainBlockNumberProvider<T>(sp_std::marker::PhantomData<T>);526527impl<T: cumulus_pallet_parachain_system::Config> BlockNumberProvider528	for RelayChainBlockNumberProvider<T>529{530	type BlockNumber = BlockNumber;531532	fn current_block_number() -> Self::BlockNumber {533		cumulus_pallet_parachain_system::Pallet::<T>::validation_data()534			.map(|d| d.relay_parent_number)535			.unwrap_or_default()536	}537}538539parameter_types! {540	pub const MinVestedTransfer: Balance = 10 * UNIQUE;541	pub const MaxVestingSchedules: u32 = 28;542}543544impl orml_vesting::Config for Runtime {545	type Event = Event;546	type Currency = pallet_balances::Pallet<Runtime>;547	type MinVestedTransfer = MinVestedTransfer;548	type VestedTransferOrigin = EnsureSigned<AccountId>;549	type WeightInfo = ();550	type MaxVestingSchedules = MaxVestingSchedules;551	type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;552}553554parameter_types! {555	pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;556	pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;557}558559impl cumulus_pallet_parachain_system::Config for Runtime {560	type Event = Event;561	type SelfParaId = parachain_info::Pallet<Self>;562	type OnSystemEvent = ();563	// type DownwardMessageHandlers = cumulus_primitives_utility::UnqueuedDmpAsParent<564	// 	MaxDownwardMessageWeight,565	// 	XcmExecutor<XcmConfig>,566	// 	Call,567	// >;568	type OutboundXcmpMessageSource = XcmpQueue;569	type DmpMessageHandler = DmpQueue;570	type ReservedDmpWeight = ReservedDmpWeight;571	type ReservedXcmpWeight = ReservedXcmpWeight;572	type XcmpMessageHandler = XcmpQueue;573}574575impl parachain_info::Config for Runtime {}576577impl cumulus_pallet_aura_ext::Config for Runtime {}578579parameter_types! {580	pub const RelayLocation: MultiLocation = MultiLocation::parent();581	pub const RelayNetwork: NetworkId = NetworkId::Polkadot;582	pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();583	pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();584}585586/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used587/// when determining ownership of accounts for asset transacting and when attempting to use XCM588/// `Transact` in order to determine the dispatch Origin.589pub type LocationToAccountId = (590	// The parent (Relay-chain) origin converts to the default `AccountId`.591	ParentIsPreset<AccountId>,592	// Sibling parachain origins convert to AccountId via the `ParaId::into`.593	SiblingParachainConvertsVia<Sibling, AccountId>,594	// Straight up local `AccountId32` origins just alias directly to `AccountId`.595	AccountId32Aliases<RelayNetwork, AccountId>,596);597598pub struct OnlySelfCurrency;599impl<B: TryFrom<u128>> MatchesFungible<B> for OnlySelfCurrency {600	fn matches_fungible(a: &MultiAsset) -> Option<B> {601		match (&a.id, &a.fun) {602			(Concrete(_), XcmFungible(ref amount)) => CheckedConversion::checked_from(*amount),603			_ => None,604		}605	}606}607608/// Means for transacting assets on this chain.609pub type LocalAssetTransactor = CurrencyAdapter<610	// Use this currency:611	Balances,612	// Use this currency when it is a fungible asset matching the given location or name:613	OnlySelfCurrency,614	// Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:615	LocationToAccountId,616	// Our chain's account ID type (we can't get away without mentioning it explicitly):617	AccountId,618	// We don't track any teleports.619	(),620>;621622/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,623/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can624/// biases the kind of local `Origin` it will become.625pub type XcmOriginToTransactDispatchOrigin = (626	// Sovereign account converter; this attempts to derive an `AccountId` from the origin location627	// using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for628	// foreign chains who want to have a local sovereign account on this chain which they control.629	SovereignSignedViaLocation<LocationToAccountId, Origin>,630	// Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when631	// recognised.632	RelayChainAsNative<RelayOrigin, Origin>,633	// Native converter for sibling Parachains; will convert to a `SiblingPara` origin when634	// recognised.635	SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,636	// Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a637	// transaction from the Root origin.638	ParentAsSuperuser<Origin>,639	// Native signed account converter; this just converts an `AccountId32` origin into a normal640	// `Origin::Signed` origin of the same 32-byte value.641	SignedAccountId32AsNative<RelayNetwork, Origin>,642	// Xcm origins can be represented natively under the Xcm pallet's Xcm origin.643	XcmPassthrough<Origin>,644);645646parameter_types! {647	// One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.648	pub UnitWeightCost: Weight = 1_000_000;649	// 1200 UNIQUEs buy 1 second of weight.650	pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);651	pub const MaxInstructions: u32 = 100;652	pub const MaxAuthorities: u32 = 100_000;653}654655match_types! {656	pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {657		MultiLocation { parents: 1, interior: Here } |658		MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }659	};660}661662pub type Barrier = (663	TakeWeightCredit,664	AllowTopLevelPaidExecutionFrom<Everything>,665	AllowUnpaidExecutionFrom<ParentOrParentsUnitPlurality>,666	// ^^^ Parent & its unit plurality gets free execution667);668669pub struct UsingOnlySelfCurrencyComponents<670	WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,671	AssetId: Get<MultiLocation>,672	AccountId,673	Currency: CurrencyT<AccountId>,674	OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,675>(676	Weight,677	Currency::Balance,678	PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>,679);680impl<681		WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,682		AssetId: Get<MultiLocation>,683		AccountId,684		Currency: CurrencyT<AccountId>,685		OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,686	> WeightTrader687	for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>688{689	fn new() -> Self {690		Self(0, Zero::zero(), PhantomData)691	}692693	fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {694		let amount = WeightToFee::calc(&weight);695		let u128_amount: u128 = amount.try_into().map_err(|_| XcmError::Overflow)?;696697		// location to this parachain through relay chain698		let option1: xcm::v1::AssetId = Concrete(MultiLocation {699			parents: 1,700			interior: X1(Parachain(ParachainInfo::parachain_id().into())),701		});702		// direct location703		let option2: xcm::v1::AssetId = Concrete(MultiLocation {704			parents: 0,705			interior: Here,706		});707708		let required = if payment.fungible.contains_key(&option1) {709			(option1, u128_amount).into()710		} else if payment.fungible.contains_key(&option2) {711			(option2, u128_amount).into()712		} else {713			(Concrete(MultiLocation::default()), u128_amount).into()714		};715716		let unused = payment717			.checked_sub(required)718			.map_err(|_| XcmError::TooExpensive)?;719		self.0 = self.0.saturating_add(weight);720		self.1 = self.1.saturating_add(amount);721		Ok(unused)722	}723724	fn refund_weight(&mut self, weight: Weight) -> Option<MultiAsset> {725		let weight = weight.min(self.0);726		let amount = WeightToFee::calc(&weight);727		self.0 -= weight;728		self.1 = self.1.saturating_sub(amount);729		let amount: u128 = amount.saturated_into();730		if amount > 0 {731			Some((AssetId::get(), amount).into())732		} else {733			None734		}735	}736}737impl<738		WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,739		AssetId: Get<MultiLocation>,740		AccountId,741		Currency: CurrencyT<AccountId>,742		OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,743	> Drop744	for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>745{746	fn drop(&mut self) {747		OnUnbalanced::on_unbalanced(Currency::issue(self.1));748	}749}750751pub struct XcmConfig;752impl Config for XcmConfig {753	type Call = Call;754	type XcmSender = XcmRouter;755	// How to withdraw and deposit an asset.756	type AssetTransactor = LocalAssetTransactor;757	type OriginConverter = XcmOriginToTransactDispatchOrigin;758	type IsReserve = NativeAsset;759	type IsTeleporter = (); // Teleportation is disabled760	type LocationInverter = LocationInverter<Ancestry>;761	type Barrier = Barrier;762	type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;763	type Trader = UsingOnlySelfCurrencyComponents<764		IdentityFee<Balance>,765		RelayLocation,766		AccountId,767		Balances,768		(),769	>;770	type ResponseHandler = (); // Don't handle responses for now.771	type SubscriptionService = PolkadotXcm;772773	type AssetTrap = PolkadotXcm;774	type AssetClaims = PolkadotXcm;775}776777// parameter_types! {778// 	pub const MaxDownwardMessageWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 10;779// }780781/// No local origins on this chain are allowed to dispatch XCM sends/executions.782pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);783784/// The means for routing XCM messages which are not for local execution into the right message785/// queues.786pub type XcmRouter = (787	// Two routers - use UMP to communicate with the relay chain:788	cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,789	// ..and XCMP to communicate with the sibling chains.790	XcmpQueue,791);792793impl pallet_evm_coder_substrate::Config for Runtime {794	type EthereumTransactionSender = pallet_ethereum::Pallet<Self>;795	type GasWeightMapping = FixedGasWeightMapping;796}797798impl pallet_xcm::Config for Runtime {799	type Event = Event;800	type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;801	type XcmRouter = XcmRouter;802	type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;803	type XcmExecuteFilter = Everything;804	type XcmExecutor = XcmExecutor<XcmConfig>;805	type XcmTeleportFilter = Everything;806	type XcmReserveTransferFilter = Everything;807	type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;808	type LocationInverter = LocationInverter<Ancestry>;809	type Origin = Origin;810	type Call = Call;811	const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;812	type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;813}814815impl cumulus_pallet_xcm::Config for Runtime {816	type Event = Event;817	type XcmExecutor = XcmExecutor<XcmConfig>;818}819820impl cumulus_pallet_xcmp_queue::Config for Runtime {821	type WeightInfo = ();822	type Event = Event;823	type XcmExecutor = XcmExecutor<XcmConfig>;824	type ChannelInfo = ParachainSystem;825	type VersionWrapper = ();826	type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;827	type ControllerOrigin = EnsureRoot<AccountId>;828	type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;829}830831impl cumulus_pallet_dmp_queue::Config for Runtime {832	type Event = Event;833	type XcmExecutor = XcmExecutor<XcmConfig>;834	type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;835}836837impl pallet_aura::Config for Runtime {838	type AuthorityId = AuraId;839	type DisabledValidators = ();840	type MaxAuthorities = MaxAuthorities;841}842843parameter_types! {844	pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();845	pub const CollectionCreationPrice: Balance = 2 * UNIQUE;846}847848impl pallet_common::Config for Runtime {849	type Event = Event;850851	type Currency = Balances;852	type CollectionCreationPrice = CollectionCreationPrice;853	type TreasuryAccountId = TreasuryAccountId;854}855856impl pallet_evm::account::Config for Runtime {857	type CrossAccountId = pallet_evm::account::BasicCrossAccountId<Self>;858	type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;859	type EvmBackwardsAddressMapping = fp_evm_mapping::MapBackwardsAddressTruncated;860}861862impl pallet_fungible::Config for Runtime {863	type WeightInfo = pallet_fungible::weights::SubstrateWeight<Self>;864}865impl pallet_refungible::Config for Runtime {866	type WeightInfo = pallet_refungible::weights::SubstrateWeight<Self>;867}868impl pallet_nonfungible::Config for Runtime {869	type WeightInfo = pallet_nonfungible::weights::SubstrateWeight<Self>;870}871872impl pallet_unique::Config for Runtime {873	type Event = Event;874	type WeightInfo = pallet_unique::weights::SubstrateWeight<Self>;875}876877parameter_types! {878	pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied879}880881/// Used for the pallet inflation882impl pallet_inflation::Config for Runtime {883	type Currency = Balances;884	type TreasuryAccountId = TreasuryAccountId;885	type InflationBlockInterval = InflationBlockInterval;886	type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;887}888889// parameter_types! {890// 	pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *891// 		RuntimeBlockWeights::get().max_block;892// 	pub const MaxScheduledPerBlock: u32 = 50;893// }894895type EvmSponsorshipHandler = (896	pallet_unique::UniqueEthSponsorshipHandler<Runtime>,897	pallet_evm_contract_helpers::HelpersContractSponsoring<Runtime>,898);899type SponsorshipHandler = (900	pallet_unique::UniqueSponsorshipHandler<Runtime>,901	//pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,902	pallet_evm_transaction_payment::BridgeSponsorshipHandler<Runtime>,903);904905// impl pallet_unq_scheduler::Config for Runtime {906// 	type Event = Event;907// 	type Origin = Origin;908// 	type PalletsOrigin = OriginCaller;909// 	type Call = Call;910// 	type MaximumWeight = MaximumSchedulerWeight;911// 	type ScheduleOrigin = EnsureSigned<AccountId>;912// 	type MaxScheduledPerBlock = MaxScheduledPerBlock;913// 	type SponsorshipHandler = SponsorshipHandler;914// 	type WeightInfo = ();915// }916917impl pallet_evm_transaction_payment::Config for Runtime {918	type EvmSponsorshipHandler = EvmSponsorshipHandler;919	type Currency = Balances;920}921922impl pallet_charge_transaction::Config for Runtime {923	type SponsorshipHandler = SponsorshipHandler;924}925926// impl pallet_contract_helpers::Config for Runtime {927//	 type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;928// }929930parameter_types! {931	// 0x842899ECF380553E8a4de75bF534cdf6fBF64049932	pub const HelpersContractAddress: H160 = H160([933		0x84, 0x28, 0x99, 0xec, 0xf3, 0x80, 0x55, 0x3e, 0x8a, 0x4d, 0xe7, 0x5b, 0xf5, 0x34, 0xcd, 0xf6, 0xfb, 0xf6, 0x40, 0x49,934	]);935}936937impl pallet_evm_contract_helpers::Config for Runtime {938	type ContractAddress = HelpersContractAddress;939	type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;940}941942construct_runtime!(943	pub enum Runtime where944		Block = Block,945		NodeBlock = opaque::Block,946		UncheckedExtrinsic = UncheckedExtrinsic947	{948		ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Config, Storage, Inherent, Event<T>, ValidateUnsigned} = 20,949		ParachainInfo: parachain_info::{Pallet, Storage, Config} = 21,950951		Aura: pallet_aura::{Pallet, Config<T>} = 22,952		AuraExt: cumulus_pallet_aura_ext::{Pallet, Config} = 23,953954		Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 30,955		RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage} = 31,956		Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 32,957		TransactionPayment: pallet_transaction_payment::{Pallet, Storage} = 33,958		Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event<T>} = 34,959		Sudo: pallet_sudo::{Pallet, Call, Storage, Config<T>, Event<T>} = 35,960		System: frame_system::{Pallet, Call, Storage, Config, Event<T>} = 36,961		Vesting: orml_vesting::{Pallet, Storage, Call, Event<T>, Config<T>} = 37,962		// Vesting: pallet_vesting::{Pallet, Call, Config<T>, Storage, Event<T>} = 37,963		// Contracts: pallet_contracts::{Pallet, Call, Storage, Event<T>} = 38,964965		// XCM helpers.966		XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 50,967		PolkadotXcm: pallet_xcm::{Pallet, Call, Event<T>, Origin} = 51,968		CumulusXcm: cumulus_pallet_xcm::{Pallet, Call, Event<T>, Origin} = 52,969		DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,970971		// Unique Pallets972		Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,973		Unique: pallet_unique::{Pallet, Call, Storage, Event<T>} = 61,974		// Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,975		// free = 63976		Charging: pallet_charge_transaction::{Pallet, Call, Storage } = 64,977		// ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,978		Common: pallet_common::{Pallet, Storage, Event<T>} = 66,979		Fungible: pallet_fungible::{Pallet, Storage} = 67,980		Refungible: pallet_refungible::{Pallet, Storage} = 68,981		Nonfungible: pallet_nonfungible::{Pallet, Storage} = 69,982983		// Frontier984		EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,985		Ethereum: pallet_ethereum::{Pallet, Config, Call, Storage, Event, Origin} = 101,986987		EvmCoderSubstrate: pallet_evm_coder_substrate::{Pallet, Storage} = 150,988		EvmContractHelpers: pallet_evm_contract_helpers::{Pallet, Storage} = 151,989		EvmTransactionPayment: pallet_evm_transaction_payment::{Pallet} = 152,990		EvmMigration: pallet_evm_migration::{Pallet, Call, Storage} = 153,991	}992);993994pub struct TransactionConverter;995996impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {997	fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {998		UncheckedExtrinsic::new_unsigned(999			pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1000		)1001	}1002}10031004impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {1005	fn convert_transaction(1006		&self,1007		transaction: pallet_ethereum::Transaction,1008	) -> opaque::UncheckedExtrinsic {1009		let extrinsic = UncheckedExtrinsic::new_unsigned(1010			pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1011		);1012		let encoded = extrinsic.encode();1013		opaque::UncheckedExtrinsic::decode(&mut &encoded[..])1014			.expect("Encoded extrinsic is always valid")1015	}1016}10171018/// The address format for describing accounts.1019pub type Address = sp_runtime::MultiAddress<AccountId, ()>;1020/// Block header type as expected by this runtime.1021pub type Header = generic::Header<BlockNumber, BlakeTwo256>;1022/// Block type as expected by this runtime.1023pub type Block = generic::Block<Header, UncheckedExtrinsic>;1024/// A Block signed with a Justification1025pub type SignedBlock = generic::SignedBlock<Block>;1026/// BlockId type as expected by this runtime.1027pub type BlockId = generic::BlockId<Block>;1028/// The SignedExtension to the basic transaction logic.1029pub type SignedExtra = (1030	frame_system::CheckSpecVersion<Runtime>,1031	// system::CheckTxVersion<Runtime>,1032	frame_system::CheckGenesis<Runtime>,1033	frame_system::CheckEra<Runtime>,1034	frame_system::CheckNonce<Runtime>,1035	frame_system::CheckWeight<Runtime>,1036	pallet_charge_transaction::ChargeTransactionPayment<Runtime>,1037	//pallet_contract_helpers::ContractHelpersExtension<Runtime>,1038);1039/// Unchecked extrinsic type as expected by this runtime.1040pub type UncheckedExtrinsic =1041	fp_self_contained::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;1042/// Extrinsic type that has already been checked.1043pub type CheckedExtrinsic = fp_self_contained::CheckedExtrinsic<AccountId, Call, SignedExtra, H160>;1044/// Executive: handles dispatch to the various modules.1045pub type Executive = frame_executive::Executive<1046	Runtime,1047	Block,1048	frame_system::ChainContext<Runtime>,1049	Runtime,1050	AllPalletsReversedWithSystemFirst,1051>;10521053impl_opaque_keys! {1054	pub struct SessionKeys {1055		pub aura: Aura,1056	}1057}10581059impl fp_self_contained::SelfContainedCall for Call {1060	type SignedInfo = H160;10611062	fn is_self_contained(&self) -> bool {1063		match self {1064			Call::Ethereum(call) => call.is_self_contained(),1065			_ => false,1066		}1067	}10681069	fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {1070		match self {1071			Call::Ethereum(call) => call.check_self_contained(),1072			_ => None,1073		}1074	}10751076	fn validate_self_contained(&self, info: &Self::SignedInfo) -> Option<TransactionValidity> {1077		match self {1078			Call::Ethereum(call) => call.validate_self_contained(info),1079			_ => None,1080		}1081	}10821083	fn pre_dispatch_self_contained(1084		&self,1085		info: &Self::SignedInfo,1086	) -> Option<Result<(), TransactionValidityError>> {1087		match self {1088			Call::Ethereum(call) => call.pre_dispatch_self_contained(info),1089			_ => None,1090		}1091	}10921093	fn apply_self_contained(1094		self,1095		info: Self::SignedInfo,1096	) -> Option<sp_runtime::DispatchResultWithInfo<PostDispatchInfoOf<Self>>> {1097		match self {1098			call @ Call::Ethereum(pallet_ethereum::Call::transact { .. }) => Some(call.dispatch(1099				Origin::from(pallet_ethereum::RawOrigin::EthereumTransaction(info)),1100			)),1101			_ => None,1102		}1103	}1104}11051106macro_rules! dispatch_unique_runtime {1107	($collection:ident.$method:ident($($name:ident),*)) => {{1108		use pallet_unique::dispatch::Dispatched;11091110		let collection = Dispatched::dispatch(<pallet_common::CollectionHandle<Runtime>>::try_get($collection)?);1111		let dispatch = collection.as_dyn();11121113		Ok(dispatch.$method($($name),*))1114	}};1115}11161117impl_common_runtime_apis!();11181119struct CheckInherents;11201121impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {1122	fn check_inherents(1123		block: &Block,1124		relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,1125	) -> sp_inherents::CheckInherentsResult {1126		let relay_chain_slot = relay_state_proof1127			.read_slot()1128			.expect("Could not read the relay chain slot from the proof");11291130		let inherent_data =1131			cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(1132				relay_chain_slot,1133				sp_std::time::Duration::from_secs(6),1134			)1135			.create_inherent_data()1136			.expect("Could not create the timestamp inherent data");11371138		inherent_data.check_extrinsics(block)1139	}1140}11411142cumulus_pallet_parachain_system::register_validate_block!(1143	Runtime = Runtime,1144	BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,1145	CheckInherents = CheckInherents,1146);