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
extern crate alloc;
26

            
27
pub mod xcm_config;
28

            
29
#[cfg(feature = "std")]
30
use sp_version::NativeVersion;
31
use {
32
    frame_support::{
33
        storage::{with_storage_layer, with_transaction},
34
        traits::{ExistenceRequirement, WithdrawReasons},
35
    },
36
    polkadot_runtime_common::SlowAdjustingFeeUpdate,
37
};
38

            
39
#[cfg(any(feature = "std", test))]
40
pub use sp_runtime::BuildStorage;
41
use sp_runtime::{DispatchError, TransactionOutcome};
42

            
43
pub mod weights;
44

            
45
#[cfg(test)]
46
mod tests;
47

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

            
140
/// Block type as expected by this runtime.
141
pub type Block = generic::Block<Header, UncheckedExtrinsic>;
142
/// A Block signed with a Justification
143
pub type SignedBlock = generic::SignedBlock<Block>;
144
/// BlockId type as expected by this runtime.
145
pub type BlockId = generic::BlockId<Block>;
146

            
147
/// CollatorId type expected by this runtime.
148
pub type CollatorId = AccountId;
149

            
150
/// The `TxExtension` to the basic transaction logic.
151
pub type TxExtension = (
152
    frame_system::CheckNonZeroSender<Runtime>,
153
    frame_system::CheckSpecVersion<Runtime>,
154
    frame_system::CheckTxVersion<Runtime>,
155
    frame_system::CheckGenesis<Runtime>,
156
    frame_system::CheckEra<Runtime>,
157
    frame_system::CheckNonce<Runtime>,
158
    frame_system::CheckWeight<Runtime>,
159
    pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
160
    cumulus_primitives_storage_weight_reclaim::StorageWeightReclaim<Runtime>,
161
);
162

            
163
/// Unchecked extrinsic type as expected by this runtime.
164
pub type UncheckedExtrinsic =
165
    generic::UncheckedExtrinsic<Address, RuntimeCall, Signature, TxExtension>;
166

            
167
/// Extrinsic type that has already been checked.
168
pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, RuntimeCall, TxExtension>;
169

            
170
/// Executive: handles dispatch to the various modules.
171
pub type Executive = frame_executive::Executive<
172
    Runtime,
173
    Block,
174
    frame_system::ChainContext<Runtime>,
175
    Runtime,
176
    AllPalletsWithSystem,
177
>;
178

            
179
/// DANCE, the native token, uses 12 decimals of precision.
180
pub mod currency {
181
    use super::Balance;
182

            
183
    // Provide a common factor between runtimes based on a supply of 10_000_000 tokens.
184
    pub const SUPPLY_FACTOR: Balance = 100;
185

            
186
    pub const MICRODANCE: Balance = 1_000_000;
187
    pub const MILLIDANCE: Balance = 1_000_000_000;
188
    pub const DANCE: Balance = 1_000_000_000_000;
189
    pub const KILODANCE: Balance = 1_000_000_000_000_000;
190

            
191
    pub const STORAGE_BYTE_FEE: Balance = 100 * MICRODANCE * SUPPLY_FACTOR;
192
    pub const STORAGE_ITEM_FEE: Balance = 100 * MILLIDANCE * SUPPLY_FACTOR;
193

            
194
4334
    pub const fn deposit(items: u32, bytes: u32) -> Balance {
195
4334
        items as Balance * STORAGE_ITEM_FEE + (bytes as Balance) * STORAGE_BYTE_FEE
196
4334
    }
197
}
198

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

            
226
/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know
227
/// the specifics of the runtime. They can then be made to be agnostic over specific formats
228
/// of data like extrinsics, allowing for them to continue syncing the network through upgrades
229
/// to even the core data structures.
230
pub mod opaque {
231
    use {
232
        super::*,
233
        sp_runtime::{
234
            generic,
235
            traits::{BlakeTwo256, Hash as HashT},
236
        },
237
    };
238

            
239
    pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;
240
    /// Opaque block header type.
241
    pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
242
    /// Opaque block type.
243
    pub type Block = generic::Block<Header, UncheckedExtrinsic>;
244
    /// Opaque block identifier type.
245
    pub type BlockId = generic::BlockId<Block>;
246
    /// Opaque block hash type.
247
    pub type Hash = <BlakeTwo256 as HashT>::Output;
248
    /// Opaque signature type.
249
    pub use super::Signature;
250
}
251

            
252
impl_opaque_keys! {
253
    pub struct SessionKeys {
254
        pub nimbus: Initializer,
255
    }
256
}
257

            
258
#[sp_version::runtime_version]
259
pub const VERSION: RuntimeVersion = RuntimeVersion {
260
    spec_name: Cow::Borrowed("dancebox"),
261
    impl_name: Cow::Borrowed("dancebox"),
262
    authoring_version: 1,
263
    spec_version: 1400,
264
    impl_version: 0,
265
    apis: RUNTIME_API_VERSIONS,
266
    transaction_version: 1,
267
    system_version: 1,
268
};
269

            
270
/// This determines the average expected block time that we are targeting.
271
/// Blocks will be produced at a minimum duration defined by `SLOT_DURATION`.
272
/// `SLOT_DURATION` is picked up by `pallet_timestamp` which is in turn picked
273
/// up by `pallet_aura` to implement `fn slot_duration()`.
274
///
275
/// Change this to adjust the block time.
276
pub const MILLISECS_PER_BLOCK: u64 = 6000;
277

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

            
282
// Time is measured by number of blocks.
283
pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);
284
pub const HOURS: BlockNumber = MINUTES * 60;
285
pub const DAYS: BlockNumber = HOURS * 24;
286

            
287
// Unit = the base number of indivisible units for balances
288
pub const UNIT: Balance = 1_000_000_000_000;
289
pub const CENTS: Balance = UNIT / 30_000;
290
pub const MILLIUNIT: Balance = 1_000_000_000;
291
pub const MICROUNIT: Balance = 1_000_000;
292
/// The existential deposit. Set to 1/10 of the Connected Relay Chain.
293
pub const EXISTENTIAL_DEPOSIT: Balance = MILLIUNIT;
294

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

            
299
/// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used by
300
/// `Operational` extrinsics.
301
const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);
302

            
303
/// We allow for 2 seconds of compute with a 6 second average block time
304
const MAXIMUM_BLOCK_WEIGHT: Weight = Weight::from_parts(
305
    WEIGHT_REF_TIME_PER_SECOND.saturating_mul(2),
306
    cumulus_primitives_core::relay_chain::MAX_POV_SIZE as u64,
307
);
308

            
309
/// The version information used to identify this runtime when compiled natively.
310
#[cfg(feature = "std")]
311
2910
pub fn native_version() -> NativeVersion {
312
2910
    NativeVersion {
313
2910
        runtime_version: VERSION,
314
2910
        can_author_with: Default::default(),
315
2910
    }
316
2910
}
317

            
318
parameter_types! {
319
    pub const Version: RuntimeVersion = VERSION;
320

            
321
    // This part is copied from Substrate's `bin/node/runtime/src/lib.rs`.
322
    //  The `RuntimeBlockLength` and `RuntimeBlockWeights` exist here because the
323
    // `DeletionWeightLimit` and `DeletionQueueDepth` depend on those to parameterize
324
    // the lazy contract deletion.
325
    pub RuntimeBlockLength: BlockLength =
326
        BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);
