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_attr(not(feature = "std"), no_std)]
18
// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.
19
#![recursion_limit = "256"]
20

            
21
// Make the WASM binary available.
22
#[cfg(feature = "std")]
23
include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
24

            
25
pub mod xcm_config;
26

            
27
use polkadot_runtime_common::SlowAdjustingFeeUpdate;
28
#[cfg(feature = "std")]
29
use sp_version::NativeVersion;
30

            
31
#[cfg(any(feature = "std", test))]
32
pub use sp_runtime::BuildStorage;
33

            
34
pub mod weights;
35

            
36
#[cfg(test)]
37
mod tests;
38

            
39
use {
40
    cumulus_pallet_parachain_system::{
41
        RelayChainStateProof, RelayNumberMonotonicallyIncreases, RelaychainDataProvider,
42
        RelaychainStateProvider,
43
    },
44
    cumulus_primitives_core::{
45
        relay_chain::{self, SessionIndex},
46
        AggregateMessageOrigin, BodyId, ParaId,
47
    },
48
    frame_support::{
49
        construct_runtime,
50
        dispatch::{DispatchClass, DispatchErrorWithPostInfo},
51
        genesis_builder_helper::{build_state, get_preset},
52
        pallet_prelude::DispatchResult,
53
        parameter_types,
54
        traits::{
55
            fungible::{Balanced, Credit, Inspect, InspectHold, Mutate, MutateHold},
56
            tokens::{
57
                imbalance::ResolveTo, ConversionToAssetBalance, PayFromAccount, Precision,
58
                Preservation, UnityAssetBalanceConversion,
59
            },
60
            ConstBool, ConstU128, ConstU32, ConstU64, ConstU8, Contains, EitherOfDiverse,
61
            Imbalance, InsideBoth, InstanceFilter, OnUnbalanced, ValidatorRegistration,
62
        },
63
        weights::{
64
            constants::{
65
                BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight,
66
                WEIGHT_REF_TIME_PER_SECOND,
67
            },
68
            ConstantMultiplier, Weight, WeightToFee as _, WeightToFeeCoefficient,
69
            WeightToFeeCoefficients, WeightToFeePolynomial,
70
        },
71
        PalletId,
72
    },
73
    frame_system::{
74
        limits::{BlockLength, BlockWeights},
75
        EnsureRoot, EnsureSigned,
76
    },
77
    nimbus_primitives::{NimbusId, SlotBeacon},
78
    pallet_balances::NegativeImbalance,
79
    pallet_collator_assignment::{GetRandomnessForNextBlock, RotateCollatorsEveryNSessions},
80
    pallet_invulnerables::InvulnerableRewardDistribution,
81
    pallet_pooled_staking::traits::{IsCandidateEligible, Timer},
82
    pallet_registrar::RegistrarHooks,
83
    pallet_registrar_runtime_api::ContainerChainGenesisData,
84
    pallet_services_payment::{ProvideBlockProductionCost, ProvideCollatorAssignmentCost},
85
    pallet_session::{SessionManager, ShouldEndSession},
86
    pallet_stream_payment_runtime_api::{StreamPaymentApiError, StreamPaymentApiStatus},
87
    pallet_transaction_payment::FungibleAdapter,
88
    pallet_xcm_core_buyer::BuyingError,
89
    polkadot_runtime_common::BlockHashCount,
90
    scale_info::prelude::format,
91
    serde::{Deserialize, Serialize},
92
    smallvec::smallvec,
93
    sp_api::impl_runtime_apis,
94
    sp_consensus_aura::SlotDuration,
95
    sp_consensus_slots::Slot,
96
    sp_core::{crypto::KeyTypeId, Get, MaxEncodedLen, OpaqueMetadata, H256},
97
    sp_runtime::{
98
        create_runtime_str, generic, impl_opaque_keys,
99
        traits::{
100
            AccountIdConversion, AccountIdLookup, BlakeTwo256, Block as BlockT, ConvertInto,
101
            Hash as HashT, IdentityLookup, Verify,
102
        },
103
        transaction_validity::{TransactionSource, TransactionValidity},
104
        AccountId32, ApplyExtrinsicResult,
105
    },
106
    sp_std::{collections::btree_set::BTreeSet, marker::PhantomData, prelude::*},
107
    sp_version::RuntimeVersion,
108
    staging_xcm::{
109
        IntoVersion, VersionedAssetId, VersionedAssets, VersionedLocation, VersionedXcm,
110
    },
111
    tp_traits::{
112
        apply, derive_storage_traits, GetContainerChainAuthor, GetHostConfiguration,
113
        GetSessionContainerChains, MaybeSelfChainBlockAuthor, RelayStorageRootProvider,
114
        RemoveInvulnerables, RemoveParaIdsWithNoCredits, SlotFrequency,
115
    },
116
    tp_xcm_core_buyer::BuyCoreCollatorProof,
117
    xcm_runtime_apis::{
118
        dry_run::{CallDryRunEffects, Error as XcmDryRunApiError, XcmDryRunEffects},
119
        fees::Error as XcmPaymentApiError,
120
    },
121
};
122
pub use {
123
    dp_core::{AccountId, Address, Balance, BlockNumber, Hash, Header, Index, Signature},
124
    sp_runtime::{MultiAddress, Perbill, Permill},
125
};
126

            
127
/// Block type as expected by this runtime.
128
pub type Block = generic::Block<Header, UncheckedExtrinsic>;
129
/// A Block signed with a Justification
130
pub type SignedBlock = generic::SignedBlock<Block>;
131
/// BlockId type as expected by this runtime.
132
pub type BlockId = generic::BlockId<Block>;
133

            
134
/// CollatorId type expected by this runtime.
135
pub type CollatorId = AccountId;
136

            
137
/// The SignedExtension to the basic transaction logic.
138
pub type SignedExtra = (
139
    frame_system::CheckNonZeroSender<Runtime>,
140
    frame_system::CheckSpecVersion<Runtime>,
141
    frame_system::CheckTxVersion<Runtime>,
142
    frame_system::CheckGenesis<Runtime>,
143
    frame_system::CheckEra<Runtime>,
144
    frame_system::CheckNonce<Runtime>,
145
    frame_system::CheckWeight<Runtime>,
146
    pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
147
    cumulus_primitives_storage_weight_reclaim::StorageWeightReclaim<Runtime>,
148
);
149

            
150
/// Unchecked extrinsic type as expected by this runtime.
151
pub type UncheckedExtrinsic =
152
    generic::UncheckedExtrinsic<Address, RuntimeCall, Signature, SignedExtra>;
153

            
154
/// Extrinsic type that has already been checked.
155
pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, RuntimeCall, SignedExtra>;
156

            
157
/// Executive: handles dispatch to the various modules.
158
pub type Executive = frame_executive::Executive<
159
    Runtime,
160
    Block,
161
    frame_system::ChainContext<Runtime>,
162
    Runtime,
163
    AllPalletsWithSystem,
164
>;
165

            
166
/// DANCE, the native token, uses 12 decimals of precision.
167
pub mod currency {
168
    use super::Balance;
169

            
170
    // Provide a common factor between runtimes based on a supply of 10_000_000 tokens.
171
    pub const SUPPLY_FACTOR: Balance = 100;
172

            
173
    pub const MICRODANCE: Balance = 1_000_000;
174
    pub const MILLIDANCE: Balance = 1_000_000_000;
175
    pub const DANCE: Balance = 1_000_000_000_000;
176
    pub const KILODANCE: Balance = 1_000_000_000_000_000;
177

            
178
    pub const STORAGE_BYTE_FEE: Balance = 100 * MICRODANCE * SUPPLY_FACTOR;
179
    pub const STORAGE_ITEM_FEE: Balance = 100 * MILLIDANCE * SUPPLY_FACTOR;
180

            
181
3541
    pub const fn deposit(items: u32, bytes: u32) -> Balance {
182
3541
        items as Balance * STORAGE_ITEM_FEE + (bytes as Balance) * STORAGE_BYTE_FEE
183
3541
    }
184
}
185

            
186
/// Handles converting a weight scalar to a fee value, based on the scale and granularity of the
187
/// node's balance type.
188
///
189
/// This should typically create a mapping between the following ranges:
190
///   - `[0, MAXIMUM_BLOCK_WEIGHT]`
191
///   - `[Balance::min, Balance::max]`
192
///
193
/// Yet, it can be used for any other sort of change to weight-fee. Some examples being:
194
///   - Setting it to `0` will essentially disable the weight fee.
195
///   - Setting it to `1` will cause the literal `#[weight = x]` values to be charged.
196
pub struct WeightToFee;
197
impl WeightToFeePolynomial for WeightToFee {
198
    type Balance = Balance;
199
11349
    fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {
200
11349
        // in Rococo, extrinsic base weight (smallest non-zero weight) is mapped to 1 MILLIUNIT:
201
11349
        // in our template, we map to 1/10 of that, or 1/10 MILLIUNIT
202
11349
        let p = MILLIUNIT / 10;
203
11349
        let q = 100 * Balance::from(ExtrinsicBaseWeight::get().ref_time());
204
11349
        smallvec![WeightToFeeCoefficient {
205
            degree: 1,
206
            negative: false,
207
            coeff_frac: Perbill::from_rational(p % q, q),
208
            coeff_integer: p / q,
209
        }]
210
11349
    }
211
}
212

            
213
/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know
214
/// the specifics of the runtime. They can then be made to be agnostic over specific formats
215
/// of data like extrinsics, allowing for them to continue syncing the network through upgrades
216
/// to even the core data structures.
217
pub mod opaque {
218
    use {
219
        super::*,
220
        sp_runtime::{
221
            generic,
222
            traits::{BlakeTwo256, Hash as HashT},
223
        },
224
    };
225

            
226
    pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;
227
    /// Opaque block header type.
228
    pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
229
    /// Opaque block type.
230
    pub type Block = generic::Block<Header, UncheckedExtrinsic>;
231
    /// Opaque block identifier type.
232
    pub type BlockId = generic::BlockId<Block>;
233
    /// Opaque block hash type.
234
    pub type Hash = <BlakeTwo256 as HashT>::Output;
235
    /// Opaque signature type.
236
    pub use super::Signature;
237
}
238

            
239
impl_opaque_keys! {
240
    pub struct SessionKeys {
241
        pub nimbus: Initializer,
242
    }
243
}
244

            
245
#[sp_version::runtime_version]
246
pub const VERSION: RuntimeVersion = RuntimeVersion {
247
    spec_name: create_runtime_str!("dancebox"),
248
    impl_name: create_runtime_str!("dancebox"),
249
    authoring_version: 1,
250
    spec_version: 1100,
251
    impl_version: 0,
252
    apis: RUNTIME_API_VERSIONS,
253
    transaction_version: 1,
254
    state_version: 1,
255
};
256

            
257
/// This determines the average expected block time that we are targeting.
258
/// Blocks will be produced at a minimum duration defined by `SLOT_DURATION`.
259
/// `SLOT_DURATION` is picked up by `pallet_timestamp` which is in turn picked
260
/// up by `pallet_aura` to implement `fn slot_duration()`.
261
///
262
/// Change this to adjust the block time.
263
pub const MILLISECS_PER_BLOCK: u64 = 6000;
264

            
265
// NOTE: Currently it is not possible to change the slot duration after the chain has started.
266
//       Attempting to do so will brick block production.
267
pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;
268

            
269
// Time is measured by number of blocks.
270
pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);
271
pub const HOURS: BlockNumber = MINUTES * 60;
272
pub const DAYS: BlockNumber = HOURS * 24;
273

            
274
// Unit = the base number of indivisible units for balances
275
pub const UNIT: Balance = 1_000_000_000_000;
276
pub const MILLIUNIT: Balance = 1_000_000_000;
277
pub const MICROUNIT: Balance = 1_000_000;
278
/// The existential deposit. Set to 1/10 of the Connected Relay Chain.
279
pub const EXISTENTIAL_DEPOSIT: Balance = MILLIUNIT;
280

            
281
/// We assume that ~5% of the block weight is consumed by `on_initialize` handlers. This is
282
/// used to limit the maximal weight of a single extrinsic.
283
const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(5);
284

            
285
/// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used by
286
/// `Operational` extrinsics.
287
const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);
288

            
289
/// We allow for 2 seconds of compute with a 6 second average block time
290
const MAXIMUM_BLOCK_WEIGHT: Weight = Weight::from_parts(
291
    WEIGHT_REF_TIME_PER_SECOND.saturating_mul(2),
292
    cumulus_primitives_core::relay_chain::MAX_POV_SIZE as u64,
293
);
294

            
295
/// The version information used to identify this runtime when compiled natively.
296
#[cfg(feature = "std")]
297
2700
pub fn native_version() -> NativeVersion {
298
2700
    NativeVersion {
299
2700
        runtime_version: VERSION,
300
2700
        can_author_with: Default::default(),
301
2700
    }
302
2700
}
303

            
304
parameter_types! {
305
    pub const Version: RuntimeVersion = VERSION;
306

            
307
    // This part is copied from Substrate's `bin/node/runtime/src/lib.rs`.
308
    //  The `RuntimeBlockLength` and `RuntimeBlockWeights` exist here because the
309
    // `DeletionWeightLimit` and `DeletionQueueDepth` depend on those to parameterize
310
    // the lazy contract deletion.
311
    pub RuntimeBlockLength: BlockLength =
312
        BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);
313
    pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()
314
        .base_block(BlockExecutionWeight::get())
315
1233018
        .for_class(DispatchClass::all(), |weights| {
316
1233018
            weights.base_extrinsic = ExtrinsicBaseWeight::get();
317
1233018
        })
318
411006
        .for_class(DispatchClass::Normal, |weights| {
319
411006
            weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);
320
411006
        })
321
411006
        .for_class(DispatchClass::Operational, |weights| {
322
411006
            weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);
323
411006
            // Operational transactions have some extra reserved space, so that they
324
411006
            // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.
325
411006
            weights.reserved = Some(
326
411006
                MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT
327
411006
            );
328
411006
        })
329
        .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)
330
        .build_or_panic();
331
    pub const SS58Prefix: u16 = 42;
