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