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