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

difftreelog

source

runtime/src/lib.rs33.1 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 frame_support::{41    construct_runtime,42	match_type,43    dispatch::DispatchResult,44	PalletId,45    parameter_types,46    StorageValue,47    traits::{48        All, Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem, LockIdentifier, OnUnbalanced, Randomness49    },50    weights::{51        constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},52        DispatchClass, DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,53        WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients54    },55};56use nft_data_structs::*;57use pallet_contracts::weights::WeightInfo;58// #[cfg(any(feature = "std", test))]59use frame_system::{60    self as system,61    EnsureRoot, EnsureSigned,62	limits::{BlockWeights, BlockLength},63};64use sp_arithmetic::{traits::{BaseArithmetic, Unsigned}};65use smallvec::smallvec;6667use sp_runtime::{68	traits::{ 69		Dispatchable,70	},71};72use pallet_contracts::chain_extension::UncheckedFrom;737475pub use pallet_timestamp::Call as TimestampCall;76pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;7778// Polkadot imports79use pallet_xcm::XcmPassthrough;80use polkadot_parachain::primitives::Sibling;81use xcm::v0::Xcm;82use xcm::v0::{BodyId, Junction::*, MultiAsset, MultiLocation, MultiLocation::*, NetworkId};83use xcm_builder::{84	AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter,85	EnsureXcmOrigin, FixedWeightBounds, IsConcrete, LocationInverter, NativeAsset,86	ParentAsSuperuser, ParentIsDefault, RelayChainAsNative, SiblingParachainAsNative,87	SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32,88	SovereignSignedViaLocation, TakeWeightCredit, UsingComponents,89};90use xcm_executor::{Config, XcmExecutor};919293mod chain_extension;94use crate::chain_extension::{ NFTExtension, Imbalance };9596/// Re-export a nft pallet97/// TODO: Check this re-export. Is this safe and good style?98extern crate pallet_nft;99pub use pallet_nft::*;100101/// Reimport pallet inflation102extern crate pallet_inflation;103pub use pallet_inflation::*;104105/// An index to a block.106pub type BlockNumber = u32;107108/// Alias to 512-bit hash when used in the context of a transaction signature on the chain.109pub type Signature = MultiSignature;110111/// Some way of identifying an account on the chain. We intentionally make it equivalent112/// to the public key of our transaction signing scheme.113pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;114115/// The type for looking up accounts. We don't expect more than 4 billion of them, but you116/// never know...117pub type AccountIndex = u32;118119/// Balance of an account.120pub type Balance = u128;121122/// Index of a transaction in the chain.123pub type Index = u32;124125/// A hash of some data used by the chain.126pub type Hash = sp_core::H256;127128/// Digest item type.129pub type DigestItem = generic::DigestItem<Hash>;130131mod nft_weights;132133/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know134/// the specifics of the runtime. They can then be made to be agnostic over specific formats135/// of data like extrinsics, allowing for them to continue syncing the network through upgrades136/// to even the core data structures.137pub mod opaque {138    use super::*;139140    pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;141142    /// Opaque block type.143    pub type Block = generic::Block<Header, UncheckedExtrinsic>;144145    pub type SessionHandlers = ();146147	impl_opaque_keys! {148        pub struct SessionKeys {149			pub aura: Aura,150		}151    }152}153154/// This runtime version.155pub const VERSION: RuntimeVersion = RuntimeVersion {156    spec_name: create_runtime_str!("nft"),157    impl_name: create_runtime_str!("nft"),158    authoring_version: 1,159    spec_version: 3,160    impl_version: 1,161    apis: RUNTIME_API_VERSIONS,162    transaction_version: 1,163};164165pub const MILLISECS_PER_BLOCK: u64 = 12000;166167pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;168169// These time units are defined in number of blocks.170pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);171pub const HOURS: BlockNumber = MINUTES * 60;172pub const DAYS: BlockNumber = HOURS * 24;173174#[derive(codec::Encode, codec::Decode)]175pub enum XCMPMessage<XAccountId, XBalance> {176    /// Transfer tokens to the given account from the Parachain account.177    TransferToken(XAccountId, XBalance),178}179180/// The version information used to identify this runtime when compiled natively.181#[cfg(feature = "std")]182pub fn native_version() -> NativeVersion {183    NativeVersion {184        runtime_version: VERSION,185        can_author_with: Default::default(),186    }187}188189type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;190191pub struct DealWithFees;192impl OnUnbalanced<NegativeImbalance> for DealWithFees {193	fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item=NegativeImbalance>) {194		if let Some(fees) = fees_then_tips.next() {195			// for fees, 100% to treasury196			let mut split = fees.ration(100, 0);197			if let Some(tips) = fees_then_tips.next() {198				// for tips, if any, 100% to treasury199				tips.ration_merge_into(100, 0, &mut split);200			}201			Treasury::on_unbalanced(split.0);202			// Author::on_unbalanced(split.1);203		}204	}205}206207/// We assume that ~10% of the block weight is consumed by `on_initalize` handlers.208/// This is used to limit the maximal weight of a single extrinsic.209const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(10);210/// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used211/// by  Operational  extrinsics.212const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);213/// We allow for 2 seconds of compute with a 6 second average block time.214const MAXIMUM_BLOCK_WEIGHT: Weight = 2 * WEIGHT_PER_SECOND;215216parameter_types! {217    pub const BlockHashCount: BlockNumber = 2400;218	pub RuntimeBlockLength: BlockLength =219		BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);220    pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);221    pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;222	pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()223		.base_block(BlockExecutionWeight::get())224		.for_class(DispatchClass::all(), |weights| {225			weights.base_extrinsic = ExtrinsicBaseWeight::get();226		})227		.for_class(DispatchClass::Normal, |weights| {228			weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);229		})230		.for_class(DispatchClass::Operational, |weights| {231			weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);232			// Operational transactions have some extra reserved space, so that they233			// are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.234			weights.reserved = Some(235				MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT236			);237		})238		.avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)239		.build_or_panic();240    pub const Version: RuntimeVersion = VERSION;241    pub const SS58Prefix: u8 = 42;242}243244impl system::Config for Runtime {245    /// The data to be stored in an account.246    type AccountData = pallet_balances::AccountData<Balance>;247    /// The identifier used to distinguish between accounts.248    type AccountId = AccountId;249    /// The basic call filter to use in dispatchable.250    type BaseCallFilter = ();251    /// Maximum number of block number to block hash mappings to keep (oldest pruned first).252    type BlockHashCount = BlockHashCount;253    /// The maximum length of a block (in bytes).254	type BlockLength = RuntimeBlockLength;255    /// The index type for blocks.256    type BlockNumber = BlockNumber;257    /// The weight of the overhead invoked on the block import process, independent of the extrinsics included in that block.258	type BlockWeights = RuntimeBlockWeights;259    /// The aggregated dispatch type that is available for extrinsics.260    type Call = Call;261    /// The weight of database operations that the runtime can invoke.262    type DbWeight = RocksDbWeight;263    /// The ubiquitous event type.264    type Event = Event;265    /// The type for hashing blocks and tries.266    type Hash = Hash;267	/// The hashing algorithm used.268    type Hashing = BlakeTwo256;269    /// The header type.270    type Header = generic::Header<BlockNumber, BlakeTwo256>;271    /// The index type for storing how many extrinsics an account has signed.272    type Index = Index;273    /// The lookup mechanism to get account ID from whatever is passed in dispatchers.274    type Lookup = AccountIdLookup<AccountId, ()>;275    /// What to do if an account is fully reaped from the system.276    type OnKilledAccount = ();277    /// What to do if a new account is created.278    type OnNewAccount = ();279    type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;280    /// The ubiquitous origin type.281    type Origin = Origin;282 	/// This type is being generated by `construct_runtime!`.283    type PalletInfo = PalletInfo;284    /// This is used as an identifier of the chain. 42 is the generic substrate prefix.285	type SS58Prefix = SS58Prefix;286	/// Weight information for the extrinsics of this pallet.287    type SystemWeightInfo = system::weights::SubstrateWeight<Runtime>;288    /// Version of the runtime.289    type Version = Version;290}291292parameter_types! {293    pub const MinimumPeriod: u64 = SLOT_DURATION / 2;294}295296impl pallet_timestamp::Config for Runtime {297	/// A timestamp: milliseconds since the unix epoch.298	type Moment = u64;299	type OnTimestampSet = ();300	type MinimumPeriod = MinimumPeriod;301	type WeightInfo = ();302}303304parameter_types! {305    // pub const ExistentialDeposit: u128 = 500;306    pub const ExistentialDeposit: u128 = 0;307	pub const MaxLocks: u32 = 50;308}309310impl pallet_balances::Config for Runtime {311	type MaxLocks = MaxLocks;312	/// The type for recording an account's balance.313	type Balance = Balance;314	/// The ubiquitous event type.315	type Event = Event;316	type DustRemoval = Treasury;317	type ExistentialDeposit = ExistentialDeposit;318	type AccountStore = System;319	type WeightInfo = pallet_balances::weights::SubstrateWeight<Runtime>;320}321322pub const MICROUNIQUE: Balance = 1_000_000_000;323pub const MILLIUNIQUE: Balance = 1_000 * MICROUNIQUE;324pub const CENTIUNIQUE: Balance = 10 * MILLIUNIQUE;325pub const UNIQUE: Balance      = 100 * CENTIUNIQUE;326327pub const fn deposit(items: u32, bytes: u32) -> Balance {328    items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE329}330331parameter_types! {332	pub TombstoneDeposit: Balance = deposit(333		1,334		sp_std::mem::size_of::<pallet_contracts::Pallet<Runtime>> as u32,335	);336	pub DepositPerContract: Balance = TombstoneDeposit::get();337	pub const DepositPerStorageByte: Balance = deposit(0, 1);338	pub const DepositPerStorageItem: Balance = deposit(1, 0);339	pub RentFraction: Perbill = Perbill::from_rational(1u32, 30 * DAYS);340	pub const SurchargeReward: Balance = 150 * MILLIUNIQUE;341	pub const SignedClaimHandicap: u32 = 2;342	pub const MaxDepth: u32 = 32;343	pub const MaxValueSize: u32 = 16 * 1024;344	pub const MaxCodeSize: u32 = 1024 * 1024 * 25; // 25 Mb 345	// The lazy deletion runs inside on_initialize.346	pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO *347		RuntimeBlockWeights::get().max_block;348	// The weight needed for decoding the queue should be less or equal than a fifth349	// of the overall weight dedicated to the lazy deletion.350	pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (351			<Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -352			<Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)353		)) / 5) as u32;354	pub Schedule: pallet_contracts::Schedule<Runtime> = Default::default();355}356357impl pallet_contracts::Config for Runtime {358	type Time = Timestamp;359	type Randomness = RandomnessCollectiveFlip;360	type Currency = Balances;361	type Event = Event;362	type RentPayment = ();363	type SignedClaimHandicap = SignedClaimHandicap;364	type TombstoneDeposit = TombstoneDeposit;365	type DepositPerContract = DepositPerContract;366	type DepositPerStorageByte = DepositPerStorageByte;367	type DepositPerStorageItem = DepositPerStorageItem;368	type RentFraction = RentFraction;369	type SurchargeReward = SurchargeReward;370	// type MaxDepth = MaxDepth;371	// type MaxValueSize = MaxValueSize;372	type WeightPrice = pallet_transaction_payment::Module<Self>;373	type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;374	type ChainExtension = NFTExtension;375	type DeletionQueueDepth = DeletionQueueDepth;376	type DeletionWeightLimit = DeletionWeightLimit;377	// type MaxCodeSize = MaxCodeSize;378	type Schedule = Schedule;379	type CallStack = [pallet_contracts::Frame<Self>; 31];380}381382parameter_types! {383	pub const TransactionByteFee: Balance = 501 * MICROUNIQUE; // Targeting 0.1 Unique per NFT transfer 384}385386/// Linear implementor of `WeightToFeePolynomial` 387pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);388389impl<T> WeightToFeePolynomial for LinearFee<T> where390	T: BaseArithmetic + From<u32> + Copy + Unsigned391{392	type Balance = T;393394	fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {395		smallvec!(WeightToFeeCoefficient {396			coeff_integer: 146_700u32.into(), // Targeting 0.1 Unique per NFT transfer397			coeff_frac: Perbill::zero(),398			negative: false,399			degree: 1,400		})401	}402}403404impl pallet_transaction_payment::Config for Runtime {405	type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, ()>;406	type TransactionByteFee = TransactionByteFee;407	type WeightToFee = LinearFee<Balance>;408	type FeeMultiplierUpdate = ();409}410411parameter_types! {412	pub const ProposalBond: Permill = Permill::from_percent(5);413	pub const ProposalBondMinimum: Balance = 1 * UNIQUE;414	pub const SpendPeriod: BlockNumber = 5 * MINUTES;415	pub const Burn: Permill = Permill::from_percent(0);416	pub const TipCountdown: BlockNumber = 1 * DAYS;417	pub const TipFindersFee: Percent = Percent::from_percent(20);418	pub const TipReportDepositBase: Balance = 1 * UNIQUE;419	pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;420	pub const BountyDepositBase: Balance = 1 * UNIQUE;421	pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;422	pub const TreasuryModuleId: PalletId = PalletId(*b"py/trsry");423	pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;424	pub const MaximumReasonLength: u32 = 16384;425	pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);426	pub const BountyValueMinimum: Balance = 5 * UNIQUE;427	pub const MaxApprovals: u32 = 100;428}429430impl pallet_treasury::Config for Runtime {431	type PalletId = TreasuryModuleId;432	type Currency = Balances;433	type ApproveOrigin = EnsureRoot<AccountId>;434	type RejectOrigin = EnsureRoot<AccountId>;435	type Event = Event;436	type OnSlash = ();437	type ProposalBond = ProposalBond;438	type ProposalBondMinimum = ProposalBondMinimum;439	type SpendPeriod = SpendPeriod;440	type Burn = Burn;441	type BurnDestination = ();442	type SpendFunds = ();443	type WeightInfo = pallet_treasury::weights::SubstrateWeight<Runtime>;444	type MaxApprovals = MaxApprovals;445}446447impl pallet_sudo::Config for Runtime {448    type Event = Event;449    type Call = Call;450}451452parameter_types! {453	pub const MinVestedTransfer: Balance = 10 * UNIQUE;454}455456impl pallet_vesting::Config for Runtime {457	type Event = Event;458	type Currency = Balances;459	type BlockNumberToBalance = ConvertInto;460	type MinVestedTransfer = MinVestedTransfer;461	type WeightInfo = ();462}463464parameter_types! {465	pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;466	pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;467}468469impl cumulus_pallet_parachain_system::Config for Runtime {470	type Event = Event;471	type OnValidationData = ();472	type SelfParaId = parachain_info::Pallet<Runtime>;473	// type DownwardMessageHandlers = cumulus_primitives_utility::UnqueuedDmpAsParent<474	// 	MaxDownwardMessageWeight,475	// 	XcmExecutor<XcmConfig>,476	// 	Call,477	// >;478	type OutboundXcmpMessageSource = XcmpQueue;479	type DmpMessageHandler = DmpQueue;480	type ReservedDmpWeight = ReservedDmpWeight;481	type ReservedXcmpWeight = ReservedXcmpWeight;482	type XcmpMessageHandler = XcmpQueue;483}484485impl parachain_info::Config for Runtime {}486487impl cumulus_pallet_aura_ext::Config for Runtime {}488489parameter_types! {490	pub const RelayLocation: MultiLocation = X1(Parent);491	pub const RelayNetwork: NetworkId = NetworkId::Polkadot;492	pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();493	pub Ancestry: MultiLocation = X1(Parachain(ParachainInfo::parachain_id().into()));494}495496/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used497/// when determining ownership of accounts for asset transacting and when attempting to use XCM498/// `Transact` in order to determine the dispatch Origin.499pub type LocationToAccountId = (500	// The parent (Relay-chain) origin converts to the default `AccountId`.501	ParentIsDefault<AccountId>,502	// Sibling parachain origins convert to AccountId via the `ParaId::into`.503	SiblingParachainConvertsVia<Sibling, AccountId>,504	// Straight up local `AccountId32` origins just alias directly to `AccountId`.505	AccountId32Aliases<RelayNetwork, AccountId>,506);507508/// Means for transacting assets on this chain.509pub type LocalAssetTransactor = CurrencyAdapter<510	// Use this currency:511	Balances,512	// Use this currency when it is a fungible asset matching the given location or name:513	IsConcrete<RelayLocation>,514	// Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:515	LocationToAccountId,516	// Our chain's account ID type (we can't get away without mentioning it explicitly):517	AccountId,518	// We don't track any teleports.519	(),520>;521522/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,523/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can524/// biases the kind of local `Origin` it will become.525pub type XcmOriginToTransactDispatchOrigin = (526	// Sovereign account converter; this attempts to derive an `AccountId` from the origin location527	// using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for528	// foreign chains who want to have a local sovereign account on this chain which they control.529	SovereignSignedViaLocation<LocationToAccountId, Origin>,530	// Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when531	// recognised.532	RelayChainAsNative<RelayOrigin, Origin>,533	// Native converter for sibling Parachains; will convert to a `SiblingPara` origin when534	// recognised.535	SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,536	// Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a537	// transaction from the Root origin.538	ParentAsSuperuser<Origin>,539	// Native signed account converter; this just converts an `AccountId32` origin into a normal540	// `Origin::Signed` origin of the same 32-byte value.541	SignedAccountId32AsNative<RelayNetwork, Origin>,542	// Xcm origins can be represented natively under the Xcm pallet's Xcm origin.543	XcmPassthrough<Origin>,544);545546parameter_types! {547	// One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.548	pub UnitWeightCost: Weight = 1_000_000;549	// 1200 UNIQUEs buy 1 second of weight.550	pub const WeightPrice: (MultiLocation, u128) = (X1(Parent), 1_200 * UNIQUE);551}552553match_type! {554	pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {555		X1(Parent) | X2(Parent, Plurality { id: BodyId::Unit, .. })556	};557}558559pub type Barrier = (560	TakeWeightCredit,561	AllowTopLevelPaidExecutionFrom<All<MultiLocation>>,562	AllowUnpaidExecutionFrom<ParentOrParentsUnitPlurality>,563	// ^^^ Parent & its unit plurality gets free execution564);565566pub struct XcmConfig;567impl Config for XcmConfig {568	type Call = Call;569	type XcmSender = XcmRouter;570	// How to withdraw and deposit an asset.571	type AssetTransactor = LocalAssetTransactor;572	type OriginConverter = XcmOriginToTransactDispatchOrigin;573	type IsReserve = NativeAsset;574	type IsTeleporter = NativeAsset;	// <- should be enough to allow teleportation of ROC575	type LocationInverter = LocationInverter<Ancestry>;576	type Barrier = Barrier;577	type Weigher = FixedWeightBounds<UnitWeightCost, Call>;578	type Trader = UsingComponents<IdentityFee<Balance>, RelayLocation, AccountId, Balances, ()>;579	type ResponseHandler = ();	// Don't handle responses for now.580}581582// parameter_types! {583// 	pub const MaxDownwardMessageWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 10;584// }585586/// No local origins on this chain are allowed to dispatch XCM sends/executions.587pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);588589/// The means for routing XCM messages which are not for local execution into the right message590/// queues.591pub type XcmRouter = (592	// Two routers - use UMP to communicate with the relay chain:593	cumulus_primitives_utility::ParentAsUmp<ParachainSystem>,594	// ..and XCMP to communicate with the sibling chains.595	XcmpQueue,596);597598impl pallet_xcm::Config for Runtime {599	type Event = Event;600	type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;601	type XcmRouter = XcmRouter;602	type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;603	type XcmExecuteFilter = All<(MultiLocation, Xcm<Call>)>;604	type XcmExecutor = XcmExecutor<XcmConfig>;605	type XcmTeleportFilter = All<(MultiLocation, Vec<MultiAsset>)>;606	type XcmReserveTransferFilter = ();607	type Weigher = FixedWeightBounds<UnitWeightCost, Call>;608}609610impl cumulus_pallet_xcm::Config for Runtime {611	type Event = Event;612	type XcmExecutor = XcmExecutor<XcmConfig>;613}614615impl cumulus_pallet_xcmp_queue::Config for Runtime {616	type Event = Event;617	type XcmExecutor = XcmExecutor<XcmConfig>;618	type ChannelInfo = ParachainSystem;619}620621impl cumulus_pallet_dmp_queue::Config for Runtime {622	type Event = Event;623	type XcmExecutor = XcmExecutor<XcmConfig>;624	type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;625}626627impl pallet_aura::Config for Runtime {628	type AuthorityId = AuraId;629}630631parameter_types! {632	pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();633	pub const CollectionCreationPrice: Balance = 100 * UNIQUE;634}635636/// Used for the pallet nft in `./nft.rs`637impl pallet_nft::Config for Runtime {638    type Event = Event;639    type WeightInfo = nft_weights::WeightInfo;640	type Currency = Balances;641	type CollectionCreationPrice = CollectionCreationPrice;642	type TreasuryAccountId = TreasuryAccountId;643}644645parameter_types! {646	pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied647}648649/// Used for the pallet inflation650impl pallet_inflation::Config for Runtime {651	type Currency = Balances;652	type TreasuryAccountId = TreasuryAccountId;653	type InflationBlockInterval = InflationBlockInterval;654}655656parameter_types! {657	pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *658		RuntimeBlockWeights::get().max_block;659	pub const MaxScheduledPerBlock: u32 = 50;660}661662pub struct Sponsoring;663impl SponsoringResolve<AccountId, Call> for Sponsoring {664665	fn resolve(who: &AccountId, call: &Call) -> Option<AccountId> 666	where 667		Call: Dispatchable<Info=DispatchInfo>,668		Call: IsSubType<pallet_nft::Call<Runtime>>, 669		Call: IsSubType<pallet_contracts::Call<Runtime>>,670		AccountId: AsRef<[u8]>,671		AccountId: UncheckedFrom<Hash>672	{673		pallet_nft_transaction_payment::Module::<Runtime>::withdraw_type(who, call)674	}675}676677impl pallet_scheduler::Config for Runtime {678	type Event = Event;679	type Origin = Origin;680	type PalletsOrigin = OriginCaller;681	type Call = Call;682	type MaximumWeight = MaximumSchedulerWeight;683	type ScheduleOrigin = EnsureSigned<AccountId>;684	type MaxScheduledPerBlock = MaxScheduledPerBlock;685	type Sponsoring = Sponsoring;686	type WeightInfo = ();687}688689impl pallet_nft_transaction_payment::Config for Runtime {690}691692impl pallet_nft_charge_transaction::Config for Runtime {693}694695construct_runtime!(696    pub enum Runtime where697        Block = Block,698        NodeBlock = opaque::Block,699        UncheckedExtrinsic = UncheckedExtrinsic700    {701		Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 30,702		Contracts: pallet_contracts::{Pallet, Call, Storage, Event<T>},703		RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Call, Storage},704		Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent},705		TransactionPayment: pallet_transaction_payment::{Pallet, Storage},706        Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event<T>},707		Sudo: pallet_sudo::{Pallet, Call, Storage, Config<T>, Event<T>},708		System: system::{Pallet, Call, Storage, Config, Event<T>},709        Vesting: pallet_vesting::{Pallet, Call, Config<T>, Storage, Event<T>},710711		ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Storage, Inherent, Event<T>, ValidateUnsigned} = 20,712		ParachainInfo: parachain_info::{Pallet, Storage, Config} = 21,713714		Aura: pallet_aura::{Pallet, Config<T>},715		AuraExt: cumulus_pallet_aura_ext::{Pallet, Config},716717		// XCM helpers.718		XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 50,719		PolkadotXcm: pallet_xcm::{Pallet, Call, Event<T>, Origin} = 51,720		CumulusXcm: cumulus_pallet_xcm::{Pallet, Call, Event<T>, Origin} = 52,721		DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,722723724		// Unique Pallets725        Inflation: pallet_inflation::{Pallet, Call, Storage},726		Nft: pallet_nft::{Pallet, Call, Config<T>, Storage, Event<T>},727		Scheduler: pallet_scheduler::{Pallet, Call, Storage, Event<T>},728		NftPayment: pallet_nft_transaction_payment::{Pallet, Call, Storage},729		Charging: pallet_nft_charge_transaction::{Pallet, Call, Storage },730    }731);732733/// The address format for describing accounts.734pub type Address = sp_runtime::MultiAddress<AccountId, ()>;735/// Block header type as expected by this runtime.736pub type Header = generic::Header<BlockNumber, BlakeTwo256>;737/// Block type as expected by this runtime.738pub type Block = generic::Block<Header, UncheckedExtrinsic>;739/// A Block signed with a Justification740pub type SignedBlock = generic::SignedBlock<Block>;741/// BlockId type as expected by this runtime.742pub type BlockId = generic::BlockId<Block>;743/// The SignedExtension to the basic transaction logic.744pub type SignedExtra = (745    system::CheckSpecVersion<Runtime>,746    // system::CheckTxVersion<Runtime>,747    system::CheckGenesis<Runtime>,748    system::CheckEra<Runtime>,749    system::CheckNonce<Runtime>,750    system::CheckWeight<Runtime>,751    pallet_nft_charge_transaction::ChargeTransactionPayment<Runtime>,752);753/// Unchecked extrinsic type as expected by this runtime.754pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;755/// Extrinsic type that has already been checked.756pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, Call, SignedExtra>;757/// Executive: handles dispatch to the various modules.758pub type Executive = frame_executive::Executive<759    Runtime,760    Block,761    frame_system::ChainContext<Runtime>,762    Runtime,763    AllPallets,764>;765766impl_opaque_keys! {767	pub struct SessionKeys {768		pub aura: Aura,769	}770}771772impl_runtime_apis! {773    impl sp_api::Core<Block> for Runtime {774        fn version() -> RuntimeVersion {775            VERSION776        }777778        fn execute_block(block: Block) {779            Executive::execute_block(block)780        }781782        fn initialize_block(header: &<Block as BlockT>::Header) {783            Executive::initialize_block(header)784        }785    }786787    impl sp_api::Metadata<Block> for Runtime {788        fn metadata() -> OpaqueMetadata {789            Runtime::metadata().into()790        }791    }792793    impl sp_block_builder::BlockBuilder<Block> for Runtime {794        fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {795            Executive::apply_extrinsic(extrinsic)796        }797798        fn finalize_block() -> <Block as BlockT>::Header {799            Executive::finalize_block()800        }801802        fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {803            data.create_extrinsics()804        }805806        fn check_inherents(807            block: Block,808            data: sp_inherents::InherentData,809        ) -> sp_inherents::CheckInherentsResult {810            data.check_extrinsics(&block)811        }812813        // fn random_seed() -> <Block as BlockT>::Hash {814        //     RandomnessCollectiveFlip::random_seed().0815        // }816    }817818    impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {819        fn validate_transaction(820            source: TransactionSource,821            tx: <Block as BlockT>::Extrinsic,822        ) -> TransactionValidity {823            Executive::validate_transaction(source, tx)824        }825    }826827	impl sp_offchain::OffchainWorkerApi<Block> for Runtime {828		fn offchain_worker(header: &<Block as BlockT>::Header) {829			Executive::offchain_worker(header)830		}831	}832833	impl sp_session::SessionKeys<Block> for Runtime {834		fn decode_session_keys(835			encoded: Vec<u8>,836		) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {837			SessionKeys::decode_into_raw_public_keys(&encoded)838		}839840		fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {841			SessionKeys::generate(seed)842		}843	}844845	impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {846		fn slot_duration() -> sp_consensus_aura::SlotDuration {847			sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())848		}849850		fn authorities() -> Vec<AuraId> {851			Aura::authorities()852		}853	}854855	impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {856		fn collect_collation_info() -> cumulus_primitives_core::CollationInfo {857			ParachainSystem::collect_collation_info()858		}859	}860861	impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {862		fn account_nonce(account: AccountId) -> Index {863			System::account_nonce(account)864		}865	}866867	impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {868		fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {869			TransactionPayment::query_info(uxt, len)870		}871		fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {872			TransactionPayment::query_fee_details(uxt, len)873		}874	}875876	impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber, Hash>877		for Runtime878	{879		fn call(880			origin: AccountId,881			dest: AccountId,882			value: Balance,883			gas_limit: u64,884			input_data: Vec<u8>,885		) -> pallet_contracts_primitives::ContractExecResult {886			Contracts::bare_call(origin, dest, value, gas_limit, input_data, false)887		}888889		fn instantiate(890			origin: AccountId,891			endowment: Balance,892			gas_limit: u64,893			code: pallet_contracts_primitives::Code<Hash>,894			data: Vec<u8>,895			salt: Vec<u8>,896		) -> pallet_contracts_primitives::ContractInstantiateResult<AccountId, BlockNumber>897		{898			Contracts::bare_instantiate(origin, endowment, gas_limit, code, data, salt, true, false)899		}900901		fn get_storage(902			address: AccountId,903			key: [u8; 32],904		) -> pallet_contracts_primitives::GetStorageResult {905			Contracts::get_storage(address, key)906		}907908		fn rent_projection(909			address: AccountId,910		) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {911			Contracts::rent_projection(address)912		}913	}914915    #[cfg(feature = "runtime-benchmarks")]916	impl frame_benchmarking::Benchmark<Block> for Runtime {917		fn dispatch_benchmark(918			config: frame_benchmarking::BenchmarkConfig919		) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {920			use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};921922			let whitelist: Vec<TrackedStorageKey> = vec![923				// Alice account924				hex_literal::hex!("d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d").to_vec().into(),925				// // Total Issuance926				// hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),927				// // Execution Phase928				// hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),929				// // Event Count930				// hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),931				// // System Events932				// hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),933            ];934935			let mut batches = Vec::<BenchmarkBatch>::new();936			let params = (&config, &whitelist);937938			add_benchmark!(params, batches, pallet_nft, Nft);939			add_benchmark!(params, batches, pallet_inflation, Inflation);940941			if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }942			Ok(batches)943		}944	}945}946947cumulus_pallet_parachain_system::register_validate_block!(948	Runtime,949	cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,950);