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 create_runtime_str, generic, impl_opaque_keys,
51 traits::Block as BlockT,
52 transaction_validity::{TransactionSource, TransactionValidity},
53 ApplyExtrinsicResult,
54};
55
56#[cfg(feature = "std")]
57use sp_version::NativeVersion;
58use sp_version::RuntimeVersion;
59
60use cumulus_primitives_core::ParaId;
61use frame_support::{
62 construct_runtime, derive_impl,
63 dispatch::DispatchClass,
64 genesis_builder_helper::{build_state, get_preset},
65 parameter_types,
66 traits::{ConstBool, ConstU32, ConstU64, ConstU8, Get, TransformOrigin},
67 weights::{ConstantMultiplier, Weight, 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};
83use xcm::VersionedLocation;
84use xcm_config::{TreasuryAccount, XcmOriginToTransactDispatchOrigin, XcmRouter};
85
86#[cfg(any(feature = "std", test))]
87pub use sp_runtime::BuildStorage;
88
89use polkadot_runtime_common::{BlockHashCount, SlowAdjustingFeeUpdate};
90use rococo_runtime_constants::system_parachain::{ASSET_HUB_ID, BRIDGE_HUB_ID};
91use snowbridge_core::{
92 outbound::{Command, Fee},
93 AgentId, PricingParameters,
94};
95use xcm::{latest::prelude::*, prelude::*, Version as XcmVersion};
96use xcm_runtime_apis::{
97 dry_run::{CallDryRunEffects, Error as XcmDryRunApiError, XcmDryRunEffects},
98 fees::Error as XcmPaymentApiError,
99};
100
101use weights::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight};
102
103use parachains_common::{
104 impls::DealWithFees, AccountId, Balance, BlockNumber, Hash, Header, Nonce, Signature,
105 AVERAGE_ON_INITIALIZE_RATIO, NORMAL_DISPATCH_RATIO,
106};
107
108#[cfg(feature = "runtime-benchmarks")]
109use alloc::boxed::Box;
110
111pub type Address = MultiAddress<AccountId, ()>;
113
114pub type Block = generic::Block<Header, UncheckedExtrinsic>;
116
117pub type SignedBlock = generic::SignedBlock<Block>;
119
120pub type BlockId = generic::BlockId<Block>;
122
123pub type SignedExtra = (
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 pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
133 BridgeRejectObsoleteHeadersAndMessages,
134 (bridge_to_westend_config::OnBridgeHubRococoRefundBridgeHubWestendMessages,),
135 cumulus_primitives_storage_weight_reclaim::StorageWeightReclaim<Runtime>,
136 frame_metadata_hash_extension::CheckMetadataHash<Runtime>,
137);
138
139pub type UncheckedExtrinsic =
141 generic::UncheckedExtrinsic<Address, RuntimeCall, Signature, SignedExtra>;
142
143pub type Migrations = (
145 pallet_collator_selection::migration::v2::MigrationToV2<Runtime>,
146 pallet_multisig::migrations::v1::MigrateToV1<Runtime>,
147 InitStorageVersions,
148 cumulus_pallet_xcmp_queue::migration::v4::MigrationToV4<Runtime>,
150 cumulus_pallet_xcmp_queue::migration::v5::MigrateV4ToV5<Runtime>,
151 snowbridge_pallet_system::migration::v0::InitializeOnUpgrade<
152 Runtime,
153 ConstU32<BRIDGE_HUB_ID>,
154 ConstU32<ASSET_HUB_ID>,
155 >,
156 pallet_bridge_messages::migration::v1::MigrationToV1<
157 Runtime,
158 bridge_to_westend_config::WithBridgeHubWestendMessagesInstance,
159 >,
160 pallet_bridge_messages::migration::v1::MigrationToV1<
161 Runtime,
162 bridge_to_bulletin_config::WithRococoBulletinMessagesInstance,
163 >,
164 bridge_to_westend_config::migration::FixMessagesV1Migration<
165 Runtime,
166 bridge_to_westend_config::WithBridgeHubWestendMessagesInstance,
167 >,
168 bridge_to_westend_config::migration::StaticToDynamicLanes,
169 bridge_to_bulletin_config::migration::StaticToDynamicLanes,
170 frame_support::migrations::RemoveStorage<
171 BridgeWestendMessagesPalletName,
172 OutboundLanesCongestedSignalsKey,
173 RocksDbWeight,
174 >,
175 frame_support::migrations::RemoveStorage<
176 BridgePolkadotBulletinMessagesPalletName,
177 OutboundLanesCongestedSignalsKey,
178 RocksDbWeight,
179 >,
180 pallet_bridge_relayers::migration::v1::MigrationToV1<Runtime, ()>,
181 pallet_xcm::migration::MigrateToLatestXcmVersion<Runtime>,
183);
184
185parameter_types! {
186 pub const BridgeWestendMessagesPalletName: &'static str = "BridgeWestendMessages";
187 pub const BridgePolkadotBulletinMessagesPalletName: &'static str = "BridgePolkadotBulletinMessages";
188 pub const OutboundLanesCongestedSignalsKey: &'static str = "OutboundLanesCongestedSignals";
189}
190
191pub struct InitStorageVersions;
198
199impl frame_support::traits::OnRuntimeUpgrade for InitStorageVersions {
200 fn on_runtime_upgrade() -> Weight {
201 use frame_support::traits::{GetStorageVersion, StorageVersion};
202 use sp_runtime::traits::Saturating;
203
204 let mut writes = 0;
205
206 if PolkadotXcm::on_chain_storage_version() == StorageVersion::new(0) {
207 PolkadotXcm::in_code_storage_version().put::<PolkadotXcm>();
208 writes.saturating_inc();
209 }
210
211 if Balances::on_chain_storage_version() == StorageVersion::new(0) {
212 Balances::in_code_storage_version().put::<Balances>();
213 writes.saturating_inc();
214 }
215
216 <Runtime as frame_system::Config>::DbWeight::get().reads_writes(2, writes)
217 }
218}
219
220pub type Executive = frame_executive::Executive<
222 Runtime,
223 Block,
224 frame_system::ChainContext<Runtime>,
225 Runtime,
226 AllPalletsWithSystem,
227 Migrations,
228>;
229
230impl_opaque_keys! {
231 pub struct SessionKeys {
232 pub aura: Aura,
233 }
234}
235
236#[sp_version::runtime_version]
237pub const VERSION: RuntimeVersion = RuntimeVersion {
238 spec_name: create_runtime_str!("bridge-hub-rococo"),
239 impl_name: create_runtime_str!("bridge-hub-rococo"),
240 authoring_version: 1,
241 spec_version: 1_016_001,
242 impl_version: 0,
243 apis: RUNTIME_API_VERSIONS,
244 transaction_version: 6,
245 state_version: 1,
246};
247
248#[cfg(feature = "std")]
250pub fn native_version() -> NativeVersion {
251 NativeVersion { runtime_version: VERSION, can_author_with: Default::default() }
252}
253
254parameter_types! {
255 pub const Version: RuntimeVersion = VERSION;
256 pub RuntimeBlockLength: BlockLength =
257 BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);
258 pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()
259 .base_block(BlockExecutionWeight::get())
260 .for_class(DispatchClass::all(), |weights| {
261 weights.base_extrinsic = ExtrinsicBaseWeight::get();
262 })
263 .for_class(DispatchClass::Normal, |weights| {
264 weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);
265 })
266 .for_class(DispatchClass::Operational, |weights| {
267 weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);
268 weights.reserved = Some(
271 MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT
272 );
273 })
274 .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)
275 .build_or_panic();
276 pub const SS58Prefix: u16 = 42;
277}
278
279#[derive_impl(frame_system::config_preludes::ParaChainDefaultConfig)]
282impl frame_system::Config for Runtime {
283 type AccountId = AccountId;
285 type Nonce = Nonce;
287 type Hash = Hash;
289 type Block = Block;
291 type BlockHashCount = BlockHashCount;
293 type Version = Version;
295 type AccountData = pallet_balances::AccountData<Balance>;
297 type DbWeight = RocksDbWeight;
299 type SystemWeightInfo = weights::frame_system::WeightInfo<Runtime>;
301 type BlockWeights = RuntimeBlockWeights;
303 type BlockLength = RuntimeBlockLength;
305 type SS58Prefix = SS58Prefix;
307 type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;
309 type MaxConsumers = frame_support::traits::ConstU32<16>;
310}
311
312impl pallet_timestamp::Config for Runtime {
313 type Moment = u64;
315 type OnTimestampSet = Aura;
316 type MinimumPeriod = ConstU64<0>;
317 type WeightInfo = weights::pallet_timestamp::WeightInfo<Runtime>;
318}
319
320impl pallet_authorship::Config for Runtime {
321 type FindAuthor = pallet_session::FindAccountFromAuthorIndex<Self, Aura>;
322 type EventHandler = (CollatorSelection,);
323}
324
325parameter_types! {
326 pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT;
327}
328
329impl pallet_balances::Config for Runtime {
330 type Balance = Balance;
332 type DustRemoval = ();
333 type RuntimeEvent = RuntimeEvent;
335 type ExistentialDeposit = ExistentialDeposit;
336 type AccountStore = System;
337 type WeightInfo = weights::pallet_balances::WeightInfo<Runtime>;
338 type MaxLocks = ConstU32<50>;
339 type MaxReserves = ConstU32<50>;
340 type ReserveIdentifier = [u8; 8];
341 type RuntimeHoldReason = RuntimeHoldReason;
342 type RuntimeFreezeReason = RuntimeFreezeReason;
343 type FreezeIdentifier = ();
344 type MaxFreezes = ConstU32<0>;
345}
346
347parameter_types! {
348 pub const TransactionByteFee: Balance = MILLICENTS;
350}
351
352impl pallet_transaction_payment::Config for Runtime {
353 type RuntimeEvent = RuntimeEvent;
354 type OnChargeTransaction =
355 pallet_transaction_payment::FungibleAdapter<Balances, DealWithFees<Runtime>>;
356 type OperationalFeeMultiplier = ConstU8<5>;
357 type WeightToFee = WeightToFee;
358 type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;
359 type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Self>;
360}
361
362parameter_types! {
363 pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
364 pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
365}
366
367impl cumulus_pallet_parachain_system::Config for Runtime {
368 type WeightInfo = weights::cumulus_pallet_parachain_system::WeightInfo<Runtime>;
369 type RuntimeEvent = RuntimeEvent;
370 type OnSystemEvent = ();
371 type SelfParaId = parachain_info::Pallet<Runtime>;
372 type OutboundXcmpMessageSource = XcmpQueue;
373 type DmpQueue = frame_support::traits::EnqueueWithOrigin<MessageQueue, RelayOrigin>;
374 type ReservedDmpWeight = ReservedDmpWeight;
375 type XcmpMessageHandler = XcmpQueue;
376 type ReservedXcmpWeight = ReservedXcmpWeight;
377 type CheckAssociatedRelayNumber = RelayNumberMonotonicallyIncreases;
378 type ConsensusHook = ConsensusHook;
379}
380
381type ConsensusHook = cumulus_pallet_aura_ext::FixedVelocityConsensusHook<
382 Runtime,
383 RELAY_CHAIN_SLOT_DURATION_MILLIS,
384 BLOCK_PROCESSING_VELOCITY,
385 UNINCLUDED_SEGMENT_CAPACITY,
386>;
387
388impl parachain_info::Config for Runtime {}
389
390parameter_types! {
391 pub MessageQueueServiceWeight: Weight = Perbill::from_percent(60) * RuntimeBlockWeights::get().max_block;
396}
397
398impl pallet_message_queue::Config for Runtime {
399 type RuntimeEvent = RuntimeEvent;
400 type WeightInfo = weights::pallet_message_queue::WeightInfo<Runtime>;
401 #[cfg(all(not(feature = "std"), feature = "runtime-benchmarks"))]
406 type MessageProcessor =
407 pallet_message_queue::mock_helpers::NoopMessageProcessor<AggregateMessageOrigin>;
408 #[cfg(not(all(not(feature = "std"), feature = "runtime-benchmarks")))]
409 type MessageProcessor = bridge_hub_common::BridgeHubMessageRouter<
410 xcm_builder::ProcessXcmMessage<
411 AggregateMessageOrigin,
412 xcm_executor::XcmExecutor<xcm_config::XcmConfig>,
413 RuntimeCall,
414 >,
415 EthereumOutboundQueue,
416 >;
417 type Size = u32;
418 type QueueChangeHandler = NarrowOriginToSibling<XcmpQueue>;
420 type QueuePausedQuery = NarrowOriginToSibling<XcmpQueue>;
421 type HeapSize = sp_core::ConstU32<{ 103 * 1024 }>;
422 type MaxStale = sp_core::ConstU32<8>;
423 type ServiceWeight = MessageQueueServiceWeight;
424 type IdleMaxServiceWeight = MessageQueueServiceWeight;
425}
426
427impl cumulus_pallet_aura_ext::Config for Runtime {}
428
429parameter_types! {
430 pub FeeAssetId: AssetId = AssetId(xcm_config::TokenLocation::get());
432 pub const BaseDeliveryFee: u128 = CENTS.saturating_mul(3);
434}
435
436pub type PriceForSiblingParachainDelivery = polkadot_runtime_common::xcm_sender::ExponentialPrice<
437 FeeAssetId,
438 BaseDeliveryFee,
439 TransactionByteFee,
440 XcmpQueue,
441>;
442
443impl cumulus_pallet_xcmp_queue::Config for Runtime {
444 type RuntimeEvent = RuntimeEvent;
445 type ChannelInfo = ParachainSystem;
446 type VersionWrapper = PolkadotXcm;
447 type XcmpQueue = TransformOrigin<MessageQueue, AggregateMessageOrigin, ParaId, ParaIdToSibling>;
449 type MaxInboundSuspended = ConstU32<1_000>;
450 type MaxActiveOutboundChannels = ConstU32<128>;
451 type MaxPageSize = ConstU32<{ 103 * 1024 }>;
454 type ControllerOrigin = EnsureRoot<AccountId>;
455 type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;
456 type WeightInfo = weights::cumulus_pallet_xcmp_queue::WeightInfo<Runtime>;
457 type PriceForSiblingDelivery = PriceForSiblingParachainDelivery;
458}
459
460impl cumulus_pallet_xcmp_queue::migration::v5::V5Config for Runtime {
461 type ChannelList = ParachainSystem;
463}
464
465parameter_types! {
466 pub const RelayOrigin: AggregateMessageOrigin = AggregateMessageOrigin::Parent;
467}
468
469pub const PERIOD: u32 = 6 * HOURS;
470pub const OFFSET: u32 = 0;
471
472impl pallet_session::Config for Runtime {
473 type RuntimeEvent = RuntimeEvent;
474 type ValidatorId = <Self as frame_system::Config>::AccountId;
475 type ValidatorIdOf = pallet_collator_selection::IdentityCollator;
477 type ShouldEndSession = pallet_session::PeriodicSessions<ConstU32<PERIOD>, ConstU32<OFFSET>>;
478 type NextSessionRotation = pallet_session::PeriodicSessions<ConstU32<PERIOD>, ConstU32<OFFSET>>;
479 type SessionManager = CollatorSelection;
480 type SessionHandler = <SessionKeys as sp_runtime::traits::OpaqueKeys>::KeyTypeIdProviders;
482 type Keys = SessionKeys;
483 type WeightInfo = weights::pallet_session::WeightInfo<Runtime>;
484}
485
486impl pallet_aura::Config for Runtime {
487 type AuthorityId = AuraId;
488 type DisabledValidators = ();
489 type MaxAuthorities = ConstU32<100_000>;
490 type AllowMultipleBlocksPerSlot = ConstBool<true>;
491 type SlotDuration = ConstU64<SLOT_DURATION>;
492}
493
494parameter_types! {
495 pub const PotId: PalletId = PalletId(*b"PotStake");
496 pub const SessionLength: BlockNumber = 6 * HOURS;
497}
498
499pub type CollatorSelectionUpdateOrigin = EnsureRoot<AccountId>;
500
501impl pallet_collator_selection::Config for Runtime {
502 type RuntimeEvent = RuntimeEvent;
503 type Currency = Balances;
504 type UpdateOrigin = CollatorSelectionUpdateOrigin;
505 type PotId = PotId;
506 type MaxCandidates = ConstU32<100>;
507 type MinEligibleCollators = ConstU32<4>;
508 type MaxInvulnerables = ConstU32<20>;
509 type KickThreshold = ConstU32<PERIOD>;
511 type ValidatorId = <Self as frame_system::Config>::AccountId;
512 type ValidatorIdOf = pallet_collator_selection::IdentityCollator;
513 type ValidatorRegistration = Session;
514 type WeightInfo = weights::pallet_collator_selection::WeightInfo<Runtime>;
515}
516
517parameter_types! {
518 pub const DepositBase: Balance = deposit(1, 88);
520 pub const DepositFactor: Balance = deposit(0, 32);
522}
523
524impl pallet_multisig::Config for Runtime {
525 type RuntimeEvent = RuntimeEvent;
526 type RuntimeCall = RuntimeCall;
527 type Currency = Balances;
528 type DepositBase = DepositBase;
529 type DepositFactor = DepositFactor;
530 type MaxSignatories = ConstU32<100>;
531 type WeightInfo = weights::pallet_multisig::WeightInfo<Runtime>;
532}
533
534impl pallet_utility::Config for Runtime {
535 type RuntimeEvent = RuntimeEvent;
536 type RuntimeCall = RuntimeCall;
537 type PalletsOrigin = OriginCaller;
538 type WeightInfo = weights::pallet_utility::WeightInfo<Runtime>;
539}
540
541construct_runtime!(
543 pub enum Runtime
544 {
545 System: frame_system = 0,
547 ParachainSystem: cumulus_pallet_parachain_system = 1,
548 Timestamp: pallet_timestamp = 2,
549 ParachainInfo: parachain_info = 3,
550
551 Balances: pallet_balances = 10,
553 TransactionPayment: pallet_transaction_payment = 11,
554
555 Authorship: pallet_authorship = 20,
557 CollatorSelection: pallet_collator_selection = 21,
558 Session: pallet_session = 22,
559 Aura: pallet_aura = 23,
560 AuraExt: cumulus_pallet_aura_ext = 24,
561
562 XcmpQueue: cumulus_pallet_xcmp_queue = 30,
564 PolkadotXcm: pallet_xcm = 31,
565 CumulusXcm: cumulus_pallet_xcm = 32,
566
567 Utility: pallet_utility = 40,
569 Multisig: pallet_multisig = 36,
570
571 BridgeRelayers: pallet_bridge_relayers = 47,
573
574 BridgeWestendGrandpa: pallet_bridge_grandpa::<Instance3> = 48,
576 BridgeWestendParachains: pallet_bridge_parachains::<Instance3> = 49,
578 BridgeWestendMessages: pallet_bridge_messages::<Instance3> = 51,
580 XcmOverBridgeHubWestend: pallet_xcm_bridge_hub::<Instance1> = 52,
582
583 BridgePolkadotBulletinGrandpa: pallet_bridge_grandpa::<Instance4> = 60,
589 BridgePolkadotBulletinMessages: pallet_bridge_messages::<Instance4> = 61,
595 XcmOverPolkadotBulletin: pallet_xcm_bridge_hub::<Instance2> = 62,
597
598 BridgeRelayersForPermissionlessLanes: pallet_bridge_relayers::<Instance2> = 63,
600
601 EthereumInboundQueue: snowbridge_pallet_inbound_queue = 80,
602 EthereumOutboundQueue: snowbridge_pallet_outbound_queue = 81,
603 EthereumBeaconClient: snowbridge_pallet_ethereum_client = 82,
604 EthereumSystem: snowbridge_pallet_system = 83,
605
606 MessageQueue: pallet_message_queue = 175,
609 }
610);
611
612pub type BridgeRococoBulletinGrandpa = BridgePolkadotBulletinGrandpa;
614pub type BridgeRococoBulletinMessages = BridgePolkadotBulletinMessages;
616pub type XcmOverRococoBulletin = XcmOverPolkadotBulletin;
618
619bridge_runtime_common::generate_bridge_reject_obsolete_headers_and_messages! {
620 RuntimeCall, AccountId,
621 CheckAndBoostBridgeGrandpaTransactions<
623 Runtime,
624 bridge_common_config::BridgeGrandpaWestendInstance,
625 bridge_to_westend_config::PriorityBoostPerRelayHeader,
626 xcm_config::TreasuryAccount,
627 >,
628 CheckAndBoostBridgeGrandpaTransactions<
629 Runtime,
630 bridge_common_config::BridgeGrandpaRococoBulletinInstance,
631 bridge_to_bulletin_config::PriorityBoostPerRelayHeader,
632 xcm_config::TreasuryAccount,
633 >,
634 CheckAndBoostBridgeParachainsTransactions<
636 Runtime,
637 bridge_common_config::BridgeParachainWestendInstance,
638 bp_bridge_hub_westend::BridgeHubWestend,
639 bridge_to_westend_config::PriorityBoostPerParachainHeader,
640 xcm_config::TreasuryAccount,
641 >,
642 BridgeWestendMessages,
644 BridgeRococoBulletinMessages
645}
646
647#[cfg(feature = "runtime-benchmarks")]
648mod benches {
649 frame_benchmarking::define_benchmarks!(
650 [frame_system, SystemBench::<Runtime>]
651 [pallet_balances, Balances]
652 [pallet_message_queue, MessageQueue]
653 [pallet_multisig, Multisig]
654 [pallet_session, SessionBench::<Runtime>]
655 [pallet_utility, Utility]
656 [pallet_timestamp, Timestamp]
657 [pallet_collator_selection, CollatorSelection]
658 [cumulus_pallet_parachain_system, ParachainSystem]
659 [cumulus_pallet_xcmp_queue, XcmpQueue]
660 [pallet_xcm, PalletXcmExtrinsicsBenchmark::<Runtime>]
662 [pallet_xcm_benchmarks::fungible, XcmBalances]
664 [pallet_xcm_benchmarks::generic, XcmGeneric]
665 [pallet_bridge_grandpa, WestendFinality]
667 [pallet_bridge_parachains, WithinWestend]
668 [pallet_bridge_messages, RococoToWestend]
669 [pallet_bridge_messages, RococoToRococoBulletin]
670 [pallet_bridge_relayers, Legacy]
671 [pallet_bridge_relayers, PermissionlessLanes]
672 [snowbridge_pallet_inbound_queue, EthereumInboundQueue]
674 [snowbridge_pallet_outbound_queue, EthereumOutboundQueue]
675 [snowbridge_pallet_system, EthereumSystem]
676 [snowbridge_pallet_ethereum_client, EthereumBeaconClient]
677 );
678}
679
680cumulus_pallet_parachain_system::register_validate_block! {
681 Runtime = Runtime,
682 BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,
683}
684
685impl_runtime_apis! {
686 impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {
687 fn slot_duration() -> sp_consensus_aura::SlotDuration {
688 sp_consensus_aura::SlotDuration::from_millis(SLOT_DURATION)
689 }
690
691 fn authorities() -> Vec<AuraId> {
692 pallet_aura::Authorities::<Runtime>::get().into_inner()
693 }
694 }
695
696 impl cumulus_primitives_aura::AuraUnincludedSegmentApi<Block> for Runtime {
697 fn can_build_upon(
698 included_hash: <Block as BlockT>::Hash,
699 slot: cumulus_primitives_aura::Slot,
700 ) -> bool {
701 ConsensusHook::can_build_upon(included_hash, slot)
702 }
703 }
704
705 impl sp_api::Core<Block> for Runtime {
706 fn version() -> RuntimeVersion {
707 VERSION
708 }
709
710 fn execute_block(block: Block) {
711 Executive::execute_block(block)
712 }
713
714 fn initialize_block(header: &<Block as BlockT>::Header) -> sp_runtime::ExtrinsicInclusionMode {
715 Executive::initialize_block(header)
716 }
717 }
718
719 impl sp_api::Metadata<Block> for Runtime {
720 fn metadata() -> OpaqueMetadata {
721 OpaqueMetadata::new(Runtime::metadata().into())
722 }
723
724 fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
725 Runtime::metadata_at_version(version)
726 }
727
728 fn metadata_versions() -> alloc::vec::Vec<u32> {
729 Runtime::metadata_versions()
730 }
731 }
732
733 impl sp_block_builder::BlockBuilder<Block> for Runtime {
734 fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
735 Executive::apply_extrinsic(extrinsic)
736 }
737
738 fn finalize_block() -> <Block as BlockT>::Header {
739 Executive::finalize_block()
740 }
741
742 fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
743 data.create_extrinsics()
744 }
745
746 fn check_inherents(
747 block: Block,
748 data: sp_inherents::InherentData,
749 ) -> sp_inherents::CheckInherentsResult {
750 data.check_extrinsics(&block)
751 }
752 }
753
754 impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
755 fn validate_transaction(
756 source: TransactionSource,
757 tx: <Block as BlockT>::Extrinsic,
758 block_hash: <Block as BlockT>::Hash,
759 ) -> TransactionValidity {
760 Executive::validate_transaction(source, tx, block_hash)
761 }
762 }
763
764 impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
765 fn offchain_worker(header: &<Block as BlockT>::Header) {
766 Executive::offchain_worker(header)
767 }
768 }
769
770 impl sp_session::SessionKeys<Block> for Runtime {
771 fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {
772 SessionKeys::generate(seed)
773 }
774
775 fn decode_session_keys(
776 encoded: Vec<u8>,
777 ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {
778 SessionKeys::decode_into_raw_public_keys(&encoded)
779 }
780 }
781
782 impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Nonce> for Runtime {
783 fn account_nonce(account: AccountId) -> Nonce {
784 System::account_nonce(account)
785 }
786 }
787
788 impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {
789 fn query_info(
790 uxt: <Block as BlockT>::Extrinsic,
791 len: u32,
792 ) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo<Balance> {
793 TransactionPayment::query_info(uxt, len)
794 }
795 fn query_fee_details(
796 uxt: <Block as BlockT>::Extrinsic,
797 len: u32,
798 ) -> pallet_transaction_payment::FeeDetails<Balance> {
799 TransactionPayment::query_fee_details(uxt, len)
800 }
801 fn query_weight_to_fee(weight: Weight) -> Balance {
802 TransactionPayment::weight_to_fee(weight)
803 }
804 fn query_length_to_fee(length: u32) -> Balance {
805 TransactionPayment::length_to_fee(length)
806 }
807 }
808
809 impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentCallApi<Block, Balance, RuntimeCall>
810 for Runtime
811 {
812 fn query_call_info(
813 call: RuntimeCall,
814 len: u32,
815 ) -> pallet_transaction_payment::RuntimeDispatchInfo<Balance> {
816 TransactionPayment::query_call_info(call, len)
817 }
818 fn query_call_fee_details(
819 call: RuntimeCall,
820 len: u32,
821 ) -> pallet_transaction_payment::FeeDetails<Balance> {
822 TransactionPayment::query_call_fee_details(call, len)
823 }
824 fn query_weight_to_fee(weight: Weight) -> Balance {
825 TransactionPayment::weight_to_fee(weight)
826 }
827 fn query_length_to_fee(length: u32) -> Balance {
828 TransactionPayment::length_to_fee(length)
829 }
830 }
831
832 impl xcm_runtime_apis::fees::XcmPaymentApi<Block> for Runtime {
833 fn query_acceptable_payment_assets(xcm_version: xcm::Version) -> Result<Vec<VersionedAssetId>, XcmPaymentApiError> {
834 let acceptable_assets = vec![AssetId(xcm_config::TokenLocation::get())];
835 PolkadotXcm::query_acceptable_payment_assets(xcm_version, acceptable_assets)
836 }
837
838 fn query_weight_to_asset_fee(weight: Weight, asset: VersionedAssetId) -> Result<u128, XcmPaymentApiError> {
839 let latest_asset_id: Result<AssetId, ()> = asset.clone().try_into();
840 match latest_asset_id {
841 Ok(asset_id) if asset_id.0 == xcm_config::TokenLocation::get() => {
842 Ok(WeightToFee::weight_to_fee(&weight))
844 },
845 Ok(asset_id) => {
846 log::trace!(target: "xcm::xcm_runtime_apis", "query_weight_to_asset_fee - unhandled asset_id: {asset_id:?}!");
847 Err(XcmPaymentApiError::AssetNotFound)
848 },
849 Err(_) => {
850 log::trace!(target: "xcm::xcm_runtime_apis", "query_weight_to_asset_fee - failed to convert asset: {asset:?}!");
851 Err(XcmPaymentApiError::VersionedConversionFailed)
852 }
853 }
854 }
855
856 fn query_xcm_weight(message: VersionedXcm<()>) -> Result<Weight, XcmPaymentApiError> {
857 PolkadotXcm::query_xcm_weight(message)
858 }
859
860 fn query_delivery_fees(destination: VersionedLocation, message: VersionedXcm<()>) -> Result<VersionedAssets, XcmPaymentApiError> {
861 PolkadotXcm::query_delivery_fees(destination, message)
862 }
863 }
864
865 impl xcm_runtime_apis::dry_run::DryRunApi<Block, RuntimeCall, RuntimeEvent, OriginCaller> for Runtime {
866 fn dry_run_call(origin: OriginCaller, call: RuntimeCall, result_xcms_version: XcmVersion) -> Result<CallDryRunEffects<RuntimeEvent>, XcmDryRunApiError> {
867 PolkadotXcm::dry_run_call::<Runtime, xcm_config::XcmRouter, OriginCaller, RuntimeCall>(origin, call, result_xcms_version)
868 }
869
870 fn dry_run_xcm(origin_location: VersionedLocation, xcm: VersionedXcm<RuntimeCall>) -> Result<XcmDryRunEffects<RuntimeEvent>, XcmDryRunApiError> {
871 PolkadotXcm::dry_run_xcm::<Runtime, xcm_config::XcmRouter, RuntimeCall, xcm_config::XcmConfig>(origin_location, xcm)
872 }
873 }
874
875 impl xcm_runtime_apis::conversions::LocationToAccountApi<Block, AccountId> for Runtime {
876 fn convert_location(location: VersionedLocation) -> Result<
877 AccountId,
878 xcm_runtime_apis::conversions::Error
879 > {
880 xcm_runtime_apis::conversions::LocationToAccountHelper::<
881 AccountId,
882 xcm_config::LocationToAccountId,
883 >::convert_location(location)
884 }
885 }
886
887 impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {
888 fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {
889 ParachainSystem::collect_collation_info(header)
890 }
891 }
892
893 impl bp_westend::WestendFinalityApi<Block> for Runtime {
894 fn best_finalized() -> Option<HeaderId<bp_westend::Hash, bp_westend::BlockNumber>> {
895 BridgeWestendGrandpa::best_finalized()
896 }
897 fn free_headers_interval() -> Option<bp_westend::BlockNumber> {
898 <Runtime as pallet_bridge_grandpa::Config<
899 bridge_common_config::BridgeGrandpaWestendInstance
900 >>::FreeHeadersInterval::get()
901 }
902 fn synced_headers_grandpa_info(
903 ) -> Vec<bp_header_chain::StoredHeaderGrandpaInfo<bp_westend::Header>> {
904 BridgeWestendGrandpa::synced_headers_grandpa_info()
905 }
906 }
907
908 impl bp_bridge_hub_westend::BridgeHubWestendFinalityApi<Block> for Runtime {
909 fn best_finalized() -> Option<HeaderId<Hash, BlockNumber>> {
910 BridgeWestendParachains::best_parachain_head_id::<
911 bp_bridge_hub_westend::BridgeHubWestend
912 >().unwrap_or(None)
913 }
914 fn free_headers_interval() -> Option<bp_bridge_hub_westend::BlockNumber> {
915 None
917 }
918 }
919
920 impl bp_bridge_hub_westend::FromBridgeHubWestendInboundLaneApi<Block> for Runtime {
922 fn message_details(
923 lane: LaneIdOf<Runtime, bridge_to_westend_config::WithBridgeHubWestendMessagesInstance>,
924 messages: Vec<(bp_messages::MessagePayload, bp_messages::OutboundMessageDetails)>,
925 ) -> Vec<bp_messages::InboundMessageDetails> {
926 bridge_runtime_common::messages_api::inbound_message_details::<
927 Runtime,
928 bridge_to_westend_config::WithBridgeHubWestendMessagesInstance,
929 >(lane, messages)
930 }
931 }
932
933 impl bp_bridge_hub_westend::ToBridgeHubWestendOutboundLaneApi<Block> for Runtime {
935 fn message_details(
936 lane: LaneIdOf<Runtime, bridge_to_westend_config::WithBridgeHubWestendMessagesInstance>,
937 begin: bp_messages::MessageNonce,
938 end: bp_messages::MessageNonce,
939 ) -> Vec<bp_messages::OutboundMessageDetails> {
940 bridge_runtime_common::messages_api::outbound_message_details::<
941 Runtime,
942 bridge_to_westend_config::WithBridgeHubWestendMessagesInstance,
943 >(lane, begin, end)
944 }
945 }
946
947 impl bp_polkadot_bulletin::PolkadotBulletinFinalityApi<Block> for Runtime {
948 fn best_finalized() -> Option<bp_runtime::HeaderId<bp_polkadot_bulletin::Hash, bp_polkadot_bulletin::BlockNumber>> {
949 BridgePolkadotBulletinGrandpa::best_finalized()
950 }
951
952 fn free_headers_interval() -> Option<bp_polkadot_bulletin::BlockNumber> {
953 <Runtime as pallet_bridge_grandpa::Config<
954 bridge_common_config::BridgeGrandpaRococoBulletinInstance
955 >>::FreeHeadersInterval::get()
956 }
957
958 fn synced_headers_grandpa_info(
959 ) -> Vec<bp_header_chain::StoredHeaderGrandpaInfo<bp_polkadot_bulletin::Header>> {
960 BridgePolkadotBulletinGrandpa::synced_headers_grandpa_info()
961 }
962 }
963
964 impl bp_polkadot_bulletin::FromPolkadotBulletinInboundLaneApi<Block> for Runtime {
965 fn message_details(
966 lane: LaneIdOf<Runtime, bridge_to_bulletin_config::WithRococoBulletinMessagesInstance>,
967 messages: Vec<(bp_messages::MessagePayload, bp_messages::OutboundMessageDetails)>,
968 ) -> Vec<bp_messages::InboundMessageDetails> {
969 bridge_runtime_common::messages_api::inbound_message_details::<
970 Runtime,
971 bridge_to_bulletin_config::WithRococoBulletinMessagesInstance,
972 >(lane, messages)
973 }
974 }
975
976 impl bp_polkadot_bulletin::ToPolkadotBulletinOutboundLaneApi<Block> for Runtime {
977 fn message_details(
978 lane: LaneIdOf<Runtime, bridge_to_bulletin_config::WithRococoBulletinMessagesInstance>,
979 begin: bp_messages::MessageNonce,
980 end: bp_messages::MessageNonce,
981 ) -> Vec<bp_messages::OutboundMessageDetails> {
982 bridge_runtime_common::messages_api::outbound_message_details::<
983 Runtime,
984 bridge_to_bulletin_config::WithRococoBulletinMessagesInstance,
985 >(lane, begin, end)
986 }
987 }
988
989 impl snowbridge_outbound_queue_runtime_api::OutboundQueueApi<Block, Balance> for Runtime {
990 fn prove_message(leaf_index: u64) -> Option<snowbridge_pallet_outbound_queue::MerkleProof> {
991 snowbridge_pallet_outbound_queue::api::prove_message::<Runtime>(leaf_index)
992 }
993
994 fn calculate_fee(command: Command, parameters: Option<PricingParameters<Balance>>) -> Fee<Balance> {
995 snowbridge_pallet_outbound_queue::api::calculate_fee::<Runtime>(command, parameters)
996 }
997 }
998
999 impl snowbridge_system_runtime_api::ControlApi<Block> for Runtime {
1000 fn agent_id(location: VersionedLocation) -> Option<AgentId> {
1001 snowbridge_pallet_system::api::agent_id::<Runtime>(location)
1002 }
1003 }
1004
1005 #[cfg(feature = "try-runtime")]
1006 impl frame_try_runtime::TryRuntime<Block> for Runtime {
1007 fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) {
1008 let weight = Executive::try_runtime_upgrade(checks).unwrap();
1009 (weight, RuntimeBlockWeights::get().max_block)
1010 }
1011
1012 fn execute_block(
1013 block: Block,
1014 state_root_check: bool,
1015 signature_check: bool,
1016 select: frame_try_runtime::TryStateSelect,
1017 ) -> Weight {
1018 Executive::try_execute_block(block, state_root_check, signature_check, select).unwrap()
1021 }
1022 }
1023
1024 #[cfg(feature = "runtime-benchmarks")]
1025 impl frame_benchmarking::Benchmark<Block> for Runtime {
1026 fn benchmark_metadata(extra: bool) -> (
1027 Vec<frame_benchmarking::BenchmarkList>,
1028 Vec<frame_support::traits::StorageInfo>,
1029 ) {
1030 use frame_benchmarking::{Benchmarking, BenchmarkList};
1031 use frame_support::traits::StorageInfoTrait;
1032 use frame_system_benchmarking::Pallet as SystemBench;
1033 use cumulus_pallet_session_benchmarking::Pallet as SessionBench;
1034 use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
1035
1036 type XcmBalances = pallet_xcm_benchmarks::fungible::Pallet::<Runtime>;
1040 type XcmGeneric = pallet_xcm_benchmarks::generic::Pallet::<Runtime>;
1041
1042 use pallet_bridge_relayers::benchmarking::Pallet as BridgeRelayersBench;
1043 type WestendFinality = BridgeWestendGrandpa;
1045 type WithinWestend = pallet_bridge_parachains::benchmarking::Pallet::<Runtime, bridge_common_config::BridgeParachainWestendInstance>;
1046 type RococoToWestend = pallet_bridge_messages::benchmarking::Pallet ::<Runtime, bridge_to_westend_config::WithBridgeHubWestendMessagesInstance>;
1047 type RococoToRococoBulletin = pallet_bridge_messages::benchmarking::Pallet ::<Runtime, bridge_to_bulletin_config::WithRococoBulletinMessagesInstance>;
1048 type Legacy = BridgeRelayersBench::<Runtime, bridge_common_config::RelayersForLegacyLaneIdsMessagesInstance>;
1049 type PermissionlessLanes = BridgeRelayersBench::<Runtime, bridge_common_config::RelayersForPermissionlessLanesInstance>;
1050
1051 let mut list = Vec::<BenchmarkList>::new();
1052 list_benchmarks!(list, extra);
1053
1054 let storage_info = AllPalletsWithSystem::storage_info();
1055 (list, storage_info)
1056 }
1057
1058 fn dispatch_benchmark(
1059 config: frame_benchmarking::BenchmarkConfig
1060 ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {
1061 use frame_benchmarking::{Benchmarking, BenchmarkBatch, BenchmarkError};
1062 use sp_storage::TrackedStorageKey;
1063
1064 use frame_system_benchmarking::Pallet as SystemBench;
1065 impl frame_system_benchmarking::Config for Runtime {
1066 fn setup_set_code_requirements(code: &alloc::vec::Vec<u8>) -> Result<(), BenchmarkError> {
1067 ParachainSystem::initialize_for_set_code_benchmark(code.len() as u32);
1068 Ok(())
1069 }
1070
1071 fn verify_set_code() {
1072 System::assert_last_event(cumulus_pallet_parachain_system::Event::<Runtime>::ValidationFunctionStored.into());
1073 }
1074 }
1075
1076 use cumulus_pallet_session_benchmarking::Pallet as SessionBench;
1077 impl cumulus_pallet_session_benchmarking::Config for Runtime {}
1078
1079 use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
1080 impl pallet_xcm::benchmarking::Config for Runtime {
1081 type DeliveryHelper = cumulus_primitives_utility::ToParentDeliveryHelper<
1082 xcm_config::XcmConfig,
1083 ExistentialDepositAsset,
1084 xcm_config::PriceForParentDelivery,
1085 >;
1086
1087 fn reachable_dest() -> Option<Location> {
1088 Some(Parent.into())
1089 }
1090
1091 fn teleportable_asset_and_dest() -> Option<(Asset, Location)> {
1092 Some((
1094 Asset {
1095 fun: Fungible(ExistentialDeposit::get()),
1096 id: AssetId(Parent.into())
1097 },
1098 Parent.into(),
1099 ))
1100 }
1101
1102 fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> {
1103 None
1105 }
1106
1107 fn set_up_complex_asset_transfer(
1108 ) -> Option<(Assets, u32, Location, Box<dyn FnOnce()>)> {
1109 let native_location = Parent.into();
1112 let dest = Parent.into();
1113 pallet_xcm::benchmarking::helpers::native_teleport_as_asset_transfer::<Runtime>(
1114 native_location,
1115 dest
1116 )
1117 }
1118
1119 fn get_asset() -> Asset {
1120 Asset {
1121 id: AssetId(Location::parent()),
1122 fun: Fungible(ExistentialDeposit::get()),
1123 }
1124 }
1125 }
1126
1127 use xcm::latest::prelude::*;
1128 use xcm_config::TokenLocation;
1129
1130 parameter_types! {
1131 pub ExistentialDepositAsset: Option<Asset> = Some((
1132 TokenLocation::get(),
1133 ExistentialDeposit::get()
1134 ).into());
1135 }
1136
1137 impl pallet_xcm_benchmarks::Config for Runtime {
1138 type XcmConfig = xcm_config::XcmConfig;
1139 type AccountIdConverter = xcm_config::LocationToAccountId;
1140 type DeliveryHelper = cumulus_primitives_utility::ToParentDeliveryHelper<
1141 xcm_config::XcmConfig,
1142 ExistentialDepositAsset,
1143 xcm_config::PriceForParentDelivery,
1144 >;
1145 fn valid_destination() -> Result<Location, BenchmarkError> {
1146 Ok(TokenLocation::get())
1147 }
1148 fn worst_case_holding(_depositable_count: u32) -> Assets {
1149 let assets: Vec<Asset> = vec![
1151 Asset {
1152 id: AssetId(TokenLocation::get()),
1153 fun: Fungible(1_000_000 * UNITS),
1154 }
1155 ];
1156 assets.into()
1157 }
1158 }
1159
1160 parameter_types! {
1161 pub const TrustedTeleporter: Option<(Location, Asset)> = Some((
1162 TokenLocation::get(),
1163 Asset { fun: Fungible(UNITS), id: AssetId(TokenLocation::get()) },
1164 ));
1165 pub const CheckedAccount: Option<(AccountId, xcm_builder::MintLocation)> = None;
1166 pub const TrustedReserve: Option<(Location, Asset)> = None;
1167 }
1168
1169 impl pallet_xcm_benchmarks::fungible::Config for Runtime {
1170 type TransactAsset = Balances;
1171
1172 type CheckedAccount = CheckedAccount;
1173 type TrustedTeleporter = TrustedTeleporter;
1174 type TrustedReserve = TrustedReserve;
1175
1176 fn get_asset() -> Asset {
1177 Asset {
1178 id: AssetId(TokenLocation::get()),
1179 fun: Fungible(UNITS),
1180 }
1181 }
1182 }
1183
1184 impl pallet_xcm_benchmarks::generic::Config for Runtime {
1185 type TransactAsset = Balances;
1186 type RuntimeCall = RuntimeCall;
1187
1188 fn worst_case_response() -> (u64, Response) {
1189 (0u64, Response::Version(Default::default()))
1190 }
1191
1192 fn worst_case_asset_exchange() -> Result<(Assets, Assets), BenchmarkError> {
1193 Err(BenchmarkError::Skip)
1194 }
1195
1196 fn universal_alias() -> Result<(Location, Junction), BenchmarkError> {
1197 Err(BenchmarkError::Skip)
1198 }
1199
1200 fn transact_origin_and_runtime_call() -> Result<(Location, RuntimeCall), BenchmarkError> {
1201 Ok((TokenLocation::get(), frame_system::Call::remark_with_event { remark: vec![] }.into()))
1202 }
1203
1204 fn subscribe_origin() -> Result<Location, BenchmarkError> {
1205 Ok(TokenLocation::get())
1206 }
1207
1208 fn claimable_asset() -> Result<(Location, Location, Assets), BenchmarkError> {
1209 let origin = TokenLocation::get();
1210 let assets: Assets = (AssetId(TokenLocation::get()), 1_000 * UNITS).into();
1211 let ticket = Location { parents: 0, interior: Here };
1212 Ok((origin, ticket, assets))
1213 }
1214
1215 fn fee_asset() -> Result<Asset, BenchmarkError> {
1216 Ok(Asset {
1217 id: AssetId(TokenLocation::get()),
1218 fun: Fungible(1_000_000 * UNITS),
1219 })
1220 }
1221
1222 fn unlockable_asset() -> Result<(Location, Location, Asset), BenchmarkError> {
1223 Err(BenchmarkError::Skip)
1224 }
1225
1226 fn export_message_origin_and_destination(
1227 ) -> Result<(Location, NetworkId, InteriorLocation), BenchmarkError> {
1228 let _ = PolkadotXcm::force_xcm_version(
1230 RuntimeOrigin::root(),
1231 Box::new(bridge_to_westend_config::BridgeHubWestendLocation::get()),
1232 XCM_VERSION,
1233 ).map_err(|e| {
1234 log::error!(
1235 "Failed to dispatch `force_xcm_version({:?}, {:?}, {:?})`, error: {:?}",
1236 RuntimeOrigin::root(),
1237 bridge_to_westend_config::BridgeHubWestendLocation::get(),
1238 XCM_VERSION,
1239 e
1240 );
1241 BenchmarkError::Stop("XcmVersion was not stored!")
1242 })?;
1243
1244 let sibling_parachain_location = Location::new(1, [Parachain(5678)]);
1245
1246 use frame_support::traits::fungible::Mutate;
1248 use xcm_executor::traits::ConvertLocation;
1249 frame_support::assert_ok!(
1250 Balances::mint_into(
1251 &xcm_config::LocationToAccountId::convert_location(&sibling_parachain_location).expect("valid AccountId"),
1252 bridge_to_westend_config::BridgeDeposit::get()
1253 .saturating_add(ExistentialDeposit::get())
1254 .saturating_add(UNITS * 5)
1255 )
1256 );
1257
1258 let bridge_destination_universal_location: InteriorLocation = [GlobalConsensus(NetworkId::Westend), Parachain(8765)].into();
1260 let locations = XcmOverBridgeHubWestend::bridge_locations(
1261 sibling_parachain_location.clone(),
1262 bridge_destination_universal_location.clone(),
1263 )?;
1264 XcmOverBridgeHubWestend::do_open_bridge(
1265 locations,
1266 bp_messages::LegacyLaneId([1, 2, 3, 4]),
1267 true,
1268 ).map_err(|e| {
1269 log::error!(
1270 "Failed to `XcmOverBridgeHubWestend::open_bridge`({:?}, {:?})`, error: {:?}",
1271 sibling_parachain_location,
1272 bridge_destination_universal_location,
1273 e
1274 );
1275 BenchmarkError::Stop("Bridge was not opened!")
1276 })?;
1277
1278 Ok(
1279 (
1280 sibling_parachain_location,
1281 NetworkId::Westend,
1282 [Parachain(8765)].into()
1283 )
1284 )
1285 }
1286
1287 fn alias_origin() -> Result<(Location, Location), BenchmarkError> {
1288 Err(BenchmarkError::Skip)
1289 }
1290 }
1291
1292 type XcmBalances = pallet_xcm_benchmarks::fungible::Pallet::<Runtime>;
1293 type XcmGeneric = pallet_xcm_benchmarks::generic::Pallet::<Runtime>;
1294
1295 type WestendFinality = BridgeWestendGrandpa;
1296 type WithinWestend = pallet_bridge_parachains::benchmarking::Pallet::<Runtime, bridge_common_config::BridgeParachainWestendInstance>;
1297 type RococoToWestend = pallet_bridge_messages::benchmarking::Pallet ::<Runtime, bridge_to_westend_config::WithBridgeHubWestendMessagesInstance>;
1298 type RococoToRococoBulletin = pallet_bridge_messages::benchmarking::Pallet ::<Runtime, bridge_to_bulletin_config::WithRococoBulletinMessagesInstance>;
1299 type Legacy = BridgeRelayersBench::<Runtime, bridge_common_config::RelayersForLegacyLaneIdsMessagesInstance>;
1300 type PermissionlessLanes = BridgeRelayersBench::<Runtime, bridge_common_config::RelayersForPermissionlessLanesInstance>;
1301
1302 use bridge_runtime_common::messages_benchmarking::{
1303 prepare_message_delivery_proof_from_grandpa_chain,
1304 prepare_message_delivery_proof_from_parachain,
1305 prepare_message_proof_from_grandpa_chain,
1306 prepare_message_proof_from_parachain,
1307 generate_xcm_builder_bridge_message_sample,
1308 };
1309 use pallet_bridge_messages::benchmarking::{
1310 Config as BridgeMessagesConfig,
1311 MessageDeliveryProofParams,
1312 MessageProofParams,
1313 };
1314
1315 impl BridgeMessagesConfig<bridge_to_westend_config::WithBridgeHubWestendMessagesInstance> for Runtime {
1316 fn is_relayer_rewarded(relayer: &Self::AccountId) -> bool {
1317 let bench_lane_id = <Self as BridgeMessagesConfig<bridge_to_westend_config::WithBridgeHubWestendMessagesInstance>>::bench_lane_id();
1318 use bp_runtime::Chain;
1319 let bridged_chain_id =<Self as pallet_bridge_messages::Config<bridge_to_westend_config::WithBridgeHubWestendMessagesInstance>>::BridgedChain::ID;
1320 pallet_bridge_relayers::Pallet::<Runtime>::relayer_reward(
1321 relayer,
1322 bp_relayers::RewardsAccountParams::new(
1323 bench_lane_id,
1324 bridged_chain_id,
1325 bp_relayers::RewardsAccountOwner::BridgedChain
1326 )
1327 ).is_some()
1328 }
1329
1330 fn prepare_message_proof(
1331 params: MessageProofParams<LaneIdOf<Runtime, bridge_to_westend_config::WithBridgeHubWestendMessagesInstance>>,
1332 ) -> (bridge_to_westend_config::FromWestendBridgeHubMessagesProof<bridge_to_westend_config::WithBridgeHubWestendMessagesInstance>, Weight) {
1333 use cumulus_primitives_core::XcmpMessageSource;
1334 assert!(XcmpQueue::take_outbound_messages(usize::MAX).is_empty());
1335 ParachainSystem::open_outbound_hrmp_channel_for_benchmarks_or_tests(42.into());
1336 let universal_source = bridge_to_westend_config::open_bridge_for_benchmarks::<
1337 Runtime,
1338 bridge_to_westend_config::XcmOverBridgeHubWestendInstance,
1339 xcm_config::LocationToAccountId,
1340 >(params.lane, 42);
1341 prepare_message_proof_from_parachain::<
1342 Runtime,
1343 bridge_common_config::BridgeGrandpaWestendInstance,
1344 bridge_to_westend_config::WithBridgeHubWestendMessagesInstance,
1345 >(params, generate_xcm_builder_bridge_message_sample(universal_source))
1346 }
1347
1348 fn prepare_message_delivery_proof(
1349 params: MessageDeliveryProofParams<AccountId, LaneIdOf<Runtime, bridge_to_westend_config::WithBridgeHubWestendMessagesInstance>>,
1350 ) -> bridge_to_westend_config::ToWestendBridgeHubMessagesDeliveryProof<bridge_to_westend_config::WithBridgeHubWestendMessagesInstance> {
1351 let _ = bridge_to_westend_config::open_bridge_for_benchmarks::<
1352 Runtime,
1353 bridge_to_westend_config::XcmOverBridgeHubWestendInstance,
1354 xcm_config::LocationToAccountId,
1355 >(params.lane, 42);
1356 prepare_message_delivery_proof_from_parachain::<
1357 Runtime,
1358 bridge_common_config::BridgeGrandpaWestendInstance,
1359 bridge_to_westend_config::WithBridgeHubWestendMessagesInstance,
1360 >(params)
1361 }
1362
1363 fn is_message_successfully_dispatched(_nonce: bp_messages::MessageNonce) -> bool {
1364 use cumulus_primitives_core::XcmpMessageSource;
1365 !XcmpQueue::take_outbound_messages(usize::MAX).is_empty()
1366 }
1367 }
1368
1369 impl BridgeMessagesConfig<bridge_to_bulletin_config::WithRococoBulletinMessagesInstance> for Runtime {
1370 fn is_relayer_rewarded(_relayer: &Self::AccountId) -> bool {
1371 true
1373 }
1374
1375 fn prepare_message_proof(
1376 params: MessageProofParams<LaneIdOf<Runtime, bridge_to_bulletin_config::WithRococoBulletinMessagesInstance>>,
1377 ) -> (bridge_to_bulletin_config::FromRococoBulletinMessagesProof<bridge_to_bulletin_config::WithRococoBulletinMessagesInstance>, Weight) {
1378 use cumulus_primitives_core::XcmpMessageSource;
1379 assert!(XcmpQueue::take_outbound_messages(usize::MAX).is_empty());
1380 ParachainSystem::open_outbound_hrmp_channel_for_benchmarks_or_tests(42.into());
1381 let universal_source = bridge_to_bulletin_config::open_bridge_for_benchmarks::<
1382 Runtime,
1383 bridge_to_bulletin_config::XcmOverPolkadotBulletinInstance,
1384 xcm_config::LocationToAccountId,
1385 >(params.lane, 42);
1386 prepare_message_proof_from_grandpa_chain::<
1387 Runtime,
1388 bridge_common_config::BridgeGrandpaRococoBulletinInstance,
1389 bridge_to_bulletin_config::WithRococoBulletinMessagesInstance,
1390 >(params, generate_xcm_builder_bridge_message_sample(universal_source))
1391 }
1392
1393 fn prepare_message_delivery_proof(
1394 params: MessageDeliveryProofParams<AccountId, LaneIdOf<Runtime, bridge_to_bulletin_config::WithRococoBulletinMessagesInstance>>,
1395 ) -> bridge_to_bulletin_config::ToRococoBulletinMessagesDeliveryProof<bridge_to_bulletin_config::WithRococoBulletinMessagesInstance> {
1396 let _ = bridge_to_bulletin_config::open_bridge_for_benchmarks::<
1397 Runtime,
1398 bridge_to_bulletin_config::XcmOverPolkadotBulletinInstance,
1399 xcm_config::LocationToAccountId,
1400 >(params.lane, 42);
1401 prepare_message_delivery_proof_from_grandpa_chain::<
1402 Runtime,
1403 bridge_common_config::BridgeGrandpaRococoBulletinInstance,
1404 bridge_to_bulletin_config::WithRococoBulletinMessagesInstance,
1405 >(params)
1406 }
1407
1408 fn is_message_successfully_dispatched(_nonce: bp_messages::MessageNonce) -> bool {
1409 use cumulus_primitives_core::XcmpMessageSource;
1410 !XcmpQueue::take_outbound_messages(usize::MAX).is_empty()
1411 }
1412 }
1413
1414 use bridge_runtime_common::parachains_benchmarking::prepare_parachain_heads_proof;
1415 use pallet_bridge_parachains::benchmarking::Config as BridgeParachainsConfig;
1416 use pallet_bridge_relayers::benchmarking::{
1417 Pallet as BridgeRelayersBench,
1418 Config as BridgeRelayersConfig,
1419 };
1420
1421 impl BridgeParachainsConfig<bridge_common_config::BridgeParachainWestendInstance> for Runtime {
1422 fn parachains() -> Vec<bp_polkadot_core::parachains::ParaId> {
1423 use bp_runtime::Parachain;
1424 vec![bp_polkadot_core::parachains::ParaId(bp_bridge_hub_westend::BridgeHubWestend::PARACHAIN_ID)]
1425 }
1426
1427 fn prepare_parachain_heads_proof(
1428 parachains: &[bp_polkadot_core::parachains::ParaId],
1429 parachain_head_size: u32,
1430 proof_params: bp_runtime::UnverifiedStorageProofParams,
1431 ) -> (
1432 bp_parachains::RelayBlockNumber,
1433 bp_parachains::RelayBlockHash,
1434 bp_polkadot_core::parachains::ParaHeadsProof,
1435 Vec<(bp_polkadot_core::parachains::ParaId, bp_polkadot_core::parachains::ParaHash)>,
1436 ) {
1437 prepare_parachain_heads_proof::<Runtime, bridge_common_config::BridgeParachainWestendInstance>(
1438 parachains,
1439 parachain_head_size,
1440 proof_params,
1441 )
1442 }
1443 }
1444
1445 impl BridgeRelayersConfig<bridge_common_config::RelayersForLegacyLaneIdsMessagesInstance> for Runtime {
1446 fn prepare_rewards_account(
1447 account_params: bp_relayers::RewardsAccountParams<<Self as pallet_bridge_relayers::Config<bridge_common_config::RelayersForLegacyLaneIdsMessagesInstance>>::LaneId>,
1448 reward: Balance,
1449 ) {
1450 let rewards_account = bp_relayers::PayRewardFromAccount::<
1451 Balances,
1452 AccountId,
1453 <Self as pallet_bridge_relayers::Config<bridge_common_config::RelayersForLegacyLaneIdsMessagesInstance>>::LaneId,
1454 >::rewards_account(account_params);
1455 <Runtime as BridgeRelayersConfig<bridge_common_config::RelayersForLegacyLaneIdsMessagesInstance>>::deposit_account(rewards_account, reward);
1456 }
1457
1458 fn deposit_account(account: AccountId, balance: Balance) {
1459 use frame_support::traits::fungible::Mutate;
1460 Balances::mint_into(&account, balance.saturating_add(ExistentialDeposit::get())).unwrap();
1461 }
1462 }
1463
1464 impl BridgeRelayersConfig<bridge_common_config::RelayersForPermissionlessLanesInstance> for Runtime {
1465 fn prepare_rewards_account(
1466 account_params: bp_relayers::RewardsAccountParams<<Self as pallet_bridge_relayers::Config<bridge_common_config::RelayersForPermissionlessLanesInstance>>::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::RelayersForPermissionlessLanesInstance>>::LaneId,
1473 >::rewards_account(account_params);
1474 <Runtime as BridgeRelayersConfig<bridge_common_config::RelayersForPermissionlessLanesInstance>>::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 let whitelist: Vec<TrackedStorageKey> = vec![
1484 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),
1486 hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),
1488 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),
1490 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),
1492 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),
1494 ];
1495
1496 let mut batches = Vec::<BenchmarkBatch>::new();
1497 let params = (&config, &whitelist);
1498 add_benchmarks!(params, batches);
1499
1500 Ok(batches)
1501 }
1502 }
1503
1504 impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
1505 fn build_state(config: Vec<u8>) -> sp_genesis_builder::Result {
1506 build_state::<RuntimeGenesisConfig>(config)
1507 }
1508
1509 fn get_preset(id: &Option<sp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
1510 get_preset::<RuntimeGenesisConfig>(id, &genesis_config_presets::get_preset)
1511 }
1512
1513 fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
1514 genesis_config_presets::preset_names()
1515 }
1516 }
1517}
1518
1519#[cfg(test)]
1520mod tests {
1521 use super::*;
1522 use codec::Encode;
1523 use sp_runtime::{
1524 generic::Era,
1525 traits::{SignedExtension, Zero},
1526 };
1527
1528 #[test]
1529 fn ensure_signed_extension_definition_is_compatible_with_relay() {
1530 use bp_polkadot_core::SuffixedCommonSignedExtensionExt;
1531
1532 sp_io::TestExternalities::default().execute_with(|| {
1533 frame_system::BlockHash::<Runtime>::insert(BlockNumber::zero(), Hash::default());
1534 let payload: SignedExtra = (
1535 frame_system::CheckNonZeroSender::new(),
1536 frame_system::CheckSpecVersion::new(),
1537 frame_system::CheckTxVersion::new(),
1538 frame_system::CheckGenesis::new(),
1539 frame_system::CheckEra::from(Era::Immortal),
1540 frame_system::CheckNonce::from(10),
1541 frame_system::CheckWeight::new(),
1542 pallet_transaction_payment::ChargeTransactionPayment::from(10),
1543 BridgeRejectObsoleteHeadersAndMessages,
1544 (
1545 bridge_to_westend_config::OnBridgeHubRococoRefundBridgeHubWestendMessages::default(),
1546 ),
1547 cumulus_primitives_storage_weight_reclaim::StorageWeightReclaim::new(),
1548 frame_metadata_hash_extension::CheckMetadataHash::new(false),
1549 );
1550
1551 {
1553 let bhr_indirect_payload = bp_bridge_hub_rococo::SignedExtension::from_params(
1554 VERSION.spec_version,
1555 VERSION.transaction_version,
1556 bp_runtime::TransactionEra::Immortal,
1557 System::block_hash(BlockNumber::zero()),
1558 10,
1559 10,
1560 (((), ()), ((), ())),
1561 );
1562 assert_eq!(payload.encode().split_last().unwrap().1, bhr_indirect_payload.encode());
1563 assert_eq!(
1564 payload.additional_signed().unwrap().encode().split_last().unwrap().1,
1565 bhr_indirect_payload.additional_signed().unwrap().encode()
1566 )
1567 }
1568 });
1569 }
1570}