327
    pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()
328
        .base_block(BlockExecutionWeight::get())
329
1655184
        .for_class(DispatchClass::all(), |weights| {
330
1655184
            weights.base_extrinsic = ExtrinsicBaseWeight::get();
331
1655184
        })
332
551728
        .for_class(DispatchClass::Normal, |weights| {
333
551728
            weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);
334
551728
        })
335
551728
        .for_class(DispatchClass::Operational, |weights| {
336
551728
            weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);
337
551728
            // Operational transactions have some extra reserved space, so that they
338
551728
            // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.
339
551728
            weights.reserved = Some(
340
551728
                MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT
341
551728
            );
342
551728
        })
343
        .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)
344
        .build_or_panic();
345
    pub const SS58Prefix: u16 = 42;
346
}
347

            
348
// Configure FRAME pallets to include in runtime.
349

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

            
405
impl pallet_timestamp::Config for Runtime {
406
    /// A timestamp: milliseconds since the unix epoch.
407
    type Moment = u64;
408
    type OnTimestampSet = dp_consensus::OnTimestampSet<
409
        <Self as pallet_author_inherent::Config>::SlotBeacon,
410
        ConstU64<{ SLOT_DURATION }>,
411
    >;
412
    type MinimumPeriod = ConstU64<{ SLOT_DURATION / 2 }>;
413
    type WeightInfo = weights::pallet_timestamp::SubstrateWeight<Runtime>;
414
}
415

            
416
pub struct CanAuthor;
417
impl nimbus_primitives::CanAuthor<NimbusId> for CanAuthor {
418
27035
    fn can_author(author: &NimbusId, slot: &u32) -> bool {
419
27035
        let authorities = AuthorityAssignment::collator_container_chain(Session::current_index())
420
27035
            .expect("authorities should be set")
421
27035
            .orchestrator_chain;
422
27035

            
423
27035
        if authorities.is_empty() {
424
            return false;
425
27035
        }
426
27035

            
427
27035
        let author_index = (*slot as usize) % authorities.len();
428
27035
        let expected_author = &authorities[author_index];
429
27035

            
430
27035
        expected_author == author
431
27035
    }
432
    #[cfg(feature = "runtime-benchmarks")]
433
    fn get_authors(_slot: &u32) -> Vec<NimbusId> {
434
        AuthorityAssignment::collator_container_chain(Session::current_index())
435
            .expect("authorities should be set")
436
            .orchestrator_chain
437
    }
438
}
439

            
440
impl pallet_author_inherent::Config for Runtime {
441
    type AuthorId = NimbusId;
442
    type AccountLookup = dp_consensus::NimbusLookUp;
443
    type CanAuthor = CanAuthor;
444
    type SlotBeacon = dp_consensus::AuraDigestSlotBeacon<Runtime>;
445
    type WeightInfo = weights::pallet_author_inherent::SubstrateWeight<Runtime>;
446
}
447

            
448
parameter_types! {
449
    pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT;
450
}
451

            
452
impl pallet_balances::Config for Runtime {
453
    type MaxLocks = ConstU32<50>;
454
    /// The type for recording an account's balance.
455
    type Balance = Balance;
456
    /// The ubiquitous event type.
457
    type RuntimeEvent = RuntimeEvent;
458
    type DustRemoval = ();
459
    type ExistentialDeposit = ExistentialDeposit;
460
    type AccountStore = System;
461
    type MaxReserves = ConstU32<50>;
462
    type ReserveIdentifier = [u8; 8];
463
    type FreezeIdentifier = RuntimeFreezeReason;
464
    type MaxFreezes = ConstU32<10>;
465
    type RuntimeHoldReason = RuntimeHoldReason;
466
    type RuntimeFreezeReason = RuntimeFreezeReason;
467
    type DoneSlashHandler = ();
468
    type WeightInfo = weights::pallet_balances::SubstrateWeight<Runtime>;
469
}
470

            
471
pub struct DealWithFees<R>(sp_std::marker::PhantomData<R>);
472
impl<R> OnUnbalanced<Credit<R::AccountId, pallet_balances::Pallet<R>>> for DealWithFees<R>
473
where
474
    R: pallet_balances::Config + pallet_treasury::Config + frame_system::Config,
475
    pallet_treasury::NegativeImbalanceOf<R>: From<NegativeImbalance<R>>,
476
{
477
    // this seems to be called for substrate-based transactions
478
2532
    fn on_unbalanceds(
479
2532
        mut fees_then_tips: impl Iterator<Item = Credit<R::AccountId, pallet_balances::Pallet<R>>>,
480
2532
    ) {
481
2532
        if let Some(fees) = fees_then_tips.next() {
482
            // 80% is burned, 20% goes to the treasury
483
            // Same policy applies for tips as well
484
2532
            let burn_percentage = 80;
485
2532
            let treasury_percentage = 20;
486
2532

            
487
2532
            let (_, to_treasury) = fees.ration(burn_percentage, treasury_percentage);
488
2532
            ResolveTo::<pallet_treasury::TreasuryAccountId<R>, pallet_balances::Pallet<R>>::on_unbalanced(to_treasury);
489
            // Balances pallet automatically burns dropped Negative Imbalances by decreasing total_supply accordingly
490
            // handle tip if there is one
491
2532
            if let Some(tip) = fees_then_tips.next() {
492
2532
                let (_, to_treasury) = tip.ration(burn_percentage, treasury_percentage);
493
2532
                ResolveTo::<pallet_treasury::TreasuryAccountId<R>, pallet_balances::Pallet<R>>::on_unbalanced(to_treasury);
494
2532
            }
495
        }
496
2532
    }
497

            
498
    // this is called from pallet_evm for Ethereum-based transactions
499
    // (technically, it calls on_unbalanced, which calls this when non-zero)
500
    fn on_nonzero_unbalanced(amount: Credit<R::AccountId, pallet_balances::Pallet<R>>) {
501
        // 80% is burned, 20% goes to the treasury
502
        let burn_percentage = 80;
503
        let treasury_percentage = 20;
504

            
505
        let (_, to_treasury) = amount.ration(burn_percentage, treasury_percentage);
506
        ResolveTo::<pallet_treasury::TreasuryAccountId<R>, pallet_balances::Pallet<R>>::on_unbalanced(to_treasury);
507
    }
508
}
509

            
510
parameter_types! {
511
    pub const TransactionByteFee: Balance = 1;
512
}
513

            
514
impl pallet_transaction_payment::Config for Runtime {
515
    type RuntimeEvent = RuntimeEvent;
516
    // This will burn 80% from fees & tips and deposit the remainder into the treasury
517
    type OnChargeTransaction = FungibleAdapter<Balances, DealWithFees<Runtime>>;
518
    type OperationalFeeMultiplier = ConstU8<5>;
519
    type WeightToFee = WeightToFee;
520
    type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;
521
    type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Self>;
522
    type WeightInfo = weights::pallet_transaction_payment::SubstrateWeight<Runtime>;
523
}
524

            
525
parameter_types! {
526
    pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
527
    pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
528
    pub const RelayOrigin: AggregateMessageOrigin = AggregateMessageOrigin::Parent;
529
}
530

            
531
pub const RELAY_CHAIN_SLOT_DURATION_MILLIS: u32 = 6000;
532
pub const UNINCLUDED_SEGMENT_CAPACITY: u32 = 3;
533
pub const BLOCK_PROCESSING_VELOCITY: u32 = 1;
534

            
535
type ConsensusHook = pallet_async_backing::consensus_hook::FixedVelocityConsensusHook<
536
    Runtime,
