1
// Copyright (C) Moondance Labs Ltd.
2
// This file is part of Tanssi.
3

            
4
// Tanssi is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8

            
9
// Tanssi is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13

            
14
// You should have received a copy of the GNU General Public License
15
// along with Tanssi.  If not, see <http://www.gnu.org/licenses/>
16

            
17
#[cfg(feature = "runtime-benchmarks")]
18
use {
19
    crate::{CollatorAssignment, Session, System},
20
    alloc::{collections::btree_map::BTreeMap, vec},
21
    pallet_session::ShouldEndSession,
22
    tp_traits::GetContainerChainAuthor,
23
};
24

            
25
use {
26
    super::{
27
        currency::MICRODANCE, weights::xcm::XcmWeight as XcmGenericWeights, AccountId,
28
        AllPalletsWithSystem, AssetRate, Balance, Balances, BlockNumber, ForeignAssets,
29
        ForeignAssetsCreator, MaintenanceMode, MessageQueue, ParachainInfo, ParachainSystem,
30
        PolkadotXcm, Registrar, Runtime, RuntimeBlockWeights, RuntimeCall, RuntimeEvent,
31
        RuntimeOrigin, TransactionByteFee, WeightToFee, XcmpQueue,
32
    },
33
    crate::{get_para_id_authorities, weights, AuthorNoting},
34
    alloc::vec::Vec,
35
    cumulus_primitives_core::{AggregateMessageOrigin, ParaId},
36
    frame_support::{
37
        parameter_types,
38
        traits::{Disabled, Equals, Everything, Nothing, PalletInfoAccess, TransformOrigin},
39
        weights::Weight,
40
    },
41
    frame_system::{pallet_prelude::BlockNumberFor, EnsureRoot},
42
    nimbus_primitives::NimbusId,
43
    pallet_xcm::XcmPassthrough,
44
    pallet_xcm_core_buyer::{
45
        CheckCollatorValidity, GetParathreadMaxCorePrice, GetParathreadParams, GetPurchaseCoreCall,
46
        ParaIdIntoAccountTruncating, XCMNotifier,
47
    },
48
    parachains_common::message_queue::{NarrowOriginToSibling, ParaIdToSibling},
49
    parity_scale_codec::{Decode, DecodeWithMemTracking, Encode},
50
    polkadot_runtime_common::xcm_sender::ExponentialPrice,
51
    scale_info::TypeInfo,
52
    sp_consensus_slots::Slot,
53
    sp_core::{ConstU32, MaxEncodedLen},
54
    sp_runtime::{transaction_validity::TransactionPriority, Perbill},
55
    tp_traits::ParathreadParams,
56
    tp_xcm_commons::NativeAssetReserve,
57
    xcm::latest::prelude::*,
58
    xcm::latest::WESTEND_GENESIS_HASH,
59
    xcm_builder::{
60
        AccountId32Aliases, AllowKnownQueryResponses, AllowSubscriptionsFrom,
61
        AllowTopLevelPaidExecutionFrom, ConvertedConcreteId, EnsureXcmOrigin, FungibleAdapter,
62
        FungiblesAdapter, IsConcrete, NoChecking, ParentIsPreset, RelayChainAsNative,
63
        SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative,
64
        SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, TrailingSetTopicAsId,
65
        UsingComponents, WeightInfoBounds, WithComputedOrigin, XcmFeeManagerFromComponents,
66
    },
67
    xcm_executor::{traits::JustTry, XcmExecutor},
68
};
69

            
70
parameter_types! {
71
    // Self Reserve location, defines the multilocation identifiying the self-reserve currency
72
    // This is used to match it also against our Balances pallet when we receive such
73
    // a Location: (Self Balances pallet index)
74
    // We use the RELATIVE multilocation
75
    pub SelfReserve: Location = Location {
76
        parents: 0,
77
        interior: [
78
            PalletInstance(<Balances as PalletInfoAccess>::index() as u8)
79
        ].into()
80
    };
81

            
82
    // One XCM operation is 1_000_000_000 weight - almost certainly a conservative estimate.
83
    pub UnitWeightCost: Weight = Weight::from_parts(1_000_000_000, 64 * 1024);
84

            
85
    // TODO: revisit
86
    pub const RelayNetwork: NetworkId = NetworkId::ByGenesis(WESTEND_GENESIS_HASH);
87

            
88
    // The relay chain Origin type
89
    pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into();
90

            
91
    pub const MaxAssetsIntoHolding: u32 = 64;
92

            
93
    /// Maximum number of instructions in a single XCM fragment. A sanity check against
94
    /// weight caculations getting too crazy.
95
    pub MaxInstructions: u32 = 100;
96

            
97
    // The universal location within the global consensus system
98
    pub UniversalLocation: InteriorLocation =
99
    [GlobalConsensus(RelayNetwork::get()), Parachain(ParachainInfo::parachain_id().into())].into();
100

            
101
    pub const BaseDeliveryFee: u128 = 100 * MICRODANCE;
102
    pub RootLocation: Location = Location::here();
103
}
104

            
105
#[cfg(feature = "runtime-benchmarks")]
106
parameter_types! {
107
    pub ReachableDest: Option<Location> = Some(Parent.into());
108
}
109

            
110
pub type XcmBarrier = (
111
    // Weight that is paid for may be consumed.
112
    TakeWeightCredit,
113
    // Expected responses are OK.
114
    TrailingSetTopicAsId<AllowKnownQueryResponses<PolkadotXcm>>,
115
    WithComputedOrigin<
116
        (
117
            // If the message is one that immediately attemps to pay for execution, then allow it.
118
            AllowTopLevelPaidExecutionFrom<Everything>,
119
            // Subscriptions for version tracking are OK.
120
            AllowSubscriptionsFrom<Everything>,
121
        ),
122
        UniversalLocation,
123
        ConstU32<8>,
124
    >,
125
);
126

            
127
/// Type for specifying how a `Location` can be converted into an `AccountId`. This is used
128
/// when determining ownership of accounts for asset transacting and when attempting to use XCM
129
/// `Transact` in order to determine the dispatch Origin.
130
pub type LocationToAccountId = (
131
    // The parent (Relay-chain) origin converts to the default `AccountId`.
132
    ParentIsPreset<AccountId>,
133
    // Sibling parachain origins convert to AccountId via the `ParaId::into`.
134
    SiblingParachainConvertsVia<polkadot_parachain_primitives::primitives::Sibling, AccountId>,
135
    // If we receive a Location of type AccountKey20, just generate a native account
136
    AccountId32Aliases<RelayNetwork, AccountId>,
137
    // Generate remote accounts according to polkadot standards
138
    xcm_builder::HashedDescription<
139
        AccountId,
140
        xcm_builder::DescribeFamily<xcm_builder::DescribeAllTerminal>,
141
    >,
142
);
143

            
144
/// Local origins on this chain are allowed to dispatch XCM sends/executions.
145
pub type LocalOriginToLocation = SignedToAccountId32<RuntimeOrigin, AccountId, RelayNetwork>;
146

            
147
/// Means for transacting the native currency on this chain.
148
pub type CurrencyTransactor = FungibleAdapter<
149
    // Use this currency:
