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 crate::{CollatorAssignment, Session, System};
19
#[cfg(feature = "runtime-benchmarks")]
20
use pallet_session::ShouldEndSession;
21
#[cfg(feature = "runtime-benchmarks")]
22
use sp_std::{collections::btree_map::BTreeMap, vec};
23
#[cfg(feature = "runtime-benchmarks")]
24
use tp_traits::GetContainerChainAuthor;
25
use xcm::latest::WESTEND_GENESIS_HASH;
26
use {
27
    super::{
28
        currency::MICRODANCE, weights::xcm::XcmWeight as XcmGenericWeights, AccountId,
29
        AllPalletsWithSystem, AssetRate, Balance, Balances, BlockNumber, ForeignAssets,
30
        ForeignAssetsCreator, MaintenanceMode, MessageQueue, ParachainInfo, ParachainSystem,
31
        PolkadotXcm, Registrar, Runtime, RuntimeBlockWeights, RuntimeCall, RuntimeEvent,
32
        RuntimeOrigin, TransactionByteFee, WeightToFee, XcmpQueue,
33
    },
34
    crate::{get_para_id_authorities, weights, AuthorNoting},
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
    sp_std::vec::Vec,
56
    tp_traits::ParathreadParams,
57
    tp_xcm_commons::NativeAssetReserve,
58
    xcm::latest::prelude::*,
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 RuntimeEvent = RuntimeEvent;
351
    type ForeignAsset = Location;
352
    type ForeignAssetCreatorOrigin = EnsureRoot<AccountId>;
353
    type ForeignAssetModifierOrigin = EnsureRoot<AccountId>;
354
    type ForeignAssetDestroyerOrigin = EnsureRoot<AccountId>;
355
    type Fungibles = ForeignAssets;
356
    type WeightInfo = weights::pallet_foreign_asset_creator::SubstrateWeight<Runtime>;
357
    type OnForeignAssetCreated = ();
358
    type OnForeignAssetDestroyed = ();
359
}
360

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

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

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

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

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

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

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

            
431
pub struct XCMNotifierImpl;
432

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

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

            
452
impl pallet_xcm_core_buyer::Config for Runtime {
453
    type RuntimeEvent = RuntimeEvent;
454
    type Currency = Balances;
455

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

            
479
pub struct GetParathreadParamsImpl;
480

            
481
impl GetParathreadParams for GetParathreadParamsImpl {
482
96
    fn get_parathread_params(para_id: ParaId) -> Option<ParathreadParams> {
483
96
        Registrar::parathread_params(para_id)
484
96
    }
485

            
486
    #[cfg(feature = "runtime-benchmarks")]
487
    fn set_parathread_params(para_id: ParaId, parathread_params: Option<ParathreadParams>) {
488
        if let Some(parathread_params) = parathread_params {
489
            pallet_registrar::ParathreadParams::<Runtime>::insert(para_id, parathread_params);
490
        } else {
491
            pallet_registrar::ParathreadParams::<Runtime>::remove(para_id);
492
        }
493
    }
494
}
495

            
496
pub struct CheckCollatorValidityImpl;
497

            
498
impl CheckCollatorValidity<AccountId, NimbusId> for CheckCollatorValidityImpl {
499
66
    fn is_valid_collator(para_id: ParaId, public_key: NimbusId) -> bool {
500
66
        let maybe_public_keys = get_para_id_authorities(para_id);
501
66
        maybe_public_keys.is_some_and(|public_keys| public_keys.contains(&public_key))
502
66
    }
503

            
504
    #[cfg(feature = "runtime-benchmarks")]
505
    fn set_valid_collator(para_id: ParaId, account_id: AccountId, public_key: NimbusId) {
506
        let parent_number = System::block_number();
507
        let should_end_session =
508
            <Runtime as pallet_session::Config>::ShouldEndSession::should_end_session(
509
                parent_number + 1,
510
            );
511

            
512
        let session_index = if should_end_session {
513
            Session::current_index() + 1
514
        } else {
515
            Session::current_index()
516
        };
517

            
518
        pallet_authority_mapping::AuthorityIdMapping::<Runtime>::insert(
519
            session_index,
520
            BTreeMap::from_iter([(public_key, account_id.clone())]),
521
        );
522

            
523
        CollatorAssignment::set_authors_for_para_id(para_id, vec![account_id]);
524
    }
525
}
526

            
527
/// Relay chains supported by pallet_xcm_core_buyer, each relay chain has different
528
/// pallet indices for pallet_on_demand_assignment_provider
529
#[derive(
530
    Debug,
531
    Default,
532
    Clone,
533
    PartialEq,
534
    Eq,
535
    Encode,
536
    Decode,
537
1236
    TypeInfo,
538
    MaxEncodedLen,
539
    DecodeWithMemTracking,
540
)]
541
pub enum RelayChain {
542
    #[default]
543
    Westend,
544
12
    Rococo,
545
}
546

            
547
pub struct EncodedCallToBuyCore;
548

            
549
impl GetPurchaseCoreCall<RelayChain> for EncodedCallToBuyCore {
550
96
    fn get_encoded(relay_chain: RelayChain, max_amount: u128, para_id: ParaId) -> Vec<u8> {
551
96
        match relay_chain {
552
            RelayChain::Westend => {
553
12
                let call = tanssi_relay_encoder::westend::RelayCall::OnDemandAssignmentProvider(
554
12
                    tanssi_relay_encoder::westend::OnDemandAssignmentProviderCall::PlaceOrderAllowDeath {
555
12
                        max_amount,
556
12
                        para_id,
557
12
                    },
558
12
                );
559
12

            
560
12
                call.encode()
561
            }
562
            RelayChain::Rococo => {
563
84
                let call = tanssi_relay_encoder::rococo::RelayCall::OnDemandAssignmentProvider(
564
84
                    tanssi_relay_encoder::rococo::OnDemandAssignmentProviderCall::PlaceOrderAllowDeath {
565
84
                        max_amount,
566
84
                        para_id,
567
84
                    },
568
84
                );
569
84

            
570
84
                call.encode()
571
            }
572
        }
573
96
    }
574
}
575

            
576
pub struct GetMaxCorePriceFromServicesPayment;
577

            
578
impl GetParathreadMaxCorePrice for GetMaxCorePriceFromServicesPayment {
579
96
    fn get_max_core_price(para_id: ParaId) -> Option<u128> {
580
96
        pallet_services_payment::MaxCorePrice::<Runtime>::get(para_id)
581
96
    }
582
}