537
    BLOCK_PROCESSING_VELOCITY,
538
    UNINCLUDED_SEGMENT_CAPACITY,
539
>;
540

            
541
impl cumulus_pallet_parachain_system::Config for Runtime {
542
    type WeightInfo = weights::cumulus_pallet_parachain_system::SubstrateWeight<Runtime>;
543
    type RuntimeEvent = RuntimeEvent;
544
    type OnSystemEvent = ();
545
    type SelfParaId = parachain_info::Pallet<Runtime>;
546
    type OutboundXcmpMessageSource = XcmpQueue;
547
    type DmpQueue = frame_support::traits::EnqueueWithOrigin<MessageQueue, RelayOrigin>;
548
    type ReservedDmpWeight = ReservedDmpWeight;
549
    type XcmpMessageHandler = XcmpQueue;
550
    type ReservedXcmpWeight = ReservedXcmpWeight;
551
    type CheckAssociatedRelayNumber = RelayNumberMonotonicallyIncreases;
552
    type ConsensusHook = ConsensusHook;
553
    type SelectCore = cumulus_pallet_parachain_system::DefaultCoreSelector<Runtime>;
554
}
555
pub struct ParaSlotProvider;
556
impl Get<(Slot, SlotDuration)> for ParaSlotProvider {
557
24436
    fn get() -> (Slot, SlotDuration) {
558
24436
        let slot = u64::from(<Runtime as pallet_author_inherent::Config>::SlotBeacon::slot());
559
24436
        (Slot::from(slot), SlotDuration::from_millis(SLOT_DURATION))
560
24436
    }
561
}
562

            
563
parameter_types! {
564
    pub const ExpectedBlockTime: u64 = MILLISECS_PER_BLOCK;
565
}
566

            
567
impl pallet_async_backing::Config for Runtime {
568
    type AllowMultipleBlocksPerSlot = ConstBool<true>;
569
    type GetAndVerifySlot =
570
        pallet_async_backing::ParaSlot<RELAY_CHAIN_SLOT_DURATION_MILLIS, ParaSlotProvider>;
571
    type ExpectedBlockTime = ExpectedBlockTime;
572
}
573

            
574
/// Only callable after `set_validation_data` is called which forms this proof the same way
575
2616
fn relay_chain_state_proof() -> RelayChainStateProof {
576
2616
    let relay_storage_root =
577
2616
        RelaychainDataProvider::<Runtime>::current_relay_chain_state().state_root;
578
2616
    let relay_chain_state = cumulus_pallet_parachain_system::RelayStateProof::<Runtime>::get()
579
2616
        .expect("set in `set_validation_data`");
580
2616
    RelayChainStateProof::new(ParachainInfo::get(), relay_storage_root, relay_chain_state)
581
2616
        .expect("Invalid relay chain state proof, already constructed in `set_validation_data`")
582
2616
}
583

            
584
pub struct BabeCurrentBlockRandomnessGetter;
585
impl BabeCurrentBlockRandomnessGetter {
586
2616
    fn get_block_randomness() -> Option<Hash> {
587
2616
        if cfg!(feature = "runtime-benchmarks") {
588
            // storage reads as per actual reads
589
            let _relay_storage_root =
590
                RelaychainDataProvider::<Runtime>::current_relay_chain_state().state_root;
591

            
592
            let _relay_chain_state =
593
                cumulus_pallet_parachain_system::RelayStateProof::<Runtime>::get();
594
            let benchmarking_babe_output = Hash::default();
595
            return Some(benchmarking_babe_output);
596
2616
        }
597
2616

            
598
2616
        relay_chain_state_proof()
599
2616
            .read_optional_entry::<Option<Hash>>(
600
2616
                relay_chain::well_known_keys::CURRENT_BLOCK_RANDOMNESS,
601
2616
            )
602
2616
            .ok()
603
2616
            .flatten()
604
2616
            .flatten()
605
2616
    }
606

            
607
    /// Return the block randomness from the relay mixed with the provided subject.
608
    /// This ensures that the randomness will be different on different pallets, as long as the subject is different.
609
    // TODO: audit usage of randomness API
610
    // https://github.com/paritytech/polkadot/issues/2601
611
2616
    fn get_block_randomness_mixed(subject: &[u8]) -> Option<Hash> {
612
2616
        Self::get_block_randomness()
613
2616
            .map(|random_hash| mix_randomness::<Runtime>(random_hash, subject))
614
2616
    }
615
}
616

            
617
/// Combines the vrf output of the previous relay block with the provided subject.
618
/// This ensures that the randomness will be different on different pallets, as long as the subject is different.
619
86
fn mix_randomness<T: frame_system::Config>(vrf_output: Hash, subject: &[u8]) -> T::Hash {
620
86
    let mut digest = Vec::new();
621
86
    digest.extend_from_slice(vrf_output.as_ref());
622
86
    digest.extend_from_slice(subject);
623
86

            
624
86
    T::Hashing::hash(digest.as_slice())
625
86
}
626

            
627
// Randomness trait
628
impl frame_support::traits::Randomness<Hash, BlockNumber> for BabeCurrentBlockRandomnessGetter {
629
    fn random(subject: &[u8]) -> (Hash, BlockNumber) {
630
        let block_number = frame_system::Pallet::<Runtime>::block_number();
631
        let randomness = Self::get_block_randomness_mixed(subject).unwrap_or_default();
632

            
633
        (randomness, block_number)
634
    }
635
}
636

            
637
pub struct OwnApplySession;
638
impl pallet_initializer::ApplyNewSession<Runtime> for OwnApplySession {
639
3331
    fn apply_new_session(
640
3331
        _changed: bool,
641
3331
        session_index: u32,
642
3331
        all_validators: Vec<(AccountId, NimbusId)>,
643
3331
        queued: Vec<(AccountId, NimbusId)>,
644
3331
    ) {
645
3331
        // We first initialize Configuration
646
3331
        Configuration::initializer_on_new_session(&session_index);
647
3331
        // Next: Registrar
648
3331
        Registrar::initializer_on_new_session(&session_index);
649
3331
        // Next: AuthorityMapping
650
3331
        AuthorityMapping::initializer_on_new_session(&session_index, &all_validators);
651
3331

            
652
11836
        let next_collators = queued.iter().map(|(k, _)| k.clone()).collect();
653
3331

            
654
3331
        // Next: CollatorAssignment
655
3331
        let assignments =
656
3331
            CollatorAssignment::initializer_on_new_session(&session_index, next_collators);
657
3331

            
658
3331
        let queued_id_to_nimbus_map = queued.iter().cloned().collect();
659
3331
        AuthorityAssignment::initializer_on_new_session(
660
3331
            &session_index,
661
3331
            &queued_id_to_nimbus_map,
662
3331
            &assignments.next_assignment,
663
3331
        );
664
3331

            
665
3331
        // Next: InactivityTracking
666
3331
        InactivityTracking::process_ended_session();
667
3331
    }
668

            
669
2604
    fn on_before_session_ending() {
670
2604
        InactivityTracking::on_before_session_ending();
671
2604
    }
672
}
673

            
674
impl pallet_initializer::Config for Runtime {
675
    type SessionIndex = u32;
676

            
677
    /// The identifier type for an authority.
678
    type AuthorityId = NimbusId;
679

            
680
    type SessionHandler = OwnApplySession;
681
}
682

            
683
impl parachain_info::Config for Runtime {}
684

            
685
/// Returns a list of collators by combining pallet_invulnerables and pallet_pooled_staking.
686
pub struct CollatorsFromInvulnerablesAndThenFromStaking;
687

            
688
/// Play the role of the session manager.
689
impl SessionManager<CollatorId> for CollatorsFromInvulnerablesAndThenFromStaking {
690
4058
    fn new_session(index: SessionIndex) -> Option<Vec<CollatorId>> {
691
4058
        if <frame_system::Pallet<Runtime>>::block_number() == 0 {
692
            // Do not show this log in genesis
693
1454
            log::debug!(
694
                "assembling new collators for new session {} at #{:?}",
695
                index,
696
                <frame_system::Pallet<Runtime>>::block_number(),
697
            );
698
        } else {
699
2604
            log::info!(
700
2226
                "assembling new collators for new session {} at #{:?}",
701
2226
                index,
702
2226
                <frame_system::Pallet<Runtime>>::block_number(),
703
            );
704
        }
705

            
706
4058
        let invulnerables = Invulnerables::invulnerables().to_vec();
707
4058
        let candidates_staking =
708
4058
            pallet_pooled_staking::SortedEligibleCandidates::<Runtime>::get().to_vec();
709
4058
        // Max number of collators is set in pallet_configuration
710
4058
        let target_session_index = index.saturating_add(1);
711
4058
        let max_collators =
712
4058
            <Configuration as GetHostConfiguration<u32>>::max_collators(target_session_index);
713
4058
        let collators = invulnerables
714
4058
            .iter()
715
4058
            .cloned()
716
4058
            .chain(candidates_staking.into_iter().filter_map(|elig| {
717
268
                let cand = elig.candidate;
718
268
                if invulnerables.contains(&cand) {
719
                    // If a candidate is both in pallet_invulnerables and pallet_staking, do not count it twice
720
80
                    None
721
                } else {
722
188
                    Some(cand)
723
                }
724
4058
            }))
725
4058
            .take(max_collators as usize)
726
4058
            .collect();
727
4058

            
728
4058
        // TODO: weight?
729
4058
        /*
730
4058
        frame_system::Pallet::<T>::register_extra_weight_unchecked(
731
4058
            T::WeightInfo::new_session(invulnerables.len() as u32),
732
4058
            DispatchClass::Mandatory,
733
4058
        );
734
4058
        */
735
4058
        Some(collators)
736
4058
    }
737
3331
    fn start_session(_: SessionIndex) {
738
3331
        // we don't care.
739
3331
    }
740
2604
    fn end_session(_: SessionIndex) {
741
2604
        // we don't care.
742
2604
    }
743
}
744

            
745
parameter_types! {
746
    pub const Period: u32 = prod_or_fast!(1 * HOURS, 1 * MINUTES);
747
    pub const Offset: u32 = 0;
748
}
749

            
750
impl pallet_session::Config for Runtime {
751
    type RuntimeEvent = RuntimeEvent;
752
    type ValidatorId = CollatorId;
753
    // we don't have stash and controller, thus we don't need the convert as well.
754
    type ValidatorIdOf = ConvertInto;
755
    type ShouldEndSession = pallet_session::PeriodicSessions<Period, Offset>;
756
    type NextSessionRotation = pallet_session::PeriodicSessions<Period, Offset>;
757
    type SessionManager = CollatorsFromInvulnerablesAndThenFromStaking;
758
    // Essentially just Aura, but let's be pedantic.
759
    type SessionHandler = <SessionKeys as sp_runtime::traits::OpaqueKeys>::KeyTypeIdProviders;
760
    type Keys = SessionKeys;
761
    type WeightInfo = weights::pallet_session::SubstrateWeight<Runtime>;
762
}
763

            
764
/// Read full_rotation_period from pallet_configuration
765
pub struct ConfigurationCollatorRotationSessionPeriod;
766

            
767
impl Get<u32> for ConfigurationCollatorRotationSessionPeriod {
768
5818
    fn get() -> u32 {
769
5818
        Configuration::config().full_rotation_period
770
5818
    }
771
}
772

            
773
pub struct BabeGetRandomnessForNextBlock;
774

            
775
impl GetRandomnessForNextBlock<u32> for BabeGetRandomnessForNextBlock {
776
53877
    fn should_end_session(n: u32) -> bool {
777
53877
        <Runtime as pallet_session::Config>::ShouldEndSession::should_end_session(n)
778
53877
    }
779

            
780
2616
    fn get_randomness() -> [u8; 32] {
781
2616
        let block_number = System::block_number();
782
2616
        let random_seed = if block_number != 0 {
783
86
            if let Some(random_hash) =
784
2616
                BabeCurrentBlockRandomnessGetter::get_block_randomness_mixed(b"CollatorAssignment")
785
            {
786
                // Return random_hash as a [u8; 32] instead of a Hash
787
86
                let mut buf = [0u8; 32];
788
86
                let len = sp_std::cmp::min(32, random_hash.as_ref().len());
789
86
                buf[..len].copy_from_slice(&random_hash.as_ref()[..len]);
790
86

            
791
86
                buf
792
            } else {
793
                // If there is no randomness (e.g when running in dev mode), return [0; 32]
794
2530
                [0; 32]
795
            }
796
        } else {
797
            // In block 0 (genesis) there is no randomness
798
            [0; 32]
799
        };
800

            
801
2616
        random_seed
802
2616
    }
803
}
804

            
805
pub struct RemoveInvulnerablesImpl;
806

            
807
impl RemoveInvulnerables<CollatorId> for RemoveInvulnerablesImpl {
808
4546
    fn remove_invulnerables(
809
4546
        collators: &mut Vec<CollatorId>,
810
4546
        num_invulnerables: usize,
811
4546
    ) -> Vec<CollatorId> {
812
4546
        if num_invulnerables == 0 {
813
            return vec![];
814
4546
        }
815
4546
        // TODO: check if this works on session changes
816
4546
        let all_invulnerables = pallet_invulnerables::Invulnerables::<Runtime>::get();
817
4546
        if all_invulnerables.is_empty() {
818
144
            return vec![];
819
4402
        }
820
4402
        let mut invulnerables = vec![];
821
4402
        // TODO: use binary_search when invulnerables are sorted
822
5497
        collators.retain(|x| {
823
5497
            if invulnerables.len() < num_invulnerables && all_invulnerables.contains(x) {
824
3587
                invulnerables.push(x.clone());
825
3587
                false
826
            } else {
827
1910
                true
828
            }
829
5497
        });
830
4402

            
831
4402
        invulnerables
832
4546
    }
833
}
834

            
835
pub struct ParaIdAssignmentHooksImpl;
836

            
837
impl ParaIdAssignmentHooksImpl {
838
7519
    fn charge_para_ids_internal(
839
7519
        blocks_per_session: tp_traits::BlockNumber,
840
7519
        para_id: ParaId,
841
7519
        currently_assigned: &BTreeSet<ParaId>,
842
7519
        maybe_tip: &Option<BalanceOf<Runtime>>,
843
7519
    ) -> Result<Weight, DispatchError> {
844
        use frame_support::traits::Currency;
845
        type ServicePaymentCurrency = <Runtime as pallet_services_payment::Config>::Currency;
846

            
847
        // Check if the container chain has enough credits for a session assignments
848
7356
        let maybe_assignment_imbalance =
849
7519
            if  pallet_services_payment::Pallet::<Runtime>::burn_collator_assignment_free_credit_for_para(&para_id).is_err() {
850
219
                let (amount_to_charge, _weight) =
851
219
                    <Runtime as pallet_services_payment::Config>::ProvideCollatorAssignmentCost::collator_assignment_cost(&para_id);
852
219
                Some(<ServicePaymentCurrency as Currency<AccountId>>::withdraw(
853
219
                    &pallet_services_payment::Pallet::<Runtime>::parachain_tank(para_id),
854
219
                    amount_to_charge,
855
219
                    WithdrawReasons::FEE,
856
219
                    ExistenceRequirement::KeepAlive,
857
219
                )?)
858
            } else {
859
7300
                None
860
            };
861

            
862
7356
        if let Some(tip) = maybe_tip {
863
4835
            if let Err(e) = pallet_services_payment::Pallet::<Runtime>::charge_tip(&para_id, tip) {
864
                // Return assignment imbalance to tank on error
865
13
                if let Some(assignment_imbalance) = maybe_assignment_imbalance {
866
                    <Runtime as pallet_services_payment::Config>::Currency::resolve_creating(
867
                        &pallet_services_payment::Pallet::<Runtime>::parachain_tank(para_id),
868
                        assignment_imbalance,
869
                    );
870
13
                }
871
13
                return Err(e);
872
4822
            }
873
2521
        }
874

            
875
7343
        if let Some(assignment_imbalance) = maybe_assignment_imbalance {
876
56
            <Runtime as pallet_services_payment::Config>::OnChargeForCollatorAssignment::on_unbalanced(assignment_imbalance);
877
7287
        }
878

            
879
        // If the para has been assigned collators for this session it must have enough block credits
880
        // for the current and the next session.
881
7343
        let block_credits_needed = if currently_assigned.contains(&para_id) {
882
6726
            blocks_per_session * 2
883
        } else {
884
617
            blocks_per_session
885
        };
886
        // Check if the container chain has enough credits for producing blocks
887
7343
        let free_block_credits =
888
7343
            pallet_services_payment::BlockProductionCredits::<Runtime>::get(para_id)
889
7343
                .unwrap_or_default();
890
7343
        let remaining_block_credits = block_credits_needed.saturating_sub(free_block_credits);
891
7343
        let (block_production_costs, _) =
892
7343
            <Runtime as pallet_services_payment::Config>::ProvideBlockProductionCost::block_cost(
893
7343
                &para_id,
894
7343
            );
895
7343
        // Check if we can withdraw
896
7343
        let remaining_block_credits_to_pay =
897
7343
            u128::from(remaining_block_credits).saturating_mul(block_production_costs);
898
7343
        let remaining_to_pay = remaining_block_credits_to_pay;
899
7343
        // This should take into account whether we tank goes below ED
900
7343
        // The true refers to keepAlive
901
7343
        Balances::can_withdraw(
902
7343
            &pallet_services_payment::Pallet::<Runtime>::parachain_tank(para_id),
903
7343
            remaining_to_pay,
904
7343
        )
905
7343
        .into_result(true)?;
906
        // TODO: Have proper weight
907
7179
        Ok(Weight::zero())
908
7519
    }
909
}
910

            
911
impl<AC> ParaIdAssignmentHooks<BalanceOf<Runtime>, AC> for ParaIdAssignmentHooksImpl {
912
6662
    fn pre_assignment(para_ids: &mut Vec<ParaId>, currently_assigned: &BTreeSet<ParaId>) {
913
6662
        let blocks_per_session = Period::get();
914
6662
        para_ids.retain(|para_id| {
915
4975
            with_transaction(|| {
916
4975
                let max_tip =
917
4975
                    pallet_services_payment::MaxTip::<Runtime>::get(para_id).unwrap_or_default();
918
4975
                TransactionOutcome::Rollback(Self::charge_para_ids_internal(
919
4975
                    blocks_per_session,
920
4975
                    *para_id,
921
4975
                    currently_assigned,
922
4975
                    &Some(max_tip),
923
4975
                ))
924
4975
            })
925
4975
            .is_ok()
926
6662
        });
927
6662
    }
928

            
929
3331
    fn post_assignment(
930
3331
        current_assigned: &BTreeSet<ParaId>,
931
3331
        new_assigned: &mut BTreeMap<ParaId, Vec<AC>>,
932
3331
        maybe_tip: &Option<BalanceOf<Runtime>>,
933
3331
    ) -> Weight {
934
3331
        let blocks_per_session = Period::get();
935
3331
        let mut total_weight = Weight::zero();
936
5251
        new_assigned.retain(|&para_id, collators| {
937
4635
            // Short-circuit in case collators are empty
938
4635
            if collators.is_empty() {
939
2091
                return true;
940
2544
            }
941
2544
            with_storage_layer(|| {
942
2544
                Self::charge_para_ids_internal(
943
2544
                    blocks_per_session,
944
2544
                    para_id,
945
2544
                    current_assigned,
946
2544
                    maybe_tip,
947
2544
                )
948
2544
            })
949
2544
            .inspect(|weight| {
950
2544
                total_weight += *weight;
951
2544
            })
952
2544
            .is_ok()
953
5251
        });
954
3331
        total_weight
955
3331
    }
956

            
957
    /// Make those para ids valid by giving them enough credits, for benchmarking.
958
    #[cfg(feature = "runtime-benchmarks")]
959
    fn make_valid_para_ids(para_ids: &[ParaId]) {
960
        use frame_support::assert_ok;
961

            
962
        let blocks_per_session = Period::get();
963
        // Enough credits to run any benchmark
964
        let block_credits = 20 * blocks_per_session;
965
        let session_credits = 20;
966

            
967
        for para_id in para_ids {
968
            assert_ok!(ServicesPayment::set_block_production_credits(
969
                RuntimeOrigin::root(),
970
                *para_id,
971
                block_credits,
972
            ));
973
            assert_ok!(ServicesPayment::set_collator_assignment_credits(
974
                RuntimeOrigin::root(),
975
                *para_id,
976
                session_credits,
977
            ));
978
        }
979
    }
980
}
981

            
982
impl pallet_collator_assignment::Config for Runtime {
983
    type RuntimeEvent = RuntimeEvent;
984
    type HostConfiguration = Configuration;
985
    type ContainerChains = Registrar;
986
    type SessionIndex = u32;
987
    type SelfParaId = ParachainInfo;
988
    type ShouldRotateAllCollators =
989
        RotateCollatorsEveryNSessions<ConfigurationCollatorRotationSessionPeriod>;
990
    type GetRandomnessForNextBlock = BabeGetRandomnessForNextBlock;
991
    type RemoveInvulnerables = RemoveInvulnerablesImpl;
992
    type ParaIdAssignmentHooks = ParaIdAssignmentHooksImpl;
993
    type CollatorAssignmentTip = ServicesPayment;
994
    type Currency = Balances;
995
    type ForceEmptyOrchestrator = ConstBool<false>;
996
    type CoreAllocationConfiguration = ();
997
    type WeightInfo = weights::pallet_collator_assignment::SubstrateWeight<Runtime>;
998
}
999

            
impl pallet_authority_assignment::Config for Runtime {
    type SessionIndex = u32;
    type AuthorityId = NimbusId;
}
pub const FIXED_BLOCK_PRODUCTION_COST: u128 = 1 * currency::MICRODANCE;
pub const FIXED_COLLATOR_ASSIGNMENT_COST: u128 = 100 * currency::MICRODANCE;
pub struct BlockProductionCost<Runtime>(PhantomData<Runtime>);
impl ProvideBlockProductionCost<Runtime> for BlockProductionCost<Runtime> {
7751
    fn block_cost(_para_id: &ParaId) -> (u128, Weight) {
7751
        (FIXED_BLOCK_PRODUCTION_COST, Weight::zero())
7751
    }
}
pub struct CollatorAssignmentCost<Runtime>(PhantomData<Runtime>);
impl ProvideCollatorAssignmentCost<Runtime> for CollatorAssignmentCost<Runtime> {
229
    fn collator_assignment_cost(_para_id: &ParaId) -> (u128, Weight) {
229
        (FIXED_COLLATOR_ASSIGNMENT_COST, Weight::zero())
229
    }
}
parameter_types! {
    // 60 days worth of blocks
    pub const FreeBlockProductionCredits: BlockNumber = 60 * DAYS;
    // 60 days worth of blocks
    pub const FreeCollatorAssignmentCredits: u32 = FreeBlockProductionCredits::get()/Period::get();
}
impl pallet_services_payment::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    /// Handler for fees
    type OnChargeForBlock = ();
    type OnChargeForCollatorAssignment = ();
    type OnChargeForCollatorAssignmentTip = ();
    /// Currency type for fee payment
    type Currency = Balances;
    /// Provider of a block cost which can adjust from block to block
    type ProvideBlockProductionCost = BlockProductionCost<Runtime>;
    /// Provider of a block cost which can adjust from block to block
    type ProvideCollatorAssignmentCost = CollatorAssignmentCost<Runtime>;
    /// The maximum number of block credits that can be accumulated
    type FreeBlockProductionCredits = FreeBlockProductionCredits;
    /// The maximum number of session credits that can be accumulated
    type FreeCollatorAssignmentCredits = FreeCollatorAssignmentCredits;
    type ManagerOrigin =
        EitherOfDiverse<pallet_registrar::EnsureSignedByManager<Runtime>, EnsureRoot<AccountId>>;
    type WeightInfo = weights::pallet_services_payment::SubstrateWeight<Runtime>;
}
parameter_types! {
    pub const ProfileDepositBaseFee: Balance = currency::STORAGE_ITEM_FEE;
    pub const ProfileDepositByteFee: Balance = currency::STORAGE_BYTE_FEE;
    #[derive(Clone)]
    pub const MaxAssignmentsPerParaId: u32 = 10;
    #[derive(Clone)]
    pub const MaxNodeUrlLen: u32 = 200;
}
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 AssignmentProcessor = tp_data_preservers_common::AssignmentProcessor<Runtime>;
    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 = CollatorAssignment;
    type SlotBeacon = dp_consensus::AuraDigestSlotBeacon<Runtime>;
    type ContainerChainAuthor = CollatorAssignment;
    type AuthorNotingHook = (
        XcmCoreBuyer,
        InflationRewards,
        ServicesPayment,
        InactivityTracking,
    );
    type RelayOrPara = pallet_author_noting::ParaMode<
        cumulus_pallet_parachain_system::RelaychainDataProvider<Self>,
    >;
    type MaxContainerChains = MaxLengthParaIds;
    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.