150
    Balances,
151
    // Use this currency when it is a fungible asset matching the given location or name:
152
    IsConcrete<SelfReserve>,
153
    // Convert an XCM Location into a local account id:
154
    LocationToAccountId,
155
    // Our chain's account ID type (we can't get away without mentioning it explicitly):
156
    AccountId,
157
    // We don't track any teleports of `Balances`.
158
    (),
159
>;
160

            
161
/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,
162
/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can
163
/// biases the kind of local `Origin` it will become.
164
pub type XcmOriginToTransactDispatchOrigin = (
165
    // Sovereign account converter; this attempts to derive an `AccountId` from the origin location
166
    // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for
167
    // foreign chains who want to have a local sovereign account on this chain which they control.
168
    SovereignSignedViaLocation<LocationToAccountId, RuntimeOrigin>,
169
    // Native converter for Relay-chain (Parent) location; will convert to a `Relay` origin when
170
    // recognised.
171
    RelayChainAsNative<RelayChainOrigin, RuntimeOrigin>,
172
    // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when
173
    // recognised.
174
    SiblingParachainAsNative<cumulus_pallet_xcm::Origin, RuntimeOrigin>,
175
    // Native signed account converter; this just converts an `AccountId32` origin into a normal
176
    // `RuntimeOrigin::Signed` origin of the same 32-byte value.
177
    SignedAccountId32AsNative<RelayNetwork, RuntimeOrigin>,
178
    // Xcm origins can be represented natively under the Xcm pallet's Xcm origin.
179
    XcmPassthrough<RuntimeOrigin>,
180
);
181

            
182
/// Means for transacting assets on this chain.
183
pub type AssetTransactors = (CurrencyTransactor, ForeignFungiblesTransactor);
184
pub type XcmWeigher =
185
    WeightInfoBounds<XcmGenericWeights<RuntimeCall>, RuntimeCall, MaxInstructions>;
