Skip to main content

bridge_hub_rococo_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//! # Bridge Hub Rococo Runtime
18//!
19//! This runtime currently supports bridging between:
20//! - Rococo <> Westend
21//! - Rococo <> Rococo Bulletin
22
23#![cfg_attr(not(feature = "std"), no_std)]
24// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.
25#![recursion_limit = "256"]
26
27// Make the WASM binary available.
28#[cfg(feature = "std")]
29include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
30
31pub mod bridge_common_config;
32pub mod bridge_to_bulletin_config;
33pub mod bridge_to_ethereum_config;
34pub mod bridge_to_westend_config;
35mod genesis_config_presets;
36mod weights;
37pub mod xcm_config;
38
39extern crate alloc;
40
41use alloc::{vec, vec::Vec};
42use bridge_runtime_common::extensions::{
43	CheckAndBoostBridgeGrandpaTransactions, CheckAndBoostBridgeParachainsTransactions,
44};
45use cumulus_pallet_parachain_system::RelayNumberMonotonicallyIncreases;
46use pallet_bridge_messages::LaneIdOf;
47use sp_api::impl_runtime_apis;
48use sp_core::{crypto::KeyTypeId, OpaqueMetadata};
49use sp_runtime::{
50	generic, impl_opaque_keys,
51	traits::Block as BlockT,
52	transaction_validity::{TransactionSource, TransactionValidity},
53	ApplyExtrinsicResult,
54};
55
56#[cfg(feature = "std")]
57use sp_version::NativeVersion;
58use sp_version::RuntimeVersion;
59
60use cumulus_primitives_core::{ParaId, VerifySchedulingSignature};
61use frame_support::{
62	construct_runtime, derive_impl,
63	dispatch::DispatchClass,
64	genesis_builder_helper::{build_state, get_preset},
65	parameter_types,
66	traits::{ConstBool, ConstU32, ConstU64, ConstU8, Get, TransformOrigin},
67	weights::{ConstantMultiplier, Weight},
68	PalletId,
69};
70use frame_system::{
71	limits::{BlockLength, BlockWeights},
72	EnsureRoot,
73};
74use testnet_parachains_constants::rococo::{consensus::*, currency::*, fee::WeightToFee, time::*};
75
76use bp_runtime::HeaderId;
77use bridge_hub_common::{
78	message_queue::{NarrowOriginToSibling, ParaIdToSibling},
79	AggregateMessageOrigin,
80};
81pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;
82pub use sp_runtime::{MultiAddress, Perbill, Permill};
83
84#[cfg(feature = "runtime-benchmarks")]
85use xcm::latest::WESTEND_GENESIS_HASH;
86use xcm::VersionedLocation;
87use xcm_config::{TreasuryAccount, XcmConfig, XcmOriginToTransactDispatchOrigin, XcmRouter};
88
89#[cfg(any(feature = "std", test))]
90pub use sp_runtime::BuildStorage;
91
92use polkadot_runtime_common::{BlockHashCount, SlowAdjustingFeeUpdate};
93use rococo_runtime_constants::system_parachain::{ASSET_HUB_ID, BRIDGE_HUB_ID};
94use snowbridge_core::{AgentId, PricingParameters};
95pub use snowbridge_outbound_queue_primitives::v1::{Command, ConstantGasMeter, Fee};
96use xcm::{latest::prelude::*, prelude::*, Version as XcmVersion};
97use xcm_runtime_apis::{
98	dry_run::{CallDryRunEffects, Error as XcmDryRunApiError, XcmDryRunEffects},
99	fees::Error as XcmPaymentApiError,
100};
101
102use weights::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight};
103
104use parachains_common::{
105	impls::DealWithFees, AccountId, Balance, BlockNumber, Hash, Header, Nonce, Signature,
106	AVERAGE_ON_INITIALIZE_RATIO, NORMAL_DISPATCH_RATIO,
107};
108
109#[cfg(feature = "runtime-benchmarks")]
110use alloc::boxed::Box;
111
112/// The address format for describing accounts.
113pub type Address = MultiAddress<AccountId, ()>;
114
115/// Block type as expected by this runtime.
116pub type Block = generic::Block<Header, UncheckedExtrinsic>;
117
118/// A Block signed with a Justification
119pub type SignedBlock = generic::SignedBlock<Block>;
120
121/// BlockId type as expected by this runtime.
122pub type BlockId = generic::BlockId<Block>;
123
124/// The TransactionExtension to the basic transaction logic.
125pub type TxExtension = cumulus_pallet_weight_reclaim::StorageWeightReclaim<
126	Runtime,
127	(
128		(
129			frame_system::AuthorizeCall<Runtime>,
130			frame_system::CheckNonZeroSender<Runtime>,
131			frame_system::CheckSpecVersion<Runtime>,
132			frame_system::CheckTxVersion<Runtime>,
133			frame_system::CheckGenesis<Runtime>,
134			frame_system::CheckEra<Runtime>,
135			frame_system::CheckNonce<Runtime>,
136			frame_system::CheckWeight<Runtime>,
137		),
138		pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
139		BridgeRejectObsoleteHeadersAndMessages,
140		(bridge_to_westend_config::OnBridgeHubRococoRefundBridgeHubWestendMessages,),
141		frame_metadata_hash_extension::CheckMetadataHash<Runtime>,
142	),
143>;
144
145/// Unchecked extrinsic type as expected by this runtime.
146pub type UncheckedExtrinsic =
147	generic::UncheckedExtrinsic<Address, RuntimeCall, Signature, TxExtension>;
148
149/// Migrations to apply on runtime upgrade.
150pub type Migrations = (
151	pallet_collator_selection::migration::v2::MigrationToV2<Runtime>,
152	pallet_multisig::migrations::v1::MigrateToV1<Runtime>,
153	InitStorageVersions,
154	// unreleased
155	cumulus_pallet_xcmp_queue::migration::v4::MigrationToV4<Runtime>,
156	cumulus_pallet_xcmp_queue::migration::v5::MigrateV4ToV5<Runtime>,
157	cumulus_pallet_xcmp_queue::migration::v6::MigrateV5ToV6<Runtime>,
158	cumulus_pallet_xcmp_queue::migration::v7::MigrateV6ToV7<Runtime>,
159	snowbridge_pallet_system::migration::v0::InitializeOnUpgrade<
160		Runtime,
161		ConstU32<BRIDGE_HUB_ID>,
162		ConstU32<ASSET_HUB_ID>,
163	>,
164	snowbridge_pallet_system::migration::FeePerGasMigrationV0ToV1<Runtime>,
165	pallet_bridge_messages::migration::v1::MigrationToV1<
166		Runtime,
167		bridge_to_westend_config::WithBridgeHubWestendMessagesInstance,
168	>,
169	pallet_bridge_messages::migration::v1::MigrationToV1<
170		Runtime,
171		bridge_to_bulletin_config::WithRococoBulletinMessagesInstance,
172	>,
173	bridge_to_westend_config::migration::FixMessagesV1Migration<
174		Runtime,
175		bridge_to_westend_config::WithBridgeHubWestendMessagesInstance,
176	>,
177	bridge_to_westend_config::migration::StaticToDynamicLanes,
178	frame_support::migrations::RemoveStorage<
179		BridgeWestendMessagesPalletName,
180		OutboundLanesCongestedSignalsKey,
181		RocksDbWeight,
182	>,
183	frame_support::migrations::RemoveStorage<
184		BridgePolkadotBulletinMessagesPalletName,
185		OutboundLanesCongestedSignalsKey,
186		RocksDbWeight,
187	>,
188	pallet_bridge_relayers::migration::v1::MigrationToV1<
189		Runtime,
190		bridge_common_config::RelayersForLegacyLaneIdsMessagesInstance,
191		bp_messages::LegacyLaneId,
192	>,
193	pallet_session::migrations::v1::MigrateV0ToV1<
194		Runtime,
195		pallet_session::migrations::v1::InitOffenceSeverity<Runtime>,
196	>,
197	// permanent
198	pallet_xcm::migration::MigrateToLatestXcmVersion<Runtime>,
199	cumulus_pallet_aura_ext::migration::MigrateV0ToV1<Runtime>,
200);
201
202parameter_types! {
203	pub const BridgeWestendMessagesPalletName: &'static str = "BridgeWestendMessages";
204	pub const BridgePolkadotBulletinMessagesPalletName: &'static str = "BridgePolkadotBulletinMessages";
205	pub const OutboundLanesCongestedSignalsKey: &'static str = "OutboundLanesCongestedSignals";
206}
207
208/// Migration to initialize storage versions for pallets added after genesis.
209///
210/// Ideally this would be done automatically (see
211/// <https://github.com/paritytech/polkadot-sdk/pull/1297>), but it probably won't be ready for some
212/// time and it's beneficial to get try-runtime-cli on-runtime-upgrade checks into the CI, so we're
213/// doing it manually.
214pub struct InitStorageVersions;
215
216impl frame_support::traits::OnRuntimeUpgrade for InitStorageVersions {
217	fn on_runtime_upgrade() -> Weight {
218		use frame_support::traits::{GetStorageVersion, StorageVersion};
219		use sp_runtime::traits::Saturating;
220
221		let mut writes = 0;
222
223		if PolkadotXcm::on_chain_storage_version() == StorageVersion::new(0) {
224			PolkadotXcm::in_code_storage_version().put::<PolkadotXcm>();
225			writes.saturating_inc();
226		}
227
228		if Balances::on_chain_storage_version() == StorageVersion::new(0) {
229			Balances::in_code_storage_version().put::<Balances>();
230			writes.saturating_inc();
231		}
232
233		<Runtime as frame_system::Config>::DbWeight::get().reads_writes(2, writes)
234	}
235}
236
237/// Executive: handles dispatch to the various modules.
238pub type Executive = frame_executive::Executive<
239	Runtime,
240	Block,
241	frame_system::ChainContext<Runtime>,
242	Runtime,
243	AllPalletsWithSystem,
244>;
245
246impl_opaque_keys! {
247	pub struct SessionKeys {
248		pub aura: Aura,
249	}
250}
251
252#[sp_version::runtime_version]
253pub const VERSION: RuntimeVersion = RuntimeVersion {
254	spec_name: alloc::borrow::Cow::Borrowed("bridge-hub-rococo"),
255	impl_name: alloc::borrow::Cow::Borrowed("bridge-hub-rococo"),
256	authoring_version: 1,
257	spec_version: 1_024_001,
258	impl_version: 0,
259	apis: RUNTIME_API_VERSIONS,
260	transaction_version: 6,
261	system_version: 1,
262};
263
264const RELAY_PARENT_OFFSET: u32 = 0;
265
266/// The version information used to identify this runtime when compiled natively.
267#[cfg(feature = "std")]
268pub fn native_version() -> NativeVersion {
269	NativeVersion { runtime_version: VERSION, can_author_with: Default::default() }
270}
271
272parameter_types! {
273	pub const Version: RuntimeVersion = VERSION;
274	pub RuntimeBlockLength: BlockLength = BlockLength::builder()
275		.max_length(5 * 1024 * 1024)
276		.modify_max_length_for_class(DispatchClass::Normal, |m| {
277			*m = NORMAL_DISPATCH_RATIO * *m
278		})
279		.build();
280	pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()
281		.base_block(BlockExecutionWeight::get())
282		.for_class(DispatchClass::all(), |weights| {
283			weights.base_extrinsic = ExtrinsicBaseWeight::get();
284		})
285		.for_class(DispatchClass::Normal, |weights| {
286			weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);
287		})
288		.for_class(DispatchClass::Operational, |weights| {
289			weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);
290			// Operational transactions have some extra reserved space, so that they
291			// are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.
292			weights.reserved = Some(
293				MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT
294			);
295		})
296		.avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)
297		.build_or_panic();
298	pub const SS58Prefix: u16 = 42;
299}
300
301// Configure FRAME pallets to include in runtime.
302
303#[derive_impl(frame_system::config_preludes::ParaChainDefaultConfig)]
304impl frame_system::Config for Runtime {
305	/// The identifier used to distinguish between accounts.
306	type AccountId = AccountId;
307	/// The index type for storing how many extrinsics an account has signed.
308	type Nonce = Nonce;
309	/// The type for hashing blocks and tries.
310	type Hash = Hash;
311	/// The block type.
312	type Block = Block;
313	/// Maximum number of block number to block hash mappings to keep (oldest pruned first).
314	type BlockHashCount = BlockHashCount;
315	/// Runtime version.
316	type Version = Version;
317	/// The data to be stored in an account.
318	type AccountData = pallet_balances::AccountData<Balance>;
319	/// The weight of database operations that the runtime can invoke.
320	type DbWeight = RocksDbWeight;
321	/// Weight information for the extrinsics of this pallet.
322	type SystemWeightInfo = weights::frame_system::WeightInfo<Runtime>;
323	/// Weight information for the extensions of this pallet.
324	type ExtensionsWeightInfo = weights::frame_system_extensions::WeightInfo<Runtime>;
325	/// Block & extrinsics weights: base values and limits.
326	type BlockWeights = RuntimeBlockWeights;
327	/// The maximum length of a block (in bytes).
328	type BlockLength = RuntimeBlockLength;
329	/// This is used as an identifier of the chain. 42 is the generic substrate prefix.
330	type SS58Prefix = SS58Prefix;
331	/// The action to take on a Runtime Upgrade
332	type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;
333	type MaxConsumers = frame_support::traits::ConstU32<16>;
334	type SingleBlockMigrations = Migrations;
335}
336
337impl cumulus_pallet_weight_reclaim::Config for Runtime {
338	type WeightInfo = weights::cumulus_pallet_weight_reclaim::WeightInfo<Runtime>;
339}
340
341impl pallet_timestamp::Config for Runtime {
342	/// A timestamp: milliseconds since the unix epoch.
343	type Moment = u64;
344	type OnTimestampSet = Aura;
345	type MinimumPeriod = ConstU64<0>;
346	type WeightInfo = weights::pallet_timestamp::WeightInfo<Runtime>;
347}
348
349impl pallet_authorship::Config for Runtime {
350	type FindAuthor = pallet_session::FindAccountFromAuthorIndex<Self, Aura>;
351	type EventHandler = (CollatorSelection,);
352}
353
354parameter_types! {
355	pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT;
356}
357
358impl pallet_balances::Config for Runtime {
359	/// The type for recording an account's balance.
360	type Balance = Balance;
361	type DustRemoval = ();
362	/// The ubiquitous event type.
363	type RuntimeEvent = RuntimeEvent;
364	type ExistentialDeposit = ExistentialDeposit;
365	type AccountStore = System;
366	type WeightInfo = weights::pallet_balances::WeightInfo<Runtime>;
367	type MaxLocks = ConstU32<50>;
368	type MaxReserves = ConstU32<50>;
369	type ReserveIdentifier = [u8; 8];
370	type RuntimeHoldReason = RuntimeHoldReason;
371	type RuntimeFreezeReason = RuntimeFreezeReason;
372	type FreezeIdentifier = ();
373	type MaxFreezes = ConstU32<0>;
374	type DoneSlashHandler = ();
375}
376
377parameter_types! {
378	/// Relay Chain `TransactionByteFee` / 10
379	pub const TransactionByteFee: Balance = MILLICENTS;
380}
381
382impl pallet_transaction_payment::Config for Runtime {
383	type RuntimeEvent = RuntimeEvent;
384	type OnChargeTransaction =
385		pallet_transaction_payment::FungibleAdapter<Balances, DealWithFees<Runtime>>;
386	type OperationalFeeMultiplier = ConstU8<5>;
387	type WeightToFee = WeightToFee;
388	type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;
389	type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Self>;
390	type WeightInfo = weights::pallet_transaction_payment::WeightInfo<Runtime>;
391}
392
393parameter_types! {
394	pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
395	pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
396}
397
398impl cumulus_pallet_parachain_system::Config for Runtime {
399	type WeightInfo = weights::cumulus_pallet_parachain_system::WeightInfo<Runtime>;
400	type RuntimeEvent = RuntimeEvent;
401	type OnSystemEvent = ();
402	type SelfParaId = parachain_info::Pallet<Runtime>;
403	type OutboundXcmpMessageSource = XcmpQueue;
404	type DmpQueue = frame_support::traits::EnqueueWithOrigin<MessageQueue, RelayOrigin>;
405	type ReservedDmpWeight = ReservedDmpWeight;
406	type XcmpMessageHandler = XcmpQueue;
407	type ReservedXcmpWeight = ReservedXcmpWeight;
408	type CheckAssociatedRelayNumber = RelayNumberMonotonicallyIncreases;
409	type ConsensusHook = ConsensusHook;
410	type RelayParentOffset = ConstU32<RELAY_PARENT_OFFSET>;
411	type SchedulingSignatureVerifier = ();
412}
413
414type ConsensusHook = cumulus_pallet_aura_ext::FixedVelocityConsensusHook<
415	Runtime,
416	RELAY_CHAIN_SLOT_DURATION_MILLIS,
417	BLOCK_PROCESSING_VELOCITY,
418	UNINCLUDED_SEGMENT_CAPACITY,
419>;
420
421impl parachain_info::Config for Runtime {}
422
423parameter_types! {
424	/// Amount of weight that can be spent per block to service messages. This was increased
425	/// from 35% to 60% of the max block weight to accommodate the Ethereum beacon light client
426	/// extrinsics. The force_checkpoint and submit extrinsics (for submit, optionally) includes
427	/// the sync committee's pubkeys (512 x 48 bytes)
428	pub MessageQueueServiceWeight: Weight = Perbill::from_percent(60) * RuntimeBlockWeights::get().max_block;
429}
430
431impl pallet_message_queue::Config for Runtime {
432	type RuntimeEvent = RuntimeEvent;
433	type WeightInfo = weights::pallet_message_queue::WeightInfo<Runtime>;
434	// Use the NoopMessageProcessor exclusively for benchmarks, not for tests with the
435	// runtime-benchmarks feature as tests require the BridgeHubMessageRouter to process messages.
436	// The "test" feature flag doesn't work, hence the reliance on the "std" feature, which is
437	// enabled during tests.
438	#[cfg(all(not(feature = "std"), feature = "runtime-benchmarks"))]
439	type MessageProcessor =
440		pallet_message_queue::mock_helpers::NoopMessageProcessor<AggregateMessageOrigin>;
441	#[cfg(not(all(not(feature = "std"), feature = "runtime-benchmarks")))]
442	type MessageProcessor = bridge_hub_common::BridgeHubMessageRouter<
443		xcm_builder::ProcessXcmMessage<
444			AggregateMessageOrigin,
445			xcm_executor::XcmExecutor<xcm_config::XcmConfig>,
446			RuntimeCall,
447		>,
448		EthereumOutboundQueue,
449	>;
450	type Size = u32;
451	// The XCMP queue pallet is only ever able to handle the `Sibling(ParaId)` origin:
452	type QueueChangeHandler = NarrowOriginToSibling<XcmpQueue>;
453	type QueuePausedQuery = NarrowOriginToSibling<XcmpQueue>;
454	type HeapSize = sp_core::ConstU32<{ 103 * 1024 }>;
455	type MaxStale = sp_core::ConstU32<8>;
456	type ServiceWeight = MessageQueueServiceWeight;
457	type IdleMaxServiceWeight = MessageQueueServiceWeight;
458}
459
460impl cumulus_pallet_aura_ext::Config for Runtime {}
461
462parameter_types! {
463	/// The asset ID for the asset that we use to pay for message delivery fees.
464	pub FeeAssetId: AssetId = AssetId(xcm_config::TokenLocation::get());
465	/// The base fee for the message delivery fees.
466	pub const BaseDeliveryFee: u128 = CENTS.saturating_mul(3);
467}
468
469pub type PriceForSiblingParachainDelivery = polkadot_runtime_common::xcm_sender::ExponentialPrice<
470	FeeAssetId,
471	BaseDeliveryFee,
472	TransactionByteFee,
473	XcmpQueue,
474>;
475
476impl cumulus_pallet_xcmp_queue::Config for Runtime {
477	type RuntimeEvent = RuntimeEvent;
478	type ChannelInfo = ParachainSystem;
479	type VersionWrapper = PolkadotXcm;
480	// Enqueue XCMP messages from siblings for later processing.
481	type XcmpQueue = TransformOrigin<MessageQueue, AggregateMessageOrigin, ParaId, ParaIdToSibling>;
482	type MaxInboundSuspended = ConstU32<1_000>;
483	type MaxActiveOutboundChannels = ConstU32<128>;
484	// Most on-chain HRMP channels are configured to use 102400 bytes of max message size, so we
485	// need to set the page size larger than that until we reduce the channel size on-chain.
486	type MaxPageSize = ConstU32<{ 103 * 1024 }>;
487	type ControllerOrigin = EnsureRoot<AccountId>;
488	type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;
489	type WeightInfo = weights::cumulus_pallet_xcmp_queue::WeightInfo<Runtime>;
490	type PriceForSiblingDelivery = PriceForSiblingParachainDelivery;
491}
492
493impl cumulus_pallet_xcmp_queue::migration::v5::V5Config for Runtime {
494	// This must be the same as the `ChannelInfo` from the `Config`:
495	type ChannelList = ParachainSystem;
496}
497
498parameter_types! {
499	pub const RelayOrigin: AggregateMessageOrigin = AggregateMessageOrigin::Parent;
500}
501
502pub const PERIOD: u32 = 6 * HOURS;
503pub const OFFSET: u32 = 0;
504
505impl pallet_session::Config for Runtime {
506	type RuntimeEvent = RuntimeEvent;
507	type ValidatorId = <Self as frame_system::Config>::AccountId;
508	// we don't have stash and controller, thus we don't need the convert as well.
509	type ValidatorIdOf = pallet_collator_selection::IdentityCollator;
510	type ShouldEndSession = pallet_session::PeriodicSessions<ConstU32<PERIOD>, ConstU32<OFFSET>>;
511	type NextSessionRotation = pallet_session::PeriodicSessions<ConstU32<PERIOD>, ConstU32<OFFSET>>;
512	type SessionManager = CollatorSelection;
513	// Essentially just Aura, but let's be pedantic.
514	type SessionHandler = <SessionKeys as sp_runtime::traits::OpaqueKeys>::KeyTypeIdProviders;
515	type Keys = SessionKeys;
516	type DisablingStrategy = ();
517	type WeightInfo = weights::pallet_session::WeightInfo<Runtime>;
518	type Currency = Balances;
519	type KeyDeposit = ();
520}
521
522impl pallet_aura::Config for Runtime {
523	type AuthorityId = AuraId;
524	type DisabledValidators = ();
525	type MaxAuthorities = ConstU32<100_000>;
526	type AllowMultipleBlocksPerSlot = ConstBool<true>;
527	type SlotDuration = ConstU64<SLOT_DURATION>;
528}
529
530parameter_types! {
531	pub const PotId: PalletId = PalletId(*b"PotStake");
532	pub const SessionLength: BlockNumber = 6 * HOURS;
533}
534
535pub type CollatorSelectionUpdateOrigin = EnsureRoot<AccountId>;
536
537impl pallet_collator_selection::Config for Runtime {
538	type RuntimeEvent = RuntimeEvent;
539	type Currency = Balances;
540	type UpdateOrigin = CollatorSelectionUpdateOrigin;
541	type PotId = PotId;
542	type MaxCandidates = ConstU32<100>;
543	type MinEligibleCollators = ConstU32<4>;
544	type MaxInvulnerables = ConstU32<20>;
545	// should be a multiple of session or things will get inconsistent
546	type KickThreshold = ConstU32<PERIOD>;
547	type ValidatorId = <Self as frame_system::Config>::AccountId;
548	type ValidatorIdOf = pallet_collator_selection::IdentityCollator;
549	type ValidatorRegistration = Session;
550	type WeightInfo = weights::pallet_collator_selection::WeightInfo<Runtime>;
551}
552
553parameter_types! {
554	// One storage item; key size is 32; value is size 4+4+16+32 bytes = 56 bytes.
555	pub const DepositBase: Balance = deposit(1, 88);
556	// Additional storage item size of 32 bytes.
557	pub const DepositFactor: Balance = deposit(0, 32);
558}
559
560impl pallet_multisig::Config for Runtime {
561	type RuntimeEvent = RuntimeEvent;
562	type RuntimeCall = RuntimeCall;
563	type Currency = Balances;
564	type DepositBase = DepositBase;
565	type DepositFactor = DepositFactor;
566	type MaxSignatories = ConstU32<100>;
567	type WeightInfo = weights::pallet_multisig::WeightInfo<Runtime>;
568	type BlockNumberProvider = frame_system::Pallet<Runtime>;
569}
570
571impl pallet_utility::Config for Runtime {
572	type RuntimeEvent = RuntimeEvent;
573	type RuntimeCall = RuntimeCall;
574	type PalletsOrigin = OriginCaller;
575	type WeightInfo = weights::pallet_utility::WeightInfo<Runtime>;
576}
577
578// Create the runtime by composing the FRAME pallets that were previously configured.
579construct_runtime!(
580	pub enum Runtime
581	{
582		// System support stuff.
583		System: frame_system = 0,
584		ParachainSystem: cumulus_pallet_parachain_system = 1,
585		Timestamp: pallet_timestamp = 2,
586		ParachainInfo: parachain_info = 3,
587		WeightReclaim: cumulus_pallet_weight_reclaim = 4,
588
589		// Monetary stuff.
590		Balances: pallet_balances = 10,
591		TransactionPayment: pallet_transaction_payment = 11,
592
593		// Collator support. The order of these 4 are important and shall not change.
594		Authorship: pallet_authorship = 20,
595		CollatorSelection: pallet_collator_selection = 21,
596		Session: pallet_session = 22,
597		Aura: pallet_aura = 23,
598		AuraExt: cumulus_pallet_aura_ext = 24,
599
600		// XCM helpers.
601		XcmpQueue: cumulus_pallet_xcmp_queue = 30,
602		PolkadotXcm: pallet_xcm = 31,
603		CumulusXcm: cumulus_pallet_xcm = 32,
604
605		// Handy utilities.
606		Utility: pallet_utility = 40,
607		Multisig: pallet_multisig = 36,
608
609		// Bridge relayers pallet, used by several bridges here.
610		BridgeRelayers: pallet_bridge_relayers = 47,
611
612		// With-Westend GRANDPA bridge module.
613		BridgeWestendGrandpa: pallet_bridge_grandpa::<Instance3> = 48,
614		// With-Westend parachain bridge module.
615		BridgeWestendParachains: pallet_bridge_parachains::<Instance3> = 49,
616		// With-Westend messaging bridge module.
617		BridgeWestendMessages: pallet_bridge_messages::<Instance3> = 51,
618		// With-Westend bridge hub pallet.
619		XcmOverBridgeHubWestend: pallet_xcm_bridge_hub::<Instance1> = 52,
620
621		// With-Rococo Bulletin GRANDPA bridge module.
622		//
623		// we can't use `BridgeRococoBulletinGrandpa` name here, because the same Bulletin runtime
624		// will be used for both Rococo and Polkadot Bulletin chains AND this name affects runtime
625		// storage keys, used by the relayer process.
626		BridgePolkadotBulletinGrandpa: pallet_bridge_grandpa::<Instance4> = 60,
627		// With-Rococo Bulletin messaging bridge module.
628		//
629		// we can't use `BridgeRococoBulletinMessages` name here, because the same Bulletin runtime
630		// will be used for both Rococo and Polkadot Bulletin chains AND this name affects runtime
631		// storage keys, used by this runtime and the relayer process.
632		BridgePolkadotBulletinMessages: pallet_bridge_messages::<Instance4> = 61,
633		// With-Rococo Bulletin bridge hub pallet.
634		XcmOverPolkadotBulletin: pallet_xcm_bridge_hub::<Instance2> = 62,
635
636		// Bridge relayers pallet, used by several bridges here (another instance).
637		BridgeRelayersForPermissionlessLanes: pallet_bridge_relayers::<Instance2> = 63,
638
639		EthereumInboundQueue: snowbridge_pallet_inbound_queue = 80,
640		EthereumOutboundQueue: snowbridge_pallet_outbound_queue = 81,
641		EthereumBeaconClient: snowbridge_pallet_ethereum_client = 82,
642		EthereumSystem: snowbridge_pallet_system = 83,
643
644		// Message Queue. Importantly, is registered last so that messages are processed after
645		// the `on_initialize` hooks of bridging pallets.
646		MessageQueue: pallet_message_queue = 175,
647	}
648);
649
650/// Proper alias for bridge GRANDPA pallet used to bridge with the bulletin chain.
651pub type BridgeRococoBulletinGrandpa = BridgePolkadotBulletinGrandpa;
652/// Proper alias for bridge messages pallet used to bridge with the bulletin chain.
653pub type BridgeRococoBulletinMessages = BridgePolkadotBulletinMessages;
654/// Proper alias for bridge messages pallet used to bridge with the bulletin chain.
655pub type XcmOverRococoBulletin = XcmOverPolkadotBulletin;
656
657bridge_runtime_common::generate_bridge_reject_obsolete_headers_and_messages! {
658	RuntimeCall, AccountId,
659	// Grandpa
660	CheckAndBoostBridgeGrandpaTransactions<
661		Runtime,
662		bridge_common_config::BridgeGrandpaWestendInstance,
663		bridge_to_westend_config::PriorityBoostPerRelayHeader,
664		xcm_config::TreasuryAccount,
665	>,
666	CheckAndBoostBridgeGrandpaTransactions<
667		Runtime,
668		bridge_common_config::BridgeGrandpaRococoBulletinInstance,
669		bridge_to_bulletin_config::PriorityBoostPerRelayHeader,
670		xcm_config::TreasuryAccount,
671	>,
672	// Parachains
673	CheckAndBoostBridgeParachainsTransactions<
674		Runtime,
675		bridge_common_config::BridgeParachainWestendInstance,
676		bp_bridge_hub_westend::BridgeHubWestend,
677		bridge_to_westend_config::PriorityBoostPerParachainHeader,
678		xcm_config::TreasuryAccount,
679	>,
680	// Messages
681	BridgeWestendMessages,
682	BridgeRococoBulletinMessages
683}
684
685#[cfg(feature = "runtime-benchmarks")]
686mod benches {
687	frame_benchmarking::define_benchmarks!(
688		[frame_system, SystemBench::<Runtime>]
689		[frame_system_extensions, SystemExtensionsBench::<Runtime>]
690		[pallet_balances, Balances]
691		[pallet_message_queue, MessageQueue]
692		[pallet_multisig, Multisig]
693		[pallet_session, SessionBench::<Runtime>]
694		[pallet_utility, Utility]
695		[pallet_timestamp, Timestamp]
696		[pallet_transaction_payment, TransactionPayment]
697		[pallet_collator_selection, CollatorSelection]
698		[cumulus_pallet_parachain_system, ParachainSystem]
699		[cumulus_pallet_xcmp_queue, XcmpQueue]
700		[cumulus_pallet_weight_reclaim, WeightReclaim]
701		// XCM
702		[pallet_xcm, PalletXcmExtrinsicsBenchmark::<Runtime>]
703		// NOTE: Make sure you point to the individual modules below.
704		[pallet_xcm_benchmarks::fungible, XcmBalances]
705		[pallet_xcm_benchmarks::generic, XcmGeneric]
706		// Bridge pallets
707		[pallet_bridge_grandpa, WestendFinality]
708		[pallet_bridge_parachains, WithinWestend]
709		[pallet_bridge_messages, RococoToWestend]
710		[pallet_bridge_messages, RococoToRococoBulletin]
711		[pallet_bridge_relayers, Legacy]
712		[pallet_bridge_relayers, PermissionlessLanes]
713		// Ethereum Bridge
714		[snowbridge_pallet_inbound_queue, EthereumInboundQueue]
715		[snowbridge_pallet_outbound_queue, EthereumOutboundQueue]
716		[snowbridge_pallet_system, EthereumSystem]
717		[snowbridge_pallet_ethereum_client, EthereumBeaconClient]
718	);
719}
720
721cumulus_pallet_parachain_system::register_validate_block! {
722	Runtime = Runtime,
723	BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,
724}
725
726impl_runtime_apis! {
727	impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {
728		fn slot_duration() -> sp_consensus_aura::SlotDuration {
729			sp_consensus_aura::SlotDuration::from_millis(SLOT_DURATION)
730		}
731
732		fn authorities() -> Vec<AuraId> {
733			pallet_aura::Authorities::<Runtime>::get().into_inner()
734		}
735	}
736
737	impl cumulus_primitives_core::RelayParentOffsetApi<Block> for Runtime {
738		fn relay_parent_offset() -> u32 {
739			RELAY_PARENT_OFFSET
740		}
741
742		fn max_claim_queue_offset() -> u8 {
743			cumulus_pallet_parachain_system::Pallet::<Runtime>::max_claim_queue_offset()
744		}
745	}
746
747	impl cumulus_primitives_core::SchedulingV3EnabledApi<Block> for Runtime {
748		fn scheduling_v3_enabled() -> bool {
749			<Runtime as cumulus_pallet_parachain_system::Config>::SchedulingSignatureVerifier::V3_SCHEDULING_ENABLED
750		}
751	}
752
753	impl cumulus_primitives_aura::AuraUnincludedSegmentApi<Block> for Runtime {
754		fn can_build_upon(
755			included_hash: <Block as BlockT>::Hash,
756			slot: cumulus_primitives_aura::Slot,
757		) -> bool {
758			ConsensusHook::can_build_upon(included_hash, slot)
759		}
760	}
761
762	impl sp_api::Core<Block> for Runtime {
763		fn version() -> RuntimeVersion {
764			VERSION
765		}
766
767		fn execute_block(block: <Block as BlockT>::LazyBlock) {
768			Executive::execute_block(block)
769		}
770
771		fn initialize_block(header: &<Block as BlockT>::Header) -> sp_runtime::ExtrinsicInclusionMode {
772			Executive::initialize_block(header)
773		}
774	}
775
776	impl sp_api::Metadata<Block> for Runtime {
777		fn metadata() -> OpaqueMetadata {
778			OpaqueMetadata::new(Runtime::metadata().into())
779		}
780
781		fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
782			Runtime::metadata_at_version(version)
783		}
784
785		fn metadata_versions() -> alloc::vec::Vec<u32> {
786			Runtime::metadata_versions()
787		}
788	}
789
790	impl sp_block_builder::BlockBuilder<Block> for Runtime {
791		fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
792			Executive::apply_extrinsic(extrinsic)
793		}
794
795		fn finalize_block() -> <Block as BlockT>::Header {
796			Executive::finalize_block()
797		}
798
799		fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
800			data.create_extrinsics()
801		}
802
803		fn check_inherents(
804			block: <Block as BlockT>::LazyBlock,
805			data: sp_inherents::InherentData,
806		) -> sp_inherents::CheckInherentsResult {
807			data.check_extrinsics(&block)
808		}
809	}
810
811	impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
812		fn validate_transaction(
813			source: TransactionSource,
814			tx: <Block as BlockT>::Extrinsic,
815			block_hash: <Block as BlockT>::Hash,
816		) -> TransactionValidity {
817			Executive::validate_transaction(source, tx, block_hash)
818		}
819	}
820
821	impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
822		fn offchain_worker(header: &<Block as BlockT>::Header) {
823			Executive::offchain_worker(header)
824		}
825	}
826
827	impl sp_session::SessionKeys<Block> for Runtime {
828		fn generate_session_keys(owner: Vec<u8>, seed: Option<Vec<u8>>) -> sp_session::OpaqueGeneratedSessionKeys {
829			SessionKeys::generate(&owner, seed).into()
830		}
831
832		fn decode_session_keys(
833			encoded: Vec<u8>,
834		) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {
835			SessionKeys::decode_into_raw_public_keys(&encoded)
836		}
837	}
838
839	impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Nonce> for Runtime {
840		fn account_nonce(account: AccountId) -> Nonce {
841			System::account_nonce(account)
842		}
843	}
844
845	impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {
846		fn query_info(
847			uxt: <Block as BlockT>::Extrinsic,
848			len: u32,
849		) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo<Balance> {
850			TransactionPayment::query_info(uxt, len)
851		}
852		fn query_fee_details(
853			uxt: <Block as BlockT>::Extrinsic,
854			len: u32,
855		) -> pallet_transaction_payment::FeeDetails<Balance> {
856			TransactionPayment::query_fee_details(uxt, len)
857		}
858		fn query_weight_to_fee(weight: Weight) -> Balance {
859			TransactionPayment::weight_to_fee(weight)
860		}
861		fn query_length_to_fee(length: u32) -> Balance {
862			TransactionPayment::length_to_fee(length)
863		}
864	}
865
866	impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentCallApi<Block, Balance, RuntimeCall>
867		for Runtime
868	{
869		fn query_call_info(
870			call: RuntimeCall,
871			len: u32,
872		) -> pallet_transaction_payment::RuntimeDispatchInfo<Balance> {
873			TransactionPayment::query_call_info(call, len)
874		}
875		fn query_call_fee_details(
876			call: RuntimeCall,
877			len: u32,
878		) -> pallet_transaction_payment::FeeDetails<Balance> {
879			TransactionPayment::query_call_fee_details(call, len)
880		}
881		fn query_weight_to_fee(weight: Weight) -> Balance {
882			TransactionPayment::weight_to_fee(weight)
883		}
884		fn query_length_to_fee(length: u32) -> Balance {
885			TransactionPayment::length_to_fee(length)
886		}
887	}
888
889	impl xcm_runtime_apis::fees::XcmPaymentApi<Block> for Runtime {
890		fn query_acceptable_payment_assets(xcm_version: xcm::Version) -> Result<Vec<VersionedAssetId>, XcmPaymentApiError> {
891			let acceptable_assets = vec![AssetId(xcm_config::TokenLocation::get())];
892			PolkadotXcm::query_acceptable_payment_assets(xcm_version, acceptable_assets)
893		}
894
895		fn query_weight_to_asset_fee(weight: Weight, asset: VersionedAssetId) -> Result<u128, XcmPaymentApiError> {
896			type Trader = <XcmConfig as xcm_executor::Config>::Trader;
897			PolkadotXcm::query_weight_to_asset_fee::<Trader>(weight, asset)
898		}
899
900		fn query_xcm_weight(message: VersionedXcm<()>) -> Result<Weight, XcmPaymentApiError> {
901			PolkadotXcm::query_xcm_weight(message)
902		}
903
904		fn query_delivery_fees(destination: VersionedLocation, message: VersionedXcm<()>, asset_id: VersionedAssetId) -> Result<VersionedAssets, XcmPaymentApiError> {
905			type AssetExchanger = <XcmConfig as xcm_executor::Config>::AssetExchanger;
906			PolkadotXcm::query_delivery_fees::<AssetExchanger>(destination, message, asset_id)
907		}
908	}
909
910	impl xcm_runtime_apis::dry_run::DryRunApi<Block, RuntimeCall, RuntimeEvent, OriginCaller> for Runtime {
911		fn dry_run_call(origin: OriginCaller, call: RuntimeCall, result_xcms_version: XcmVersion) -> Result<CallDryRunEffects<RuntimeEvent>, XcmDryRunApiError> {
912			PolkadotXcm::dry_run_call::<Runtime, xcm_config::XcmRouter, OriginCaller, RuntimeCall>(origin, call, result_xcms_version)
913		}
914
915		fn dry_run_xcm(origin_location: VersionedLocation, xcm: VersionedXcm<RuntimeCall>) -> Result<XcmDryRunEffects<RuntimeEvent>, XcmDryRunApiError> {
916			PolkadotXcm::dry_run_xcm::<xcm_config::XcmRouter>(origin_location, xcm)
917		}
918	}
919
920	impl xcm_runtime_apis::conversions::LocationToAccountApi<Block, AccountId> for Runtime {
921		fn convert_location(location: VersionedLocation) -> Result<
922			AccountId,
923			xcm_runtime_apis::conversions::Error
924		> {
925			xcm_runtime_apis::conversions::LocationToAccountHelper::<
926				AccountId,
927				xcm_config::LocationToAccountId,
928			>::convert_location(location)
929		}
930	}
931
932	impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {
933		fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {
934			ParachainSystem::collect_collation_info(header)
935		}
936	}
937
938	impl bp_westend::WestendFinalityApi<Block> for Runtime {
939		fn best_finalized() -> Option<HeaderId<bp_westend::Hash, bp_westend::BlockNumber>> {
940			BridgeWestendGrandpa::best_finalized()
941		}
942		fn free_headers_interval() -> Option<bp_westend::BlockNumber> {
943			<Runtime as pallet_bridge_grandpa::Config<
944				bridge_common_config::BridgeGrandpaWestendInstance
945			>>::FreeHeadersInterval::get()
946		}
947		fn synced_headers_grandpa_info(
948		) -> Vec<bp_header_chain::StoredHeaderGrandpaInfo<bp_westend::Header>> {
949			BridgeWestendGrandpa::synced_headers_grandpa_info()
950		}
951	}
952
953	impl bp_bridge_hub_westend::BridgeHubWestendFinalityApi<Block> for Runtime {
954		fn best_finalized() -> Option<HeaderId<Hash, BlockNumber>> {
955			BridgeWestendParachains::best_parachain_head_id::<
956				bp_bridge_hub_westend::BridgeHubWestend
957			>().unwrap_or(None)
958		}
959		fn free_headers_interval() -> Option<bp_bridge_hub_westend::BlockNumber> {
960			// "free interval" is not currently used for parachains
961			None
962		}
963	}
964
965	// This is exposed by BridgeHubRococo
966	impl bp_bridge_hub_westend::FromBridgeHubWestendInboundLaneApi<Block> for Runtime {
967		fn message_details(
968			lane: LaneIdOf<Runtime, bridge_to_westend_config::WithBridgeHubWestendMessagesInstance>,
969			messages: Vec<(bp_messages::MessagePayload, bp_messages::OutboundMessageDetails)>,
970		) -> Vec<bp_messages::InboundMessageDetails> {
971			bridge_runtime_common::messages_api::inbound_message_details::<
972				Runtime,
973				bridge_to_westend_config::WithBridgeHubWestendMessagesInstance,
974			>(lane, messages)
975		}
976	}
977
978	// This is exposed by BridgeHubRococo
979	impl bp_bridge_hub_westend::ToBridgeHubWestendOutboundLaneApi<Block> for Runtime {
980		fn message_details(
981			lane: LaneIdOf<Runtime, bridge_to_westend_config::WithBridgeHubWestendMessagesInstance>,
982			begin: bp_messages::MessageNonce,
983			end: bp_messages::MessageNonce,
984		) -> Vec<bp_messages::OutboundMessageDetails> {
985			bridge_runtime_common::messages_api::outbound_message_details::<
986				Runtime,
987				bridge_to_westend_config::WithBridgeHubWestendMessagesInstance,
988			>(lane, begin, end)
989		}
990	}
991
992	impl bp_polkadot_bulletin::PolkadotBulletinFinalityApi<Block> for Runtime {
993		fn best_finalized() -> Option<bp_runtime::HeaderId<bp_polkadot_bulletin::Hash, bp_polkadot_bulletin::BlockNumber>> {
994			BridgePolkadotBulletinGrandpa::best_finalized()
995		}
996
997		fn free_headers_interval() -> Option<bp_polkadot_bulletin::BlockNumber> {
998			<Runtime as pallet_bridge_grandpa::Config<
999				bridge_common_config::BridgeGrandpaRococoBulletinInstance
1000			>>::FreeHeadersInterval::get()
1001		}
1002
1003		fn synced_headers_grandpa_info(
1004		) -> Vec<bp_header_chain::StoredHeaderGrandpaInfo<bp_polkadot_bulletin::Header>> {
1005			BridgePolkadotBulletinGrandpa::synced_headers_grandpa_info()
1006		}
1007	}
1008
1009	impl bp_polkadot_bulletin::FromPolkadotBulletinInboundLaneApi<Block> for Runtime {
1010		fn message_details(
1011			lane: LaneIdOf<Runtime, bridge_to_bulletin_config::WithRococoBulletinMessagesInstance>,
1012			messages: Vec<(bp_messages::MessagePayload, bp_messages::OutboundMessageDetails)>,
1013		) -> Vec<bp_messages::InboundMessageDetails> {
1014			bridge_runtime_common::messages_api::inbound_message_details::<
1015				Runtime,
1016				bridge_to_bulletin_config::WithRococoBulletinMessagesInstance,
1017			>(lane, messages)
1018		}
1019	}
1020
1021	impl bp_polkadot_bulletin::ToPolkadotBulletinOutboundLaneApi<Block> for Runtime {
1022		fn message_details(
1023			lane: LaneIdOf<Runtime, bridge_to_bulletin_config::WithRococoBulletinMessagesInstance>,
1024			begin: bp_messages::MessageNonce,
1025			end: bp_messages::MessageNonce,
1026		) -> Vec<bp_messages::OutboundMessageDetails> {
1027			bridge_runtime_common::messages_api::outbound_message_details::<
1028				Runtime,
1029				bridge_to_bulletin_config::WithRococoBulletinMessagesInstance,
1030			>(lane, begin, end)
1031		}
1032	}
1033
1034	impl snowbridge_outbound_queue_runtime_api::OutboundQueueApi<Block, Balance> for Runtime {
1035		fn prove_message(leaf_index: u64) -> Option<snowbridge_merkle_tree::MerkleProof> {
1036			snowbridge_pallet_outbound_queue::api::prove_message::<Runtime>(leaf_index)
1037		}
1038
1039		fn calculate_fee(command: Command, parameters: Option<PricingParameters<Balance>>) -> Fee<Balance> {
1040			snowbridge_pallet_outbound_queue::api::calculate_fee::<Runtime>(command, parameters)
1041		}
1042	}
1043
1044	impl snowbridge_system_runtime_api::ControlApi<Block> for Runtime {
1045		fn agent_id(location: VersionedLocation) -> Option<AgentId> {
1046			snowbridge_pallet_system::api::agent_id::<Runtime>(location)
1047		}
1048	}
1049
1050	#[cfg(feature = "try-runtime")]
1051	impl frame_try_runtime::TryRuntime<Block> for Runtime {
1052		fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) {
1053			let weight = Executive::try_runtime_upgrade(checks).unwrap();
1054			(weight, RuntimeBlockWeights::get().max_block)
1055		}
1056
1057		fn execute_block(
1058			block: <Block as BlockT>::LazyBlock,
1059			state_root_check: bool,
1060			signature_check: bool,
1061			select: frame_try_runtime::TryStateSelect,
1062		) -> Weight {
1063			// NOTE: intentional unwrap: we don't want to propagate the error backwards, and want to
1064			// have a backtrace here.
1065			Executive::try_execute_block(block, state_root_check, signature_check, select).unwrap()
1066		}
1067	}
1068
1069	#[cfg(feature = "runtime-benchmarks")]
1070	impl frame_benchmarking::Benchmark<Block> for Runtime {
1071		fn benchmark_metadata(extra: bool) -> (
1072			Vec<frame_benchmarking::BenchmarkList>,
1073			Vec<frame_support::traits::StorageInfo>,
1074		) {
1075			use frame_benchmarking::BenchmarkList;
1076			use frame_support::traits::StorageInfoTrait;
1077			use frame_system_benchmarking::Pallet as SystemBench;
1078			use frame_system_benchmarking::extensions::Pallet as SystemExtensionsBench;
1079			use cumulus_pallet_session_benchmarking::Pallet as SessionBench;
1080			use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
1081
1082			// This is defined once again in dispatch_benchmark, because list_benchmarks!
1083			// and add_benchmarks! are macros exported by define_benchmarks! macros and those types
1084			// are referenced in that call.
1085			type XcmBalances = pallet_xcm_benchmarks::fungible::Pallet::<Runtime>;
1086			type XcmGeneric = pallet_xcm_benchmarks::generic::Pallet::<Runtime>;
1087
1088			use pallet_bridge_relayers::benchmarking::Pallet as BridgeRelayersBench;
1089			// Change weight file names.
1090			type WestendFinality = BridgeWestendGrandpa;
1091			type WithinWestend = pallet_bridge_parachains::benchmarking::Pallet::<Runtime, bridge_common_config::BridgeParachainWestendInstance>;
1092			type RococoToWestend = pallet_bridge_messages::benchmarking::Pallet ::<Runtime, bridge_to_westend_config::WithBridgeHubWestendMessagesInstance>;
1093			type RococoToRococoBulletin = pallet_bridge_messages::benchmarking::Pallet ::<Runtime, bridge_to_bulletin_config::WithRococoBulletinMessagesInstance>;
1094			type Legacy = BridgeRelayersBench::<Runtime, bridge_common_config::RelayersForLegacyLaneIdsMessagesInstance>;
1095			type PermissionlessLanes = BridgeRelayersBench::<Runtime, bridge_common_config::RelayersForPermissionlessLanesInstance>;
1096
1097			let mut list = Vec::<BenchmarkList>::new();
1098			list_benchmarks!(list, extra);
1099
1100			let storage_info = AllPalletsWithSystem::storage_info();
1101			(list, storage_info)
1102		}
1103
1104		#[allow(non_local_definitions)]
1105		fn dispatch_benchmark(
1106			config: frame_benchmarking::BenchmarkConfig
1107		) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, alloc::string::String> {
1108			use frame_benchmarking::{BenchmarkBatch, BenchmarkError};
1109			use sp_storage::TrackedStorageKey;
1110			use codec::Encode;
1111
1112			use frame_system_benchmarking::Pallet as SystemBench;
1113			use frame_system_benchmarking::extensions::Pallet as SystemExtensionsBench;
1114			impl frame_system_benchmarking::Config for Runtime {
1115				fn setup_set_code_requirements(code: &alloc::vec::Vec<u8>) -> Result<(), BenchmarkError> {
1116					ParachainSystem::initialize_for_set_code_benchmark(code.len() as u32);
1117					Ok(())
1118				}
1119
1120				fn verify_set_code() {
1121					System::assert_last_event(cumulus_pallet_parachain_system::Event::<Runtime>::ValidationFunctionStored.into());
1122				}
1123			}
1124
1125			use cumulus_pallet_session_benchmarking::Pallet as SessionBench;
1126			impl cumulus_pallet_session_benchmarking::Config for Runtime {
1127				fn generate_session_keys_and_proof(owner: Self::AccountId) -> (Self::Keys, Vec<u8>) {
1128					let keys = SessionKeys::generate(&owner.encode(), None);
1129					(keys.keys, keys.proof.encode())
1130				}
1131			}
1132
1133			impl pallet_transaction_payment::BenchmarkConfig for Runtime {}
1134
1135			use xcm::latest::prelude::*;
1136			use xcm_config::TokenLocation;
1137			use testnet_parachains_constants::rococo::locations::{AssetHubParaId, AssetHubLocation};
1138			parameter_types! {
1139				pub ExistentialDepositAsset: Option<Asset> = Some((
1140					TokenLocation::get(),
1141					ExistentialDeposit::get()
1142				).into());
1143			}
1144
1145			use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
1146			impl pallet_xcm::benchmarking::Config for Runtime {
1147				type DeliveryHelper = polkadot_runtime_common::xcm_sender::ToParachainDeliveryHelper<
1148						xcm_config::XcmConfig,
1149						ExistentialDepositAsset,
1150						PriceForSiblingParachainDelivery,
1151						AssetHubParaId,
1152						ParachainSystem,
1153					>;
1154
1155				fn reachable_dest() -> Option<Location> {
1156					Some(AssetHubLocation::get())
1157				}
1158
1159				fn teleportable_asset_and_dest() -> Option<(Asset, Location)> {
1160					// Relay/native token can be teleported between BH and Relay.
1161					Some((
1162						Asset {
1163							fun: Fungible(ExistentialDeposit::get()),
1164							id: AssetId(TokenLocation::get())
1165						},
1166						AssetHubLocation::get(),
1167					))
1168				}
1169
1170				fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> {
1171					// Reserve transfers are disabled on BH.
1172					None
1173				}
1174
1175				fn set_up_complex_asset_transfer(
1176				) -> Option<(Assets, u32, Location, Box<dyn FnOnce()>)> {
1177					// BH only supports teleports to system parachain.
1178					// Relay/native token can be teleported between BH and Relay.
1179					let native_location = TokenLocation::get();
1180					let dest = AssetHubLocation::get();
1181					pallet_xcm::benchmarking::helpers::native_teleport_as_asset_transfer::<Runtime>(
1182						native_location,
1183						dest
1184					)
1185				}
1186
1187				fn get_asset() -> Asset {
1188					Asset {
1189						id: AssetId(Location::parent()),
1190						fun: Fungible(ExistentialDeposit::get()),
1191					}
1192				}
1193			}
1194
1195			impl pallet_xcm_benchmarks::Config for Runtime {
1196				type XcmConfig = xcm_config::XcmConfig;
1197				type AccountIdConverter = xcm_config::LocationToAccountId;
1198				type DeliveryHelper = polkadot_runtime_common::xcm_sender::ToParachainDeliveryHelper<
1199						xcm_config::XcmConfig,
1200						ExistentialDepositAsset,
1201						PriceForSiblingParachainDelivery,
1202						AssetHubParaId,
1203						ParachainSystem,
1204					>;
1205				fn valid_destination() -> Result<Location, BenchmarkError> {
1206					Ok(AssetHubLocation::get())
1207				}
1208				fn worst_case_holding(_depositable_count: u32) -> xcm_executor::AssetsInHolding {
1209					use pallet_xcm_benchmarks::MockCredit;
1210					// just concrete assets according to relay chain.
1211					let mut holding = xcm_executor::AssetsInHolding::new();
1212					holding.fungible.insert(
1213						AssetId(TokenLocation::get()),
1214						alloc::boxed::Box::new(MockCredit(1_000_000 * UNITS)),
1215					);
1216					holding
1217				}
1218			}
1219
1220			parameter_types! {
1221				pub TrustedTeleporter: Option<(Location, Asset)> = Some((
1222					AssetHubLocation::get(),
1223					Asset { fun: Fungible(UNITS), id: AssetId(TokenLocation::get()) },
1224				));
1225				pub const CheckedAccount: Option<(AccountId, xcm_builder::MintLocation)> = None;
1226				pub const TrustedReserve: Option<(Location, Asset)> = None;
1227			}
1228
1229			impl pallet_xcm_benchmarks::fungible::Config for Runtime {
1230				type TransactAsset = Balances;
1231
1232				type CheckedAccount = CheckedAccount;
1233				type TrustedTeleporter = TrustedTeleporter;
1234				type TrustedReserve = TrustedReserve;
1235
1236				fn get_asset() -> Asset {
1237					Asset {
1238						id: AssetId(TokenLocation::get()),
1239						fun: Fungible(UNITS),
1240					}
1241				}
1242			}
1243
1244			impl pallet_xcm_benchmarks::generic::Config for Runtime {
1245				type TransactAsset = Balances;
1246				type RuntimeCall = RuntimeCall;
1247
1248				fn worst_case_response() -> (u64, Response) {
1249					(0u64, Response::Version(Default::default()))
1250				}
1251
1252				fn worst_case_asset_exchange() -> Result<(Assets, Assets), BenchmarkError> {
1253					Err(BenchmarkError::Skip)
1254				}
1255
1256				fn universal_alias() -> Result<(Location, Junction), BenchmarkError> {
1257					Err(BenchmarkError::Skip)
1258				}
1259
1260				fn transact_origin_and_runtime_call() -> Result<(Location, RuntimeCall), BenchmarkError> {
1261					Ok((AssetHubLocation::get(), frame_system::Call::remark_with_event { remark: vec![] }.into()))
1262				}
1263
1264				fn subscribe_origin() -> Result<Location, BenchmarkError> {
1265					Ok(AssetHubLocation::get())
1266				}
1267
1268				fn claimable_asset() -> Result<(Location, Location, Assets), BenchmarkError> {
1269					let origin = AssetHubLocation::get();
1270					let assets: Assets = (AssetId(TokenLocation::get()), 1_000 * UNITS).into();
1271					let ticket = Location { parents: 0, interior: Here };
1272					Ok((origin, ticket, assets))
1273				}
1274
1275				fn worst_case_for_trader() -> Result<(Asset, WeightLimit), BenchmarkError> {
1276					Ok((Asset {
1277						id: AssetId(TokenLocation::get()),
1278						fun: Fungible(1_000_000 * UNITS),
1279					}, WeightLimit::Limited(Weight::from_parts(5000, 5000))))
1280				}
1281
1282				fn unlockable_asset() -> Result<(Location, Location, Asset), BenchmarkError> {
1283					Err(BenchmarkError::Skip)
1284				}
1285
1286				fn export_message_origin_and_destination(
1287				) -> Result<(Location, NetworkId, InteriorLocation), BenchmarkError> {
1288					// save XCM version for remote bridge hub
1289					let _ = PolkadotXcm::force_xcm_version(
1290						RuntimeOrigin::root(),
1291						Box::new(bridge_to_westend_config::BridgeHubWestendLocation::get()),
1292						XCM_VERSION,
1293					).map_err(|e| {
1294						tracing::error!(
1295							target: "bridges::benchmark",
1296							error=?e,
1297							origin=?RuntimeOrigin::root(),
1298							location=?bridge_to_westend_config::BridgeHubWestendLocation::get(),
1299							version=?XCM_VERSION,
1300							"Failed to dispatch `force_xcm_version`"
1301						);
1302						BenchmarkError::Stop("XcmVersion was not stored!")
1303					})?;
1304
1305					let sibling_parachain_location = Location::new(1, [Parachain(5678)]);
1306
1307					// fund SA
1308					use frame_support::traits::fungible::Mutate;
1309					use xcm_executor::traits::ConvertLocation;
1310					frame_support::assert_ok!(
1311						Balances::mint_into(
1312							&xcm_config::LocationToAccountId::convert_location(&sibling_parachain_location).expect("valid AccountId"),
1313							bridge_to_westend_config::BridgeDeposit::get()
1314								.saturating_add(ExistentialDeposit::get())
1315								.saturating_add(UNITS * 5)
1316						)
1317					);
1318
1319					// open bridge
1320					let bridge_destination_universal_location: InteriorLocation = [GlobalConsensus(NetworkId::ByGenesis(WESTEND_GENESIS_HASH)), Parachain(8765)].into();
1321					let locations = XcmOverBridgeHubWestend::bridge_locations(
1322						sibling_parachain_location.clone(),
1323						bridge_destination_universal_location.clone(),
1324					)?;
1325					XcmOverBridgeHubWestend::do_open_bridge(
1326						locations,
1327						bp_messages::LegacyLaneId([1, 2, 3, 4]),
1328						true,
1329					).map_err(|e| {
1330						tracing::error!(
1331							target: "bridges::benchmark",
1332							error=?e,
1333							locations=?sibling_parachain_location,
1334							lane_id=?bridge_destination_universal_location,
1335							"Failed to `XcmOverBridgeHubWestend::open_bridge`"
1336						);
1337						BenchmarkError::Stop("Bridge was not opened!")
1338					})?;
1339
1340					Ok(
1341						(
1342							sibling_parachain_location,
1343							NetworkId::ByGenesis(WESTEND_GENESIS_HASH),
1344							[Parachain(8765)].into()
1345						)
1346					)
1347				}
1348
1349				fn alias_origin() -> Result<(Location, Location), BenchmarkError> {
1350					Err(BenchmarkError::Skip)
1351				}
1352			}
1353
1354			type XcmBalances = pallet_xcm_benchmarks::fungible::Pallet::<Runtime>;
1355			type XcmGeneric = pallet_xcm_benchmarks::generic::Pallet::<Runtime>;
1356
1357			type WestendFinality = BridgeWestendGrandpa;
1358			type WithinWestend = pallet_bridge_parachains::benchmarking::Pallet::<Runtime, bridge_common_config::BridgeParachainWestendInstance>;
1359			type RococoToWestend = pallet_bridge_messages::benchmarking::Pallet ::<Runtime, bridge_to_westend_config::WithBridgeHubWestendMessagesInstance>;
1360			type RococoToRococoBulletin = pallet_bridge_messages::benchmarking::Pallet ::<Runtime, bridge_to_bulletin_config::WithRococoBulletinMessagesInstance>;
1361			type Legacy = BridgeRelayersBench::<Runtime, bridge_common_config::RelayersForLegacyLaneIdsMessagesInstance>;
1362			type PermissionlessLanes = BridgeRelayersBench::<Runtime, bridge_common_config::RelayersForPermissionlessLanesInstance>;
1363
1364			use bridge_runtime_common::messages_benchmarking::{
1365				prepare_message_delivery_proof_from_grandpa_chain,
1366				prepare_message_delivery_proof_from_parachain,
1367				prepare_message_proof_from_grandpa_chain,
1368				prepare_message_proof_from_parachain,
1369				generate_xcm_builder_bridge_message_sample,
1370			};
1371			use pallet_bridge_messages::benchmarking::{
1372				Config as BridgeMessagesConfig,
1373				MessageDeliveryProofParams,
1374				MessageProofParams,
1375			};
1376
1377			impl BridgeMessagesConfig<bridge_to_westend_config::WithBridgeHubWestendMessagesInstance> for Runtime {
1378				fn is_relayer_rewarded(relayer: &Self::AccountId) -> bool {
1379					let bench_lane_id = <Self as BridgeMessagesConfig<bridge_to_westend_config::WithBridgeHubWestendMessagesInstance>>::bench_lane_id();
1380					use bp_runtime::Chain;
1381					let bridged_chain_id =<Self as pallet_bridge_messages::Config<bridge_to_westend_config::WithBridgeHubWestendMessagesInstance>>::BridgedChain::ID;
1382					pallet_bridge_relayers::Pallet::<Runtime, bridge_common_config::RelayersForLegacyLaneIdsMessagesInstance>::relayer_reward(
1383						relayer,
1384						bp_relayers::RewardsAccountParams::new(
1385							bench_lane_id,
1386							bridged_chain_id,
1387							bp_relayers::RewardsAccountOwner::BridgedChain
1388						)
1389					).is_some()
1390				}
1391
1392				fn prepare_message_proof(
1393					params: MessageProofParams<LaneIdOf<Runtime, bridge_to_westend_config::WithBridgeHubWestendMessagesInstance>>,
1394				) -> (bridge_to_westend_config::FromWestendBridgeHubMessagesProof<bridge_to_westend_config::WithBridgeHubWestendMessagesInstance>, Weight) {
1395					use cumulus_primitives_core::XcmpMessageSource;
1396					assert!(XcmpQueue::take_outbound_messages(usize::MAX, &[]).is_empty());
1397					ParachainSystem::open_outbound_hrmp_channel_for_benchmarks_or_tests(42.into());
1398					let universal_source = bridge_to_westend_config::open_bridge_for_benchmarks::<
1399						Runtime,
1400						bridge_to_westend_config::XcmOverBridgeHubWestendInstance,
1401						xcm_config::LocationToAccountId,
1402					>(params.lane, 42);
1403					prepare_message_proof_from_parachain::<
1404						Runtime,
1405						bridge_common_config::BridgeGrandpaWestendInstance,
1406						bridge_to_westend_config::WithBridgeHubWestendMessagesInstance,
1407					>(params, generate_xcm_builder_bridge_message_sample(universal_source))
1408				}
1409
1410				fn prepare_message_delivery_proof(
1411					params: MessageDeliveryProofParams<AccountId, LaneIdOf<Runtime, bridge_to_westend_config::WithBridgeHubWestendMessagesInstance>>,
1412				) -> bridge_to_westend_config::ToWestendBridgeHubMessagesDeliveryProof<bridge_to_westend_config::WithBridgeHubWestendMessagesInstance> {
1413					let _ = bridge_to_westend_config::open_bridge_for_benchmarks::<
1414						Runtime,
1415						bridge_to_westend_config::XcmOverBridgeHubWestendInstance,
1416						xcm_config::LocationToAccountId,
1417					>(params.lane, 42);
1418					prepare_message_delivery_proof_from_parachain::<
1419						Runtime,
1420						bridge_common_config::BridgeGrandpaWestendInstance,
1421						bridge_to_westend_config::WithBridgeHubWestendMessagesInstance,
1422					>(params)
1423				}
1424
1425				fn is_message_successfully_dispatched(_nonce: bp_messages::MessageNonce) -> bool {
1426					use cumulus_primitives_core::XcmpMessageSource;
1427					!XcmpQueue::take_outbound_messages(usize::MAX, &[]).is_empty()
1428				}
1429			}
1430
1431			impl BridgeMessagesConfig<bridge_to_bulletin_config::WithRococoBulletinMessagesInstance> for Runtime {
1432				fn is_relayer_rewarded(_relayer: &Self::AccountId) -> bool {
1433					// we do not pay any rewards in this bridge
1434					true
1435				}
1436
1437				fn prepare_message_proof(
1438					params: MessageProofParams<LaneIdOf<Runtime, bridge_to_bulletin_config::WithRococoBulletinMessagesInstance>>,
1439				) -> (bridge_to_bulletin_config::FromRococoBulletinMessagesProof<bridge_to_bulletin_config::WithRococoBulletinMessagesInstance>, Weight) {
1440					use cumulus_primitives_core::XcmpMessageSource;
1441					assert!(XcmpQueue::take_outbound_messages(usize::MAX, &[]).is_empty());
1442					ParachainSystem::open_outbound_hrmp_channel_for_benchmarks_or_tests(42.into());
1443					let universal_source = bridge_to_bulletin_config::open_bridge_for_benchmarks::<
1444						Runtime,
1445						bridge_to_bulletin_config::XcmOverPolkadotBulletinInstance,
1446						xcm_config::LocationToAccountId,
1447					>(params.lane, 42);
1448					prepare_message_proof_from_grandpa_chain::<
1449						Runtime,
1450						bridge_common_config::BridgeGrandpaRococoBulletinInstance,
1451						bridge_to_bulletin_config::WithRococoBulletinMessagesInstance,
1452					>(params, generate_xcm_builder_bridge_message_sample(universal_source))
1453				}
1454
1455				fn prepare_message_delivery_proof(
1456					params: MessageDeliveryProofParams<AccountId, LaneIdOf<Runtime, bridge_to_bulletin_config::WithRococoBulletinMessagesInstance>>,
1457				) -> bridge_to_bulletin_config::ToRococoBulletinMessagesDeliveryProof<bridge_to_bulletin_config::WithRococoBulletinMessagesInstance> {
1458					let _ = bridge_to_bulletin_config::open_bridge_for_benchmarks::<
1459						Runtime,
1460						bridge_to_bulletin_config::XcmOverPolkadotBulletinInstance,
1461						xcm_config::LocationToAccountId,
1462					>(params.lane, 42);
1463					prepare_message_delivery_proof_from_grandpa_chain::<
1464						Runtime,
1465						bridge_common_config::BridgeGrandpaRococoBulletinInstance,
1466						bridge_to_bulletin_config::WithRococoBulletinMessagesInstance,
1467					>(params)
1468				}
1469
1470				fn is_message_successfully_dispatched(_nonce: bp_messages::MessageNonce) -> bool {
1471					use cumulus_primitives_core::XcmpMessageSource;
1472					!XcmpQueue::take_outbound_messages(usize::MAX, &[]).is_empty()
1473				}
1474			}
1475
1476			use bridge_runtime_common::parachains_benchmarking::prepare_parachain_heads_proof;
1477			use pallet_bridge_parachains::benchmarking::Config as BridgeParachainsConfig;
1478			use pallet_bridge_relayers::benchmarking::{
1479				Pallet as BridgeRelayersBench,
1480				Config as BridgeRelayersConfig,
1481			};
1482
1483			impl BridgeParachainsConfig<bridge_common_config::BridgeParachainWestendInstance> for Runtime {
1484				fn parachains() -> Vec<bp_polkadot_core::parachains::ParaId> {
1485					use bp_runtime::Parachain;
1486					vec![bp_polkadot_core::parachains::ParaId(bp_bridge_hub_westend::BridgeHubWestend::PARACHAIN_ID)]
1487				}
1488
1489				fn prepare_parachain_heads_proof(
1490					parachains: &[bp_polkadot_core::parachains::ParaId],
1491					parachain_head_size: u32,
1492					proof_params: bp_runtime::UnverifiedStorageProofParams,
1493				) -> (
1494					bp_parachains::RelayBlockNumber,
1495					bp_parachains::RelayBlockHash,
1496					bp_polkadot_core::parachains::ParaHeadsProof,
1497					Vec<(bp_polkadot_core::parachains::ParaId, bp_polkadot_core::parachains::ParaHash)>,
1498				) {
1499					prepare_parachain_heads_proof::<Runtime, bridge_common_config::BridgeParachainWestendInstance>(
1500						parachains,
1501						parachain_head_size,
1502						proof_params,
1503					)
1504				}
1505			}
1506
1507			impl BridgeRelayersConfig<bridge_common_config::RelayersForLegacyLaneIdsMessagesInstance> for Runtime {
1508				fn bench_reward() -> Self::Reward {
1509					bp_relayers::RewardsAccountParams::new(
1510						bp_messages::LegacyLaneId::default(),
1511						*b"test",
1512						bp_relayers::RewardsAccountOwner::ThisChain
1513					)
1514				}
1515
1516				fn prepare_rewards_account(
1517					_relayer: &AccountId,
1518					reward_kind: Self::Reward,
1519					reward: Balance,
1520				) -> Option<(Self::Reward, AccountId)> {
1521					let rewards_account = bp_relayers::PayRewardFromAccount::<
1522						Balances,
1523						AccountId,
1524						bp_messages::LegacyLaneId,
1525						Balance,
1526					>::rewards_account(reward_kind);
1527					<Runtime as BridgeRelayersConfig<bridge_common_config::RelayersForLegacyLaneIdsMessagesInstance>>::deposit_account(rewards_account, reward);
1528
1529					None
1530				}
1531
1532				fn deposit_account(account: AccountId, balance: Balance) {
1533					use frame_support::traits::fungible::Mutate;
1534					Balances::mint_into(&account, balance.saturating_add(ExistentialDeposit::get())).unwrap();
1535				}
1536			}
1537
1538			impl BridgeRelayersConfig<bridge_common_config::RelayersForPermissionlessLanesInstance> for Runtime {
1539				fn bench_reward() -> Self::Reward {
1540					bp_relayers::RewardsAccountParams::new(
1541						bp_messages::HashedLaneId::default(),
1542						*b"test",
1543						bp_relayers::RewardsAccountOwner::ThisChain
1544					)
1545				}
1546
1547				fn prepare_rewards_account(
1548					_relayer: &AccountId,
1549					reward_kind: Self::Reward,
1550					reward: Balance,
1551				) -> Option<(Self::Reward, AccountId)> {
1552					let rewards_account = bp_relayers::PayRewardFromAccount::<
1553						Balances,
1554						AccountId,
1555						bp_messages::HashedLaneId,
1556						Balance,
1557					>::rewards_account(reward_kind);
1558					<Runtime as BridgeRelayersConfig<bridge_common_config::RelayersForPermissionlessLanesInstance>>::deposit_account(rewards_account, reward);
1559
1560					None
1561				}
1562
1563				fn deposit_account(account: AccountId, balance: Balance) {
1564					use frame_support::traits::fungible::Mutate;
1565					Balances::mint_into(&account, balance.saturating_add(ExistentialDeposit::get())).unwrap();
1566				}
1567			}
1568
1569			use frame_support::traits::WhitelistedStorageKeys;
1570			let whitelist: Vec<TrackedStorageKey> = AllPalletsWithSystem::whitelisted_storage_keys();
1571
1572			let mut batches = Vec::<BenchmarkBatch>::new();
1573			let params = (&config, &whitelist);
1574			add_benchmarks!(params, batches);
1575
1576			Ok(batches)
1577		}
1578	}
1579
1580	impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
1581		fn build_state(config: Vec<u8>) -> sp_genesis_builder::Result {
1582			build_state::<RuntimeGenesisConfig>(config)
1583		}
1584
1585		fn get_preset(id: &Option<sp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
1586			get_preset::<RuntimeGenesisConfig>(id, &genesis_config_presets::get_preset)
1587		}
1588
1589		fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
1590			genesis_config_presets::preset_names()
1591		}
1592	}
1593
1594	impl xcm_runtime_apis::trusted_query::TrustedQueryApi<Block> for Runtime {
1595		fn is_trusted_reserve(asset: VersionedAsset, location: VersionedLocation) -> xcm_runtime_apis::trusted_query::XcmTrustedQueryResult {
1596			PolkadotXcm::is_trusted_reserve(asset, location)
1597		}
1598		fn is_trusted_teleporter(asset: VersionedAsset, location: VersionedLocation) -> xcm_runtime_apis::trusted_query::XcmTrustedQueryResult {
1599			PolkadotXcm::is_trusted_teleporter(asset, location)
1600		}
1601	}
1602
1603	impl cumulus_primitives_core::GetParachainInfo<Block> for Runtime {
1604		fn parachain_id() -> ParaId {
1605			ParachainInfo::parachain_id()
1606		}
1607	}
1608
1609	impl cumulus_primitives_core::TargetBlockRate<Block> for Runtime {
1610		fn target_block_rate() -> u32 {
1611			BLOCK_PROCESSING_VELOCITY
1612		}
1613	}
1614}
1615
1616#[cfg(test)]
1617mod tests {
1618	use super::*;
1619	use codec::Encode;
1620	use sp_runtime::{
1621		generic::Era,
1622		traits::{TransactionExtension, Zero},
1623	};
1624
1625	#[test]
1626	fn ensure_transaction_extension_definition_is_compatible_with_relay() {
1627		use bp_polkadot_core::SuffixedCommonTransactionExtensionExt;
1628
1629		sp_io::TestExternalities::default().execute_with(|| {
1630			frame_system::BlockHash::<Runtime>::insert(BlockNumber::zero(), Hash::default());
1631			let payload: TxExtension = (
1632				(
1633					frame_system::AuthorizeCall::<Runtime>::new(),
1634					frame_system::CheckNonZeroSender::new(),
1635					frame_system::CheckSpecVersion::new(),
1636					frame_system::CheckTxVersion::new(),
1637					frame_system::CheckGenesis::new(),
1638					frame_system::CheckEra::from(Era::Immortal),
1639					frame_system::CheckNonce::from(10),
1640					frame_system::CheckWeight::new(),
1641				),
1642				pallet_transaction_payment::ChargeTransactionPayment::from(10),
1643				BridgeRejectObsoleteHeadersAndMessages,
1644				(
1645					bridge_to_westend_config::OnBridgeHubRococoRefundBridgeHubWestendMessages::default(),
1646				),
1647				frame_metadata_hash_extension::CheckMetadataHash::new(false),
1648			).into();
1649
1650			// for BridgeHubRococo
1651			{
1652				let bhr_indirect_payload = bp_bridge_hub_rococo::TransactionExtension::from_params(
1653					VERSION.spec_version,
1654					VERSION.transaction_version,
1655					bp_runtime::TransactionEra::Immortal,
1656					System::block_hash(BlockNumber::zero()),
1657					10,
1658					10,
1659					(((), ()), ((), ())),
1660				);
1661				assert_eq!(payload.encode().split_last().unwrap().1, bhr_indirect_payload.encode());
1662				assert_eq!(
1663					TxExtension::implicit(&payload).unwrap().encode().split_last().unwrap().1,
1664					sp_runtime::traits::TransactionExtension::<RuntimeCall>::implicit(
1665						&bhr_indirect_payload
1666					)
1667					.unwrap()
1668					.encode()
1669				)
1670			}
1671		});
1672	}
1673}