332
}
333

            
334
// Configure FRAME pallets to include in runtime.
335

            
336
impl frame_system::Config for Runtime {
337
    /// The identifier used to distinguish between accounts.
338
    type AccountId = AccountId;
339
    /// The aggregated dispatch type that is available for extrinsics.
340
    type RuntimeCall = RuntimeCall;
341
    /// The lookup mechanism to get account ID from whatever is passed in dispatchers.
342
    type Lookup = AccountIdLookup<AccountId, ()>;
343
    /// The index type for storing how many extrinsics an account has signed.
344
    type Nonce = Index;
345
    /// The index type for blocks.
346
    type Block = Block;
347
    /// The type for hashing blocks and tries.
348
    type Hash = Hash;
349
    /// The hashing algorithm used.
350
    type Hashing = BlakeTwo256;
351
    /// The ubiquitous event type.
352
    type RuntimeEvent = RuntimeEvent;
353
    /// The ubiquitous origin type.
354
    type RuntimeOrigin = RuntimeOrigin;
355
    /// Maximum number of block number to block hash mappings to keep (oldest pruned first).
356
    type BlockHashCount = BlockHashCount;
357
    /// Runtime version.
358
    type Version = Version;
359
    /// Converts a module to an index of this module in the runtime.
360
    type PalletInfo = PalletInfo;
361
    /// The data to be stored in an account.
362
    type AccountData = pallet_balances::AccountData<Balance>;
363
    /// What to do if a new account is created.
364
    type OnNewAccount = ();
365
    /// What to do if an account is fully reaped from the system.
366
    type OnKilledAccount = ();
367
    /// The weight of database operations that the runtime can invoke.
368
    type DbWeight = RocksDbWeight;
369
    /// The basic call filter to use in dispatchable.
370
    type BaseCallFilter = InsideBoth<MaintenanceMode, TxPause>;
371
    /// Weight information for the extrinsics of this pallet.
372
    type SystemWeightInfo = weights::frame_system::SubstrateWeight<Runtime>;
373
    /// Block & extrinsics weights: base values and limits.
374
    type BlockWeights = RuntimeBlockWeights;
375
    /// The maximum length of a block (in bytes).
376
    type BlockLength = RuntimeBlockLength;
377
    /// This is used as an identifier of the chain. 42 is the generic substrate prefix.
378
    type SS58Prefix = SS58Prefix;
379
    /// The action to take on a Runtime Upgrade
380
    type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;
381
    type MaxConsumers = frame_support::traits::ConstU32<16>;
382
    type RuntimeTask = RuntimeTask;
383
    type SingleBlockMigrations = ();
384
    type MultiBlockMigrator = ();
385
    type PreInherents = ();
386
    type PostInherents = ();
387
    type PostTransactions = ();
388
}
389

            
390
impl pallet_timestamp::Config for Runtime {
391
    /// A timestamp: milliseconds since the unix epoch.
392
    type Moment = u64;
393
    type OnTimestampSet = dp_consensus::OnTimestampSet<
394
        <Self as pallet_author_inherent::Config>::SlotBeacon,
395
        ConstU64<{ SLOT_DURATION }>,
396
    >;
397
    type MinimumPeriod = ConstU64<{ SLOT_DURATION / 2 }>;
398
    type WeightInfo = weights::pallet_timestamp::SubstrateWeight<Runtime>;
399
}
400

            
401
pub struct CanAuthor;
402
impl nimbus_primitives::CanAuthor<NimbusId> for CanAuthor {
403
23212
    fn can_author(author: &NimbusId, slot: &u32) -> bool {
404
23212
        let authorities = AuthorityAssignment::collator_container_chain(Session::current_index())
405
23212
            .expect("authorities should be set")
406
23212
            .orchestrator_chain;
407
23212

            
408
23212
        if authorities.is_empty() {
409
            return false;
410
23212
        }
411
23212

            
412
23212
        let author_index = (*slot as usize) % authorities.len();
413
23212
        let expected_author = &authorities[author_index];
414
23212

            
415
23212
        expected_author == author
416
23212
    }
417
    #[cfg(feature = "runtime-benchmarks")]
418
    fn get_authors(_slot: &u32) -> Vec<NimbusId> {
419
        AuthorityAssignment::collator_container_chain(Session::current_index())
420
            .expect("authorities should be set")
421
            .orchestrator_chain
422
    }
423
}
424

            
425
impl pallet_author_inherent::Config for Runtime {
426
    type AuthorId = NimbusId;
427
    type AccountLookup = dp_consensus::NimbusLookUp;
428
    type CanAuthor = CanAuthor;
429
    type SlotBeacon = dp_consensus::AuraDigestSlotBeacon<Runtime>;
430
    type WeightInfo = weights::pallet_author_inherent::SubstrateWeight<Runtime>;
431
}
432

            
433
parameter_types! {
434
    pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT;
435
}
436

            
437
impl pallet_balances::Config for Runtime {
438
    type MaxLocks = ConstU32<50>;
439
    /// The type for recording an account's balance.
440
    type Balance = Balance;
441
    /// The ubiquitous event type.
442
    type RuntimeEvent = RuntimeEvent;
443
    type DustRemoval = ();
444
    type ExistentialDeposit = ExistentialDeposit;
445
    type AccountStore = System;
446
    type MaxReserves = ConstU32<50>;
447
    type ReserveIdentifier = [u8; 8];
448
    type FreezeIdentifier = RuntimeFreezeReason;
449
    type MaxFreezes = ConstU32<10>;
450
    type RuntimeHoldReason = RuntimeHoldReason;
451
    type RuntimeFreezeReason = RuntimeFreezeReason;
452
    type WeightInfo = weights::pallet_balances::SubstrateWeight<Runtime>;
453
}
454

            
455
pub struct DealWithFees<R>(sp_std::marker::PhantomData<R>);
456
impl<R> OnUnbalanced<Credit<R::AccountId, pallet_balances::Pallet<R>>> for DealWithFees<R>
457
where
458
    R: pallet_balances::Config + pallet_treasury::Config + frame_system::Config,
459
    pallet_treasury::NegativeImbalanceOf<R>: From<NegativeImbalance<R>>,
460
{
461
    // this seems to be called for substrate-based transactions
462
2226
    fn on_unbalanceds<B>(
463
2226
        mut fees_then_tips: impl Iterator<Item = Credit<R::AccountId, pallet_balances::Pallet<R>>>,
464
2226
    ) {
465
2226
        if let Some(fees) = fees_then_tips.next() {
466
            // 80% is burned, 20% goes to the treasury
467
            // Same policy applies for tips as well
468
2226
            let burn_percentage = 80;
469
2226
            let treasury_percentage = 20;
470
2226

            
471
2226
            let (_, to_treasury) = fees.ration(burn_percentage, treasury_percentage);
472
2226
            ResolveTo::<pallet_treasury::TreasuryAccountId<R>, pallet_balances::Pallet<R>>::on_unbalanced(to_treasury);
473
            // Balances pallet automatically burns dropped Negative Imbalances by decreasing total_supply accordingly
474
            // handle tip if there is one
475
2226
            if let Some(tip) = fees_then_tips.next() {
476
2226
                let (_, to_treasury) = tip.ration(burn_percentage, treasury_percentage);
477
2226
                ResolveTo::<pallet_treasury::TreasuryAccountId<R>, pallet_balances::Pallet<R>>::on_unbalanced(to_treasury);
478
2226
            }
479
        }
480
2226
    }
481

            
482
    // this is called from pallet_evm for Ethereum-based transactions
483
    // (technically, it calls on_unbalanced, which calls this when non-zero)
484
    fn on_nonzero_unbalanced(amount: Credit<R::AccountId, pallet_balances::Pallet<R>>) {
485
        // 80% is burned, 20% goes to the treasury
486
        let burn_percentage = 80;
487
        let treasury_percentage = 20;
488

            
489
        let (_, to_treasury) = amount.ration(burn_percentage, treasury_percentage);
490
        ResolveTo::<pallet_treasury::TreasuryAccountId<R>, pallet_balances::Pallet<R>>::on_unbalanced(to_treasury);
491
    }
492
}
493

            
494
parameter_types! {
495
    pub const TransactionByteFee: Balance = 1;
496
}
497

            
498
impl pallet_transaction_payment::Config for Runtime {
499
    type RuntimeEvent = RuntimeEvent;
500
    // This will burn 80% from fees & tips and deposit the remainder into the treasury
501
    type OnChargeTransaction = FungibleAdapter<Balances, DealWithFees<Runtime>>;
502
    type OperationalFeeMultiplier = ConstU8<5>;
503
    type WeightToFee = WeightToFee;
504
    type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;
505
    type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Self>;
506
}
507

            
508
parameter_types! {
509
    pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
510
    pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
511
    pub const RelayOrigin: AggregateMessageOrigin = AggregateMessageOrigin::Parent;
512
}
513

            
514
pub const RELAY_CHAIN_SLOT_DURATION_MILLIS: u32 = 6000;
515
pub const UNINCLUDED_SEGMENT_CAPACITY: u32 = 3;
516
pub const BLOCK_PROCESSING_VELOCITY: u32 = 1;
517

            
518
type ConsensusHook = pallet_async_backing::consensus_hook::FixedVelocityConsensusHook<
519
    Runtime,
520
    BLOCK_PROCESSING_VELOCITY,
521
    UNINCLUDED_SEGMENT_CAPACITY,