186

            
187
/// The means for routing XCM messages which are not for local execution into the right message
188
/// queues.
189
pub type XcmRouter = (
190
    // Two routers - use UMP to communicate with the relay chain:
191
    cumulus_primitives_utility::ParentAsUmp<ParachainSystem, PolkadotXcm, PriceForParentDelivery>,
192
    // ..and XCMP to communicate with the sibling chains.
193
    XcmpQueue,
194
);
195

            
196
pub struct XcmConfig;
197
impl xcm_executor::Config for XcmConfig {
198
    type RuntimeCall = RuntimeCall;
199
    type XcmSender = XcmRouter;
200
    type AssetTransactor = AssetTransactors;
201
    type OriginConverter = XcmOriginToTransactDispatchOrigin;
202
    type IsReserve = NativeAssetReserve;
203
    type IsTeleporter = ();
204
    type UniversalLocation = UniversalLocation;
205
    type Barrier = XcmBarrier;
206
    type Weigher = XcmWeigher;
207
    // Local token trader only
208
    type Trader = (
209
        UsingComponents<WeightToFee, SelfReserve, AccountId, Balances, ()>,
210
        cumulus_primitives_utility::TakeFirstAssetTrader<
211
            AccountId,
212
            AssetRateAsMultiplier,
213
            // Use this currency when it is a fungible asset matching the given location or name:
214
            (ConvertedConcreteId<AssetId, Balance, ForeignAssetsCreator, JustTry>,),
215
            ForeignAssets,
216
            (),
217
        >,
218
    );
219
    type ResponseHandler = PolkadotXcm;
220
    type AssetTrap = PolkadotXcm;
221
    type AssetClaims = PolkadotXcm;
222
    type SubscriptionService = PolkadotXcm;
223
    type PalletInstancesInfo = AllPalletsWithSystem;
224
    type MaxAssetsIntoHolding = MaxAssetsIntoHolding;
225
    type AssetLocker = ();
226
    type AssetExchanger = ();
227
    type FeeManager = XcmFeeManagerFromComponents<Equals<RootLocation>, ()>;
228
    type MessageExporter = ();
229
    type UniversalAliases = Nothing;
230
    type CallDispatcher = RuntimeCall;
231
    type SafeCallFilter = Everything;
232
    type Aliasers = Nothing;
233
    type TransactionalProcessor = xcm_builder::FrameTransactionalProcessor;
234
    type HrmpNewChannelOpenRequestHandler = ();
235
    type HrmpChannelAcceptedHandler = ();
236
    type HrmpChannelClosingHandler = ();
237
    type XcmRecorder = ();
238
    type XcmEventEmitter = PolkadotXcm;
239
}
240

            
241
impl pallet_xcm::Config for Runtime {
242
    type RuntimeEvent = RuntimeEvent;
243
    type SendXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
244
    type XcmRouter = XcmRouter;
245
    type ExecuteXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
246
    type XcmExecuteFilter = Everything;
247
    type XcmExecutor = XcmExecutor<XcmConfig>;
248
    type XcmTeleportFilter = Nothing;
249
    type XcmReserveTransferFilter = Everything;
250
    type Weigher = XcmWeigher;
251
    type UniversalLocation = UniversalLocation;
252
    type RuntimeOrigin = RuntimeOrigin;
253
    type RuntimeCall = RuntimeCall;
254
    const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;
255
    type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;
256
    type Currency = Balances;
257
    type CurrencyMatcher = ();
258
    type TrustedLockers = ();
259
    type SovereignAccountOf = LocationToAccountId;
260
    type MaxLockers = ConstU32<8>;
261
    type MaxRemoteLockConsumers = ConstU32<0>;
262
    type RemoteLockConsumerIdentifier = ();
263
    type WeightInfo = weights::pallet_xcm::SubstrateWeight<Runtime>;
264
    type AdminOrigin = EnsureRoot<AccountId>;
265
    type AuthorizedAliasConsideration = Disabled;
266
}
267

            
268
pub type PriceForSiblingParachainDelivery =
269
    ExponentialPrice<SelfReserve, BaseDeliveryFee, TransactionByteFee, XcmpQueue>;