54307
    fn session_index() -> u32 {
54307
        Session::current_index()
54307
    }
    #[cfg(feature = "runtime-benchmarks")]
    fn skip_to_session(session_index: SessionIndex) {
        while Session::current_index() < session_index {
            Session::rotate_session();
        }
    }
}
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 {
153
    fn para_marked_valid_for_collating(para_id: ParaId) -> Weight {
153
        // Give free credits but only once per para id
153
        ServicesPayment::give_free_credits(&para_id)
153
    }
72
    fn para_deregistered(para_id: ParaId) -> Weight {
        // Clear pallet_author_noting storage
72
        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,
            );
72
        }
        // Remove bootnodes from pallet_data_preservers
72
        DataPreservers::para_deregistered(para_id);
72

            
72
        ServicesPayment::para_deregistered(para_id);
72

            
72
        XcmCoreBuyer::para_deregistered(para_id);
72

            
72
        Weight::default()
72
    }
154
    fn check_valid_for_collating(para_id: ParaId) -> DispatchResult {
154
        // To be able to call mark_valid_for_collating, a container chain must have bootnodes
154
        DataPreservers::check_valid_for_collating(para_id)
154
    }
    #[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: tp_data_preservers_common::ProviderRequest::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,
            tp_data_preservers_common::AssignerExtra::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,
        );
    }
}
impl pallet_registrar::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type RegistrarOrigin =
        EitherOfDiverse<pallet_registrar::EnsureSignedByManager<Runtime>, 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 RegistrarHooks = DanceboxRegistrarHooks;
    type RuntimeHoldReason = RuntimeHoldReason;
    type InnerRegistrar = ();
    type WeightInfo = weights::pallet_registrar::SubstrateWeight<Runtime>;
    type DataDepositPerByte = DataDepositPerByte;
}
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;
}
parameter_types! {
    pub MbmServiceWeight: Weight = Perbill::from_percent(80) * RuntimeBlockWeights::get().max_block;
}
impl pallet_multiblock_migrations::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    #[cfg(not(feature = "runtime-benchmarks"))]
    type Migrations = (
        pallet_identity::migration::v2::LazyMigrationV1ToV2<Runtime>,
        pallet_pooled_staking::migrations::MigrationGenerateSummaries<Runtime>,
    );
    // Benchmarks need mocked migrations to guarantee that they succeed.
    #[cfg(feature = "runtime-benchmarks")]
    type Migrations = pallet_multiblock_migrations::mock_helpers::MockedMigrations;
    type CursorMaxLen = ConstU32<65_536>;
    type IdentifierMaxLen = ConstU32<256>;
    type MigrationStatusHandler = ();
    type FailedMigrationHandler = frame_support::migrations::FreezeChainOnFailedMigration;
    type MaxServiceWeight = MbmServiceWeight;
    type WeightInfo = weights::pallet_multiblock_migrations::SubstrateWeight<Runtime>;
}
/// 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 {
95670
    fn contains(_c: &RuntimeCall) -> bool {
95670
        true
95670
    }
}
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<Delay>(PhantomData<Delay>);
impl<Delay> Timer for SessionTimer<Delay>
where
    Delay: Get<u32>,
{
    type Instant = u32;
243
    fn now() -> Self::Instant {
243
        Session::current_index()
243
    }
85
    fn is_elapsed(instant: &Self::Instant) -> bool {
85
        let delay = Delay::get();
85
        let Some(end) = instant.checked_add(delay) else {
            return false;
        };
85
        end <= Self::now()
85
    }
    #[cfg(feature = "runtime-benchmarks")]
    fn elapsed_instant() -> Self::Instant {
        let delay = Delay::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 {
139
    fn is_candidate_eligible(a: &AccountId) -> bool {
139
        <Session as ValidatorRegistration<AccountId>>::is_registered(a)
139
    }
    #[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 {
79693
    fn get_block_author() -> Option<AccountId32> {
79693
        // TODO: we should do a refactor here, and use either authority-mapping or collator-assignemnt
79693
        // we should also make sure we actually account for the weight of these
79693
        // although most of these should be cached as they are read every block
79693
        let slot = u64::from(<Runtime as pallet_author_inherent::Config>::SlotBeacon::slot());
79693
        let self_para_id = ParachainInfo::get();
79693
        CollatorAssignment::author_for_slot(slot.into(), self_para_id)
79693
    }
}
pub struct OnUnbalancedInflation;
impl frame_support::traits::OnUnbalanced<Credit<AccountId, Balances>> for OnUnbalancedInflation {
27035
    fn on_nonzero_unbalanced(credit: Credit<AccountId, Balances>) {
27035
        let _ = <Balances as Balanced<_>>::resolve(&ParachainBondAccount::get(), credit);
27035
    }
}
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>;
}
parameter_types! {
    // 1 entry, storing 253 bytes on-chain in the worst case
    pub const OpenStreamHoldAmount: Balance = currency::deposit(1, 253);
}
impl pallet_stream_payment::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type StreamId = StreamId;
    type TimeUnit = tp_stream_payment_common::TimeUnit;
    type Balance = Balance;
    type AssetId = tp_stream_payment_common::AssetId;
    type AssetsManager = tp_stream_payment_common::AssetsManager<Runtime>;
    type Currency = Balances;
    type OpenStreamHoldAmount = OpenStreamHoldAmount;
    type RuntimeHoldReason = RuntimeHoldReason;
    type TimeProvider = tp_stream_payment_common::TimeProvider<Runtime>;
    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 UsernameDeposit: Balance = currency::deposit(0, 32);
    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 UsernameDeposit = UsernameDeposit;
    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 UsernameGracePeriod = ConstU32<{ 30 * 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);
    pub const DataDepositPerByte: Balance = 1 * CENTS;
}
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 }>;
    type BlockNumberProvider = System;
    #[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>;
}
impl pallet_inactivity_tracking::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type CollatorId = CollatorId;
    type MaxInactiveSessions = ConstU32<5>;
    type MaxCollatorsPerSession = ConstU32<100>;
    type CurrentSessionIndex = CurrentSessionIndexGetter;
    type CurrentCollatorsFetcher = CollatorAssignment;
    type GetSelfChainBlockAuthor = GetSelfChainBlockAuthor;
    type WeightInfo = weights::pallet_inactivity_tracking::SubstrateWeight<Runtime>;
}
// Create the runtime by composing the FRAME pallets that were previously configured.
11142926
construct_runtime!(
1028839
    pub enum Runtime
1028839
    {
1028839
        // System support stuff.
1028839
        System: frame_system = 0,
1028839
        ParachainSystem: cumulus_pallet_parachain_system = 1,
1028839
        Timestamp: pallet_timestamp = 2,
1028839
        ParachainInfo: parachain_info = 3,
1028839
        Sudo: pallet_sudo = 4,
1028839
        Utility: pallet_utility = 5,
1028839
        Proxy: pallet_proxy = 6,
1028839
        Migrations: pallet_migrations = 7,
1028839
        MultiBlockMigrations: pallet_multiblock_migrations = 121,
1028839
        MaintenanceMode: pallet_maintenance_mode = 8,
1028839
        TxPause: pallet_tx_pause = 9,
1028839

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

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

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

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

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

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

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

            
1028839
        RootTesting: pallet_root_testing = 100,
1028839
        AsyncBacking: pallet_async_backing::{Pallet, Storage} = 110,
1028839
    }
11533995
);
#[cfg(feature = "runtime-benchmarks")]
mod benches {
    frame_benchmarking::define_benchmarks!(
        [frame_system, frame_system_benchmarking::Pallet::<Runtime>]
        [frame_system_extensions, frame_system_benchmarking::extensions::Pallet::<Runtime>]
        [cumulus_pallet_parachain_system, ParachainSystem]
        [pallet_timestamp, Timestamp]
        [pallet_sudo, Sudo]
        [pallet_utility, Utility]
        [pallet_proxy, Proxy]
        [pallet_transaction_payment, TransactionPayment]
        [pallet_tx_pause, TxPause]
        [pallet_balances, Balances]
        [pallet_stream_payment, StreamPayment]
        [pallet_identity, Identity]
        [pallet_multiblock_migrations, MultiBlockMigrations]
        [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_inactivity_tracking, InactivityTracking]
        [pallet_treasury, Treasury]
        [cumulus_pallet_xcmp_queue, XcmpQueue]
        // XCM
        [pallet_xcm, PalletXcmExtrinsicsBenchmark::<Runtime>]
        [pallet_xcm_benchmarks::fungible, pallet_xcm_benchmarks::fungible::Pallet::<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]
    );
}
27117
pub fn get_para_id_authorities(para_id: ParaId) -> Option<Vec<NimbusId>> {
27117
    let parent_number = System::block_number();
27117

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

            
27117
    if para_id == self_para_id {
27043
        Some(assigned_authorities.orchestrator_chain)
    } else {
74
        assigned_authorities.container_chains.get(&para_id).cloned()
    }
27117
}
395466
impl_runtime_apis! {
51102
    impl sp_consensus_aura::AuraApi<Block, NimbusId> for Runtime {
66630
        fn slot_duration() -> sp_consensus_aura::SlotDuration {
23904
            sp_consensus_aura::SlotDuration::from_millis(SLOT_DURATION)
23904
        }
51102

            
51102
        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);
51102

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

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

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

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

            
66266
        fn initialize_block(header: &<Block as BlockT>::Header) -> sp_runtime::ExtrinsicInclusionMode {
23358
            Executive::initialize_block(header)
23358
        }
51102
    }
