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