522
>;
523

            
524
impl cumulus_pallet_parachain_system::Config for Runtime {
525
    type WeightInfo = weights::cumulus_pallet_parachain_system::SubstrateWeight<Runtime>;
526
    type RuntimeEvent = RuntimeEvent;
527
    type OnSystemEvent = ();
528
    type SelfParaId = parachain_info::Pallet<Runtime>;
529
    type OutboundXcmpMessageSource = XcmpQueue;
530
    type DmpQueue = frame_support::traits::EnqueueWithOrigin<MessageQueue, RelayOrigin>;
531
    type ReservedDmpWeight = ReservedDmpWeight;
532
    type XcmpMessageHandler = XcmpQueue;
533
    type ReservedXcmpWeight = ReservedXcmpWeight;
534
    type CheckAssociatedRelayNumber = RelayNumberMonotonicallyIncreases;
535
    type ConsensusHook = ConsensusHook;
536
}
537
pub struct ParaSlotProvider;
538
impl Get<(Slot, SlotDuration)> for ParaSlotProvider {
539
21219
    fn get() -> (Slot, SlotDuration) {
540
21219
        let slot = u64::from(<Runtime as pallet_author_inherent::Config>::SlotBeacon::slot());
541
21219
        (Slot::from(slot), SlotDuration::from_millis(SLOT_DURATION))
542
21219
    }
543
}
544

            
545
parameter_types! {
546
    pub const ExpectedBlockTime: u64 = MILLISECS_PER_BLOCK;
547
}
548

            
549
impl pallet_async_backing::Config for Runtime {
550
    type AllowMultipleBlocksPerSlot = ConstBool<true>;
551
    type GetAndVerifySlot =
552
        pallet_async_backing::ParaSlot<RELAY_CHAIN_SLOT_DURATION_MILLIS, ParaSlotProvider>;
553
    type ExpectedBlockTime = ExpectedBlockTime;
554
}
555

            
556
/// Only callable after `set_validation_data` is called which forms this proof the same way
557
2216
fn relay_chain_state_proof() -> RelayChainStateProof {
558
2216
    let relay_storage_root =
559
2216
        RelaychainDataProvider::<Runtime>::current_relay_chain_state().state_root;
560
2216
    let relay_chain_state = cumulus_pallet_parachain_system::RelayStateProof::<Runtime>::get()
561
2216
        .expect("set in `set_validation_data`");
562
2216
    RelayChainStateProof::new(ParachainInfo::get(), relay_storage_root, relay_chain_state)
563
2216
        .expect("Invalid relay chain state proof, already constructed in `set_validation_data`")
564
2216
}
565

            
566
pub struct BabeCurrentBlockRandomnessGetter;
567
impl BabeCurrentBlockRandomnessGetter {
568
2216
    fn get_block_randomness() -> Option<Hash> {
569
2216
        if cfg!(feature = "runtime-benchmarks") {
570
            // storage reads as per actual reads
571
            let _relay_storage_root =
572
                RelaychainDataProvider::<Runtime>::current_relay_chain_state().state_root;
573

            
574
            let _relay_chain_state =
575
                cumulus_pallet_parachain_system::RelayStateProof::<Runtime>::get();
576
            let benchmarking_babe_output = Hash::default();
577
            return Some(benchmarking_babe_output);
578
2216
        }
579
2216

            
580
2216
        relay_chain_state_proof()
581
2216
            .read_optional_entry::<Option<Hash>>(
582
2216
                relay_chain::well_known_keys::CURRENT_BLOCK_RANDOMNESS,
583
2216
            )
584
2216
            .ok()
585
2216
            .flatten()
586
2216
            .flatten()
587
2216
    }
588

            
589
    /// Return the block randomness from the relay mixed with the provided subject.
590
    /// This ensures that the randomness will be different on different pallets, as long as the subject is different.
591
    // TODO: audit usage of randomness API
592
    // https://github.com/paritytech/polkadot/issues/2601
593
2216
    fn get_block_randomness_mixed(subject: &[u8]) -> Option<Hash> {
594
2216
        Self::get_block_randomness()
595
2216
            .map(|random_hash| mix_randomness::<Runtime>(random_hash, subject))
596
2216
    }
597
}
598

            
599
/// Combines the vrf output of the previous relay block with the provided subject.
600
/// This ensures that the randomness will be different on different pallets, as long as the subject is different.
601
26
fn mix_randomness<T: frame_system::Config>(vrf_output: Hash, subject: &[u8]) -> T::Hash {
602
26
    let mut digest = Vec::new();
603
26
    digest.extend_from_slice(vrf_output.as_ref());
604
26
    digest.extend_from_slice(subject);
605
26

            
606
26
    T::Hashing::hash(digest.as_slice())
607
26
}
608

            
609
// Randomness trait
610
impl frame_support::traits::Randomness<Hash, BlockNumber> for BabeCurrentBlockRandomnessGetter {
611
    fn random(subject: &[u8]) -> (Hash, BlockNumber) {
612
        let block_number = frame_system::Pallet::<Runtime>::block_number();
613
        let randomness = Self::get_block_randomness_mixed(subject).unwrap_or_default();
614

            
615
        (randomness, block_number)
616
    }
617
}
618

            
619
pub struct OwnApplySession;
620
impl pallet_initializer::ApplyNewSession<Runtime> for OwnApplySession {
621
2396
    fn apply_new_session(
622
2396
        _changed: bool,
623
2396
        session_index: u32,
624
2396
        all_validators: Vec<(AccountId, NimbusId)>,
625
2396
        queued: Vec<(AccountId, NimbusId)>,
626
2396
    ) {
627
2396
        // We first initialize Configuration
628
2396
        Configuration::initializer_on_new_session(&session_index);
629
2396
        // Next: Registrar
630
2396
        Registrar::initializer_on_new_session(&session_index);
631
2396
        // Next: AuthorityMapping
632
2396
        AuthorityMapping::initializer_on_new_session(&session_index, &all_validators);
633
2396

            
634
9122
        let next_collators = queued.iter().map(|(k, _)| k.clone()).collect();
635
2396

            
636
2396
        // Next: CollatorAssignment
637
2396
        let assignments =
638
2396
            CollatorAssignment::initializer_on_new_session(&session_index, next_collators);
639
2396

            
640
2396
        let queued_id_to_nimbus_map = queued.iter().cloned().collect();
641
2396
        AuthorityAssignment::initializer_on_new_session(
642
2396
            &session_index,
643
2396
            &queued_id_to_nimbus_map,
644
2396
            &assignments.next_assignment,
645
2396
        );
646
2396
    }
647
}
648

            
649
impl pallet_initializer::Config for Runtime {
650
    type SessionIndex = u32;
651

            
652
    /// The identifier type for an authority.
653
    type AuthorityId = NimbusId;
654

            
655
    type SessionHandler = OwnApplySession;
656
}
657

            
658
impl parachain_info::Config for Runtime {}
659

            
660
/// Returns a list of collators by combining pallet_invulnerables and pallet_pooled_staking.
661
pub struct CollatorsFromInvulnerablesAndThenFromStaking;
662

            
663
/// Play the role of the session manager.
664
impl SessionManager<CollatorId> for CollatorsFromInvulnerablesAndThenFromStaking {
665
2588
    fn new_session(index: SessionIndex) -> Option<Vec<CollatorId>> {
666
2588
        if <frame_system::Pallet<Runtime>>::block_number() == 0 {
667
            // Do not show this log in genesis
668
384
            log::debug!(
669
                "assembling new collators for new session {} at #{:?}",
670
                index,
671
                <frame_system::Pallet<Runtime>>::block_number(),
672
            );
673
        } else {
674
2204
            log::info!(
675
1992
                "assembling new collators for new session {} at #{:?}",
676
1992
                index,
677
1992
                <frame_system::Pallet<Runtime>>::block_number(),
678
            );
679
        }
680

            
681
2588
        let invulnerables = Invulnerables::invulnerables().to_vec();
682
2588
        let candidates_staking =
683
2588
            pallet_pooled_staking::SortedEligibleCandidates::<Runtime>::get().to_vec();
684
2588
        // Max number of collators is set in pallet_configuration
685
2588
        let target_session_index = index.saturating_add(1);
686
2588
        let max_collators =
687
2588
            <Configuration as GetHostConfiguration<u32>>::max_collators(target_session_index);
688
2588
        let collators = invulnerables
689
2588
            .iter()
690
2588
            .cloned()
691
2588
            .chain(candidates_staking.into_iter().filter_map(|elig| {
692
244
                let cand = elig.candidate;
693
244
                if invulnerables.contains(&cand) {
694
                    // If a candidate is both in pallet_invulnerables and pallet_staking, do not count it twice
695
56
                    None
696
                } else {
697
188
                    Some(cand)
698
                }
699
2588
            }))
700
2588
            .take(max_collators as usize)
701
2588
            .collect();
702
2588

            
703
2588
        // TODO: weight?
704
2588
        /*
705
2588
        frame_system::Pallet::<T>::register_extra_weight_unchecked(
706
2588
            T::WeightInfo::new_session(invulnerables.len() as u32),
707
2588
            DispatchClass::Mandatory,
708
2588
        );
709
2588
        */
710
2588
        Some(collators)
711
2588
    }
712
2396
    fn start_session(_: SessionIndex) {
713
2396
        // we don't care.
714
2396
    }
715
2204
    fn end_session(_: SessionIndex) {
716
2204
        // we don't care.
717
2204
    }
718
}
719

            
720
parameter_types! {
721
    pub const Period: u32 = prod_or_fast!(1 * HOURS, 1 * MINUTES);
722
    pub const Offset: u32 = 0;
723
}
724

            
725
impl pallet_session::Config for Runtime {
726
    type RuntimeEvent = RuntimeEvent;
727
    type ValidatorId = CollatorId;
728
    // we don't have stash and controller, thus we don't need the convert as well.
729
    type ValidatorIdOf = ConvertInto;
730
    type ShouldEndSession = pallet_session::PeriodicSessions<Period, Offset>;
731
    type NextSessionRotation = pallet_session::PeriodicSessions<Period, Offset>;
732
    type SessionManager = CollatorsFromInvulnerablesAndThenFromStaking;
733
    // Essentially just Aura, but let's be pedantic.
734
    type SessionHandler = <SessionKeys as sp_runtime::traits::OpaqueKeys>::KeyTypeIdProviders;
735
    type Keys = SessionKeys;
736
    type WeightInfo = weights::pallet_session::SubstrateWeight<Runtime>;
737
}
738

            
739
/// Read full_rotation_period from pallet_configuration
740
pub struct ConfigurationCollatorRotationSessionPeriod;
741

            
742
impl Get<u32> for ConfigurationCollatorRotationSessionPeriod {
743
4684
    fn get() -> u32 {
744
4684
        Configuration::config().full_rotation_period
745
4684
    }
746
}
747

            
748
pub struct BabeGetRandomnessForNextBlock;
749

            
750
impl GetRandomnessForNextBlock<u32> for BabeGetRandomnessForNextBlock {
751
46310
    fn should_end_session(n: u32) -> bool {
752
46310
        <Runtime as pallet_session::Config>::ShouldEndSession::should_end_session(n)
753
46310
    }
754

            
755
2216
    fn get_randomness() -> [u8; 32] {
756
2216
        let block_number = System::block_number();
757
2216
        let random_seed = if block_number != 0 {
758
26
            if let Some(random_hash) =
759
2216
                BabeCurrentBlockRandomnessGetter::get_block_randomness_mixed(b"CollatorAssignment")
760
            {
761
                // Return random_hash as a [u8; 32] instead of a Hash
762
26
                let mut buf = [0u8; 32];
763
26
                let len = sp_std::cmp::min(32, random_hash.as_ref().len());
764
26
                buf[..len].copy_from_slice(&random_hash.as_ref()[..len]);
765
26

            
766
26
                buf
767
            } else {
768
                // If there is no randomness (e.g when running in dev mode), return [0; 32]
769
2190
                [0; 32]
770
            }
771
        } else {
772
            // In block 0 (genesis) there is no randomness
773
            [0; 32]
774
        };
775

            
776
2216
        random_seed
777
2216
    }
778
}
779

            
780
pub struct RemoveInvulnerablesImpl;
781

            
782
impl RemoveInvulnerables<CollatorId> for RemoveInvulnerablesImpl {
783
3040
    fn remove_invulnerables(
784
3040
        collators: &mut Vec<CollatorId>,
785
3040
        num_invulnerables: usize,
786
3040
    ) -> Vec<CollatorId> {
787
3040
        if num_invulnerables == 0 {
788
            return vec![];
789
3040
        }
790
3040
        // TODO: check if this works on session changes
791
3040
        let all_invulnerables = pallet_invulnerables::Invulnerables::<Runtime>::get();
792
3040
        if all_invulnerables.is_empty() {
793
144
            return vec![];
794
2896
        }
795
2896
        let mut invulnerables = vec![];
796
2896
        // TODO: use binary_search when invulnerables are sorted
797
3826
        collators.retain(|x| {
798
3826
            if invulnerables.len() < num_invulnerables && all_invulnerables.contains(x) {
799
2693
                invulnerables.push(x.clone());
800
2693
                false
801
            } else {
802
1133
                true
803
            }
804
3826
        });
805
2896

            
806
2896
        invulnerables
807
3040
    }
808
}
809

            
810
pub struct RemoveParaIdsWithNoCreditsImpl;
811

            
812
impl RemoveParaIdsWithNoCredits for RemoveParaIdsWithNoCreditsImpl {
813
4792
    fn remove_para_ids_with_no_credits(
814
4792
        para_ids: &mut Vec<ParaId>,
815
4792
        currently_assigned: &BTreeSet<ParaId>,
816
4792
    ) {
817
4792
        let blocks_per_session = Period::get();
818
4792

            
819
4792
        para_ids.retain(|para_id| {
820
            // If the para has been assigned collators for this session it must have enough block credits
821
            // for the current and the next session.
822
4372
            let block_credits_needed = if currently_assigned.contains(para_id) {
823
3915
                blocks_per_session * 2
824
            } else {
825
457
                blocks_per_session
826
            };
827

            
828
            // Check if the container chain has enough credits for producing blocks
829
4372
            let free_block_credits = pallet_services_payment::BlockProductionCredits::<Runtime>::get(para_id)
830
4372
                .unwrap_or_default();
831
4372

            
832
4372
            // Check if the container chain has enough credits for a session assignments
833
4372
            let free_session_credits = pallet_services_payment::CollatorAssignmentCredits::<Runtime>::get(para_id)
834
4372
                .unwrap_or_default();
835
4372

            
836
4372
            // If para's max tip is set it should have enough to pay for one assignment with tip
837
4372
            let max_tip = pallet_services_payment::MaxTip::<Runtime>::get(para_id).unwrap_or_default() ;
838
4372

            
839
4372
            // Return if we can survive with free credits
840
4372
            if free_block_credits >= block_credits_needed && free_session_credits >= 1 {
841
                // Max tip should always be checked, as it can be withdrawn even if free credits were used
842
3992
                return Balances::can_withdraw(&pallet_services_payment::Pallet::<Runtime>::parachain_tank(*para_id), max_tip).into_result(true).is_ok()
843
380
            }
844
380

            
845
380
            let remaining_block_credits = block_credits_needed.saturating_sub(free_block_credits);
846
380
            let remaining_session_credits = 1u32.saturating_sub(free_session_credits);
847
380

            
848
380
            let (block_production_costs, _) = <Runtime as pallet_services_payment::Config>::ProvideBlockProductionCost::block_cost(para_id);
849
380
            let (collator_assignment_costs, _) = <Runtime as pallet_services_payment::Config>::ProvideCollatorAssignmentCost::collator_assignment_cost(para_id);
850
380
            // let's check if we can withdraw
851
380
            let remaining_block_credits_to_pay = u128::from(remaining_block_credits).saturating_mul(block_production_costs);
852
380
            let remaining_session_credits_to_pay = u128::from(remaining_session_credits).saturating_mul(collator_assignment_costs);
853
380

            
854
380
            let remaining_to_pay = remaining_block_credits_to_pay.saturating_add(remaining_session_credits_to_pay).saturating_add(max_tip);
855
380

            
856
380
            // This should take into account whether we tank goes below ED
857
380
            // The true refers to keepAlive
858
380
            Balances::can_withdraw(&pallet_services_payment::Pallet::<Runtime>::parachain_tank(*para_id), remaining_to_pay).into_result(true).is_ok()
859
4792
        });
860
4792
    }
861

            
862
    /// Make those para ids valid by giving them enough credits, for benchmarking.
863
    #[cfg(feature = "runtime-benchmarks")]
864
    fn make_valid_para_ids(para_ids: &[ParaId]) {
865
        use frame_support::assert_ok;
866

            
867
        let blocks_per_session = Period::get();
868
        // Enough credits to run any benchmark
869
        let block_credits = 20 * blocks_per_session;
870
        let session_credits = 20;
871

            
872
        for para_id in para_ids {
873
            assert_ok!(ServicesPayment::set_block_production_credits(
874
                RuntimeOrigin::root(),
875
                *para_id,
876
                block_credits,
877
            ));
878
            assert_ok!(ServicesPayment::set_collator_assignment_credits(
879
                RuntimeOrigin::root(),
880
                *para_id,
881
                session_credits,
882
            ));
883
        }
884
    }
885
}
886

            
887
impl pallet_collator_assignment::Config for Runtime {
888
    type RuntimeEvent = RuntimeEvent;
889
    type HostConfiguration = Configuration;
890
    type ContainerChains = Registrar;
891
    type SessionIndex = u32;
892
    type SelfParaId = ParachainInfo;
893
    type ShouldRotateAllCollators =
894
        RotateCollatorsEveryNSessions<ConfigurationCollatorRotationSessionPeriod>;
895
    type GetRandomnessForNextBlock = BabeGetRandomnessForNextBlock;
896
    type RemoveInvulnerables = RemoveInvulnerablesImpl;
897
    type RemoveParaIdsWithNoCredits = RemoveParaIdsWithNoCreditsImpl;
898
    type CollatorAssignmentHook = ServicesPayment;
899
    type CollatorAssignmentTip = ServicesPayment;
900
    type Currency = Balances;
901
    type ForceEmptyOrchestrator = ConstBool<false>;
902
    type CoreAllocationConfiguration = ();
903
    type WeightInfo = weights::pallet_collator_assignment::SubstrateWeight<Runtime>;
904
}
905

            
906
impl pallet_authority_assignment::Config for Runtime {
907
    type SessionIndex = u32;
908
    type AuthorityId = NimbusId;
909
}
910

            
911
pub const FIXED_BLOCK_PRODUCTION_COST: u128 = 1 * currency::MICRODANCE;
912
pub const FIXED_COLLATOR_ASSIGNMENT_COST: u128 = 100 * currency::MICRODANCE;
913

            
914
pub struct BlockProductionCost<Runtime>(PhantomData<Runtime>);
915
impl ProvideBlockProductionCost<Runtime> for BlockProductionCost<Runtime> {
916
788
    fn block_cost(_para_id: &ParaId) -> (u128, Weight) {
917
788
        (FIXED_BLOCK_PRODUCTION_COST, Weight::zero())
918
788
    }
919
}
920

            
921
pub struct CollatorAssignmentCost<Runtime>(PhantomData<Runtime>);
922
impl ProvideCollatorAssignmentCost<Runtime> for CollatorAssignmentCost<Runtime> {
923
412
    fn collator_assignment_cost(_para_id: &ParaId) -> (u128, Weight) {
924
412
        (FIXED_COLLATOR_ASSIGNMENT_COST, Weight::zero())
925
412
    }
926
}
927

            
928
parameter_types! {
929
    // 60 days worth of blocks
930
    pub const FreeBlockProductionCredits: BlockNumber = 60 * DAYS;
931
    // 60 days worth of blocks
932
    pub const FreeCollatorAssignmentCredits: u32 = FreeBlockProductionCredits::get()/Period::get();
933
}
934

            
935
impl pallet_services_payment::Config for Runtime {
936
    type RuntimeEvent = RuntimeEvent;
937
    /// Handler for fees
938
    type OnChargeForBlock = ();
939
    type OnChargeForCollatorAssignment = ();
940
    type OnChargeForCollatorAssignmentTip = ();
941
    /// Currency type for fee payment
942
    type Currency = Balances;
943
    /// Provider of a block cost which can adjust from block to block
944
    type ProvideBlockProductionCost = BlockProductionCost<Runtime>;
945
    /// Provider of a block cost which can adjust from block to block
946
    type ProvideCollatorAssignmentCost = CollatorAssignmentCost<Runtime>;
947
    /// The maximum number of block credits that can be accumulated
948
    type FreeBlockProductionCredits = FreeBlockProductionCredits;
949
    /// The maximum number of session credits that can be accumulated
950
    type FreeCollatorAssignmentCredits = FreeCollatorAssignmentCredits;
951
    type ManagerOrigin =
952
        EitherOfDiverse<pallet_registrar::EnsureSignedByManager<Runtime>, EnsureRoot<AccountId>>;
953
    type WeightInfo = weights::pallet_services_payment::SubstrateWeight<Runtime>;
954
}
955

            
956
parameter_types! {
957
    pub const ProfileDepositBaseFee: Balance = currency::STORAGE_ITEM_FEE;
958
    pub const ProfileDepositByteFee: Balance = currency::STORAGE_BYTE_FEE;
959
    #[derive(Clone)]
960
    pub const MaxAssignmentsPerParaId: u32 = 10;
961
    #[derive(Clone)]
962
    pub const MaxNodeUrlLen: u32 = 200;
963
}
964

            
965
#[apply(derive_storage_traits)]
966
#[derive(Copy, Serialize, Deserialize, MaxEncodedLen)]
967
pub enum PreserversAssignementPaymentRequest {
968
441
    Free,
969
    StreamPayment {
970
        config: pallet_stream_payment::StreamConfigOf<Runtime>,
971
    },
972
}
973

            
974
#[apply(derive_storage_traits)]
975
#[derive(Copy, Serialize, Deserialize)]
976
pub enum PreserversAssignementPaymentExtra {
977
120
    Free,
978
    StreamPayment { initial_deposit: Balance },
979
}
980

            
981
#[apply(derive_storage_traits)]
982
#[derive(Copy, Serialize, Deserialize, MaxEncodedLen)]
983
pub enum PreserversAssignementPaymentWitness {
984
97
    Free,
985
    StreamPayment {
986
        stream_id: <Runtime as pallet_stream_payment::Config>::StreamId,
987
    },
988
}
989

            
990
pub struct PreserversAssignementPayment;
991

            
992
impl pallet_data_preservers::AssignmentPayment<AccountId> for PreserversAssignementPayment {
993
    /// Providers requests which kind of payment it accepts.
994
    type ProviderRequest = PreserversAssignementPaymentRequest;
995
    /// Extra parameter the assigner provides.
996
    type AssignerParameter = PreserversAssignementPaymentExtra;
997
    /// Represents the succesful outcome of the assignment.
998
    type AssignmentWitness = PreserversAssignementPaymentWitness;
999

            
94
    fn try_start_assignment(
94
        assigner: AccountId,
94
        provider: AccountId,
94
        request: &Self::ProviderRequest,
94
        extra: Self::AssignerParameter,
94
    ) -> Result<Self::AssignmentWitness, DispatchErrorWithPostInfo> {
94
        let witness = match (request, extra) {
94
            (Self::ProviderRequest::Free, Self::AssignerParameter::Free) => {
94
                Self::AssignmentWitness::Free
            }
            (
                Self::ProviderRequest::StreamPayment { config },
                Self::AssignerParameter::StreamPayment { initial_deposit },
            ) => {
                let stream_id = StreamPayment::open_stream_returns_id(
                    assigner,
                    provider,
                    *config,
                    initial_deposit,
                )?;
                Self::AssignmentWitness::StreamPayment { stream_id }
            }
            _ => Err(
                pallet_data_preservers::Error::<Runtime>::AssignmentPaymentRequestParameterMismatch,
            )?,
        };
94
        Ok(witness)
94
    }
12
    fn try_stop_assignment(
12
        provider: AccountId,
12
        witness: Self::AssignmentWitness,
12
    ) -> Result<(), DispatchErrorWithPostInfo> {
12
        match witness {
12
            Self::AssignmentWitness::Free => (),
            Self::AssignmentWitness::StreamPayment { stream_id } => {
                StreamPayment::close_stream(RuntimeOrigin::signed(provider), stream_id)?;
            }
        }
12
        Ok(())
12
    }
    /// Return the values for a free assignment if it is supported.
    /// This is required to perform automatic migration from old Bootnodes storage.
1
    fn free_variant_values() -> Option<(
1
        Self::ProviderRequest,
1
        Self::AssignerParameter,
1
        Self::AssignmentWitness,
1
    )> {
1
        Some((
1
            Self::ProviderRequest::Free,
1
            Self::AssignerParameter::Free,
1
            Self::AssignmentWitness::Free,
1
        ))
1
    }
    // The values returned by the following functions should match with each other.
    #[cfg(feature = "runtime-benchmarks")]
    fn benchmark_provider_request() -> Self::ProviderRequest {
        PreserversAssignementPaymentRequest::Free
    }
    #[cfg(feature = "runtime-benchmarks")]
    fn benchmark_assigner_parameter() -> Self::AssignerParameter {
        PreserversAssignementPaymentExtra::Free
    }
    #[cfg(feature = "runtime-benchmarks")]
    fn benchmark_assignment_witness() -> Self::AssignmentWitness {
        PreserversAssignementPaymentWitness::Free
    }
}
pub type DataPreserversProfileId = u64;
impl pallet_data_preservers::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type RuntimeHoldReason = RuntimeHoldReason;
    type Currency = Balances;
    type WeightInfo = weights::pallet_data_preservers::SubstrateWeight<Runtime>;
    type ProfileId = DataPreserversProfileId;
    type ProfileDeposit = tp_traits::BytesDeposit<ProfileDepositBaseFee, ProfileDepositByteFee>;
    type AssignmentPayment = PreserversAssignementPayment;
    type AssignmentOrigin = pallet_registrar::EnsureSignedByManager<Runtime>;
    type ForceSetProfileOrigin = EnsureRoot<AccountId>;
    type MaxAssignmentsPerParaId = MaxAssignmentsPerParaId;
    type MaxNodeUrlLen = MaxNodeUrlLen;
    type MaxParaIdsVecLen = MaxLengthParaIds;
}
impl pallet_author_noting::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type ContainerChains = Registrar;
    type SlotBeacon = dp_consensus::AuraDigestSlotBeacon<Runtime>;
    type ContainerChainAuthor = CollatorAssignment;
    // We benchmark each hook individually, so for runtime-benchmarks this should be empty
    #[cfg(feature = "runtime-benchmarks")]
    type AuthorNotingHook = ();
    #[cfg(not(feature = "runtime-benchmarks"))]
    type AuthorNotingHook = (XcmCoreBuyer, InflationRewards, ServicesPayment);
    type RelayOrPara = pallet_author_noting::ParaMode<
        cumulus_pallet_parachain_system::RelaychainDataProvider<Self>,
    >;
    type WeightInfo = weights::pallet_author_noting::SubstrateWeight<Runtime>;
}
parameter_types! {
    pub const PotId: PalletId = PalletId(*b"PotStake");
    pub const MaxCandidates: u32 = 1000;
    pub const MinCandidates: u32 = 5;
    pub const SessionLength: BlockNumber = 5;
    pub const MaxInvulnerables: u32 = 100;
    pub const ExecutiveBody: BodyId = BodyId::Executive;
}
impl pallet_invulnerables::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type UpdateOrigin = EnsureRoot<AccountId>;
    type MaxInvulnerables = MaxInvulnerables;
    type CollatorId = <Self as frame_system::Config>::AccountId;
    type CollatorIdOf = ConvertInto;
    type CollatorRegistration = Session;
    type WeightInfo = weights::pallet_invulnerables::SubstrateWeight<Runtime>;
    #[cfg(feature = "runtime-benchmarks")]
    type Currency = Balances;
}
parameter_types! {
    #[derive(Clone)]
    pub const MaxLengthParaIds: u32 = 100u32;
    pub const MaxEncodedGenesisDataSize: u32 = 5_000_000u32; // 5MB
}
pub struct CurrentSessionIndexGetter;
impl tp_traits::GetSessionIndex<u32> for CurrentSessionIndexGetter {
    /// Returns current session index.
239
    fn session_index() -> u32 {
239
        Session::current_index()
239
    }
}
impl pallet_configuration::Config for Runtime {
    type SessionDelay = ConstU32<2>;
    type SessionIndex = u32;
    type CurrentSessionIndex = CurrentSessionIndexGetter;
    type ForceEmptyOrchestrator = ConstBool<false>;
    type WeightInfo = weights::pallet_configuration::SubstrateWeight<Runtime>;
}
pub struct DanceboxRegistrarHooks;
impl RegistrarHooks for DanceboxRegistrarHooks {
69
    fn para_marked_valid_for_collating(para_id: ParaId) -> Weight {
69
        // Give free credits but only once per para id
69
        ServicesPayment::give_free_credits(&para_id)
69
    }
54
    fn para_deregistered(para_id: ParaId) -> Weight {
        // Clear pallet_author_noting storage
54
        if let Err(e) = AuthorNoting::kill_author_data(RuntimeOrigin::root(), para_id) {
            log::warn!(
                "Failed to kill_author_data after para id {} deregistered: {:?}",
                u32::from(para_id),
                e,
            );
54
        }
        // Remove bootnodes from pallet_data_preservers
54
        DataPreservers::para_deregistered(para_id);
54

            
54
        ServicesPayment::para_deregistered(para_id);
54

            
54
        XcmCoreBuyer::para_deregistered(para_id);
54

            
54
        Weight::default()
54
    }
70
    fn check_valid_for_collating(para_id: ParaId) -> DispatchResult {
70
        // To be able to call mark_valid_for_collating, a container chain must have bootnodes
70
        DataPreservers::check_valid_for_collating(para_id)
70
    }
    #[cfg(feature = "runtime-benchmarks")]
    fn benchmarks_ensure_valid_for_collating(para_id: ParaId) {
        use {
            frame_support::traits::EnsureOriginWithArg,
            pallet_data_preservers::{ParaIdsFilter, Profile, ProfileMode},
        };
        let profile = Profile {
            url: b"/ip4/127.0.0.1/tcp/33049/ws/p2p/12D3KooWHVMhQDHBpj9vQmssgyfspYecgV6e3hH1dQVDUkUbCYC9"
                    .to_vec()
                    .try_into()
                    .expect("to fit in BoundedVec"),
            para_ids: ParaIdsFilter::AnyParaId,
            mode: ProfileMode::Bootnode,
            assignment_request: PreserversAssignementPaymentRequest::Free,
        };
        let profile_id = pallet_data_preservers::NextProfileId::<Runtime>::get();
        let profile_owner = AccountId::new([1u8; 32]);
        DataPreservers::force_create_profile(RuntimeOrigin::root(), profile, profile_owner)
            .expect("profile create to succeed");
        let para_manager =
            <Runtime as pallet_data_preservers::Config>::AssignmentOrigin::try_successful_origin(
                &para_id,
            )
            .expect("should be able to get para manager");
        DataPreservers::start_assignment(
            para_manager,
            profile_id,
            para_id,
            PreserversAssignementPaymentExtra::Free,
        )
        .expect("assignement to work");
        assert!(
            pallet_data_preservers::Assignments::<Runtime>::get(para_id).contains(&profile_id),
            "profile should be correctly assigned"
        );
    }
}
pub struct PalletRelayStorageRootProvider;
impl RelayStorageRootProvider for PalletRelayStorageRootProvider {
12
    fn get_relay_storage_root(relay_block_number: u32) -> Option<H256> {
12
        pallet_relay_storage_roots::pallet::RelayStorageRoot::<Runtime>::get(relay_block_number)
12
    }
    #[cfg(feature = "runtime-benchmarks")]
    fn set_relay_storage_root(relay_block_number: u32, storage_root: Option<H256>) {
        pallet_relay_storage_roots::pallet::RelayStorageRootKeys::<Runtime>::mutate(|x| {
            if storage_root.is_some() {
                if x.is_full() {
                    let key = x.remove(0);
                    pallet_relay_storage_roots::pallet::RelayStorageRoot::<Runtime>::remove(key);
                }
                let pos = x.iter().position(|x| *x >= relay_block_number);
                if let Some(pos) = pos {
                    if x[pos] != relay_block_number {
                        x.try_insert(pos, relay_block_number).unwrap();
                    }
                } else {
                    // Push at end
                    x.try_push(relay_block_number).unwrap();
                }
            } else {
                let pos = x.iter().position(|x| *x == relay_block_number);
                if let Some(pos) = pos {
                    x.remove(pos);
                }
            }
        });
        pallet_relay_storage_roots::pallet::RelayStorageRoot::<Runtime>::set(
            relay_block_number,
            storage_root,
        );
    }
}
parameter_types! {
    pub const DepositAmount: Balance = 100 * UNIT;
}
impl pallet_registrar::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type RegistrarOrigin = EnsureRoot<AccountId>;
    type MarkValidForCollatingOrigin = EnsureRoot<AccountId>;
    type MaxLengthParaIds = MaxLengthParaIds;
    type MaxGenesisDataSize = MaxEncodedGenesisDataSize;
    type RegisterWithRelayProofOrigin = EnsureSigned<AccountId>;
    type RelayStorageRootProvider = PalletRelayStorageRootProvider;
    type SessionDelay = ConstU32<2>;
    type SessionIndex = u32;
    type CurrentSessionIndex = CurrentSessionIndexGetter;
    type Currency = Balances;
    type DepositAmount = DepositAmount;
    type RegistrarHooks = DanceboxRegistrarHooks;
    type RuntimeHoldReason = RuntimeHoldReason;
    type InnerRegistrar = ();
    type WeightInfo = weights::pallet_registrar::SubstrateWeight<Runtime>;
}
impl pallet_authority_mapping::Config for Runtime {
    type SessionIndex = u32;
    type SessionRemovalBoundary = ConstU32<2>;
    type AuthorityId = NimbusId;
}
impl pallet_sudo::Config for Runtime {
    type RuntimeCall = RuntimeCall;
    type RuntimeEvent = RuntimeEvent;
    type WeightInfo = weights::pallet_sudo::SubstrateWeight<Runtime>;
}
impl pallet_utility::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type RuntimeCall = RuntimeCall;
    type PalletsOrigin = OriginCaller;
    type WeightInfo = weights::pallet_utility::SubstrateWeight<Runtime>;
}
/// The type used to represent the kinds of proxying allowed.
#[apply(derive_storage_traits)]
#[derive(Copy, Ord, PartialOrd, MaxEncodedLen)]
#[allow(clippy::unnecessary_cast)]
pub enum ProxyType {
145
    /// All calls can be proxied. This is the trivial/most permissive filter.
    Any = 0,
44
    /// Only extrinsics that do not transfer funds.
    NonTransfer = 1,
37
    /// Only extrinsics related to governance (democracy and collectives).
    Governance = 2,
31
    /// Only extrinsics related to staking.
    Staking = 3,
79
    /// Allow to veto an announced proxy call.
    CancelProxy = 4,
25
    /// Allow extrinsic related to Balances.
    Balances = 5,
25
    /// Allow extrinsics related to Registrar
    Registrar = 6,
19
    /// Allow extrinsics related to Registrar that needs to be called through Sudo
    SudoRegistrar = 7,
25
    /// Allow extrinsics from the Session pallet for key management.
    SessionKeyManagement = 8,
}
impl Default for ProxyType {
    fn default() -> Self {
        Self::Any
    }
}
impl InstanceFilter<RuntimeCall> for ProxyType {
94
    fn filter(&self, c: &RuntimeCall) -> bool {
94
        // Since proxy filters are respected in all dispatches of the Utility
94
        // pallet, it should never need to be filtered by any proxy.
94
        if let RuntimeCall::Utility(..) = c {
            return true;
94
        }
94

            
94
        match self {
25
            ProxyType::Any => true,
            ProxyType::NonTransfer => {
8
                matches!(
14
                    c,
                    RuntimeCall::System(..)
                        | RuntimeCall::ParachainSystem(..)
                        | RuntimeCall::Timestamp(..)
                        | RuntimeCall::Proxy(..)
                        | RuntimeCall::Registrar(..)
                )
            }
            // We don't have governance yet
1
            ProxyType::Governance => false,
            ProxyType::Staking => {
1
                matches!(c, RuntimeCall::Session(..) | RuntimeCall::PooledStaking(..))
            }
7
            ProxyType::CancelProxy => matches!(
6
                c,
                RuntimeCall::Proxy(pallet_proxy::Call::reject_announcement { .. })
            ),
            ProxyType::Balances => {
13
                matches!(c, RuntimeCall::Balances(..))
            }
            ProxyType::Registrar => {
1
                matches!(
13
                    c,
                    RuntimeCall::Registrar(..) | RuntimeCall::DataPreservers(..)
                )
            }
7
            ProxyType::SudoRegistrar => match c {
7
                RuntimeCall::Sudo(pallet_sudo::Call::sudo { call: ref x }) => {
1
                    matches!(
7
                        x.as_ref(),
                        &RuntimeCall::Registrar(..) | &RuntimeCall::DataPreservers(..)
                    )
                }
                _ => false,
            },
            ProxyType::SessionKeyManagement => {
7
                matches!(c, RuntimeCall::Session(..))
            }
        }
94
    }
    fn is_superset(&self, o: &Self) -> bool {
        match (self, o) {
            (x, y) if x == y => true,
            (ProxyType::Any, _) => true,
            (_, ProxyType::Any) => false,
            _ => false,
        }
    }
}
impl pallet_proxy::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type RuntimeCall = RuntimeCall;
    type Currency = Balances;
    type ProxyType = ProxyType;
    // One storage item; key size 32, value size 8
    type ProxyDepositBase = ConstU128<{ currency::deposit(1, 8) }>;
    // Additional storage item size of 33 bytes (32 bytes AccountId + 1 byte sizeof(ProxyType)).
    type ProxyDepositFactor = ConstU128<{ currency::deposit(0, 33) }>;
    type MaxProxies = ConstU32<32>;
    type MaxPending = ConstU32<32>;
    type CallHasher = BlakeTwo256;
    type AnnouncementDepositBase = ConstU128<{ currency::deposit(1, 8) }>;
    // Additional storage item size of 68 bytes:
    // - 32 bytes AccountId
    // - 32 bytes Hasher (Blake2256)
    // - 4 bytes BlockNumber (u32)
    type AnnouncementDepositFactor = ConstU128<{ currency::deposit(0, 68) }>;
    type WeightInfo = weights::pallet_proxy::SubstrateWeight<Runtime>;
}
pub struct XcmExecutionManager;
impl xcm_primitives::PauseXcmExecution for XcmExecutionManager {
30
    fn suspend_xcm_execution() -> DispatchResult {
30
        XcmpQueue::suspend_xcm_execution(RuntimeOrigin::root())
30
    }
30
    fn resume_xcm_execution() -> DispatchResult {
30
        XcmpQueue::resume_xcm_execution(RuntimeOrigin::root())
30
    }
}
impl pallet_migrations::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type MigrationsList = (tanssi_runtime_common::migrations::DanceboxMigrations<Runtime>,);
    type XcmExecutionManager = XcmExecutionManager;
}
/// Maintenance mode Call filter
pub struct MaintenanceFilter;
impl Contains<RuntimeCall> for MaintenanceFilter {
648
    fn contains(c: &RuntimeCall) -> bool {
630
        !matches!(
648
            c,
            RuntimeCall::Balances(..)
                | RuntimeCall::Registrar(..)
                | RuntimeCall::Session(..)
                | RuntimeCall::System(..)
                | RuntimeCall::PooledStaking(..)
                | RuntimeCall::Utility(..)
                | RuntimeCall::PolkadotXcm(..)
        )
648
    }
}
/// Normal Call Filter
pub struct NormalFilter;
impl Contains<RuntimeCall> for NormalFilter {
85744
    fn contains(_c: &RuntimeCall) -> bool {
85744
        true
85744
    }
}
impl pallet_maintenance_mode::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type NormalCallFilter = NormalFilter;
    type MaintenanceCallFilter = MaintenanceFilter;
    type MaintenanceOrigin = EnsureRoot<AccountId>;
    type XcmExecutionManager = XcmExecutionManager;
}
parameter_types! {
    pub const MaxStorageRoots: u32 = 10; // 1 minute of relay blocks
}
impl pallet_relay_storage_roots::Config for Runtime {
    type RelaychainStateProvider = cumulus_pallet_parachain_system::RelaychainDataProvider<Self>;
    type MaxStorageRoots = MaxStorageRoots;
    type WeightInfo = weights::pallet_relay_storage_roots::SubstrateWeight<Runtime>;
}
impl pallet_root_testing::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
}
parameter_types! {
    pub StakingAccount: AccountId32 = PalletId(*b"POOLSTAK").into_account_truncating();
    pub const InitialManualClaimShareValue: u128 = currency::MILLIDANCE;
    pub const InitialAutoCompoundingShareValue: u128 = currency::MILLIDANCE;
    pub const MinimumSelfDelegation: u128 = 10 * currency::KILODANCE;
    pub const RewardsCollatorCommission: Perbill = Perbill::from_percent(20);
    // Need to wait 2 sessions before being able to join or leave staking pools
    pub const StakingSessionDelay: u32 = 2;
}
pub struct SessionTimer<G>(PhantomData<G>);
impl<G> Timer for SessionTimer<G>
where
    G: Get<u32>,
{
    type Instant = u32;
213
    fn now() -> Self::Instant {
213
        Session::current_index()
213
    }
73
    fn is_elapsed(instant: &Self::Instant) -> bool {
73
        let delay = G::get();
73
        let Some(end) = instant.checked_add(delay) else {
            return false;
        };
73
        end <= Self::now()
73
    }
    #[cfg(feature = "runtime-benchmarks")]
    fn elapsed_instant() -> Self::Instant {
        let delay = G::get();
        Self::now()
            .checked_add(delay)
            .expect("overflow when computing valid elapsed instant")
    }
    #[cfg(feature = "runtime-benchmarks")]
    fn skip_to_elapsed() {
        let session_to_reach = Self::elapsed_instant();
        while Self::now() < session_to_reach {
            Session::rotate_session();
        }
    }
}
pub struct CandidateHasRegisteredKeys;
impl IsCandidateEligible<AccountId> for CandidateHasRegisteredKeys {
127
    fn is_candidate_eligible(a: &AccountId) -> bool {
127
        <Session as ValidatorRegistration<AccountId>>::is_registered(a)
127
    }
    #[cfg(feature = "runtime-benchmarks")]
    fn make_candidate_eligible(a: &AccountId, eligible: bool) {
        use sp_core::crypto::UncheckedFrom;
        if eligible {
            let account_slice: &[u8; 32] = a.as_ref();
            let _ = Session::set_keys(
                RuntimeOrigin::signed(a.clone()),
                SessionKeys {
                    nimbus: NimbusId::unchecked_from(*account_slice),
                },
                vec![],
            );
        } else {
            let _ = Session::purge_keys(RuntimeOrigin::signed(a.clone()));
        }
    }
}
impl pallet_pooled_staking::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type Currency = Balances;
    type Balance = Balance;
    type StakingAccount = StakingAccount;
    type InitialManualClaimShareValue = InitialManualClaimShareValue;
    type InitialAutoCompoundingShareValue = InitialAutoCompoundingShareValue;
    type MinimumSelfDelegation = MinimumSelfDelegation;
    type RuntimeHoldReason = RuntimeHoldReason;
    type RewardsCollatorCommission = RewardsCollatorCommission;
    type JoiningRequestTimer = SessionTimer<StakingSessionDelay>;
    type LeavingRequestTimer = SessionTimer<StakingSessionDelay>;
    type EligibleCandidatesBufferSize = ConstU32<100>;
    type EligibleCandidatesFilter = CandidateHasRegisteredKeys;
    type WeightInfo = weights::pallet_pooled_staking::SubstrateWeight<Runtime>;
}
parameter_types! {
    pub ParachainBondAccount: AccountId32 = PalletId(*b"ParaBond").into_account_truncating();
    pub PendingRewardsAccount: AccountId32 = PalletId(*b"PENDREWD").into_account_truncating();
    // The equation to solve is:
    // initial_supply * (1.05) = initial_supply * (1+x)^5_259_600
    // we should solve for x = (1.05)^(1/5_259_600) -1 -> 0.000000009 per block or 9/1_000_000_000
    // 1% in the case of dev mode
    // TODO: check if we can put the prod inflation for tests too
    // TODO: better calculus for going from annual to block inflation (if it can be done)
    pub const InflationRate: Perbill = prod_or_fast!(Perbill::from_parts(9), Perbill::from_percent(1));
    // 30% for parachain bond, so 70% for staking
    pub const RewardsPortion: Perbill = Perbill::from_percent(70);
}
pub struct GetSelfChainBlockAuthor;
impl MaybeSelfChainBlockAuthor<AccountId32> for GetSelfChainBlockAuthor {
46424
    fn get_block_author() -> Option<AccountId32> {
46424
        // TODO: we should do a refactor here, and use either authority-mapping or collator-assignemnt
46424
        // we should also make sure we actually account for the weight of these
46424
        // although most of these should be cached as they are read every block
46424
        let slot = u64::from(<Runtime as pallet_author_inherent::Config>::SlotBeacon::slot());
46424
        let self_para_id = ParachainInfo::get();
46424
        CollatorAssignment::author_for_slot(slot.into(), self_para_id)
46424
    }
}
pub struct OnUnbalancedInflation;
impl frame_support::traits::OnUnbalanced<Credit<AccountId, Balances>> for OnUnbalancedInflation {
23212
    fn on_nonzero_unbalanced(credit: Credit<AccountId, Balances>) {
23212
        let _ = <Balances as Balanced<_>>::resolve(&ParachainBondAccount::get(), credit);
23212
    }
}
impl pallet_inflation_rewards::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type Currency = Balances;
    type ContainerChains = Registrar;
    type GetSelfChainBlockAuthor = GetSelfChainBlockAuthor;
    type InflationRate = InflationRate;
    type OnUnbalanced = OnUnbalancedInflation;
    type PendingRewardsAccount = PendingRewardsAccount;
    type StakingRewardsDistributor = InvulnerableRewardDistribution<Self, Balances, PooledStaking>;
    type RewardsPortion = RewardsPortion;
}
impl pallet_tx_pause::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type RuntimeCall = RuntimeCall;
    type PauseOrigin = EnsureRoot<AccountId>;
    type UnpauseOrigin = EnsureRoot<AccountId>;
    type WhitelistedCalls = ();
    type MaxNameLen = ConstU32<256>;
    type WeightInfo = weights::pallet_tx_pause::SubstrateWeight<Runtime>;
}
#[apply(derive_storage_traits)]
#[derive(Copy, Serialize, Deserialize, MaxEncodedLen)]
pub enum StreamPaymentAssetId {
173
    Native,
}
pub struct StreamPaymentAssets;
impl pallet_stream_payment::Assets<AccountId, StreamPaymentAssetId, Balance>
    for StreamPaymentAssets
{
38
    fn transfer_deposit(
38
        asset_id: &StreamPaymentAssetId,
38
        from: &AccountId,
38
        to: &AccountId,
38
        amount: Balance,
38
    ) -> frame_support::pallet_prelude::DispatchResult {
38
        match asset_id {
38
            StreamPaymentAssetId::Native => {
38
                // We remove the hold before transfering.
38
                Self::decrease_deposit(asset_id, from, amount)?;
38
                Balances::transfer(from, to, amount, Preservation::Preserve).map(|_| ())
            }
        }
38
    }
25
    fn increase_deposit(
25
        asset_id: &StreamPaymentAssetId,
25
        account: &AccountId,
25
        amount: Balance,
25
    ) -> frame_support::pallet_prelude::DispatchResult {
25
        match asset_id {
25
            StreamPaymentAssetId::Native => Balances::hold(
25
                &pallet_stream_payment::HoldReason::StreamPayment.into(),
25
                account,
25
                amount,
25
            ),
25
        }
25
    }
51
    fn decrease_deposit(
51
        asset_id: &StreamPaymentAssetId,
51
        account: &AccountId,
51
        amount: Balance,
51
    ) -> frame_support::pallet_prelude::DispatchResult {
51
        match asset_id {
51
            StreamPaymentAssetId::Native => Balances::release(
51
                &pallet_stream_payment::HoldReason::StreamPayment.into(),
51
                account,
51
                amount,
51
                Precision::Exact,
51
            )
51
            .map(|_| ()),
51
        }
51
    }
    fn get_deposit(asset_id: &StreamPaymentAssetId, account: &AccountId) -> Balance {
        match asset_id {
            StreamPaymentAssetId::Native => Balances::balance_on_hold(
                &pallet_stream_payment::HoldReason::StreamPayment.into(),
                account,
            ),
        }
    }
    /// Benchmarks: should return the asset id which has the worst performance when interacting
    /// with it.
    #[cfg(feature = "runtime-benchmarks")]
    fn bench_worst_case_asset_id() -> StreamPaymentAssetId {
        StreamPaymentAssetId::Native
    }
    /// Benchmarks: should return the another asset id which has the worst performance when interacting
    /// with it afther `bench_worst_case_asset_id`. This is to benchmark the worst case when changing config
    /// from one asset to another.
    #[cfg(feature = "runtime-benchmarks")]
    fn bench_worst_case_asset_id2() -> StreamPaymentAssetId {
        StreamPaymentAssetId::Native
    }
    /// Benchmarks: should set the balance for the asset id returned by `bench_worst_case_asset_id`.
    #[cfg(feature = "runtime-benchmarks")]
    fn bench_set_balance(asset_id: &StreamPaymentAssetId, account: &AccountId, amount: Balance) {
        // only one asset id
        let StreamPaymentAssetId::Native = asset_id;
        Balances::set_balance(account, amount);
    }
}
#[apply(derive_storage_traits)]
#[derive(Copy, Serialize, Deserialize, MaxEncodedLen)]
pub enum TimeUnit {
173
    BlockNumber,
    Timestamp,
    // TODO: Container chains/relay block number.
}
pub struct TimeProvider;
impl pallet_stream_payment::TimeProvider<TimeUnit, Balance> for TimeProvider {
106
    fn now(unit: &TimeUnit) -> Option<Balance> {
106
        match *unit {
106
            TimeUnit::BlockNumber => Some(System::block_number().into()),
            TimeUnit::Timestamp => Some(Timestamp::get().into()),
        }
106
    }
    /// Benchmarks: should return the time unit which has the worst performance calling
    /// `TimeProvider::now(unit)` with.
    #[cfg(feature = "runtime-benchmarks")]
    fn bench_worst_case_time_unit() -> TimeUnit {
        // Both BlockNumber and Timestamp cost the same (1 db read), but overriding timestamp
        // doesn't work well in benches, while block number works fine.
        TimeUnit::BlockNumber
    }
    /// Benchmarks: sets the "now" time for time unit returned by `worst_case_time_unit`.
    #[cfg(feature = "runtime-benchmarks")]
    fn bench_set_now(instant: Balance) {
        System::set_block_number(instant as u32)
    }
}
type StreamId = u64;
parameter_types! {
    // 1 entry, storing 173 bytes on-chain
    pub const OpenStreamHoldAmount: Balance = currency::deposit(1, 173);
}
impl pallet_stream_payment::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type StreamId = StreamId;
    type TimeUnit = TimeUnit;
    type Balance = Balance;
    type AssetId = StreamPaymentAssetId;
    type Assets = StreamPaymentAssets;
    type Currency = Balances;
    type OpenStreamHoldAmount = OpenStreamHoldAmount;
    type RuntimeHoldReason = RuntimeHoldReason;
    type TimeProvider = TimeProvider;
    type WeightInfo = weights::pallet_stream_payment::SubstrateWeight<Runtime>;
}
parameter_types! {
    // 1 entry, storing 258 bytes on-chain
    pub const BasicDeposit: Balance = currency::deposit(1, 258);
    // 1 entry, storing 53 bytes on-chain
    pub const SubAccountDeposit: Balance = currency::deposit(1, 53);
    // Additional bytes adds 0 entries, storing 1 byte on-chain
    pub const ByteDeposit: Balance = currency::deposit(0, 1);
    pub const MaxSubAccounts: u32 = 100;
    pub const MaxAdditionalFields: u32 = 100;
    pub const MaxRegistrars: u32 = 20;
}
impl pallet_identity::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type Currency = Balances;
    type BasicDeposit = BasicDeposit;
    type ByteDeposit = ByteDeposit;
    type SubAccountDeposit = SubAccountDeposit;
    type MaxSubAccounts = MaxSubAccounts;
    type MaxRegistrars = MaxRegistrars;
    type IdentityInformation = pallet_identity::legacy::IdentityInfo<MaxAdditionalFields>;
    // Slashed balances are burnt
    type Slashed = ();
    type ForceOrigin = EnsureRoot<AccountId>;
    type RegistrarOrigin = EnsureRoot<AccountId>;
    type OffchainSignature = Signature;
    type SigningPublicKey = <Signature as Verify>::Signer;
    type UsernameAuthorityOrigin = EnsureRoot<Self::AccountId>;
    type PendingUsernameExpiration = ConstU32<{ 7 * DAYS }>;
    type MaxSuffixLength = ConstU32<7>;
    type MaxUsernameLength = ConstU32<32>;
    type WeightInfo = weights::pallet_identity::SubstrateWeight<Runtime>;
}
parameter_types! {
    pub const TreasuryId: PalletId = PalletId(*b"tns/tsry");
    pub const ProposalBond: Permill = Permill::from_percent(5);
    pub TreasuryAccount: AccountId = Treasury::account_id();
    pub const MaxBalance: Balance = Balance::max_value();
    // We allow it to be 1 minute in fast mode to be able to test it
    pub const SpendPeriod: BlockNumber = prod_or_fast!(6 * DAYS, 1 * MINUTES);
}
impl pallet_treasury::Config for Runtime {
    type PalletId = TreasuryId;
    type Currency = Balances;
    type RejectOrigin = EnsureRoot<AccountId>;
    type RuntimeEvent = RuntimeEvent;
    // If proposal gets rejected, bond goes to treasury
    type SpendPeriod = SpendPeriod;
    type Burn = ();
    type BurnDestination = ();
    type MaxApprovals = ConstU32<100>;
    type WeightInfo = weights::pallet_treasury::SubstrateWeight<Runtime>;
    type SpendFunds = ();
    type SpendOrigin =
        frame_system::EnsureWithSuccess<EnsureRoot<AccountId>, AccountId, MaxBalance>;
    type AssetKind = ();
    type Beneficiary = AccountId;
    type BeneficiaryLookup = IdentityLookup<AccountId>;
    type Paymaster = PayFromAccount<Balances, TreasuryAccount>;
    // TODO: implement pallet-asset-rate to allow the treasury to spend other assets
    type BalanceConverter = UnityAssetBalanceConversion;
    type PayoutPeriod = ConstU32<{ 30 * DAYS }>;
    #[cfg(feature = "runtime-benchmarks")]
    type BenchmarkHelper = tanssi_runtime_common::benchmarking::TreasuryBenchmarkHelper<Runtime>;
}
parameter_types! {
    // One storage item; key size 32; value is size 4+4+16+32. Total = 1 * (32 + 56)
    pub const DepositBase: Balance = currency::deposit(1, 88);
    // Additional storage item size of 32 bytes.
    pub const DepositFactor: Balance = currency::deposit(0, 32);
    pub const MaxSignatories: u32 = 100;
}
impl pallet_multisig::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type RuntimeCall = RuntimeCall;
    type Currency = Balances;
    type DepositBase = DepositBase;
    type DepositFactor = DepositFactor;
    type MaxSignatories = MaxSignatories;
    type WeightInfo = weights::pallet_multisig::SubstrateWeight<Runtime>;
}
// Create the runtime by composing the FRAME pallets that were previously configured.
9347069
construct_runtime!(
879060
    pub enum Runtime
879060
    {
879060
        // System support stuff.
879060
        System: frame_system = 0,
879060
        ParachainSystem: cumulus_pallet_parachain_system = 1,
879060
        Timestamp: pallet_timestamp = 2,
879060
        ParachainInfo: parachain_info = 3,
879060
        Sudo: pallet_sudo = 4,
879060
        Utility: pallet_utility = 5,
879060
        Proxy: pallet_proxy = 6,
879060
        Migrations: pallet_migrations = 7,
879060
        MaintenanceMode: pallet_maintenance_mode = 8,
879060
        TxPause: pallet_tx_pause = 9,
879060

            
879060
        // Monetary stuff.
879060
        Balances: pallet_balances = 10,
879060
        TransactionPayment: pallet_transaction_payment = 11,
879060
        StreamPayment: pallet_stream_payment = 12,
879060

            
879060
        // Other utilities
879060
        Identity: pallet_identity = 15,
879060
        Multisig: pallet_multisig = 16,
879060

            
879060
        // ContainerChain management. It should go before Session for Genesis
879060
        Registrar: pallet_registrar = 20,
879060
        Configuration: pallet_configuration = 21,
879060
        CollatorAssignment: pallet_collator_assignment = 22,
879060
        Initializer: pallet_initializer = 23,
879060
        AuthorNoting: pallet_author_noting = 24,
879060
        AuthorityAssignment: pallet_authority_assignment = 25,
879060
        ServicesPayment: pallet_services_payment = 26,
879060
        DataPreservers: pallet_data_preservers = 27,
879060

            
879060
        // Collator support. The order of these 6 are important and shall not change.
879060
        Invulnerables: pallet_invulnerables = 30,
879060
        Session: pallet_session = 31,
879060
        AuthorityMapping: pallet_authority_mapping = 32,
879060
        AuthorInherent: pallet_author_inherent = 33,
879060
        PooledStaking: pallet_pooled_staking = 34,
879060
        // InflationRewards must be after Session and AuthorInherent
879060
        InflationRewards: pallet_inflation_rewards = 35,
879060

            
879060
        // Treasury stuff.
879060
        Treasury: pallet_treasury::{Pallet, Storage, Config<T>, Event<T>, Call} = 40,
879060

            
879060
        //XCM
879060
        XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 50,
879060
        CumulusXcm: cumulus_pallet_xcm::{Pallet, Event<T>, Origin} = 51,
879060
        PolkadotXcm: pallet_xcm::{Pallet, Call, Storage, Event<T>, Origin, Config<T>} = 53,
879060
        ForeignAssets: pallet_assets::<Instance1>::{Pallet, Call, Storage, Event<T>} = 54,
879060
        ForeignAssetsCreator: pallet_foreign_asset_creator::{Pallet, Call, Storage, Event<T>} = 55,
879060
        AssetRate: pallet_asset_rate::{Pallet, Call, Storage, Event<T>} = 56,
879060
        MessageQueue: pallet_message_queue::{Pallet, Call, Storage, Event<T>} = 57,
879060
        XcmCoreBuyer: pallet_xcm_core_buyer = 58,
879060

            
879060
        // More system support stuff
879060
        RelayStorageRoots: pallet_relay_storage_roots = 60,
879060

            
879060
        RootTesting: pallet_root_testing = 100,
879060
        AsyncBacking: pallet_async_backing::{Pallet, Storage} = 110,
879060
    }
9693231
);
#[cfg(feature = "runtime-benchmarks")]
mod benches {
    frame_benchmarking::define_benchmarks!(
        [frame_system, frame_system_benchmarking::Pallet::<Runtime>]
        [cumulus_pallet_parachain_system, ParachainSystem]
        [pallet_timestamp, Timestamp]
        [pallet_sudo, Sudo]
        [pallet_utility, Utility]
        [pallet_proxy, Proxy]
        [pallet_tx_pause, TxPause]
        [pallet_balances, Balances]
        [pallet_stream_payment, StreamPayment]
        [pallet_identity, Identity]
        [pallet_multisig, Multisig]
        [pallet_registrar, Registrar]
        [pallet_configuration, Configuration]
        [pallet_collator_assignment, CollatorAssignment]
        [pallet_author_noting, AuthorNoting]
        [pallet_services_payment, ServicesPayment]
        [pallet_data_preservers, DataPreservers]
        [pallet_invulnerables, Invulnerables]
        [pallet_session, SessionBench::<Runtime>]
        [pallet_author_inherent, AuthorInherent]
        [pallet_pooled_staking, PooledStaking]
        [pallet_treasury, Treasury]
        [cumulus_pallet_xcmp_queue, XcmpQueue]
        [pallet_xcm, PalletXcmExtrinsicsBenchmark::<Runtime>]
        [pallet_xcm_benchmarks::generic, pallet_xcm_benchmarks::generic::Pallet::<Runtime>]
        [pallet_assets, ForeignAssets]
        [pallet_foreign_asset_creator, ForeignAssetsCreator]
        [pallet_asset_rate, AssetRate]
        [pallet_message_queue, MessageQueue]
        [pallet_xcm_core_buyer, XcmCoreBuyer]
        [pallet_relay_storage_roots, RelayStorageRoots]
    );
}
23258
pub fn get_para_id_authorities(para_id: ParaId) -> Option<Vec<NimbusId>> {
23258
    let parent_number = System::block_number();
23258

            
23258
    let should_end_session =
23258
        <Runtime as pallet_session::Config>::ShouldEndSession::should_end_session(
23258
            parent_number + 1,
23258
        );
23258
    let session_index = if should_end_session {
2208
        Session::current_index() + 1
    } else {
21050
        Session::current_index()
    };
23258
    let assigned_authorities = AuthorityAssignment::collator_container_chain(session_index)?;
23258
    let self_para_id = ParachainInfo::get();
23258

            
23258
    if para_id == self_para_id {
23220
        Some(assigned_authorities.orchestrator_chain)
    } else {
38
        assigned_authorities.container_chains.get(&para_id).cloned()
    }
23258
}
327488
impl_runtime_apis! {
46002
    impl sp_consensus_aura::AuraApi<Block, NimbusId> for Runtime {
59938
        fn slot_duration() -> sp_consensus_aura::SlotDuration {
21486
            sp_consensus_aura::SlotDuration::from_millis(SLOT_DURATION)
21486
        }
46002

            
46002
        fn authorities() -> Vec<NimbusId> {
            // Check whether we need to fetch the next authorities or current ones
            let parent_number = System::block_number();
            let should_end_session = <Runtime as pallet_session::Config>::ShouldEndSession::should_end_session(parent_number + 1);
46002

            
46002
            let session_index = if should_end_session {
46002
                Session::current_index() +1
46002
            }
46002
            else {
46002
                Session::current_index()
46002
            };
46002

            
46002
            pallet_authority_assignment::CollatorContainerChain::<Runtime>::get(session_index)
                .expect("authorities for current session should exist")
                .orchestrator_chain
        }
46002
    }
46002

            
46002
    impl sp_api::Core<Block> for Runtime {
46002
        fn version() -> RuntimeVersion {
            VERSION
        }
46002

            
46002
        fn execute_block(block: Block) {
            Executive::execute_block(block)
        }
46002

            
59598
        fn initialize_block(header: &<Block as BlockT>::Header) -> sp_runtime::ExtrinsicInclusionMode {
20976
            Executive::initialize_block(header)
20976
        }
46002
    }
46002

            
46002
    impl sp_api::Metadata<Block> for Runtime {
46002
        fn metadata() -> OpaqueMetadata {
84
            OpaqueMetadata::new(Runtime::metadata().into())
84
        }
46002

            
46002
        fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
498
            Runtime::metadata_at_version(version)
498
        }
46002

            
46002
        fn metadata_versions() -> Vec<u32> {
498
            Runtime::metadata_versions()
498
        }
46002
    }
