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