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