46002

            
46002
    impl sp_block_builder::BlockBuilder<Block> for Runtime {
103082
        fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
86202
            Executive::apply_extrinsic(extrinsic)
86202
        }
46002

            
59598
        fn finalize_block() -> <Block as BlockT>::Header {
20976
            Executive::finalize_block()
20976
        }
46002

            
59598
        fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
20976
            data.create_extrinsics()
20976
        }
46002

            
46002
        fn check_inherents(
            block: Block,
            data: sp_inherents::InherentData,
        ) -> sp_inherents::CheckInherentsResult {
            data.check_extrinsics(&block)
        }
46002
    }
46002

            
46002
    impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
52550
        fn validate_transaction(
10404
            source: TransactionSource,
10404
            tx: <Block as BlockT>::Extrinsic,
10404
            block_hash: <Block as BlockT>::Hash,
10404
        ) -> TransactionValidity {
10404
            Executive::validate_transaction(source, tx, block_hash)
10404
        }
46002
    }
46002

            
46002
    impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
59598
        fn offchain_worker(header: &<Block as BlockT>::Header) {
20976
            Executive::offchain_worker(header)
20976
        }
46002
    }
46002

            
46002
    impl sp_session::SessionKeys<Block> for Runtime {
46002
        fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {
540
            SessionKeys::generate(seed)
540
        }
46002

            
46002
        fn decode_session_keys(
            encoded: Vec<u8>,
        ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {
            SessionKeys::decode_into_raw_public_keys(&encoded)
        }
46002
    }
46002

            
46002
    impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {
46002
        fn account_nonce(account: AccountId) -> Index {
96
            System::account_nonce(account)
96
        }
46002
    }
46002

            
46002
    impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {
46002
        fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {
            ParachainSystem::collect_collation_info(header)
        }
46002
    }
46002

            
46002
    impl async_backing_primitives::UnincludedSegmentApi<Block> for Runtime {
46002
        fn can_build_upon(
            included_hash: <Block as BlockT>::Hash,
            slot: async_backing_primitives::Slot,
        ) -> bool {
            ConsensusHook::can_build_upon(included_hash, slot)
        }
46002
    }
46002

            
46002
    impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
46002
        fn build_state(config: Vec<u8>) -> sp_genesis_builder::Result {
            build_state::<RuntimeGenesisConfig>(config)
        }
46002

            
46002
        fn get_preset(id: &Option<sp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
            get_preset::<RuntimeGenesisConfig>(id, |_| None)
        }
46002

            
46002
        fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
            vec![]
        }
