Skip to main content

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