51102

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

            
51102
        fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
522
            Runtime::metadata_at_version(version)
522
        }
51102

            
51102
        fn metadata_versions() -> Vec<u32> {
522
            Runtime::metadata_versions()
522
        }
51102
    }
51102

            
51102
    impl sp_block_builder::BlockBuilder<Block> for Runtime {
114718
        fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
96036
            Executive::apply_extrinsic(extrinsic)
96036
        }
51102

            
66266
        fn finalize_block() -> <Block as BlockT>::Header {
23358
            Executive::finalize_block()
23358
        }
51102

            
66266
        fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
23358
            data.create_extrinsics()
23358
        }
51102

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

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

            
51102
    impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
66266
        fn offchain_worker(header: &<Block as BlockT>::Header) {
23358
            Executive::offchain_worker(header)
23358
        }
51102
    }
51102

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
51102
            use xcm::latest::prelude::*;
51102
            use crate::xcm_config::SelfReserve;
51102

            
51102
            parameter_types! {
51102
                pub ExistentialDepositAsset: Option<Asset> = Some((
51102
                    SelfReserve::get(),
51102
                    ExistentialDeposit::get()
51102
                ).into());
51102
                pub TrustedReserve: Option<(Location, Asset)> = Some(
51102
                    (
51102
                        Location::parent(),
51102
                        Asset {
51102
                            id: AssetId(Location::parent()),
51102
                            fun: Fungible(ExistentialDeposit::get() * 100),
51102
                        },
51102
                    )
51102
                );
51102
            }