46002
    }
46002

            
46002
    #[cfg(feature = "runtime-benchmarks")]
46002
    impl frame_benchmarking::Benchmark<Block> for Runtime {
46002
        fn benchmark_metadata(
46002
            extra: bool,
46002
        ) -> (
46002
            Vec<frame_benchmarking::BenchmarkList>,
46002
            Vec<frame_support::traits::StorageInfo>,
46002
        ) {
46002
            use cumulus_pallet_session_benchmarking::Pallet as SessionBench;
46002
            use frame_benchmarking::{Benchmarking, BenchmarkList};
46002
            use frame_support::traits::StorageInfoTrait;
46002
            use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
46002

            
46002
            let mut list = Vec::<BenchmarkList>::new();
46002
            list_benchmarks!(list, extra);
46002

            
46002
            let storage_info = AllPalletsWithSystem::storage_info();
46002
            (list, storage_info)
46002
        }
46002

            
46002
        fn dispatch_benchmark(
46002
            config: frame_benchmarking::BenchmarkConfig,
46002
        ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {
46002
            use frame_benchmarking::{BenchmarkBatch, Benchmarking, BenchmarkError};
46002
            use sp_core::storage::TrackedStorageKey;
46002
            use cumulus_pallet_session_benchmarking::Pallet as SessionBench;
46002
            impl cumulus_pallet_session_benchmarking::Config for Runtime {}
46002

            
46002
            impl frame_system_benchmarking::Config for Runtime {
46002
                fn setup_set_code_requirements(code: &sp_std::vec::Vec<u8>) -> Result<(), BenchmarkError> {
46002
                    ParachainSystem::initialize_for_set_code_benchmark(code.len() as u32);
46002
                    Ok(())
46002
                }
46002

            
46002
                fn verify_set_code() {
46002
                    System::assert_last_event(cumulus_pallet_parachain_system::Event::<Runtime>::ValidationFunctionStored.into());
46002
                }
46002
            }
46002

            
46002
            use staging_xcm::latest::prelude::*;
46002
            use crate::xcm_config::SelfReserve;
46002
            parameter_types! {
46002
                pub ExistentialDepositAsset: Option<Asset> = Some((
46002
                    SelfReserve::get(),
46002
                    ExistentialDeposit::get()
46002
                ).into());
46002
            }
46002

            
46002
            impl pallet_xcm_benchmarks::Config for Runtime {
46002
                type XcmConfig = xcm_config::XcmConfig;
46002
                type AccountIdConverter = xcm_config::LocationToAccountId;
46002
                type DeliveryHelper = cumulus_primitives_utility::ToParentDeliveryHelper<
46002
                xcm_config::XcmConfig,
46002
                ExistentialDepositAsset,
46002
                xcm_config::PriceForParentDelivery,
46002
                >;
46002
                fn valid_destination() -> Result<Location, BenchmarkError> {
46002
                    Ok(Location::parent())
46002
                }
46002
                fn worst_case_holding(_depositable_count: u32) -> Assets {
46002
                    // We only care for native asset until we support others
46002
                    // TODO: refactor this case once other assets are supported
46002
                    vec![Asset{
46002
                        id: AssetId(SelfReserve::get()),
46002
                        fun: Fungible(u128::MAX),
46002
                    }].into()
46002
                }
46002
            }
46002

            
46002
            impl pallet_xcm_benchmarks::generic::Config for Runtime {
46002
                type TransactAsset = Balances;
46002
                type RuntimeCall = RuntimeCall;
46002

            
46002
                fn worst_case_response() -> (u64, Response) {
46002
                    (0u64, Response::Version(Default::default()))
46002
                }
46002

            
46002
                fn worst_case_asset_exchange() -> Result<(Assets, Assets), BenchmarkError> {
46002
                    Err(BenchmarkError::Skip)
46002
                }
46002

            
46002
                fn universal_alias() -> Result<(Location, Junction), BenchmarkError> {
46002
                    Err(BenchmarkError::Skip)
46002
                }
46002

            
46002
                fn transact_origin_and_runtime_call() -> Result<(Location, RuntimeCall), BenchmarkError> {
46002
                    Ok((Location::parent(), frame_system::Call::remark_with_event { remark: vec![] }.into()))
46002
                }
46002

            
46002
                fn subscribe_origin() -> Result<Location, BenchmarkError> {
46002
                    Ok(Location::parent())
46002
                }
46002

            
46002
                fn fee_asset() -> Result<Asset, BenchmarkError> {
46002
                    Ok(Asset {
46002
                        id: AssetId(SelfReserve::get()),
46002
                        fun: Fungible(ExistentialDeposit::get()*100),
46002
                    })
46002
                }
46002

            
46002
                fn claimable_asset() -> Result<(Location, Location, Assets), BenchmarkError> {
46002
                    let origin = Location::parent();
46002
                    let assets: Assets = (Location::parent(), 1_000u128).into();
46002
                    let ticket = Location { parents: 0, interior: Here };
46002
                    Ok((origin, ticket, assets))
46002
                }
46002

            
46002
                fn unlockable_asset() -> Result<(Location, Location, Asset), BenchmarkError> {
46002
                    Err(BenchmarkError::Skip)
46002
                }
46002

            
46002
                fn export_message_origin_and_destination(
46002
                ) -> Result<(Location, NetworkId, InteriorLocation), BenchmarkError> {
46002
                    Err(BenchmarkError::Skip)
46002
                }
46002

            
46002
                fn alias_origin() -> Result<(Location, Location), BenchmarkError> {
46002
                    Err(BenchmarkError::Skip)
46002
                }
46002
            }
46002

            
46002
            use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
46002
            impl pallet_xcm::benchmarking::Config for Runtime {
46002
                type DeliveryHelper = ();
46002
                fn get_asset() -> Asset {
46002
                    Asset {
46002
                        id: AssetId(SelfReserve::get()),
46002
                        fun: Fungible(ExistentialDeposit::get()),
46002
                    }
46002
                }
46002

            
46002
                fn reachable_dest() -> Option<Location> {
46002
                    Some(Parent.into())
46002
                }
46002

            
46002
                fn teleportable_asset_and_dest() -> Option<(Asset, Location)> {
46002
                    // Relay/native token can be teleported between AH and Relay.
46002
                    Some((
46002
                        Asset {
46002
                            fun: Fungible(EXISTENTIAL_DEPOSIT),
46002
                            id: Parent.into()
46002
                        },
46002
                        Parent.into(),
46002
                    ))
46002
                }
46002

            
46002
                fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> {
46002
                    use xcm_config::SelfReserve;
46002
                    // AH can reserve transfer native token to some random parachain.
46002
                    let random_para_id = 43211234;
46002
                    ParachainSystem::open_outbound_hrmp_channel_for_benchmarks_or_tests(
46002
                        random_para_id.into()
46002
                    );
46002
                    let who = frame_benchmarking::whitelisted_caller();
46002
                    // Give some multiple of the existential deposit
46002
                    let balance = EXISTENTIAL_DEPOSIT * 1000;
46002
                    let _ = <Balances as frame_support::traits::Currency<_>>::make_free_balance_be(
46002
                        &who, balance,
46002
                    );
46002
                    Some((
46002
                        Asset {
46002
                            fun: Fungible(EXISTENTIAL_DEPOSIT),
46002
                            id: AssetId(SelfReserve::get())
46002
                        },
46002
                        ParentThen(Parachain(random_para_id).into()).into(),
46002
                    ))
46002
                }
46002

            
46002
                fn set_up_complex_asset_transfer(
46002
                ) -> Option<(Assets, u32, Location, Box<dyn FnOnce()>)> {
46002
                    use xcm_config::SelfReserve;
46002
                    // Transfer to Relay some local AH asset (local-reserve-transfer) while paying
46002
                    // fees using teleported native token.
46002
                    // (We don't care that Relay doesn't accept incoming unknown AH local asset)
46002
                    let dest = Parent.into();
46002

            
46002
                    let fee_amount = EXISTENTIAL_DEPOSIT;
46002
                    let fee_asset: Asset = (SelfReserve::get(), fee_amount).into();
46002

            
46002
                    let who = frame_benchmarking::whitelisted_caller();
46002
                    // Give some multiple of the existential deposit
46002
                    let balance = fee_amount + EXISTENTIAL_DEPOSIT * 1000;
46002
                    let _ = <Balances as frame_support::traits::Currency<_>>::make_free_balance_be(
46002
                        &who, balance,
46002
                    );
46002

            
46002
                    // verify initial balance
46002
                    assert_eq!(Balances::free_balance(&who), balance);
46002

            
46002
                    // set up local asset
46002
                    let asset_amount = 10u128;
46002
                    let initial_asset_amount = asset_amount * 10;
46002

            
46002
                    // inject it into pallet-foreign-asset-creator.
46002
                    let (asset_id, asset_location) = pallet_foreign_asset_creator::benchmarks::create_default_minted_asset::<Runtime>(
46002
                        initial_asset_amount,
46002
                        who.clone()
46002
                    );
46002
                    let transfer_asset: Asset = (asset_location, asset_amount).into();
46002

            
46002
                    let assets: Assets = vec![fee_asset.clone(), transfer_asset].into();
46002
                    let fee_index = if assets.get(0).unwrap().eq(&fee_asset) { 0 } else { 1 };
46002

            
46002
                    // verify transferred successfully
46002
                    let verify = Box::new(move || {
46002
                        // verify native balance after transfer, decreased by transferred fee amount
46002
                        // (plus transport fees)
46002
                        assert!(Balances::free_balance(&who) <= balance - fee_amount);
46002
                        // verify asset balance decreased by exactly transferred amount
46002
                        assert_eq!(
46002
                            ForeignAssets::balance(asset_id, &who),
46002
                            initial_asset_amount - asset_amount,
46002
                        );
46002
                    });
46002
                    Some((assets, fee_index as u32, dest, verify))
46002
                }
46002
            }
46002

            
46002
            let whitelist: Vec<TrackedStorageKey> = vec![
46002
                // Block Number
46002
                hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac")
46002
                    .to_vec()
46002
                    .into(),
46002
                // Total Issuance
46002
                hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80")
46002
                    .to_vec()
46002
                    .into(),
46002
                // Execution Phase
46002
                hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a")
46002
                    .to_vec()
46002
                    .into(),
46002
                // Event Count
46002
                hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850")
46002
                    .to_vec()
46002
                    .into(),
46002
                // System Events
46002
                hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7")
46002
                    .to_vec()
46002
                    .into(),
46002
                // The transactional storage limit.
46002
                hex_literal::hex!("3a7472616e73616374696f6e5f6c6576656c3a")
46002
                    .to_vec()
46002
                    .into(),
46002

            
46002
                // ParachainInfo ParachainId
46002
                hex_literal::hex!(  "0d715f2646c8f85767b5d2764bb2782604a74d81251e398fd8a0a4d55023bb3f")
46002
                    .to_vec()
46002
                    .into(),
46002
            ];
46002

            
46002
            let mut batches = Vec::<BenchmarkBatch>::new();
46002
            let params = (&config, &whitelist);
46002

            
46002
            add_benchmarks!(params, batches);
46002

            
46002
            Ok(batches)
46002
        }
46002
    }
46002

            
46002
    #[cfg(feature = "try-runtime")]
46002
    impl frame_try_runtime::TryRuntime<Block> for Runtime {
46002
        fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) {
46002
            let weight = Executive::try_runtime_upgrade(checks).unwrap();
46002
            (weight, RuntimeBlockWeights::get().max_block)
46002
        }
46002

            
46002
        fn execute_block(
46002
            block: Block,
46002
            state_root_check: bool,
46002
            signature_check: bool,
46002
            select: frame_try_runtime::TryStateSelect,
46002
        ) -> Weight {
46002
            // NOTE: intentional unwrap: we don't want to propagate the error backwards, and want to
46002
            // have a backtrace here.
46002
            Executive::try_execute_block(block, state_root_check, signature_check, select).unwrap()
46002
        }
46002
    }
