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::*};
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 match asset.try_as::<AssetId>() {
850 Ok(asset_id) if asset_id.0 == xcm_config::TokenLocation::get() => {
851 Ok(WeightToFee::weight_to_fee(&weight))
853 },
854 Ok(asset_id) => {
855 log::trace!(target: "xcm::xcm_runtime_apis", "query_weight_to_asset_fee - unhandled asset_id: {asset_id:?}!");
856 Err(XcmPaymentApiError::AssetNotFound)
857 },
858 Err(_) => {
859 log::trace!(target: "xcm::xcm_runtime_apis", "query_weight_to_asset_fee - failed to convert asset: {asset:?}!");
860 Err(XcmPaymentApiError::VersionedConversionFailed)
861 }
862 }
863 }
864
865 fn query_xcm_weight(message: VersionedXcm<()>) -> Result<Weight, XcmPaymentApiError> {
866 PolkadotXcm::query_xcm_weight(message)
867 }
868
869 fn query_delivery_fees(destination: VersionedLocation, message: VersionedXcm<()>) -> Result<VersionedAssets, XcmPaymentApiError> {
870 PolkadotXcm::query_delivery_fees(destination, message)
871 }
872 }
873
874 impl xcm_runtime_apis::dry_run::DryRunApi<Block, RuntimeCall, RuntimeEvent, OriginCaller> for Runtime {
875 fn dry_run_call(origin: OriginCaller, call: RuntimeCall) -> Result<CallDryRunEffects<RuntimeEvent>, XcmDryRunApiError> {
876 PolkadotXcm::dry_run_call::<Runtime, xcm_config::XcmRouter, OriginCaller, RuntimeCall>(origin, call)
877 }
878
879 fn dry_run_xcm(origin_location: VersionedLocation, xcm: VersionedXcm<RuntimeCall>) -> Result<XcmDryRunEffects<RuntimeEvent>, XcmDryRunApiError> {
880 PolkadotXcm::dry_run_xcm::<Runtime, xcm_config::XcmRouter, RuntimeCall, xcm_config::XcmConfig>(origin_location, xcm)
881 }
882 }
883
884 impl xcm_runtime_apis::conversions::LocationToAccountApi<Block, AccountId> for Runtime {
885 fn convert_location(location: VersionedLocation) -> Result<
886 AccountId,
887 xcm_runtime_apis::conversions::Error
888 > {
889 xcm_runtime_apis::conversions::LocationToAccountHelper::<
890 AccountId,
891 xcm_config::LocationToAccountId,
892 >::convert_location(location)
893 }
894 }
895
896 impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {
897 fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {
898 ParachainSystem::collect_collation_info(header)
899 }
900 }
901
902 impl cumulus_primitives_core::GetCoreSelectorApi<Block> for Runtime {
903 fn core_selector() -> (CoreSelector, ClaimQueueOffset) {
904 ParachainSystem::core_selector()
905 }
906 }
907
908 impl bp_westend::WestendFinalityApi<Block> for Runtime {
909 fn best_finalized() -> Option<HeaderId<bp_westend::Hash, bp_westend::BlockNumber>> {
910 BridgeWestendGrandpa::best_finalized()
911 }
912 fn free_headers_interval() -> Option<bp_westend::BlockNumber> {
913 <Runtime as pallet_bridge_grandpa::Config<
914 bridge_common_config::BridgeGrandpaWestendInstance
915 >>::FreeHeadersInterval::get()
916 }
917 fn synced_headers_grandpa_info(
918 ) -> Vec<bp_header_chain::StoredHeaderGrandpaInfo<bp_westend::Header>> {
919 BridgeWestendGrandpa::synced_headers_grandpa_info()
920 }
921 }
922
923 impl bp_bridge_hub_westend::BridgeHubWestendFinalityApi<Block> for Runtime {
924 fn best_finalized() -> Option<HeaderId<Hash, BlockNumber>> {
925 BridgeWestendParachains::best_parachain_head_id::<
926 bp_bridge_hub_westend::BridgeHubWestend
927 >().unwrap_or(None)
928 }
929 fn free_headers_interval() -> Option<bp_bridge_hub_westend::BlockNumber> {
930 None
932 }
933 }
934
935 impl bp_bridge_hub_westend::FromBridgeHubWestendInboundLaneApi<Block> for Runtime {
937 fn message_details(
938 lane: LaneIdOf<Runtime, bridge_to_westend_config::WithBridgeHubWestendMessagesInstance>,
939 messages: Vec<(bp_messages::MessagePayload, bp_messages::OutboundMessageDetails)>,
940 ) -> Vec<bp_messages::InboundMessageDetails> {
941 bridge_runtime_common::messages_api::inbound_message_details::<
942 Runtime,
943 bridge_to_westend_config::WithBridgeHubWestendMessagesInstance,
944 >(lane, messages)
945 }
946 }
947
948 impl bp_bridge_hub_westend::ToBridgeHubWestendOutboundLaneApi<Block> for Runtime {
950 fn message_details(
951 lane: LaneIdOf<Runtime, bridge_to_westend_config::WithBridgeHubWestendMessagesInstance>,
952 begin: bp_messages::MessageNonce,
953 end: bp_messages::MessageNonce,
954 ) -> Vec<bp_messages::OutboundMessageDetails> {
955 bridge_runtime_common::messages_api::outbound_message_details::<
956 Runtime,
957 bridge_to_westend_config::WithBridgeHubWestendMessagesInstance,
958 >(lane, begin, end)
959 }
960 }
961
962 impl bp_polkadot_bulletin::PolkadotBulletinFinalityApi<Block> for Runtime {
963 fn best_finalized() -> Option<bp_runtime::HeaderId<bp_polkadot_bulletin::Hash, bp_polkadot_bulletin::BlockNumber>> {
964 BridgePolkadotBulletinGrandpa::best_finalized()
965 }
966
967 fn free_headers_interval() -> Option<bp_polkadot_bulletin::BlockNumber> {
968 <Runtime as pallet_bridge_grandpa::Config<
969 bridge_common_config::BridgeGrandpaRococoBulletinInstance
970 >>::FreeHeadersInterval::get()
971 }
972
973 fn synced_headers_grandpa_info(
974 ) -> Vec<bp_header_chain::StoredHeaderGrandpaInfo<bp_polkadot_bulletin::Header>> {
975 BridgePolkadotBulletinGrandpa::synced_headers_grandpa_info()
976 }
977 }
978
979 impl bp_polkadot_bulletin::FromPolkadotBulletinInboundLaneApi<Block> for Runtime {
980 fn message_details(
981 lane: LaneIdOf<Runtime, bridge_to_bulletin_config::WithRococoBulletinMessagesInstance>,
982 messages: Vec<(bp_messages::MessagePayload, bp_messages::OutboundMessageDetails)>,
983 ) -> Vec<bp_messages::InboundMessageDetails> {
984 bridge_runtime_common::messages_api::inbound_message_details::<
985 Runtime,
986 bridge_to_bulletin_config::WithRococoBulletinMessagesInstance,
987 >(lane, messages)
988 }
989 }
990
991 impl bp_polkadot_bulletin::ToPolkadotBulletinOutboundLaneApi<Block> for Runtime {
992 fn message_details(
993 lane: LaneIdOf<Runtime, bridge_to_bulletin_config::WithRococoBulletinMessagesInstance>,
994 begin: bp_messages::MessageNonce,
995 end: bp_messages::MessageNonce,
996 ) -> Vec<bp_messages::OutboundMessageDetails> {
997 bridge_runtime_common::messages_api::outbound_message_details::<
998 Runtime,
999 bridge_to_bulletin_config::WithRococoBulletinMessagesInstance,
1000 >(lane, begin, end)
1001 }
1002 }
1003
1004 impl snowbridge_outbound_queue_runtime_api::OutboundQueueApi<Block, Balance> for Runtime {
1005 fn prove_message(leaf_index: u64) -> Option<snowbridge_pallet_outbound_queue::MerkleProof> {
1006 snowbridge_pallet_outbound_queue::api::prove_message::<Runtime>(leaf_index)
1007 }
1008
1009 fn calculate_fee(command: Command, parameters: Option<PricingParameters<Balance>>) -> Fee<Balance> {
1010 snowbridge_pallet_outbound_queue::api::calculate_fee::<Runtime>(command, parameters)
1011 }
1012 }
1013
1014 impl snowbridge_system_runtime_api::ControlApi<Block> for Runtime {
1015 fn agent_id(location: VersionedLocation) -> Option<AgentId> {
1016 snowbridge_pallet_system::api::agent_id::<Runtime>(location)
1017 }
1018 }
1019
1020 #[cfg(feature = "try-runtime")]
1021 impl frame_try_runtime::TryRuntime<Block> for Runtime {
1022 fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) {
1023 let weight = Executive::try_runtime_upgrade(checks).unwrap();
1024 (weight, RuntimeBlockWeights::get().max_block)
1025 }
1026
1027 fn execute_block(
1028 block: Block,
1029 state_root_check: bool,
1030 signature_check: bool,
1031 select: frame_try_runtime::TryStateSelect,
1032 ) -> Weight {
1033 Executive::try_execute_block(block, state_root_check, signature_check, select).unwrap()
1036 }
1037 }
1038
1039 #[cfg(feature = "runtime-benchmarks")]
1040 impl frame_benchmarking::Benchmark<Block> for Runtime {
1041 fn benchmark_metadata(extra: bool) -> (
1042 Vec<frame_benchmarking::BenchmarkList>,
1043 Vec<frame_support::traits::StorageInfo>,
1044 ) {
1045 use frame_benchmarking::{Benchmarking, BenchmarkList};
1046 use frame_support::traits::StorageInfoTrait;
1047 use frame_system_benchmarking::Pallet as SystemBench;
1048 use frame_system_benchmarking::extensions::Pallet as SystemExtensionsBench;
1049 use cumulus_pallet_session_benchmarking::Pallet as SessionBench;
1050 use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
1051
1052 type XcmBalances = pallet_xcm_benchmarks::fungible::Pallet::<Runtime>;
1056 type XcmGeneric = pallet_xcm_benchmarks::generic::Pallet::<Runtime>;
1057
1058 use pallet_bridge_relayers::benchmarking::Pallet as BridgeRelayersBench;
1059 type WestendFinality = BridgeWestendGrandpa;
1061 type WithinWestend = pallet_bridge_parachains::benchmarking::Pallet::<Runtime, bridge_common_config::BridgeParachainWestendInstance>;
1062 type RococoToWestend = pallet_bridge_messages::benchmarking::Pallet ::<Runtime, bridge_to_westend_config::WithBridgeHubWestendMessagesInstance>;
1063 type RococoToRococoBulletin = pallet_bridge_messages::benchmarking::Pallet ::<Runtime, bridge_to_bulletin_config::WithRococoBulletinMessagesInstance>;
1064 type Legacy = BridgeRelayersBench::<Runtime, bridge_common_config::RelayersForLegacyLaneIdsMessagesInstance>;
1065 type PermissionlessLanes = BridgeRelayersBench::<Runtime, bridge_common_config::RelayersForPermissionlessLanesInstance>;
1066
1067 let mut list = Vec::<BenchmarkList>::new();
1068 list_benchmarks!(list, extra);
1069
1070 let storage_info = AllPalletsWithSystem::storage_info();
1071 (list, storage_info)
1072 }
1073
1074 fn dispatch_benchmark(
1075 config: frame_benchmarking::BenchmarkConfig
1076 ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, alloc::string::String> {
1077 use frame_benchmarking::{Benchmarking, BenchmarkBatch, BenchmarkError};
1078 use sp_storage::TrackedStorageKey;
1079
1080 use frame_system_benchmarking::Pallet as SystemBench;
1081 use frame_system_benchmarking::extensions::Pallet as SystemExtensionsBench;
1082 impl frame_system_benchmarking::Config for Runtime {
1083 fn setup_set_code_requirements(code: &alloc::vec::Vec<u8>) -> Result<(), BenchmarkError> {
1084 ParachainSystem::initialize_for_set_code_benchmark(code.len() as u32);
1085 Ok(())
1086 }
1087
1088 fn verify_set_code() {
1089 System::assert_last_event(cumulus_pallet_parachain_system::Event::<Runtime>::ValidationFunctionStored.into());
1090 }
1091 }
1092
1093 use cumulus_pallet_session_benchmarking::Pallet as SessionBench;
1094 impl cumulus_pallet_session_benchmarking::Config for Runtime {}
1095
1096 use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
1097 impl pallet_xcm::benchmarking::Config for Runtime {
1098 type DeliveryHelper = cumulus_primitives_utility::ToParentDeliveryHelper<
1099 xcm_config::XcmConfig,
1100 ExistentialDepositAsset,
1101 xcm_config::PriceForParentDelivery,
1102 >;
1103
1104 fn reachable_dest() -> Option<Location> {
1105 Some(Parent.into())
1106 }
1107
1108 fn teleportable_asset_and_dest() -> Option<(Asset, Location)> {
1109 Some((
1111 Asset {
1112 fun: Fungible(ExistentialDeposit::get()),
1113 id: AssetId(Parent.into())
1114 },
1115 Parent.into(),
1116 ))
1117 }
1118
1119 fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> {
1120 None
1122 }
1123
1124 fn set_up_complex_asset_transfer(
1125 ) -> Option<(Assets, u32, Location, Box<dyn FnOnce()>)> {
1126 let native_location = Parent.into();
1129 let dest = Parent.into();
1130 pallet_xcm::benchmarking::helpers::native_teleport_as_asset_transfer::<Runtime>(
1131 native_location,
1132 dest
1133 )
1134 }
1135
1136 fn get_asset() -> Asset {
1137 Asset {
1138 id: AssetId(Location::parent()),
1139 fun: Fungible(ExistentialDeposit::get()),
1140 }
1141 }
1142 }
1143
1144 use xcm::latest::prelude::*;
1145 use xcm_config::TokenLocation;
1146
1147 parameter_types! {
1148 pub ExistentialDepositAsset: Option<Asset> = Some((
1149 TokenLocation::get(),
1150 ExistentialDeposit::get()
1151 ).into());
1152 }
1153
1154 impl pallet_xcm_benchmarks::Config for Runtime {
1155 type XcmConfig = xcm_config::XcmConfig;
1156 type AccountIdConverter = xcm_config::LocationToAccountId;
1157 type DeliveryHelper = cumulus_primitives_utility::ToParentDeliveryHelper<
1158 xcm_config::XcmConfig,
1159 ExistentialDepositAsset,
1160 xcm_config::PriceForParentDelivery,
1161 >;
1162 fn valid_destination() -> Result<Location, BenchmarkError> {
1163 Ok(TokenLocation::get())
1164 }
1165 fn worst_case_holding(_depositable_count: u32) -> Assets {
1166 let assets: Vec<Asset> = vec![
1168 Asset {
1169 id: AssetId(TokenLocation::get()),
1170 fun: Fungible(1_000_000 * UNITS),
1171 }
1172 ];
1173 assets.into()
1174 }
1175 }
1176
1177 parameter_types! {
1178 pub const TrustedTeleporter: Option<(Location, Asset)> = Some((
1179 TokenLocation::get(),
1180 Asset { fun: Fungible(UNITS), id: AssetId(TokenLocation::get()) },
1181 ));
1182 pub const CheckedAccount: Option<(AccountId, xcm_builder::MintLocation)> = None;
1183 pub const TrustedReserve: Option<(Location, Asset)> = None;
1184 }
1185
1186 impl pallet_xcm_benchmarks::fungible::Config for Runtime {
1187 type TransactAsset = Balances;
1188
1189 type CheckedAccount = CheckedAccount;
1190 type TrustedTeleporter = TrustedTeleporter;
1191 type TrustedReserve = TrustedReserve;
1192
1193 fn get_asset() -> Asset {
1194 Asset {
1195 id: AssetId(TokenLocation::get()),
1196 fun: Fungible(UNITS),
1197 }
1198 }
1199 }
1200
1201 impl pallet_xcm_benchmarks::generic::Config for Runtime {
1202 type TransactAsset = Balances;
1203 type RuntimeCall = RuntimeCall;
1204
1205 fn worst_case_response() -> (u64, Response) {
1206 (0u64, Response::Version(Default::default()))
1207 }
1208
1209 fn worst_case_asset_exchange() -> Result<(Assets, Assets), BenchmarkError> {
1210 Err(BenchmarkError::Skip)
1211 }
1212
1213 fn universal_alias() -> Result<(Location, Junction), BenchmarkError> {
1214 Err(BenchmarkError::Skip)
1215 }
1216
1217 fn transact_origin_and_runtime_call() -> Result<(Location, RuntimeCall), BenchmarkError> {
1218 Ok((TokenLocation::get(), frame_system::Call::remark_with_event { remark: vec![] }.into()))
1219 }
1220
1221 fn subscribe_origin() -> Result<Location, BenchmarkError> {
1222 Ok(TokenLocation::get())
1223 }
1224
1225 fn claimable_asset() -> Result<(Location, Location, Assets), BenchmarkError> {
1226 let origin = TokenLocation::get();
1227 let assets: Assets = (AssetId(TokenLocation::get()), 1_000 * UNITS).into();
1228 let ticket = Location { parents: 0, interior: Here };
1229 Ok((origin, ticket, assets))
1230 }
1231
1232 fn fee_asset() -> Result<Asset, BenchmarkError> {
1233 Ok(Asset {
1234 id: AssetId(TokenLocation::get()),
1235 fun: Fungible(1_000_000 * UNITS),
1236 })
1237 }
1238
1239 fn unlockable_asset() -> Result<(Location, Location, Asset), BenchmarkError> {
1240 Err(BenchmarkError::Skip)
1241 }
1242
1243 fn export_message_origin_and_destination(
1244 ) -> Result<(Location, NetworkId, InteriorLocation), BenchmarkError> {
1245 let _ = PolkadotXcm::force_xcm_version(
1247 RuntimeOrigin::root(),
1248 Box::new(bridge_to_westend_config::BridgeHubWestendLocation::get()),
1249 XCM_VERSION,
1250 ).map_err(|e| {
1251 log::error!(
1252 "Failed to dispatch `force_xcm_version({:?}, {:?}, {:?})`, error: {:?}",
1253 RuntimeOrigin::root(),
1254 bridge_to_westend_config::BridgeHubWestendLocation::get(),
1255 XCM_VERSION,
1256 e
1257 );
1258 BenchmarkError::Stop("XcmVersion was not stored!")
1259 })?;
1260
1261 let sibling_parachain_location = Location::new(1, [Parachain(5678)]);
1262
1263 use frame_support::traits::fungible::Mutate;
1265 use xcm_executor::traits::ConvertLocation;
1266 frame_support::assert_ok!(
1267 Balances::mint_into(
1268 &xcm_config::LocationToAccountId::convert_location(&sibling_parachain_location).expect("valid AccountId"),
1269 bridge_to_westend_config::BridgeDeposit::get()
1270 .saturating_add(ExistentialDeposit::get())
1271 .saturating_add(UNITS * 5)
1272 )
1273 );
1274
1275 let bridge_destination_universal_location: InteriorLocation = [GlobalConsensus(NetworkId::ByGenesis(WESTEND_GENESIS_HASH)), Parachain(8765)].into();
1277 let locations = XcmOverBridgeHubWestend::bridge_locations(
1278 sibling_parachain_location.clone(),
1279 bridge_destination_universal_location.clone(),
1280 )?;
1281 XcmOverBridgeHubWestend::do_open_bridge(
1282 locations,
1283 bp_messages::LegacyLaneId([1, 2, 3, 4]),
1284 true,
1285 ).map_err(|e| {
1286 log::error!(
1287 "Failed to `XcmOverBridgeHubWestend::open_bridge`({:?}, {:?})`, error: {:?}",
1288 sibling_parachain_location,
1289 bridge_destination_universal_location,
1290 e
1291 );
1292 BenchmarkError::Stop("Bridge was not opened!")
1293 })?;
1294
1295 Ok(
1296 (
1297 sibling_parachain_location,
1298 NetworkId::ByGenesis(WESTEND_GENESIS_HASH),
1299 [Parachain(8765)].into()
1300 )
1301 )
1302 }
1303
1304 fn alias_origin() -> Result<(Location, Location), BenchmarkError> {
1305 Err(BenchmarkError::Skip)
1306 }
1307 }
1308
1309 type XcmBalances = pallet_xcm_benchmarks::fungible::Pallet::<Runtime>;
1310 type XcmGeneric = pallet_xcm_benchmarks::generic::Pallet::<Runtime>;
1311
1312 type WestendFinality = BridgeWestendGrandpa;
1313 type WithinWestend = pallet_bridge_parachains::benchmarking::Pallet::<Runtime, bridge_common_config::BridgeParachainWestendInstance>;
1314 type RococoToWestend = pallet_bridge_messages::benchmarking::Pallet ::<Runtime, bridge_to_westend_config::WithBridgeHubWestendMessagesInstance>;
1315 type RococoToRococoBulletin = pallet_bridge_messages::benchmarking::Pallet ::<Runtime, bridge_to_bulletin_config::WithRococoBulletinMessagesInstance>;
1316 type Legacy = BridgeRelayersBench::<Runtime, bridge_common_config::RelayersForLegacyLaneIdsMessagesInstance>;
1317 type PermissionlessLanes = BridgeRelayersBench::<Runtime, bridge_common_config::RelayersForPermissionlessLanesInstance>;
1318
1319 use bridge_runtime_common::messages_benchmarking::{
1320 prepare_message_delivery_proof_from_grandpa_chain,
1321 prepare_message_delivery_proof_from_parachain,
1322 prepare_message_proof_from_grandpa_chain,
1323 prepare_message_proof_from_parachain,
1324 generate_xcm_builder_bridge_message_sample,
1325 };
1326 use pallet_bridge_messages::benchmarking::{
1327 Config as BridgeMessagesConfig,
1328 MessageDeliveryProofParams,
1329 MessageProofParams,
1330 };
1331
1332 impl BridgeMessagesConfig<bridge_to_westend_config::WithBridgeHubWestendMessagesInstance> for Runtime {
1333 fn is_relayer_rewarded(relayer: &Self::AccountId) -> bool {
1334 let bench_lane_id = <Self as BridgeMessagesConfig<bridge_to_westend_config::WithBridgeHubWestendMessagesInstance>>::bench_lane_id();
1335 use bp_runtime::Chain;
1336 let bridged_chain_id =<Self as pallet_bridge_messages::Config<bridge_to_westend_config::WithBridgeHubWestendMessagesInstance>>::BridgedChain::ID;
1337 pallet_bridge_relayers::Pallet::<Runtime>::relayer_reward(
1338 relayer,
1339 bp_relayers::RewardsAccountParams::new(
1340 bench_lane_id,
1341 bridged_chain_id,
1342 bp_relayers::RewardsAccountOwner::BridgedChain
1343 )
1344 ).is_some()
1345 }
1346
1347 fn prepare_message_proof(
1348 params: MessageProofParams<LaneIdOf<Runtime, bridge_to_westend_config::WithBridgeHubWestendMessagesInstance>>,
1349 ) -> (bridge_to_westend_config::FromWestendBridgeHubMessagesProof<bridge_to_westend_config::WithBridgeHubWestendMessagesInstance>, Weight) {
1350 use cumulus_primitives_core::XcmpMessageSource;
1351 assert!(XcmpQueue::take_outbound_messages(usize::MAX).is_empty());
1352 ParachainSystem::open_outbound_hrmp_channel_for_benchmarks_or_tests(42.into());
1353 let universal_source = bridge_to_westend_config::open_bridge_for_benchmarks::<
1354 Runtime,
1355 bridge_to_westend_config::XcmOverBridgeHubWestendInstance,
1356 xcm_config::LocationToAccountId,
1357 >(params.lane, 42);
1358 prepare_message_proof_from_parachain::<
1359 Runtime,
1360 bridge_common_config::BridgeGrandpaWestendInstance,
1361 bridge_to_westend_config::WithBridgeHubWestendMessagesInstance,
1362 >(params, generate_xcm_builder_bridge_message_sample(universal_source))
1363 }
1364
1365 fn prepare_message_delivery_proof(
1366 params: MessageDeliveryProofParams<AccountId, LaneIdOf<Runtime, bridge_to_westend_config::WithBridgeHubWestendMessagesInstance>>,
1367 ) -> bridge_to_westend_config::ToWestendBridgeHubMessagesDeliveryProof<bridge_to_westend_config::WithBridgeHubWestendMessagesInstance> {
1368 let _ = bridge_to_westend_config::open_bridge_for_benchmarks::<
1369 Runtime,
1370 bridge_to_westend_config::XcmOverBridgeHubWestendInstance,
1371 xcm_config::LocationToAccountId,
1372 >(params.lane, 42);
1373 prepare_message_delivery_proof_from_parachain::<
1374 Runtime,
1375 bridge_common_config::BridgeGrandpaWestendInstance,
1376 bridge_to_westend_config::WithBridgeHubWestendMessagesInstance,
1377 >(params)
1378 }
1379
1380 fn is_message_successfully_dispatched(_nonce: bp_messages::MessageNonce) -> bool {
1381 use cumulus_primitives_core::XcmpMessageSource;
1382 !XcmpQueue::take_outbound_messages(usize::MAX).is_empty()
1383 }
1384 }
1385
1386 impl BridgeMessagesConfig<bridge_to_bulletin_config::WithRococoBulletinMessagesInstance> for Runtime {
1387 fn is_relayer_rewarded(_relayer: &Self::AccountId) -> bool {
1388 true
1390 }
1391
1392 fn prepare_message_proof(
1393 params: MessageProofParams<LaneIdOf<Runtime, bridge_to_bulletin_config::WithRococoBulletinMessagesInstance>>,
1394 ) -> (bridge_to_bulletin_config::FromRococoBulletinMessagesProof<bridge_to_bulletin_config::WithRococoBulletinMessagesInstance>, Weight) {
1395 use cumulus_primitives_core::XcmpMessageSource;
1396 assert!(XcmpQueue::take_outbound_messages(usize::MAX).is_empty());
1397 ParachainSystem::open_outbound_hrmp_channel_for_benchmarks_or_tests(42.into());
1398 let universal_source = bridge_to_bulletin_config::open_bridge_for_benchmarks::<
1399 Runtime,
1400 bridge_to_bulletin_config::XcmOverPolkadotBulletinInstance,
1401 xcm_config::LocationToAccountId,
1402 >(params.lane, 42);
1403 prepare_message_proof_from_grandpa_chain::<
1404 Runtime,
1405 bridge_common_config::BridgeGrandpaRococoBulletinInstance,
1406 bridge_to_bulletin_config::WithRococoBulletinMessagesInstance,
1407 >(params, generate_xcm_builder_bridge_message_sample(universal_source))
1408 }
1409
1410 fn prepare_message_delivery_proof(
1411 params: MessageDeliveryProofParams<AccountId, LaneIdOf<Runtime, bridge_to_bulletin_config::WithRococoBulletinMessagesInstance>>,
1412 ) -> bridge_to_bulletin_config::ToRococoBulletinMessagesDeliveryProof<bridge_to_bulletin_config::WithRococoBulletinMessagesInstance> {
1413 let _ = bridge_to_bulletin_config::open_bridge_for_benchmarks::<
1414 Runtime,
1415 bridge_to_bulletin_config::XcmOverPolkadotBulletinInstance,
1416 xcm_config::LocationToAccountId,
1417 >(params.lane, 42);
1418 prepare_message_delivery_proof_from_grandpa_chain::<
1419 Runtime,
1420 bridge_common_config::BridgeGrandpaRococoBulletinInstance,
1421 bridge_to_bulletin_config::WithRococoBulletinMessagesInstance,
1422 >(params)
1423 }
1424
1425 fn is_message_successfully_dispatched(_nonce: bp_messages::MessageNonce) -> bool {
1426 use cumulus_primitives_core::XcmpMessageSource;
1427 !XcmpQueue::take_outbound_messages(usize::MAX).is_empty()
1428 }
1429 }
1430
1431 use bridge_runtime_common::parachains_benchmarking::prepare_parachain_heads_proof;
1432 use pallet_bridge_parachains::benchmarking::Config as BridgeParachainsConfig;
1433 use pallet_bridge_relayers::benchmarking::{
1434 Pallet as BridgeRelayersBench,
1435 Config as BridgeRelayersConfig,
1436 };
1437
1438 impl BridgeParachainsConfig<bridge_common_config::BridgeParachainWestendInstance> for Runtime {
1439 fn parachains() -> Vec<bp_polkadot_core::parachains::ParaId> {
1440 use bp_runtime::Parachain;
1441 vec![bp_polkadot_core::parachains::ParaId(bp_bridge_hub_westend::BridgeHubWestend::PARACHAIN_ID)]
1442 }
1443
1444 fn prepare_parachain_heads_proof(
1445 parachains: &[bp_polkadot_core::parachains::ParaId],
1446 parachain_head_size: u32,
1447 proof_params: bp_runtime::UnverifiedStorageProofParams,
1448 ) -> (
1449 bp_parachains::RelayBlockNumber,
1450 bp_parachains::RelayBlockHash,
1451 bp_polkadot_core::parachains::ParaHeadsProof,
1452 Vec<(bp_polkadot_core::parachains::ParaId, bp_polkadot_core::parachains::ParaHash)>,
1453 ) {
1454 prepare_parachain_heads_proof::<Runtime, bridge_common_config::BridgeParachainWestendInstance>(
1455 parachains,
1456 parachain_head_size,
1457 proof_params,
1458 )
1459 }
1460 }
1461
1462 impl BridgeRelayersConfig<bridge_common_config::RelayersForLegacyLaneIdsMessagesInstance> for Runtime {
1463 fn prepare_rewards_account(
1464 account_params: bp_relayers::RewardsAccountParams<<Self as pallet_bridge_relayers::Config<bridge_common_config::RelayersForLegacyLaneIdsMessagesInstance>>::LaneId>,
1465 reward: Balance,
1466 ) {
1467 let rewards_account = bp_relayers::PayRewardFromAccount::<
1468 Balances,
1469 AccountId,
1470 <Self as pallet_bridge_relayers::Config<bridge_common_config::RelayersForLegacyLaneIdsMessagesInstance>>::LaneId,
1471 >::rewards_account(account_params);
1472 <Runtime as BridgeRelayersConfig<bridge_common_config::RelayersForLegacyLaneIdsMessagesInstance>>::deposit_account(rewards_account, reward);
1473 }
1474
1475 fn deposit_account(account: AccountId, balance: Balance) {
1476 use frame_support::traits::fungible::Mutate;
1477 Balances::mint_into(&account, balance.saturating_add(ExistentialDeposit::get())).unwrap();
1478 }
1479 }
1480
1481 impl BridgeRelayersConfig<bridge_common_config::RelayersForPermissionlessLanesInstance> for Runtime {
1482 fn prepare_rewards_account(
1483 account_params: bp_relayers::RewardsAccountParams<<Self as pallet_bridge_relayers::Config<bridge_common_config::RelayersForPermissionlessLanesInstance>>::LaneId>,
1484 reward: Balance,
1485 ) {
1486 let rewards_account = bp_relayers::PayRewardFromAccount::<
1487 Balances,
1488 AccountId,
1489 <Self as pallet_bridge_relayers::Config<bridge_common_config::RelayersForPermissionlessLanesInstance>>::LaneId,
1490 >::rewards_account(account_params);
1491 <Runtime as BridgeRelayersConfig<bridge_common_config::RelayersForPermissionlessLanesInstance>>::deposit_account(rewards_account, reward);
1492 }
1493
1494 fn deposit_account(account: AccountId, balance: Balance) {
1495 use frame_support::traits::fungible::Mutate;
1496 Balances::mint_into(&account, balance.saturating_add(ExistentialDeposit::get())).unwrap();
1497 }
1498 }
1499
1500 let whitelist: Vec<TrackedStorageKey> = vec![
1501 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),
1503 hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),
1505 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),
1507 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),
1509 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),
1511 ];
1512
1513 let mut batches = Vec::<BenchmarkBatch>::new();
1514 let params = (&config, &whitelist);
1515 add_benchmarks!(params, batches);
1516
1517 Ok(batches)
1518 }
1519 }
1520
1521 impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
1522 fn build_state(config: Vec<u8>) -> sp_genesis_builder::Result {
1523 build_state::<RuntimeGenesisConfig>(config)
1524 }
1525
1526 fn get_preset(id: &Option<sp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
1527 get_preset::<RuntimeGenesisConfig>(id, &genesis_config_presets::get_preset)
1528 }
1529
1530 fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
1531 genesis_config_presets::preset_names()
1532 }
1533 }
1534
1535 impl xcm_runtime_apis::trusted_query::TrustedQueryApi<Block> for Runtime {
1536 fn is_trusted_reserve(asset: VersionedAsset, location: VersionedLocation) -> xcm_runtime_apis::trusted_query::XcmTrustedQueryResult {
1537 PolkadotXcm::is_trusted_reserve(asset, location)
1538 }
1539 fn is_trusted_teleporter(asset: VersionedAsset, location: VersionedLocation) -> xcm_runtime_apis::trusted_query::XcmTrustedQueryResult {
1540 PolkadotXcm::is_trusted_teleporter(asset, location)
1541 }
1542 }
1543}
1544
1545#[cfg(test)]
1546mod tests {
1547 use super::*;
1548 use codec::Encode;
1549 use sp_runtime::{
1550 generic::Era,
1551 traits::{TransactionExtension, Zero},
1552 };
1553
1554 #[test]
1555 fn ensure_transaction_extension_definition_is_compatible_with_relay() {
1556 use bp_polkadot_core::SuffixedCommonTransactionExtensionExt;
1557
1558 sp_io::TestExternalities::default().execute_with(|| {
1559 frame_system::BlockHash::<Runtime>::insert(BlockNumber::zero(), Hash::default());
1560 let payload: TxExtension = (
1561 frame_system::CheckNonZeroSender::new(),
1562 frame_system::CheckSpecVersion::new(),
1563 frame_system::CheckTxVersion::new(),
1564 frame_system::CheckGenesis::new(),
1565 frame_system::CheckEra::from(Era::Immortal),
1566 frame_system::CheckNonce::from(10),
1567 frame_system::CheckWeight::new(),
1568 pallet_transaction_payment::ChargeTransactionPayment::from(10),
1569 BridgeRejectObsoleteHeadersAndMessages,
1570 (
1571 bridge_to_westend_config::OnBridgeHubRococoRefundBridgeHubWestendMessages::default(),
1572 ),
1573 frame_metadata_hash_extension::CheckMetadataHash::new(false),
1574 cumulus_primitives_storage_weight_reclaim::StorageWeightReclaim::new(),
1575 );
1576
1577 {
1579 let bhr_indirect_payload = bp_bridge_hub_rococo::TransactionExtension::from_params(
1580 VERSION.spec_version,
1581 VERSION.transaction_version,
1582 bp_runtime::TransactionEra::Immortal,
1583 System::block_hash(BlockNumber::zero()),
1584 10,
1585 10,
1586 (((), ()), ((), ())),
1587 );
1588 assert_eq!(payload.encode().split_last().unwrap().1, bhr_indirect_payload.encode());
1589 assert_eq!(
1590 TxExtension::implicit(&payload).unwrap().encode().split_last().unwrap().1,
1591 sp_runtime::traits::TransactionExtension::<RuntimeCall>::implicit(&bhr_indirect_payload).unwrap().encode()
1592 )
1593 }
1594 });
1595 }
1596}