51102

            
51102
            impl pallet_xcm_benchmarks::fungible::Config for Runtime {
51102
                type TransactAsset = Balances;
51102
                type CheckedAccount = ();
51102
                type TrustedTeleporter = ();
51102
                type TrustedReserve = TrustedReserve;
51102

            
51102
                fn get_asset() -> Asset {
51102
                    Asset {
51102
                        id: AssetId(SelfReserve::get()),
51102
                        fun: Fungible(ExistentialDeposit::get() * 100),
51102
                    }
51102
                }
51102
            }
51102

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
51102
            add_benchmarks!(params, batches);
51102

            
51102
            Ok(batches)
51102
        }
51102
    }
51102

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

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

            
51102
    impl pallet_collator_assignment_runtime_api::CollatorAssignmentApi<Block, AccountId, ParaId> for Runtime {
51102
        /// Return the parachain that the given `AccountId` is collating for.
51102
        /// Returns `None` if the `AccountId` is not collating.
51110
        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
        }
51102

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

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

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

            
51108
        }
51102

            
51102
        /// Return the list of collators of the given `ParaId`.
51102
        /// Returns `None` if the `ParaId` is not in the registrar.
51116
        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 {
51111
                Some(assigned_collators.orchestrator_chain)
51102
            } else {
51107
                assigned_collators.container_chains.get(&para_id).cloned()
51102
            }
