git.delta.rocks / unique-network / refs/commits / 4dbeda6769b2

difftreelog

source

runtime/src/lib.rs38.3 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"]1112// Make the WASM binary available.13#[cfg(feature = "std")]14include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));1516use sp_api::impl_runtime_apis;17use sp_core::{ crypto::KeyTypeId, OpaqueMetadata };18// #[cfg(any(feature = "std", test))]19// pub use sp_runtime::BuildStorage;2021use sp_runtime::{22    Permill, Perbill, Percent,23    create_runtime_str, generic, impl_opaque_keys,24    traits::{25        AccountIdLookup, ConvertInto, BlakeTwo256, Block as BlockT, IdentifyAccount, 26		Verify, AccountIdConversion,27    },28    transaction_validity::{TransactionSource, TransactionValidity},29    ApplyExtrinsicResult, MultiSignature,30};3132use sp_std::prelude::*;3334#[cfg(feature = "std")]35use sp_version::NativeVersion;36use sp_version::RuntimeVersion;37pub use pallet_transaction_payment::{Multiplier, TargetedFeeAdjustment, FeeDetails, RuntimeDispatchInfo};38// A few exports that help ease life for downstream crates.39pub use pallet_balances::Call as BalancesCall;40pub use pallet_evm::{EnsureAddressTruncated, HashedAddressMapping, Runner};41pub use frame_support::{42    construct_runtime,43	match_type,44    dispatch::DispatchResult,45	PalletId,46    parameter_types,47    StorageValue,48    traits::{49        All, Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem, LockIdentifier, OnUnbalanced, Randomness50    },51    weights::{52        constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},53        DispatchClass, DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,54        WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients55    },56};57use nft_data_structs::*;58use pallet_contracts::weights::WeightInfo;59// #[cfg(any(feature = "std", test))]60use frame_system::{61    self as system,62    EnsureRoot, EnsureSigned,63	limits::{BlockWeights, BlockLength},64};65use sp_arithmetic::{traits::{BaseArithmetic, Unsigned}};66use smallvec::smallvec;67use codec::{Encode, Decode};68use pallet_evm::{Account as EVMAccount, FeeCalculator, OnMethodCall};69use fp_rpc::TransactionStatus;70use sp_core::H256;7172use sp_runtime::{73	traits::{ 74		Dispatchable,75	},76};77use pallet_contracts::chain_extension::UncheckedFrom;787980pub use pallet_timestamp::Call as TimestampCall;81pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;8283// Polkadot imports84use pallet_xcm::XcmPassthrough;85use polkadot_parachain::primitives::Sibling;86use xcm::v0::Xcm;87use xcm::v0::{BodyId, Junction::*, MultiAsset, MultiLocation, MultiLocation::*, NetworkId};88use xcm_builder::{89	AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter,90	EnsureXcmOrigin, FixedWeightBounds, IsConcrete, LocationInverter, NativeAsset,91	ParentAsSuperuser, ParentIsDefault, RelayChainAsNative, SiblingParachainAsNative,92	SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32,93	SovereignSignedViaLocation, TakeWeightCredit, UsingComponents,94};95use xcm_executor::{Config, XcmExecutor};969798mod chain_extension;99use crate::chain_extension::{ NFTExtension, Imbalance };100101/// Re-export a nft pallet102/// TODO: Check this re-export. Is this safe and good style?103extern crate pallet_nft;104pub use pallet_nft::*;105106/// Reimport pallet inflation107extern crate pallet_inflation;108pub use pallet_inflation::*;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;119120/// The type for looking up accounts. We don't expect more than 4 billion of them, but you121/// never know...122pub type AccountIndex = u32;123124/// Balance of an account.125pub type Balance = u128;126127/// Index of a transaction in the chain.128pub type Index = u32;129130/// A hash of some data used by the chain.131pub type Hash = sp_core::H256;132133/// Digest item type.134pub type DigestItem = generic::DigestItem<Hash>;135136mod nft_weights;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!("nft"),162	impl_name: create_runtime_str!("nft"),163	authoring_version: 1,164	spec_version: 3,165	impl_version: 1,166	apis: RUNTIME_API_VERSIONS,167	transaction_version: 1,168};169170pub const MILLISECS_PER_BLOCK: u64 = 12000;171172pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;173174// These time units are defined in number of blocks.175pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);176pub const HOURS: BlockNumber = MINUTES * 60;177pub const DAYS: BlockNumber = HOURS * 24;178179#[derive(codec::Encode, codec::Decode)]180pub enum XCMPMessage<XAccountId, XBalance> {181    /// Transfer tokens to the given account from the Parachain account.182    TransferToken(XAccountId, XBalance),183}184185/// The version information used to identify this runtime when compiled natively.186#[cfg(feature = "std")]187pub fn native_version() -> NativeVersion {188	NativeVersion {189		runtime_version: VERSION,190		can_author_with: Default::default(),191	}192}193194type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;195196pub struct DealWithFees;197impl OnUnbalanced<NegativeImbalance> for DealWithFees {198	fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item=NegativeImbalance>) {199		if let Some(fees) = fees_then_tips.next() {200			// for fees, 100% to treasury201			let mut split = fees.ration(100, 0);202			if let Some(tips) = fees_then_tips.next() {203				// for tips, if any, 100% to treasury204				tips.ration_merge_into(100, 0, &mut split);205			}206			Treasury::on_unbalanced(split.0);207			// Author::on_unbalanced(split.1);208		}209	}210}211212/// We assume that ~10% of the block weight is consumed by `on_initalize` handlers.213/// This is used to limit the maximal weight of a single extrinsic.214const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(10);215/// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used216/// by  Operational  extrinsics.217const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);218/// We allow for 2 seconds of compute with a 6 second average block time.219const MAXIMUM_BLOCK_WEIGHT: Weight = 2 * WEIGHT_PER_SECOND;220221parameter_types! {222	pub const BlockHashCount: BlockNumber = 2400;223	pub RuntimeBlockLength: BlockLength =224		BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);225	pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);226	pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;227	pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()228		.base_block(BlockExecutionWeight::get())229		.for_class(DispatchClass::all(), |weights| {230			weights.base_extrinsic = ExtrinsicBaseWeight::get();231		})232		.for_class(DispatchClass::Normal, |weights| {233			weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);234		})235		.for_class(DispatchClass::Operational, |weights| {236			weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);237			// Operational transactions have some extra reserved space, so that they238			// are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.239			weights.reserved = Some(240				MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT241			);242		})243		.avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)244		.build_or_panic();245	pub const Version: RuntimeVersion = VERSION;246	pub const SS58Prefix: u8 = 42;247}248249250parameter_types! {251	pub const ChainId: u64 = 8888;252}253254impl pallet_evm::Config for Runtime {255	type BlockGasLimit = BlockGasLimit;256	type FeeCalculator = ();257	type GasWeightMapping = ();258	type CallOrigin = EnsureAddressTruncated;259	type WithdrawOrigin = EnsureAddressTruncated;260	type AddressMapping = HashedAddressMapping<Self::Hashing>;261	type Precompiles = ();262	type Currency = Balances;263	type Event = Event;264	type OnMethodCall = pallet_nft::NftErcSupport<Self>;265	type ChainId = ChainId;266	type Runner = pallet_evm::runner::stack::Runner<Self>;267	type OnChargeTransaction = ();268}269270pub struct EthereumFindAuthor<F>(PhantomData<F>);271impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F>272{273	fn find_author<'a, I>(digests: I) -> Option<H160> where274		I: 'a + IntoIterator<Item=(ConsensusEngineId, &'a [u8])>275	{276		if let Some(author_index) = F::find_author(digests) {277			let authority_id = Aura::authorities()[author_index as usize].clone();278			return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24]));279		}280		None281	}282}283284parameter_types! {285	pub BlockGasLimit: U256 = U256::from(u32::max_value());286}287288impl pallet_ethereum::Config for Runtime {289	type Event = Event;290	type FindAuthor = EthereumFindAuthor<Aura>;291	type StateRoot = pallet_ethereum::IntermediateStateRoot;292	type EvmSubmitLog = pallet_evm::Module<Runtime>;293}294295impl system::Config for Runtime {296    /// The data to be stored in an account.297    type AccountData = pallet_balances::AccountData<Balance>;298    /// The identifier used to distinguish between accounts.299    type AccountId = AccountId;300    /// The basic call filter to use in dispatchable.301    type BaseCallFilter = ();302    /// Maximum number of block number to block hash mappings to keep (oldest pruned first).303    type BlockHashCount = BlockHashCount;304    /// The maximum length of a block (in bytes).305	type BlockLength = RuntimeBlockLength;306    /// The index type for blocks.307    type BlockNumber = BlockNumber;308    /// The weight of the overhead invoked on the block import process, independent of the extrinsics included in that block.309	type BlockWeights = RuntimeBlockWeights;310    /// The aggregated dispatch type that is available for extrinsics.311    type Call = Call;312    /// The weight of database operations that the runtime can invoke.313    type DbWeight = RocksDbWeight;314    /// The ubiquitous event type.315    type Event = Event;316    /// The type for hashing blocks and tries.317    type Hash = Hash;318	/// The hashing algorithm used.319    type Hashing = BlakeTwo256;320    /// The header type.321    type Header = generic::Header<BlockNumber, BlakeTwo256>;322    /// The index type for storing how many extrinsics an account has signed.323    type Index = Index;324    /// The lookup mechanism to get account ID from whatever is passed in dispatchers.325    type Lookup = AccountIdLookup<AccountId, ()>;326    /// What to do if an account is fully reaped from the system.327    type OnKilledAccount = ();328    /// What to do if a new account is created.329    type OnNewAccount = ();330    type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;331    /// The ubiquitous origin type.332    type Origin = Origin;333 	/// This type is being generated by `construct_runtime!`.334    type PalletInfo = PalletInfo;335    /// This is used as an identifier of the chain. 42 is the generic substrate prefix.336	type SS58Prefix = SS58Prefix;337	/// Weight information for the extrinsics of this pallet.338    type SystemWeightInfo = system::weights::SubstrateWeight<Runtime>;339    /// Version of the runtime.340    type Version = Version;341}342343parameter_types! {344	pub const MinimumPeriod: u64 = SLOT_DURATION / 2;345}346347impl pallet_timestamp::Config for Runtime {348	/// A timestamp: milliseconds since the unix epoch.349	type Moment = u64;350	type OnTimestampSet = ();351	type MinimumPeriod = MinimumPeriod;352	type WeightInfo = ();353}354355parameter_types! {356	// pub const ExistentialDeposit: u128 = 500;357	pub const ExistentialDeposit: u128 = 0;358	pub const MaxLocks: u32 = 50;359}360361impl pallet_balances::Config for Runtime {362	type MaxLocks = MaxLocks;363	/// The type for recording an account's balance.364	type Balance = Balance;365	/// The ubiquitous event type.366	type Event = Event;367	type DustRemoval = Treasury;368	type ExistentialDeposit = ExistentialDeposit;369	type AccountStore = System;370	type WeightInfo = pallet_balances::weights::SubstrateWeight<Runtime>;371}372373pub const MICROUNIQUE: Balance = 1_000_000_000;374pub const MILLIUNIQUE: Balance = 1_000 * MICROUNIQUE;375pub const CENTIUNIQUE: Balance = 10 * MILLIUNIQUE;376pub const UNIQUE: Balance      = 100 * CENTIUNIQUE;377378pub const fn deposit(items: u32, bytes: u32) -> Balance {379	items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE380}381382parameter_types! {383	pub TombstoneDeposit: Balance = deposit(384		1,385		sp_std::mem::size_of::<pallet_contracts::Pallet<Runtime>> as u32,386	);387	pub DepositPerContract: Balance = TombstoneDeposit::get();388	pub const DepositPerStorageByte: Balance = deposit(0, 1);389	pub const DepositPerStorageItem: Balance = deposit(1, 0);390	pub RentFraction: Perbill = Perbill::from_rational(1u32, 30 * DAYS);391	pub const SurchargeReward: Balance = 150 * MILLIUNIQUE;392	pub const SignedClaimHandicap: u32 = 2;393	pub const MaxDepth: u32 = 32;394	pub const MaxValueSize: u32 = 16 * 1024;395	pub const MaxCodeSize: u32 = 1024 * 1024 * 25; // 25 Mb396	// The lazy deletion runs inside on_initialize.397	pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO *398		RuntimeBlockWeights::get().max_block;399	// The weight needed for decoding the queue should be less or equal than a fifth400	// of the overall weight dedicated to the lazy deletion.401	pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (402			<Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -403			<Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)404		)) / 5) as u32;405	pub Schedule: pallet_contracts::Schedule<Runtime> = Default::default();406}407408impl pallet_contracts::Config for Runtime {409	type Time = Timestamp;410	type Randomness = RandomnessCollectiveFlip;411	type Currency = Balances;412	type Event = Event;413	type RentPayment = ();414	type SignedClaimHandicap = SignedClaimHandicap;415	type TombstoneDeposit = TombstoneDeposit;416	type DepositPerContract = DepositPerContract;417	type DepositPerStorageByte = DepositPerStorageByte;418	type DepositPerStorageItem = DepositPerStorageItem;419	type RentFraction = RentFraction;420	type SurchargeReward = SurchargeReward;421	// type MaxDepth = MaxDepth;422	// type MaxValueSize = MaxValueSize;423	type WeightPrice = pallet_transaction_payment::Module<Self>;424	type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;425	type ChainExtension = NFTExtension;426	type DeletionQueueDepth = DeletionQueueDepth;427	type DeletionWeightLimit = DeletionWeightLimit;428	// type MaxCodeSize = MaxCodeSize;429	type Schedule = Schedule;430	type CallStack = [pallet_contracts::Frame<Self>; 31];431}432433parameter_types! {434	pub const TransactionByteFee: Balance = 501 * MICROUNIQUE; // Targeting 0.1 Unique per NFT transfer435}436437/// Linear implementor of `WeightToFeePolynomial`438pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);439440impl<T> WeightToFeePolynomial for LinearFee<T> where441	T: BaseArithmetic + From<u32> + Copy + Unsigned442{443	type Balance = T;444445	fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {446		smallvec!(WeightToFeeCoefficient {447			coeff_integer: 146_700u32.into(), // Targeting 0.1 Unique per NFT transfer448			coeff_frac: Perbill::zero(),449			negative: false,450			degree: 1,451		})452	}453}454455impl pallet_transaction_payment::Config for Runtime {456	type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, ()>;457	type TransactionByteFee = TransactionByteFee;458	type WeightToFee = LinearFee<Balance>;459	type FeeMultiplierUpdate = ();460}461462parameter_types! {463	pub const ProposalBond: Permill = Permill::from_percent(5);464	pub const ProposalBondMinimum: Balance = 1 * UNIQUE;465	pub const SpendPeriod: BlockNumber = 5 * MINUTES;466	pub const Burn: Permill = Permill::from_percent(0);467	pub const TipCountdown: BlockNumber = 1 * DAYS;468	pub const TipFindersFee: Percent = Percent::from_percent(20);469	pub const TipReportDepositBase: Balance = 1 * UNIQUE;470	pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;471	pub const BountyDepositBase: Balance = 1 * UNIQUE;472	pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;473	pub const TreasuryModuleId: PalletId = PalletId(*b"py/trsry");474	pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;475	pub const MaximumReasonLength: u32 = 16384;476	pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);477	pub const BountyValueMinimum: Balance = 5 * UNIQUE;478	pub const MaxApprovals: u32 = 100;479}480481impl pallet_treasury::Config for Runtime {482	type PalletId = TreasuryModuleId;483	type Currency = Balances;484	type ApproveOrigin = EnsureRoot<AccountId>;485	type RejectOrigin = EnsureRoot<AccountId>;486	type Event = Event;487	type OnSlash = ();488	type ProposalBond = ProposalBond;489	type ProposalBondMinimum = ProposalBondMinimum;490	type SpendPeriod = SpendPeriod;491	type Burn = Burn;492	type BurnDestination = ();493	type SpendFunds = ();494	type WeightInfo = pallet_treasury::weights::SubstrateWeight<Runtime>;495	type MaxApprovals = MaxApprovals;496}497498impl pallet_sudo::Config for Runtime {499	type Event = Event;500	type Call = Call;501}502503parameter_types! {504	pub const MinVestedTransfer: Balance = 10 * UNIQUE;505}506507impl pallet_vesting::Config for Runtime {508	type Event = Event;509	type Currency = Balances;510	type BlockNumberToBalance = ConvertInto;511	type MinVestedTransfer = MinVestedTransfer;512	type WeightInfo = ();513}514515parameter_types! {516	pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;517	pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;518}519520impl cumulus_pallet_parachain_system::Config for Runtime {521	type Event = Event;522	type OnValidationData = ();523	type SelfParaId = parachain_info::Pallet<Runtime>;524	// type DownwardMessageHandlers = cumulus_primitives_utility::UnqueuedDmpAsParent<525	// 	MaxDownwardMessageWeight,526	// 	XcmExecutor<XcmConfig>,527	// 	Call,528	// >;529	type OutboundXcmpMessageSource = XcmpQueue;530	type DmpMessageHandler = DmpQueue;531	type ReservedDmpWeight = ReservedDmpWeight;532	type ReservedXcmpWeight = ReservedXcmpWeight;533	type XcmpMessageHandler = XcmpQueue;534}535536impl parachain_info::Config for Runtime {}537538impl cumulus_pallet_aura_ext::Config for Runtime {}539540parameter_types! {541	pub const RelayLocation: MultiLocation = X1(Parent);542	pub const RelayNetwork: NetworkId = NetworkId::Polkadot;543	pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();544	pub Ancestry: MultiLocation = X1(Parachain(ParachainInfo::parachain_id().into()));545}546547/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used548/// when determining ownership of accounts for asset transacting and when attempting to use XCM549/// `Transact` in order to determine the dispatch Origin.550pub type LocationToAccountId = (551	// The parent (Relay-chain) origin converts to the default `AccountId`.552	ParentIsDefault<AccountId>,553	// Sibling parachain origins convert to AccountId via the `ParaId::into`.554	SiblingParachainConvertsVia<Sibling, AccountId>,555	// Straight up local `AccountId32` origins just alias directly to `AccountId`.556	AccountId32Aliases<RelayNetwork, AccountId>,557);558559/// Means for transacting assets on this chain.560pub type LocalAssetTransactor = CurrencyAdapter<561	// Use this currency:562	Balances,563	// Use this currency when it is a fungible asset matching the given location or name:564	IsConcrete<RelayLocation>,565	// Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:566	LocationToAccountId,567	// Our chain's account ID type (we can't get away without mentioning it explicitly):568	AccountId,569	// We don't track any teleports.570	(),571>;572573/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,574/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can575/// biases the kind of local `Origin` it will become.576pub type XcmOriginToTransactDispatchOrigin = (577	// Sovereign account converter; this attempts to derive an `AccountId` from the origin location578	// using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for579	// foreign chains who want to have a local sovereign account on this chain which they control.580	SovereignSignedViaLocation<LocationToAccountId, Origin>,581	// Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when582	// recognised.583	RelayChainAsNative<RelayOrigin, Origin>,584	// Native converter for sibling Parachains; will convert to a `SiblingPara` origin when585	// recognised.586	SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,587	// Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a588	// transaction from the Root origin.589	ParentAsSuperuser<Origin>,590	// Native signed account converter; this just converts an `AccountId32` origin into a normal591	// `Origin::Signed` origin of the same 32-byte value.592	SignedAccountId32AsNative<RelayNetwork, Origin>,593	// Xcm origins can be represented natively under the Xcm pallet's Xcm origin.594	XcmPassthrough<Origin>,595);596597parameter_types! {598	// One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.599	pub UnitWeightCost: Weight = 1_000_000;600	// 1200 UNIQUEs buy 1 second of weight.601	pub const WeightPrice: (MultiLocation, u128) = (X1(Parent), 1_200 * UNIQUE);602}603604match_type! {605	pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {606		X1(Parent) | X2(Parent, Plurality { id: BodyId::Unit, .. })607	};608}609610pub type Barrier = (611	TakeWeightCredit,612	AllowTopLevelPaidExecutionFrom<All<MultiLocation>>,613	AllowUnpaidExecutionFrom<ParentOrParentsUnitPlurality>,614	// ^^^ Parent & its unit plurality gets free execution615);616617pub struct XcmConfig;618impl Config for XcmConfig {619	type Call = Call;620	type XcmSender = XcmRouter;621	// How to withdraw and deposit an asset.622	type AssetTransactor = LocalAssetTransactor;623	type OriginConverter = XcmOriginToTransactDispatchOrigin;624	type IsReserve = NativeAsset;625	type IsTeleporter = NativeAsset;	// <- should be enough to allow teleportation of ROC626	type LocationInverter = LocationInverter<Ancestry>;627	type Barrier = Barrier;628	type Weigher = FixedWeightBounds<UnitWeightCost, Call>;629	type Trader = UsingComponents<IdentityFee<Balance>, RelayLocation, AccountId, Balances, ()>;630	type ResponseHandler = ();	// Don't handle responses for now.631}632633// parameter_types! {634// 	pub const MaxDownwardMessageWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 10;635// }636637/// No local origins on this chain are allowed to dispatch XCM sends/executions.638pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);639640/// The means for routing XCM messages which are not for local execution into the right message641/// queues.642pub type XcmRouter = (643	// Two routers - use UMP to communicate with the relay chain:644	cumulus_primitives_utility::ParentAsUmp<ParachainSystem>,645	// ..and XCMP to communicate with the sibling chains.646	XcmpQueue,647);648649impl pallet_xcm::Config for Runtime {650	type Event = Event;651	type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;652	type XcmRouter = XcmRouter;653	type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;654	type XcmExecuteFilter = All<(MultiLocation, Xcm<Call>)>;655	type XcmExecutor = XcmExecutor<XcmConfig>;656	type XcmTeleportFilter = All<(MultiLocation, Vec<MultiAsset>)>;657	type XcmReserveTransferFilter = ();658	type Weigher = FixedWeightBounds<UnitWeightCost, Call>;659}660661impl cumulus_pallet_xcm::Config for Runtime {662	type Event = Event;663	type XcmExecutor = XcmExecutor<XcmConfig>;664}665666impl cumulus_pallet_xcmp_queue::Config for Runtime {667	type Event = Event;668	type XcmExecutor = XcmExecutor<XcmConfig>;669	type ChannelInfo = ParachainSystem;670}671672impl cumulus_pallet_dmp_queue::Config for Runtime {673	type Event = Event;674	type XcmExecutor = XcmExecutor<XcmConfig>;675	type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;676}677678impl pallet_aura::Config for Runtime {679	type AuthorityId = AuraId;680}681682parameter_types! {683	pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();684	pub const CollectionCreationPrice: Balance = 100 * UNIQUE;685}686687/// Used for the pallet nft in `./nft.rs`688impl pallet_nft::Config for Runtime {689	type Event = Event;690	type WeightInfo = nft_weights::WeightInfo;691692	type EvmWithdrawOrigin = EnsureAddressTruncated;693	type EvmBackwardsAddressMapping = pallet_nft::MapBackwardsAddressTruncated;694	type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;695	type CrossAccountId = pallet_nft::BasicCrossAccountId<Self>;696697	type Currency = Balances;698	type CollectionCreationPrice = CollectionCreationPrice;699	type TreasuryAccountId = TreasuryAccountId;700701	type EthereumChainId = ChainId;702	type EthereumTransactionSender = pallet_ethereum::Module<Runtime>;703}704705parameter_types! {706	pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied707}708709/// Used for the pallet inflation710impl pallet_inflation::Config for Runtime {711	type Currency = Balances;712	type TreasuryAccountId = TreasuryAccountId;713	type InflationBlockInterval = InflationBlockInterval;714}715716parameter_types! {717	pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *718		RuntimeBlockWeights::get().max_block;719	pub const MaxScheduledPerBlock: u32 = 50;720}721722pub struct Sponsoring;723impl SponsoringResolve<AccountId, Call> for Sponsoring {724725	fn resolve(who: &AccountId, call: &Call) -> Option<AccountId> 726	where 727		Call: Dispatchable<Info=DispatchInfo>,728		Call: IsSubType<pallet_nft::Call<Runtime>>, 729		Call: IsSubType<pallet_contracts::Call<Runtime>>,730		AccountId: AsRef<[u8]>,731		AccountId: UncheckedFrom<Hash>732	{733		pallet_nft_transaction_payment::Module::<Runtime>::withdraw_type(who, call)734	}735}736737impl pallet_scheduler::Config for Runtime {738	type Event = Event;739	type Origin = Origin;740	type PalletsOrigin = OriginCaller;741	type Call = Call;742	type MaximumWeight = MaximumSchedulerWeight;743	type ScheduleOrigin = EnsureSigned<AccountId>;744	type MaxScheduledPerBlock = MaxScheduledPerBlock;745	type Sponsoring = Sponsoring;746	type WeightInfo = ();747}748749impl pallet_nft_transaction_payment::Config for Runtime {750}751752impl pallet_nft_charge_transaction::Config for Runtime {753}754755construct_runtime!(756    pub enum Runtime where757        Block = Block,758        NodeBlock = opaque::Block,759        UncheckedExtrinsic = UncheckedExtrinsic760    {761		Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 30,762		Contracts: pallet_contracts::{Pallet, Call, Storage, Event<T>},763		RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Call, Storage},764		Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent},765		TransactionPayment: pallet_transaction_payment::{Pallet, Storage},766        Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event<T>},767		Sudo: pallet_sudo::{Pallet, Call, Storage, Config<T>, Event<T>},768		System: system::{Pallet, Call, Storage, Config, Event<T>},769        Vesting: pallet_vesting::{Pallet, Call, Config<T>, Storage, Event<T>},770771		ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Storage, Inherent, Event<T>, ValidateUnsigned} = 20,772		ParachainInfo: parachain_info::{Pallet, Storage, Config} = 21,773774		Aura: pallet_aura::{Pallet, Config<T>},775		AuraExt: cumulus_pallet_aura_ext::{Pallet, Config},776777		// Frontier778		EVM: pallet_evm::{Module, Config, Call, Storage, Event<T>},779		Ethereum: pallet_ethereum::{Module, Config, Call, Storage, Event, ValidateUnsigned},780781		// XCM helpers.782		XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 50,783		PolkadotXcm: pallet_xcm::{Pallet, Call, Event<T>, Origin} = 51,784		CumulusXcm: cumulus_pallet_xcm::{Pallet, Call, Event<T>, Origin} = 52,785		DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,786787788		// Unique Pallets789        Inflation: pallet_inflation::{Pallet, Call, Storage},790		Nft: pallet_nft::{Pallet, Call, Config<T>, Storage, Event<T>},791		Scheduler: pallet_scheduler::{Pallet, Call, Storage, Event<T>},792		NftPayment: pallet_nft_transaction_payment::{Pallet, Call, Storage},793		Charging: pallet_nft_charge_transaction::{Pallet, Call, Storage },794    }795);796797pub struct TransactionConverter;798799impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {800	fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {801		UncheckedExtrinsic::new_unsigned(pallet_ethereum::Call::<Runtime>::transact(transaction).into())802	}803}804805impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {806	fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> opaque::UncheckedExtrinsic {807		let extrinsic = UncheckedExtrinsic::new_unsigned(pallet_ethereum::Call::<Runtime>::transact(transaction).into());808		let encoded = extrinsic.encode();809		opaque::UncheckedExtrinsic::decode(&mut &encoded[..]).expect("Encoded extrinsic is always valid")810	}811}812813/// The address format for describing accounts.814pub type Address = sp_runtime::MultiAddress<AccountId, ()>;815/// Block header type as expected by this runtime.816pub type Header = generic::Header<BlockNumber, BlakeTwo256>;817/// Block type as expected by this runtime.818pub type Block = generic::Block<Header, UncheckedExtrinsic>;819/// A Block signed with a Justification820pub type SignedBlock = generic::SignedBlock<Block>;821/// BlockId type as expected by this runtime.822pub type BlockId = generic::BlockId<Block>;823/// The SignedExtension to the basic transaction logic.824pub type SignedExtra = (825    system::CheckSpecVersion<Runtime>,826    // system::CheckTxVersion<Runtime>,827    system::CheckGenesis<Runtime>,828    system::CheckEra<Runtime>,829    system::CheckNonce<Runtime>,830    system::CheckWeight<Runtime>,831    pallet_nft_charge_transaction::ChargeTransactionPayment<Runtime>,832);833/// Unchecked extrinsic type as expected by this runtime.834pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;835/// Extrinsic type that has already been checked.836pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, Call, SignedExtra>;837/// Executive: handles dispatch to the various modules.838pub type Executive = frame_executive::Executive<839    Runtime,840    Block,841    frame_system::ChainContext<Runtime>,842    Runtime,843    AllPallets,844>;845846impl_opaque_keys! {847	pub struct SessionKeys {848		pub aura: Aura,849	}850}851852impl_runtime_apis! {853    impl sp_api::Core<Block> for Runtime {854        fn version() -> RuntimeVersion {855            VERSION856        }857858        fn execute_block(block: Block) {859            Executive::execute_block(block)860        }861862        fn initialize_block(header: &<Block as BlockT>::Header) {863            Executive::initialize_block(header)864        }865    }866867    impl sp_api::Metadata<Block> for Runtime {868        fn metadata() -> OpaqueMetadata {869            Runtime::metadata().into()870        }871    }872873    impl sp_block_builder::BlockBuilder<Block> for Runtime {874        fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {875            Executive::apply_extrinsic(extrinsic)876        }877878        fn finalize_block() -> <Block as BlockT>::Header {879            Executive::finalize_block()880        }881882        fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {883            data.create_extrinsics()884        }885886        fn check_inherents(887            block: Block,888            data: sp_inherents::InherentData,889        ) -> sp_inherents::CheckInherentsResult {890            data.check_extrinsics(&block)891        }892893        // fn random_seed() -> <Block as BlockT>::Hash {894        //     RandomnessCollectiveFlip::random_seed().0895        // }896    }897898    impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {899        fn validate_transaction(900            source: TransactionSource,901            tx: <Block as BlockT>::Extrinsic,902        ) -> TransactionValidity {903            Executive::validate_transaction(source, tx)904        }905    }906907	impl sp_offchain::OffchainWorkerApi<Block> for Runtime {908		fn offchain_worker(header: &<Block as BlockT>::Header) {909			Executive::offchain_worker(header)910		}911	}912913	impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {914		fn chain_id() -> u64 {915			<Runtime as pallet_evm::Config>::ChainId::get()916		}917918		fn account_basic(address: H160) -> EVMAccount {919			EVM::account_basic(&address)920		}921922		fn gas_price() -> U256 {923			<Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price()924		}925926		fn account_code_at(address: H160) -> Vec<u8> {927			EVM::account_codes(address)928		}929930		fn author() -> H160 {931			<pallet_ethereum::Module<Runtime>>::find_author()932		}933934		fn storage_at(address: H160, index: U256) -> H256 {935			let mut tmp = [0u8; 32];936			index.to_big_endian(&mut tmp);937			EVM::account_storages(address, H256::from_slice(&tmp[..]))938		}939940		fn call(941			from: H160,942			to: H160,943			data: Vec<u8>,944			value: U256,945			gas_limit: U256,946			gas_price: Option<U256>,947			nonce: Option<U256>,948			estimate: bool,949		) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {950			let config = if estimate {951				let mut config = <Runtime as pallet_evm::Config>::config().clone();952				config.estimate = true;953				Some(config)954			} else {955				None956			};957958			<Runtime as pallet_evm::Config>::Runner::call(959				from,960				to,961				data,962				value,963				gas_limit.low_u64(),964				gas_price,965				nonce,966				config.as_ref().unwrap_or(<Runtime as pallet_evm::Config>::config()),967			).map_err(|err| err.into())968		}969970		fn create(971			from: H160,972			data: Vec<u8>,973			value: U256,974			gas_limit: U256,975			gas_price: Option<U256>,976			nonce: Option<U256>,977			estimate: bool,978		) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {979			let config = if estimate {980				let mut config = <Runtime as pallet_evm::Config>::config().clone();981				config.estimate = true;982				Some(config)983			} else {984				None985			};986987			<Runtime as pallet_evm::Config>::Runner::create(988				from,989				data,990				value,991				gas_limit.low_u64(),992				gas_price,993				nonce,994				config.as_ref().unwrap_or(<Runtime as pallet_evm::Config>::config()),995			).map_err(|err| err.into())996		}997998		fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {999			Ethereum::current_transaction_statuses()1000		}10011002		fn current_block() -> Option<pallet_ethereum::Block> {1003			Ethereum::current_block()1004		}10051006		fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {1007			Ethereum::current_receipts()1008		}10091010		fn current_all() -> (1011			Option<pallet_ethereum::Block>,1012			Option<Vec<pallet_ethereum::Receipt>>,1013			Option<Vec<TransactionStatus>>1014		) {1015			(1016				Ethereum::current_block(),1017				Ethereum::current_receipts(),1018				Ethereum::current_transaction_statuses()1019			)1020		}1021	}10221023	impl sp_session::SessionKeys<Block> for Runtime {1024		fn decode_session_keys(1025			encoded: Vec<u8>,1026		) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {1027			SessionKeys::decode_into_raw_public_keys(&encoded)1028		}10291030		fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {1031			SessionKeys::generate(seed)1032		}1033	}10341035	impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {1036		fn slot_duration() -> sp_consensus_aura::SlotDuration {1037			sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())1038		}10391040		fn authorities() -> Vec<AuraId> {1041			Aura::authorities()1042		}1043	}10441045	impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {1046		fn collect_collation_info() -> cumulus_primitives_core::CollationInfo {1047			ParachainSystem::collect_collation_info()1048		}1049	}10501051	impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {1052		fn account_nonce(account: AccountId) -> Index {1053			System::account_nonce(account)1054		}1055	}10561057	impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {1058		fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {1059			TransactionPayment::query_info(uxt, len)1060		}1061		fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {1062			TransactionPayment::query_fee_details(uxt, len)1063		}1064	}10651066	impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber, Hash>1067		for Runtime1068	{1069		fn call(1070			origin: AccountId,1071			dest: AccountId,1072			value: Balance,1073			gas_limit: u64,1074			input_data: Vec<u8>,1075		) -> pallet_contracts_primitives::ContractExecResult {1076			Contracts::bare_call(origin, dest, value, gas_limit, input_data, false)1077		}10781079		fn instantiate(1080			origin: AccountId,1081			endowment: Balance,1082			gas_limit: u64,1083			code: pallet_contracts_primitives::Code<Hash>,1084			data: Vec<u8>,1085			salt: Vec<u8>,1086		) -> pallet_contracts_primitives::ContractInstantiateResult<AccountId, BlockNumber>1087		{1088			Contracts::bare_instantiate(origin, endowment, gas_limit, code, data, salt, true, false)1089		}10901091		fn get_storage(1092			address: AccountId,1093			key: [u8; 32],1094		) -> pallet_contracts_primitives::GetStorageResult {1095			Contracts::get_storage(address, key)1096		}10971098		fn rent_projection(1099			address: AccountId,1100		) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {1101			Contracts::rent_projection(address)1102		}1103	}11041105    #[cfg(feature = "runtime-benchmarks")]1106	impl frame_benchmarking::Benchmark<Block> for Runtime {1107		fn dispatch_benchmark(1108			config: frame_benchmarking::BenchmarkConfig1109		) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {1110			use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};11111112			let whitelist: Vec<TrackedStorageKey> = vec![1113				// Alice account1114				hex_literal::hex!("d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d").to_vec().into(),1115				// // Total Issuance1116				// hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),1117				// // Execution Phase1118				// hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),1119				// // Event Count1120				// hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),1121				// // System Events1122				// hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),1123			];11241125			let mut batches = Vec::<BenchmarkBatch>::new();1126			let params = (&config, &whitelist);11271128			add_benchmark!(params, batches, pallet_nft, Nft);1129			add_benchmark!(params, batches, pallet_inflation, Inflation);11301131			if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }1132			Ok(batches)1133		}1134	}1135}11361137cumulus_pallet_parachain_system::register_validate_block!(1138	Runtime,1139	cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,1140);