1#![cfg_attr(not(feature = "std"), no_std)]
24#![recursion_limit = "256"]
26
27#[cfg(feature = "std")]
29include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
30
31pub mod bridge_common_config;
32pub mod bridge_to_bulletin_config;
33pub mod bridge_to_ethereum_config;
34pub mod bridge_to_westend_config;
35mod genesis_config_presets;
36mod weights;
37pub mod xcm_config;
38
39extern crate alloc;
40
41use alloc::{vec, vec::Vec};
42use bridge_runtime_common::extensions::{
43 CheckAndBoostBridgeGrandpaTransactions, CheckAndBoostBridgeParachainsTransactions,
44};
45use cumulus_pallet_parachain_system::RelayNumberMonotonicallyIncreases;
46use pallet_bridge_messages::LaneIdOf;
47use sp_api::impl_runtime_apis;
48use sp_core::{crypto::KeyTypeId, OpaqueMetadata};
49use sp_runtime::{
50 generic, impl_opaque_keys,
51 traits::Block as BlockT,
52 transaction_validity::{TransactionSource, TransactionValidity},
53 ApplyExtrinsicResult,
54};
55
56#[cfg(feature = "std")]
57use sp_version::NativeVersion;
58use sp_version::RuntimeVersion;
59
60use cumulus_primitives_core::{ClaimQueueOffset, CoreSelector, ParaId};
61use frame_support::{
62 construct_runtime, derive_impl,
63 dispatch::DispatchClass,
64 genesis_builder_helper::{build_state, get_preset},
65 parameter_types,
66 traits::{ConstBool, ConstU32, ConstU64, ConstU8, Get, TransformOrigin},
67 weights::{ConstantMultiplier, Weight, WeightToFee as _},
68 PalletId,
69};
70use frame_system::{
71 limits::{BlockLength, BlockWeights},
72 EnsureRoot,
73};
74use testnet_parachains_constants::rococo::{consensus::*, currency::*, fee::WeightToFee, time::*};
75
76use bp_runtime::HeaderId;
77use bridge_hub_common::{
78 message_queue::{NarrowOriginToSibling, ParaIdToSibling},
79 AggregateMessageOrigin,
80};
81pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;
82pub use sp_runtime::{MultiAddress, Perbill, Permill};
83
84#[cfg(feature = "runtime-benchmarks")]
85use xcm::latest::WESTEND_GENESIS_HASH;
86use xcm::VersionedLocation;
87use xcm_config::{TreasuryAccount, XcmOriginToTransactDispatchOrigin, XcmRouter};
88
89#[cfg(any(feature = "std", test))]
90pub use sp_runtime::BuildStorage;
91
92use polkadot_runtime_common::{BlockHashCount, SlowAdjustingFeeUpdate};
93use rococo_runtime_constants::system_parachain::{ASSET_HUB_ID, BRIDGE_HUB_ID};
94use snowbridge_core::{
95 outbound::{Command, Fee},
96 AgentId, PricingParameters,
97};
98use xcm::{latest::prelude::*, prelude::*, Version as XcmVersion};
99use xcm_runtime_apis::{
100 dry_run::{CallDryRunEffects, Error as XcmDryRunApiError, XcmDryRunEffects},
101 fees::Error as XcmPaymentApiError,
102};
103
104use weights::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight};
105
106use parachains_common::{
107 impls::DealWithFees, AccountId, Balance, BlockNumber, Hash, Header, Nonce, Signature,
108 AVERAGE_ON_INITIALIZE_RATIO, NORMAL_DISPATCH_RATIO,
109};
110
111#[cfg(feature = "runtime-benchmarks")]
112use alloc::boxed::Box;
113
114pub type Address = MultiAddress<AccountId, ()>;
116
117pub type Block = generic::Block<Header, UncheckedExtrinsic>;
119
120pub type SignedBlock = generic::SignedBlock<Block>;
122
123pub type BlockId = generic::BlockId<Block>;
125
126pub type TxExtension = (
128 frame_system::CheckNonZeroSender<Runtime>,
129 frame_system::CheckSpecVersion<Runtime>,
130 frame_system::CheckTxVersion<Runtime>,
131 frame_system::CheckGenesis<Runtime>,
132 frame_system::CheckEra<Runtime>,
133 frame_system::CheckNonce<Runtime>,
134 frame_system::CheckWeight<Runtime>,
135 pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
136 BridgeRejectObsoleteHeadersAndMessages,
137 (bridge_to_westend_config::OnBridgeHubRococoRefundBridgeHubWestendMessages,),
138 frame_metadata_hash_extension::CheckMetadataHash<Runtime>,
139 cumulus_primitives_storage_weight_reclaim::StorageWeightReclaim<Runtime>,
140);
141
142pub type UncheckedExtrinsic =
144 generic::UncheckedExtrinsic<Address, RuntimeCall, Signature, TxExtension>;
145
146pub type Migrations = (
148 pallet_collator_selection::migration::v2::MigrationToV2<Runtime>,
149 pallet_multisig::migrations::v1::MigrateToV1<Runtime>,
150 InitStorageVersions,
151 cumulus_pallet_xcmp_queue::migration::v4::MigrationToV4<Runtime>,
153 cumulus_pallet_xcmp_queue::migration::v5::MigrateV4ToV5<Runtime>,
154 snowbridge_pallet_system::migration::v0::InitializeOnUpgrade<
155 Runtime,
156 ConstU32<BRIDGE_HUB_ID>,
157 ConstU32<ASSET_HUB_ID>,
158 >,
159 snowbridge_pallet_system::migration::FeePerGasMigrationV0ToV1<Runtime>,
160 pallet_bridge_messages::migration::v1::MigrationToV1<
161 Runtime,
162 bridge_to_westend_config::WithBridgeHubWestendMessagesInstance,
163 >,
164 pallet_bridge_messages::migration::v1::MigrationToV1<
165 Runtime,
166 bridge_to_bulletin_config::WithRococoBulletinMessagesInstance,
167 >,
168 bridge_to_westend_config::migration::FixMessagesV1Migration<
169 Runtime,
170 bridge_to_westend_config::WithBridgeHubWestendMessagesInstance,
171 >,
172 bridge_to_westend_config::migration::StaticToDynamicLanes,
173 bridge_to_bulletin_config::migration::StaticToDynamicLanes,
174 frame_support::migrations::RemoveStorage<
175 BridgeWestendMessagesPalletName,
176 OutboundLanesCongestedSignalsKey,
177 RocksDbWeight,
178 >,
179 frame_support::migrations::RemoveStorage<
180 BridgePolkadotBulletinMessagesPalletName,
181 OutboundLanesCongestedSignalsKey,
182 RocksDbWeight,
183 >,
184 pallet_bridge_relayers::migration::v1::MigrationToV1<Runtime, ()>,
185 pallet_xcm::migration::MigrateToLatestXcmVersion<Runtime>,
187);
188
189parameter_types! {
190 pub const BridgeWestendMessagesPalletName: &'static str = "BridgeWestendMessages";
191 pub const BridgePolkadotBulletinMessagesPalletName: &'static str = "BridgePolkadotBulletinMessages";
192 pub const OutboundLanesCongestedSignalsKey: &'static str = "OutboundLanesCongestedSignals";
193}
194
195pub struct InitStorageVersions;
202
203impl frame_support::traits::OnRuntimeUpgrade for InitStorageVersions {
204 fn on_runtime_upgrade() -> Weight {
205 use frame_support::traits::{GetStorageVersion, StorageVersion};
206 use sp_runtime::traits::Saturating;
207
208 let mut writes = 0;
209
210 if PolkadotXcm::on_chain_storage_version() == StorageVersion::new(0) {
211 PolkadotXcm::in_code_storage_version().put::<PolkadotXcm>();
212 writes.saturating_inc();
213 }
214
215 if Balances::on_chain_storage_version() == StorageVersion::new(0) {
216 Balances::in_code_storage_version().put::<Balances>();
217 writes.saturating_inc();
218 }
219
220 <Runtime as frame_system::Config>::DbWeight::get().reads_writes(2, writes)
221 }
222}
223
224pub type Executive = frame_executive::Executive<
226 Runtime,
227 Block,
228 frame_system::ChainContext<Runtime>,
229 Runtime,
230 AllPalletsWithSystem,
231 Migrations,
232>;
233
234impl_opaque_keys! {
235 pub struct SessionKeys {
236 pub aura: Aura,
237 }
238}
239
240#[sp_version::runtime_version]
241pub const VERSION: RuntimeVersion = RuntimeVersion {
242 spec_name: alloc::borrow::Cow::Borrowed("bridge-hub-rococo"),
243 impl_name: alloc::borrow::Cow::Borrowed("bridge-hub-rococo"),
244 authoring_version: 1,
245 spec_version: 1_017_001,
246 impl_version: 0,
247 apis: RUNTIME_API_VERSIONS,
248 transaction_version: 6,
249 system_version: 1,
250};
251
252#[cfg(feature = "std")]
254pub fn native_version() -> NativeVersion {
255 NativeVersion { runtime_version: VERSION, can_author_with: Default::default() }
256}
257
258parameter_types! {
259 pub const Version: RuntimeVersion = VERSION;
260 pub RuntimeBlockLength: BlockLength =
261 BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);
262 pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()
263 .base_block(BlockExecutionWeight::get())
264 .for_class(DispatchClass::all(), |weights| {
265 weights.base_extrinsic = ExtrinsicBaseWeight::get();
266 })
267 .for_class(DispatchClass::Normal, |weights| {
268 weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);
269 })
270 .for_class(DispatchClass::Operational, |weights| {
271 weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);
272 weights.reserved = Some(
275 MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT
276 );
277 })
278 .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)
279 .build_or_panic();
280 pub const SS58Prefix: u16 = 42;
281}
282
283#[derive_impl(frame_system::config_preludes::ParaChainDefaultConfig)]
286impl frame_system::Config for Runtime {
287 type AccountId = AccountId;
289 type Nonce = Nonce;
291 type Hash = Hash;
293 type Block = Block;
295 type BlockHashCount = BlockHashCount;
297 type Version = Version;
299 type AccountData = pallet_balances::AccountData<Balance>;
301 type DbWeight = RocksDbWeight;
303 type SystemWeightInfo = weights::frame_system::WeightInfo<Runtime>;
305 type ExtensionsWeightInfo = weights::frame_system_extensions::WeightInfo<Runtime>;
307 type BlockWeights = RuntimeBlockWeights;
309 type BlockLength = RuntimeBlockLength;
311 type SS58Prefix = SS58Prefix;
313 type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;
315 type MaxConsumers = frame_support::traits::ConstU32<16>;
316}
317
318impl pallet_timestamp::Config for Runtime {
319 type Moment = u64;
321 type OnTimestampSet = Aura;
322 type MinimumPeriod = ConstU64<0>;
323 type WeightInfo = weights::pallet_timestamp::WeightInfo<Runtime>;
324}
325
326impl pallet_authorship::Config for Runtime {
327 type FindAuthor = pallet_session::FindAccountFromAuthorIndex<Self, Aura>;
328 type EventHandler = (CollatorSelection,);
329}
330
331parameter_types! {
332 pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT;
333}
334
335impl pallet_balances::Config for Runtime {
336 type Balance = Balance;
338 type DustRemoval = ();
339 type RuntimeEvent = RuntimeEvent;
341 type ExistentialDeposit = ExistentialDeposit;
342 type AccountStore = System;
343 type WeightInfo = weights::pallet_balances::WeightInfo<Runtime>;
344 type MaxLocks = ConstU32<50>;
345 type MaxReserves = ConstU32<50>;
346 type ReserveIdentifier = [u8; 8];
347 type RuntimeHoldReason = RuntimeHoldReason;
348 type RuntimeFreezeReason = RuntimeFreezeReason;
349 type FreezeIdentifier = ();
350 type MaxFreezes = ConstU32<0>;
351 type DoneSlashHandler = ();
352}
353
354parameter_types! {
355 pub const TransactionByteFee: Balance = MILLICENTS;
357}
358
359impl pallet_transaction_payment::Config for Runtime {
360 type RuntimeEvent = RuntimeEvent;
361 type OnChargeTransaction =
362 pallet_transaction_payment::FungibleAdapter<Balances, DealWithFees<Runtime>>;
363 type OperationalFeeMultiplier = ConstU8<5>;
364 type WeightToFee = WeightToFee;
365 type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;
366 type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Self>;
367 type WeightInfo = weights::pallet_transaction_payment::WeightInfo<Runtime>;
368}
369
370parameter_types! {
371 pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
372 pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
373}
374
375impl cumulus_pallet_parachain_system::Config for Runtime {
376 type WeightInfo = weights::cumulus_pallet_parachain_system::WeightInfo<Runtime>;
377 type RuntimeEvent = RuntimeEvent;
378 type OnSystemEvent = ();
379 type SelfParaId = parachain_info::Pallet<Runtime>;
380 type OutboundXcmpMessageSource = XcmpQueue;
381 type DmpQueue = frame_support::traits::EnqueueWithOrigin<MessageQueue, RelayOrigin>;
382 type ReservedDmpWeight = ReservedDmpWeight;
383 type XcmpMessageHandler = XcmpQueue;
384 type ReservedXcmpWeight = ReservedXcmpWeight;
385 type CheckAssociatedRelayNumber = RelayNumberMonotonicallyIncreases;
386 type ConsensusHook = ConsensusHook;
387 type SelectCore = cumulus_pallet_parachain_system::DefaultCoreSelector<Runtime>;
388}
389
390type ConsensusHook = cumulus_pallet_aura_ext::FixedVelocityConsensusHook<
391 Runtime,
392 RELAY_CHAIN_SLOT_DURATION_MILLIS,
393 BLOCK_PROCESSING_VELOCITY,
394 UNINCLUDED_SEGMENT_CAPACITY,
395>;
396
397impl parachain_info::Config for Runtime {}
398
399parameter_types! {
400 pub MessageQueueServiceWeight: Weight = Perbill::from_percent(60) * RuntimeBlockWeights::get().max_block;
405}
406
407impl pallet_message_queue::Config for Runtime {
408 type RuntimeEvent = RuntimeEvent;
409 type WeightInfo = weights::pallet_message_queue::WeightInfo<Runtime>;
410 #[cfg(all(not(feature = "std"), feature = "runtime-benchmarks"))]
415 type MessageProcessor =
416 pallet_message_queue::mock_helpers::NoopMessageProcessor<AggregateMessageOrigin>;
417 #[cfg(not(all(not(feature = "std"), feature = "runtime-benchmarks")))]
418 type MessageProcessor = bridge_hub_common::BridgeHubMessageRouter<
419 xcm_builder::ProcessXcmMessage<
420 AggregateMessageOrigin,
421 xcm_executor::XcmExecutor<xcm_config::XcmConfig>,
422 RuntimeCall,
423 >,
424 EthereumOutboundQueue,
425 >;
426 type Size = u32;
427 type QueueChangeHandler = NarrowOriginToSibling<XcmpQueue>;
429 type QueuePausedQuery = NarrowOriginToSibling<XcmpQueue>;
430 type HeapSize = sp_core::ConstU32<{ 103 * 1024 }>;
431 type MaxStale = sp_core::ConstU32<8>;
432 type ServiceWeight = MessageQueueServiceWeight;
433 type IdleMaxServiceWeight = MessageQueueServiceWeight;
434}
435
436impl cumulus_pallet_aura_ext::Config for Runtime {}
437
438parameter_types! {
439 pub FeeAssetId: AssetId = AssetId(xcm_config::TokenLocation::get());
441 pub const BaseDeliveryFee: u128 = CENTS.saturating_mul(3);
443}
444
445pub type PriceForSiblingParachainDelivery = polkadot_runtime_common::xcm_sender::ExponentialPrice<
446 FeeAssetId,
447 BaseDeliveryFee,
448 TransactionByteFee,
449 XcmpQueue,
450>;
451
452impl cumulus_pallet_xcmp_queue::Config for Runtime {
453 type RuntimeEvent = RuntimeEvent;
454 type ChannelInfo = ParachainSystem;
455 type VersionWrapper = PolkadotXcm;
456 type XcmpQueue = TransformOrigin<MessageQueue, AggregateMessageOrigin, ParaId, ParaIdToSibling>;
458 type MaxInboundSuspended = ConstU32<1_000>;
459 type MaxActiveOutboundChannels = ConstU32<128>;
460 type MaxPageSize = ConstU32<{ 103 * 1024 }>;
463 type ControllerOrigin = EnsureRoot<AccountId>;
464 type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;
465 type WeightInfo = weights::cumulus_pallet_xcmp_queue::WeightInfo<Runtime>;
466 type PriceForSiblingDelivery = PriceForSiblingParachainDelivery;
467}
468
469impl cumulus_pallet_xcmp_queue::migration::v5::V5Config for Runtime {
470 type ChannelList = ParachainSystem;
472}
473
474parameter_types! {
475 pub const RelayOrigin: AggregateMessageOrigin = AggregateMessageOrigin::Parent;
476}
477
478pub const PERIOD: u32 = 6 * HOURS;
479pub const OFFSET: u32 = 0;
480
481impl pallet_session::Config for Runtime {
482 type RuntimeEvent = RuntimeEvent;
483 type ValidatorId = <Self as frame_system::Config>::AccountId;
484 type ValidatorIdOf = pallet_collator_selection::IdentityCollator;
486 type ShouldEndSession = pallet_session::PeriodicSessions<ConstU32<PERIOD>, ConstU32<OFFSET>>;
487 type NextSessionRotation = pallet_session::PeriodicSessions<ConstU32<PERIOD>, ConstU32<OFFSET>>;
488 type SessionManager = CollatorSelection;
489 type SessionHandler = <SessionKeys as sp_runtime::traits::OpaqueKeys>::KeyTypeIdProviders;
491 type Keys = SessionKeys;
492 type WeightInfo = weights::pallet_session::WeightInfo<Runtime>;
493}
494
495impl pallet_aura::Config for Runtime {
496 type AuthorityId = AuraId;
497 type DisabledValidators = ();
498 type MaxAuthorities = ConstU32<100_000>;
499 type AllowMultipleBlocksPerSlot = ConstBool<true>;
500 type SlotDuration = ConstU64<SLOT_DURATION>;
501}
502
503parameter_types! {
504 pub const PotId: PalletId = PalletId(*b"PotStake");
505 pub const SessionLength: BlockNumber = 6 * HOURS;
506}
507
508pub type CollatorSelectionUpdateOrigin = EnsureRoot<AccountId>;
509
510impl pallet_collator_selection::Config for Runtime {
511 type RuntimeEvent = RuntimeEvent;
512 type Currency = Balances;
513 type UpdateOrigin = CollatorSelectionUpdateOrigin;
514 type PotId = PotId;
515 type MaxCandidates = ConstU32<100>;
516 type MinEligibleCollators = ConstU32<4>;
517 type MaxInvulnerables = ConstU32<20>;
518 type KickThreshold = ConstU32<PERIOD>;
520 type ValidatorId = <Self as frame_system::Config>::AccountId;
521 type ValidatorIdOf = pallet_collator_selection::IdentityCollator;
522 type ValidatorRegistration = Session;
523 type WeightInfo = weights::pallet_collator_selection::WeightInfo<Runtime>;
524}
525
526parameter_types! {
527 pub const DepositBase: Balance = deposit(1, 88);
529 pub const DepositFactor: Balance = deposit(0, 32);
531}
532
533impl pallet_multisig::Config for Runtime {
534 type RuntimeEvent = RuntimeEvent;
535 type RuntimeCall = RuntimeCall;
536 type Currency = Balances;
537 type DepositBase = DepositBase;
538 type DepositFactor = DepositFactor;
539 type MaxSignatories = ConstU32<100>;
540 type WeightInfo = weights::pallet_multisig::WeightInfo<Runtime>;
541}
542
543impl pallet_utility::Config for Runtime {
544 type RuntimeEvent = RuntimeEvent;
545 type RuntimeCall = RuntimeCall;
546 type PalletsOrigin = OriginCaller;
547 type WeightInfo = weights::pallet_utility::WeightInfo<Runtime>;
548}
549
550construct_runtime!(
552 pub enum Runtime
553 {
554 System: frame_system = 0,
556 ParachainSystem: cumulus_pallet_parachain_system = 1,
557 Timestamp: pallet_timestamp = 2,
558 ParachainInfo: parachain_info = 3,
559
560 Balances: pallet_balances = 10,
562 TransactionPayment: pallet_transaction_payment = 11,
563
564 Authorship: pallet_authorship = 20,
566 CollatorSelection: pallet_collator_selection = 21,
567 Session: pallet_session = 22,
568 Aura: pallet_aura = 23,
569 AuraExt: cumulus_pallet_aura_ext = 24,
570
571 XcmpQueue: cumulus_pallet_xcmp_queue = 30,
573 PolkadotXcm: pallet_xcm = 31,
574 CumulusXcm: cumulus_pallet_xcm = 32,
575
576 Utility: pallet_utility = 40,
578 Multisig: pallet_multisig = 36,
579
580 BridgeRelayers: pallet_bridge_relayers = 47,
582
583 BridgeWestendGrandpa: pallet_bridge_grandpa::<Instance3> = 48,
585 BridgeWestendParachains: pallet_bridge_parachains::<Instance3> = 49,
587 BridgeWestendMessages: pallet_bridge_messages::<Instance3> = 51,
589 XcmOverBridgeHubWestend: pallet_xcm_bridge_hub::<Instance1> = 52,
591
592 BridgePolkadotBulletinGrandpa: pallet_bridge_grandpa::<Instance4> = 60,
598 BridgePolkadotBulletinMessages: pallet_bridge_messages::<Instance4> = 61,
604 XcmOverPolkadotBulletin: pallet_xcm_bridge_hub::<Instance2> = 62,
606
607 BridgeRelayersForPermissionlessLanes: pallet_bridge_relayers::<Instance2> = 63,
609
610 EthereumInboundQueue: snowbridge_pallet_inbound_queue = 80,
611 EthereumOutboundQueue: snowbridge_pallet_outbound_queue = 81,
612 EthereumBeaconClient: snowbridge_pallet_ethereum_client = 82,
613 EthereumSystem: snowbridge_pallet_system = 83,
614
615 MessageQueue: pallet_message_queue = 175,
618 }
619);
620
621pub type BridgeRococoBulletinGrandpa = BridgePolkadotBulletinGrandpa;
623pub type BridgeRococoBulletinMessages = BridgePolkadotBulletinMessages;
625pub type XcmOverRococoBulletin = XcmOverPolkadotBulletin;
627
628bridge_runtime_common::generate_bridge_reject_obsolete_headers_and_messages! {
629 RuntimeCall, AccountId,
630 CheckAndBoostBridgeGrandpaTransactions<
632 Runtime,
633 bridge_common_config::BridgeGrandpaWestendInstance,
634 bridge_to_westend_config::PriorityBoostPerRelayHeader,
635 xcm_config::TreasuryAccount,
636 >,
637 CheckAndBoostBridgeGrandpaTransactions<
638 Runtime,
639 bridge_common_config::BridgeGrandpaRococoBulletinInstance,
640 bridge_to_bulletin_config::PriorityBoostPerRelayHeader,
641 xcm_config::TreasuryAccount,
642 >,
643 CheckAndBoostBridgeParachainsTransactions<
645 Runtime,
646 bridge_common_config::BridgeParachainWestendInstance,
647 bp_bridge_hub_westend::BridgeHubWestend,
648 bridge_to_westend_config::PriorityBoostPerParachainHeader,
649 xcm_config::TreasuryAccount,
650 >,
651 BridgeWestendMessages,
653 BridgeRococoBulletinMessages
654}
655
656#[cfg(feature = "runtime-benchmarks")]
657mod benches {
658 frame_benchmarking::define_benchmarks!(
659 [frame_system, SystemBench::<Runtime>]
660 [frame_system_extensions, SystemExtensionsBench::<Runtime>]
661 [pallet_balances, Balances]
662 [pallet_message_queue, MessageQueue]
663 [pallet_multisig, Multisig]
664 [pallet_session, SessionBench::<Runtime>]
665 [pallet_utility, Utility]
666 [pallet_timestamp, Timestamp]
667 [pallet_transaction_payment, TransactionPayment]
668 [pallet_collator_selection, CollatorSelection]
669 [cumulus_pallet_parachain_system, ParachainSystem]
670 [cumulus_pallet_xcmp_queue, XcmpQueue]
671 [pallet_xcm, PalletXcmExtrinsicsBenchmark::<Runtime>]
673 [pallet_xcm_benchmarks::fungible, XcmBalances]
675 [pallet_xcm_benchmarks::generic, XcmGeneric]
676 [pallet_bridge_grandpa, WestendFinality]
678 [pallet_bridge_parachains, WithinWestend]
679 [pallet_bridge_messages, RococoToWestend]
680 [pallet_bridge_messages, RococoToRococoBulletin]
681 [pallet_bridge_relayers, Legacy]
682 [pallet_bridge_relayers, PermissionlessLanes]
683 [snowbridge_pallet_inbound_queue, EthereumInboundQueue]
685 [snowbridge_pallet_outbound_queue, EthereumOutboundQueue]
686 [snowbridge_pallet_system, EthereumSystem]
687 [snowbridge_pallet_ethereum_client, EthereumBeaconClient]
688 );
689}
690
691cumulus_pallet_parachain_system::register_validate_block! {
692 Runtime = Runtime,
693 BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,
694}
695
696impl_runtime_apis! {
697 impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {
698 fn slot_duration() -> sp_consensus_aura::SlotDuration {
699 sp_consensus_aura::SlotDuration::from_millis(SLOT_DURATION)
700 }
701
702 fn authorities() -> Vec<AuraId> {
703 pallet_aura::Authorities::<Runtime>::get().into_inner()
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) {
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,
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(seed: Option<Vec<u8>>) -> Vec<u8> {
783 SessionKeys::generate(seed)
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::TokenLocation::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 let latest_asset_id: Result<AssetId, ()> = asset.clone().try_into();
851 match latest_asset_id {
852 Ok(asset_id) if asset_id.0 == xcm_config::TokenLocation::get() => {
853 Ok(WeightToFee::weight_to_fee(&weight))
855 },
856 Ok(asset_id) => {
857 log::trace!(target: "xcm::xcm_runtime_apis", "query_weight_to_asset_fee - unhandled asset_id: {asset_id:?}!");
858 Err(XcmPaymentApiError::AssetNotFound)
859 },
860 Err(_) => {
861 log::trace!(target: "xcm::xcm_runtime_apis", "query_weight_to_asset_fee - failed to convert asset: {asset:?}!");
862 Err(XcmPaymentApiError::VersionedConversionFailed)
863 }
864 }
865 }
866
867 fn query_xcm_weight(message: VersionedXcm<()>) -> Result<Weight, XcmPaymentApiError> {
868 PolkadotXcm::query_xcm_weight(message)
869 }
870
871 fn query_delivery_fees(destination: VersionedLocation, message: VersionedXcm<()>) -> Result<VersionedAssets, XcmPaymentApiError> {
872 PolkadotXcm::query_delivery_fees(destination, message)
873 }
874 }
875
876 impl xcm_runtime_apis::dry_run::DryRunApi<Block, RuntimeCall, RuntimeEvent, OriginCaller> for Runtime {
877 fn dry_run_call(origin: OriginCaller, call: RuntimeCall, result_xcms_version: XcmVersion) -> Result<CallDryRunEffects<RuntimeEvent>, XcmDryRunApiError> {
878 PolkadotXcm::dry_run_call::<Runtime, xcm_config::XcmRouter, OriginCaller, RuntimeCall>(origin, call, result_xcms_version)
879 }
880
881 fn dry_run_xcm(origin_location: VersionedLocation, xcm: VersionedXcm<RuntimeCall>) -> Result<XcmDryRunEffects<RuntimeEvent>, XcmDryRunApiError> {
882 PolkadotXcm::dry_run_xcm::<Runtime, xcm_config::XcmRouter, RuntimeCall, xcm_config::XcmConfig>(origin_location, xcm)
883 }
884 }
885
886 impl xcm_runtime_apis::conversions::LocationToAccountApi<Block, AccountId> for Runtime {
887 fn convert_location(location: VersionedLocation) -> Result<
888 AccountId,
889 xcm_runtime_apis::conversions::Error
890 > {
891 xcm_runtime_apis::conversions::LocationToAccountHelper::<
892 AccountId,
893 xcm_config::LocationToAccountId,
894 >::convert_location(location)
895 }
896 }
897
898 impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {
899 fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {
900 ParachainSystem::collect_collation_info(header)
901 }
902 }
903
904 impl cumulus_primitives_core::GetCoreSelectorApi<Block> for Runtime {
905 fn core_selector() -> (CoreSelector, ClaimQueueOffset) {
906 ParachainSystem::core_selector()
907 }
908 }
909
910 impl bp_westend::WestendFinalityApi<Block> for Runtime {
911 fn best_finalized() -> Option<HeaderId<bp_westend::Hash, bp_westend::BlockNumber>> {
912 BridgeWestendGrandpa::best_finalized()
913 }
914 fn free_headers_interval() -> Option<bp_westend::BlockNumber> {
915 <Runtime as pallet_bridge_grandpa::Config<
916 bridge_common_config::BridgeGrandpaWestendInstance
917 >>::FreeHeadersInterval::get()
918 }
919 fn synced_headers_grandpa_info(
920 ) -> Vec<bp_header_chain::StoredHeaderGrandpaInfo<bp_westend::Header>> {
921 BridgeWestendGrandpa::synced_headers_grandpa_info()
922 }
923 }
924
925 impl bp_bridge_hub_westend::BridgeHubWestendFinalityApi<Block> for Runtime {
926 fn best_finalized() -> Option<HeaderId<Hash, BlockNumber>> {
927 BridgeWestendParachains::best_parachain_head_id::<
928 bp_bridge_hub_westend::BridgeHubWestend
929 >().unwrap_or(None)
930 }
931 fn free_headers_interval() -> Option<bp_bridge_hub_westend::BlockNumber> {
932 None
934 }
935 }
936
937 impl bp_bridge_hub_westend::FromBridgeHubWestendInboundLaneApi<Block> for Runtime {
939 fn message_details(
940 lane: LaneIdOf<Runtime, bridge_to_westend_config::WithBridgeHubWestendMessagesInstance>,
941 messages: Vec<(bp_messages::MessagePayload, bp_messages::OutboundMessageDetails)>,
942 ) -> Vec<bp_messages::InboundMessageDetails> {
943 bridge_runtime_common::messages_api::inbound_message_details::<
944 Runtime,
945 bridge_to_westend_config::WithBridgeHubWestendMessagesInstance,
946 >(lane, messages)
947 }
948 }
949
950 impl bp_bridge_hub_westend::ToBridgeHubWestendOutboundLaneApi<Block> for Runtime {
952 fn message_details(
953 lane: LaneIdOf<Runtime, bridge_to_westend_config::WithBridgeHubWestendMessagesInstance>,
954 begin: bp_messages::MessageNonce,
955 end: bp_messages::MessageNonce,
956 ) -> Vec<bp_messages::OutboundMessageDetails> {
957 bridge_runtime_common::messages_api::outbound_message_details::<
958 Runtime,
959 bridge_to_westend_config::WithBridgeHubWestendMessagesInstance,
960 >(lane, begin, end)
961 }
962 }
963
964 impl bp_polkadot_bulletin::PolkadotBulletinFinalityApi<Block> for Runtime {
965 fn best_finalized() -> Option<bp_runtime::HeaderId<bp_polkadot_bulletin::Hash, bp_polkadot_bulletin::BlockNumber>> {
966 BridgePolkadotBulletinGrandpa::best_finalized()
967 }
968
969 fn free_headers_interval() -> Option<bp_polkadot_bulletin::BlockNumber> {
970 <Runtime as pallet_bridge_grandpa::Config<
971 bridge_common_config::BridgeGrandpaRococoBulletinInstance
972 >>::FreeHeadersInterval::get()
973 }
974
975 fn synced_headers_grandpa_info(
976 ) -> Vec<bp_header_chain::StoredHeaderGrandpaInfo<bp_polkadot_bulletin::Header>> {
977 BridgePolkadotBulletinGrandpa::synced_headers_grandpa_info()
978 }
979 }
980
981 impl bp_polkadot_bulletin::FromPolkadotBulletinInboundLaneApi<Block> for Runtime {
982 fn message_details(
983 lane: LaneIdOf<Runtime, bridge_to_bulletin_config::WithRococoBulletinMessagesInstance>,
984 messages: Vec<(bp_messages::MessagePayload, bp_messages::OutboundMessageDetails)>,
985 ) -> Vec<bp_messages::InboundMessageDetails> {
986 bridge_runtime_common::messages_api::inbound_message_details::<
987 Runtime,
988 bridge_to_bulletin_config::WithRococoBulletinMessagesInstance,
989 >(lane, messages)
990 }
991 }
992
993 impl bp_polkadot_bulletin::ToPolkadotBulletinOutboundLaneApi<Block> for Runtime {
994 fn message_details(
995 lane: LaneIdOf<Runtime, bridge_to_bulletin_config::WithRococoBulletinMessagesInstance>,
996 begin: bp_messages::MessageNonce,
997 end: bp_messages::MessageNonce,
998 ) -> Vec<bp_messages::OutboundMessageDetails> {
999 bridge_runtime_common::messages_api::outbound_message_details::<
1000 Runtime,
1001 bridge_to_bulletin_config::WithRococoBulletinMessagesInstance,
1002 >(lane, begin, end)
1003 }
1004 }
1005
1006 impl snowbridge_outbound_queue_runtime_api::OutboundQueueApi<Block, Balance> for Runtime {
1007 fn prove_message(leaf_index: u64) -> Option<snowbridge_pallet_outbound_queue::MerkleProof> {
1008 snowbridge_pallet_outbound_queue::api::prove_message::<Runtime>(leaf_index)
1009 }
1010
1011 fn calculate_fee(command: Command, parameters: Option<PricingParameters<Balance>>) -> Fee<Balance> {
1012 snowbridge_pallet_outbound_queue::api::calculate_fee::<Runtime>(command, parameters)
1013 }
1014 }
1015
1016 impl snowbridge_system_runtime_api::ControlApi<Block> for Runtime {
1017 fn agent_id(location: VersionedLocation) -> Option<AgentId> {
1018 snowbridge_pallet_system::api::agent_id::<Runtime>(location)
1019 }
1020 }
1021
1022 #[cfg(feature = "try-runtime")]
1023 impl frame_try_runtime::TryRuntime<Block> for Runtime {
1024 fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) {
1025 let weight = Executive::try_runtime_upgrade(checks).unwrap();
1026 (weight, RuntimeBlockWeights::get().max_block)
1027 }
1028
1029 fn execute_block(
1030 block: Block,
1031 state_root_check: bool,
1032 signature_check: bool,
1033 select: frame_try_runtime::TryStateSelect,
1034 ) -> Weight {
1035 Executive::try_execute_block(block, state_root_check, signature_check, select).unwrap()
1038 }
1039 }
1040
1041 #[cfg(feature = "runtime-benchmarks")]
1042 impl frame_benchmarking::Benchmark<Block> for Runtime {
1043 fn benchmark_metadata(extra: bool) -> (
1044 Vec<frame_benchmarking::BenchmarkList>,
1045 Vec<frame_support::traits::StorageInfo>,
1046 ) {
1047 use frame_benchmarking::{Benchmarking, BenchmarkList};
1048 use frame_support::traits::StorageInfoTrait;
1049 use frame_system_benchmarking::Pallet as SystemBench;
1050 use frame_system_benchmarking::extensions::Pallet as SystemExtensionsBench;
1051 use cumulus_pallet_session_benchmarking::Pallet as SessionBench;
1052 use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
1053
1054 type XcmBalances = pallet_xcm_benchmarks::fungible::Pallet::<Runtime>;
1058 type XcmGeneric = pallet_xcm_benchmarks::generic::Pallet::<Runtime>;
1059
1060 use pallet_bridge_relayers::benchmarking::Pallet as BridgeRelayersBench;
1061 type WestendFinality = BridgeWestendGrandpa;
1063 type WithinWestend = pallet_bridge_parachains::benchmarking::Pallet::<Runtime, bridge_common_config::BridgeParachainWestendInstance>;
1064 type RococoToWestend = pallet_bridge_messages::benchmarking::Pallet ::<Runtime, bridge_to_westend_config::WithBridgeHubWestendMessagesInstance>;
1065 type RococoToRococoBulletin = pallet_bridge_messages::benchmarking::Pallet ::<Runtime, bridge_to_bulletin_config::WithRococoBulletinMessagesInstance>;
1066 type Legacy = BridgeRelayersBench::<Runtime, bridge_common_config::RelayersForLegacyLaneIdsMessagesInstance>;
1067 type PermissionlessLanes = BridgeRelayersBench::<Runtime, bridge_common_config::RelayersForPermissionlessLanesInstance>;
1068
1069 let mut list = Vec::<BenchmarkList>::new();
1070 list_benchmarks!(list, extra);
1071
1072 let storage_info = AllPalletsWithSystem::storage_info();
1073 (list, storage_info)
1074 }
1075
1076 fn dispatch_benchmark(
1077 config: frame_benchmarking::BenchmarkConfig
1078 ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, alloc::string::String> {
1079 use frame_benchmarking::{Benchmarking, BenchmarkBatch, BenchmarkError};
1080 use sp_storage::TrackedStorageKey;
1081
1082 use frame_system_benchmarking::Pallet as SystemBench;
1083 use frame_system_benchmarking::extensions::Pallet as SystemExtensionsBench;
1084 impl frame_system_benchmarking::Config for Runtime {
1085 fn setup_set_code_requirements(code: &alloc::vec::Vec<u8>) -> Result<(), BenchmarkError> {
1086 ParachainSystem::initialize_for_set_code_benchmark(code.len() as u32);
1087 Ok(())
1088 }
1089
1090 fn verify_set_code() {
1091 System::assert_last_event(cumulus_pallet_parachain_system::Event::<Runtime>::ValidationFunctionStored.into());
1092 }
1093 }
1094
1095 use cumulus_pallet_session_benchmarking::Pallet as SessionBench;
1096 impl cumulus_pallet_session_benchmarking::Config for Runtime {}
1097
1098 use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
1099 impl pallet_xcm::benchmarking::Config for Runtime {
1100 type DeliveryHelper = cumulus_primitives_utility::ToParentDeliveryHelper<
1101 xcm_config::XcmConfig,
1102 ExistentialDepositAsset,
1103 xcm_config::PriceForParentDelivery,
1104 >;
1105
1106 fn reachable_dest() -> Option<Location> {
1107 Some(Parent.into())
1108 }
1109
1110 fn teleportable_asset_and_dest() -> Option<(Asset, Location)> {
1111 Some((
1113 Asset {
1114 fun: Fungible(ExistentialDeposit::get()),
1115 id: AssetId(Parent.into())
1116 },
1117 Parent.into(),
1118 ))
1119 }
1120
1121 fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> {
1122 None
1124 }
1125
1126 fn set_up_complex_asset_transfer(
1127 ) -> Option<(Assets, u32, Location, Box<dyn FnOnce()>)> {
1128 let native_location = Parent.into();
1131 let dest = Parent.into();
1132 pallet_xcm::benchmarking::helpers::native_teleport_as_asset_transfer::<Runtime>(
1133 native_location,
1134 dest
1135 )
1136 }
1137
1138 fn get_asset() -> Asset {
1139 Asset {
1140 id: AssetId(Location::parent()),
1141 fun: Fungible(ExistentialDeposit::get()),
1142 }
1143 }
1144 }
1145
1146 use xcm::latest::prelude::*;
1147 use xcm_config::TokenLocation;
1148
1149 parameter_types! {
1150 pub ExistentialDepositAsset: Option<Asset> = Some((
1151 TokenLocation::get(),
1152 ExistentialDeposit::get()
1153 ).into());
1154 }
1155
1156 impl pallet_xcm_benchmarks::Config for Runtime {
1157 type XcmConfig = xcm_config::XcmConfig;
1158 type AccountIdConverter = xcm_config::LocationToAccountId;
1159 type DeliveryHelper = cumulus_primitives_utility::ToParentDeliveryHelper<
1160 xcm_config::XcmConfig,
1161 ExistentialDepositAsset,
1162 xcm_config::PriceForParentDelivery,
1163 >;
1164 fn valid_destination() -> Result<Location, BenchmarkError> {
1165 Ok(TokenLocation::get())
1166 }
1167 fn worst_case_holding(_depositable_count: u32) -> Assets {
1168 let assets: Vec<Asset> = vec![
1170 Asset {
1171 id: AssetId(TokenLocation::get()),
1172 fun: Fungible(1_000_000 * UNITS),
1173 }
1174 ];
1175 assets.into()
1176 }
1177 }
1178
1179 parameter_types! {
1180 pub const TrustedTeleporter: Option<(Location, Asset)> = Some((
1181 TokenLocation::get(),
1182 Asset { fun: Fungible(UNITS), id: AssetId(TokenLocation::get()) },
1183 ));
1184 pub const CheckedAccount: Option<(AccountId, xcm_builder::MintLocation)> = None;
1185 pub const TrustedReserve: Option<(Location, Asset)> = None;
1186 }
1187
1188 impl pallet_xcm_benchmarks::fungible::Config for Runtime {
1189 type TransactAsset = Balances;
1190
1191 type CheckedAccount = CheckedAccount;
1192 type TrustedTeleporter = TrustedTeleporter;
1193 type TrustedReserve = TrustedReserve;
1194
1195 fn get_asset() -> Asset {
1196 Asset {
1197 id: AssetId(TokenLocation::get()),
1198 fun: Fungible(UNITS),
1199 }
1200 }
1201 }
1202
1203 impl pallet_xcm_benchmarks::generic::Config for Runtime {
1204 type TransactAsset = Balances;
1205 type RuntimeCall = RuntimeCall;
1206
1207 fn worst_case_response() -> (u64, Response) {
1208 (0u64, Response::Version(Default::default()))
1209 }
1210
1211 fn worst_case_asset_exchange() -> Result<(Assets, Assets), BenchmarkError> {
1212 Err(BenchmarkError::Skip)
1213 }
1214
1215 fn universal_alias() -> Result<(Location, Junction), BenchmarkError> {
1216 Err(BenchmarkError::Skip)
1217 }
1218
1219 fn transact_origin_and_runtime_call() -> Result<(Location, RuntimeCall), BenchmarkError> {
1220 Ok((TokenLocation::get(), frame_system::Call::remark_with_event { remark: vec![] }.into()))
1221 }
1222
1223 fn subscribe_origin() -> Result<Location, BenchmarkError> {
1224 Ok(TokenLocation::get())
1225 }
1226
1227 fn claimable_asset() -> Result<(Location, Location, Assets), BenchmarkError> {
1228 let origin = TokenLocation::get();
1229 let assets: Assets = (AssetId(TokenLocation::get()), 1_000 * UNITS).into();
1230 let ticket = Location { parents: 0, interior: Here };
1231 Ok((origin, ticket, assets))
1232 }
1233
1234 fn fee_asset() -> Result<Asset, BenchmarkError> {
1235 Ok(Asset {
1236 id: AssetId(TokenLocation::get()),
1237 fun: Fungible(1_000_000 * UNITS),
1238 })
1239 }
1240
1241 fn unlockable_asset() -> Result<(Location, Location, Asset), BenchmarkError> {
1242 Err(BenchmarkError::Skip)
1243 }
1244
1245 fn export_message_origin_and_destination(
1246 ) -> Result<(Location, NetworkId, InteriorLocation), BenchmarkError> {
1247 let _ = PolkadotXcm::force_xcm_version(
1249 RuntimeOrigin::root(),
1250 Box::new(bridge_to_westend_config::BridgeHubWestendLocation::get()),
1251 XCM_VERSION,
1252 ).map_err(|e| {
1253 log::error!(
1254 "Failed to dispatch `force_xcm_version({:?}, {:?}, {:?})`, error: {:?}",
1255 RuntimeOrigin::root(),
1256 bridge_to_westend_config::BridgeHubWestendLocation::get(),
1257 XCM_VERSION,
1258 e
1259 );
1260 BenchmarkError::Stop("XcmVersion was not stored!")
1261 })?;
1262
1263 let sibling_parachain_location = Location::new(1, [Parachain(5678)]);
1264
1265 use frame_support::traits::fungible::Mutate;
1267 use xcm_executor::traits::ConvertLocation;
1268 frame_support::assert_ok!(
1269 Balances::mint_into(
1270 &xcm_config::LocationToAccountId::convert_location(&sibling_parachain_location).expect("valid AccountId"),
1271 bridge_to_westend_config::BridgeDeposit::get()
1272 .saturating_add(ExistentialDeposit::get())
1273 .saturating_add(UNITS * 5)
1274 )
1275 );
1276
1277 let bridge_destination_universal_location: InteriorLocation = [GlobalConsensus(NetworkId::ByGenesis(WESTEND_GENESIS_HASH)), Parachain(8765)].into();
1279 let locations = XcmOverBridgeHubWestend::bridge_locations(
1280 sibling_parachain_location.clone(),
1281 bridge_destination_universal_location.clone(),
1282 )?;
1283 XcmOverBridgeHubWestend::do_open_bridge(
1284 locations,
1285 bp_messages::LegacyLaneId([1, 2, 3, 4]),
1286 true,
1287 ).map_err(|e| {
1288 log::error!(
1289 "Failed to `XcmOverBridgeHubWestend::open_bridge`({:?}, {:?})`, error: {:?}",
1290 sibling_parachain_location,
1291 bridge_destination_universal_location,
1292 e
1293 );
1294 BenchmarkError::Stop("Bridge was not opened!")
1295 })?;
1296
1297 Ok(
1298 (
1299 sibling_parachain_location,
1300 NetworkId::ByGenesis(WESTEND_GENESIS_HASH),
1301 [Parachain(8765)].into()
1302 )
1303 )
1304 }
1305
1306 fn alias_origin() -> Result<(Location, Location), BenchmarkError> {
1307 Err(BenchmarkError::Skip)
1308 }
1309 }
1310
1311 type XcmBalances = pallet_xcm_benchmarks::fungible::Pallet::<Runtime>;
1312 type XcmGeneric = pallet_xcm_benchmarks::generic::Pallet::<Runtime>;
1313
1314 type WestendFinality = BridgeWestendGrandpa;
1315 type WithinWestend = pallet_bridge_parachains::benchmarking::Pallet::<Runtime, bridge_common_config::BridgeParachainWestendInstance>;
1316 type RococoToWestend = pallet_bridge_messages::benchmarking::Pallet ::<Runtime, bridge_to_westend_config::WithBridgeHubWestendMessagesInstance>;
1317 type RococoToRococoBulletin = pallet_bridge_messages::benchmarking::Pallet ::<Runtime, bridge_to_bulletin_config::WithRococoBulletinMessagesInstance>;
1318 type Legacy = BridgeRelayersBench::<Runtime, bridge_common_config::RelayersForLegacyLaneIdsMessagesInstance>;
1319 type PermissionlessLanes = BridgeRelayersBench::<Runtime, bridge_common_config::RelayersForPermissionlessLanesInstance>;
1320
1321 use bridge_runtime_common::messages_benchmarking::{
1322 prepare_message_delivery_proof_from_grandpa_chain,
1323 prepare_message_delivery_proof_from_parachain,
1324 prepare_message_proof_from_grandpa_chain,
1325 prepare_message_proof_from_parachain,
1326 generate_xcm_builder_bridge_message_sample,
1327 };
1328 use pallet_bridge_messages::benchmarking::{
1329 Config as BridgeMessagesConfig,
1330 MessageDeliveryProofParams,
1331 MessageProofParams,
1332 };
1333
1334 impl BridgeMessagesConfig<bridge_to_westend_config::WithBridgeHubWestendMessagesInstance> for Runtime {
1335 fn is_relayer_rewarded(relayer: &Self::AccountId) -> bool {
1336 let bench_lane_id = <Self as BridgeMessagesConfig<bridge_to_westend_config::WithBridgeHubWestendMessagesInstance>>::bench_lane_id();
1337 use bp_runtime::Chain;
1338 let bridged_chain_id =<Self as pallet_bridge_messages::Config<bridge_to_westend_config::WithBridgeHubWestendMessagesInstance>>::BridgedChain::ID;
1339 pallet_bridge_relayers::Pallet::<Runtime>::relayer_reward(
1340 relayer,
1341 bp_relayers::RewardsAccountParams::new(
1342 bench_lane_id,
1343 bridged_chain_id,
1344 bp_relayers::RewardsAccountOwner::BridgedChain
1345 )
1346 ).is_some()
1347 }
1348
1349 fn prepare_message_proof(
1350 params: MessageProofParams<LaneIdOf<Runtime, bridge_to_westend_config::WithBridgeHubWestendMessagesInstance>>,
1351 ) -> (bridge_to_westend_config::FromWestendBridgeHubMessagesProof<bridge_to_westend_config::WithBridgeHubWestendMessagesInstance>, Weight) {
1352 use cumulus_primitives_core::XcmpMessageSource;
1353 assert!(XcmpQueue::take_outbound_messages(usize::MAX).is_empty());
1354 ParachainSystem::open_outbound_hrmp_channel_for_benchmarks_or_tests(42.into());
1355 let universal_source = bridge_to_westend_config::open_bridge_for_benchmarks::<
1356 Runtime,
1357 bridge_to_westend_config::XcmOverBridgeHubWestendInstance,
1358 xcm_config::LocationToAccountId,
1359 >(params.lane, 42);
1360 prepare_message_proof_from_parachain::<
1361 Runtime,
1362 bridge_common_config::BridgeGrandpaWestendInstance,
1363 bridge_to_westend_config::WithBridgeHubWestendMessagesInstance,
1364 >(params, generate_xcm_builder_bridge_message_sample(universal_source))
1365 }
1366
1367 fn prepare_message_delivery_proof(
1368 params: MessageDeliveryProofParams<AccountId, LaneIdOf<Runtime, bridge_to_westend_config::WithBridgeHubWestendMessagesInstance>>,
1369 ) -> bridge_to_westend_config::ToWestendBridgeHubMessagesDeliveryProof<bridge_to_westend_config::WithBridgeHubWestendMessagesInstance> {
1370 let _ = bridge_to_westend_config::open_bridge_for_benchmarks::<
1371 Runtime,
1372 bridge_to_westend_config::XcmOverBridgeHubWestendInstance,
1373 xcm_config::LocationToAccountId,
1374 >(params.lane, 42);
1375 prepare_message_delivery_proof_from_parachain::<
1376 Runtime,
1377 bridge_common_config::BridgeGrandpaWestendInstance,
1378 bridge_to_westend_config::WithBridgeHubWestendMessagesInstance,
1379 >(params)
1380 }
1381
1382 fn is_message_successfully_dispatched(_nonce: bp_messages::MessageNonce) -> bool {
1383 use cumulus_primitives_core::XcmpMessageSource;
1384 !XcmpQueue::take_outbound_messages(usize::MAX).is_empty()
1385 }
1386 }
1387
1388 impl BridgeMessagesConfig<bridge_to_bulletin_config::WithRococoBulletinMessagesInstance> for Runtime {
1389 fn is_relayer_rewarded(_relayer: &Self::AccountId) -> bool {
1390 true
1392 }
1393
1394 fn prepare_message_proof(
1395 params: MessageProofParams<LaneIdOf<Runtime, bridge_to_bulletin_config::WithRococoBulletinMessagesInstance>>,
1396 ) -> (bridge_to_bulletin_config::FromRococoBulletinMessagesProof<bridge_to_bulletin_config::WithRococoBulletinMessagesInstance>, Weight) {
1397 use cumulus_primitives_core::XcmpMessageSource;
1398 assert!(XcmpQueue::take_outbound_messages(usize::MAX).is_empty());
1399 ParachainSystem::open_outbound_hrmp_channel_for_benchmarks_or_tests(42.into());
1400 let universal_source = bridge_to_bulletin_config::open_bridge_for_benchmarks::<
1401 Runtime,
1402 bridge_to_bulletin_config::XcmOverPolkadotBulletinInstance,
1403 xcm_config::LocationToAccountId,
1404 >(params.lane, 42);
1405 prepare_message_proof_from_grandpa_chain::<
1406 Runtime,
1407 bridge_common_config::BridgeGrandpaRococoBulletinInstance,
1408 bridge_to_bulletin_config::WithRococoBulletinMessagesInstance,
1409 >(params, generate_xcm_builder_bridge_message_sample(universal_source))
1410 }
1411
1412 fn prepare_message_delivery_proof(
1413 params: MessageDeliveryProofParams<AccountId, LaneIdOf<Runtime, bridge_to_bulletin_config::WithRococoBulletinMessagesInstance>>,
1414 ) -> bridge_to_bulletin_config::ToRococoBulletinMessagesDeliveryProof<bridge_to_bulletin_config::WithRococoBulletinMessagesInstance> {
1415 let _ = bridge_to_bulletin_config::open_bridge_for_benchmarks::<
1416 Runtime,
1417 bridge_to_bulletin_config::XcmOverPolkadotBulletinInstance,
1418 xcm_config::LocationToAccountId,
1419 >(params.lane, 42);
1420 prepare_message_delivery_proof_from_grandpa_chain::<
1421 Runtime,
1422 bridge_common_config::BridgeGrandpaRococoBulletinInstance,
1423 bridge_to_bulletin_config::WithRococoBulletinMessagesInstance,
1424 >(params)
1425 }
1426
1427 fn is_message_successfully_dispatched(_nonce: bp_messages::MessageNonce) -> bool {
1428 use cumulus_primitives_core::XcmpMessageSource;
1429 !XcmpQueue::take_outbound_messages(usize::MAX).is_empty()
1430 }
1431 }
1432
1433 use bridge_runtime_common::parachains_benchmarking::prepare_parachain_heads_proof;
1434 use pallet_bridge_parachains::benchmarking::Config as BridgeParachainsConfig;
1435 use pallet_bridge_relayers::benchmarking::{
1436 Pallet as BridgeRelayersBench,
1437 Config as BridgeRelayersConfig,
1438 };
1439
1440 impl BridgeParachainsConfig<bridge_common_config::BridgeParachainWestendInstance> for Runtime {
1441 fn parachains() -> Vec<bp_polkadot_core::parachains::ParaId> {
1442 use bp_runtime::Parachain;
1443 vec![bp_polkadot_core::parachains::ParaId(bp_bridge_hub_westend::BridgeHubWestend::PARACHAIN_ID)]
1444 }
1445
1446 fn prepare_parachain_heads_proof(
1447 parachains: &[bp_polkadot_core::parachains::ParaId],
1448 parachain_head_size: u32,
1449 proof_params: bp_runtime::UnverifiedStorageProofParams,
1450 ) -> (
1451 bp_parachains::RelayBlockNumber,
1452 bp_parachains::RelayBlockHash,
1453 bp_polkadot_core::parachains::ParaHeadsProof,
1454 Vec<(bp_polkadot_core::parachains::ParaId, bp_polkadot_core::parachains::ParaHash)>,
1455 ) {
1456 prepare_parachain_heads_proof::<Runtime, bridge_common_config::BridgeParachainWestendInstance>(
1457 parachains,
1458 parachain_head_size,
1459 proof_params,
1460 )
1461 }
1462 }
1463
1464 impl BridgeRelayersConfig<bridge_common_config::RelayersForLegacyLaneIdsMessagesInstance> for Runtime {
1465 fn prepare_rewards_account(
1466 account_params: bp_relayers::RewardsAccountParams<<Self as pallet_bridge_relayers::Config<bridge_common_config::RelayersForLegacyLaneIdsMessagesInstance>>::LaneId>,
1467 reward: Balance,
1468 ) {
1469 let rewards_account = bp_relayers::PayRewardFromAccount::<
1470 Balances,
1471 AccountId,
1472 <Self as pallet_bridge_relayers::Config<bridge_common_config::RelayersForLegacyLaneIdsMessagesInstance>>::LaneId,
1473 >::rewards_account(account_params);
1474 <Runtime as BridgeRelayersConfig<bridge_common_config::RelayersForLegacyLaneIdsMessagesInstance>>::deposit_account(rewards_account, reward);
1475 }
1476
1477 fn deposit_account(account: AccountId, balance: Balance) {
1478 use frame_support::traits::fungible::Mutate;
1479 Balances::mint_into(&account, balance.saturating_add(ExistentialDeposit::get())).unwrap();
1480 }
1481 }
1482
1483 impl BridgeRelayersConfig<bridge_common_config::RelayersForPermissionlessLanesInstance> for Runtime {
1484 fn prepare_rewards_account(
1485 account_params: bp_relayers::RewardsAccountParams<<Self as pallet_bridge_relayers::Config<bridge_common_config::RelayersForPermissionlessLanesInstance>>::LaneId>,
1486 reward: Balance,
1487 ) {
1488 let rewards_account = bp_relayers::PayRewardFromAccount::<
1489 Balances,
1490 AccountId,
1491 <Self as pallet_bridge_relayers::Config<bridge_common_config::RelayersForPermissionlessLanesInstance>>::LaneId,
1492 >::rewards_account(account_params);
1493 <Runtime as BridgeRelayersConfig<bridge_common_config::RelayersForPermissionlessLanesInstance>>::deposit_account(rewards_account, reward);
1494 }
1495
1496 fn deposit_account(account: AccountId, balance: Balance) {
1497 use frame_support::traits::fungible::Mutate;
1498 Balances::mint_into(&account, balance.saturating_add(ExistentialDeposit::get())).unwrap();
1499 }
1500 }
1501
1502 let whitelist: Vec<TrackedStorageKey> = vec![
1503 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),
1505 hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),
1507 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),
1509 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),
1511 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),
1513 ];
1514
1515 let mut batches = Vec::<BenchmarkBatch>::new();
1516 let params = (&config, &whitelist);
1517 add_benchmarks!(params, batches);
1518
1519 Ok(batches)
1520 }
1521 }
1522
1523 impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
1524 fn build_state(config: Vec<u8>) -> sp_genesis_builder::Result {
1525 build_state::<RuntimeGenesisConfig>(config)
1526 }
1527
1528 fn get_preset(id: &Option<sp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
1529 get_preset::<RuntimeGenesisConfig>(id, &genesis_config_presets::get_preset)
1530 }
1531
1532 fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
1533 genesis_config_presets::preset_names()
1534 }
1535 }
1536
1537 impl xcm_runtime_apis::trusted_query::TrustedQueryApi<Block> for Runtime {
1538 fn is_trusted_reserve(asset: VersionedAsset, location: VersionedLocation) -> xcm_runtime_apis::trusted_query::XcmTrustedQueryResult {
1539 PolkadotXcm::is_trusted_reserve(asset, location)
1540 }
1541 fn is_trusted_teleporter(asset: VersionedAsset, location: VersionedLocation) -> xcm_runtime_apis::trusted_query::XcmTrustedQueryResult {
1542 PolkadotXcm::is_trusted_teleporter(asset, location)
1543 }
1544 }
1545}
1546
1547#[cfg(test)]
1548mod tests {
1549 use super::*;
1550 use codec::Encode;
1551 use sp_runtime::{
1552 generic::Era,
1553 traits::{TransactionExtension, Zero},
1554 };
1555
1556 #[test]
1557 fn ensure_transaction_extension_definition_is_compatible_with_relay() {
1558 use bp_polkadot_core::SuffixedCommonTransactionExtensionExt;
1559
1560 sp_io::TestExternalities::default().execute_with(|| {
1561 frame_system::BlockHash::<Runtime>::insert(BlockNumber::zero(), Hash::default());
1562 let payload: TxExtension = (
1563 frame_system::CheckNonZeroSender::new(),
1564 frame_system::CheckSpecVersion::new(),
1565 frame_system::CheckTxVersion::new(),
1566 frame_system::CheckGenesis::new(),
1567 frame_system::CheckEra::from(Era::Immortal),
1568 frame_system::CheckNonce::from(10),
1569 frame_system::CheckWeight::new(),
1570 pallet_transaction_payment::ChargeTransactionPayment::from(10),
1571 BridgeRejectObsoleteHeadersAndMessages,
1572 (
1573 bridge_to_westend_config::OnBridgeHubRococoRefundBridgeHubWestendMessages::default(),
1574 ),
1575 frame_metadata_hash_extension::CheckMetadataHash::new(false),
1576 cumulus_primitives_storage_weight_reclaim::StorageWeightReclaim::new(),
1577 );
1578
1579 {
1581 let bhr_indirect_payload = bp_bridge_hub_rococo::TransactionExtension::from_params(
1582 VERSION.spec_version,
1583 VERSION.transaction_version,
1584 bp_runtime::TransactionEra::Immortal,
1585 System::block_hash(BlockNumber::zero()),
1586 10,
1587 10,
1588 (((), ()), ((), ())),
1589 );
1590 assert_eq!(payload.encode().split_last().unwrap().1, bhr_indirect_payload.encode());
1591 assert_eq!(
1592 TxExtension::implicit(&payload).unwrap().encode().split_last().unwrap().1,
1593 sp_runtime::traits::TransactionExtension::<RuntimeCall>::implicit(&bhr_indirect_payload).unwrap().encode()
1594 )
1595 }
1596 });
1597 }
1598}