51116
        }
51102

            
51102
        /// Returns the list of `ParaId` of registered chains with at least some
51102
        /// collators. This filters out parachains with no assigned collators.
51102
        /// Since runtime APIs are called on top of a parent block, we need to be carefull
51102
        /// at session boundaries. If the next block will change session, this function returns
51102
        /// the parachains relevant for the next session.
51102
        fn parachains_with_some_collators() -> Vec<ParaId> {
51102
            use tp_traits::{GetContainerChainsWithCollators, ForSession};
51102

            
51102
            // We should return the container-chains for the session in which we are kicking in
51102
            let parent_number = System::block_number();
            let should_end_session = <Runtime as pallet_session::Config>::ShouldEndSession::should_end_session(parent_number + 1);
51102
            let for_session = if should_end_session { ForSession::Next } else { ForSession::Current };
51102

            
51102
            CollatorAssignment::container_chains_with_collators(for_session)
                .into_iter()
                .filter_map(
                    |(para_id, collators)| (!collators.is_empty()).then_some(para_id)
                ).collect()
        }
51102
    }
51102

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

            
66271
            let session_index = if should_end_session {
52178
                Session::current_index() +1
51102
            }
51102
            else {
64787
                Session::current_index()
51102
            };
51102

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

            
23363
            para_ids