46002

            
46002
    impl pallet_collator_assignment_runtime_api::CollatorAssignmentApi<Block, AccountId, ParaId> for Runtime {
46002
        /// Return the parachain that the given `AccountId` is collating for.
46002
        /// Returns `None` if the `AccountId` is not collating.
46010
        fn current_collator_parachain_assignment(account: AccountId) -> Option<ParaId> {
8
            let assigned_collators = CollatorAssignment::collator_container_chain();
8
            let self_para_id = ParachainInfo::get();
8

            
8
            assigned_collators.para_id_of(&account, self_para_id)
8
        }
46002

            
46002
        /// Return the parachain that the given `AccountId` will be collating for
46002
        /// in the next session change.
46002
        /// Returns `None` if the `AccountId` will not be collating.
46008
        fn future_collator_parachain_assignment(account: AccountId) -> Option<ParaId> {
6
            let assigned_collators = CollatorAssignment::pending_collator_container_chain();
6

            
6
            match assigned_collators {
46006
                Some(assigned_collators) => {
4
                    let self_para_id = ParachainInfo::get();
4

            
4
                    assigned_collators.para_id_of(&account, self_para_id)
46002
                }
46002
                None => {
46004
                    Self::current_collator_parachain_assignment(account)
46002
                }
46002
            }
46002

            
46008
        }
46002

            
46002
        /// Return the list of collators of the given `ParaId`.
46002
        /// Returns `None` if the `ParaId` is not in the registrar.
46016
        fn parachain_collators(para_id: ParaId) -> Option<Vec<AccountId>> {
14
            let assigned_collators = CollatorAssignment::collator_container_chain();
14
            let self_para_id = ParachainInfo::get();
14

            
14
            if para_id == self_para_id {
46011
                Some(assigned_collators.orchestrator_chain)
46002
            } else {
46007
                assigned_collators.container_chains.get(&para_id).cloned()
46002
            }
46016
        }
46002
    }
