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 {
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
    cumulus_primitives_core::{AggregateMessageOrigin, ParaId},
35
    frame_support::{
36
        parameter_types,
37
        traits::{Everything, Nothing, PalletInfoAccess, TransformOrigin},
38
        weights::Weight,
39
    },
40
    frame_system::{pallet_prelude::BlockNumberFor, EnsureRoot},
41
    nimbus_primitives::NimbusId,
42
    pallet_xcm::XcmPassthrough,
43
    pallet_xcm_core_buyer::{
44
        CheckCollatorValidity, GetParathreadMaxCorePrice, GetParathreadParams, GetPurchaseCoreCall,
45
        ParaIdIntoAccountTruncating, XCMNotifier,
46
    },
47
    parachains_common::message_queue::{NarrowOriginToSibling, ParaIdToSibling},
48
    parity_scale_codec::{Decode, Encode},
49
    polkadot_runtime_common::xcm_sender::ExponentialPrice,
50
    scale_info::TypeInfo,
51
    sp_consensus_slots::Slot,
52
    sp_core::{ConstU32, MaxEncodedLen},
53
    sp_runtime::{transaction_validity::TransactionPriority, Perbill},
54
    sp_std::vec::Vec,
55
    staging_xcm::latest::prelude::*,
56
    staging_xcm_builder::{
57
        AccountId32Aliases, AllowKnownQueryResponses, AllowSubscriptionsFrom,
58
        AllowTopLevelPaidExecutionFrom, ConvertedConcreteId, EnsureXcmOrigin, FungibleAdapter,
59
        FungiblesAdapter, IsConcrete, NoChecking, ParentIsPreset, RelayChainAsNative,
60
        SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative,
61
        SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, TrailingSetTopicAsId,
62
        UsingComponents, WeightInfoBounds, WithComputedOrigin,
63
    },
64
    staging_xcm_executor::{traits::JustTry, XcmExecutor},
65
    tp_traits::ParathreadParams,
66
    tp_xcm_commons::NativeAssetReserve,
67
};
68

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

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

            
84
    // TODO: revisit
85
    pub const RelayNetwork: NetworkId = NetworkId::Westend;
86

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

            
90
    pub const MaxAssetsIntoHolding: u32 = 64;
91

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

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

            
100
    pub const BaseDeliveryFee: u128 = 100 * MICRODANCE;
101
}
102

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
399
impl pallet_message_queue::Config for Runtime {
400
    type RuntimeEvent = RuntimeEvent;
401
    type WeightInfo = weights::pallet_message_queue::SubstrateWeight<Runtime>;
402
    #[cfg(feature = "runtime-benchmarks")]
403
    type MessageProcessor = pallet_message_queue::mock_helpers::NoopMessageProcessor<
404
        cumulus_primitives_core::AggregateMessageOrigin,
405
    >;
406
    #[cfg(not(feature = "runtime-benchmarks"))]
407
    type MessageProcessor = staging_xcm_builder::ProcessXcmMessage<
408
        AggregateMessageOrigin,
409
        XcmExecutor<XcmConfig>,
410
        RuntimeCall,
411
    >;
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
    pub const CoreBuyingXCMQueryTtl: BlockNumber = 100;
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 RuntimeEvent = RuntimeEvent;
453
    type Currency = Balances;
454

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

            
478
pub struct GetParathreadParamsImpl;
479

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

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

            
495
pub struct CheckCollatorValidityImpl;
496

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

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

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

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

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

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

            
535
pub struct EncodedCallToBuyCore;
536

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

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

            
558
12
                call.encode()
559
            }
560
        }
561
24
    }
562
}
563

            
564
pub struct GetMaxCorePriceFromServicesPayment;
565

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