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