git.delta.rocks / unique-network / refs/commits / 8f77dc2402c4

difftreelog

source

runtime/opal/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::{EnsureAddressTruncated, HashedAddressMapping, Runner};52pub use frame_support::{53	construct_runtime, match_type,54	dispatch::DispatchResult,55	PalletId, parameter_types, StorageValue, ConsensusEngineId,56	traits::{57		tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT, Everything,58		Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem, LockIdentifier,59		OnUnbalanced, Randomness, FindAuthor,60	},61	weights::{62		constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},63		DispatchClass, DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,64		WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients,65	},66};67use up_data_structs::*;68// use pallet_contracts::weights::WeightInfo;69// #[cfg(any(feature = "std", test))]70use frame_system::{71	self as frame_system, EnsureRoot, EnsureSigned,72	limits::{BlockWeights, BlockLength},73};74use sp_arithmetic::{75	traits::{BaseArithmetic, Unsigned},76};77use smallvec::smallvec;78use codec::{Encode, Decode};79use pallet_evm::{Account as EVMAccount, FeeCalculator, GasWeightMapping, OnMethodCall};80use fp_rpc::TransactionStatus;81use sp_runtime::{82	traits::{BlockNumberProvider, Dispatchable, PostDispatchInfoOf, Saturating},83	transaction_validity::TransactionValidityError,84	SaturatedConversion,85};8687// pub use pallet_timestamp::Call as TimestampCall;88pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;8990// Polkadot imports91use pallet_xcm::XcmPassthrough;92use polkadot_parachain::primitives::Sibling;93use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};94use xcm_builder::{95	AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter,96	EnsureXcmOrigin, FixedWeightBounds, LocationInverter, NativeAsset, ParentAsSuperuser,97	RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia,98	SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit,99	ParentIsPreset,100};101use xcm_executor::{Config, XcmExecutor, Assets};102use sp_std::{marker::PhantomData};103104use xcm::latest::{105	//	Xcm,106	AssetId::{Concrete},107	Fungibility::Fungible as XcmFungible,108	MultiAsset,109	Error as XcmError,110};111use xcm_executor::traits::{MatchesFungible, WeightTrader};112//use xcm_executor::traits::MatchesFungible;113use sp_runtime::traits::CheckedConversion;114115use unique_runtime_common::{impl_common_runtime_apis, types::*, constants::*};116117pub const RUNTIME_NAME: &str = "Opal";118119type CrossAccountId = pallet_common::account::BasicCrossAccountId<Runtime>;120121impl RuntimeInstance for Runtime {122	type CrossAccountId = self::CrossAccountId;123124	type TransactionConverter = self::TransactionConverter;125126	fn get_transaction_converter() -> TransactionConverter {127		TransactionConverter128	}129}130131/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know132/// the specifics of the runtime. They can then be made to be agnostic over specific formats133/// of data like extrinsics, allowing for them to continue syncing the network through upgrades134/// to even the core data structures.135pub mod opaque {136	use sp_std::prelude::*;137	use sp_runtime::impl_opaque_keys;138	use super::Aura;139140	pub use unique_runtime_common::types::*;141142	impl_opaque_keys! {143		pub struct SessionKeys {144			pub aura: Aura,145		}146	}147}148149/// This runtime version.150pub const VERSION: RuntimeVersion = RuntimeVersion {151	spec_name: create_runtime_str!(RUNTIME_NAME),152	impl_name: create_runtime_str!(RUNTIME_NAME),153	authoring_version: 1,154	spec_version: 917004,155	impl_version: 0,156	apis: RUNTIME_API_VERSIONS,157	transaction_version: 1,158	state_version: 0,159};160161#[derive(codec::Encode, codec::Decode)]162pub enum XCMPMessage<XAccountId, XBalance> {163	/// Transfer tokens to the given account from the Parachain account.164	TransferToken(XAccountId, XBalance),165}166167/// The version information used to identify this runtime when compiled natively.168#[cfg(feature = "std")]169pub fn native_version() -> NativeVersion {170	NativeVersion {171		runtime_version: VERSION,172		can_author_with: Default::default(),173	}174}175176type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;177178pub struct DealWithFees;179impl OnUnbalanced<NegativeImbalance> for DealWithFees {180	fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {181		if let Some(fees) = fees_then_tips.next() {182			// for fees, 100% to treasury183			let mut split = fees.ration(100, 0);184			if let Some(tips) = fees_then_tips.next() {185				// for tips, if any, 100% to treasury186				tips.ration_merge_into(100, 0, &mut split);187			}188			Treasury::on_unbalanced(split.0);189			// Author::on_unbalanced(split.1);190		}191	}192}193194parameter_types! {195	pub const BlockHashCount: BlockNumber = 2400;196	pub RuntimeBlockLength: BlockLength =197		BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);198	pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);199	pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;200	pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()201		.base_block(BlockExecutionWeight::get())202		.for_class(DispatchClass::all(), |weights| {203			weights.base_extrinsic = ExtrinsicBaseWeight::get();204		})205		.for_class(DispatchClass::Normal, |weights| {206			weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);207		})208		.for_class(DispatchClass::Operational, |weights| {209			weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);210			// Operational transactions have some extra reserved space, so that they211			// are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.212			weights.reserved = Some(213				MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT214			);215		})216		.avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)217		.build_or_panic();218	pub const Version: RuntimeVersion = VERSION;219	pub const SS58Prefix: u8 = 42;220}221222parameter_types! {223	pub const ChainId: u64 = 8882;224}225226pub struct FixedFee;227impl FeeCalculator for FixedFee {228	fn min_gas_price() -> U256 {229		// Targeting 0.15 UNQ per transfer230		1_018_751_825_264u64.into()231	}232}233234// Assuming slowest ethereum opcode is SSTORE, with gas price of 20000 as our worst case235// (contract, which only writes a lot of data),236// approximating on top of our real store write weight237parameter_types! {238	pub const WritesPerSecond: u64 = WEIGHT_PER_SECOND / <Runtime as frame_system::Config>::DbWeight::get().write;239	pub const GasPerSecond: u64 = WritesPerSecond::get() * 20000;240	pub const WeightPerGas: u64 = WEIGHT_PER_SECOND / GasPerSecond::get();241}242243/// Limiting EVM execution to 50% of block for substrate users and management tasks244/// EVM transaction consumes more weight than substrate's, so we can't rely on them being245/// scheduled fairly246const EVM_DISPATCH_RATIO: Perbill = Perbill::from_percent(50);247parameter_types! {248	pub BlockGasLimit: U256 = U256::from(NORMAL_DISPATCH_RATIO * EVM_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT / WeightPerGas::get());249}250251pub enum FixedGasWeightMapping {}252impl GasWeightMapping for FixedGasWeightMapping {253	fn gas_to_weight(gas: u64) -> Weight {254		gas.saturating_mul(WeightPerGas::get())255	}256	fn weight_to_gas(weight: Weight) -> u64 {257		weight / WeightPerGas::get()258	}259}260261impl pallet_evm::Config for Runtime {262	type BlockGasLimit = BlockGasLimit;263	type FeeCalculator = FixedFee;264	type GasWeightMapping = FixedGasWeightMapping;265	type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;266	type CallOrigin = EnsureAddressTruncated;267	type WithdrawOrigin = EnsureAddressTruncated;268	type AddressMapping = HashedAddressMapping<Self::Hashing>;269	type PrecompilesType = ();270	type PrecompilesValue = ();271	type Currency = Balances;272	type Event = Event;273	type OnMethodCall = (274		pallet_evm_migration::OnMethodCall<Self>,275		pallet_unique::UniqueErcSupport<Self>,276		pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,277	);278	type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;279	type ChainId = ChainId;280	type Runner = pallet_evm::runner::stack::Runner<Self>;281	type OnChargeTransaction = pallet_evm_transaction_payment::OnChargeTransaction<Self>;282	type TransactionValidityHack = pallet_evm_transaction_payment::TransactionValidityHack<Self>;283	type FindAuthor = EthereumFindAuthor<Aura>;284}285286impl pallet_evm_migration::Config for Runtime {287	type WeightInfo = pallet_evm_migration::weights::SubstrateWeight<Self>;288}289290pub struct EthereumFindAuthor<F>(core::marker::PhantomData<F>);291impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F> {292	fn find_author<'a, I>(digests: I) -> Option<H160>293	where294		I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,295	{296		if let Some(author_index) = F::find_author(digests) {297			let authority_id = Aura::authorities()[author_index as usize].clone();298			return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24]));299		}300		None301	}302}303304impl pallet_ethereum::Config for Runtime {305	type Event = Event;306	type StateRoot = pallet_ethereum::IntermediateStateRoot;307}308309impl pallet_randomness_collective_flip::Config for Runtime {}310311impl frame_system::Config for Runtime {312	/// The data to be stored in an account.313	type AccountData = pallet_balances::AccountData<Balance>;314	/// The identifier used to distinguish between accounts.315	type AccountId = AccountId;316	/// The basic call filter to use in dispatchable.317	type BaseCallFilter = Everything;318	/// Maximum number of block number to block hash mappings to keep (oldest pruned first).319	type BlockHashCount = BlockHashCount;320	/// The maximum length of a block (in bytes).321	type BlockLength = RuntimeBlockLength;322	/// The index type for blocks.323	type BlockNumber = BlockNumber;324	/// The weight of the overhead invoked on the block import process, independent of the extrinsics included in that block.325	type BlockWeights = RuntimeBlockWeights;326	/// The aggregated dispatch type that is available for extrinsics.327	type Call = Call;328	/// The weight of database operations that the runtime can invoke.329	type DbWeight = RocksDbWeight;330	/// The ubiquitous event type.331	type Event = Event;332	/// The type for hashing blocks and tries.333	type Hash = Hash;334	/// The hashing algorithm used.335	type Hashing = BlakeTwo256;336	/// The header type.337	type Header = generic::Header<BlockNumber, BlakeTwo256>;338	/// The index type for storing how many extrinsics an account has signed.339	type Index = Index;340	/// The lookup mechanism to get account ID from whatever is passed in dispatchers.341	type Lookup = AccountIdLookup<AccountId, ()>;342	/// What to do if an account is fully reaped from the system.343	type OnKilledAccount = ();344	/// What to do if a new account is created.345	type OnNewAccount = ();346	type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;347	/// The ubiquitous origin type.348	type Origin = Origin;349	/// This type is being generated by `construct_runtime!`.350	type PalletInfo = PalletInfo;351	/// This is used as an identifier of the chain. 42 is the generic substrate prefix.352	type SS58Prefix = SS58Prefix;353	/// Weight information for the extrinsics of this pallet.354	type SystemWeightInfo = frame_system::weights::SubstrateWeight<Self>;355	/// Version of the runtime.356	type Version = Version;357	type MaxConsumers = ConstU32<16>;358}359360parameter_types! {361	pub const MinimumPeriod: u64 = SLOT_DURATION / 2;362}363364impl pallet_timestamp::Config for Runtime {365	/// A timestamp: milliseconds since the unix epoch.366	type Moment = u64;367	type OnTimestampSet = ();368	type MinimumPeriod = MinimumPeriod;369	type WeightInfo = ();370}371372parameter_types! {373	// pub const ExistentialDeposit: u128 = 500;374	pub const ExistentialDeposit: u128 = 0;375	pub const MaxLocks: u32 = 50;376}377378impl pallet_balances::Config for Runtime {379	type MaxLocks = MaxLocks;380	type MaxReserves = ();381	type ReserveIdentifier = [u8; 8];382	/// The type for recording an account's balance.383	type Balance = Balance;384	/// The ubiquitous event type.385	type Event = Event;386	type DustRemoval = Treasury;387	type ExistentialDeposit = ExistentialDeposit;388	type AccountStore = System;389	type WeightInfo = pallet_balances::weights::SubstrateWeight<Self>;390}391392pub const fn deposit(items: u32, bytes: u32) -> Balance {393	items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE394}395396/*397parameter_types! {398	pub TombstoneDeposit: Balance = deposit(399		1,400		sp_std::mem::size_of::<pallet_contracts::Pallet<Runtime>> as u32,401	);402	pub DepositPerContract: Balance = TombstoneDeposit::get();403	pub const DepositPerStorageByte: Balance = deposit(0, 1);404	pub const DepositPerStorageItem: Balance = deposit(1, 0);405	pub RentFraction: Perbill = Perbill::from_rational(1u32, 30 * DAYS);406	pub const SurchargeReward: Balance = 150 * MILLIUNIQUE;407	pub const SignedClaimHandicap: u32 = 2;408	pub const MaxDepth: u32 = 32;409	pub const MaxValueSize: u32 = 16 * 1024;410	pub const MaxCodeSize: u32 = 1024 * 1024 * 25; // 25 Mb411	// The lazy deletion runs inside on_initialize.412	pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO *413		RuntimeBlockWeights::get().max_block;414	// The weight needed for decoding the queue should be less or equal than a fifth415	// of the overall weight dedicated to the lazy deletion.416	pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (417			<Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -418			<Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)419		)) / 5) as u32;420	pub Schedule: pallet_contracts::Schedule<Runtime> = Default::default();421}422423impl pallet_contracts::Config for Runtime {424	type Time = Timestamp;425	type Randomness = RandomnessCollectiveFlip;426	type Currency = Balances;427	type Event = Event;428	type RentPayment = ();429	type SignedClaimHandicap = SignedClaimHandicap;430	type TombstoneDeposit = TombstoneDeposit;431	type DepositPerContract = DepositPerContract;432	type DepositPerStorageByte = DepositPerStorageByte;433	type DepositPerStorageItem = DepositPerStorageItem;434	type RentFraction = RentFraction;435	type SurchargeReward = SurchargeReward;436	type WeightPrice = pallet_transaction_payment::Pallet<Self>;437	type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;438	type ChainExtension = NFTExtension;439	type DeletionQueueDepth = DeletionQueueDepth;440	type DeletionWeightLimit = DeletionWeightLimit;441	type Schedule = Schedule;442	type CallStack = [pallet_contracts::Frame<Self>; 31];443}444*/445446parameter_types! {447	/// This value increases the priority of `Operational` transactions by adding448	/// a "virtual tip" that's equal to the `OperationalFeeMultiplier * final_fee`.449	pub const OperationalFeeMultiplier: u8 = 5;450}451452/// Linear implementor of `WeightToFeePolynomial`453pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);454455impl<T> WeightToFeePolynomial for LinearFee<T>456where457	T: BaseArithmetic + From<u32> + Copy + Unsigned,458{459	type Balance = T;460461	fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {462		smallvec!(WeightToFeeCoefficient {463			// Targeting 0.1 Unique per NFT transfer464			coeff_integer: WEIGHT_TO_FEE_COEFF.into(),465			coeff_frac: Perbill::zero(),466			negative: false,467			degree: 1,468		})469	}470}471472impl pallet_transaction_payment::Config for Runtime {473	type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, DealWithFees>;474	type TransactionByteFee = TransactionByteFee;475	type OperationalFeeMultiplier = OperationalFeeMultiplier;476	type WeightToFee = LinearFee<Balance>;477	type FeeMultiplierUpdate = ();478}479480parameter_types! {481	pub const ProposalBond: Permill = Permill::from_percent(5);482	pub const ProposalBondMinimum: Balance = 1 * UNIQUE;483	pub const ProposalBondMaximum: Balance = 1000 * UNIQUE;484	pub const SpendPeriod: BlockNumber = 5 * MINUTES;485	pub const Burn: Permill = Permill::from_percent(0);486	pub const TipCountdown: BlockNumber = 1 * DAYS;487	pub const TipFindersFee: Percent = Percent::from_percent(20);488	pub const TipReportDepositBase: Balance = 1 * UNIQUE;489	pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;490	pub const BountyDepositBase: Balance = 1 * UNIQUE;491	pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;492	pub const TreasuryModuleId: PalletId = PalletId(*b"py/trsry");493	pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;494	pub const MaximumReasonLength: u32 = 16384;495	pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);496	pub const BountyValueMinimum: Balance = 5 * UNIQUE;497	pub const MaxApprovals: u32 = 100;498}499500impl pallet_treasury::Config for Runtime {501	type PalletId = TreasuryModuleId;502	type Currency = Balances;503	type ApproveOrigin = EnsureRoot<AccountId>;504	type RejectOrigin = EnsureRoot<AccountId>;505	type Event = Event;506	type OnSlash = ();507	type ProposalBond = ProposalBond;508	type ProposalBondMinimum = ProposalBondMinimum;509	type ProposalBondMaximum = ProposalBondMaximum;510	type SpendPeriod = SpendPeriod;511	type Burn = Burn;512	type BurnDestination = ();513	type SpendFunds = ();514	type WeightInfo = pallet_treasury::weights::SubstrateWeight<Self>;515	type MaxApprovals = MaxApprovals;516}517518impl pallet_sudo::Config for Runtime {519	type Event = Event;520	type Call = Call;521}522523pub struct RelayChainBlockNumberProvider<T>(sp_std::marker::PhantomData<T>);524525impl<T: cumulus_pallet_parachain_system::Config> BlockNumberProvider526	for RelayChainBlockNumberProvider<T>527{528	type BlockNumber = BlockNumber;529530	fn current_block_number() -> Self::BlockNumber {531		cumulus_pallet_parachain_system::Pallet::<T>::validation_data()532			.map(|d| d.relay_parent_number)533			.unwrap_or_default()534	}535}536537parameter_types! {538	pub const MinVestedTransfer: Balance = 10 * UNIQUE;539	pub const MaxVestingSchedules: u32 = 28;540}541542impl orml_vesting::Config for Runtime {543	type Event = Event;544	type Currency = pallet_balances::Pallet<Runtime>;545	type MinVestedTransfer = MinVestedTransfer;546	type VestedTransferOrigin = EnsureSigned<AccountId>;547	type WeightInfo = ();548	type MaxVestingSchedules = MaxVestingSchedules;549	type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;550}551552parameter_types! {553	pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;554	pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;555}556557impl cumulus_pallet_parachain_system::Config for Runtime {558	type Event = Event;559	type SelfParaId = parachain_info::Pallet<Self>;560	type OnSystemEvent = ();561	// type DownwardMessageHandlers = cumulus_primitives_utility::UnqueuedDmpAsParent<562	// 	MaxDownwardMessageWeight,563	// 	XcmExecutor<XcmConfig>,564	// 	Call,565	// >;566	type OutboundXcmpMessageSource = XcmpQueue;567	type DmpMessageHandler = DmpQueue;568	type ReservedDmpWeight = ReservedDmpWeight;569	type ReservedXcmpWeight = ReservedXcmpWeight;570	type XcmpMessageHandler = XcmpQueue;571}572573impl parachain_info::Config for Runtime {}574575impl cumulus_pallet_aura_ext::Config for Runtime {}576577parameter_types! {578	pub const RelayLocation: MultiLocation = MultiLocation::parent();579	pub const RelayNetwork: NetworkId = NetworkId::Polkadot;580	pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();581	pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();582}583584/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used585/// when determining ownership of accounts for asset transacting and when attempting to use XCM586/// `Transact` in order to determine the dispatch Origin.587pub type LocationToAccountId = (588	// The parent (Relay-chain) origin converts to the default `AccountId`.589	ParentIsPreset<AccountId>,590	// Sibling parachain origins convert to AccountId via the `ParaId::into`.591	SiblingParachainConvertsVia<Sibling, AccountId>,592	// Straight up local `AccountId32` origins just alias directly to `AccountId`.593	AccountId32Aliases<RelayNetwork, AccountId>,594);595596pub struct OnlySelfCurrency;597impl<B: TryFrom<u128>> MatchesFungible<B> for OnlySelfCurrency {598	fn matches_fungible(a: &MultiAsset) -> Option<B> {599		match (&a.id, &a.fun) {600			(Concrete(_), XcmFungible(ref amount)) => CheckedConversion::checked_from(*amount),601			_ => None,602		}603	}604}605606/// Means for transacting assets on this chain.607pub type LocalAssetTransactor = CurrencyAdapter<608	// Use this currency:609	Balances,610	// Use this currency when it is a fungible asset matching the given location or name:611	OnlySelfCurrency,612	// Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:613	LocationToAccountId,614	// Our chain's account ID type (we can't get away without mentioning it explicitly):615	AccountId,616	// We don't track any teleports.617	(),618>;619620/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,621/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can622/// biases the kind of local `Origin` it will become.623pub type XcmOriginToTransactDispatchOrigin = (624	// Sovereign account converter; this attempts to derive an `AccountId` from the origin location625	// using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for626	// foreign chains who want to have a local sovereign account on this chain which they control.627	SovereignSignedViaLocation<LocationToAccountId, Origin>,628	// Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when629	// recognised.630	RelayChainAsNative<RelayOrigin, Origin>,631	// Native converter for sibling Parachains; will convert to a `SiblingPara` origin when632	// recognised.633	SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,634	// Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a635	// transaction from the Root origin.636	ParentAsSuperuser<Origin>,637	// Native signed account converter; this just converts an `AccountId32` origin into a normal638	// `Origin::Signed` origin of the same 32-byte value.639	SignedAccountId32AsNative<RelayNetwork, Origin>,640	// Xcm origins can be represented natively under the Xcm pallet's Xcm origin.641	XcmPassthrough<Origin>,642);643644parameter_types! {645	// One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.646	pub UnitWeightCost: Weight = 1_000_000;647	// 1200 UNIQUEs buy 1 second of weight.648	pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);649	pub const MaxInstructions: u32 = 100;650	pub const MaxAuthorities: u32 = 100_000;651}652653match_type! {654	pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {655		MultiLocation { parents: 1, interior: Here } |656		MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }657	};658}659660pub type Barrier = (661	TakeWeightCredit,662	AllowTopLevelPaidExecutionFrom<Everything>,663	AllowUnpaidExecutionFrom<ParentOrParentsUnitPlurality>,664	// ^^^ Parent & its unit plurality gets free execution665);666667pub struct UsingOnlySelfCurrencyComponents<668	WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,669	AssetId: Get<MultiLocation>,670	AccountId,671	Currency: CurrencyT<AccountId>,672	OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,673>(674	Weight,675	Currency::Balance,676	PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>,677);678impl<679		WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,680		AssetId: Get<MultiLocation>,681		AccountId,682		Currency: CurrencyT<AccountId>,683		OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,684	> WeightTrader685	for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>686{687	fn new() -> Self {688		Self(0, Zero::zero(), PhantomData)689	}690691	fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {692		let amount = WeightToFee::calc(&weight);693		let u128_amount: u128 = amount.try_into().map_err(|_| XcmError::Overflow)?;694695		// location to this parachain through relay chain696		let option1: xcm::v1::AssetId = Concrete(MultiLocation {697			parents: 1,698			interior: X1(Parachain(ParachainInfo::parachain_id().into())),699		});700		// direct location701		let option2: xcm::v1::AssetId = Concrete(MultiLocation {702			parents: 0,703			interior: Here,704		});705706		let required = if payment.fungible.contains_key(&option1) {707			(option1, u128_amount).into()708		} else if payment.fungible.contains_key(&option2) {709			(option2, u128_amount).into()710		} else {711			(Concrete(MultiLocation::default()), u128_amount).into()712		};713714		let unused = payment715			.checked_sub(required)716			.map_err(|_| XcmError::TooExpensive)?;717		self.0 = self.0.saturating_add(weight);718		self.1 = self.1.saturating_add(amount);719		Ok(unused)720	}721722	fn refund_weight(&mut self, weight: Weight) -> Option<MultiAsset> {723		let weight = weight.min(self.0);724		let amount = WeightToFee::calc(&weight);725		self.0 -= weight;726		self.1 = self.1.saturating_sub(amount);727		let amount: u128 = amount.saturated_into();728		if amount > 0 {729			Some((AssetId::get(), amount).into())730		} else {731			None732		}733	}734}735impl<736		WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,737		AssetId: Get<MultiLocation>,738		AccountId,739		Currency: CurrencyT<AccountId>,740		OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,741	> Drop742	for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>743{744	fn drop(&mut self) {745		OnUnbalanced::on_unbalanced(Currency::issue(self.1));746	}747}748749pub struct XcmConfig;750impl Config for XcmConfig {751	type Call = Call;752	type XcmSender = XcmRouter;753	// How to withdraw and deposit an asset.754	type AssetTransactor = LocalAssetTransactor;755	type OriginConverter = XcmOriginToTransactDispatchOrigin;756	type IsReserve = NativeAsset;757	type IsTeleporter = (); // Teleportation is disabled758	type LocationInverter = LocationInverter<Ancestry>;759	type Barrier = Barrier;760	type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;761	type Trader = UsingOnlySelfCurrencyComponents<762		IdentityFee<Balance>,763		RelayLocation,764		AccountId,765		Balances,766		(),767	>;768	type ResponseHandler = (); // Don't handle responses for now.769	type SubscriptionService = PolkadotXcm;770771	type AssetTrap = PolkadotXcm;772	type AssetClaims = PolkadotXcm;773}774775// parameter_types! {776// 	pub const MaxDownwardMessageWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 10;777// }778779/// No local origins on this chain are allowed to dispatch XCM sends/executions.780pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);781782/// The means for routing XCM messages which are not for local execution into the right message783/// queues.784pub type XcmRouter = (785	// Two routers - use UMP to communicate with the relay chain:786	cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,787	// ..and XCMP to communicate with the sibling chains.788	XcmpQueue,789);790791impl pallet_evm_coder_substrate::Config for Runtime {792	type EthereumTransactionSender = pallet_ethereum::Pallet<Self>;793	type GasWeightMapping = FixedGasWeightMapping;794}795796impl pallet_xcm::Config for Runtime {797	type Event = Event;798	type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;799	type XcmRouter = XcmRouter;800	type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;801	type XcmExecuteFilter = Everything;802	type XcmExecutor = XcmExecutor<XcmConfig>;803	type XcmTeleportFilter = Everything;804	type XcmReserveTransferFilter = Everything;805	type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;806	type LocationInverter = LocationInverter<Ancestry>;807	type Origin = Origin;808	type Call = Call;809	const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;810	type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;811}812813impl cumulus_pallet_xcm::Config for Runtime {814	type Event = Event;815	type XcmExecutor = XcmExecutor<XcmConfig>;816}817818impl cumulus_pallet_xcmp_queue::Config for Runtime {819	type Event = Event;820	type XcmExecutor = XcmExecutor<XcmConfig>;821	type ChannelInfo = ParachainSystem;822	type VersionWrapper = ();823	type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;824	type ControllerOrigin = EnsureRoot<AccountId>;825	type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;826}827828impl cumulus_pallet_dmp_queue::Config for Runtime {829	type Event = Event;830	type XcmExecutor = XcmExecutor<XcmConfig>;831	type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;832}833834impl pallet_aura::Config for Runtime {835	type AuthorityId = AuraId;836	type DisabledValidators = ();837	type MaxAuthorities = MaxAuthorities;838}839840parameter_types! {841	pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();842	pub const CollectionCreationPrice: Balance = 2 * UNIQUE;843}844845impl pallet_common::Config for Runtime {846	type Event = Event;847	type EvmBackwardsAddressMapping = up_evm_mapping::MapBackwardsAddressTruncated;848	type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;849	type CrossAccountId = pallet_common::account::BasicCrossAccountId<Self>;850851	type Currency = Balances;852	type CollectionCreationPrice = CollectionCreationPrice;853	type TreasuryAccountId = TreasuryAccountId;854}855856impl pallet_fungible::Config for Runtime {857	type WeightInfo = pallet_fungible::weights::SubstrateWeight<Self>;858}859impl pallet_refungible::Config for Runtime {860	type WeightInfo = pallet_refungible::weights::SubstrateWeight<Self>;861}862impl pallet_nonfungible::Config for Runtime {863	type WeightInfo = pallet_nonfungible::weights::SubstrateWeight<Self>;864}865866impl pallet_unique::Config for Runtime {867	type Event = Event;868	type WeightInfo = pallet_unique::weights::SubstrateWeight<Self>;869}870871parameter_types! {872	pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied873}874875/// Used for the pallet inflation876impl pallet_inflation::Config for Runtime {877	type Currency = Balances;878	type TreasuryAccountId = TreasuryAccountId;879	type InflationBlockInterval = InflationBlockInterval;880	type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;881}882883// parameter_types! {884// 	pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *885// 		RuntimeBlockWeights::get().max_block;886// 	pub const MaxScheduledPerBlock: u32 = 50;887// }888889type EvmSponsorshipHandler = (890	pallet_unique::UniqueEthSponsorshipHandler<Runtime>,891	pallet_evm_contract_helpers::HelpersContractSponsoring<Runtime>,892);893type SponsorshipHandler = (894	pallet_unique::UniqueSponsorshipHandler<Runtime>,895	//pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,896	pallet_evm_transaction_payment::BridgeSponsorshipHandler<Runtime>,897);898899// impl pallet_unq_scheduler::Config for Runtime {900// 	type Event = Event;901// 	type Origin = Origin;902// 	type PalletsOrigin = OriginCaller;903// 	type Call = Call;904// 	type MaximumWeight = MaximumSchedulerWeight;905// 	type ScheduleOrigin = EnsureSigned<AccountId>;906// 	type MaxScheduledPerBlock = MaxScheduledPerBlock;907// 	type SponsorshipHandler = SponsorshipHandler;908// 	type WeightInfo = ();909// }910911impl pallet_evm_transaction_payment::Config for Runtime {912	type EvmSponsorshipHandler = EvmSponsorshipHandler;913	type Currency = Balances;914	type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;915	type EvmBackwardsAddressMapping = up_evm_mapping::MapBackwardsAddressTruncated;916}917918impl pallet_charge_transaction::Config for Runtime {919	type SponsorshipHandler = SponsorshipHandler;920}921922// impl pallet_contract_helpers::Config for Runtime {923//	 type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;924// }925926parameter_types! {927	// 0x842899ECF380553E8a4de75bF534cdf6fBF64049928	pub const HelpersContractAddress: H160 = H160([929		0x84, 0x28, 0x99, 0xec, 0xf3, 0x80, 0x55, 0x3e, 0x8a, 0x4d, 0xe7, 0x5b, 0xf5, 0x34, 0xcd, 0xf6, 0xfb, 0xf6, 0x40, 0x49,930	]);931}932933impl pallet_evm_contract_helpers::Config for Runtime {934	type ContractAddress = HelpersContractAddress;935	type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;936}937938construct_runtime!(939	pub enum Runtime where940		Block = Block,941		NodeBlock = opaque::Block,942		UncheckedExtrinsic = UncheckedExtrinsic943	{944		ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Config, Storage, Inherent, Event<T>, ValidateUnsigned} = 20,945		ParachainInfo: parachain_info::{Pallet, Storage, Config} = 21,946947		Aura: pallet_aura::{Pallet, Config<T>} = 22,948		AuraExt: cumulus_pallet_aura_ext::{Pallet, Config} = 23,949950		Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 30,951		RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage} = 31,952		Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 32,953		TransactionPayment: pallet_transaction_payment::{Pallet, Storage} = 33,954		Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event<T>} = 34,955		Sudo: pallet_sudo::{Pallet, Call, Storage, Config<T>, Event<T>} = 35,956		System: frame_system::{Pallet, Call, Storage, Config, Event<T>} = 36,957		Vesting: orml_vesting::{Pallet, Storage, Call, Event<T>, Config<T>} = 37,958		// Vesting: pallet_vesting::{Pallet, Call, Config<T>, Storage, Event<T>} = 37,959		// Contracts: pallet_contracts::{Pallet, Call, Storage, Event<T>} = 38,960961		// XCM helpers.962		XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 50,963		PolkadotXcm: pallet_xcm::{Pallet, Call, Event<T>, Origin} = 51,964		CumulusXcm: cumulus_pallet_xcm::{Pallet, Call, Event<T>, Origin} = 52,965		DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,966967		// Unique Pallets968		Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,969		Unique: pallet_unique::{Pallet, Call, Storage, Event<T>} = 61,970		// Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,971		// free = 63972		Charging: pallet_charge_transaction::{Pallet, Call, Storage } = 64,973		// ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,974		Common: pallet_common::{Pallet, Storage, Event<T>} = 66,975		Fungible: pallet_fungible::{Pallet, Storage} = 67,976		Refungible: pallet_refungible::{Pallet, Storage} = 68,977		Nonfungible: pallet_nonfungible::{Pallet, Storage} = 69,978979		// Frontier980		EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,981		Ethereum: pallet_ethereum::{Pallet, Config, Call, Storage, Event, Origin} = 101,982983		EvmCoderSubstrate: pallet_evm_coder_substrate::{Pallet, Storage} = 150,984		EvmContractHelpers: pallet_evm_contract_helpers::{Pallet, Storage} = 151,985		EvmTransactionPayment: pallet_evm_transaction_payment::{Pallet} = 152,986		EvmMigration: pallet_evm_migration::{Pallet, Call, Storage} = 153,987	}988);989990pub struct TransactionConverter;991992impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {993	fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {994		UncheckedExtrinsic::new_unsigned(995			pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),996		)997	}998}9991000impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {1001	fn convert_transaction(1002		&self,1003		transaction: pallet_ethereum::Transaction,1004	) -> opaque::UncheckedExtrinsic {1005		let extrinsic = UncheckedExtrinsic::new_unsigned(1006			pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1007		);1008		let encoded = extrinsic.encode();1009		opaque::UncheckedExtrinsic::decode(&mut &encoded[..])1010			.expect("Encoded extrinsic is always valid")1011	}1012}10131014/// The address format for describing accounts.1015pub type Address = sp_runtime::MultiAddress<AccountId, ()>;1016/// Block header type as expected by this runtime.1017pub type Header = generic::Header<BlockNumber, BlakeTwo256>;1018/// Block type as expected by this runtime.1019pub type Block = generic::Block<Header, UncheckedExtrinsic>;1020/// A Block signed with a Justification1021pub type SignedBlock = generic::SignedBlock<Block>;1022/// BlockId type as expected by this runtime.1023pub type BlockId = generic::BlockId<Block>;1024/// The SignedExtension to the basic transaction logic.1025pub type SignedExtra = (1026	frame_system::CheckSpecVersion<Runtime>,1027	// system::CheckTxVersion<Runtime>,1028	frame_system::CheckGenesis<Runtime>,1029	frame_system::CheckEra<Runtime>,1030	frame_system::CheckNonce<Runtime>,1031	frame_system::CheckWeight<Runtime>,1032	pallet_charge_transaction::ChargeTransactionPayment<Runtime>,1033	//pallet_contract_helpers::ContractHelpersExtension<Runtime>,1034);1035/// Unchecked extrinsic type as expected by this runtime.1036pub type UncheckedExtrinsic =1037	fp_self_contained::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;1038/// Extrinsic type that has already been checked.1039pub type CheckedExtrinsic = fp_self_contained::CheckedExtrinsic<AccountId, Call, SignedExtra, H160>;1040/// Executive: handles dispatch to the various modules.1041pub type Executive = frame_executive::Executive<1042	Runtime,1043	Block,1044	frame_system::ChainContext<Runtime>,1045	Runtime,1046	AllPalletsReversedWithSystemFirst,1047>;10481049impl_opaque_keys! {1050	pub struct SessionKeys {1051		pub aura: Aura,1052	}1053}10541055impl fp_self_contained::SelfContainedCall for Call {1056	type SignedInfo = H160;10571058	fn is_self_contained(&self) -> bool {1059		match self {1060			Call::Ethereum(call) => call.is_self_contained(),1061			_ => false,1062		}1063	}10641065	fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {1066		match self {1067			Call::Ethereum(call) => call.check_self_contained(),1068			_ => None,1069		}1070	}10711072	fn validate_self_contained(&self, info: &Self::SignedInfo) -> Option<TransactionValidity> {1073		match self {1074			Call::Ethereum(call) => call.validate_self_contained(info),1075			_ => None,1076		}1077	}10781079	fn pre_dispatch_self_contained(1080		&self,1081		info: &Self::SignedInfo,1082	) -> Option<Result<(), TransactionValidityError>> {1083		match self {1084			Call::Ethereum(call) => call.pre_dispatch_self_contained(info),1085			_ => None,1086		}1087	}10881089	fn apply_self_contained(1090		self,1091		info: Self::SignedInfo,1092	) -> Option<sp_runtime::DispatchResultWithInfo<PostDispatchInfoOf<Self>>> {1093		match self {1094			call @ Call::Ethereum(pallet_ethereum::Call::transact { .. }) => Some(call.dispatch(1095				Origin::from(pallet_ethereum::RawOrigin::EthereumTransaction(info)),1096			)),1097			_ => None,1098		}1099	}1100}11011102macro_rules! dispatch_unique_runtime {1103	($collection:ident.$method:ident($($name:ident),*)) => {{1104		use pallet_unique::dispatch::Dispatched;11051106		let collection = Dispatched::dispatch(<pallet_common::CollectionHandle<Runtime>>::try_get($collection)?);1107		let dispatch = collection.as_dyn();11081109		Ok(dispatch.$method($($name),*))1110	}};1111}11121113impl_common_runtime_apis!();11141115struct CheckInherents;11161117impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {1118	fn check_inherents(1119		block: &Block,1120		relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,1121	) -> sp_inherents::CheckInherentsResult {1122		let relay_chain_slot = relay_state_proof1123			.read_slot()1124			.expect("Could not read the relay chain slot from the proof");11251126		let inherent_data =1127			cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(1128				relay_chain_slot,1129				sp_std::time::Duration::from_secs(6),1130			)1131			.create_inherent_data()1132			.expect("Could not create the timestamp inherent data");11331134		inherent_data.check_extrinsics(block)1135	}1136}11371138cumulus_pallet_parachain_system::register_validate_block!(1139	Runtime = Runtime,1140	BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,1141	CheckInherents = CheckInherents,1142);