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