270

            
271
pub type PriceForParentDelivery =
272
    ExponentialPrice<SelfReserve, BaseDeliveryFee, TransactionByteFee, ParachainSystem>;
273

            
274
impl cumulus_pallet_xcmp_queue::Config for Runtime {
275
    type RuntimeEvent = RuntimeEvent;
276
    type ChannelInfo = ParachainSystem;
277
    type VersionWrapper = PolkadotXcm;
278
    type ControllerOrigin = EnsureRoot<AccountId>;
279
    type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;
280
    type WeightInfo = weights::cumulus_pallet_xcmp_queue::SubstrateWeight<Runtime>;
281
    type PriceForSiblingDelivery = PriceForSiblingParachainDelivery;
282
    // Enqueue XCMP messages from siblings for later processing.
283
    type XcmpQueue = TransformOrigin<MessageQueue, AggregateMessageOrigin, ParaId, ParaIdToSibling>;
284
    type MaxInboundSuspended = sp_core::ConstU32<1_000>;
285
    type MaxActiveOutboundChannels = ConstU32<128>;
286
    type MaxPageSize = ConstU32<{ 103 * 1024 }>;
287
}
288

            
289
impl cumulus_pallet_xcm::Config for Runtime {
290
    type RuntimeEvent = RuntimeEvent;
291
    type XcmExecutor = XcmExecutor<XcmConfig>;
292
}
293

            
294
parameter_types! {
295
    // we just reuse the same deposits
296
    pub const ForeignAssetsAssetDeposit: Balance = 0;
297
    pub const ForeignAssetsAssetAccountDeposit: Balance = 0;
298
    pub const ForeignAssetsApprovalDeposit: Balance = 0;
299
    pub const ForeignAssetsAssetsStringLimit: u32 = 50;
300
    pub const ForeignAssetsMetadataDepositBase: Balance = 0;
301
    pub const ForeignAssetsMetadataDepositPerByte: Balance = 0;
302
    pub CheckingAccount: AccountId = PolkadotXcm::check_account();
303
}
304

            
305
#[cfg(feature = "runtime-benchmarks")]
306
/// Simple conversion of `u32` into an `AssetId` for use in benchmarking.
307
pub struct ForeignAssetBenchmarkHelper;
308
#[cfg(feature = "runtime-benchmarks")]
309
impl pallet_assets::BenchmarkHelper<AssetId> for ForeignAssetBenchmarkHelper {
310
    fn create_asset_id_parameter(id: u32) -> AssetId {
311
        id.try_into()
312
            .expect("number too large to create benchmarks")
313
    }
314
}
315
#[cfg(feature = "runtime-benchmarks")]
316
impl pallet_asset_rate::AssetKindFactory<AssetId> for ForeignAssetBenchmarkHelper {
317
    fn create_asset_kind(id: u32) -> AssetId {
318
        id.try_into()
319
            .expect("number too large to create benchmarks")
320
    }
321
}
322

            
323
pub type AssetId = u16;
324
pub type ForeignAssetsInstance = pallet_assets::Instance1;
325
impl pallet_assets::Config<ForeignAssetsInstance> for Runtime {
326
    type RuntimeEvent = RuntimeEvent;
327
    type Balance = Balance;
328
    type AssetId = AssetId;
329
    type AssetIdParameter = AssetId;
330
    type Currency = Balances;
331
    type CreateOrigin = frame_support::traits::NeverEnsureOrigin<AccountId>;
332
    type ForceOrigin = EnsureRoot<AccountId>;
333
    type AssetDeposit = ForeignAssetsAssetDeposit;
334
    type MetadataDepositBase = ForeignAssetsMetadataDepositBase;
335
    type MetadataDepositPerByte = ForeignAssetsMetadataDepositPerByte;
336
    type ApprovalDeposit = ForeignAssetsApprovalDeposit;
337
    type StringLimit = ForeignAssetsAssetsStringLimit;
338
    type Freezer = ();
339
    type Extra = ();
340
    type WeightInfo = weights::pallet_assets::SubstrateWeight<Runtime>;
341
    type CallbackHandle = ();
342
    type AssetAccountDeposit = ForeignAssetsAssetAccountDeposit;
343
    type RemoveItemsLimit = frame_support::traits::ConstU32<1000>;
344
    type Holder = ();
345
    #[cfg(feature = "runtime-benchmarks")]
346
    type BenchmarkHelper = ForeignAssetBenchmarkHelper;
347
}
348

            
349
impl pallet_foreign_asset_creator::Config for Runtime {
350
    type ForeignAsset = Location;
351
    type ForeignAssetCreatorOrigin = EnsureRoot<AccountId>;
352
    type ForeignAssetModifierOrigin = EnsureRoot<AccountId>;
353
    type ForeignAssetDestroyerOrigin = EnsureRoot<AccountId>;
354
    type Fungibles = ForeignAssets;
355
    type WeightInfo = weights::pallet_foreign_asset_creator::SubstrateWeight<Runtime>;
356
    type OnForeignAssetCreated = ();
357
    type OnForeignAssetDestroyed = ();
358
}
359

            
360
impl pallet_asset_rate::Config for Runtime {
361
    type CreateOrigin = EnsureRoot<AccountId>;
362
    type RemoveOrigin = EnsureRoot<AccountId>;
363
    type UpdateOrigin = EnsureRoot<AccountId>;
364
    type Currency = Balances;
365
    type AssetKind = AssetId;
366
    type RuntimeEvent = RuntimeEvent;
367
    type WeightInfo = weights::pallet_asset_rate::SubstrateWeight<Runtime>;
368
    #[cfg(feature = "runtime-benchmarks")]
369
    type BenchmarkHelper = ForeignAssetBenchmarkHelper;
370
}
371

            
372
/// Means for transacting foreign assets from different global consensus.
373
pub type ForeignFungiblesTransactor = FungiblesAdapter<
374
    // Use this fungibles implementation:
375
    ForeignAssets,
376
    // Use this currency when it is a fungible asset matching the given location or name:
377
    (ConvertedConcreteId<AssetId, Balance, ForeignAssetsCreator, JustTry>,),
378
    // Convert an XCM Location into a local account id:
379
    LocationToAccountId,
380
    // Our chain's account ID type (we can't get away without mentioning it explicitly):
381
    AccountId,
382
    // We dont need to check teleports here.
383
    NoChecking,
384
    // The account to use for tracking teleports.
385
    CheckingAccount,
386
>;
387

            
388
/// Multiplier used for dedicated `TakeFirstAssetTrader` with `ForeignAssets` instance.
389
pub type AssetRateAsMultiplier =
390
    parachains_common::xcm_config::AssetFeeAsExistentialDepositMultiplier<
391
        Runtime,
392
        WeightToFee,
393
        AssetRate,
394
        ForeignAssetsInstance,
395
    >;
396

            
397
parameter_types! {
398
    pub MessageQueueServiceWeight: Weight = Perbill::from_percent(25) * RuntimeBlockWeights::get().max_block;
399
}
400

            
401
impl pallet_message_queue::Config for Runtime {
402
    type RuntimeEvent = RuntimeEvent;
403
    type WeightInfo = weights::pallet_message_queue::SubstrateWeight<Runtime>;
404
    #[cfg(feature = "runtime-benchmarks")]
405
    type MessageProcessor = pallet_message_queue::mock_helpers::NoopMessageProcessor<
406
        cumulus_primitives_core::AggregateMessageOrigin,
407
    >;
408
    #[cfg(not(feature = "runtime-benchmarks"))]
409
    type MessageProcessor =
410
        xcm_builder::ProcessXcmMessage<AggregateMessageOrigin, XcmExecutor<XcmConfig>, RuntimeCall>;
411
    type Size = u32;
412
    // The XCMP queue pallet is only ever able to handle the `Sibling(ParaId)` origin:
413
    type QueueChangeHandler = NarrowOriginToSibling<XcmpQueue>;
414
    // NarrowOriginToSibling calls XcmpQueue's is_pause if Origin is sibling. Allows all other origins
415
    type QueuePausedQuery = (MaintenanceMode, NarrowOriginToSibling<XcmpQueue>);
416
    // TODO verify values
417
    type HeapSize = sp_core::ConstU32<{ 64 * 1024 }>;
418
    type MaxStale = sp_core::ConstU32<8>;
419
    type ServiceWeight = MessageQueueServiceWeight;
420
    type IdleMaxServiceWeight = MessageQueueServiceWeight;
421
}
422

            
423
parameter_types! {
424
    pub const ParasUnsignedPriority: TransactionPriority = TransactionPriority::MAX;
425
    pub const XcmBuyExecutionDotRococo: u128 = XCM_BUY_EXECUTION_COST_ROCOCO;
426
}
427

            
428
pub const XCM_BUY_EXECUTION_COST_ROCOCO: u128 = 70_000_000 + 126_666_399;
429

            
430
pub struct XCMNotifierImpl;
431

            
432
impl XCMNotifier<Runtime> for XCMNotifierImpl {
433
12
    fn new_notify_query(
434
12
        responder: impl Into<Location>,
435
12
        notify: impl Into<RuntimeCall>,
436
12
        timeout: BlockNumberFor<Runtime>,
437
12
        match_querier: impl Into<Location>,
438
12
    ) -> u64 {
439
12
        pallet_xcm::Pallet::<Runtime>::new_notify_query(responder, notify, timeout, match_querier)
440
12
    }
441
}
442

            
443
parameter_types! {
444
    // TODO: used to be 100 but TS tests failed if we set it to 100, previously it used AdditionalTtlForInflightOrders with value 5
445
    pub const CoreBuyingXCMQueryTtl: BlockNumber = 5;
446
    pub const AdditionalTtlForInflightOrders: BlockNumber = 5;
447
    pub const PendingBlockTtl: BlockNumber = 10;
448
    pub BuyCoreSlotDrift: Slot = Slot::from(5u64);
449
}
450

            
451
impl pallet_xcm_core_buyer::Config for Runtime {
452
    type Currency = Balances;
453

            
454
    type XcmSender = XcmRouter;
455
    type GetPurchaseCoreCall = EncodedCallToBuyCore;
456
    type GetParathreadAccountId = ParaIdIntoAccountTruncating;
457
    type GetParathreadMaxCorePrice = GetMaxCorePriceFromServicesPayment;
458
    type SelfParaId = parachain_info::Pallet<Runtime>;
459
    type RelayChain = RelayChain;
460
    type GetParathreadParams = GetParathreadParamsImpl;
461
    type CheckCollatorValidity = CheckCollatorValidityImpl;
462
    type UnsignedPriority = ParasUnsignedPriority;
463
    type PendingBlocksTtl = PendingBlockTtl;
464
    type CoreBuyingXCMQueryTtl = CoreBuyingXCMQueryTtl;
465
    type AdditionalTtlForInflightOrders = AdditionalTtlForInflightOrders;
466
    type BuyCoreSlotDrift = BuyCoreSlotDrift;
467
    type UniversalLocation = UniversalLocation;
468
    type RuntimeOrigin = RuntimeOrigin;
469
    type RuntimeCall = RuntimeCall;
470
    type XCMNotifier = XCMNotifierImpl;
471
    type LatestAuthorInfoFetcher = AuthorNoting;
472
    type SlotBeacon = dp_consensus::AuraDigestSlotBeacon<Runtime>;
473
    type CollatorPublicKey = NimbusId;
474
    type WeightInfo = weights::pallet_xcm_core_buyer::SubstrateWeight<Runtime>;
475
}
476

            
477
pub struct GetParathreadParamsImpl;
478

            
479
impl GetParathreadParams for GetParathreadParamsImpl {
480
120
    fn get_parathread_params(para_id: ParaId) -> Option<ParathreadParams> {
481
120
        Registrar::parathread_params(para_id)
482
120
    }
483

            
484
    #[cfg(feature = "runtime-benchmarks")]
485
    fn set_parathread_params(para_id: ParaId, parathread_params: Option<ParathreadParams>) {
486
        pallet_registrar::ParathreadParams::<Runtime>::set(para_id, parathread_params);
487
    }
488
}
489

            
490
pub struct CheckCollatorValidityImpl;
491

            
492
impl CheckCollatorValidity<AccountId, NimbusId> for CheckCollatorValidityImpl {
493
60
    fn is_valid_collator(para_id: ParaId, public_key: NimbusId) -> bool {
494
60
        let maybe_public_keys = get_para_id_authorities(para_id);
495
60
        maybe_public_keys.is_some_and(|public_keys| public_keys.contains(&public_key))
496
60
    }
497

            
498
    #[cfg(feature = "runtime-benchmarks")]
499
    fn set_valid_collator(para_id: ParaId, account_id: AccountId, public_key: NimbusId) {
500
        let parent_number = System::block_number();
501
        let should_end_session =
502
            <Runtime as pallet_session::Config>::ShouldEndSession::should_end_session(
503
                parent_number + 1,
504
            );
505

            
506
        let session_index = if should_end_session {
507
            Session::current_index() + 1
508
        } else {
509
            Session::current_index()
510
        };
511

            
512
        pallet_authority_mapping::AuthorityIdMapping::<Runtime>::insert(
513
            session_index,
514
            BTreeMap::from_iter([(public_key, account_id.clone())]),
515
        );
516

            
517
        CollatorAssignment::set_authors_for_para_id(para_id, vec![account_id]);
518
    }
519
}
520

            
521
/// Relay chains supported by pallet_xcm_core_buyer, each relay chain has different
522
/// pallet indices for pallet_on_demand_assignment_provider
523
#[derive(
524
    Debug,
