1#![cfg_attr(not(feature = "std"), no_std)]
24#![recursion_limit = "256"]
26
27#[cfg(feature = "std")]
29include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
30
31pub mod bridge_common_config;
32pub mod bridge_to_bulletin_config;
33pub mod bridge_to_ethereum_config;
34pub mod bridge_to_westend_config;
35mod genesis_config_presets;
36mod weights;
37pub mod xcm_config;
38
39extern crate alloc;
40
41use alloc::{vec, vec::Vec};
42use bridge_runtime_common::extensions::{
43 CheckAndBoostBridgeGrandpaTransactions, CheckAndBoostBridgeParachainsTransactions,
44};
45use cumulus_pallet_parachain_system::RelayNumberMonotonicallyIncreases;
46use pallet_bridge_messages::LaneIdOf;
47use sp_api::impl_runtime_apis;
48use sp_core::{crypto::KeyTypeId, OpaqueMetadata};
49use sp_runtime::{
50 generic, impl_opaque_keys,
51 traits::Block as BlockT,
52 transaction_validity::{TransactionSource, TransactionValidity},
53 ApplyExtrinsicResult,
54};
55
56#[cfg(feature = "std")]
57use sp_version::NativeVersion;
58use sp_version::RuntimeVersion;
59
60use cumulus_primitives_core::ParaId;
61use frame_support::{
62 construct_runtime, derive_impl,
63 dispatch::DispatchClass,
64 genesis_builder_helper::{build_state, get_preset},
65 parameter_types,
66 traits::{ConstBool, ConstU32, ConstU64, ConstU8, Get, TransformOrigin},
67 weights::{ConstantMultiplier, Weight},
68 PalletId,
69};
70use frame_system::{
71 limits::{BlockLength, BlockWeights},
72 EnsureRoot,
73};
74use testnet_parachains_constants::rococo::{consensus::*, currency::*, fee::WeightToFee, time::*};
75
76use bp_runtime::HeaderId;
77use bridge_hub_common::{
78 message_queue::{NarrowOriginToSibling, ParaIdToSibling},
79 AggregateMessageOrigin,
80};
81pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;
82pub use sp_runtime::{MultiAddress, Perbill, Permill};
83
84#[cfg(feature = "runtime-benchmarks")]
85use xcm::latest::WESTEND_GENESIS_HASH;
86use xcm::VersionedLocation;
87use xcm_config::{TreasuryAccount, 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_003,
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 RelayParentOffset = ConstU32<0>;
403}
404
405type ConsensusHook = cumulus_pallet_aura_ext::FixedVelocityConsensusHook<
406 Runtime,
407 RELAY_CHAIN_SLOT_DURATION_MILLIS,
408 BLOCK_PROCESSING_VELOCITY,
409 UNINCLUDED_SEGMENT_CAPACITY,
410>;
411
412impl parachain_info::Config for Runtime {}
413
414parameter_types! {
415 pub MessageQueueServiceWeight: Weight = Perbill::from_percent(60) * RuntimeBlockWeights::get().max_block;
420}
421
422impl pallet_message_queue::Config for Runtime {
423 type RuntimeEvent = RuntimeEvent;
424 type WeightInfo = weights::pallet_message_queue::WeightInfo<Runtime>;
425 #[cfg(all(not(feature = "std"), feature = "runtime-benchmarks"))]
430 type MessageProcessor =
431 pallet_message_queue::mock_helpers::NoopMessageProcessor<AggregateMessageOrigin>;
432 #[cfg(not(all(not(feature = "std"), feature = "runtime-benchmarks")))]
433 type MessageProcessor = bridge_hub_common::BridgeHubMessageRouter<
434 xcm_builder::ProcessXcmMessage<
435 AggregateMessageOrigin,
436 xcm_executor::XcmExecutor<xcm_config::XcmConfig>,
437 RuntimeCall,
438 >,
439 EthereumOutboundQueue,
440 >;
441 type Size = u32;
442 type QueueChangeHandler = NarrowOriginToSibling<XcmpQueue>;
444 type QueuePausedQuery = NarrowOriginToSibling<XcmpQueue>;
445 type HeapSize = sp_core::ConstU32<{ 103 * 1024 }>;
446 type MaxStale = sp_core::ConstU32<8>;
447 type ServiceWeight = MessageQueueServiceWeight;
448 type IdleMaxServiceWeight = MessageQueueServiceWeight;
449}
450
451impl cumulus_pallet_aura_ext::Config for Runtime {}
452
453parameter_types! {
454 pub FeeAssetId: AssetId = AssetId(xcm_config::TokenLocation::get());
456 pub const BaseDeliveryFee: u128 = CENTS.saturating_mul(3);
458}
459
460pub type PriceForSiblingParachainDelivery = polkadot_runtime_common::xcm_sender::ExponentialPrice<
461 FeeAssetId,
462 BaseDeliveryFee,
463 TransactionByteFee,
464 XcmpQueue,
465>;
466
467impl cumulus_pallet_xcmp_queue::Config for Runtime {
468 type RuntimeEvent = RuntimeEvent;
469 type ChannelInfo = ParachainSystem;
470 type VersionWrapper = PolkadotXcm;
471 type XcmpQueue = TransformOrigin<MessageQueue, AggregateMessageOrigin, ParaId, ParaIdToSibling>;
473 type MaxInboundSuspended = ConstU32<1_000>;
474 type MaxActiveOutboundChannels = ConstU32<128>;
475 type MaxPageSize = ConstU32<{ 103 * 1024 }>;
478 type ControllerOrigin = EnsureRoot<AccountId>;
479 type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;
480 type WeightInfo = weights::cumulus_pallet_xcmp_queue::WeightInfo<Runtime>;
481 type PriceForSiblingDelivery = PriceForSiblingParachainDelivery;
482}
483
484impl cumulus_pallet_xcmp_queue::migration::v5::V5Config for Runtime {
485 type ChannelList = ParachainSystem;
487}
488
489parameter_types! {
490 pub const RelayOrigin: AggregateMessageOrigin = AggregateMessageOrigin::Parent;
491}
492
493pub const PERIOD: u32 = 6 * HOURS;
494pub const OFFSET: u32 = 0;
495
496impl pallet_session::Config for Runtime {
497 type RuntimeEvent = RuntimeEvent;
498 type ValidatorId = <Self as frame_system::Config>::AccountId;
499 type ValidatorIdOf = pallet_collator_selection::IdentityCollator;
501 type ShouldEndSession = pallet_session::PeriodicSessions<ConstU32<PERIOD>, ConstU32<OFFSET>>;
502 type NextSessionRotation = pallet_session::PeriodicSessions<ConstU32<PERIOD>, ConstU32<OFFSET>>;
503 type SessionManager = CollatorSelection;
504 type SessionHandler = <SessionKeys as sp_runtime::traits::OpaqueKeys>::KeyTypeIdProviders;
506 type Keys = SessionKeys;
507 type DisablingStrategy = ();
508 type WeightInfo = weights::pallet_session::WeightInfo<Runtime>;
509 type Currency = Balances;
510 type KeyDeposit = ();
511}
512
513impl pallet_aura::Config for Runtime {
514 type AuthorityId = AuraId;
515 type DisabledValidators = ();
516 type MaxAuthorities = ConstU32<100_000>;
517 type AllowMultipleBlocksPerSlot = ConstBool<true>;
518 type SlotDuration = ConstU64<SLOT_DURATION>;
519}
520
521parameter_types! {
522 pub const PotId: PalletId = PalletId(*b"PotStake");
523 pub const SessionLength: BlockNumber = 6 * HOURS;
524}
525
526pub type CollatorSelectionUpdateOrigin = EnsureRoot<AccountId>;
527
528impl pallet_collator_selection::Config for Runtime {
529 type RuntimeEvent = RuntimeEvent;
530 type Currency = Balances;
531 type UpdateOrigin = CollatorSelectionUpdateOrigin;
532 type PotId = PotId;
533 type MaxCandidates = ConstU32<100>;
534 type MinEligibleCollators = ConstU32<4>;
535 type MaxInvulnerables = ConstU32<20>;
536 type KickThreshold = ConstU32<PERIOD>;
538 type ValidatorId = <Self as frame_system::Config>::AccountId;
539 type ValidatorIdOf = pallet_collator_selection::IdentityCollator;
540 type ValidatorRegistration = Session;
541 type WeightInfo = weights::pallet_collator_selection::WeightInfo<Runtime>;
542}
543
544parameter_types! {
545 pub const DepositBase: Balance = deposit(1, 88);
547 pub const DepositFactor: Balance = deposit(0, 32);
549}
550
551impl pallet_multisig::Config for Runtime {
552 type RuntimeEvent = RuntimeEvent;
553 type RuntimeCall = RuntimeCall;
554 type Currency = Balances;
555 type DepositBase = DepositBase;
556 type DepositFactor = DepositFactor;
557 type MaxSignatories = ConstU32<100>;
558 type WeightInfo = weights::pallet_multisig::WeightInfo<Runtime>;
559 type BlockNumberProvider = frame_system::Pallet<Runtime>;
560}
561
562impl pallet_utility::Config for Runtime {
563 type RuntimeEvent = RuntimeEvent;
564 type RuntimeCall = RuntimeCall;
565 type PalletsOrigin = OriginCaller;
566 type WeightInfo = weights::pallet_utility::WeightInfo<Runtime>;
567}
568
569construct_runtime!(
571 pub enum Runtime
572 {
573 System: frame_system = 0,
575 ParachainSystem: cumulus_pallet_parachain_system = 1,
576 Timestamp: pallet_timestamp = 2,
577 ParachainInfo: parachain_info = 3,
578 WeightReclaim: cumulus_pallet_weight_reclaim = 4,
579
580 Balances: pallet_balances = 10,
582 TransactionPayment: pallet_transaction_payment = 11,
583
584 Authorship: pallet_authorship = 20,
586 CollatorSelection: pallet_collator_selection = 21,
587 Session: pallet_session = 22,
588 Aura: pallet_aura = 23,
589 AuraExt: cumulus_pallet_aura_ext = 24,
590
591 XcmpQueue: cumulus_pallet_xcmp_queue = 30,
593 PolkadotXcm: pallet_xcm = 31,
594 CumulusXcm: cumulus_pallet_xcm = 32,
595
596 Utility: pallet_utility = 40,
598 Multisig: pallet_multisig = 36,
599
600 BridgeRelayers: pallet_bridge_relayers = 47,
602
603 BridgeWestendGrandpa: pallet_bridge_grandpa::<Instance3> = 48,
605 BridgeWestendParachains: pallet_bridge_parachains::<Instance3> = 49,
607 BridgeWestendMessages: pallet_bridge_messages::<Instance3> = 51,
609 XcmOverBridgeHubWestend: pallet_xcm_bridge_hub::<Instance1> = 52,
611
612 BridgePolkadotBulletinGrandpa: pallet_bridge_grandpa::<Instance4> = 60,
618 BridgePolkadotBulletinMessages: pallet_bridge_messages::<Instance4> = 61,
624 XcmOverPolkadotBulletin: pallet_xcm_bridge_hub::<Instance2> = 62,
626
627 BridgeRelayersForPermissionlessLanes: pallet_bridge_relayers::<Instance2> = 63,
629
630 EthereumInboundQueue: snowbridge_pallet_inbound_queue = 80,
631 EthereumOutboundQueue: snowbridge_pallet_outbound_queue = 81,
632 EthereumBeaconClient: snowbridge_pallet_ethereum_client = 82,
633 EthereumSystem: snowbridge_pallet_system = 83,
634
635 MessageQueue: pallet_message_queue = 175,
638 }
639);
640
641pub type BridgeRococoBulletinGrandpa = BridgePolkadotBulletinGrandpa;
643pub type BridgeRococoBulletinMessages = BridgePolkadotBulletinMessages;
645pub type XcmOverRococoBulletin = XcmOverPolkadotBulletin;
647
648bridge_runtime_common::generate_bridge_reject_obsolete_headers_and_messages! {
649 RuntimeCall, AccountId,
650 CheckAndBoostBridgeGrandpaTransactions<
652 Runtime,
653 bridge_common_config::BridgeGrandpaWestendInstance,
654 bridge_to_westend_config::PriorityBoostPerRelayHeader,
655 xcm_config::TreasuryAccount,
656 >,
657 CheckAndBoostBridgeGrandpaTransactions<
658 Runtime,
659 bridge_common_config::BridgeGrandpaRococoBulletinInstance,
660 bridge_to_bulletin_config::PriorityBoostPerRelayHeader,
661 xcm_config::TreasuryAccount,
662 >,
663 CheckAndBoostBridgeParachainsTransactions<
665 Runtime,
666 bridge_common_config::BridgeParachainWestendInstance,
667 bp_bridge_hub_westend::BridgeHubWestend,
668 bridge_to_westend_config::PriorityBoostPerParachainHeader,
669 xcm_config::TreasuryAccount,
670 >,
671 BridgeWestendMessages,
673 BridgeRococoBulletinMessages
674}
675
676#[cfg(feature = "runtime-benchmarks")]
677mod benches {
678 frame_benchmarking::define_benchmarks!(
679 [frame_system, SystemBench::<Runtime>]
680 [frame_system_extensions, SystemExtensionsBench::<Runtime>]
681 [pallet_balances, Balances]
682 [pallet_message_queue, MessageQueue]
683 [pallet_multisig, Multisig]
684 [pallet_session, SessionBench::<Runtime>]
685 [pallet_utility, Utility]
686 [pallet_timestamp, Timestamp]
687 [pallet_transaction_payment, TransactionPayment]
688 [pallet_collator_selection, CollatorSelection]
689 [cumulus_pallet_parachain_system, ParachainSystem]
690 [cumulus_pallet_xcmp_queue, XcmpQueue]
691 [cumulus_pallet_weight_reclaim, WeightReclaim]
692 [pallet_xcm, PalletXcmExtrinsicsBenchmark::<Runtime>]
694 [pallet_xcm_benchmarks::fungible, XcmBalances]
696 [pallet_xcm_benchmarks::generic, XcmGeneric]
697 [pallet_bridge_grandpa, WestendFinality]
699 [pallet_bridge_parachains, WithinWestend]
700 [pallet_bridge_messages, RococoToWestend]
701 [pallet_bridge_messages, RococoToRococoBulletin]
702 [pallet_bridge_relayers, Legacy]
703 [pallet_bridge_relayers, PermissionlessLanes]
704 [snowbridge_pallet_inbound_queue, EthereumInboundQueue]
706 [snowbridge_pallet_outbound_queue, EthereumOutboundQueue]
707 [snowbridge_pallet_system, EthereumSystem]
708 [snowbridge_pallet_ethereum_client, EthereumBeaconClient]
709 );
710}
711
712cumulus_pallet_parachain_system::register_validate_block! {
713 Runtime = Runtime,
714 BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,
715}
716
717impl_runtime_apis! {
718 impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {
719 fn slot_duration() -> sp_consensus_aura::SlotDuration {
720 sp_consensus_aura::SlotDuration::from_millis(SLOT_DURATION)
721 }
722
723 fn authorities() -> Vec<AuraId> {
724 pallet_aura::Authorities::<Runtime>::get().into_inner()
725 }
726 }
727
728 impl cumulus_primitives_core::RelayParentOffsetApi<Block> for Runtime {
729 fn relay_parent_offset() -> u32 {
730 0
731 }
732 }
733
734 impl cumulus_primitives_aura::AuraUnincludedSegmentApi<Block> for Runtime {
735 fn can_build_upon(
736 included_hash: <Block as BlockT>::Hash,
737 slot: cumulus_primitives_aura::Slot,
738 ) -> bool {
739 ConsensusHook::can_build_upon(included_hash, slot)
740 }
741 }
742
743 impl sp_api::Core<Block> for Runtime {
744 fn version() -> RuntimeVersion {
745 VERSION
746 }
747
748 fn execute_block(block: Block) {
749 Executive::execute_block(block)
750 }
751
752 fn initialize_block(header: &<Block as BlockT>::Header) -> sp_runtime::ExtrinsicInclusionMode {
753 Executive::initialize_block(header)
754 }
755 }
756
757 impl sp_api::Metadata<Block> for Runtime {
758 fn metadata() -> OpaqueMetadata {
759 OpaqueMetadata::new(Runtime::metadata().into())
760 }
761
762 fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
763 Runtime::metadata_at_version(version)
764 }
765
766 fn metadata_versions() -> alloc::vec::Vec<u32> {
767 Runtime::metadata_versions()
768 }
769 }
770
771 impl sp_block_builder::BlockBuilder<Block> for Runtime {
772 fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
773 Executive::apply_extrinsic(extrinsic)
774 }
775
776 fn finalize_block() -> <Block as BlockT>::Header {
777 Executive::finalize_block()
778 }
779
780 fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
781 data.create_extrinsics()
782 }
783
784 fn check_inherents(
785 block: Block,
786 data: sp_inherents::InherentData,
787 ) -> sp_inherents::CheckInherentsResult {
788 data.check_extrinsics(&block)
789 }
790 }
791
792 impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
793 fn validate_transaction(
794 source: TransactionSource,
795 tx: <Block as BlockT>::Extrinsic,
796 block_hash: <Block as BlockT>::Hash,
797 ) -> TransactionValidity {
798 Executive::validate_transaction(source, tx, block_hash)
799 }
800 }
801
802 impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
803 fn offchain_worker(header: &<Block as BlockT>::Header) {
804 Executive::offchain_worker(header)
805 }
806 }
807
808 impl sp_session::SessionKeys<Block> for Runtime {
809 fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {
810 SessionKeys::generate(seed)
811 }
812
813 fn decode_session_keys(
814 encoded: Vec<u8>,
815 ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {
816 SessionKeys::decode_into_raw_public_keys(&encoded)
817 }
818 }
819
820 impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Nonce> for Runtime {
821 fn account_nonce(account: AccountId) -> Nonce {
822 System::account_nonce(account)
823 }
824 }
825
826 impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {
827 fn query_info(
828 uxt: <Block as BlockT>::Extrinsic,
829 len: u32,
830 ) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo<Balance> {
831 TransactionPayment::query_info(uxt, len)
832 }
833 fn query_fee_details(
834 uxt: <Block as BlockT>::Extrinsic,
835 len: u32,
836 ) -> pallet_transaction_payment::FeeDetails<Balance> {
837 TransactionPayment::query_fee_details(uxt, len)
838 }
839 fn query_weight_to_fee(weight: Weight) -> Balance {
840 TransactionPayment::weight_to_fee(weight)
841 }
842 fn query_length_to_fee(length: u32) -> Balance {
843 TransactionPayment::length_to_fee(length)
844 }
845 }
846
847 impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentCallApi<Block, Balance, RuntimeCall>
848 for Runtime
849 {
850 fn query_call_info(
851 call: RuntimeCall,
852 len: u32,
853 ) -> pallet_transaction_payment::RuntimeDispatchInfo<Balance> {
854 TransactionPayment::query_call_info(call, len)
855 }
856 fn query_call_fee_details(
857 call: RuntimeCall,
858 len: u32,
859 ) -> pallet_transaction_payment::FeeDetails<Balance> {
860 TransactionPayment::query_call_fee_details(call, len)
861 }
862 fn query_weight_to_fee(weight: Weight) -> Balance {
863 TransactionPayment::weight_to_fee(weight)
864 }
865 fn query_length_to_fee(length: u32) -> Balance {
866 TransactionPayment::length_to_fee(length)
867 }
868 }
869
870 impl xcm_runtime_apis::fees::XcmPaymentApi<Block> for Runtime {
871 fn query_acceptable_payment_assets(xcm_version: xcm::Version) -> Result<Vec<VersionedAssetId>, XcmPaymentApiError> {
872 let acceptable_assets = vec![AssetId(xcm_config::TokenLocation::get())];
873 PolkadotXcm::query_acceptable_payment_assets(xcm_version, acceptable_assets)
874 }
875
876 fn query_weight_to_asset_fee(weight: Weight, asset: VersionedAssetId) -> Result<u128, XcmPaymentApiError> {
877 use crate::xcm_config::XcmConfig;
878
879 type Trader = <XcmConfig as xcm_executor::Config>::Trader;
880
881 PolkadotXcm::query_weight_to_asset_fee::<Trader>(weight, asset)
882 }
883
884 fn query_xcm_weight(message: VersionedXcm<()>) -> Result<Weight, XcmPaymentApiError> {
885 PolkadotXcm::query_xcm_weight(message)
886 }
887
888 fn query_delivery_fees(destination: VersionedLocation, message: VersionedXcm<()>) -> Result<VersionedAssets, XcmPaymentApiError> {
889 PolkadotXcm::query_delivery_fees(destination, message)
890 }
891 }
892
893 impl xcm_runtime_apis::dry_run::DryRunApi<Block, RuntimeCall, RuntimeEvent, OriginCaller> for Runtime {
894 fn dry_run_call(origin: OriginCaller, call: RuntimeCall, result_xcms_version: XcmVersion) -> Result<CallDryRunEffects<RuntimeEvent>, XcmDryRunApiError> {
895 PolkadotXcm::dry_run_call::<Runtime, xcm_config::XcmRouter, OriginCaller, RuntimeCall>(origin, call, result_xcms_version)
896 }
897
898 fn dry_run_xcm(origin_location: VersionedLocation, xcm: VersionedXcm<RuntimeCall>) -> Result<XcmDryRunEffects<RuntimeEvent>, XcmDryRunApiError> {
899 PolkadotXcm::dry_run_xcm::<Runtime, xcm_config::XcmRouter, RuntimeCall, xcm_config::XcmConfig>(origin_location, xcm)
900 }
901 }
902
903 impl xcm_runtime_apis::conversions::LocationToAccountApi<Block, AccountId> for Runtime {
904 fn convert_location(location: VersionedLocation) -> Result<
905 AccountId,
906 xcm_runtime_apis::conversions::Error
907 > {
908 xcm_runtime_apis::conversions::LocationToAccountHelper::<
909 AccountId,
910 xcm_config::LocationToAccountId,
911 >::convert_location(location)
912 }
913 }
914
915 impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {
916 fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {
917 ParachainSystem::collect_collation_info(header)
918 }
919 }
920
921 impl bp_westend::WestendFinalityApi<Block> for Runtime {
922 fn best_finalized() -> Option<HeaderId<bp_westend::Hash, bp_westend::BlockNumber>> {
923 BridgeWestendGrandpa::best_finalized()
924 }
925 fn free_headers_interval() -> Option<bp_westend::BlockNumber> {
926 <Runtime as pallet_bridge_grandpa::Config<
927 bridge_common_config::BridgeGrandpaWestendInstance
928 >>::FreeHeadersInterval::get()
929 }
930 fn synced_headers_grandpa_info(
931 ) -> Vec<bp_header_chain::StoredHeaderGrandpaInfo<bp_westend::Header>> {
932 BridgeWestendGrandpa::synced_headers_grandpa_info()
933 }
934 }
935
936 impl bp_bridge_hub_westend::BridgeHubWestendFinalityApi<Block> for Runtime {
937 fn best_finalized() -> Option<HeaderId<Hash, BlockNumber>> {
938 BridgeWestendParachains::best_parachain_head_id::<
939 bp_bridge_hub_westend::BridgeHubWestend
940 >().unwrap_or(None)
941 }
942 fn free_headers_interval() -> Option<bp_bridge_hub_westend::BlockNumber> {
943 None
945 }
946 }
947
948 impl bp_bridge_hub_westend::FromBridgeHubWestendInboundLaneApi<Block> for Runtime {
950 fn message_details(
951 lane: LaneIdOf<Runtime, bridge_to_westend_config::WithBridgeHubWestendMessagesInstance>,
952 messages: Vec<(bp_messages::MessagePayload, bp_messages::OutboundMessageDetails)>,
953 ) -> Vec<bp_messages::InboundMessageDetails> {
954 bridge_runtime_common::messages_api::inbound_message_details::<
955 Runtime,
956 bridge_to_westend_config::WithBridgeHubWestendMessagesInstance,
957 >(lane, messages)
958 }
959 }
960
961 impl bp_bridge_hub_westend::ToBridgeHubWestendOutboundLaneApi<Block> for Runtime {
963 fn message_details(
964 lane: LaneIdOf<Runtime, bridge_to_westend_config::WithBridgeHubWestendMessagesInstance>,
965 begin: bp_messages::MessageNonce,
966 end: bp_messages::MessageNonce,
967 ) -> Vec<bp_messages::OutboundMessageDetails> {
968 bridge_runtime_common::messages_api::outbound_message_details::<
969 Runtime,
970 bridge_to_westend_config::WithBridgeHubWestendMessagesInstance,
971 >(lane, begin, end)
972 }
973 }
974
975 impl bp_polkadot_bulletin::PolkadotBulletinFinalityApi<Block> for Runtime {
976 fn best_finalized() -> Option<bp_runtime::HeaderId<bp_polkadot_bulletin::Hash, bp_polkadot_bulletin::BlockNumber>> {
977 BridgePolkadotBulletinGrandpa::best_finalized()
978 }
979
980 fn free_headers_interval() -> Option<bp_polkadot_bulletin::BlockNumber> {
981 <Runtime as pallet_bridge_grandpa::Config<
982 bridge_common_config::BridgeGrandpaRococoBulletinInstance
983 >>::FreeHeadersInterval::get()
984 }
985
986 fn synced_headers_grandpa_info(
987 ) -> Vec<bp_header_chain::StoredHeaderGrandpaInfo<bp_polkadot_bulletin::Header>> {
988 BridgePolkadotBulletinGrandpa::synced_headers_grandpa_info()
989 }
990 }
991
992 impl bp_polkadot_bulletin::FromPolkadotBulletinInboundLaneApi<Block> for Runtime {
993 fn message_details(
994 lane: LaneIdOf<Runtime, bridge_to_bulletin_config::WithRococoBulletinMessagesInstance>,
995 messages: Vec<(bp_messages::MessagePayload, bp_messages::OutboundMessageDetails)>,
996 ) -> Vec<bp_messages::InboundMessageDetails> {
997 bridge_runtime_common::messages_api::inbound_message_details::<
998 Runtime,
999 bridge_to_bulletin_config::WithRococoBulletinMessagesInstance,
1000 >(lane, messages)
1001 }
1002 }
1003
1004 impl bp_polkadot_bulletin::ToPolkadotBulletinOutboundLaneApi<Block> for Runtime {
1005 fn message_details(
1006 lane: LaneIdOf<Runtime, bridge_to_bulletin_config::WithRococoBulletinMessagesInstance>,
1007 begin: bp_messages::MessageNonce,
1008 end: bp_messages::MessageNonce,
1009 ) -> Vec<bp_messages::OutboundMessageDetails> {
1010 bridge_runtime_common::messages_api::outbound_message_details::<
1011 Runtime,
1012 bridge_to_bulletin_config::WithRococoBulletinMessagesInstance,
1013 >(lane, begin, end)
1014 }
1015 }
1016
1017 impl snowbridge_outbound_queue_runtime_api::OutboundQueueApi<Block, Balance> for Runtime {
1018 fn prove_message(leaf_index: u64) -> Option<snowbridge_merkle_tree::MerkleProof> {
1019 snowbridge_pallet_outbound_queue::api::prove_message::<Runtime>(leaf_index)
1020 }
1021
1022 fn calculate_fee(command: Command, parameters: Option<PricingParameters<Balance>>) -> Fee<Balance> {
1023 snowbridge_pallet_outbound_queue::api::calculate_fee::<Runtime>(command, parameters)
1024 }
1025 }
1026
1027 impl snowbridge_system_runtime_api::ControlApi<Block> for Runtime {
1028 fn agent_id(location: VersionedLocation) -> Option<AgentId> {
1029 snowbridge_pallet_system::api::agent_id::<Runtime>(location)
1030 }
1031 }
1032
1033 #[cfg(feature = "try-runtime")]
1034 impl frame_try_runtime::TryRuntime<Block> for Runtime {
1035 fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) {
1036 let weight = Executive::try_runtime_upgrade(checks).unwrap();
1037 (weight, RuntimeBlockWeights::get().max_block)
1038 }
1039
1040 fn execute_block(
1041 block: Block,
1042 state_root_check: bool,
1043 signature_check: bool,
1044 select: frame_try_runtime::TryStateSelect,
1045 ) -> Weight {
1046 Executive::try_execute_block(block, state_root_check, signature_check, select).unwrap()
1049 }
1050 }
1051
1052 #[cfg(feature = "runtime-benchmarks")]
1053 impl frame_benchmarking::Benchmark<Block> for Runtime {
1054 fn benchmark_metadata(extra: bool) -> (
1055 Vec<frame_benchmarking::BenchmarkList>,
1056 Vec<frame_support::traits::StorageInfo>,
1057 ) {
1058 use frame_benchmarking::BenchmarkList;
1059 use frame_support::traits::StorageInfoTrait;
1060 use frame_system_benchmarking::Pallet as SystemBench;
1061 use frame_system_benchmarking::extensions::Pallet as SystemExtensionsBench;
1062 use cumulus_pallet_session_benchmarking::Pallet as SessionBench;
1063 use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
1064
1065 type XcmBalances = pallet_xcm_benchmarks::fungible::Pallet::<Runtime>;
1069 type XcmGeneric = pallet_xcm_benchmarks::generic::Pallet::<Runtime>;
1070
1071 use pallet_bridge_relayers::benchmarking::Pallet as BridgeRelayersBench;
1072 type WestendFinality = BridgeWestendGrandpa;
1074 type WithinWestend = pallet_bridge_parachains::benchmarking::Pallet::<Runtime, bridge_common_config::BridgeParachainWestendInstance>;
1075 type RococoToWestend = pallet_bridge_messages::benchmarking::Pallet ::<Runtime, bridge_to_westend_config::WithBridgeHubWestendMessagesInstance>;
1076 type RococoToRococoBulletin = pallet_bridge_messages::benchmarking::Pallet ::<Runtime, bridge_to_bulletin_config::WithRococoBulletinMessagesInstance>;
1077 type Legacy = BridgeRelayersBench::<Runtime, bridge_common_config::RelayersForLegacyLaneIdsMessagesInstance>;
1078 type PermissionlessLanes = BridgeRelayersBench::<Runtime, bridge_common_config::RelayersForPermissionlessLanesInstance>;
1079
1080 let mut list = Vec::<BenchmarkList>::new();
1081 list_benchmarks!(list, extra);
1082
1083 let storage_info = AllPalletsWithSystem::storage_info();
1084 (list, storage_info)
1085 }
1086
1087 #[allow(non_local_definitions)]
1088 fn dispatch_benchmark(
1089 config: frame_benchmarking::BenchmarkConfig
1090 ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, alloc::string::String> {
1091 use frame_benchmarking::{BenchmarkBatch, BenchmarkError};
1092 use sp_storage::TrackedStorageKey;
1093
1094 use frame_system_benchmarking::Pallet as SystemBench;
1095 use frame_system_benchmarking::extensions::Pallet as SystemExtensionsBench;
1096 impl frame_system_benchmarking::Config for Runtime {
1097 fn setup_set_code_requirements(code: &alloc::vec::Vec<u8>) -> Result<(), BenchmarkError> {
1098 ParachainSystem::initialize_for_set_code_benchmark(code.len() as u32);
1099 Ok(())
1100 }
1101
1102 fn verify_set_code() {
1103 System::assert_last_event(cumulus_pallet_parachain_system::Event::<Runtime>::ValidationFunctionStored.into());
1104 }
1105 }
1106
1107 use cumulus_pallet_session_benchmarking::Pallet as SessionBench;
1108 impl cumulus_pallet_session_benchmarking::Config for Runtime {}
1109
1110 use xcm::latest::prelude::*;
1111 use xcm_config::TokenLocation;
1112 use testnet_parachains_constants::rococo::locations::{AssetHubParaId, AssetHubLocation};
1113 parameter_types! {
1114 pub ExistentialDepositAsset: Option<Asset> = Some((
1115 TokenLocation::get(),
1116 ExistentialDeposit::get()
1117 ).into());
1118 }
1119
1120 use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
1121 impl pallet_xcm::benchmarking::Config for Runtime {
1122 type DeliveryHelper = polkadot_runtime_common::xcm_sender::ToParachainDeliveryHelper<
1123 xcm_config::XcmConfig,
1124 ExistentialDepositAsset,
1125 PriceForSiblingParachainDelivery,
1126 AssetHubParaId,
1127 ParachainSystem,
1128 >;
1129
1130 fn reachable_dest() -> Option<Location> {
1131 Some(AssetHubLocation::get())
1132 }
1133
1134 fn teleportable_asset_and_dest() -> Option<(Asset, Location)> {
1135 Some((
1137 Asset {
1138 fun: Fungible(ExistentialDeposit::get()),
1139 id: AssetId(TokenLocation::get())
1140 },
1141 AssetHubLocation::get(),
1142 ))
1143 }
1144
1145 fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> {
1146 None
1148 }
1149
1150 fn set_up_complex_asset_transfer(
1151 ) -> Option<(Assets, u32, Location, Box<dyn FnOnce()>)> {
1152 let native_location = TokenLocation::get();
1155 let dest = AssetHubLocation::get();
1156 pallet_xcm::benchmarking::helpers::native_teleport_as_asset_transfer::<Runtime>(
1157 native_location,
1158 dest
1159 )
1160 }
1161
1162 fn get_asset() -> Asset {
1163 Asset {
1164 id: AssetId(Location::parent()),
1165 fun: Fungible(ExistentialDeposit::get()),
1166 }
1167 }
1168 }
1169
1170 impl pallet_xcm_benchmarks::Config for Runtime {
1171 type XcmConfig = xcm_config::XcmConfig;
1172 type AccountIdConverter = xcm_config::LocationToAccountId;
1173 type DeliveryHelper = polkadot_runtime_common::xcm_sender::ToParachainDeliveryHelper<
1174 xcm_config::XcmConfig,
1175 ExistentialDepositAsset,
1176 PriceForSiblingParachainDelivery,
1177 AssetHubParaId,
1178 ParachainSystem,
1179 >;
1180 fn valid_destination() -> Result<Location, BenchmarkError> {
1181 Ok(AssetHubLocation::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 TrustedTeleporter: Option<(Location, Asset)> = Some((
1197 AssetHubLocation::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((AssetHubLocation::get(), frame_system::Call::remark_with_event { remark: vec![] }.into()))
1237 }
1238
1239 fn subscribe_origin() -> Result<Location, BenchmarkError> {
1240 Ok(AssetHubLocation::get())
1241 }
1242
1243 fn claimable_asset() -> Result<(Location, Location, Assets), BenchmarkError> {
1244 let origin = AssetHubLocation::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 worst_case_for_trader() -> Result<(Asset, WeightLimit), BenchmarkError> {
1251 Ok((Asset {
1252 id: AssetId(TokenLocation::get()),
1253 fun: Fungible(1_000_000 * UNITS),
1254 }, WeightLimit::Limited(Weight::from_parts(5000, 5000))))
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 tracing::error!(
1270 target: "bridges::benchmark",
1271 error=?e,
1272 origin=?RuntimeOrigin::root(),
1273 location=?bridge_to_westend_config::BridgeHubWestendLocation::get(),
1274 version=?XCM_VERSION,
1275 "Failed to dispatch `force_xcm_version`"
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 tracing::error!(
1306 target: "bridges::benchmark",
1307 error=?e,
1308 locations=?sibling_parachain_location,
1309 lane_id=?bridge_destination_universal_location,
1310 "Failed to `XcmOverBridgeHubWestend::open_bridge`"
1311 );
1312 BenchmarkError::Stop("Bridge was not opened!")
1313 })?;
1314
1315 Ok(
1316 (
1317 sibling_parachain_location,
1318 NetworkId::ByGenesis(WESTEND_GENESIS_HASH),
1319 [Parachain(8765)].into()
1320 )
1321 )
1322 }
1323
1324 fn alias_origin() -> Result<(Location, Location), BenchmarkError> {
1325 Err(BenchmarkError::Skip)
1326 }
1327 }
1328
1329 type XcmBalances = pallet_xcm_benchmarks::fungible::Pallet::<Runtime>;
1330 type XcmGeneric = pallet_xcm_benchmarks::generic::Pallet::<Runtime>;
1331
1332 type WestendFinality = BridgeWestendGrandpa;
1333 type WithinWestend = pallet_bridge_parachains::benchmarking::Pallet::<Runtime, bridge_common_config::BridgeParachainWestendInstance>;
1334 type RococoToWestend = pallet_bridge_messages::benchmarking::Pallet ::<Runtime, bridge_to_westend_config::WithBridgeHubWestendMessagesInstance>;
1335 type RococoToRococoBulletin = pallet_bridge_messages::benchmarking::Pallet ::<Runtime, bridge_to_bulletin_config::WithRococoBulletinMessagesInstance>;
1336 type Legacy = BridgeRelayersBench::<Runtime, bridge_common_config::RelayersForLegacyLaneIdsMessagesInstance>;
1337 type PermissionlessLanes = BridgeRelayersBench::<Runtime, bridge_common_config::RelayersForPermissionlessLanesInstance>;
1338
1339 use bridge_runtime_common::messages_benchmarking::{
1340 prepare_message_delivery_proof_from_grandpa_chain,
1341 prepare_message_delivery_proof_from_parachain,
1342 prepare_message_proof_from_grandpa_chain,
1343 prepare_message_proof_from_parachain,
1344 generate_xcm_builder_bridge_message_sample,
1345 };
1346 use pallet_bridge_messages::benchmarking::{
1347 Config as BridgeMessagesConfig,
1348 MessageDeliveryProofParams,
1349 MessageProofParams,
1350 };
1351
1352 impl BridgeMessagesConfig<bridge_to_westend_config::WithBridgeHubWestendMessagesInstance> for Runtime {
1353 fn is_relayer_rewarded(relayer: &Self::AccountId) -> bool {
1354 let bench_lane_id = <Self as BridgeMessagesConfig<bridge_to_westend_config::WithBridgeHubWestendMessagesInstance>>::bench_lane_id();
1355 use bp_runtime::Chain;
1356 let bridged_chain_id =<Self as pallet_bridge_messages::Config<bridge_to_westend_config::WithBridgeHubWestendMessagesInstance>>::BridgedChain::ID;
1357 pallet_bridge_relayers::Pallet::<Runtime, bridge_common_config::RelayersForLegacyLaneIdsMessagesInstance>::relayer_reward(
1358 relayer,
1359 bp_relayers::RewardsAccountParams::new(
1360 bench_lane_id,
1361 bridged_chain_id,
1362 bp_relayers::RewardsAccountOwner::BridgedChain
1363 )
1364 ).is_some()
1365 }
1366
1367 fn prepare_message_proof(
1368 params: MessageProofParams<LaneIdOf<Runtime, bridge_to_westend_config::WithBridgeHubWestendMessagesInstance>>,
1369 ) -> (bridge_to_westend_config::FromWestendBridgeHubMessagesProof<bridge_to_westend_config::WithBridgeHubWestendMessagesInstance>, Weight) {
1370 use cumulus_primitives_core::XcmpMessageSource;
1371 assert!(XcmpQueue::take_outbound_messages(usize::MAX).is_empty());
1372 ParachainSystem::open_outbound_hrmp_channel_for_benchmarks_or_tests(42.into());
1373 let universal_source = bridge_to_westend_config::open_bridge_for_benchmarks::<
1374 Runtime,
1375 bridge_to_westend_config::XcmOverBridgeHubWestendInstance,
1376 xcm_config::LocationToAccountId,
1377 >(params.lane, 42);
1378 prepare_message_proof_from_parachain::<
1379 Runtime,
1380 bridge_common_config::BridgeGrandpaWestendInstance,
1381 bridge_to_westend_config::WithBridgeHubWestendMessagesInstance,
1382 >(params, generate_xcm_builder_bridge_message_sample(universal_source))
1383 }
1384
1385 fn prepare_message_delivery_proof(
1386 params: MessageDeliveryProofParams<AccountId, LaneIdOf<Runtime, bridge_to_westend_config::WithBridgeHubWestendMessagesInstance>>,
1387 ) -> bridge_to_westend_config::ToWestendBridgeHubMessagesDeliveryProof<bridge_to_westend_config::WithBridgeHubWestendMessagesInstance> {
1388 let _ = bridge_to_westend_config::open_bridge_for_benchmarks::<
1389 Runtime,
1390 bridge_to_westend_config::XcmOverBridgeHubWestendInstance,
1391 xcm_config::LocationToAccountId,
1392 >(params.lane, 42);
1393 prepare_message_delivery_proof_from_parachain::<
1394 Runtime,
1395 bridge_common_config::BridgeGrandpaWestendInstance,
1396 bridge_to_westend_config::WithBridgeHubWestendMessagesInstance,
1397 >(params)
1398 }
1399
1400 fn is_message_successfully_dispatched(_nonce: bp_messages::MessageNonce) -> bool {
1401 use cumulus_primitives_core::XcmpMessageSource;
1402 !XcmpQueue::take_outbound_messages(usize::MAX).is_empty()
1403 }
1404 }
1405
1406 impl BridgeMessagesConfig<bridge_to_bulletin_config::WithRococoBulletinMessagesInstance> for Runtime {
1407 fn is_relayer_rewarded(_relayer: &Self::AccountId) -> bool {
1408 true
1410 }
1411
1412 fn prepare_message_proof(
1413 params: MessageProofParams<LaneIdOf<Runtime, bridge_to_bulletin_config::WithRococoBulletinMessagesInstance>>,
1414 ) -> (bridge_to_bulletin_config::FromRococoBulletinMessagesProof<bridge_to_bulletin_config::WithRococoBulletinMessagesInstance>, Weight) {
1415 use cumulus_primitives_core::XcmpMessageSource;
1416 assert!(XcmpQueue::take_outbound_messages(usize::MAX).is_empty());
1417 ParachainSystem::open_outbound_hrmp_channel_for_benchmarks_or_tests(42.into());
1418 let universal_source = bridge_to_bulletin_config::open_bridge_for_benchmarks::<
1419 Runtime,
1420 bridge_to_bulletin_config::XcmOverPolkadotBulletinInstance,
1421 xcm_config::LocationToAccountId,
1422 >(params.lane, 42);
1423 prepare_message_proof_from_grandpa_chain::<
1424 Runtime,
1425 bridge_common_config::BridgeGrandpaRococoBulletinInstance,
1426 bridge_to_bulletin_config::WithRococoBulletinMessagesInstance,
1427 >(params, generate_xcm_builder_bridge_message_sample(universal_source))
1428 }
1429
1430 fn prepare_message_delivery_proof(
1431 params: MessageDeliveryProofParams<AccountId, LaneIdOf<Runtime, bridge_to_bulletin_config::WithRococoBulletinMessagesInstance>>,
1432 ) -> bridge_to_bulletin_config::ToRococoBulletinMessagesDeliveryProof<bridge_to_bulletin_config::WithRococoBulletinMessagesInstance> {
1433 let _ = bridge_to_bulletin_config::open_bridge_for_benchmarks::<
1434 Runtime,
1435 bridge_to_bulletin_config::XcmOverPolkadotBulletinInstance,
1436 xcm_config::LocationToAccountId,
1437 >(params.lane, 42);
1438 prepare_message_delivery_proof_from_grandpa_chain::<
1439 Runtime,
1440 bridge_common_config::BridgeGrandpaRococoBulletinInstance,
1441 bridge_to_bulletin_config::WithRococoBulletinMessagesInstance,
1442 >(params)
1443 }
1444
1445 fn is_message_successfully_dispatched(_nonce: bp_messages::MessageNonce) -> bool {
1446 use cumulus_primitives_core::XcmpMessageSource;
1447 !XcmpQueue::take_outbound_messages(usize::MAX).is_empty()
1448 }
1449 }
1450
1451 use bridge_runtime_common::parachains_benchmarking::prepare_parachain_heads_proof;
1452 use pallet_bridge_parachains::benchmarking::Config as BridgeParachainsConfig;
1453 use pallet_bridge_relayers::benchmarking::{
1454 Pallet as BridgeRelayersBench,
1455 Config as BridgeRelayersConfig,
1456 };
1457
1458 impl BridgeParachainsConfig<bridge_common_config::BridgeParachainWestendInstance> for Runtime {
1459 fn parachains() -> Vec<bp_polkadot_core::parachains::ParaId> {
1460 use bp_runtime::Parachain;
1461 vec![bp_polkadot_core::parachains::ParaId(bp_bridge_hub_westend::BridgeHubWestend::PARACHAIN_ID)]
1462 }
1463
1464 fn prepare_parachain_heads_proof(
1465 parachains: &[bp_polkadot_core::parachains::ParaId],
1466 parachain_head_size: u32,
1467 proof_params: bp_runtime::UnverifiedStorageProofParams,
1468 ) -> (
1469 bp_parachains::RelayBlockNumber,
1470 bp_parachains::RelayBlockHash,
1471 bp_polkadot_core::parachains::ParaHeadsProof,
1472 Vec<(bp_polkadot_core::parachains::ParaId, bp_polkadot_core::parachains::ParaHash)>,
1473 ) {
1474 prepare_parachain_heads_proof::<Runtime, bridge_common_config::BridgeParachainWestendInstance>(
1475 parachains,
1476 parachain_head_size,
1477 proof_params,
1478 )
1479 }
1480 }
1481
1482 impl BridgeRelayersConfig<bridge_common_config::RelayersForLegacyLaneIdsMessagesInstance> for Runtime {
1483 fn bench_reward() -> Self::Reward {
1484 bp_relayers::RewardsAccountParams::new(
1485 bp_messages::LegacyLaneId::default(),
1486 *b"test",
1487 bp_relayers::RewardsAccountOwner::ThisChain
1488 )
1489 }
1490
1491 fn prepare_rewards_account(
1492 reward_kind: Self::Reward,
1493 reward: Balance,
1494 ) -> Option<AccountId> {
1495 let rewards_account = bp_relayers::PayRewardFromAccount::<
1496 Balances,
1497 AccountId,
1498 bp_messages::LegacyLaneId,
1499 Balance,
1500 >::rewards_account(reward_kind);
1501 <Runtime as BridgeRelayersConfig<bridge_common_config::RelayersForLegacyLaneIdsMessagesInstance>>::deposit_account(rewards_account, reward);
1502
1503 None
1504 }
1505
1506 fn deposit_account(account: AccountId, balance: Balance) {
1507 use frame_support::traits::fungible::Mutate;
1508 Balances::mint_into(&account, balance.saturating_add(ExistentialDeposit::get())).unwrap();
1509 }
1510 }
1511
1512 impl BridgeRelayersConfig<bridge_common_config::RelayersForPermissionlessLanesInstance> for Runtime {
1513 fn bench_reward() -> Self::Reward {
1514 bp_relayers::RewardsAccountParams::new(
1515 bp_messages::HashedLaneId::default(),
1516 *b"test",
1517 bp_relayers::RewardsAccountOwner::ThisChain
1518 )
1519 }
1520
1521 fn prepare_rewards_account(
1522 reward_kind: Self::Reward,
1523 reward: Balance,
1524 ) -> Option<AccountId> {
1525 let rewards_account = bp_relayers::PayRewardFromAccount::<
1526 Balances,
1527 AccountId,
1528 bp_messages::HashedLaneId,
1529 Balance,
1530 >::rewards_account(reward_kind);
1531 <Runtime as BridgeRelayersConfig<bridge_common_config::RelayersForPermissionlessLanesInstance>>::deposit_account(rewards_account, reward);
1532
1533 None
1534 }
1535
1536 fn deposit_account(account: AccountId, balance: Balance) {
1537 use frame_support::traits::fungible::Mutate;
1538 Balances::mint_into(&account, balance.saturating_add(ExistentialDeposit::get())).unwrap();
1539 }
1540 }
1541
1542 use frame_support::traits::WhitelistedStorageKeys;
1543 let whitelist: Vec<TrackedStorageKey> = AllPalletsWithSystem::whitelisted_storage_keys();
1544
1545 let mut batches = Vec::<BenchmarkBatch>::new();
1546 let params = (&config, &whitelist);
1547 add_benchmarks!(params, batches);
1548
1549 Ok(batches)
1550 }
1551 }
1552
1553 impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
1554 fn build_state(config: Vec<u8>) -> sp_genesis_builder::Result {
1555 build_state::<RuntimeGenesisConfig>(config)
1556 }
1557
1558 fn get_preset(id: &Option<sp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
1559 get_preset::<RuntimeGenesisConfig>(id, &genesis_config_presets::get_preset)
1560 }
1561
1562 fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
1563 genesis_config_presets::preset_names()
1564 }
1565 }
1566
1567 impl xcm_runtime_apis::trusted_query::TrustedQueryApi<Block> for Runtime {
1568 fn is_trusted_reserve(asset: VersionedAsset, location: VersionedLocation) -> xcm_runtime_apis::trusted_query::XcmTrustedQueryResult {
1569 PolkadotXcm::is_trusted_reserve(asset, location)
1570 }
1571 fn is_trusted_teleporter(asset: VersionedAsset, location: VersionedLocation) -> xcm_runtime_apis::trusted_query::XcmTrustedQueryResult {
1572 PolkadotXcm::is_trusted_teleporter(asset, location)
1573 }
1574 }
1575
1576 impl cumulus_primitives_core::GetParachainInfo<Block> for Runtime {
1577 fn parachain_id() -> ParaId {
1578 ParachainInfo::parachain_id()
1579 }
1580 }
1581}
1582
1583#[cfg(test)]
1584mod tests {
1585 use super::*;
1586 use codec::Encode;
1587 use sp_runtime::{
1588 generic::Era,
1589 traits::{TransactionExtension, Zero},
1590 };
1591
1592 #[test]
1593 fn ensure_transaction_extension_definition_is_compatible_with_relay() {
1594 use bp_polkadot_core::SuffixedCommonTransactionExtensionExt;
1595
1596 sp_io::TestExternalities::default().execute_with(|| {
1597 frame_system::BlockHash::<Runtime>::insert(BlockNumber::zero(), Hash::default());
1598 let payload: TxExtension = (
1599 (
1600 frame_system::AuthorizeCall::<Runtime>::new(),
1601 frame_system::CheckNonZeroSender::new(),
1602 frame_system::CheckSpecVersion::new(),
1603 frame_system::CheckTxVersion::new(),
1604 frame_system::CheckGenesis::new(),
1605 frame_system::CheckEra::from(Era::Immortal),
1606 frame_system::CheckNonce::from(10),
1607 frame_system::CheckWeight::new(),
1608 ),
1609 pallet_transaction_payment::ChargeTransactionPayment::from(10),
1610 BridgeRejectObsoleteHeadersAndMessages,
1611 (
1612 bridge_to_westend_config::OnBridgeHubRococoRefundBridgeHubWestendMessages::default(),
1613 ),
1614 frame_metadata_hash_extension::CheckMetadataHash::new(false),
1615 ).into();
1616
1617 {
1619 let bhr_indirect_payload = bp_bridge_hub_rococo::TransactionExtension::from_params(
1620 VERSION.spec_version,
1621 VERSION.transaction_version,
1622 bp_runtime::TransactionEra::Immortal,
1623 System::block_hash(BlockNumber::zero()),
1624 10,
1625 10,
1626 (((), ()), ((), ())),
1627 );
1628 assert_eq!(payload.encode().split_last().unwrap().1, bhr_indirect_payload.encode());
1629 assert_eq!(
1630 TxExtension::implicit(&payload).unwrap().encode().split_last().unwrap().1,
1631 sp_runtime::traits::TransactionExtension::<RuntimeCall>::implicit(
1632 &bhr_indirect_payload
1633 )
1634 .unwrap()
1635 .encode()
1636 )
1637 }
1638 });
1639 }
1640}