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::{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, 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,
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
}
103

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

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

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

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

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

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

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

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

            
195
pub struct XcmConfig;
196
impl xcm_executor::Config for XcmConfig {
197
    type RuntimeCall = RuntimeCall;
198
    type XcmSender = XcmRouter;
199
    type AssetTransactor = AssetTransactors;
200
    type OriginConverter = XcmOriginToTransactDispatchOrigin;
201
    type IsReserve = NativeAssetReserve;
202
    type IsTeleporter = ();
203
    type UniversalLocation = UniversalLocation;
204
    type Barrier = XcmBarrier;
205
    type Weigher = XcmWeigher;
206
    // Local token trader only
207
    // TODO: update once we have a way to do fees
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 = ();
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
}
239

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
429
pub struct XCMNotifierImpl;
430

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

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

            
450
impl pallet_xcm_core_buyer::Config for Runtime {
451
    type RuntimeEvent = RuntimeEvent;
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
96
    fn get_parathread_params(para_id: ParaId) -> Option<ParathreadParams> {
481
96
        Registrar::parathread_params(para_id)
482
96
    }
483

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

            
494
pub struct CheckCollatorValidityImpl;
495

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

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

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

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

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

            
525
/// Relay chains supported by pallet_xcm_core_buyer, each relay chain has different
526
/// pallet indices for pallet_on_demand_assignment_provider
527
1236
#[derive(Debug, Default, Clone, PartialEq, Eq, Encode, Decode, TypeInfo, MaxEncodedLen)]
528
pub enum RelayChain {
529
    #[default]
530
    Westend,
531
12
    Rococo,
532
}
533

            
534
pub struct EncodedCallToBuyCore;
535

            
536
impl GetPurchaseCoreCall<RelayChain> for EncodedCallToBuyCore {
537
96
    fn get_encoded(relay_chain: RelayChain, max_amount: u128, para_id: ParaId) -> Vec<u8> {
538
96
        match relay_chain {
539
            RelayChain::Westend => {
540
12
                let call = tanssi_relay_encoder::westend::RelayCall::OnDemandAssignmentProvider(
541
12
                    tanssi_relay_encoder::westend::OnDemandAssignmentProviderCall::PlaceOrderAllowDeath {
542
12
                        max_amount,
543
12
                        para_id,
544
12
                    },
545
12
                );
546
12

            
547
12
                call.encode()
548
            }
549
            RelayChain::Rococo => {
550
84
                let call = tanssi_relay_encoder::rococo::RelayCall::OnDemandAssignmentProvider(
551
84
                    tanssi_relay_encoder::rococo::OnDemandAssignmentProviderCall::PlaceOrderAllowDeath {
552
84
                        max_amount,
553
84
                        para_id,
554
84
                    },
555
84
                );
556
84

            
557
84
                call.encode()
558
            }
559
        }
560
96
    }
561
}
562

            
563
pub struct GetMaxCorePriceFromServicesPayment;
564

            
565
impl GetParathreadMaxCorePrice for GetMaxCorePriceFromServicesPayment {
566
96
    fn get_max_core_price(para_id: ParaId) -> Option<u128> {
567
96
        pallet_services_payment::MaxCorePrice::<Runtime>::get(para_id)
568
96
    }
569
}