46002

            
46002
    impl pallet_registrar_runtime_api::RegistrarApi<Block, ParaId> for Runtime {
46002
        /// Return the registered para ids
59603
        fn registered_paras() -> Vec<ParaId> {
20981
            // We should return the container-chains for the session in which we are kicking in
20981
            let parent_number = System::block_number();
20981
            let should_end_session = <Runtime as pallet_session::Config>::ShouldEndSession::should_end_session(parent_number + 1);
46002

            
59603
            let session_index = if should_end_session {
46942
                Session::current_index() +1
46002
            }
46002
            else {
58275
                Session::current_index()
46002
            };
46002

            
59603
            let container_chains = Registrar::session_container_chains(session_index);
20981
            let mut para_ids = vec![];
20981
            para_ids.extend(container_chains.parachains);
20981
            para_ids.extend(container_chains.parathreads.into_iter().map(|(para_id, _)| para_id));
20981

            
20981
            para_ids
20981
        }
46002

            
46002
        /// Fetch genesis data for this para id
46009
        fn genesis_data(para_id: ParaId) -> Option<ContainerChainGenesisData> {
7
            Registrar::para_genesis_data(para_id)
7
        }
46002

            
46002
        /// Fetch boot_nodes for this para id
46002
        fn boot_nodes(para_id: ParaId) -> Vec<Vec<u8>> {
            DataPreservers::assignments_profiles(para_id)
                .filter(|profile| profile.mode == pallet_data_preservers::ProfileMode::Bootnode)
                .map(|profile| profile.url.into())
                .collect()
        }
46002
    }
