1#![cfg_attr(not(feature = "std"), no_std)]
23#![recursion_limit = "256"]
25
26#[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::{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
107pub type Address = MultiAddress<AccountId, ()>;
109
110pub type Block = generic::Block<Header, UncheckedExtrinsic>;
112
113pub type SignedBlock = generic::SignedBlock<Block>;
115
116pub type BlockId = generic::BlockId<Block>;
118
119pub 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
140pub type UncheckedExtrinsic =
142 generic::UncheckedExtrinsic<Address, RuntimeCall, Signature, TxExtension>;
143
144pub type Migrations = (
146 pallet_collator_selection::migration::v2::MigrationToV2<Runtime>,
147 pallet_multisig::migrations::v1::MigrateToV1<Runtime>,
148 InitStorageVersions,
149 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 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
196pub 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
225pub type Executive = frame_executive::Executive<
227 Runtime,
228 Block,
229 frame_system::ChainContext<Runtime>,
230 Runtime,
231 AllPalletsWithSystem,
232 Migrations,
233>;
234
235impl_opaque_keys! {
236 pub struct SessionKeys {
237 pub aura: Aura,
238 }
239}
240
241#[sp_version::runtime_version]
242pub const VERSION: RuntimeVersion = RuntimeVersion {
243 spec_name: alloc::borrow::Cow::Borrowed("bridge-hub-westend"),
244 impl_name: alloc::borrow::Cow::Borrowed("bridge-hub-westend"),
245 authoring_version: 1,
246 spec_version: 1_019_003,
247 impl_version: 0,
248 apis: RUNTIME_API_VERSIONS,
249 transaction_version: 6,
250 system_version: 1,
251};
252
253#[cfg(feature = "std")]
255pub fn native_version() -> NativeVersion {
256 NativeVersion { runtime_version: VERSION, can_author_with: Default::default() }
257}
258
259parameter_types! {
260 pub const Version: RuntimeVersion = VERSION;
261 pub RuntimeBlockLength: BlockLength =
262 BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);
263 pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()
264 .base_block(BlockExecutionWeight::get())
265 .for_class(DispatchClass::all(), |weights| {
266 weights.base_extrinsic = ExtrinsicBaseWeight::get();
267 })
268 .for_class(DispatchClass::Normal, |weights| {
269 weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);
270 })
271 .for_class(DispatchClass::Operational, |weights| {
272 weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);
273 weights.reserved = Some(
276 MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT
277 );
278 })
279 .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)
280 .build_or_panic();
281 pub const SS58Prefix: u16 = 42;
282}
283
284#[derive_impl(frame_system::config_preludes::ParaChainDefaultConfig)]
287impl frame_system::Config for Runtime {
288 type AccountId = AccountId;
290 type Nonce = Nonce;
292 type Hash = Hash;
294 type Block = Block;
296 type BlockHashCount = BlockHashCount;
298 type Version = Version;
300 type AccountData = pallet_balances::AccountData<Balance>;
302 type DbWeight = RocksDbWeight;
304 type SystemWeightInfo = weights::frame_system::WeightInfo<Runtime>;
306 type ExtensionsWeightInfo = weights::frame_system_extensions::WeightInfo<Runtime>;
308 type BlockWeights = RuntimeBlockWeights;
310 type BlockLength = RuntimeBlockLength;
312 type SS58Prefix = SS58Prefix;
314 type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;
316 type MaxConsumers = frame_support::traits::ConstU32<16>;
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 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 type Balance = Balance;
343 type DustRemoval = ();
344 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 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 #[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 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 pub FeeAssetId: AssetId = AssetId(xcm_config::WestendLocation::get());
443 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 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 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 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 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 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 pub const DepositBase: Balance = deposit(1, 88);
533 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
555construct_runtime!(
557 pub enum Runtime
558 {
559 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 Balances: pallet_balances = 10,
568 TransactionPayment: pallet_transaction_payment = 11,
569
570 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 XcmpQueue: cumulus_pallet_xcmp_queue = 30,
579 PolkadotXcm: pallet_xcm = 31,
580 CumulusXcm: cumulus_pallet_xcm = 32,
581
582 Utility: pallet_utility = 40,
584 Multisig: pallet_multisig = 36,
585
586 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 MessageQueue: pallet_message_queue = 250,
605 }
606);
607
608bridge_runtime_common::generate_bridge_reject_obsolete_headers_and_messages! {
609 RuntimeCall, AccountId,
610 CheckAndBoostBridgeGrandpaTransactions<
612 Runtime,
613 bridge_to_rococo_config::BridgeGrandpaRococoInstance,
614 bridge_to_rococo_config::PriorityBoostPerRelayHeader,
615 xcm_config::TreasuryAccount,
616 >,
617 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 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 [pallet_xcm, PalletXcmExtrinsicsBenchmark::<Runtime>]
646 [pallet_xcm_benchmarks::fungible, XcmBalances]
648 [pallet_xcm_benchmarks::generic, XcmGeneric]
649 [pallet_bridge_relayers, BridgeRelayersBench::<Runtime>]
651 [pallet_bridge_grandpa, RococoFinality]
652 [pallet_bridge_parachains, WithinRococo]
653 [pallet_bridge_messages, WestendToRococo]
654 [snowbridge_pallet_system, EthereumSystem]
656 [snowbridge_pallet_ethereum_client, EthereumBeaconClient]
657 [snowbridge_pallet_inbound_queue, EthereumInboundQueue]
658 [snowbridge_pallet_outbound_queue, EthereumOutboundQueue]
659 [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) {
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,
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 use crate::xcm_config::XcmConfig;
829
830 type Trader = <XcmConfig as xcm_executor::Config>::Trader;
831
832 PolkadotXcm::query_weight_to_asset_fee::<Trader>(weight, asset)
833 }
834
835 fn query_xcm_weight(message: VersionedXcm<()>) -> Result<Weight, XcmPaymentApiError> {
836 PolkadotXcm::query_xcm_weight(message)
837 }
838
839 fn query_delivery_fees(destination: VersionedLocation, message: VersionedXcm<()>) -> Result<VersionedAssets, XcmPaymentApiError> {
840 PolkadotXcm::query_delivery_fees(destination, message)
841 }
842 }
843
844 impl xcm_runtime_apis::dry_run::DryRunApi<Block, RuntimeCall, RuntimeEvent, OriginCaller> for Runtime {
845 fn dry_run_call(origin: OriginCaller, call: RuntimeCall, result_xcms_version: XcmVersion) -> Result<CallDryRunEffects<RuntimeEvent>, XcmDryRunApiError> {
846 PolkadotXcm::dry_run_call::<Runtime, xcm_config::XcmRouter, OriginCaller, RuntimeCall>(origin, call, result_xcms_version)
847 }
848
849 fn dry_run_xcm(origin_location: VersionedLocation, xcm: VersionedXcm<RuntimeCall>) -> Result<XcmDryRunEffects<RuntimeEvent>, XcmDryRunApiError> {
850 PolkadotXcm::dry_run_xcm::<Runtime, xcm_config::XcmRouter, RuntimeCall, xcm_config::XcmConfig>(origin_location, xcm)
851 }
852 }
853
854 impl xcm_runtime_apis::conversions::LocationToAccountApi<Block, AccountId> for Runtime {
855 fn convert_location(location: VersionedLocation) -> Result<
856 AccountId,
857 xcm_runtime_apis::conversions::Error
858 > {
859 xcm_runtime_apis::conversions::LocationToAccountHelper::<
860 AccountId,
861 xcm_config::LocationToAccountId,
862 >::convert_location(location)
863 }
864 }
865
866 impl xcm_runtime_apis::trusted_query::TrustedQueryApi<Block> for Runtime {
867 fn is_trusted_reserve(asset: VersionedAsset, location: VersionedLocation) -> xcm_runtime_apis::trusted_query::XcmTrustedQueryResult {
868 PolkadotXcm::is_trusted_reserve(asset, location)
869 }
870 fn is_trusted_teleporter(asset: VersionedAsset, location: VersionedLocation) -> xcm_runtime_apis::trusted_query::XcmTrustedQueryResult {
871 PolkadotXcm::is_trusted_teleporter(asset, location)
872 }
873 }
874
875 impl xcm_runtime_apis::authorized_aliases::AuthorizedAliasersApi<Block> for Runtime {
876 fn authorized_aliasers(target: VersionedLocation) -> Result<
877 Vec<xcm_runtime_apis::authorized_aliases::OriginAliaser>,
878 xcm_runtime_apis::authorized_aliases::Error
879 > {
880 PolkadotXcm::authorized_aliasers(target)
881 }
882 fn is_authorized_alias(origin: VersionedLocation, target: VersionedLocation) -> Result<
883 bool,
884 xcm_runtime_apis::authorized_aliases::Error
885 > {
886 PolkadotXcm::is_authorized_alias(origin, target)
887 }
888 }
889
890 impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {
891 fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {
892 ParachainSystem::collect_collation_info(header)
893 }
894 }
895
896 impl bp_rococo::RococoFinalityApi<Block> for Runtime {
897 fn best_finalized() -> Option<HeaderId<bp_rococo::Hash, bp_rococo::BlockNumber>> {
898 BridgeRococoGrandpa::best_finalized()
899 }
900 fn free_headers_interval() -> Option<bp_rococo::BlockNumber> {
901 <Runtime as pallet_bridge_grandpa::Config<
902 bridge_to_rococo_config::BridgeGrandpaRococoInstance
903 >>::FreeHeadersInterval::get()
904 }
905 fn synced_headers_grandpa_info(
906 ) -> Vec<bp_header_chain::StoredHeaderGrandpaInfo<bp_rococo::Header>> {
907 BridgeRococoGrandpa::synced_headers_grandpa_info()
908 }
909 }
910
911 impl bp_bridge_hub_rococo::BridgeHubRococoFinalityApi<Block> for Runtime {
912 fn best_finalized() -> Option<HeaderId<Hash, BlockNumber>> {
913 BridgeRococoParachains::best_parachain_head_id::<
914 bp_bridge_hub_rococo::BridgeHubRococo
915 >().unwrap_or(None)
916 }
917 fn free_headers_interval() -> Option<bp_bridge_hub_rococo::BlockNumber> {
918 None
920 }
921 }
922
923 impl bp_bridge_hub_rococo::FromBridgeHubRococoInboundLaneApi<Block> for Runtime {
924 fn message_details(
925 lane: LaneIdOf<Runtime, bridge_to_rococo_config::WithBridgeHubRococoMessagesInstance>,
926 messages: Vec<(bp_messages::MessagePayload, bp_messages::OutboundMessageDetails)>,
927 ) -> Vec<bp_messages::InboundMessageDetails> {
928 bridge_runtime_common::messages_api::inbound_message_details::<
929 Runtime,
930 bridge_to_rococo_config::WithBridgeHubRococoMessagesInstance,
931 >(lane, messages)
932 }
933 }
934
935 impl bp_bridge_hub_rococo::ToBridgeHubRococoOutboundLaneApi<Block> for Runtime {
936 fn message_details(
937 lane: LaneIdOf<Runtime, bridge_to_rococo_config::WithBridgeHubRococoMessagesInstance>,
938 begin: bp_messages::MessageNonce,
939 end: bp_messages::MessageNonce,
940 ) -> Vec<bp_messages::OutboundMessageDetails> {
941 bridge_runtime_common::messages_api::outbound_message_details::<
942 Runtime,
943 bridge_to_rococo_config::WithBridgeHubRococoMessagesInstance,
944 >(lane, begin, end)
945 }
946 }
947
948 impl snowbridge_outbound_queue_runtime_api::OutboundQueueApi<Block, Balance> for Runtime {
949 fn prove_message(leaf_index: u64) -> Option<snowbridge_merkle_tree::MerkleProof> {
950 snowbridge_pallet_outbound_queue::api::prove_message::<Runtime>(leaf_index)
951 }
952
953 fn calculate_fee(command: Command, parameters: Option<PricingParameters<Balance>>) -> Fee<Balance> {
954 snowbridge_pallet_outbound_queue::api::calculate_fee::<Runtime>(command, parameters)
955 }
956 }
957
958 impl snowbridge_outbound_queue_v2_runtime_api::OutboundQueueV2Api<Block, Balance> for Runtime {
959 fn prove_message(leaf_index: u64) -> Option<snowbridge_merkle_tree::MerkleProof> {
960 snowbridge_pallet_outbound_queue_v2::api::prove_message::<Runtime>(leaf_index)
961 }
962 }
963
964 impl snowbridge_system_runtime_api::ControlApi<Block> for Runtime {
965 fn agent_id(location: VersionedLocation) -> Option<AgentId> {
966 snowbridge_pallet_system::api::agent_id::<Runtime>(location)
967 }
968 }
969
970 impl snowbridge_system_v2_runtime_api::ControlV2Api<Block> for Runtime {
971 fn agent_id(location: VersionedLocation) -> Option<AgentId> {
972 snowbridge_pallet_system_v2::api::agent_id::<Runtime>(location)
973 }
974 }
975
976 #[cfg(feature = "try-runtime")]
977 impl frame_try_runtime::TryRuntime<Block> for Runtime {
978 fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) {
979 let weight = Executive::try_runtime_upgrade(checks).unwrap();
980 (weight, RuntimeBlockWeights::get().max_block)
981 }
982
983 fn execute_block(
984 block: Block,
985 state_root_check: bool,
986 signature_check: bool,
987 select: frame_try_runtime::TryStateSelect,
988 ) -> Weight {
989 Executive::try_execute_block(block, state_root_check, signature_check, select).unwrap()
992 }
993 }
994
995 #[cfg(feature = "runtime-benchmarks")]
996 impl frame_benchmarking::Benchmark<Block> for Runtime {
997 fn benchmark_metadata(extra: bool) -> (
998 Vec<frame_benchmarking::BenchmarkList>,
999 Vec<frame_support::traits::StorageInfo>,
1000 ) {
1001 use frame_benchmarking::BenchmarkList;
1002 use frame_support::traits::StorageInfoTrait;
1003 use frame_system_benchmarking::Pallet as SystemBench;
1004 use frame_system_benchmarking::extensions::Pallet as SystemExtensionsBench;
1005 use cumulus_pallet_session_benchmarking::Pallet as SessionBench;
1006 use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
1007
1008 type XcmBalances = pallet_xcm_benchmarks::fungible::Pallet::<Runtime>;
1012 type XcmGeneric = pallet_xcm_benchmarks::generic::Pallet::<Runtime>;
1013
1014 use pallet_bridge_relayers::benchmarking::Pallet as BridgeRelayersBench;
1015 type RococoFinality = BridgeRococoGrandpa;
1017 type WithinRococo = pallet_bridge_parachains::benchmarking::Pallet::<Runtime, bridge_to_rococo_config::BridgeParachainRococoInstance>;
1018 type WestendToRococo = pallet_bridge_messages::benchmarking::Pallet ::<Runtime, bridge_to_rococo_config::WithBridgeHubRococoMessagesInstance>;
1019
1020 let mut list = Vec::<BenchmarkList>::new();
1021 list_benchmarks!(list, extra);
1022
1023 let storage_info = AllPalletsWithSystem::storage_info();
1024 (list, storage_info)
1025 }
1026
1027 #[allow(non_local_definitions)]
1028 fn dispatch_benchmark(
1029 config: frame_benchmarking::BenchmarkConfig
1030 ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, alloc::string::String> {
1031 use frame_benchmarking::{BenchmarkBatch, BenchmarkError};
1032 use sp_storage::TrackedStorageKey;
1033
1034 use frame_system_benchmarking::Pallet as SystemBench;
1035 use frame_system_benchmarking::extensions::Pallet as SystemExtensionsBench;
1036 impl frame_system_benchmarking::Config for Runtime {
1037 fn setup_set_code_requirements(code: &alloc::vec::Vec<u8>) -> Result<(), BenchmarkError> {
1038 ParachainSystem::initialize_for_set_code_benchmark(code.len() as u32);
1039 Ok(())
1040 }
1041
1042 fn verify_set_code() {
1043 System::assert_last_event(cumulus_pallet_parachain_system::Event::<Runtime>::ValidationFunctionStored.into());
1044 }
1045 }
1046
1047 use cumulus_pallet_session_benchmarking::Pallet as SessionBench;
1048 impl cumulus_pallet_session_benchmarking::Config for Runtime {}
1049
1050 use xcm::latest::prelude::*;
1051 use xcm_config::WestendLocation;
1052 use testnet_parachains_constants::westend::locations::{AssetHubParaId, AssetHubLocation};
1053 parameter_types! {
1054 pub ExistentialDepositAsset: Option<Asset> = Some((
1055 WestendLocation::get(),
1056 ExistentialDeposit::get()
1057 ).into());
1058 }
1059
1060 use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
1061 impl pallet_xcm::benchmarking::Config for Runtime {
1062 type DeliveryHelper = polkadot_runtime_common::xcm_sender::ToParachainDeliveryHelper<
1063 xcm_config::XcmConfig,
1064 ExistentialDepositAsset,
1065 PriceForSiblingParachainDelivery,
1066 AssetHubParaId,
1067 ParachainSystem,
1068 >;
1069
1070 fn reachable_dest() -> Option<Location> {
1071 Some(AssetHubLocation::get())
1072 }
1073
1074 fn teleportable_asset_and_dest() -> Option<(Asset, Location)> {
1075 Some((
1077 Asset {
1078 fun: Fungible(ExistentialDeposit::get()),
1079 id: AssetId(WestendLocation::get())
1080 },
1081 AssetHubLocation::get(),
1082 ))
1083 }
1084
1085 fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> {
1086 None
1088 }
1089
1090 fn set_up_complex_asset_transfer(
1091 ) -> Option<(Assets, u32, Location, alloc::boxed::Box<dyn FnOnce()>)> {
1092 let native_location = WestendLocation::get();
1095 let dest = AssetHubLocation::get();
1096 pallet_xcm::benchmarking::helpers::native_teleport_as_asset_transfer::<Runtime>(
1097 native_location,
1098 dest
1099 )
1100 }
1101
1102 fn get_asset() -> Asset {
1103 Asset {
1104 id: AssetId(Location::parent()),
1105 fun: Fungible(ExistentialDeposit::get()),
1106 }
1107 }
1108 }
1109
1110 impl pallet_xcm_benchmarks::Config for Runtime {
1111 type XcmConfig = xcm_config::XcmConfig;
1112 type AccountIdConverter = xcm_config::LocationToAccountId;
1113 type DeliveryHelper = polkadot_runtime_common::xcm_sender::ToParachainDeliveryHelper<
1114 xcm_config::XcmConfig,
1115 ExistentialDepositAsset,
1116 PriceForSiblingParachainDelivery,
1117 AssetHubParaId,
1118 ParachainSystem,
1119 >;
1120 fn valid_destination() -> Result<Location, BenchmarkError> {
1121 Ok(AssetHubLocation::get())
1122 }
1123 fn worst_case_holding(_depositable_count: u32) -> Assets {
1124 let assets: Vec<Asset> = vec![
1126 Asset {
1127 id: AssetId(WestendLocation::get()),
1128 fun: Fungible(1_000_000 * UNITS),
1129 }
1130 ];
1131 assets.into()
1132 }
1133 }
1134
1135 parameter_types! {
1136 pub TrustedTeleporter: Option<(Location, Asset)> = Some((
1137 AssetHubLocation::get(),
1138 Asset { fun: Fungible(UNITS), id: AssetId(WestendLocation::get()) },
1139 ));
1140 pub const CheckedAccount: Option<(AccountId, xcm_builder::MintLocation)> = None;
1141 pub const TrustedReserve: Option<(Location, Asset)> = None;
1142 }
1143
1144 impl pallet_xcm_benchmarks::fungible::Config for Runtime {
1145 type TransactAsset = Balances;
1146
1147 type CheckedAccount = CheckedAccount;
1148 type TrustedTeleporter = TrustedTeleporter;
1149 type TrustedReserve = TrustedReserve;
1150
1151 fn get_asset() -> Asset {
1152 Asset {
1153 id: AssetId(WestendLocation::get()),
1154 fun: Fungible(UNITS),
1155 }
1156 }
1157 }
1158
1159 impl pallet_xcm_benchmarks::generic::Config for Runtime {
1160 type TransactAsset = Balances;
1161 type RuntimeCall = RuntimeCall;
1162
1163 fn worst_case_response() -> (u64, Response) {
1164 (0u64, Response::Version(Default::default()))
1165 }
1166
1167 fn worst_case_asset_exchange() -> Result<(Assets, Assets), BenchmarkError> {
1168 Err(BenchmarkError::Skip)
1169 }
1170
1171 fn universal_alias() -> Result<(Location, Junction), BenchmarkError> {
1172 Err(BenchmarkError::Skip)
1173 }
1174
1175 fn transact_origin_and_runtime_call() -> Result<(Location, RuntimeCall), BenchmarkError> {
1176 Ok((AssetHubLocation::get(), frame_system::Call::remark_with_event { remark: vec![] }.into()))
1177 }
1178
1179 fn subscribe_origin() -> Result<Location, BenchmarkError> {
1180 Ok(AssetHubLocation::get())
1181 }
1182
1183 fn claimable_asset() -> Result<(Location, Location, Assets), BenchmarkError> {
1184 let origin = AssetHubLocation::get();
1185 let assets: Assets = (AssetId(WestendLocation::get()), 1_000 * UNITS).into();
1186 let ticket = Location { parents: 0, interior: Here };
1187 Ok((origin, ticket, assets))
1188 }
1189
1190 fn worst_case_for_trader() -> Result<(Asset, WeightLimit), BenchmarkError> {
1191 Ok((Asset {
1192 id: AssetId(WestendLocation::get()),
1193 fun: Fungible(1_000_000 * UNITS),
1194 }, WeightLimit::Limited(Weight::from_parts(5000, 5000))))
1195 }
1196
1197 fn unlockable_asset() -> Result<(Location, Location, Asset), BenchmarkError> {
1198 Err(BenchmarkError::Skip)
1199 }
1200
1201 fn export_message_origin_and_destination(
1202 ) -> Result<(Location, NetworkId, InteriorLocation), BenchmarkError> {
1203 let _ = PolkadotXcm::force_xcm_version(
1205 RuntimeOrigin::root(),
1206 alloc::boxed::Box::new(bridge_to_rococo_config::BridgeHubRococoLocation::get()),
1207 XCM_VERSION,
1208 ).map_err(|e| {
1209 let origin = RuntimeOrigin::root();
1210 let bridge = bridge_to_rococo_config::BridgeHubRococoLocation::get();
1211 tracing::error!(
1212 target: "xcm::export_message_origin_and_destination",
1213 ?origin,
1214 ?bridge,
1215 ?XCM_VERSION,
1216 ?e,
1217 "Failed to dispatch `force_xcm_version`",
1218 );
1219 BenchmarkError::Stop("XcmVersion was not stored!")
1220 })?;
1221
1222 let sibling_parachain_location = Location::new(1, [Parachain(5678)]);
1223
1224 use frame_support::traits::fungible::Mutate;
1226 use xcm_executor::traits::ConvertLocation;
1227 frame_support::assert_ok!(
1228 Balances::mint_into(
1229 &xcm_config::LocationToAccountId::convert_location(&sibling_parachain_location).expect("valid AccountId"),
1230 bridge_to_rococo_config::BridgeDeposit::get()
1231 .saturating_add(ExistentialDeposit::get())
1232 .saturating_add(UNITS * 5)
1233 )
1234 );
1235
1236 let bridge_destination_universal_location: InteriorLocation = [GlobalConsensus(ByGenesis(ROCOCO_GENESIS_HASH)), Parachain(8765)].into();
1238 let locations = XcmOverBridgeHubRococo::bridge_locations(
1239 sibling_parachain_location.clone(),
1240 bridge_destination_universal_location.clone(),
1241 )?;
1242 XcmOverBridgeHubRococo::do_open_bridge(
1243 locations,
1244 bp_messages::LegacyLaneId([1, 2, 3, 4]),
1245 true,
1246 ).map_err(|e| {
1247 tracing::error!(
1248 target: "xcm::export_message_origin_and_destination",
1249 ?sibling_parachain_location,
1250 ?bridge_destination_universal_location,
1251 ?e,
1252 "Failed to `XcmOverBridgeHubRococo::open_bridge`",
1253 );
1254 BenchmarkError::Stop("Bridge was not opened!")
1255 })?;
1256
1257 Ok(
1258 (
1259 sibling_parachain_location,
1260 NetworkId::ByGenesis(ROCOCO_GENESIS_HASH),
1261 [Parachain(8765)].into()
1262 )
1263 )
1264 }
1265
1266 fn alias_origin() -> Result<(Location, Location), BenchmarkError> {
1267 let origin = Location::new(1, [Parachain(1000)]);
1270 let target = Location::new(1, [Parachain(1000), AccountId32 { id: [128u8; 32], network: None }]);
1271 Ok((origin, target))
1272 }
1273 }
1274
1275 type XcmBalances = pallet_xcm_benchmarks::fungible::Pallet::<Runtime>;
1276 type XcmGeneric = pallet_xcm_benchmarks::generic::Pallet::<Runtime>;
1277
1278 type RococoFinality = BridgeRococoGrandpa;
1279 type WithinRococo = pallet_bridge_parachains::benchmarking::Pallet::<Runtime, bridge_to_rococo_config::BridgeParachainRococoInstance>;
1280 type WestendToRococo = pallet_bridge_messages::benchmarking::Pallet ::<Runtime, bridge_to_rococo_config::WithBridgeHubRococoMessagesInstance>;
1281
1282 use bridge_runtime_common::messages_benchmarking::{
1283 prepare_message_delivery_proof_from_parachain,
1284 prepare_message_proof_from_parachain,
1285 generate_xcm_builder_bridge_message_sample,
1286 };
1287 use pallet_bridge_messages::benchmarking::{
1288 Config as BridgeMessagesConfig,
1289 MessageDeliveryProofParams,
1290 MessageProofParams,
1291 };
1292
1293 impl BridgeMessagesConfig<bridge_to_rococo_config::WithBridgeHubRococoMessagesInstance> for Runtime {
1294 fn is_relayer_rewarded(relayer: &Self::AccountId) -> bool {
1295 let bench_lane_id = <Self as BridgeMessagesConfig<bridge_to_rococo_config::WithBridgeHubRococoMessagesInstance>>::bench_lane_id();
1296 use bp_runtime::Chain;
1297 let bridged_chain_id =<Self as pallet_bridge_messages::Config<bridge_to_rococo_config::WithBridgeHubRococoMessagesInstance>>::BridgedChain::ID;
1298 pallet_bridge_relayers::Pallet::<Runtime, bridge_common_config::BridgeRelayersInstance>::relayer_reward(
1299 relayer,
1300 bridge_common_config::BridgeReward::RococoWestend(
1301 bp_relayers::RewardsAccountParams::new(
1302 bench_lane_id,
1303 bridged_chain_id,
1304 bp_relayers::RewardsAccountOwner::BridgedChain
1305 )
1306 )
1307 ).is_some()
1308 }
1309
1310 fn prepare_message_proof(
1311 params: MessageProofParams<LaneIdOf<Runtime, bridge_to_rococo_config::WithBridgeHubRococoMessagesInstance>>,
1312 ) -> (bridge_to_rococo_config::FromRococoBridgeHubMessagesProof<bridge_to_rococo_config::WithBridgeHubRococoMessagesInstance>, Weight) {
1313 use cumulus_primitives_core::XcmpMessageSource;
1314 assert!(XcmpQueue::take_outbound_messages(usize::MAX).is_empty());
1315 ParachainSystem::open_outbound_hrmp_channel_for_benchmarks_or_tests(42.into());
1316 let universal_source = bridge_to_rococo_config::open_bridge_for_benchmarks::<
1317 Runtime,
1318 bridge_to_rococo_config::XcmOverBridgeHubRococoInstance,
1319 xcm_config::LocationToAccountId,
1320 >(params.lane, 42);
1321 prepare_message_proof_from_parachain::<
1322 Runtime,
1323 bridge_to_rococo_config::BridgeGrandpaRococoInstance,
1324 bridge_to_rococo_config::WithBridgeHubRococoMessagesInstance,
1325 >(params, generate_xcm_builder_bridge_message_sample(universal_source))
1326 }
1327
1328 fn prepare_message_delivery_proof(
1329 params: MessageDeliveryProofParams<AccountId, LaneIdOf<Runtime, bridge_to_rococo_config::WithBridgeHubRococoMessagesInstance>>,
1330 ) -> bridge_to_rococo_config::ToRococoBridgeHubMessagesDeliveryProof<bridge_to_rococo_config::WithBridgeHubRococoMessagesInstance> {
1331 let _ = bridge_to_rococo_config::open_bridge_for_benchmarks::<
1332 Runtime,
1333 bridge_to_rococo_config::XcmOverBridgeHubRococoInstance,
1334 xcm_config::LocationToAccountId,
1335 >(params.lane, 42);
1336 prepare_message_delivery_proof_from_parachain::<
1337 Runtime,
1338 bridge_to_rococo_config::BridgeGrandpaRococoInstance,
1339 bridge_to_rococo_config::WithBridgeHubRococoMessagesInstance,
1340 >(params)
1341 }
1342
1343 fn is_message_successfully_dispatched(_nonce: bp_messages::MessageNonce) -> bool {
1344 use cumulus_primitives_core::XcmpMessageSource;
1345 !XcmpQueue::take_outbound_messages(usize::MAX).is_empty()
1346 }
1347 }
1348
1349 use bridge_runtime_common::parachains_benchmarking::prepare_parachain_heads_proof;
1350 use pallet_bridge_parachains::benchmarking::Config as BridgeParachainsConfig;
1351 use pallet_bridge_relayers::benchmarking::{
1352 Pallet as BridgeRelayersBench,
1353 Config as BridgeRelayersConfig,
1354 };
1355
1356 impl BridgeParachainsConfig<bridge_to_rococo_config::BridgeParachainRococoInstance> for Runtime {
1357 fn parachains() -> Vec<bp_polkadot_core::parachains::ParaId> {
1358 use bp_runtime::Parachain;
1359 vec![bp_polkadot_core::parachains::ParaId(bp_bridge_hub_rococo::BridgeHubRococo::PARACHAIN_ID)]
1360 }
1361
1362 fn prepare_parachain_heads_proof(
1363 parachains: &[bp_polkadot_core::parachains::ParaId],
1364 parachain_head_size: u32,
1365 proof_params: bp_runtime::UnverifiedStorageProofParams,
1366 ) -> (
1367 bp_parachains::RelayBlockNumber,
1368 bp_parachains::RelayBlockHash,
1369 bp_polkadot_core::parachains::ParaHeadsProof,
1370 Vec<(bp_polkadot_core::parachains::ParaId, bp_polkadot_core::parachains::ParaHash)>,
1371 ) {
1372 prepare_parachain_heads_proof::<Runtime, bridge_to_rococo_config::BridgeParachainRococoInstance>(
1373 parachains,
1374 parachain_head_size,
1375 proof_params,
1376 )
1377 }
1378 }
1379
1380 impl BridgeRelayersConfig<bridge_common_config::BridgeRelayersInstance> for Runtime {
1381 fn bench_reward() -> Self::Reward {
1382 bp_relayers::RewardsAccountParams::new(
1383 bp_messages::LegacyLaneId::default(),
1384 *b"test",
1385 bp_relayers::RewardsAccountOwner::ThisChain
1386 ).into()
1387 }
1388
1389 fn prepare_rewards_account(
1390 reward_kind: Self::Reward,
1391 reward: Balance,
1392 ) -> Option<pallet_bridge_relayers::BeneficiaryOf<Runtime, bridge_common_config::BridgeRelayersInstance>> {
1393 let bridge_common_config::BridgeReward::RococoWestend(reward_kind) = reward_kind else {
1394 panic!("Unexpected reward_kind: {:?} - not compatible with `bench_reward`!", reward_kind);
1395 };
1396 let rewards_account = bp_relayers::PayRewardFromAccount::<
1397 Balances,
1398 AccountId,
1399 bp_messages::LegacyLaneId,
1400 u128,
1401 >::rewards_account(reward_kind);
1402 Self::deposit_account(rewards_account, reward);
1403
1404 None
1405 }
1406
1407 fn deposit_account(account: AccountId, balance: Balance) {
1408 use frame_support::traits::fungible::Mutate;
1409 Balances::mint_into(&account, balance.saturating_add(ExistentialDeposit::get())).unwrap();
1410 }
1411 }
1412
1413 use frame_support::traits::WhitelistedStorageKeys;
1414 let whitelist: Vec<TrackedStorageKey> = AllPalletsWithSystem::whitelisted_storage_keys();
1415
1416 let mut batches = Vec::<BenchmarkBatch>::new();
1417 let params = (&config, &whitelist);
1418 add_benchmarks!(params, batches);
1419
1420 Ok(batches)
1421 }
1422 }
1423
1424 impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
1425 fn build_state(config: Vec<u8>) -> sp_genesis_builder::Result {
1426 build_state::<RuntimeGenesisConfig>(config)
1427 }
1428
1429 fn get_preset(id: &Option<sp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
1430 get_preset::<RuntimeGenesisConfig>(id, &genesis_config_presets::get_preset)
1431 }
1432
1433 fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
1434 genesis_config_presets::preset_names()
1435 }
1436 }
1437
1438 impl cumulus_primitives_core::GetParachainInfo<Block> for Runtime {
1439 fn parachain_id() -> ParaId {
1440 ParachainInfo::parachain_id()
1441 }
1442 }
1443}
1444
1445cumulus_pallet_parachain_system::register_validate_block! {
1446 Runtime = Runtime,
1447 BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,
1448}
1449
1450#[cfg(test)]
1451mod tests {
1452 use super::*;
1453 use codec::Encode;
1454 use sp_runtime::{
1455 generic::Era,
1456 traits::{TransactionExtension, Zero},
1457 };
1458
1459 #[test]
1460 fn ensure_transaction_extension_definition_is_compatible_with_relay() {
1461 use bp_polkadot_core::SuffixedCommonTransactionExtensionExt;
1462
1463 sp_io::TestExternalities::default().execute_with(|| {
1464 frame_system::BlockHash::<Runtime>::insert(BlockNumber::zero(), Hash::default());
1465 let payload: TxExtension = (
1466 (
1467 frame_system::AuthorizeCall::<Runtime>::new(),
1468 frame_system::CheckNonZeroSender::new(),
1469 frame_system::CheckSpecVersion::new(),
1470 frame_system::CheckTxVersion::new(),
1471 frame_system::CheckGenesis::new(),
1472 frame_system::CheckEra::from(Era::Immortal),
1473 frame_system::CheckNonce::from(10),
1474 frame_system::CheckWeight::new(),
1475 ),
1476 pallet_transaction_payment::ChargeTransactionPayment::from(10),
1477 BridgeRejectObsoleteHeadersAndMessages,
1478 (
1479 bridge_to_rococo_config::OnBridgeHubWestendRefundBridgeHubRococoMessages::default(),
1480 ),
1481 frame_metadata_hash_extension::CheckMetadataHash::new(false),
1482 ).into();
1483
1484 {
1485 let bh_indirect_payload = bp_bridge_hub_westend::TransactionExtension::from_params(
1486 VERSION.spec_version,
1487 VERSION.transaction_version,
1488 bp_runtime::TransactionEra::Immortal,
1489 System::block_hash(BlockNumber::zero()),
1490 10,
1491 10,
1492 (((), ()), ((), ())),
1493 );
1494 assert_eq!(payload.encode().split_last().unwrap().1, bh_indirect_payload.encode());
1495 assert_eq!(
1496 TxExtension::implicit(&payload).unwrap().encode().split_last().unwrap().1,
1497 sp_runtime::traits::TransactionExtension::<RuntimeCall>::implicit(
1498 &bh_indirect_payload
1499 )
1500 .unwrap()
1501 .encode()
1502 )
1503 }
1504 });
1505 }
1506}