1#![cfg_attr(not(feature = "std"), no_std)]
24#![recursion_limit = "256"]
26
27#[cfg(feature = "std")]
29include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
30
31pub mod bridge_common_config;
32pub mod bridge_to_bulletin_config;
33pub mod bridge_to_ethereum_config;
34pub mod bridge_to_westend_config;
35mod genesis_config_presets;
36mod weights;
37pub mod xcm_config;
38
39extern crate alloc;
40
41use alloc::{vec, vec::Vec};
42use bridge_runtime_common::extensions::{
43 CheckAndBoostBridgeGrandpaTransactions, CheckAndBoostBridgeParachainsTransactions,
44};
45use cumulus_pallet_parachain_system::RelayNumberMonotonicallyIncreases;
46use pallet_bridge_messages::LaneIdOf;
47use sp_api::impl_runtime_apis;
48use sp_core::{crypto::KeyTypeId, OpaqueMetadata};
49use sp_runtime::{
50 generic, impl_opaque_keys,
51 traits::Block as BlockT,
52 transaction_validity::{TransactionSource, TransactionValidity},
53 ApplyExtrinsicResult,
54};
55
56#[cfg(feature = "std")]
57use sp_version::NativeVersion;
58use sp_version::RuntimeVersion;
59
60use cumulus_primitives_core::{ClaimQueueOffset, CoreSelector, ParaId};
61use frame_support::{
62 construct_runtime, derive_impl,
63 dispatch::DispatchClass,
64 genesis_builder_helper::{build_state, get_preset},
65 parameter_types,
66 traits::{ConstBool, ConstU32, ConstU64, ConstU8, Get, TransformOrigin},
67 weights::{ConstantMultiplier, Weight, WeightToFee as _},
68 PalletId,
69};
70use frame_system::{
71 limits::{BlockLength, BlockWeights},
72 EnsureRoot,
73};
74use testnet_parachains_constants::rococo::{consensus::*, currency::*, fee::WeightToFee, time::*};
75
76use bp_runtime::HeaderId;
77use bridge_hub_common::{
78 message_queue::{NarrowOriginToSibling, ParaIdToSibling},
79 AggregateMessageOrigin,
80};
81pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;
82pub use sp_runtime::{MultiAddress, Perbill, Permill};
83
84#[cfg(feature = "runtime-benchmarks")]
85use xcm::latest::WESTEND_GENESIS_HASH;
86use xcm::VersionedLocation;
87use xcm_config::{TreasuryAccount, XcmOriginToTransactDispatchOrigin, XcmRouter};
88
89#[cfg(any(feature = "std", test))]
90pub use sp_runtime::BuildStorage;
91
92use polkadot_runtime_common::{BlockHashCount, SlowAdjustingFeeUpdate};
93use rococo_runtime_constants::system_parachain::{ASSET_HUB_ID, BRIDGE_HUB_ID};
94use snowbridge_core::{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 frame_system::CheckNonZeroSender<Runtime>,
129 frame_system::CheckSpecVersion<Runtime>,
130 frame_system::CheckTxVersion<Runtime>,
131 frame_system::CheckGenesis<Runtime>,
132 frame_system::CheckEra<Runtime>,
133 frame_system::CheckNonce<Runtime>,
134 frame_system::CheckWeight<Runtime>,
135 pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
136 BridgeRejectObsoleteHeadersAndMessages,
137 (bridge_to_westend_config::OnBridgeHubRococoRefundBridgeHubWestendMessages,),
138 frame_metadata_hash_extension::CheckMetadataHash<Runtime>,
139 ),
140>;
141
142pub type UncheckedExtrinsic =
144 generic::UncheckedExtrinsic<Address, RuntimeCall, Signature, TxExtension>;
145
146pub type Migrations = (
148 pallet_collator_selection::migration::v2::MigrationToV2<Runtime>,
149 pallet_multisig::migrations::v1::MigrateToV1<Runtime>,
150 InitStorageVersions,
151 cumulus_pallet_xcmp_queue::migration::v4::MigrationToV4<Runtime>,
153 cumulus_pallet_xcmp_queue::migration::v5::MigrateV4ToV5<Runtime>,
154 snowbridge_pallet_system::migration::v0::InitializeOnUpgrade<
155 Runtime,
156 ConstU32<BRIDGE_HUB_ID>,
157 ConstU32<ASSET_HUB_ID>,
158 >,
159 pallet_bridge_messages::migration::v1::MigrationToV1<
160 Runtime,
161 bridge_to_westend_config::WithBridgeHubWestendMessagesInstance,
162 >,
163 pallet_bridge_messages::migration::v1::MigrationToV1<
164 Runtime,
165 bridge_to_bulletin_config::WithRococoBulletinMessagesInstance,
166 >,
167 bridge_to_westend_config::migration::FixMessagesV1Migration<
168 Runtime,
169 bridge_to_westend_config::WithBridgeHubWestendMessagesInstance,
170 >,
171 bridge_to_westend_config::migration::StaticToDynamicLanes,
172 frame_support::migrations::RemoveStorage<
173 BridgeWestendMessagesPalletName,
174 OutboundLanesCongestedSignalsKey,
175 RocksDbWeight,
176 >,
177 frame_support::migrations::RemoveStorage<
178 BridgePolkadotBulletinMessagesPalletName,
179 OutboundLanesCongestedSignalsKey,
180 RocksDbWeight,
181 >,
182 pallet_bridge_relayers::migration::v1::MigrationToV1<
183 Runtime,
184 bridge_common_config::RelayersForLegacyLaneIdsMessagesInstance,
185 bp_messages::LegacyLaneId,
186 >,
187 pallet_session::migrations::v1::MigrateV0ToV1<
188 Runtime,
189 pallet_session::migrations::v1::InitOffenceSeverity<Runtime>,
190 >,
191 pallet_xcm::migration::MigrateToLatestXcmVersion<Runtime>,
193 cumulus_pallet_aura_ext::migration::MigrateV0ToV1<Runtime>,
194);
195
196parameter_types! {
197 pub const BridgeWestendMessagesPalletName: &'static str = "BridgeWestendMessages";
198 pub const BridgePolkadotBulletinMessagesPalletName: &'static str = "BridgePolkadotBulletinMessages";
199 pub const OutboundLanesCongestedSignalsKey: &'static str = "OutboundLanesCongestedSignals";
200}
201
202pub struct InitStorageVersions;
209
210impl frame_support::traits::OnRuntimeUpgrade for InitStorageVersions {
211 fn on_runtime_upgrade() -> Weight {
212 use frame_support::traits::{GetStorageVersion, StorageVersion};
213 use sp_runtime::traits::Saturating;
214
215 let mut writes = 0;
216
217 if PolkadotXcm::on_chain_storage_version() == StorageVersion::new(0) {
218 PolkadotXcm::in_code_storage_version().put::<PolkadotXcm>();
219 writes.saturating_inc();
220 }
221
222 if Balances::on_chain_storage_version() == StorageVersion::new(0) {
223 Balances::in_code_storage_version().put::<Balances>();
224 writes.saturating_inc();
225 }
226
227 <Runtime as frame_system::Config>::DbWeight::get().reads_writes(2, writes)
228 }
229}
230
231pub type Executive = frame_executive::Executive<
233 Runtime,
234 Block,
235 frame_system::ChainContext<Runtime>,
236 Runtime,
237 AllPalletsWithSystem,
238 Migrations,
239>;
240
241impl_opaque_keys! {
242 pub struct SessionKeys {
243 pub aura: Aura,
244 }
245}
246
247#[sp_version::runtime_version]
248pub const VERSION: RuntimeVersion = RuntimeVersion {
249 spec_name: alloc::borrow::Cow::Borrowed("bridge-hub-rococo"),
250 impl_name: alloc::borrow::Cow::Borrowed("bridge-hub-rococo"),
251 authoring_version: 1,
252 spec_version: 1_018_001,
253 impl_version: 0,
254 apis: RUNTIME_API_VERSIONS,
255 transaction_version: 6,
256 system_version: 1,
257};
258
259#[cfg(feature = "std")]
261pub fn native_version() -> NativeVersion {
262 NativeVersion { runtime_version: VERSION, can_author_with: Default::default() }
263}
264
265parameter_types! {
266 pub const Version: RuntimeVersion = VERSION;
267 pub RuntimeBlockLength: BlockLength =
268 BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);
269 pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()
270 .base_block(BlockExecutionWeight::get())
271 .for_class(DispatchClass::all(), |weights| {
272 weights.base_extrinsic = ExtrinsicBaseWeight::get();
273 })
274 .for_class(DispatchClass::Normal, |weights| {
275 weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);
276 })
277 .for_class(DispatchClass::Operational, |weights| {
278 weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);
279 weights.reserved = Some(
282 MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT
283 );
284 })
285 .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)
286 .build_or_panic();
287 pub const SS58Prefix: u16 = 42;
288}
289
290#[derive_impl(frame_system::config_preludes::ParaChainDefaultConfig)]
293impl frame_system::Config for Runtime {
294 type AccountId = AccountId;
296 type Nonce = Nonce;
298 type Hash = Hash;
300 type Block = Block;
302 type BlockHashCount = BlockHashCount;
304 type Version = Version;
306 type AccountData = pallet_balances::AccountData<Balance>;
308 type DbWeight = RocksDbWeight;
310 type SystemWeightInfo = weights::frame_system::WeightInfo<Runtime>;
312 type ExtensionsWeightInfo = weights::frame_system_extensions::WeightInfo<Runtime>;
314 type BlockWeights = RuntimeBlockWeights;
316 type BlockLength = RuntimeBlockLength;
318 type SS58Prefix = SS58Prefix;
320 type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;
322 type MaxConsumers = frame_support::traits::ConstU32<16>;
323}
324
325impl cumulus_pallet_weight_reclaim::Config for Runtime {
326 type WeightInfo = weights::cumulus_pallet_weight_reclaim::WeightInfo<Runtime>;
327}
328
329impl pallet_timestamp::Config for Runtime {
330 type Moment = u64;
332 type OnTimestampSet = Aura;
333 type MinimumPeriod = ConstU64<0>;
334 type WeightInfo = weights::pallet_timestamp::WeightInfo<Runtime>;
335}
336
337impl pallet_authorship::Config for Runtime {
338 type FindAuthor = pallet_session::FindAccountFromAuthorIndex<Self, Aura>;
339 type EventHandler = (CollatorSelection,);
340}
341
342parameter_types! {
343 pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT;
344}
345
346impl pallet_balances::Config for Runtime {
347 type Balance = Balance;
349 type DustRemoval = ();
350 type RuntimeEvent = RuntimeEvent;
352 type ExistentialDeposit = ExistentialDeposit;
353 type AccountStore = System;
354 type WeightInfo = weights::pallet_balances::WeightInfo<Runtime>;
355 type MaxLocks = ConstU32<50>;
356 type MaxReserves = ConstU32<50>;
357 type ReserveIdentifier = [u8; 8];
358 type RuntimeHoldReason = RuntimeHoldReason;
359 type RuntimeFreezeReason = RuntimeFreezeReason;
360 type FreezeIdentifier = ();
361 type MaxFreezes = ConstU32<0>;
362 type DoneSlashHandler = ();
363}
364
365parameter_types! {
366 pub const TransactionByteFee: Balance = MILLICENTS;
368}
369
370impl pallet_transaction_payment::Config for Runtime {
371 type RuntimeEvent = RuntimeEvent;
372 type OnChargeTransaction =
373 pallet_transaction_payment::FungibleAdapter<Balances, DealWithFees<Runtime>>;
374 type OperationalFeeMultiplier = ConstU8<5>;
375 type WeightToFee = WeightToFee;
376 type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;
377 type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Self>;
378 type WeightInfo = weights::pallet_transaction_payment::WeightInfo<Runtime>;
379}
380
381parameter_types! {
382 pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
383 pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
384}
385
386impl cumulus_pallet_parachain_system::Config for Runtime {
387 type WeightInfo = weights::cumulus_pallet_parachain_system::WeightInfo<Runtime>;
388 type RuntimeEvent = RuntimeEvent;
389 type OnSystemEvent = ();
390 type SelfParaId = parachain_info::Pallet<Runtime>;
391 type OutboundXcmpMessageSource = XcmpQueue;
392 type DmpQueue = frame_support::traits::EnqueueWithOrigin<MessageQueue, RelayOrigin>;
393 type ReservedDmpWeight = ReservedDmpWeight;
394 type XcmpMessageHandler = XcmpQueue;
395 type ReservedXcmpWeight = ReservedXcmpWeight;
396 type CheckAssociatedRelayNumber = RelayNumberMonotonicallyIncreases;
397 type ConsensusHook = ConsensusHook;
398 type SelectCore = cumulus_pallet_parachain_system::DefaultCoreSelector<Runtime>;
399}
400
401type ConsensusHook = cumulus_pallet_aura_ext::FixedVelocityConsensusHook<
402 Runtime,
403 RELAY_CHAIN_SLOT_DURATION_MILLIS,
404 BLOCK_PROCESSING_VELOCITY,
405 UNINCLUDED_SEGMENT_CAPACITY,
406>;
407
408impl parachain_info::Config for Runtime {}
409
410parameter_types! {
411 pub MessageQueueServiceWeight: Weight = Perbill::from_percent(60) * RuntimeBlockWeights::get().max_block;
416}
417
418impl pallet_message_queue::Config for Runtime {
419 type RuntimeEvent = RuntimeEvent;
420 type WeightInfo = weights::pallet_message_queue::WeightInfo<Runtime>;
421 #[cfg(all(not(feature = "std"), feature = "runtime-benchmarks"))]
426 type MessageProcessor =
427 pallet_message_queue::mock_helpers::NoopMessageProcessor<AggregateMessageOrigin>;
428 #[cfg(not(all(not(feature = "std"), feature = "runtime-benchmarks")))]
429 type MessageProcessor = bridge_hub_common::BridgeHubMessageRouter<
430 xcm_builder::ProcessXcmMessage<
431 AggregateMessageOrigin,
432 xcm_executor::XcmExecutor<xcm_config::XcmConfig>,
433 RuntimeCall,
434 >,
435 EthereumOutboundQueue,
436 >;
437 type Size = u32;
438 type QueueChangeHandler = NarrowOriginToSibling<XcmpQueue>;
440 type QueuePausedQuery = NarrowOriginToSibling<XcmpQueue>;
441 type HeapSize = sp_core::ConstU32<{ 103 * 1024 }>;
442 type MaxStale = sp_core::ConstU32<8>;
443 type ServiceWeight = MessageQueueServiceWeight;
444 type IdleMaxServiceWeight = MessageQueueServiceWeight;
445}
446
447impl cumulus_pallet_aura_ext::Config for Runtime {}
448
449parameter_types! {
450 pub FeeAssetId: AssetId = AssetId(xcm_config::TokenLocation::get());
452 pub const BaseDeliveryFee: u128 = CENTS.saturating_mul(3);
454}
455
456pub type PriceForSiblingParachainDelivery = polkadot_runtime_common::xcm_sender::ExponentialPrice<
457 FeeAssetId,
458 BaseDeliveryFee,
459 TransactionByteFee,
460 XcmpQueue,
461>;
462
463impl cumulus_pallet_xcmp_queue::Config for Runtime {
464 type RuntimeEvent = RuntimeEvent;
465 type ChannelInfo = ParachainSystem;
466 type VersionWrapper = PolkadotXcm;
467 type XcmpQueue = TransformOrigin<MessageQueue, AggregateMessageOrigin, ParaId, ParaIdToSibling>;
469 type MaxInboundSuspended = ConstU32<1_000>;
470 type MaxActiveOutboundChannels = ConstU32<128>;
471 type MaxPageSize = ConstU32<{ 103 * 1024 }>;
474 type ControllerOrigin = EnsureRoot<AccountId>;
475 type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;
476 type WeightInfo = weights::cumulus_pallet_xcmp_queue::WeightInfo<Runtime>;
477 type PriceForSiblingDelivery = PriceForSiblingParachainDelivery;
478}
479
480impl cumulus_pallet_xcmp_queue::migration::v5::V5Config for Runtime {
481 type ChannelList = ParachainSystem;
483}
484
485parameter_types! {
486 pub const RelayOrigin: AggregateMessageOrigin = AggregateMessageOrigin::Parent;
487}
488
489pub const PERIOD: u32 = 6 * HOURS;
490pub const OFFSET: u32 = 0;
491
492impl pallet_session::Config for Runtime {
493 type RuntimeEvent = RuntimeEvent;
494 type ValidatorId = <Self as frame_system::Config>::AccountId;
495 type ValidatorIdOf = pallet_collator_selection::IdentityCollator;
497 type ShouldEndSession = pallet_session::PeriodicSessions<ConstU32<PERIOD>, ConstU32<OFFSET>>;
498 type NextSessionRotation = pallet_session::PeriodicSessions<ConstU32<PERIOD>, ConstU32<OFFSET>>;
499 type SessionManager = CollatorSelection;
500 type SessionHandler = <SessionKeys as sp_runtime::traits::OpaqueKeys>::KeyTypeIdProviders;
502 type Keys = SessionKeys;
503 type DisablingStrategy = ();
504 type WeightInfo = weights::pallet_session::WeightInfo<Runtime>;
505}
506
507impl pallet_aura::Config for Runtime {
508 type AuthorityId = AuraId;
509 type DisabledValidators = ();
510 type MaxAuthorities = ConstU32<100_000>;
511 type AllowMultipleBlocksPerSlot = ConstBool<true>;
512 type SlotDuration = ConstU64<SLOT_DURATION>;
513}
514
515parameter_types! {
516 pub const PotId: PalletId = PalletId(*b"PotStake");
517 pub const SessionLength: BlockNumber = 6 * HOURS;
518}
519
520pub type CollatorSelectionUpdateOrigin = EnsureRoot<AccountId>;
521
522impl pallet_collator_selection::Config for Runtime {
523 type RuntimeEvent = RuntimeEvent;
524 type Currency = Balances;
525 type UpdateOrigin = CollatorSelectionUpdateOrigin;
526 type PotId = PotId;
527 type MaxCandidates = ConstU32<100>;
528 type MinEligibleCollators = ConstU32<4>;
529 type MaxInvulnerables = ConstU32<20>;
530 type KickThreshold = ConstU32<PERIOD>;
532 type ValidatorId = <Self as frame_system::Config>::AccountId;
533 type ValidatorIdOf = pallet_collator_selection::IdentityCollator;
534 type ValidatorRegistration = Session;
535 type WeightInfo = weights::pallet_collator_selection::WeightInfo<Runtime>;
536}
537
538parameter_types! {
539 pub const DepositBase: Balance = deposit(1, 88);
541 pub const DepositFactor: Balance = deposit(0, 32);
543}
544
545impl pallet_multisig::Config for Runtime {
546 type RuntimeEvent = RuntimeEvent;
547 type RuntimeCall = RuntimeCall;
548 type Currency = Balances;
549 type DepositBase = DepositBase;
550 type DepositFactor = DepositFactor;
551 type MaxSignatories = ConstU32<100>;
552 type WeightInfo = weights::pallet_multisig::WeightInfo<Runtime>;
553 type BlockNumberProvider = frame_system::Pallet<Runtime>;
554}
555
556impl pallet_utility::Config for Runtime {
557 type RuntimeEvent = RuntimeEvent;
558 type RuntimeCall = RuntimeCall;
559 type PalletsOrigin = OriginCaller;
560 type WeightInfo = weights::pallet_utility::WeightInfo<Runtime>;
561}
562
563construct_runtime!(
565 pub enum Runtime
566 {
567 System: frame_system = 0,
569 ParachainSystem: cumulus_pallet_parachain_system = 1,
570 Timestamp: pallet_timestamp = 2,
571 ParachainInfo: parachain_info = 3,
572 WeightReclaim: cumulus_pallet_weight_reclaim = 4,
573
574 Balances: pallet_balances = 10,
576 TransactionPayment: pallet_transaction_payment = 11,
577
578 Authorship: pallet_authorship = 20,
580 CollatorSelection: pallet_collator_selection = 21,
581 Session: pallet_session = 22,
582 Aura: pallet_aura = 23,
583 AuraExt: cumulus_pallet_aura_ext = 24,
584
585 XcmpQueue: cumulus_pallet_xcmp_queue = 30,
587 PolkadotXcm: pallet_xcm = 31,
588 CumulusXcm: cumulus_pallet_xcm = 32,
589
590 Utility: pallet_utility = 40,
592 Multisig: pallet_multisig = 36,
593
594 BridgeRelayers: pallet_bridge_relayers = 47,
596
597 BridgeWestendGrandpa: pallet_bridge_grandpa::<Instance3> = 48,
599 BridgeWestendParachains: pallet_bridge_parachains::<Instance3> = 49,
601 BridgeWestendMessages: pallet_bridge_messages::<Instance3> = 51,
603 XcmOverBridgeHubWestend: pallet_xcm_bridge_hub::<Instance1> = 52,
605
606 BridgePolkadotBulletinGrandpa: pallet_bridge_grandpa::<Instance4> = 60,
612 BridgePolkadotBulletinMessages: pallet_bridge_messages::<Instance4> = 61,
618 XcmOverPolkadotBulletin: pallet_xcm_bridge_hub::<Instance2> = 62,
620
621 BridgeRelayersForPermissionlessLanes: pallet_bridge_relayers::<Instance2> = 63,
623
624 EthereumInboundQueue: snowbridge_pallet_inbound_queue = 80,
625 EthereumOutboundQueue: snowbridge_pallet_outbound_queue = 81,
626 EthereumBeaconClient: snowbridge_pallet_ethereum_client = 82,
627 EthereumSystem: snowbridge_pallet_system = 83,
628
629 MessageQueue: pallet_message_queue = 175,
632 }
633);
634
635pub type BridgeRococoBulletinGrandpa = BridgePolkadotBulletinGrandpa;
637pub type BridgeRococoBulletinMessages = BridgePolkadotBulletinMessages;
639pub type XcmOverRococoBulletin = XcmOverPolkadotBulletin;
641
642bridge_runtime_common::generate_bridge_reject_obsolete_headers_and_messages! {
643 RuntimeCall, AccountId,
644 CheckAndBoostBridgeGrandpaTransactions<
646 Runtime,
647 bridge_common_config::BridgeGrandpaWestendInstance,
648 bridge_to_westend_config::PriorityBoostPerRelayHeader,
649 xcm_config::TreasuryAccount,
650 >,
651 CheckAndBoostBridgeGrandpaTransactions<
652 Runtime,
653 bridge_common_config::BridgeGrandpaRococoBulletinInstance,
654 bridge_to_bulletin_config::PriorityBoostPerRelayHeader,
655 xcm_config::TreasuryAccount,
656 >,
657 CheckAndBoostBridgeParachainsTransactions<
659 Runtime,
660 bridge_common_config::BridgeParachainWestendInstance,
661 bp_bridge_hub_westend::BridgeHubWestend,
662 bridge_to_westend_config::PriorityBoostPerParachainHeader,
663 xcm_config::TreasuryAccount,
664 >,
665 BridgeWestendMessages,
667 BridgeRococoBulletinMessages
668}
669
670#[cfg(feature = "runtime-benchmarks")]
671mod benches {
672 frame_benchmarking::define_benchmarks!(
673 [frame_system, SystemBench::<Runtime>]
674 [frame_system_extensions, SystemExtensionsBench::<Runtime>]
675 [pallet_balances, Balances]
676 [pallet_message_queue, MessageQueue]
677 [pallet_multisig, Multisig]
678 [pallet_session, SessionBench::<Runtime>]
679 [pallet_utility, Utility]
680 [pallet_timestamp, Timestamp]
681 [pallet_transaction_payment, TransactionPayment]
682 [pallet_collator_selection, CollatorSelection]
683 [cumulus_pallet_parachain_system, ParachainSystem]
684 [cumulus_pallet_xcmp_queue, XcmpQueue]
685 [cumulus_pallet_weight_reclaim, WeightReclaim]
686 [pallet_xcm, PalletXcmExtrinsicsBenchmark::<Runtime>]
688 [pallet_xcm_benchmarks::fungible, XcmBalances]
690 [pallet_xcm_benchmarks::generic, XcmGeneric]
691 [pallet_bridge_grandpa, WestendFinality]
693 [pallet_bridge_parachains, WithinWestend]
694 [pallet_bridge_messages, RococoToWestend]
695 [pallet_bridge_messages, RococoToRococoBulletin]
696 [pallet_bridge_relayers, Legacy]
697 [pallet_bridge_relayers, PermissionlessLanes]
698 [snowbridge_pallet_inbound_queue, EthereumInboundQueue]
700 [snowbridge_pallet_outbound_queue, EthereumOutboundQueue]
701 [snowbridge_pallet_system, EthereumSystem]
702 [snowbridge_pallet_ethereum_client, EthereumBeaconClient]
703 );
704}
705
706cumulus_pallet_parachain_system::register_validate_block! {
707 Runtime = Runtime,
708 BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,
709}
710
711impl_runtime_apis! {
712 impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {
713 fn slot_duration() -> sp_consensus_aura::SlotDuration {
714 sp_consensus_aura::SlotDuration::from_millis(SLOT_DURATION)
715 }
716
717 fn authorities() -> Vec<AuraId> {
718 pallet_aura::Authorities::<Runtime>::get().into_inner()
719 }
720 }
721
722 impl cumulus_primitives_aura::AuraUnincludedSegmentApi<Block> for Runtime {
723 fn can_build_upon(
724 included_hash: <Block as BlockT>::Hash,
725 slot: cumulus_primitives_aura::Slot,
726 ) -> bool {
727 ConsensusHook::can_build_upon(included_hash, slot)
728 }
729 }
730
731 impl sp_api::Core<Block> for Runtime {
732 fn version() -> RuntimeVersion {
733 VERSION
734 }
735
736 fn execute_block(block: Block) {
737 Executive::execute_block(block)
738 }
739
740 fn initialize_block(header: &<Block as BlockT>::Header) -> sp_runtime::ExtrinsicInclusionMode {
741 Executive::initialize_block(header)
742 }
743 }
744
745 impl sp_api::Metadata<Block> for Runtime {
746 fn metadata() -> OpaqueMetadata {
747 OpaqueMetadata::new(Runtime::metadata().into())
748 }
749
750 fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
751 Runtime::metadata_at_version(version)
752 }
753
754 fn metadata_versions() -> alloc::vec::Vec<u32> {
755 Runtime::metadata_versions()
756 }
757 }
758
759 impl sp_block_builder::BlockBuilder<Block> for Runtime {
760 fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
761 Executive::apply_extrinsic(extrinsic)
762 }
763
764 fn finalize_block() -> <Block as BlockT>::Header {
765 Executive::finalize_block()
766 }
767
768 fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
769 data.create_extrinsics()
770 }
771
772 fn check_inherents(
773 block: Block,
774 data: sp_inherents::InherentData,
775 ) -> sp_inherents::CheckInherentsResult {
776 data.check_extrinsics(&block)
777 }
778 }
779
780 impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
781 fn validate_transaction(
782 source: TransactionSource,
783 tx: <Block as BlockT>::Extrinsic,
784 block_hash: <Block as BlockT>::Hash,
785 ) -> TransactionValidity {
786 Executive::validate_transaction(source, tx, block_hash)
787 }
788 }
789
790 impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
791 fn offchain_worker(header: &<Block as BlockT>::Header) {
792 Executive::offchain_worker(header)
793 }
794 }
795
796 impl sp_session::SessionKeys<Block> for Runtime {
797 fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {
798 SessionKeys::generate(seed)
799 }
800
801 fn decode_session_keys(
802 encoded: Vec<u8>,
803 ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {
804 SessionKeys::decode_into_raw_public_keys(&encoded)
805 }
806 }
807
808 impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Nonce> for Runtime {
809 fn account_nonce(account: AccountId) -> Nonce {
810 System::account_nonce(account)
811 }
812 }
813
814 impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {
815 fn query_info(
816 uxt: <Block as BlockT>::Extrinsic,
817 len: u32,
818 ) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo<Balance> {
819 TransactionPayment::query_info(uxt, len)
820 }
821 fn query_fee_details(
822 uxt: <Block as BlockT>::Extrinsic,
823 len: u32,
824 ) -> pallet_transaction_payment::FeeDetails<Balance> {
825 TransactionPayment::query_fee_details(uxt, len)
826 }
827 fn query_weight_to_fee(weight: Weight) -> Balance {
828 TransactionPayment::weight_to_fee(weight)
829 }
830 fn query_length_to_fee(length: u32) -> Balance {
831 TransactionPayment::length_to_fee(length)
832 }
833 }
834
835 impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentCallApi<Block, Balance, RuntimeCall>
836 for Runtime
837 {
838 fn query_call_info(
839 call: RuntimeCall,
840 len: u32,
841 ) -> pallet_transaction_payment::RuntimeDispatchInfo<Balance> {
842 TransactionPayment::query_call_info(call, len)
843 }
844 fn query_call_fee_details(
845 call: RuntimeCall,
846 len: u32,
847 ) -> pallet_transaction_payment::FeeDetails<Balance> {
848 TransactionPayment::query_call_fee_details(call, len)
849 }
850 fn query_weight_to_fee(weight: Weight) -> Balance {
851 TransactionPayment::weight_to_fee(weight)
852 }
853 fn query_length_to_fee(length: u32) -> Balance {
854 TransactionPayment::length_to_fee(length)
855 }
856 }
857
858 impl xcm_runtime_apis::fees::XcmPaymentApi<Block> for Runtime {
859 fn query_acceptable_payment_assets(xcm_version: xcm::Version) -> Result<Vec<VersionedAssetId>, XcmPaymentApiError> {
860 let acceptable_assets = vec![AssetId(xcm_config::TokenLocation::get())];
861 PolkadotXcm::query_acceptable_payment_assets(xcm_version, acceptable_assets)
862 }
863
864 fn query_weight_to_asset_fee(weight: Weight, asset: VersionedAssetId) -> Result<u128, XcmPaymentApiError> {
865 let latest_asset_id: Result<AssetId, ()> = asset.clone().try_into();
866 match latest_asset_id {
867 Ok(asset_id) if asset_id.0 == xcm_config::TokenLocation::get() => {
868 Ok(WeightToFee::weight_to_fee(&weight))
870 },
871 Ok(asset_id) => {
872 log::trace!(target: "xcm::xcm_runtime_apis", "query_weight_to_asset_fee - unhandled asset_id: {asset_id:?}!");
873 Err(XcmPaymentApiError::AssetNotFound)
874 },
875 Err(_) => {
876 log::trace!(target: "xcm::xcm_runtime_apis", "query_weight_to_asset_fee - failed to convert asset: {asset:?}!");
877 Err(XcmPaymentApiError::VersionedConversionFailed)
878 }
879 }
880 }
881
882 fn query_xcm_weight(message: VersionedXcm<()>) -> Result<Weight, XcmPaymentApiError> {
883 PolkadotXcm::query_xcm_weight(message)
884 }
885
886 fn query_delivery_fees(destination: VersionedLocation, message: VersionedXcm<()>) -> Result<VersionedAssets, XcmPaymentApiError> {
887 PolkadotXcm::query_delivery_fees(destination, message)
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::<Runtime, xcm_config::XcmRouter, RuntimeCall, xcm_config::XcmConfig>(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 cumulus_primitives_core::GetCoreSelectorApi<Block> for Runtime {
920 fn core_selector() -> (CoreSelector, ClaimQueueOffset) {
921 ParachainSystem::core_selector()
922 }
923 }
924
925 impl bp_westend::WestendFinalityApi<Block> for Runtime {
926 fn best_finalized() -> Option<HeaderId<bp_westend::Hash, bp_westend::BlockNumber>> {
927 BridgeWestendGrandpa::best_finalized()
928 }
929 fn free_headers_interval() -> Option<bp_westend::BlockNumber> {
930 <Runtime as pallet_bridge_grandpa::Config<
931 bridge_common_config::BridgeGrandpaWestendInstance
932 >>::FreeHeadersInterval::get()
933 }
934 fn synced_headers_grandpa_info(
935 ) -> Vec<bp_header_chain::StoredHeaderGrandpaInfo<bp_westend::Header>> {
936 BridgeWestendGrandpa::synced_headers_grandpa_info()
937 }
938 }
939
940 impl bp_bridge_hub_westend::BridgeHubWestendFinalityApi<Block> for Runtime {
941 fn best_finalized() -> Option<HeaderId<Hash, BlockNumber>> {
942 BridgeWestendParachains::best_parachain_head_id::<
943 bp_bridge_hub_westend::BridgeHubWestend
944 >().unwrap_or(None)
945 }
946 fn free_headers_interval() -> Option<bp_bridge_hub_westend::BlockNumber> {
947 None
949 }
950 }
951
952 impl bp_bridge_hub_westend::FromBridgeHubWestendInboundLaneApi<Block> for Runtime {
954 fn message_details(
955 lane: LaneIdOf<Runtime, bridge_to_westend_config::WithBridgeHubWestendMessagesInstance>,
956 messages: Vec<(bp_messages::MessagePayload, bp_messages::OutboundMessageDetails)>,
957 ) -> Vec<bp_messages::InboundMessageDetails> {
958 bridge_runtime_common::messages_api::inbound_message_details::<
959 Runtime,
960 bridge_to_westend_config::WithBridgeHubWestendMessagesInstance,
961 >(lane, messages)
962 }
963 }
964
965 impl bp_bridge_hub_westend::ToBridgeHubWestendOutboundLaneApi<Block> for Runtime {
967 fn message_details(
968 lane: LaneIdOf<Runtime, bridge_to_westend_config::WithBridgeHubWestendMessagesInstance>,
969 begin: bp_messages::MessageNonce,
970 end: bp_messages::MessageNonce,
971 ) -> Vec<bp_messages::OutboundMessageDetails> {
972 bridge_runtime_common::messages_api::outbound_message_details::<
973 Runtime,
974 bridge_to_westend_config::WithBridgeHubWestendMessagesInstance,
975 >(lane, begin, end)
976 }
977 }
978
979 impl bp_polkadot_bulletin::PolkadotBulletinFinalityApi<Block> for Runtime {
980 fn best_finalized() -> Option<bp_runtime::HeaderId<bp_polkadot_bulletin::Hash, bp_polkadot_bulletin::BlockNumber>> {
981 BridgePolkadotBulletinGrandpa::best_finalized()
982 }
983
984 fn free_headers_interval() -> Option<bp_polkadot_bulletin::BlockNumber> {
985 <Runtime as pallet_bridge_grandpa::Config<
986 bridge_common_config::BridgeGrandpaRococoBulletinInstance
987 >>::FreeHeadersInterval::get()
988 }
989
990 fn synced_headers_grandpa_info(
991 ) -> Vec<bp_header_chain::StoredHeaderGrandpaInfo<bp_polkadot_bulletin::Header>> {
992 BridgePolkadotBulletinGrandpa::synced_headers_grandpa_info()
993 }
994 }
995
996 impl bp_polkadot_bulletin::FromPolkadotBulletinInboundLaneApi<Block> for Runtime {
997 fn message_details(
998 lane: LaneIdOf<Runtime, bridge_to_bulletin_config::WithRococoBulletinMessagesInstance>,
999 messages: Vec<(bp_messages::MessagePayload, bp_messages::OutboundMessageDetails)>,
1000 ) -> Vec<bp_messages::InboundMessageDetails> {
1001 bridge_runtime_common::messages_api::inbound_message_details::<
1002 Runtime,
1003 bridge_to_bulletin_config::WithRococoBulletinMessagesInstance,
1004 >(lane, messages)
1005 }
1006 }
1007
1008 impl bp_polkadot_bulletin::ToPolkadotBulletinOutboundLaneApi<Block> for Runtime {
1009 fn message_details(
1010 lane: LaneIdOf<Runtime, bridge_to_bulletin_config::WithRococoBulletinMessagesInstance>,
1011 begin: bp_messages::MessageNonce,
1012 end: bp_messages::MessageNonce,
1013 ) -> Vec<bp_messages::OutboundMessageDetails> {
1014 bridge_runtime_common::messages_api::outbound_message_details::<
1015 Runtime,
1016 bridge_to_bulletin_config::WithRococoBulletinMessagesInstance,
1017 >(lane, begin, end)
1018 }
1019 }
1020
1021 impl snowbridge_outbound_queue_runtime_api::OutboundQueueApi<Block, Balance> for Runtime {
1022 fn prove_message(leaf_index: u64) -> Option<snowbridge_merkle_tree::MerkleProof> {
1023 snowbridge_pallet_outbound_queue::api::prove_message::<Runtime>(leaf_index)
1024 }
1025
1026 fn calculate_fee(command: Command, parameters: Option<PricingParameters<Balance>>) -> Fee<Balance> {
1027 snowbridge_pallet_outbound_queue::api::calculate_fee::<Runtime>(command, parameters)
1028 }
1029 }
1030
1031 impl snowbridge_system_runtime_api::ControlApi<Block> for Runtime {
1032 fn agent_id(location: VersionedLocation) -> Option<AgentId> {
1033 snowbridge_pallet_system::api::agent_id::<Runtime>(location)
1034 }
1035 }
1036
1037 #[cfg(feature = "try-runtime")]
1038 impl frame_try_runtime::TryRuntime<Block> for Runtime {
1039 fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) {
1040 let weight = Executive::try_runtime_upgrade(checks).unwrap();
1041 (weight, RuntimeBlockWeights::get().max_block)
1042 }
1043
1044 fn execute_block(
1045 block: Block,
1046 state_root_check: bool,
1047 signature_check: bool,
1048 select: frame_try_runtime::TryStateSelect,
1049 ) -> Weight {
1050 Executive::try_execute_block(block, state_root_check, signature_check, select).unwrap()
1053 }
1054 }
1055
1056 #[cfg(feature = "runtime-benchmarks")]
1057 impl frame_benchmarking::Benchmark<Block> for Runtime {
1058 fn benchmark_metadata(extra: bool) -> (
1059 Vec<frame_benchmarking::BenchmarkList>,
1060 Vec<frame_support::traits::StorageInfo>,
1061 ) {
1062 use frame_benchmarking::BenchmarkList;
1063 use frame_support::traits::StorageInfoTrait;
1064 use frame_system_benchmarking::Pallet as SystemBench;
1065 use frame_system_benchmarking::extensions::Pallet as SystemExtensionsBench;
1066 use cumulus_pallet_session_benchmarking::Pallet as SessionBench;
1067 use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
1068
1069 type XcmBalances = pallet_xcm_benchmarks::fungible::Pallet::<Runtime>;
1073 type XcmGeneric = pallet_xcm_benchmarks::generic::Pallet::<Runtime>;
1074
1075 use pallet_bridge_relayers::benchmarking::Pallet as BridgeRelayersBench;
1076 type WestendFinality = BridgeWestendGrandpa;
1078 type WithinWestend = pallet_bridge_parachains::benchmarking::Pallet::<Runtime, bridge_common_config::BridgeParachainWestendInstance>;
1079 type RococoToWestend = pallet_bridge_messages::benchmarking::Pallet ::<Runtime, bridge_to_westend_config::WithBridgeHubWestendMessagesInstance>;
1080 type RococoToRococoBulletin = pallet_bridge_messages::benchmarking::Pallet ::<Runtime, bridge_to_bulletin_config::WithRococoBulletinMessagesInstance>;
1081 type Legacy = BridgeRelayersBench::<Runtime, bridge_common_config::RelayersForLegacyLaneIdsMessagesInstance>;
1082 type PermissionlessLanes = BridgeRelayersBench::<Runtime, bridge_common_config::RelayersForPermissionlessLanesInstance>;
1083
1084 let mut list = Vec::<BenchmarkList>::new();
1085 list_benchmarks!(list, extra);
1086
1087 let storage_info = AllPalletsWithSystem::storage_info();
1088 (list, storage_info)
1089 }
1090
1091 #[allow(non_local_definitions)]
1092 fn dispatch_benchmark(
1093 config: frame_benchmarking::BenchmarkConfig
1094 ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, alloc::string::String> {
1095 use frame_benchmarking::{BenchmarkBatch, BenchmarkError};
1096 use sp_storage::TrackedStorageKey;
1097
1098 use frame_system_benchmarking::Pallet as SystemBench;
1099 use frame_system_benchmarking::extensions::Pallet as SystemExtensionsBench;
1100 impl frame_system_benchmarking::Config for Runtime {
1101 fn setup_set_code_requirements(code: &alloc::vec::Vec<u8>) -> Result<(), BenchmarkError> {
1102 ParachainSystem::initialize_for_set_code_benchmark(code.len() as u32);
1103 Ok(())
1104 }
1105
1106 fn verify_set_code() {
1107 System::assert_last_event(cumulus_pallet_parachain_system::Event::<Runtime>::ValidationFunctionStored.into());
1108 }
1109 }
1110
1111 use cumulus_pallet_session_benchmarking::Pallet as SessionBench;
1112 impl cumulus_pallet_session_benchmarking::Config for Runtime {}
1113
1114 use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
1115 impl pallet_xcm::benchmarking::Config for Runtime {
1116 type DeliveryHelper = cumulus_primitives_utility::ToParentDeliveryHelper<
1117 xcm_config::XcmConfig,
1118 ExistentialDepositAsset,
1119 xcm_config::PriceForParentDelivery,
1120 >;
1121
1122 fn reachable_dest() -> Option<Location> {
1123 Some(Parent.into())
1124 }
1125
1126 fn teleportable_asset_and_dest() -> Option<(Asset, Location)> {
1127 Some((
1129 Asset {
1130 fun: Fungible(ExistentialDeposit::get()),
1131 id: AssetId(Parent.into())
1132 },
1133 Parent.into(),
1134 ))
1135 }
1136
1137 fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> {
1138 None
1140 }
1141
1142 fn set_up_complex_asset_transfer(
1143 ) -> Option<(Assets, u32, Location, Box<dyn FnOnce()>)> {
1144 let native_location = Parent.into();
1147 let dest = Parent.into();
1148 pallet_xcm::benchmarking::helpers::native_teleport_as_asset_transfer::<Runtime>(
1149 native_location,
1150 dest
1151 )
1152 }
1153
1154 fn get_asset() -> Asset {
1155 Asset {
1156 id: AssetId(Location::parent()),
1157 fun: Fungible(ExistentialDeposit::get()),
1158 }
1159 }
1160 }
1161
1162 use xcm::latest::prelude::*;
1163 use xcm_config::TokenLocation;
1164
1165 parameter_types! {
1166 pub ExistentialDepositAsset: Option<Asset> = Some((
1167 TokenLocation::get(),
1168 ExistentialDeposit::get()
1169 ).into());
1170 }
1171
1172 impl pallet_xcm_benchmarks::Config for Runtime {
1173 type XcmConfig = xcm_config::XcmConfig;
1174 type AccountIdConverter = xcm_config::LocationToAccountId;
1175 type DeliveryHelper = cumulus_primitives_utility::ToParentDeliveryHelper<
1176 xcm_config::XcmConfig,
1177 ExistentialDepositAsset,
1178 xcm_config::PriceForParentDelivery,
1179 >;
1180 fn valid_destination() -> Result<Location, BenchmarkError> {
1181 Ok(TokenLocation::get())
1182 }
1183 fn worst_case_holding(_depositable_count: u32) -> Assets {
1184 let assets: Vec<Asset> = vec![
1186 Asset {
1187 id: AssetId(TokenLocation::get()),
1188 fun: Fungible(1_000_000 * UNITS),
1189 }
1190 ];
1191 assets.into()
1192 }
1193 }
1194
1195 parameter_types! {
1196 pub const TrustedTeleporter: Option<(Location, Asset)> = Some((
1197 TokenLocation::get(),
1198 Asset { fun: Fungible(UNITS), id: AssetId(TokenLocation::get()) },
1199 ));
1200 pub const CheckedAccount: Option<(AccountId, xcm_builder::MintLocation)> = None;
1201 pub const TrustedReserve: Option<(Location, Asset)> = None;
1202 }
1203
1204 impl pallet_xcm_benchmarks::fungible::Config for Runtime {
1205 type TransactAsset = Balances;
1206
1207 type CheckedAccount = CheckedAccount;
1208 type TrustedTeleporter = TrustedTeleporter;
1209 type TrustedReserve = TrustedReserve;
1210
1211 fn get_asset() -> Asset {
1212 Asset {
1213 id: AssetId(TokenLocation::get()),
1214 fun: Fungible(UNITS),
1215 }
1216 }
1217 }
1218
1219 impl pallet_xcm_benchmarks::generic::Config for Runtime {
1220 type TransactAsset = Balances;
1221 type RuntimeCall = RuntimeCall;
1222
1223 fn worst_case_response() -> (u64, Response) {
1224 (0u64, Response::Version(Default::default()))
1225 }
1226
1227 fn worst_case_asset_exchange() -> Result<(Assets, Assets), BenchmarkError> {
1228 Err(BenchmarkError::Skip)
1229 }
1230
1231 fn universal_alias() -> Result<(Location, Junction), BenchmarkError> {
1232 Err(BenchmarkError::Skip)
1233 }
1234
1235 fn transact_origin_and_runtime_call() -> Result<(Location, RuntimeCall), BenchmarkError> {
1236 Ok((TokenLocation::get(), frame_system::Call::remark_with_event { remark: vec![] }.into()))
1237 }
1238
1239 fn subscribe_origin() -> Result<Location, BenchmarkError> {
1240 Ok(TokenLocation::get())
1241 }
1242
1243 fn claimable_asset() -> Result<(Location, Location, Assets), BenchmarkError> {
1244 let origin = TokenLocation::get();
1245 let assets: Assets = (AssetId(TokenLocation::get()), 1_000 * UNITS).into();
1246 let ticket = Location { parents: 0, interior: Here };
1247 Ok((origin, ticket, assets))
1248 }
1249
1250 fn fee_asset() -> Result<Asset, BenchmarkError> {
1251 Ok(Asset {
1252 id: AssetId(TokenLocation::get()),
1253 fun: Fungible(1_000_000 * UNITS),
1254 })
1255 }
1256
1257 fn unlockable_asset() -> Result<(Location, Location, Asset), BenchmarkError> {
1258 Err(BenchmarkError::Skip)
1259 }
1260
1261 fn export_message_origin_and_destination(
1262 ) -> Result<(Location, NetworkId, InteriorLocation), BenchmarkError> {
1263 let _ = PolkadotXcm::force_xcm_version(
1265 RuntimeOrigin::root(),
1266 Box::new(bridge_to_westend_config::BridgeHubWestendLocation::get()),
1267 XCM_VERSION,
1268 ).map_err(|e| {
1269 log::error!(
1270 "Failed to dispatch `force_xcm_version({:?}, {:?}, {:?})`, error: {:?}",
1271 RuntimeOrigin::root(),
1272 bridge_to_westend_config::BridgeHubWestendLocation::get(),
1273 XCM_VERSION,
1274 e
1275 );
1276 BenchmarkError::Stop("XcmVersion was not stored!")
1277 })?;
1278
1279 let sibling_parachain_location = Location::new(1, [Parachain(5678)]);
1280
1281 use frame_support::traits::fungible::Mutate;
1283 use xcm_executor::traits::ConvertLocation;
1284 frame_support::assert_ok!(
1285 Balances::mint_into(
1286 &xcm_config::LocationToAccountId::convert_location(&sibling_parachain_location).expect("valid AccountId"),
1287 bridge_to_westend_config::BridgeDeposit::get()
1288 .saturating_add(ExistentialDeposit::get())
1289 .saturating_add(UNITS * 5)
1290 )
1291 );
1292
1293 let bridge_destination_universal_location: InteriorLocation = [GlobalConsensus(NetworkId::ByGenesis(WESTEND_GENESIS_HASH)), Parachain(8765)].into();
1295 let locations = XcmOverBridgeHubWestend::bridge_locations(
1296 sibling_parachain_location.clone(),
1297 bridge_destination_universal_location.clone(),
1298 )?;
1299 XcmOverBridgeHubWestend::do_open_bridge(
1300 locations,
1301 bp_messages::LegacyLaneId([1, 2, 3, 4]),
1302 true,
1303 ).map_err(|e| {
1304 log::error!(
1305 "Failed to `XcmOverBridgeHubWestend::open_bridge`({:?}, {:?})`, error: {:?}",
1306 sibling_parachain_location,
1307 bridge_destination_universal_location,
1308 e
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
1575#[cfg(test)]
1576mod tests {
1577 use super::*;
1578 use codec::Encode;
1579 use sp_runtime::{
1580 generic::Era,
1581 traits::{TransactionExtension, Zero},
1582 };
1583
1584 #[test]
1585 fn ensure_transaction_extension_definition_is_compatible_with_relay() {
1586 use bp_polkadot_core::SuffixedCommonTransactionExtensionExt;
1587
1588 sp_io::TestExternalities::default().execute_with(|| {
1589 frame_system::BlockHash::<Runtime>::insert(BlockNumber::zero(), Hash::default());
1590 let payload: TxExtension = (
1591 frame_system::CheckNonZeroSender::new(),
1592 frame_system::CheckSpecVersion::new(),
1593 frame_system::CheckTxVersion::new(),
1594 frame_system::CheckGenesis::new(),
1595 frame_system::CheckEra::from(Era::Immortal),
1596 frame_system::CheckNonce::from(10),
1597 frame_system::CheckWeight::new(),
1598 pallet_transaction_payment::ChargeTransactionPayment::from(10),
1599 BridgeRejectObsoleteHeadersAndMessages,
1600 (
1601 bridge_to_westend_config::OnBridgeHubRococoRefundBridgeHubWestendMessages::default(),
1602 ),
1603 frame_metadata_hash_extension::CheckMetadataHash::new(false),
1604 ).into();
1605
1606 {
1608 let bhr_indirect_payload = bp_bridge_hub_rococo::TransactionExtension::from_params(
1609 VERSION.spec_version,
1610 VERSION.transaction_version,
1611 bp_runtime::TransactionEra::Immortal,
1612 System::block_hash(BlockNumber::zero()),
1613 10,
1614 10,
1615 (((), ()), ((), ())),
1616 );
1617 assert_eq!(payload.encode().split_last().unwrap().1, bhr_indirect_payload.encode());
1618 assert_eq!(
1619 TxExtension::implicit(&payload).unwrap().encode().split_last().unwrap().1,
1620 sp_runtime::traits::TransactionExtension::<RuntimeCall>::implicit(
1621 &bhr_indirect_payload
1622 )
1623 .unwrap()
1624 .encode()
1625 )
1626 }
1627 });
1628 }
1629}