46002

            
46002
    impl pallet_registrar_runtime_api::OnDemandBlockProductionApi<Block, ParaId, Slot> for Runtime {
46002
        /// Returns slot frequency for particular para thread. Slot frequency specifies amount of slot
46002
        /// need to be passed between two parathread blocks. It is expressed as `(min, max)` pair where `min`
46002
        /// indicates amount of slot must pass before we produce another block and `max` indicates amount of
46002
        /// blocks before this parathread must produce the block.
46002
        ///
46002
        /// Simply put, parathread must produce a block after `min`  but before `(min+max)` slots.
46002
        ///
46002
        /// # Returns
46002
        ///
46002
        /// * `Some(slot_frequency)`.
46002
        /// * `None` if the `para_id` is not a parathread.
46002
        fn parathread_slot_frequency(para_id: ParaId) -> Option<SlotFrequency> {
            Registrar::parathread_params(para_id).map(|params| {
                params.slot_frequency
            })
        }
46002
    }
46002

            
46002
    impl pallet_author_noting_runtime_api::AuthorNotingApi<Block, AccountId, BlockNumber, ParaId> for Runtime
46002
        where
46002
        AccountId: parity_scale_codec::Codec,
46002
        BlockNumber: parity_scale_codec::Codec,
46002
        ParaId: parity_scale_codec::Codec,
46002
    {
46003
        fn latest_block_number(para_id: ParaId) -> Option<BlockNumber> {
1
            AuthorNoting::latest_author(para_id).map(|info| info.block_number)
1
        }
46002

            
46003
        fn latest_author(para_id: ParaId) -> Option<AccountId> {
1
            AuthorNoting::latest_author(para_id).map(|info| info.author)
1
        }
46002
    }
46002

            
46002
    impl dp_consensus::TanssiAuthorityAssignmentApi<Block, NimbusId> for Runtime {
46002
        /// Return the current authorities assigned to a given paraId
61850
        fn para_id_authorities(para_id: ParaId) -> Option<Vec<NimbusId>> {
23228
            get_para_id_authorities(para_id)
23228
        }
46002

            
46002
        /// Return the paraId assigned to a given authority
46034
        fn check_para_id_assignment(authority: NimbusId) -> Option<ParaId> {
32
            let parent_number = System::block_number();
32
            let should_end_session = <Runtime as pallet_session::Config>::ShouldEndSession::should_end_session(parent_number + 1);
46002

            
46034
            let session_index = if should_end_session {
46010
                Session::current_index() +1
46002
            }
46002
            else {
46026
                Session::current_index()
46002
            };
46034
            let assigned_authorities = AuthorityAssignment::collator_container_chain(session_index)?;
46034
            let self_para_id = ParachainInfo::get();
32

            
32
            assigned_authorities.para_id_of(&authority, self_para_id)
46034
        }
46002

            
46002
        /// Return the paraId assigned to a given authority on the next session.
46002
        /// On session boundary this returns the same as `check_para_id_assignment`.
46014
        fn check_para_id_assignment_next_session(authority: NimbusId) -> Option<ParaId> {
12
            let session_index = Session::current_index() + 1;
46014
            let assigned_authorities = AuthorityAssignment::collator_container_chain(session_index)?;
46014
            let self_para_id = ParachainInfo::get();
12

            
12
            assigned_authorities.para_id_of(&authority, self_para_id)
46014
        }
46002
    }
46002

            
46002
    impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>
46002
    for Runtime {
46002
        fn query_info(
24
            uxt: <Block as BlockT>::Extrinsic,
24
            len: u32,
24
        ) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo<Balance> {
24
            TransactionPayment::query_info(uxt, len)
24
        }
46002

            
46002
        fn query_fee_details(
12
            uxt: <Block as BlockT>::Extrinsic,
12
            len: u32,
12
        ) -> pallet_transaction_payment::FeeDetails<Balance> {
12
            TransactionPayment::query_fee_details(uxt, len)
12
        }
46002

            
46002
        fn query_weight_to_fee(weight: Weight) -> Balance {
60
            TransactionPayment::weight_to_fee(weight)
60
        }
46002

            
46002
        fn query_length_to_fee(length: u32) -> Balance {
18
            TransactionPayment::length_to_fee(length)
18
        }
46002
    }
46002

            
46002
    impl pallet_stream_payment_runtime_api::StreamPaymentApi<Block, StreamId, Balance, Balance>
46002
    for Runtime {
46002
        fn stream_payment_status(
54
            stream_id: StreamId,
54
            now: Option<Balance>,
54
        ) -> Result<StreamPaymentApiStatus<Balance>, StreamPaymentApiError> {
54
            match StreamPayment::stream_payment_status(stream_id, now) {
46002
                Ok(pallet_stream_payment::StreamPaymentStatus {
46002
                    payment, deposit_left, stalled
42
                }) => Ok(StreamPaymentApiStatus {
42
                    payment, deposit_left, stalled
42
                }),
46002
                Err(pallet_stream_payment::Error::<Runtime>::UnknownStreamId)
46002
                => Err(StreamPaymentApiError::UnknownStreamId),
46002
                Err(e) => Err(StreamPaymentApiError::Other(format!("{e:?}")))
46002
            }
46002
        }
46002
    }
46002

            
46002
    impl pallet_data_preservers_runtime_api::DataPreserversApi<Block, DataPreserversProfileId, ParaId> for Runtime {
46002
        fn get_active_assignment(
            profile_id: DataPreserversProfileId,
        ) -> pallet_data_preservers_runtime_api::Assignment<ParaId> {
46002
            use pallet_data_preservers_runtime_api::Assignment;
46002
            use pallet_stream_payment::StreamPaymentStatus;
46002

            
46002
            let Some((para_id, witness)) = pallet_data_preservers::Profiles::<Runtime>::get(profile_id)
                .and_then(|x| x.assignment) else
46002
            {
46002
                return Assignment::NotAssigned;
46002
            };
46002

            
46002
            match witness {
46002
                PreserversAssignementPaymentWitness::Free => Assignment::Active(para_id),
46002
                PreserversAssignementPaymentWitness::StreamPayment { stream_id } => {
46002
                    // Error means no Stream exists with that ID or some issue occured when computing
46002
                    // the status. In that case we cannot consider the assignment as active.
46002
                    let Ok(StreamPaymentStatus { stalled, .. }) = StreamPayment::stream_payment_status( stream_id, None) else {
46002
                        return Assignment::Inactive(para_id);
46002
                    };
46002

            
46002
                    if stalled {
46002
                        Assignment::Inactive(para_id)
46002
                    } else {
46002
                        Assignment::Active(para_id)
46002
                    }
46002
                },
46002
            }
46002
        }
46002
    }
46002

            
46002
    impl dp_slot_duration_runtime_api::TanssiSlotDurationApi<Block> for Runtime {
46002
        fn slot_duration() -> u64 {
            SLOT_DURATION
        }
46002
    }
46002

            
46002
    impl pallet_services_payment_runtime_api::ServicesPaymentApi<Block, Balance, ParaId> for Runtime {
46002
        fn block_cost(para_id: ParaId) -> Balance {
6
            let (block_production_costs, _) = <Runtime as pallet_services_payment::Config>::ProvideBlockProductionCost::block_cost(&para_id);
6
            block_production_costs
6
        }
46002

            
46002
        fn collator_assignment_cost(para_id: ParaId) -> Balance {
6
            let (collator_assignment_costs, _) = <Runtime as pallet_services_payment::Config>::ProvideCollatorAssignmentCost::collator_assignment_cost(&para_id);
6
            collator_assignment_costs
6
        }
46002
    }
46002

            
46002
    impl pallet_xcm_core_buyer_runtime_api::XCMCoreBuyerApi<Block, BlockNumber, ParaId, NimbusId> for Runtime {
46002
        fn is_core_buying_allowed(para_id: ParaId, collator_public_key: NimbusId) -> Result<(), BuyingError<BlockNumber>> {
            XcmCoreBuyer::is_core_buying_allowed(para_id, Some(collator_public_key))
        }
46002

            
46002
        fn create_buy_core_unsigned_extrinsic(para_id: ParaId, proof: BuyCoreCollatorProof<NimbusId>) -> Box<<Block as BlockT>::Extrinsic> {
            let call = RuntimeCall::XcmCoreBuyer(pallet_xcm_core_buyer::Call::buy_core {
                para_id,
                proof
            });
            let unsigned_extrinsic = UncheckedExtrinsic::new_unsigned(call);
            Box::new(unsigned_extrinsic)
        }
46002

            
46002
        fn get_buy_core_signature_nonce(para_id: ParaId) -> u64 {
            pallet_xcm_core_buyer::CollatorSignatureNonce::<Runtime>::get(para_id)
        }
46002

            
46002
        fn get_buy_core_slot_drift() -> Slot {
            <Runtime as pallet_xcm_core_buyer::Config>::BuyCoreSlotDrift::get()
        }
46002
    }
46002

            
46002
    impl xcm_runtime_apis::fees::XcmPaymentApi<Block> for Runtime {
46002
        fn query_acceptable_payment_assets(xcm_version: staging_xcm::Version) -> Result<Vec<VersionedAssetId>, XcmPaymentApiError> {
46002
            if !matches!(xcm_version, 3 | 4) {
46002
                return Err(XcmPaymentApiError::UnhandledXcmVersion);
46002
            }
6

            
6
            Ok([VersionedAssetId::V4(xcm_config::SelfReserve::get().into())]
6
                .into_iter()
6
                .chain(
6
                    pallet_asset_rate::ConversionRateToNative::<Runtime>::iter_keys().filter_map(|asset_id_u16| {
6
                        pallet_foreign_asset_creator::AssetIdToForeignAsset::<Runtime>::get(asset_id_u16).map(|location| {
6
                            VersionedAssetId::V4(location.into())
6
                        }).or_else(|| {
                            log::warn!("Asset `{}` is present in pallet_asset_rate but not in pallet_foreign_asset_creator", asset_id_u16);
46002
                            None
6
                        })
6
                    })
6
                )
12
                .filter_map(|asset| asset.into_version(xcm_version).map_err(|e| {
                    log::warn!("Failed to convert asset to version {}: {:?}", xcm_version, e);
46002
                }).ok())
6
                .collect())
46002
        }
46002

            
46002
        fn query_weight_to_asset_fee(weight: Weight, asset: VersionedAssetId) -> Result<u128, XcmPaymentApiError> {
12
            let local_asset = VersionedAssetId::V4(xcm_config::SelfReserve::get().into());
46002
            let asset = asset
12
                .into_version(4)
12
                .map_err(|_| XcmPaymentApiError::VersionedConversionFailed)?;
46002

            
46002
            if asset == local_asset {
46002
                Ok(WeightToFee::weight_to_fee(&weight))
46002
            } else {
46002
                let native_fee = WeightToFee::weight_to_fee(&weight);
46002
                let asset_v4: staging_xcm::opaque::lts::AssetId = asset.try_into().map_err(|_| XcmPaymentApiError::VersionedConversionFailed)?;
46002
                let location: staging_xcm::opaque::lts::Location = asset_v4.0;
46002
                let asset_id = pallet_foreign_asset_creator::ForeignAssetToAssetId::<Runtime>::get(location).ok_or(XcmPaymentApiError::AssetNotFound)?;
46002
                let asset_rate = AssetRate::to_asset_balance(native_fee, asset_id);
46002
                match asset_rate {
46002
                    Ok(x) => Ok(x),
46002
                    Err(pallet_asset_rate::Error::UnknownAssetKind) => Err(XcmPaymentApiError::AssetNotFound),
46002
                    // Error when converting native balance to asset balance, probably overflow
46002
                    Err(_e) => Err(XcmPaymentApiError::WeightNotComputable),
46002
                }
46002
            }
46002
        }
46002

            
46002
        fn query_xcm_weight(message: VersionedXcm<()>) -> Result<Weight, XcmPaymentApiError> {
6
            PolkadotXcm::query_xcm_weight(message)
6
        }
46002

            
46002
        fn query_delivery_fees(destination: VersionedLocation, message: VersionedXcm<()>) -> Result<VersionedAssets, XcmPaymentApiError> {
            PolkadotXcm::query_delivery_fees(destination, message)
        }
46002
    }
46002

            
46002
    impl xcm_runtime_apis::dry_run::DryRunApi<Block, RuntimeCall, RuntimeEvent, OriginCaller> for Runtime {
46002
        fn dry_run_call(origin: OriginCaller, call: RuntimeCall) -> Result<CallDryRunEffects<RuntimeEvent>, XcmDryRunApiError> {
6
            PolkadotXcm::dry_run_call::<Runtime, xcm_config::XcmRouter, OriginCaller, RuntimeCall>(origin, call)
6
        }
46002

            
46002
        fn dry_run_xcm(origin_location: VersionedLocation, xcm: VersionedXcm<RuntimeCall>) -> Result<XcmDryRunEffects<RuntimeEvent>, XcmDryRunApiError> {
6
            PolkadotXcm::dry_run_xcm::<Runtime, xcm_config::XcmRouter, RuntimeCall, xcm_config::XcmConfig>(origin_location, xcm)
6
        }
46002
    }
46002

            
46002
    impl xcm_runtime_apis::conversions::LocationToAccountApi<Block, AccountId> for Runtime {
46002
        fn convert_location(location: VersionedLocation) -> Result<
6
            AccountId,
6
            xcm_runtime_apis::conversions::Error
6
        > {
6
            xcm_runtime_apis::conversions::LocationToAccountHelper::<
6
                AccountId,
6
                xcm_config::LocationToAccountId,
6
            >::convert_location(location)
6
        }
46002
    }
327488
}
#[allow(dead_code)]
struct CheckInherents;
// TODO: this should be removed but currently if we remove it the relay does not check anything
// related to other inherents that are not parachain-system
#[allow(deprecated)]
impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {
    fn check_inherents(
        block: &Block,
        relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,
    ) -> sp_inherents::CheckInherentsResult {
        let relay_chain_slot = relay_state_proof
            .read_slot()
            .expect("Could not read the relay chain slot from the proof");
        let inherent_data =
            cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(
                relay_chain_slot,
                sp_std::time::Duration::from_secs(6),
            )
            .create_inherent_data()
            .expect("Could not create the timestamp inherent data");
        inherent_data.check_extrinsics(block)
    }
}
cumulus_pallet_parachain_system::register_validate_block! {
    Runtime = Runtime,
    CheckInherents = CheckInherents,
    BlockExecutor = pallet_author_inherent::BlockExecutor::<Runtime, Executive>,
}
#[macro_export]
macro_rules! prod_or_fast {
    ($prod:expr, $test:expr) => {
        if cfg!(feature = "fast-runtime") {
            $test
        } else {
            $prod
        }
    };
    ($prod:expr, $test:expr, $env:expr) => {
        if cfg!(feature = "fast-runtime") {
            core::option_env!($env)
                .map(|s| s.parse().ok())
                .flatten()
                .unwrap_or($test)
        } else {
            $prod
        }
    };
}