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