525
    Default,
526
    Clone,
527
    PartialEq,
528
    Eq,
529
    Encode,
530
    Decode,
531
    TypeInfo,
532
    MaxEncodedLen,
533
    DecodeWithMemTracking,
534
)]
535
pub enum RelayChain {
536
    #[default]
537
    Westend,
538
    Rococo,
539
}
540

            
541
pub struct EncodedCallToBuyCore;
542

            
543
impl GetPurchaseCoreCall<RelayChain> for EncodedCallToBuyCore {
544
120
    fn get_encoded(relay_chain: RelayChain, max_amount: u128, para_id: ParaId) -> Vec<u8> {
545
120
        match relay_chain {
546
            RelayChain::Westend => {
547
                let call = tanssi_relay_encoder::westend::RelayCall::OnDemandAssignmentProvider(
548
                    tanssi_relay_encoder::westend::OnDemandAssignmentProviderCall::PlaceOrderAllowDeath {
549
                        max_amount,
550
                        para_id,
551
                    },
552
                );
553

            
554
                call.encode()
555
            }
556
            RelayChain::Rococo => {
557
120
                let call = tanssi_relay_encoder::rococo::RelayCall::OnDemandAssignmentProvider(
558
120
                    tanssi_relay_encoder::rococo::OnDemandAssignmentProviderCall::PlaceOrderAllowDeath {
559
120
                        max_amount,
560
120
                        para_id,
561
120
                    },
562
120
                );
563

            
564
120
                call.encode()
565
            }
566
        }
567
120
    }
568
}
569

            
570
pub struct GetMaxCorePriceFromServicesPayment;
571

            
572
impl GetParathreadMaxCorePrice for GetMaxCorePriceFromServicesPayment {
573
120
    fn get_max_core_price(para_id: ParaId) -> Option<u128> {
574
120
        pallet_services_payment::MaxCorePrice::<Runtime>::get(para_id)
575
120
    }
576
}