23363
        }
51102

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

            
51102
        /// Fetch boot_nodes for this para id
51102
        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()
        }
51102
    }
51102

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

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

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

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

            
51102
        /// Return the paraId assigned to a given authority
51134
        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);
51102

            
51134
            let session_index = if should_end_session {
51110
                Session::current_index() +1
51102
            }
51102
            else {
51126
                Session::current_index()
51102
            };
51134
            let assigned_authorities = AuthorityAssignment::collator_container_chain(session_index)?;
51134
            let self_para_id = ParachainInfo::get();
32

            
32
            assigned_authorities.para_id_of(&authority, self_para_id)
51134
        }
51102

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

            
12
            assigned_authorities.para_id_of(&authority, self_para_id)
51114
        }
51102
    }
51102

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

            
51102
        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
        }
51102

            
51102
        fn query_weight_to_fee(weight: Weight) -> Balance {
66
            TransactionPayment::weight_to_fee(weight)
66
        }
51102

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

            
51102
    impl pallet_stream_payment_runtime_api::StreamPaymentApi<Block, StreamId, Balance, Balance>
51102
    for Runtime {
51102
        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) {
51102
                Ok(pallet_stream_payment::StreamPaymentStatus {
51102
                    payment, deposit_left, stalled
42
                }) => Ok(StreamPaymentApiStatus {
42
                    payment, deposit_left, stalled
42
                }),
51102
                Err(pallet_stream_payment::Error::<Runtime>::UnknownStreamId)
51102
                => Err(StreamPaymentApiError::UnknownStreamId),
51102
                Err(e) => Err(StreamPaymentApiError::Other(format!("{e:?}")))
51102
            }
51102
        }
51102
    }
51102

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

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

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

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

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

            
51102
    impl pallet_services_payment_runtime_api::ServicesPaymentApi<Block, Balance, ParaId> for Runtime {
51102
        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
        }
51102

            
51102
        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
        }
51102
    }
51102

            
51102
    impl pallet_xcm_core_buyer_runtime_api::XCMCoreBuyerApi<Block, BlockNumber, ParaId, NimbusId> for Runtime {
51102
        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))
        }
51102

            
51102
        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_bare(call);
            Box::new(unsigned_extrinsic)
        }
51102

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

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

            
51102
    impl xcm_runtime_apis::fees::XcmPaymentApi<Block> for Runtime {
51102
        fn query_acceptable_payment_assets(xcm_version: xcm::Version) -> Result<Vec<VersionedAssetId>, XcmPaymentApiError> {
51102
            if !matches!(xcm_version, 3..=5) {
51102
                return Err(XcmPaymentApiError::UnhandledXcmVersion);
51102
            }
6

            
6
            Ok([VersionedAssetId::V5(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::V5(location.into())
6
                        }).or_else(|| {
                            log::warn!("Asset `{}` is present in pallet_asset_rate but not in pallet_foreign_asset_creator", asset_id_u16);
51102
                            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);
51102
                }).ok())
6
                .collect())
51102
        }
51102

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

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

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

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

            
51102
    impl xcm_runtime_apis::dry_run::DryRunApi<Block, RuntimeCall, RuntimeEvent, OriginCaller> for Runtime {
51102
        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
        }
51102

            
51102
        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
        }
51102
    }
51102

            
51102
    impl xcm_runtime_apis::conversions::LocationToAccountApi<Block, AccountId> for Runtime {
51102
        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
        }
51102
    }
395466
}
#[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
        }
    };
}