Skip to main content

yet_another_parachain_runtime/
lib.rs

1// Copyright (C) Parity Technologies (UK) Ltd.
2// This file is part of Cumulus.
3// SPDX-License-Identifier: Apache-2.0
4
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// 	http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16
17#![cfg_attr(not(feature = "std"), no_std)]
18#![recursion_limit = "256"]
19
20// Make the WASM binary available.
21#[cfg(feature = "std")]
22include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
23
24extern crate alloc;
25
26mod genesis_config_presets;
27mod xcm_config;
28
29use crate::xcm_config::{RelayLocation, XcmOriginToTransactDispatchOrigin};
30
31use pallet_xcm::{EnsureXcm, IsVoiceOfBody};
32pub use polkadot_sdk::{staging_parachain_info as parachain_info, *};
33use staging_xcm_builder as xcm_builder;
34use staging_xcm_executor as xcm_executor;
35
36use cumulus_primitives_core::ParaId;
37use parachains_common::message_queue::{NarrowOriginToSibling, ParaIdToSibling};
38use polkadot_runtime_common::{prod_or_fast, xcm_sender::NoPriceForMessageDelivery};
39
40use alloc::{borrow::Cow, vec, vec::Vec};
41use cumulus_pallet_parachain_system::RelayNumberMonotonicallyIncreases;
42use frame_support::weights::{constants, FixedFee, RuntimeDbWeight};
43use sp_api::impl_runtime_apis;
44use sp_core::OpaqueMetadata;
45use sp_runtime::{
46	generic, impl_opaque_keys,
47	traits::{AccountIdLookup, BlakeTwo256, Block as BlockT, Hash as HashT},
48	transaction_validity::{TransactionSource, TransactionValidity},
49	ApplyExtrinsicResult, MultiSignature, MultiSigner,
50};
51use sp_session::OpaqueGeneratedSessionKeys;
52
53#[cfg(feature = "std")]
54use sp_version::NativeVersion;
55use sp_version::RuntimeVersion;
56
57// A few exports that help ease life for downstream crates.
58pub use frame_support::{
59	construct_runtime, derive_impl,
60	dispatch::DispatchClass,
61	genesis_builder_helper::{build_state, get_preset},
62	parameter_types,
63	traits::{
64		AsEnsureOriginWithArg, ConstBool, ConstU32, ConstU64, ConstU8, Contains, EitherOfDiverse,
65		Everything, HandleMessage, IsInVec, Nothing, QueueFootprint, Randomness, TransformOrigin,
66	},
67	weights::{
68		constants::{BlockExecutionWeight, WEIGHT_REF_TIME_PER_SECOND},
69		ConstantMultiplier, IdentityFee, Weight, WeightToFeeCoefficient, WeightToFeeCoefficients,
70		WeightToFeePolynomial,
71	},
72	BoundedSlice, PalletId, StorageValue,
73};
74use frame_system::{
75	limits::{BlockLength, BlockWeights},
76	EnsureRoot,
77};
78pub use pallet_balances::Call as BalancesCall;
79pub use pallet_timestamp::Call as TimestampCall;
80pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;
81#[cfg(any(feature = "std", test))]
82pub use sp_runtime::BuildStorage;
83pub use sp_runtime::{Perbill, Permill};
84
85use cumulus_primitives_core::AggregateMessageOrigin; //, ClaimQueueOffset, CoreSelector};
86use parachains_common::{AccountId, Signature};
87use staging_xcm::latest::prelude::BodyId;
88
89pub type SessionHandlers = ();
90
91impl_opaque_keys! {
92	pub struct SessionKeys {
93		pub aura: Aura,
94	}
95}
96
97/// This runtime version.
98#[sp_version::runtime_version]
99pub const VERSION: RuntimeVersion = RuntimeVersion {
100	spec_name: Cow::Borrowed("yet-another-parachain"),
101	impl_name: Cow::Borrowed("yet-another-parachain"),
102	authoring_version: 1,
103	spec_version: 1_003_000,
104	impl_version: 0,
105	apis: RUNTIME_API_VERSIONS,
106	transaction_version: 6,
107	system_version: 1,
108};
109
110pub const MILLISECS_PER_BLOCK: u64 = 2000;
111
112pub const SLOT_DURATION: u64 = 24_000;
113
114pub const EPOCH_DURATION_IN_BLOCKS: u32 = 10 * MINUTES;
115
116// These time units are defined in number of blocks.
117pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);
118pub const HOURS: BlockNumber = MINUTES * 60;
119pub const DAYS: BlockNumber = HOURS * 24;
120
121pub const YAP: Balance = 1_000_000_000_000;
122pub const NANOYAP: Balance = 1_000;
123
124/// The version information used to identify this runtime when compiled natively.
125#[cfg(feature = "std")]
126pub fn native_version() -> NativeVersion {
127	NativeVersion { runtime_version: VERSION, can_author_with: Default::default() }
128}
129
130/// We assume that ~10% of the block weight is consumed by `on_initialize` handlers.
131/// This is used to limit the maximal weight of a single extrinsic.
132const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(10);
133/// We allow `Normal` extrinsics to fill up the block up to 95%, the rest can be used
134/// by  Operational  extrinsics.
135const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(95);
136/// We allow for 2 seconds of compute with a 6 second average block time.
137const MAXIMUM_BLOCK_WEIGHT: Weight = Weight::from_parts(
138	WEIGHT_REF_TIME_PER_SECOND.saturating_mul(2),
139	cumulus_primitives_core::relay_chain::MAX_POV_SIZE as u64,
140);
141
142/// Maximum number of blocks simultaneously accepted by the Runtime, not yet included
143/// into the relay chain.
144const UNINCLUDED_SEGMENT_CAPACITY: u32 = 10;
145
146/// Build with an offset of 1 behind the relay chain.
147const RELAY_PARENT_OFFSET: u32 = 1;
148
149/// How many parachain blocks are processed by the relay chain per parent. Limits the
150/// number of blocks authored per slot.
151const BLOCK_PROCESSING_VELOCITY: u32 = 3;
152/// Relay chain slot duration, in milliseconds.
153const RELAY_CHAIN_SLOT_DURATION_MILLIS: u32 = 6000;
154
155parameter_types! {
156	pub const BlockHashCount: BlockNumber = 250;
157	pub const Version: RuntimeVersion = VERSION;
158	pub RuntimeBlockLength: BlockLength = BlockLength::builder()
159		.max_length(5 * 1024 * 1024)
160		.modify_max_length_for_class(DispatchClass::Normal, |m| {
161			*m = NORMAL_DISPATCH_RATIO * *m
162		})
163		.build();
164	pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()
165		.base_block(BlockExecutionWeight::get())
166		.for_class(DispatchClass::all(), |weights| {
167			weights.base_extrinsic = <pallet_verify_signature::weights::SubstrateWeight::<Runtime> as pallet_verify_signature::WeightInfo>::verify_signature();
168		})
169		.for_class(DispatchClass::Normal, |weights| {
170			weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);
171		})
172		.for_class(DispatchClass::Operational, |weights| {
173			weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);
174			// Operational transactions have some extra reserved space, so that they
175			// are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.
176			weights.reserved = Some(
177				MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT
178			);
179		})
180		.avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)
181		.build_or_panic();
182	pub const SS58Prefix: u8 = 42;
183	// We assume the whole parachain state fits into the trie cache
184	// Numbers are from <https://github.com/paritytech/polkadot-sdk/pull/7867>
185	pub const InMemoryDbWeight: RuntimeDbWeight = RuntimeDbWeight {
186		read: 9_000 * constants::WEIGHT_REF_TIME_PER_NANOS,
187		write: 28_000 * constants::WEIGHT_REF_TIME_PER_NANOS,
188	};
189}
190
191#[derive_impl(frame_system::config_preludes::TestDefaultConfig)]
192impl frame_system::Config for Runtime {
193	/// The identifier used to distinguish between accounts.
194	type AccountId = AccountId;
195	/// The aggregated dispatch type that is available for extrinsics.
196	type RuntimeCall = RuntimeCall;
197	/// The lookup mechanism to get account ID from whatever is passed in dispatchers.
198	type Lookup = AccountIdLookup<AccountId, ()>;
199	/// The index type for storing how many extrinsics an account has signed.
200	type Nonce = Nonce;
201	/// The type for hashing blocks and tries.
202	type Hash = Hash;
203	/// The hashing algorithm used.
204	type Hashing = BlakeTwo256;
205	/// The block type.
206	type Block = Block;
207	/// The ubiquitous event type.
208	type RuntimeEvent = RuntimeEvent;
209	/// The ubiquitous origin type.
210	type RuntimeOrigin = RuntimeOrigin;
211	/// Maximum number of block number to block hash mappings to keep (oldest pruned first).
212	type BlockHashCount = BlockHashCount;
213	/// Runtime version.
214	type Version = Version;
215	/// Converts a module to an index of this module in the runtime.
216	type PalletInfo = PalletInfo;
217	type AccountData = pallet_balances::AccountData<Balance>;
218	type OnNewAccount = ();
219	type OnKilledAccount = ();
220	type DbWeight = InMemoryDbWeight;
221	type BaseCallFilter = frame_support::traits::Everything;
222	type SystemWeightInfo = frame_system::weights::SubstrateWeight<Self>;
223	type ExtensionsWeightInfo = frame_system::SubstrateExtensionsWeight<Self>;
224	type BlockWeights = RuntimeBlockWeights;
225	type BlockLength = RuntimeBlockLength;
226	type SS58Prefix = SS58Prefix;
227	type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;
228	type MaxConsumers = frame_support::traits::ConstU32<16>;
229	type SingleBlockMigrations = RemoveCollectiveFlip;
230}
231
232impl cumulus_pallet_weight_reclaim::Config for Runtime {
233	type WeightInfo = ();
234}
235
236impl pallet_timestamp::Config for Runtime {
237	/// A timestamp: milliseconds since the unix epoch.
238	type Moment = u64;
239	type OnTimestampSet = Aura;
240	type MinimumPeriod = ConstU64<0>;
241	type WeightInfo = pallet_timestamp::weights::SubstrateWeight<Self>;
242}
243
244parameter_types! {
245	pub const Period: u32 = prod_or_fast!(10 * MINUTES, 10);
246	pub const Offset: u32 = 0;
247}
248
249impl pallet_session::Config for Runtime {
250	type RuntimeEvent = RuntimeEvent;
251	type ValidatorId = <Self as frame_system::Config>::AccountId;
252	type ValidatorIdOf = pallet_collator_selection::IdentityCollator;
253	type ShouldEndSession = pallet_session::PeriodicSessions<Period, Offset>;
254	type NextSessionRotation = pallet_session::PeriodicSessions<Period, Offset>;
255	type SessionManager = CollatorSelection;
256	// Essentially just Aura, but let's be pedantic.
257	type SessionHandler = <SessionKeys as sp_runtime::traits::OpaqueKeys>::KeyTypeIdProviders;
258	type Keys = SessionKeys;
259	type DisablingStrategy = ();
260	type WeightInfo = ();
261	type Currency = Balances;
262	type KeyDeposit = ();
263}
264
265parameter_types! {
266	pub const PotId: PalletId = PalletId(*b"PotStake");
267	pub const SessionLength: BlockNumber = prod_or_fast!(10 * MINUTES, 10);
268	// StakingAdmin pluralistic body.
269	pub const StakingAdminBodyId: BodyId = BodyId::Defense;
270}
271
272/// We allow root and the StakingAdmin to execute privileged collator selection operations.
273pub type CollatorSelectionUpdateOrigin = EitherOfDiverse<
274	EnsureRoot<AccountId>,
275	EnsureXcm<IsVoiceOfBody<RelayLocation, StakingAdminBodyId>>,
276>;
277
278impl pallet_collator_selection::Config for Runtime {
279	type RuntimeEvent = RuntimeEvent;
280	type Currency = Balances;
281	type UpdateOrigin = CollatorSelectionUpdateOrigin;
282	type PotId = PotId;
283	type MaxCandidates = ConstU32<100>;
284	type MinEligibleCollators = ConstU32<4>;
285	type MaxInvulnerables = ConstU32<20>;
286	// should be a multiple of session or things will get inconsistent
287	type KickThreshold = Period;
288	type ValidatorId = <Self as frame_system::Config>::AccountId;
289	type ValidatorIdOf = pallet_collator_selection::IdentityCollator;
290	type ValidatorRegistration = Session;
291	type WeightInfo = ();
292}
293
294parameter_types! {
295	pub const ExistentialDeposit: u128 = NANOYAP;
296	pub const TransactionByteFee: u128 = NANOYAP;
297}
298
299impl pallet_balances::Config for Runtime {
300	/// The type for recording an account's balance.
301	type Balance = Balance;
302	type DustRemoval = ();
303	/// The ubiquitous event type.
304	type RuntimeEvent = RuntimeEvent;
305	type ExistentialDeposit = ExistentialDeposit;
306	type AccountStore = System;
307	type WeightInfo = pallet_balances::weights::SubstrateWeight<Self>;
308	type MaxLocks = ConstU32<50>;
309	type MaxReserves = ConstU32<50>;
310	type ReserveIdentifier = [u8; 8];
311	type RuntimeHoldReason = RuntimeHoldReason;
312	type RuntimeFreezeReason = RuntimeFreezeReason;
313	type FreezeIdentifier = ();
314	type MaxFreezes = ConstU32<0>;
315	type DoneSlashHandler = ();
316}
317
318impl pallet_transaction_payment::Config for Runtime {
319	type RuntimeEvent = RuntimeEvent;
320	type OnChargeTransaction = pallet_transaction_payment::FungibleAdapter<Balances, ()>;
321	type WeightToFee = FixedFee<1, <Self as pallet_balances::Config>::Balance>;
322	type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;
323	type FeeMultiplierUpdate = ();
324	type OperationalFeeMultiplier = ConstU8<5>;
325	type WeightInfo = pallet_transaction_payment::weights::SubstrateWeight<Self>;
326}
327
328impl pallet_sudo::Config for Runtime {
329	type RuntimeCall = RuntimeCall;
330	type RuntimeEvent = RuntimeEvent;
331	type WeightInfo = pallet_sudo::weights::SubstrateWeight<Runtime>;
332}
333
334parameter_types! {
335	pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
336	pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
337	pub const RelayOrigin: AggregateMessageOrigin = AggregateMessageOrigin::Parent;
338}
339
340type ConsensusHook = cumulus_pallet_aura_ext::FixedVelocityConsensusHook<
341	Runtime,
342	RELAY_CHAIN_SLOT_DURATION_MILLIS,
343	BLOCK_PROCESSING_VELOCITY,
344	UNINCLUDED_SEGMENT_CAPACITY,
345>;
346
347pub struct DmpSink;
348impl HandleMessage for DmpSink {
349	type MaxMessageLen = ConstU32<16>;
350
351	fn handle_message(_msg: BoundedSlice<u8, Self::MaxMessageLen>) {}
352
353	fn handle_messages<'a>(_: impl Iterator<Item = BoundedSlice<'a, u8, Self::MaxMessageLen>>) {
354		unimplemented!()
355	}
356
357	fn sweep_queue() {
358		unimplemented!()
359	}
360}
361
362impl cumulus_pallet_parachain_system::Config for Runtime {
363	type WeightInfo = cumulus_pallet_parachain_system::weights::SubstrateWeight<Self>;
364	type RuntimeEvent = RuntimeEvent;
365	type OnSystemEvent = ();
366	type SelfParaId = parachain_info::Pallet<Runtime>;
367	type OutboundXcmpMessageSource = XcmpQueue;
368	type DmpQueue = frame_support::traits::EnqueueWithOrigin<MessageQueue, RelayOrigin>;
369	type ReservedDmpWeight = ReservedDmpWeight;
370	type XcmpMessageHandler = XcmpQueue;
371	type ReservedXcmpWeight = ReservedXcmpWeight;
372	type CheckAssociatedRelayNumber = RelayNumberMonotonicallyIncreases;
373	type ConsensusHook = ConsensusHook;
374	type RelayParentOffset = ConstU32<RELAY_PARENT_OFFSET>;
375}
376
377impl pallet_message_queue::Config for Runtime {
378	type RuntimeEvent = RuntimeEvent;
379	type WeightInfo = ();
380	type MessageProcessor = xcm_builder::ProcessXcmMessage<
381		AggregateMessageOrigin,
382		xcm_executor::XcmExecutor<xcm_config::XcmConfig>,
383		RuntimeCall,
384	>;
385	type Size = u32;
386	// The XCMP queue pallet is only ever able to handle the `Sibling(ParaId)` origin:
387	type QueueChangeHandler = NarrowOriginToSibling<XcmpQueue>;
388	type QueuePausedQuery = NarrowOriginToSibling<XcmpQueue>;
389	type HeapSize = sp_core::ConstU32<{ 103 * 1024 }>;
390	type MaxStale = sp_core::ConstU32<8>;
391	type ServiceWeight = MessageQueueServiceWeight;
392	type IdleMaxServiceWeight = ();
393}
394parameter_types! {
395	pub MessageQueueServiceWeight: Weight = Perbill::from_percent(35) * RuntimeBlockWeights::get().max_block;
396}
397
398impl pallet_authorship::Config for Runtime {
399	type FindAuthor = ();
400	type EventHandler = ();
401}
402
403pub struct WeightToFee;
404impl WeightToFeePolynomial for WeightToFee {
405	type Balance = Balance;
406	fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {
407		// in Rococo, extrinsic base weight (smallest non-zero weight) is mapped to 1 MILLI_UNIT:
408		// in our template, we map to 1/10 of that, or 1/10 MILLI_UNIT
409		let p = YAP / 10;
410		let q = 100 *
411			Balance::from(
412				frame_support::weights::constants::ExtrinsicBaseWeight::get().ref_time(),
413			);
414		vec![WeightToFeeCoefficient {
415			degree: 1,
416			negative: false,
417			coeff_frac: Perbill::from_rational(p % q, q),
418			coeff_integer: p / q,
419		}]
420		.into()
421	}
422}
423
424impl cumulus_pallet_xcmp_queue::Config for Runtime {
425	type RuntimeEvent = RuntimeEvent;
426	type ChannelInfo = ParachainSystem;
427	type VersionWrapper = ();
428	// Enqueue XCMP messages from siblings for later processing.
429	type XcmpQueue = TransformOrigin<MessageQueue, AggregateMessageOrigin, ParaId, ParaIdToSibling>;
430	type MaxInboundSuspended = sp_core::ConstU32<1_000>;
431	type MaxActiveOutboundChannels = ConstU32<128>;
432	type MaxPageSize = ConstU32<{ 1 << 16 }>;
433	type ControllerOrigin = EnsureRoot<AccountId>;
434	type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;
435	type WeightInfo = ();
436	type PriceForSiblingDelivery = NoPriceForMessageDelivery<ParaId>;
437}
438
439impl parachain_info::Config for Runtime {}
440
441impl cumulus_pallet_aura_ext::Config for Runtime {}
442
443impl pallet_aura::Config for Runtime {
444	type AuthorityId = AuraId;
445	type DisabledValidators = ();
446	type MaxAuthorities = ConstU32<100_000>;
447	type AllowMultipleBlocksPerSlot = ConstBool<true>;
448	type SlotDuration = ConstU64<SLOT_DURATION>;
449}
450
451impl pallet_utility::Config for Runtime {
452	type RuntimeEvent = RuntimeEvent;
453	type RuntimeCall = RuntimeCall;
454	type PalletsOrigin = OriginCaller;
455	type WeightInfo = ();
456}
457
458#[cfg(feature = "runtime-benchmarks")]
459pub struct VerifySignatureBenchmarkHelper;
460#[cfg(feature = "runtime-benchmarks")]
461impl pallet_verify_signature::BenchmarkHelper<MultiSignature, AccountId>
462	for VerifySignatureBenchmarkHelper
463{
464	fn create_signature(_entropy: &[u8], msg: &[u8]) -> (MultiSignature, AccountId) {
465		use sp_io::crypto::{sr25519_generate, sr25519_sign};
466		use sp_runtime::traits::IdentifyAccount;
467		let public = sr25519_generate(0.into(), None);
468		let who_account: AccountId = MultiSigner::Sr25519(public).into_account().into();
469		let signature = MultiSignature::Sr25519(sr25519_sign(0.into(), &public, msg).unwrap());
470		(signature, who_account)
471	}
472}
473
474impl pallet_verify_signature::Config for Runtime {
475	type Signature = MultiSignature;
476	type AccountIdentifier = MultiSigner;
477	type WeightInfo = pallet_verify_signature::weights::SubstrateWeight<Runtime>;
478	#[cfg(feature = "runtime-benchmarks")]
479	type BenchmarkHelper = VerifySignatureBenchmarkHelper;
480}
481
482#[frame_support::runtime]
483mod runtime {
484	#[runtime::runtime]
485	#[runtime::derive(
486		RuntimeCall,
487		RuntimeEvent,
488		RuntimeError,
489		RuntimeOrigin,
490		RuntimeFreezeReason,
491		RuntimeHoldReason,
492		RuntimeSlashReason,
493		RuntimeLockId,
494		RuntimeTask,
495		RuntimeViewFunction
496	)]
497	pub struct Runtime;
498
499	#[runtime::pallet_index(0)]
500	pub type System = frame_system;
501	#[runtime::pallet_index(1)]
502	pub type Timestamp = pallet_timestamp;
503	#[runtime::pallet_index(2)]
504	pub type Sudo = pallet_sudo;
505	#[runtime::pallet_index(3)]
506	pub type TransactionPayment = pallet_transaction_payment;
507	#[runtime::pallet_index(4)]
508	pub type WeightReclaim = cumulus_pallet_weight_reclaim;
509
510	#[runtime::pallet_index(20)]
511	pub type ParachainSystem = cumulus_pallet_parachain_system;
512	#[runtime::pallet_index(21)]
513	pub type ParachainInfo = parachain_info;
514
515	#[runtime::pallet_index(25)]
516	pub type Authorship = pallet_authorship;
517	#[runtime::pallet_index(26)]
518	pub type CollatorSelection = pallet_collator_selection;
519	#[runtime::pallet_index(27)]
520	pub type Session = pallet_session;
521
522	#[runtime::pallet_index(30)]
523	pub type Balances = pallet_balances;
524
525	#[runtime::pallet_index(31)]
526	pub type Aura = pallet_aura;
527	#[runtime::pallet_index(32)]
528	pub type AuraExt = cumulus_pallet_aura_ext;
529
530	#[runtime::pallet_index(40)]
531	pub type Utility = pallet_utility;
532	#[runtime::pallet_index(41)]
533	pub type VerifySignature = pallet_verify_signature;
534
535	#[runtime::pallet_index(51)]
536	pub type XcmpQueue = cumulus_pallet_xcmp_queue;
537	#[runtime::pallet_index(52)]
538	pub type PolkadotXcm = pallet_xcm;
539	#[runtime::pallet_index(53)]
540	pub type CumulusXcm = cumulus_pallet_xcm;
541	#[runtime::pallet_index(54)]
542	pub type MessageQueue = pallet_message_queue;
543}
544
545/// Balance of an account.
546pub type Balance = u128;
547/// Index of a transaction in the chain.
548pub type Nonce = u32;
549/// A hash of some data used by the chain.
550pub type Hash = <BlakeTwo256 as HashT>::Output;
551/// An index to a block.
552pub type BlockNumber = u32;
553/// The address format for describing accounts.
554pub type Address = sp_runtime::MultiAddress<AccountId, ()>;
555/// Block header type as expected by this runtime.
556pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
557/// Block type as expected by this runtime.
558pub type Block = generic::Block<Header, UncheckedExtrinsic>;
559/// A Block signed with a Justification
560pub type SignedBlock = generic::SignedBlock<Block>;
561/// BlockId type as expected by this runtime.
562pub type BlockId = generic::BlockId<Block>;
563/// The TransactionExtension to the basic transaction logic.
564pub type TxExtension = cumulus_pallet_weight_reclaim::StorageWeightReclaim<
565	Runtime,
566	(
567		// Uncomment this to enable running signed transactions using v5 extrinsics.
568		// pallet_verify_signature::VerifySignature<Runtime>,
569		frame_system::CheckNonZeroSender<Runtime>,
570		frame_system::CheckSpecVersion<Runtime>,
571		frame_system::CheckTxVersion<Runtime>,
572		frame_system::CheckGenesis<Runtime>,
573		frame_system::CheckEra<Runtime>,
574		frame_system::CheckNonce<Runtime>,
575		frame_system::CheckWeight<Runtime>,
576		pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
577	),
578>;
579/// Unchecked extrinsic type as expected by this runtime.
580pub type UncheckedExtrinsic =
581	generic::UncheckedExtrinsic<Address, RuntimeCall, Signature, TxExtension>;
582/// Executive: handles dispatch to the various modules.
583pub type Executive = frame_executive::Executive<
584	Runtime,
585	Block,
586	frame_system::ChainContext<Runtime>,
587	Runtime,
588	AllPalletsWithSystem,
589>;
590
591pub struct RemoveCollectiveFlip;
592impl frame_support::traits::OnRuntimeUpgrade for RemoveCollectiveFlip {
593	fn on_runtime_upgrade() -> Weight {
594		use frame_support::storage::migration;
595		// Remove the storage value `RandomMaterial` from removed pallet `RandomnessCollectiveFlip`
596		#[allow(deprecated)]
597		migration::remove_storage_prefix(b"RandomnessCollectiveFlip", b"RandomMaterial", b"");
598		<Runtime as frame_system::Config>::DbWeight::get().writes(1)
599	}
600}
601
602impl_runtime_apis! {
603	impl sp_api::Core<Block> for Runtime {
604		fn version() -> RuntimeVersion {
605			VERSION
606		}
607
608		fn execute_block(block: <Block as BlockT>::LazyBlock) {
609			Executive::execute_block(block);
610		}
611
612		fn initialize_block(header: &<Block as BlockT>::Header) -> sp_runtime::ExtrinsicInclusionMode {
613			Executive::initialize_block(header)
614		}
615	}
616
617	impl sp_api::Metadata<Block> for Runtime {
618		fn metadata() -> OpaqueMetadata {
619			OpaqueMetadata::new(Runtime::metadata().into())
620		}
621
622		fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
623			Runtime::metadata_at_version(version)
624		}
625
626		fn metadata_versions() -> alloc::vec::Vec<u32> {
627			Runtime::metadata_versions()
628		}
629	}
630
631	impl sp_block_builder::BlockBuilder<Block> for Runtime {
632		fn apply_extrinsic(
633			extrinsic: <Block as BlockT>::Extrinsic,
634		) -> ApplyExtrinsicResult {
635			Executive::apply_extrinsic(extrinsic)
636		}
637
638		fn finalize_block() -> <Block as BlockT>::Header {
639			Executive::finalize_block()
640		}
641
642		fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
643			data.create_extrinsics()
644		}
645
646		fn check_inherents(block: <Block as BlockT>::LazyBlock, data: sp_inherents::InherentData) -> sp_inherents::CheckInherentsResult {
647			data.check_extrinsics(&block)
648		}
649	}
650
651	impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
652		fn validate_transaction(
653			source: TransactionSource,
654			tx: <Block as BlockT>::Extrinsic,
655			block_hash: <Block as BlockT>::Hash,
656		) -> TransactionValidity {
657			Executive::validate_transaction(source, tx, block_hash)
658		}
659	}
660
661	impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
662		fn offchain_worker(header: &<Block as BlockT>::Header) {
663			Executive::offchain_worker(header)
664		}
665	}
666
667	impl sp_session::SessionKeys<Block> for Runtime {
668		fn decode_session_keys(
669			encoded: Vec<u8>,
670		) -> Option<Vec<(Vec<u8>, sp_core::crypto::KeyTypeId)>> {
671			SessionKeys::decode_into_raw_public_keys(&encoded)
672		}
673
674			fn generate_session_keys(owner: Vec<u8>, seed: Option<Vec<u8>>) -> OpaqueGeneratedSessionKeys {
675			SessionKeys::generate(&owner, seed).into()
676		}
677
678	}
679
680	impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {
681		fn slot_duration() -> sp_consensus_aura::SlotDuration {
682			sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())
683		}
684
685		fn authorities() -> Vec<AuraId> {
686			pallet_aura::Authorities::<Runtime>::get().into_inner()
687		}
688	}
689
690	impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Nonce> for Runtime {
691		fn account_nonce(account: AccountId) -> Nonce {
692			System::account_nonce(account)
693		}
694	}
695
696	impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {
697		fn query_info(
698			uxt: <Block as BlockT>::Extrinsic,
699			len: u32,
700		) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo<Balance> {
701			TransactionPayment::query_info(uxt, len)
702		}
703		fn query_fee_details(
704			uxt: <Block as BlockT>::Extrinsic,
705			len: u32,
706		) -> pallet_transaction_payment::FeeDetails<Balance> {
707			TransactionPayment::query_fee_details(uxt, len)
708		}
709		fn query_weight_to_fee(weight: Weight) -> Balance {
710			TransactionPayment::weight_to_fee(weight)
711		}
712		fn query_length_to_fee(length: u32) -> Balance {
713			TransactionPayment::length_to_fee(length)
714		}
715	}
716
717	impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentCallApi<Block, Balance, RuntimeCall>
718		for Runtime
719	{
720		fn query_call_info(
721			call: RuntimeCall,
722			len: u32,
723		) -> pallet_transaction_payment::RuntimeDispatchInfo<Balance> {
724			TransactionPayment::query_call_info(call, len)
725		}
726		fn query_call_fee_details(
727			call: RuntimeCall,
728			len: u32,
729		) -> pallet_transaction_payment::FeeDetails<Balance> {
730			TransactionPayment::query_call_fee_details(call, len)
731		}
732		fn query_weight_to_fee(weight: Weight) -> Balance {
733			TransactionPayment::weight_to_fee(weight)
734		}
735		fn query_length_to_fee(length: u32) -> Balance {
736			TransactionPayment::length_to_fee(length)
737		}
738	}
739
740	impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {
741		fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {
742			ParachainSystem::collect_collation_info(header)
743		}
744	}
745
746	impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
747		fn build_state(config: Vec<u8>) -> sp_genesis_builder::Result {
748			build_state::<RuntimeGenesisConfig>(config)
749		}
750
751		fn get_preset(id: &Option<sp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
752			get_preset::<RuntimeGenesisConfig>(id, &genesis_config_presets::get_preset)
753		}
754
755		fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
756			genesis_config_presets::preset_names()
757		}
758	}
759
760	impl cumulus_primitives_core::RelayParentOffsetApi<Block> for Runtime {
761		fn relay_parent_offset() -> u32 {
762			RELAY_PARENT_OFFSET
763		}
764	}
765
766	impl cumulus_primitives_aura::AuraUnincludedSegmentApi<Block> for Runtime {
767		fn can_build_upon(
768			included_hash: <Block as BlockT>::Hash,
769			slot: cumulus_primitives_aura::Slot,
770		) -> bool {
771			ConsensusHook::can_build_upon(included_hash, slot)
772		}
773	}
774
775	impl cumulus_primitives_core::GetParachainInfo<Block> for Runtime {
776		fn parachain_id() -> ParaId {
777			ParachainInfo::parachain_id()
778		}
779	}
780}
781
782cumulus_pallet_parachain_system::register_validate_block! {
783	Runtime = Runtime,
784	BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,
785}