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
#[cfg(feature = "std")]
28
use sp_version::NativeVersion;
29
use {
30
    frame_support::{
31
        storage::{with_storage_layer, with_transaction},
32
        traits::{ExistenceRequirement, WithdrawReasons},
33
    },
34
    pallet_services_payment::ProvideCollatorAssignmentCost,
35
    parity_scale_codec::DecodeWithMemTracking,
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
pub mod genesis_config_presets;
46

            
47
#[cfg(test)]
48
mod tests;
49

            
50
use {
51
    alloc::string::ToString,
52
    alloc::{
53
        collections::{btree_map::BTreeMap, btree_set::BTreeSet},
54
        vec,
55
        vec::Vec,
56
    },
57
    core::marker::PhantomData,
58
    cumulus_pallet_parachain_system::RelayNumberMonotonicallyIncreases,
59
    cumulus_primitives_core::{relay_chain::SessionIndex, BodyId, ParaId},
60
    frame_support::{
61
        construct_runtime,
62
        dispatch::DispatchClass,
63
        genesis_builder_helper::{build_state, get_preset},
64
        pallet_prelude::DispatchResult,
65
        parameter_types,
66
        traits::{
67
            fungible::{Balanced, Credit, Inspect},
68
            tokens::{PayFromAccount, UnityAssetBalanceConversion},
69
            ConstBool, ConstU128, ConstU32, ConstU64, ConstU8, Contains, EitherOfDiverse,
70
            EverythingBut, InsideBoth, InstanceFilter, OnUnbalanced,
71
        },
72
        weights::{
73
            constants::{
74
                BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight,
75
                WEIGHT_REF_TIME_PER_SECOND,
76
            },
77
            ConstantMultiplier, FeePolynomial, Weight, WeightToFeeCoefficient,
78
            WeightToFeeCoefficients, WeightToFeePolynomial,
79
        },
80
        PalletId,
81
    },
82
    frame_system::{
83
        limits::{BlockLength, BlockWeights},
84
        EnsureNever, EnsureRoot,
85
    },
86
    nimbus_primitives::{NimbusId, SlotBeacon},
87
    pallet_invulnerables::InvulnerableRewardDistribution,
88
    pallet_registrar::RegistrarHooks,
89
    pallet_registrar_runtime_api::ContainerChainGenesisData,
90
    pallet_services_payment::{BalanceOf, ProvideBlockProductionCost},
91
    pallet_session::{SessionManager, ShouldEndSession},
92
    pallet_stream_payment_runtime_api::{StreamPaymentApiError, StreamPaymentApiStatus},
93
    pallet_transaction_payment::FungibleAdapter,
94
    polkadot_runtime_common::BlockHashCount,
95
    scale_info::prelude::format,
96
    smallvec::smallvec,
97
    sp_api::impl_runtime_apis,
98
    sp_consensus_slots::{Slot, SlotDuration},
99
    sp_core::{crypto::KeyTypeId, Get, MaxEncodedLen, OpaqueMetadata, H256},
100
    sp_runtime::{
101
        generic, impl_opaque_keys,
102
        traits::{
103
            AccountIdConversion, AccountIdLookup, BlakeTwo256, Block as BlockT, ConvertInto,
104
            IdentityLookup, Verify,
105
        },
106
        transaction_validity::{TransactionSource, TransactionValidity},
107
        AccountId32, ApplyExtrinsicResult, Cow,
108
    },
109
    sp_version::RuntimeVersion,
110
    tp_stream_payment_common::StreamId,
111
    tp_traits::{
112
        apply, derive_storage_traits, GetContainerChainAuthor, GetHostConfiguration,
113
        GetSessionContainerChains, MaybeSelfChainBlockAuthor, ParaIdAssignmentHooks,
114
        RelayStorageRootProvider, RemoveInvulnerables, ShouldRotateAllCollators,
115
    },
116
};
117
pub use {
118
    dp_core::{AccountId, Address, Balance, BlockNumber, Hash, Header, Index, Signature},
119
    sp_runtime::{MultiAddress, Perbill, Permill},
120
};
121

            
122
/// Block type as expected by this runtime.
123
pub type Block = generic::Block<Header, UncheckedExtrinsic>;
124
/// A Block signed with a Justification
125
pub type SignedBlock = generic::SignedBlock<Block>;
126
/// BlockId type as expected by this runtime.
127
pub type BlockId = generic::BlockId<Block>;
128

            
129
/// CollatorId type expected by this runtime.
130
pub type CollatorId = AccountId;
131

            
132
/// The `TxExtension` to the basic transaction logic.
133
pub type TxExtension = cumulus_pallet_weight_reclaim::StorageWeightReclaim<
134
    Runtime,
135
    (
136
        frame_system::CheckNonZeroSender<Runtime>,
137
        frame_system::CheckSpecVersion<Runtime>,
138
        frame_system::CheckTxVersion<Runtime>,
139
        frame_system::CheckGenesis<Runtime>,
140
        frame_system::CheckEra<Runtime>,
141
        frame_system::CheckNonce<Runtime>,
142
        frame_system::CheckWeight<Runtime>,
143
        pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
144
        frame_metadata_hash_extension::CheckMetadataHash<Runtime>,
145
    ),
146
>;
147

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

            
152
/// Extrinsic type that has already been checked.
153
pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, RuntimeCall, TxExtension>;
154

            
155
/// The runtime migrations per release.
156
pub mod migrations {
157
    /// Unreleased migrations. Add new ones here:
158
    pub type Unreleased = ();
159
}
160

            
161
/// Executive: handles dispatch to the various modules.
162
pub type Executive = frame_executive::Executive<
163
    Runtime,
164
    Block,
165
    frame_system::ChainContext<Runtime>,
166
    Runtime,
167
    AllPalletsWithSystem,
168
    migrations::Unreleased,
169
>;
170

            
171
/// DANCE, the native token, uses 12 decimals of precision.
172
pub mod currency {
173
    use super::Balance;
174

            
175
    // Provide a common factor between runtimes based on a supply of 10_000_000 tokens.
176
    pub const SUPPLY_FACTOR: Balance = 100;
177

            
178
    pub const MICRODANCE: Balance = 1_000_000;
179
    pub const MILLIDANCE: Balance = 1_000_000_000;
180
    pub const DANCE: Balance = 1_000_000_000_000;
181
    pub const KILODANCE: Balance = 1_000_000_000_000_000;
182

            
183
    pub const STORAGE_BYTE_FEE: Balance = 100 * MICRODANCE * SUPPLY_FACTOR;
184
    pub const STORAGE_ITEM_FEE: Balance = 100 * MILLIDANCE * SUPPLY_FACTOR;
185

            
186
2
    pub const fn deposit(items: u32, bytes: u32) -> Balance {
187
2
        items as Balance * STORAGE_ITEM_FEE + (bytes as Balance) * STORAGE_BYTE_FEE
188
2
    }
189
}
190

            
191
/// Handles converting a weight scalar to a fee value, based on the scale and granularity of the
192
/// node's balance type.
193
///
194
/// This should typically create a mapping between the following ranges:
195
///   - `[0, MAXIMUM_BLOCK_WEIGHT]`
196
///   - `[Balance::min, Balance::max]`
197
///
198
/// Yet, it can be used for any other sort of change to weight-fee. Some examples being:
199
///   - Setting it to `0` will essentially disable the weight fee.
200
///   - Setting it to `1` will cause the literal `#[weight = x]` values to be charged.
201
pub struct WeightToFee;
202
impl frame_support::weights::WeightToFee for WeightToFee {
203
    type Balance = Balance;
204

            
205
    fn weight_to_fee(weight: &Weight) -> Self::Balance {
206
        let time_poly: FeePolynomial<Balance> = RefTimeToFee::polynomial().into();
207
        let proof_poly: FeePolynomial<Balance> = ProofSizeToFee::polynomial().into();
208

            
209
        // Take the maximum instead of the sum to charge by the more scarce resource.
210
        time_poly
211
            .eval(weight.ref_time())
212
            .max(proof_poly.eval(weight.proof_size()))
213
    }
214
}
215
pub struct RefTimeToFee;
216
impl WeightToFeePolynomial for RefTimeToFee {
217
    type Balance = Balance;
218
    fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {
219
        // in Rococo, extrinsic base weight (smallest non-zero weight) is mapped to 1 MILLIUNIT:
220
        // in our template, we map to 1/10 of that, or 1/10 MILLIUNIT
221
        let p = MILLIUNIT / 10;
222
        let q = 100 * Balance::from(ExtrinsicBaseWeight::get().ref_time());
223
        smallvec![WeightToFeeCoefficient {
224
            degree: 1,
225
            negative: false,
226
            coeff_frac: Perbill::from_rational(p % q, q),
227
            coeff_integer: p / q,
228
        }]
229
    }
230
}
231

            
232
/// Maps the proof size component of `Weight` to a fee.
233
pub struct ProofSizeToFee;
234
impl WeightToFeePolynomial for ProofSizeToFee {
235
    type Balance = Balance;
236
    fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {
237
        // Map 10kb proof to 1 CENT.
238
        let p = MILLIUNIT / 10;
239
        let q = 10_000;
240

            
241
        smallvec![WeightToFeeCoefficient {
242
            degree: 1,
243
            negative: false,
244
            coeff_frac: Perbill::from_rational(p % q, q),
245
            coeff_integer: p / q,
246
        }]
247
    }
248
}
249

            
250
/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know
251
/// the specifics of the runtime. They can then be made to be agnostic over specific formats
252
/// of data like extrinsics, allowing for them to continue syncing the network through upgrades
253
/// to even the core data structures.
254
pub mod opaque {
255
    use {
256
        super::*,
257
        sp_runtime::{generic, traits::BlakeTwo256},
258
    };
259

            
260
    pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;
261
    /// Opaque block header type.
262
    pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
263
    /// Opaque block type.
264
    pub type Block = generic::Block<Header, UncheckedExtrinsic>;
265
    /// Opaque block identifier type.
266
    pub type BlockId = generic::BlockId<Block>;
267
}
268

            
269
impl_opaque_keys! {
270
    pub struct SessionKeys {
271
        pub nimbus: Initializer,
272
    }
273
}
274

            
275
#[sp_version::runtime_version]
276
pub const VERSION: RuntimeVersion = RuntimeVersion {
277
    spec_name: Cow::Borrowed("flashbox"),
278
    impl_name: Cow::Borrowed("flashbox"),
279
    authoring_version: 1,
280
    spec_version: 1700,
281
    impl_version: 0,
282
    apis: RUNTIME_API_VERSIONS,
283
    transaction_version: 1,
284
    system_version: 1,
285
};
286

            
287
/// This determines the average expected block time that we are targeting.
288
/// Blocks will be produced at a minimum duration defined by `SLOT_DURATION`.
289
/// `SLOT_DURATION` is picked up by `pallet_timestamp` which is in turn picked
290
/// up by `pallet_aura` to implement `fn slot_duration()`.
291
///
292
/// Change this to adjust the block time.
293
pub const MILLISECS_PER_BLOCK: u64 = 6000;
294

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

            
299
// Time is measured by number of blocks.
300
pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);
301
pub const HOURS: BlockNumber = MINUTES * 60;
302
pub const DAYS: BlockNumber = HOURS * 24;
303

            
304
// Unit = the base number of indivisible units for balances
305
pub const UNIT: Balance = 1_000_000_000_000;
306
pub const CENTS: Balance = UNIT / 30_000;
307
pub const MILLIUNIT: Balance = 1_000_000_000;
308
pub const MICROUNIT: Balance = 1_000_000;
309

            
310
/// The existential deposit. Set to 1/10 of the Connected Relay Chain.
311
pub const EXISTENTIAL_DEPOSIT: Balance = MILLIUNIT;
312

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

            
317
/// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used by
318
/// `Operational` extrinsics.
319
const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);
320

            
321
/// We allow for 2 seconds of compute with a 6 second average block time
322
const MAXIMUM_BLOCK_WEIGHT: Weight = Weight::from_parts(
323
    WEIGHT_REF_TIME_PER_SECOND.saturating_mul(2),
324
    cumulus_primitives_core::relay_chain::MAX_POV_SIZE as u64,
325
);
326

            
327
/// The version information used to identify this runtime when compiled natively.
328
#[cfg(feature = "std")]
329
pub fn native_version() -> NativeVersion {
330
    NativeVersion {
331
        runtime_version: VERSION,
332
        can_author_with: Default::default(),
333
    }
334
}
335

            
336
parameter_types! {
337
    pub const Version: RuntimeVersion = VERSION;
338

            
339
    // This part is copied from Substrate's `bin/node/runtime/src/lib.rs`.
340
    //  The `RuntimeBlockLength` and `RuntimeBlockWeights` exist here because the
341
    // `DeletionWeightLimit` and `DeletionQueueDepth` depend on those to parameterize
342
    // the lazy contract deletion.
343
    pub RuntimeBlockLength: BlockLength =
344
        BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);
345
    pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()
346
        .base_block(BlockExecutionWeight::get())
347
3276
        .for_class(DispatchClass::all(), |weights| {
348
3276
            weights.base_extrinsic = ExtrinsicBaseWeight::get();
349
3276
        })
350
1092
        .for_class(DispatchClass::Normal, |weights| {
351
1092
            weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);
352
1092
        })
353
1092
        .for_class(DispatchClass::Operational, |weights| {
354
1092
            weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);
355
            // Operational transactions have some extra reserved space, so that they
356
            // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.
357
1092
            weights.reserved = Some(
358
1092
                MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT
359
1092
            );
360
1092
        })
361
        .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)
362
        .build_or_panic();
363
    pub const SS58Prefix: u16 = 42;
364
}
365

            
366
// Configure FRAME pallets to include in runtime.
367

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

            
423
impl pallet_timestamp::Config for Runtime {
424
    /// A timestamp: milliseconds since the unix epoch.
425
    type Moment = u64;
426
    type OnTimestampSet = dp_consensus::OnTimestampSet<
427
        <Self as pallet_author_inherent::Config>::SlotBeacon,
428
        ConstU64<{ SLOT_DURATION }>,
429
    >;
430
    type MinimumPeriod = ConstU64<{ SLOT_DURATION / 2 }>;
431
    type WeightInfo = weights::pallet_timestamp::SubstrateWeight<Runtime>;
432
}
433

            
434
pub struct CanAuthor;
435
impl nimbus_primitives::CanAuthor<NimbusId> for CanAuthor {
436
1062
    fn can_author(author: &NimbusId, slot: &u32) -> bool {
437
1062
        let authorities = AuthorityAssignment::collator_container_chain(Session::current_index())
438
1062
            .expect("authorities should be set")
439
1062
            .orchestrator_chain;
440

            
441
1062
        if authorities.is_empty() {
442
            return false;
443
1062
        }
444

            
445
1062
        let author_index = (*slot as usize) % authorities.len();
446
1062
        let expected_author = &authorities[author_index];
447

            
448
1062
        expected_author == author
449
1062
    }
450
    #[cfg(feature = "runtime-benchmarks")]
451
    fn get_authors(_slot: &u32) -> Vec<NimbusId> {
452
        AuthorityAssignment::collator_container_chain(Session::current_index())
453
            .expect("authorities should be set")
454
            .orchestrator_chain
455
    }
456
}
457

            
458
impl pallet_author_inherent::Config for Runtime {
459
    type AuthorId = NimbusId;
460
    type AccountLookup = dp_consensus::NimbusLookUp;
461
    type CanAuthor = CanAuthor;
462
    type SlotBeacon = dp_consensus::AuraDigestSlotBeacon<Runtime>;
463
    type WeightInfo = weights::pallet_author_inherent::SubstrateWeight<Runtime>;
464
}
465

            
466
parameter_types! {
467
    pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT;
468
}
469

            
470
impl pallet_balances::Config for Runtime {
471
    type MaxLocks = ConstU32<50>;
472
    /// The type for recording an account's balance.
473
    type Balance = Balance;
474
    /// The ubiquitous event type.
475
    type RuntimeEvent = RuntimeEvent;
476
    type DustRemoval = ();
477
    type ExistentialDeposit = ExistentialDeposit;
478
    type AccountStore = System;
479
    type MaxReserves = ConstU32<50>;
480
    type ReserveIdentifier = [u8; 8];
481
    type FreezeIdentifier = RuntimeFreezeReason;
482
    type MaxFreezes = ConstU32<10>;
483
    type RuntimeHoldReason = RuntimeHoldReason;
484
    type RuntimeFreezeReason = RuntimeFreezeReason;
485
    type DoneSlashHandler = ();
486
    type WeightInfo = weights::pallet_balances::SubstrateWeight<Runtime>;
487
}
488

            
489
parameter_types! {
490
    pub const TransactionByteFee: Balance = 1;
491
}
492

            
493
impl pallet_transaction_payment::Config for Runtime {
494
    type RuntimeEvent = RuntimeEvent;
495
    type OnChargeTransaction =
496
        FungibleAdapter<Balances, tanssi_runtime_common::DealWithFees<Runtime>>;
497
    type OperationalFeeMultiplier = ConstU8<5>;
498
    type WeightToFee = WeightToFee;
499
    type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;
500
    type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Self>;
501
    type WeightInfo = weights::pallet_transaction_payment::SubstrateWeight<Runtime>;
502
}
503

            
504
pub const RELAY_CHAIN_SLOT_DURATION_MILLIS: u32 = 6000;
505
pub const UNINCLUDED_SEGMENT_CAPACITY: u32 = 3;
506
pub const BLOCK_PROCESSING_VELOCITY: u32 = 1;
507

            
508
type ConsensusHook = pallet_async_backing::consensus_hook::FixedVelocityConsensusHook<
509
    Runtime,
510
    BLOCK_PROCESSING_VELOCITY,
511
    UNINCLUDED_SEGMENT_CAPACITY,
512
>;
513

            
514
impl cumulus_pallet_parachain_system::Config for Runtime {
515
    type WeightInfo = weights::cumulus_pallet_parachain_system::SubstrateWeight<Runtime>;
516
    type RuntimeEvent = RuntimeEvent;
517
    type OnSystemEvent = ();
518
    type SelfParaId = parachain_info::Pallet<Runtime>;
519
    type OutboundXcmpMessageSource = ();
520
    // Ignore all DMP messages by enqueueing them into `()`:
521
    type DmpQueue = frame_support::traits::EnqueueWithOrigin<(), sp_core::ConstU8<0>>;
522
    type ReservedDmpWeight = ();
523
    type XcmpMessageHandler = ();
524
    type ReservedXcmpWeight = ();
525
    type CheckAssociatedRelayNumber = RelayNumberMonotonicallyIncreases;
526
    type ConsensusHook = ConsensusHook;
527
    type SelectCore = cumulus_pallet_parachain_system::DefaultCoreSelector<Runtime>;
528
    type RelayParentOffset = ConstU32<0>;
529
}
530

            
531
pub struct ParaSlotProvider;
532
impl Get<(Slot, SlotDuration)> for ParaSlotProvider {
533
73
    fn get() -> (Slot, SlotDuration) {
534
73
        let slot = u64::from(<Runtime as pallet_author_inherent::Config>::SlotBeacon::slot());
535
73
        (Slot::from(slot), SlotDuration::from_millis(SLOT_DURATION))
536
73
    }
537
}
538

            
539
parameter_types! {
540
    pub const ExpectedBlockTime: u64 = MILLISECS_PER_BLOCK;
541
}
542

            
543
impl pallet_async_backing::Config for Runtime {
544
    type AllowMultipleBlocksPerSlot = ConstBool<true>;
545
    type GetAndVerifySlot =
546
        pallet_async_backing::ParaSlot<RELAY_CHAIN_SLOT_DURATION_MILLIS, ParaSlotProvider>;
547
    type ExpectedBlockTime = ExpectedBlockTime;
548
}
549

            
550
pub struct OwnApplySession;
551
impl pallet_initializer::ApplyNewSession<Runtime> for OwnApplySession {
552
169
    fn apply_new_session(
553
169
        _changed: bool,
554
169
        session_index: u32,
555
169
        all_validators: Vec<(AccountId, NimbusId)>,
556
169
        queued: Vec<(AccountId, NimbusId)>,
557
169
    ) {
558
        // We first initialize Configuration
559
169
        Configuration::initializer_on_new_session(&session_index);
560
        // Next: Registrar
561
169
        Registrar::initializer_on_new_session(&session_index);
562
        // Next: AuthorityMapping
563
169
        AuthorityMapping::initializer_on_new_session(&session_index, &all_validators);
564

            
565
562
        let next_collators = queued.iter().map(|(k, _)| k.clone()).collect();
566

            
567
        // Next: CollatorAssignment
568
169
        let assignments =
569
169
            CollatorAssignment::initializer_on_new_session(&session_index, next_collators);
570

            
571
169
        let queued_id_to_nimbus_map = queued.iter().cloned().collect();
572
169
        AuthorityAssignment::initializer_on_new_session(
573
169
            &session_index,
574
169
            &queued_id_to_nimbus_map,
575
169
            &assignments.next_assignment,
576
        );
577
169
    }
578
95
    fn on_before_session_ending() {}
579
}
580

            
581
impl pallet_initializer::Config for Runtime {
582
    type SessionIndex = u32;
583

            
584
    /// The identifier type for an authority.
585
    type AuthorityId = NimbusId;
586

            
587
    type SessionHandler = OwnApplySession;
588
}
589

            
590
impl parachain_info::Config for Runtime {}
591

            
592
pub struct CollatorsFromInvulnerables;
593

            
594
/// Play the role of the session manager.
595
impl SessionManager<CollatorId> for CollatorsFromInvulnerables {
596
243
    fn new_session(index: SessionIndex) -> Option<Vec<CollatorId>> {
597
243
        log::info!(
598
            "assembling new collators for new session {} at #{:?}",
599
            index,
600
            <frame_system::Pallet<Runtime>>::block_number(),
601
        );
602

            
603
243
        let invulnerables = Invulnerables::invulnerables().to_vec();
604
243
        let target_session_index = index.saturating_add(1);
605
243
        let max_collators =
606
243
            <Configuration as GetHostConfiguration<u32>>::max_collators(target_session_index);
607
243
        let collators = invulnerables
608
243
            .iter()
609
243
            .take(max_collators as usize)
610
243
            .cloned()
611
243
            .collect();
612

            
613
243
        Some(collators)
614
243
    }
615
169
    fn start_session(_: SessionIndex) {
616
        // we don't care.
617
169
    }
618
95
    fn end_session(_: SessionIndex) {
619
        // we don't care.
620
95
    }
621
}
622

            
623
parameter_types! {
624
    pub const Period: u32 = prod_or_fast!(5 * MINUTES, 1 * MINUTES);
625
    pub const Offset: u32 = 0;
626
}
627

            
628
impl pallet_session::Config for Runtime {
629
    type RuntimeEvent = RuntimeEvent;
630
    type ValidatorId = <Self as frame_system::Config>::AccountId;
631
    // we don't have stash and controller, thus we don't need the convert as well.
632
    type ValidatorIdOf = ConvertInto;
633
    type ShouldEndSession = pallet_session::PeriodicSessions<Period, Offset>;
634
    type NextSessionRotation = pallet_session::PeriodicSessions<Period, Offset>;
635
    type SessionManager = CollatorsFromInvulnerables;
636
    // Essentially just Aura, but let's be pedantic.
637
    type SessionHandler = <SessionKeys as sp_runtime::traits::OpaqueKeys>::KeyTypeIdProviders;
638
    type Keys = SessionKeys;
639
    type WeightInfo = weights::pallet_session::SubstrateWeight<Runtime>;
640
    type DisablingStrategy = ();
641
}
642

            
643
pub struct RemoveInvulnerablesImpl;
644

            
645
impl RemoveInvulnerables<CollatorId> for RemoveInvulnerablesImpl {
646
250
    fn remove_invulnerables(
647
250
        collators: &mut Vec<CollatorId>,
648
250
        num_invulnerables: usize,
649
250
    ) -> Vec<CollatorId> {
650
250
        if num_invulnerables == 0 {
651
            return vec![];
652
250
        }
653
250
        let all_invulnerables = pallet_invulnerables::Invulnerables::<Runtime>::get();
654
250
        if all_invulnerables.is_empty() {
655
            return vec![];
656
250
        }
657
250
        let mut invulnerables = vec![];
658
        // TODO: use binary_search when invulnerables are sorted
659
404
        collators.retain(|x| {
660
404
            if invulnerables.len() < num_invulnerables && all_invulnerables.contains(x) {
661
317
                invulnerables.push(x.clone());
662
317
                false
663
            } else {
664
87
                true
665
            }
666
404
        });
667

            
668
250
        invulnerables
669
250
    }
670
}
671

            
672
pub struct ParaIdAssignmentHooksImpl;
673

            
674
impl ParaIdAssignmentHooksImpl {
675
279
    fn charge_para_ids_internal(
676
279
        blocks_per_session: tp_traits::BlockNumber,
677
279
        para_id: ParaId,
678
279
        currently_assigned: &BTreeSet<ParaId>,
679
279
        maybe_tip: &Option<BalanceOf<Runtime>>,
680
279
    ) -> Result<Weight, DispatchError> {
681
        use frame_support::traits::Currency;
682
        type ServicePaymentCurrency = <Runtime as pallet_services_payment::Config>::Currency;
683

            
684
        // Check if the container chain has enough credits for a session assignments
685
272
        let maybe_assignment_imbalance =
686
279
            if  pallet_services_payment::Pallet::<Runtime>::burn_collator_assignment_free_credit_for_para(&para_id).is_err() {
687
15
                let (amount_to_charge, _weight) =
688
15
                    <Runtime as pallet_services_payment::Config>::ProvideCollatorAssignmentCost::collator_assignment_cost(&para_id);
689
15
                Some(<ServicePaymentCurrency as Currency<AccountId>>::withdraw(
690
15
                    &pallet_services_payment::Pallet::<Runtime>::parachain_tank(para_id),
691
15
                    amount_to_charge,
692
                    WithdrawReasons::FEE,
693
15
                    ExistenceRequirement::KeepAlive,
694
7
                )?)
695
            } else {
696
264
                None
697
            };
698

            
699
272
        if let Some(tip) = maybe_tip {
700
200
            if let Err(e) = pallet_services_payment::Pallet::<Runtime>::charge_tip(&para_id, tip) {
701
                // Return assignment imbalance to tank on error
702
1
                if let Some(assignment_imbalance) = maybe_assignment_imbalance {
703
                    <Runtime as pallet_services_payment::Config>::Currency::resolve_creating(
704
                        &pallet_services_payment::Pallet::<Runtime>::parachain_tank(para_id),
705
                        assignment_imbalance,
706
                    );
707
1
                }
708
1
                return Err(e);
709
199
            }
710
72
        }
711

            
712
271
        if let Some(assignment_imbalance) = maybe_assignment_imbalance {
713
8
            <Runtime as pallet_services_payment::Config>::OnChargeForCollatorAssignment::on_unbalanced(assignment_imbalance);
714
263
        }
715

            
716
        // If the para has been assigned collators for this session it must have enough block credits
717
        // for the current and the next session.
718
271
        let block_credits_needed = if currently_assigned.contains(&para_id) {
719
146
            blocks_per_session * 2
720
        } else {
721
125
            blocks_per_session
722
        };
723
        // Check if the container chain has enough credits for producing blocks
724
271
        let free_block_credits =
725
271
            pallet_services_payment::BlockProductionCredits::<Runtime>::get(para_id)
726
271
                .unwrap_or_default();
727
271
        let remaining_block_credits = block_credits_needed.saturating_sub(free_block_credits);
728
271
        let (block_production_costs, _) =
729
271
            <Runtime as pallet_services_payment::Config>::ProvideBlockProductionCost::block_cost(
730
271
                &para_id,
731
271
            );
732
        // Check if we can withdraw
733
271
        let remaining_block_credits_to_pay =
734
271
            u128::from(remaining_block_credits).saturating_mul(block_production_costs);
735
271
        let remaining_to_pay = remaining_block_credits_to_pay;
736
        // This should take into account whether we tank goes below ED
737
        // The true refers to keepAlive
738
271
        Balances::can_withdraw(
739
271
            &pallet_services_payment::Pallet::<Runtime>::parachain_tank(para_id),
740
271
            remaining_to_pay,
741
        )
742
271
        .into_result(true)?;
743
        // TODO: Have proper weight
744
257
        Ok(Weight::zero())
745
279
    }
746
}
747

            
748
impl<AC> ParaIdAssignmentHooks<BalanceOf<Runtime>, AC> for ParaIdAssignmentHooksImpl {
749
338
    fn pre_assignment(para_ids: &mut Vec<ParaId>, currently_assigned: &BTreeSet<ParaId>) {
750
338
        let blocks_per_session = Period::get();
751
338
        para_ids.retain(|para_id| {
752
197
            with_transaction(|| {
753
197
                let max_tip =
754
197
                    pallet_services_payment::MaxTip::<Runtime>::get(para_id).unwrap_or_default();
755
197
                TransactionOutcome::Rollback(Self::charge_para_ids_internal(
756
197
                    blocks_per_session,
757
197
                    *para_id,
758
197
                    currently_assigned,
759
197
                    &Some(max_tip),
760
197
                ))
761
197
            })
762
197
            .is_ok()
763
197
        });
764
338
    }
765

            
766
169
    fn post_assignment(
767
169
        current_assigned: &BTreeSet<ParaId>,
768
169
        new_assigned: &mut BTreeMap<ParaId, Vec<AC>>,
769
169
        maybe_tip: &Option<BalanceOf<Runtime>>,
770
169
    ) -> Weight {
771
169
        let blocks_per_session = Period::get();
772
169
        let mut total_weight = Weight::zero();
773
175
        new_assigned.retain(|&para_id, collators| {
774
            // Short-circuit in case collators are empty
775
175
            if collators.is_empty() {
776
93
                return true;
777
82
            }
778
82
            with_storage_layer(|| {
779
82
                Self::charge_para_ids_internal(
780
82
                    blocks_per_session,
781
82
                    para_id,
782
82
                    current_assigned,
783
82
                    maybe_tip,
784
                )
785
82
            })
786
82
            .inspect(|weight| {
787
82
                total_weight += *weight;
788
82
            })
789
82
            .is_ok()
790
175
        });
791
169
        total_weight
792
169
    }
793

            
794
    /// Make those para ids valid by giving them enough credits, for benchmarking.
795
    #[cfg(feature = "runtime-benchmarks")]
796
    fn make_valid_para_ids(para_ids: &[ParaId]) {
797
        use frame_support::assert_ok;
798

            
799
        let blocks_per_session = Period::get();
800
        // Enough credits to run any benchmark
801
        let block_credits = 20 * blocks_per_session;
802
        let session_credits = 20;
803

            
804
        for para_id in para_ids {
805
            assert_ok!(ServicesPayment::set_block_production_credits(
806
                RuntimeOrigin::root(),
807
                *para_id,
808
                block_credits,
809
            ));
810
            assert_ok!(ServicesPayment::set_collator_assignment_credits(
811
                RuntimeOrigin::root(),
812
                *para_id,
813
                session_credits,
814
            ));
815
        }
816
    }
817
}
818

            
819
pub struct NeverRotateCollators;
820

            
821
impl ShouldRotateAllCollators<u32> for NeverRotateCollators {
822
169
    fn should_rotate_all_collators(_: u32) -> bool {
823
169
        false
824
169
    }
825
}
826

            
827
impl pallet_collator_assignment::Config for Runtime {
828
    type HostConfiguration = Configuration;
829
    type ContainerChains = Registrar;
830
    type SessionIndex = u32;
831
    type SelfParaId = ParachainInfo;
832
    type ShouldRotateAllCollators = NeverRotateCollators;
833
    type Randomness = ();
834
    type RemoveInvulnerables = RemoveInvulnerablesImpl;
835
    type ParaIdAssignmentHooks = ParaIdAssignmentHooksImpl;
836
    type CollatorAssignmentTip = ServicesPayment;
837
    type Currency = Balances;
838
    type ForceEmptyOrchestrator = ConstBool<false>;
839
    type CoreAllocationConfiguration = ();
840
    type WeightInfo = weights::pallet_collator_assignment::SubstrateWeight<Runtime>;
841
}
842

            
843
impl pallet_authority_assignment::Config for Runtime {
844
    type SessionIndex = u32;
845
    type AuthorityId = NimbusId;
846
}
847

            
848
pub const FIXED_BLOCK_PRODUCTION_COST: u128 = 1 * currency::MICRODANCE;
849
pub const FIXED_COLLATOR_ASSIGNMENT_COST: u128 = 100 * currency::MICRODANCE;
850

            
851
pub struct BlockProductionCost<Runtime>(PhantomData<Runtime>);
852
impl ProvideBlockProductionCost<Runtime> for BlockProductionCost<Runtime> {
853
289
    fn block_cost(_para_id: &ParaId) -> (u128, Weight) {
854
289
        (FIXED_BLOCK_PRODUCTION_COST, Weight::zero())
855
289
    }
856
}
857

            
858
pub struct CollatorAssignmentCost<Runtime>(PhantomData<Runtime>);
859
impl ProvideCollatorAssignmentCost<Runtime> for CollatorAssignmentCost<Runtime> {
860
19
    fn collator_assignment_cost(_para_id: &ParaId) -> (u128, Weight) {
861
19
        (FIXED_COLLATOR_ASSIGNMENT_COST, Weight::zero())
862
19
    }
863
}
864

            
865
parameter_types! {
866
    // 60 days worth of blocks
867
    pub const FreeBlockProductionCredits: BlockNumber = 60 * DAYS;
868
    // 60 days worth of blocks
869
    pub const FreeCollatorAssignmentCredits: u32 = FreeBlockProductionCredits::get()/Period::get();
870
}
871

            
872
impl pallet_services_payment::Config for Runtime {
873
    /// Handler for fees
874
    type OnChargeForBlock = ();
875
    type OnChargeForCollatorAssignment = ();
876
    type OnChargeForCollatorAssignmentTip = ();
877
    /// Currency type for fee payment
878
    type Currency = Balances;
879
    /// Provider of a block cost which can adjust from block to block
880
    type ProvideBlockProductionCost = BlockProductionCost<Runtime>;
881
    /// Provider of a block cost which can adjust from block to block
882
    type ProvideCollatorAssignmentCost = CollatorAssignmentCost<Runtime>;
883
    /// The maximum number of block credits that can be accumulated
884
    type FreeBlockProductionCredits = FreeBlockProductionCredits;
885
    /// The maximum number of session credits that can be accumulated
886
    type FreeCollatorAssignmentCredits = FreeCollatorAssignmentCredits;
887
    type ManagerOrigin =
888
        EitherOfDiverse<pallet_registrar::EnsureSignedByManager<Runtime>, EnsureRoot<AccountId>>;
889
    type WeightInfo = weights::pallet_services_payment::SubstrateWeight<Runtime>;
890
}
891

            
892
parameter_types! {
893
    pub const ProfileDepositBaseFee: Balance = currency::STORAGE_ITEM_FEE;
894
    pub const ProfileDepositByteFee: Balance = currency::STORAGE_BYTE_FEE;
895
    #[derive(Clone)]
896
    pub const MaxAssignmentsPerParaId: u32 = 10;
897
    #[derive(Clone)]
898
    pub const MaxNodeUrlCount: u32 = 4;
899
    #[derive(Clone)]
900
    pub const MaxStringLen: u32 = 200;
901
}
902

            
903
pub type DataPreserversProfileId = u64;
904

            
905
impl pallet_data_preservers::Config for Runtime {
906
    type RuntimeHoldReason = RuntimeHoldReason;
907
    type Currency = Balances;
908
    type WeightInfo = weights::pallet_data_preservers::SubstrateWeight<Runtime>;
909

            
910
    type ProfileId = DataPreserversProfileId;
911
    type ProfileDeposit = tp_traits::BytesDeposit<ProfileDepositBaseFee, ProfileDepositByteFee>;
912
    type AssignmentProcessor = tp_data_preservers_common::AssignmentProcessor<Runtime>;
913

            
914
    type AssignmentOrigin = pallet_registrar::EnsureSignedByManager<Runtime>;
915
    type ForceSetProfileOrigin = EnsureRoot<AccountId>;
916

            
917
    type MaxAssignmentsPerParaId = MaxAssignmentsPerParaId;
918
    type MaxNodeUrlCount = MaxNodeUrlCount;
919
    type MaxStringLen = MaxStringLen;
920
    type MaxParaIdsVecLen = MaxLengthParaIds;
921
}
922

            
923
impl pallet_author_noting::Config for Runtime {
924
    type ContainerChains = CollatorAssignment;
925
    type SlotBeacon = dp_consensus::AuraDigestSlotBeacon<Runtime>;
926
    type ContainerChainAuthor = CollatorAssignment;
927
    type AuthorNotingHook = (InflationRewards, ServicesPayment);
928
    type RelayOrPara = pallet_author_noting::ParaMode<
929
        cumulus_pallet_parachain_system::RelaychainDataProvider<Self>,
930
    >;
931
    type MaxContainerChains = MaxLengthParaIds;
932
    type WeightInfo = weights::pallet_author_noting::SubstrateWeight<Runtime>;
933
}
934

            
935
parameter_types! {
936
    pub const PotId: PalletId = PalletId(*b"PotStake");
937
    pub const MaxCandidates: u32 = 1000;
938
    pub const MinCandidates: u32 = 5;
939
    pub const SessionLength: BlockNumber = 5;
940
    pub const MaxInvulnerables: u32 = 200;
941
    pub const ExecutiveBody: BodyId = BodyId::Executive;
942
}
943

            
944
impl pallet_invulnerables::Config for Runtime {
945
    type UpdateOrigin = EnsureRoot<AccountId>;
946
    type MaxInvulnerables = MaxInvulnerables;
947
    type CollatorId = CollatorId;
948
    type CollatorIdOf = ConvertInto;
949
    type CollatorRegistration = Session;
950
    type WeightInfo = weights::pallet_invulnerables::SubstrateWeight<Runtime>;
951
    #[cfg(feature = "runtime-benchmarks")]
952
    type Currency = Balances;
953
}
954

            
955
parameter_types! {
956
    #[derive(Clone)]
957
    pub const MaxLengthParaIds: u32 = 200u32;
958
    pub const MaxEncodedGenesisDataSize: u32 = 5_000_000u32; // 5MB
959
}
960

            
961
pub struct CurrentSessionIndexGetter;
962

            
963
impl tp_traits::GetSessionIndex<u32> for CurrentSessionIndexGetter {
964
    /// Returns current session index.
965
42
    fn session_index() -> u32 {
966
42
        Session::current_index()
967
42
    }
968

            
969
    #[cfg(feature = "runtime-benchmarks")]
970
    fn skip_to_session(_session_index: SessionIndex) {}
971
}
972

            
973
impl pallet_configuration::Config for Runtime {
974
    type SessionDelay = ConstU32<2>;
975
    type SessionIndex = u32;
976
    type CurrentSessionIndex = CurrentSessionIndexGetter;
977
    type ForceEmptyOrchestrator = ConstBool<false>;
978
    type WeightInfo = weights::pallet_configuration::SubstrateWeight<Runtime>;
979
}
980

            
981
pub struct FlashboxRegistrarHooks;
982

            
983
impl RegistrarHooks for FlashboxRegistrarHooks {
984
20
    fn para_marked_valid_for_collating(para_id: ParaId) -> Weight {
985
        // Give free credits but only once per para id
986
20
        ServicesPayment::give_free_credits(&para_id)
987
20
    }
988

            
989
6
    fn para_deregistered(para_id: ParaId) -> Weight {
990
        // Clear pallet_author_noting storage
991
6
        if let Err(e) = AuthorNoting::kill_author_data(RuntimeOrigin::root(), para_id) {
992
            log::warn!(
993
                "Failed to kill_author_data after para id {} deregistered: {:?}",
994
                u32::from(para_id),
995
                e,
996
            );
997
6
        }
998
        // Remove bootnodes from pallet_data_preservers
999
6
        DataPreservers::para_deregistered(para_id);
6
        ServicesPayment::para_deregistered(para_id);
6
        Weight::default()
6
    }
21
    fn check_valid_for_collating(para_id: ParaId) -> DispatchResult {
        // To be able to call mark_valid_for_collating, a container chain must have bootnodes
21
        DataPreservers::check_valid_for_collating(para_id)
21
    }
    #[cfg(feature = "runtime-benchmarks")]
    fn benchmarks_ensure_valid_for_collating(para_id: ParaId) {
        use {
            frame_support::traits::EnsureOriginWithArg,
            pallet_data_preservers::{NodeType, ParaIdsFilter, Profile},
        };
        let profile = Profile {
            bootnode_url: Some(b"/ip4/127.0.0.1/tcp/33049/ws/p2p/12D3KooWHVMhQDHBpj9vQmssgyfspYecgV6e3hH1dQVDUkUbCYC9"
                    .to_vec()
                    .try_into()
                    .expect("to fit in BoundedVec")) ,
            direct_rpc_urls: Default::default(),
            proxy_rpc_urls: Default::default(),
            para_ids: ParaIdsFilter::AnyParaId,
            node_type: NodeType::Substrate,
            assignment_request: tp_data_preservers_common::ProviderRequest::Free,
            additional_info: Default::default(),
        };
        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 {
    fn get_relay_storage_root(relay_block_number: u32) -> Option<H256> {
        pallet_relay_storage_roots::pallet::RelayStorageRoot::<Runtime>::get(relay_block_number)
    }
    #[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 RegistrarOrigin =
        EitherOfDiverse<pallet_registrar::EnsureSignedByManager<Runtime>, EnsureRoot<AccountId>>;
    type MarkValidForCollatingOrigin = EnsureRoot<AccountId>;
    type MaxLengthParaIds = MaxLengthParaIds;
    type MaxGenesisDataSize = MaxEncodedGenesisDataSize;
    type RegisterWithRelayProofOrigin = EnsureNever<AccountId>;
    type RelayStorageRootProvider = PalletRelayStorageRootProvider;
    type SessionDelay = ConstU32<2>;
    type SessionIndex = u32;
    type CurrentSessionIndex = CurrentSessionIndexGetter;
    type Currency = Balances;
    type RegistrarHooks = FlashboxRegistrarHooks;
    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 proxies allowed.
#[apply(derive_storage_traits)]
#[derive(Copy, Ord, PartialOrd, MaxEncodedLen, DecodeWithMemTracking)]
#[allow(clippy::unnecessary_cast)]
pub enum ProxyType {
    /// All calls can be proxied. This is the trivial/most permissive filter.
    Any = 0,
    /// Only extrinsics that do not transfer funds.
    NonTransfer = 1,
    /// Only extrinsics related to governance (democracy and collectives).
    Governance = 2,
    /// Only extrinsics related to staking.
    Staking = 3,
    /// Allow to veto an announced proxy call.
    CancelProxy = 4,
    /// Allow extrinsic related to Balances.
    Balances = 5,
    /// Allow extrinsics related to Registrar
    Registrar = 6,
    /// Allow extrinsics related to Registrar that needs to be called through Sudo
    SudoRegistrar = 7,
}
impl Default for ProxyType {
    fn default() -> Self {
        Self::Any
    }
}
impl InstanceFilter<RuntimeCall> for ProxyType {
9
    fn filter(&self, c: &RuntimeCall) -> bool {
        // Since proxy filters are respected in all dispatches of the Utility
        // pallet, it should never need to be filtered by any proxy.
9
        if let RuntimeCall::Utility(..) = c {
            return true;
9
        }
9
        match self {
1
            ProxyType::Any => true,
            ProxyType::NonTransfer => {
2
                matches!(
2
                    c,
                    RuntimeCall::System(..)
                        | RuntimeCall::ParachainSystem(..)
                        | RuntimeCall::Timestamp(..)
                        | RuntimeCall::Proxy(..)
                        | RuntimeCall::Registrar(..)
                )
            }
            // We don't have governance yet
1
            ProxyType::Governance => false,
1
            ProxyType::Staking => matches!(c, RuntimeCall::Session(..)),
1
            ProxyType::CancelProxy => matches!(
                c,
                RuntimeCall::Proxy(pallet_proxy::Call::reject_announcement { .. })
            ),
            ProxyType::Balances => {
1
                matches!(c, RuntimeCall::Balances(..))
            }
            ProxyType::Registrar => {
1
                matches!(
1
                    c,
                    RuntimeCall::Registrar(..) | RuntimeCall::DataPreservers(..)
                )
            }
1
            ProxyType::SudoRegistrar => match c {
1
                RuntimeCall::Sudo(pallet_sudo::Call::sudo { call: ref x }) => {
1
                    matches!(
1
                        x.as_ref(),
                        &RuntimeCall::Registrar(..) | &RuntimeCall::DataPreservers(..)
                    )
                }
                _ => false,
            },
        }
9
    }
    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>;
    type BlockNumberProvider = System;
}
impl pallet_migrations::Config for Runtime {
    type MigrationsList = (tanssi_runtime_common::migrations::FlashboxMigrations<Runtime>,);
    type 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 = ();
    // 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 = MaintenanceMode;
    type MaxServiceWeight = MbmServiceWeight;
    type WeightInfo = weights::pallet_multiblock_migrations::SubstrateWeight<Runtime>;
}
/// Maintenance mode Call filter
pub struct MaintenanceFilter;
impl Contains<RuntimeCall> for MaintenanceFilter {
    fn contains(c: &RuntimeCall) -> bool {
        !matches!(
            c,
            RuntimeCall::Balances(..)
                | RuntimeCall::Registrar(..)
                | RuntimeCall::Session(..)
                | RuntimeCall::System(..)
                | RuntimeCall::Utility(..)
        )
    }
}
/// We allow everything but registering parathreads
pub struct IsRegisterParathreads;
impl Contains<RuntimeCall> for IsRegisterParathreads {
91
    fn contains(c: &RuntimeCall) -> bool {
90
        matches!(
1
            c,
            RuntimeCall::Registrar(pallet_registrar::Call::register_parathread { .. })
        )
91
    }
}
type NormalFilter = EverythingBut<IsRegisterParathreads>;
impl pallet_maintenance_mode::Config for Runtime {
    type NormalCallFilter = NormalFilter;
    type MaintenanceCallFilter = InsideBoth<MaintenanceFilter, NormalFilter>;
    type MaintenanceOrigin = EnsureRoot<AccountId>;
    type 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;
}
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: 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 {
2124
    fn get_block_author() -> Option<AccountId32> {
        // TODO: we should do a refactor here, and use either authority-mapping or collator-assignemnt
        // we should also make sure we actually account for the weight of these
        // although most of these should be cached as they are read every block
2124
        let slot = u64::from(<Runtime as pallet_author_inherent::Config>::SlotBeacon::slot());
2124
        let self_para_id = ParachainInfo::get();
2124
        CollatorAssignment::author_for_slot(slot.into(), self_para_id)
2124
    }
}
pub struct OnUnbalancedInflation;
impl frame_support::traits::OnUnbalanced<Credit<AccountId, Balances>> for OnUnbalancedInflation {
1062
    fn on_nonzero_unbalanced(credit: Credit<AccountId, Balances>) {
1062
        let _ = <Balances as Balanced<_>>::resolve(&ParachainBondAccount::get(), credit);
1062
    }
}
impl pallet_inflation_rewards::Config for Runtime {
    type Currency = Balances;
    type ContainerChains = CollatorAssignment;
    type MaxContainerChains = MaxLengthParaIds;
    type GetSelfChainBlockAuthor = GetSelfChainBlockAuthor;
    type InflationRate = InflationRate;
    type OnUnbalanced = OnUnbalancedInflation;
    type PendingRewardsAccount = PendingRewardsAccount;
    type StakingRewardsDistributor = InvulnerableRewardDistribution<Self, Balances, ()>;
    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 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>;
    #[cfg(feature = "runtime-benchmarks")]
    type BenchmarkHelper = ();
    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;
    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>;
    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>;
    type BlockNumberProvider = System;
}
impl cumulus_pallet_weight_reclaim::Config for Runtime {
    type WeightInfo = weights::cumulus_pallet_weight_reclaim::SubstrateWeight<Runtime>;
}
// Create the runtime by composing the FRAME pallets that were previously configured.
construct_runtime!(
    pub enum Runtime
    {
        // System support stuff.
        System: frame_system = 0,
        ParachainSystem: cumulus_pallet_parachain_system = 1,
        Timestamp: pallet_timestamp = 2,
        ParachainInfo: parachain_info = 3,
        Sudo: pallet_sudo = 4,
        Utility: pallet_utility = 5,
        Proxy: pallet_proxy = 6,
        Migrations: pallet_migrations = 7,
        MultiBlockMigrations: pallet_multiblock_migrations = 121,
        MaintenanceMode: pallet_maintenance_mode = 8,
        TxPause: pallet_tx_pause = 9,
        // Monetary stuff.
        Balances: pallet_balances = 10,
        TransactionPayment: pallet_transaction_payment = 11,
        StreamPayment: pallet_stream_payment = 12,
        // Other utilities
        Identity: pallet_identity = 15,
        Multisig: pallet_multisig = 16,
        // ContainerChain management. It should go before Session for Genesis
        Registrar: pallet_registrar = 20,
        Configuration: pallet_configuration = 21,
        CollatorAssignment: pallet_collator_assignment = 22,
        Initializer: pallet_initializer = 23,
        AuthorNoting: pallet_author_noting = 24,
        AuthorityAssignment: pallet_authority_assignment = 25,
        ServicesPayment: pallet_services_payment = 26,
        DataPreservers: pallet_data_preservers = 27,
        // Collator support. The order of these 6 are important and shall not change.
        Invulnerables: pallet_invulnerables = 30,
        Session: pallet_session = 31,
        AuthorityMapping: pallet_authority_mapping = 32,
        AuthorInherent: pallet_author_inherent = 33,
        // InflationRewards must be after Session and AuthorInherent
        InflationRewards: pallet_inflation_rewards = 35,
        // Treasury stuff.
        Treasury: pallet_treasury::{Pallet, Storage, Config<T>, Event<T>, Call} = 40,
        // More system support stuff
        RelayStorageRoots: pallet_relay_storage_roots = 60,
        WeightReclaim: cumulus_pallet_weight_reclaim = 61,
        RootTesting: pallet_root_testing = 100,
        AsyncBacking: pallet_async_backing::{Pallet, Storage} = 110,
    }
);
#[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_treasury, Treasury]
        [pallet_relay_storage_roots, RelayStorageRoots]
        [cumulus_pallet_weight_reclaim, WeightReclaim]
    );
}
impl_runtime_apis! {
    impl sp_consensus_aura::AuraApi<Block, NimbusId> for Runtime {
        fn slot_duration() -> sp_consensus_aura::SlotDuration {
            sp_consensus_aura::SlotDuration::from_millis(SLOT_DURATION)
        }
        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);
            let session_index = if should_end_session {
                Session::current_index() +1
            }
            else {
                Session::current_index()
            };
            pallet_authority_assignment::CollatorContainerChain::<Runtime>::get(session_index)
                .expect("authorities for current session should exist")
                .orchestrator_chain
        }
    }
    impl sp_api::Core<Block> for Runtime {
        fn version() -> RuntimeVersion {
            VERSION
        }
        fn execute_block(block: Block) {
            Executive::execute_block(block)
        }
        fn initialize_block(header: &<Block as BlockT>::Header) -> sp_runtime::ExtrinsicInclusionMode {
            Executive::initialize_block(header)
        }
    }
    impl sp_api::Metadata<Block> for Runtime {
        fn metadata() -> OpaqueMetadata {
            OpaqueMetadata::new(Runtime::metadata().into())
        }
        fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
            Runtime::metadata_at_version(version)
        }
        fn metadata_versions() -> Vec<u32> {
            Runtime::metadata_versions()
        }
    }
    impl sp_block_builder::BlockBuilder<Block> for Runtime {
        fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
            Executive::apply_extrinsic(extrinsic)
        }
        fn finalize_block() -> <Block as BlockT>::Header {
            Executive::finalize_block()
        }
        fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
            data.create_extrinsics()
        }
        fn check_inherents(
            block: Block,
            data: sp_inherents::InherentData,
        ) -> sp_inherents::CheckInherentsResult {
            data.check_extrinsics(&block)
        }
    }
    impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
        fn validate_transaction(
            source: TransactionSource,
            tx: <Block as BlockT>::Extrinsic,
            block_hash: <Block as BlockT>::Hash,
        ) -> TransactionValidity {
            Executive::validate_transaction(source, tx, block_hash)
        }
    }
    impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
        fn offchain_worker(header: &<Block as BlockT>::Header) {
            Executive::offchain_worker(header)
        }
    }
    impl sp_session::SessionKeys<Block> for Runtime {
        fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {
            SessionKeys::generate(seed)
        }
        fn decode_session_keys(
            encoded: Vec<u8>,
        ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {
            SessionKeys::decode_into_raw_public_keys(&encoded)
        }
    }
    impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {
        fn account_nonce(account: AccountId) -> Index {
            System::account_nonce(account)
        }
    }
    impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {
        fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {
            ParachainSystem::collect_collation_info(header)
        }
    }
    impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
        fn build_state(config: Vec<u8>) -> sp_genesis_builder::Result {
            build_state::<RuntimeGenesisConfig>(config)
        }
       fn get_preset(id: &Option<sp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
            get_preset::<RuntimeGenesisConfig>(id, |id: &sp_genesis_builder::PresetId| {
                let para_id: ParaId = 1000.into();
                let mock_container_chains: Vec<ParaId> =
                    vec![2000, 2001].iter().map(|&x| x.into()).collect();
                let invulnerables = vec![
                    "Alice".to_string(),
                    "Bob".to_string(),
                    "Charlie".to_string(),
                    "Dave".to_string(),
                ];
                let patch = match id.as_ref() {
                    "development" => genesis_config_presets::development(para_id, vec![], mock_container_chains, invulnerables),
                    _ => return None,
                };
                Some(
                    serde_json::to_string(&patch)
                        .expect("serialization to json is expected to work. qed.")
                        .into_bytes(),
                )
            })
        }
        fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
            vec!["development".into()]
        }
    }
    #[cfg(feature = "runtime-benchmarks")]
    impl frame_benchmarking::Benchmark<Block> for Runtime {
        fn benchmark_metadata(
            extra: bool,
        ) -> (
            Vec<frame_benchmarking::BenchmarkList>,
            Vec<frame_support::traits::StorageInfo>,
        ) {
            use cumulus_pallet_session_benchmarking::Pallet as SessionBench;
            use frame_benchmarking::{BenchmarkList};
            use frame_support::traits::StorageInfoTrait;
            let mut list = Vec::<BenchmarkList>::new();
            list_benchmarks!(list, extra);
            let storage_info = AllPalletsWithSystem::storage_info();
            (list, storage_info)
        }
        #[allow(non_local_definitions)]
        fn dispatch_benchmark(
            config: frame_benchmarking::BenchmarkConfig,
        ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, alloc::string::String> {
            use frame_benchmarking::{BenchmarkBatch, BenchmarkError};
            use sp_core::storage::TrackedStorageKey;
            impl frame_system_benchmarking::Config for Runtime {
                fn setup_set_code_requirements(code: &alloc::vec::Vec<u8>) -> Result<(), BenchmarkError> {
                    ParachainSystem::initialize_for_set_code_benchmark(code.len() as u32);
                    Ok(())
                }
                fn verify_set_code() {
                    System::assert_last_event(cumulus_pallet_parachain_system::Event::<Runtime>::ValidationFunctionStored.into());
                }
            }
            use cumulus_pallet_session_benchmarking::Pallet as SessionBench;
            impl cumulus_pallet_session_benchmarking::Config for Runtime {}
            let whitelist: Vec<TrackedStorageKey> = vec![
                // Block Number
                hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac")
                    .to_vec()
                    .into(),
                // Total Issuance
                hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80")
                    .to_vec()
                    .into(),
                // Execution Phase
                hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a")
                    .to_vec()
                    .into(),
                // Event Count
                hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850")
                    .to_vec()
                    .into(),
                // System Events
                hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7")
                    .to_vec()
                    .into(),
                // The transactional storage limit.
                hex_literal::hex!("3a7472616e73616374696f6e5f6c6576656c3a")
                    .to_vec()
                    .into(),
                // ParachainInfo ParachainId
                hex_literal::hex!(  "0d715f2646c8f85767b5d2764bb2782604a74d81251e398fd8a0a4d55023bb3f")
                    .to_vec()
                    .into(),
            ];
            let mut batches = Vec::<BenchmarkBatch>::new();
            let params = (&config, &whitelist);
            add_benchmarks!(params, batches);
            Ok(batches)
        }
    }
    #[cfg(feature = "try-runtime")]
    impl frame_try_runtime::TryRuntime<Block> for Runtime {
        fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) {
            let weight = Executive::try_runtime_upgrade(checks).unwrap();
            (weight, RuntimeBlockWeights::get().max_block)
        }
        fn execute_block(
            block: Block,
            state_root_check: bool,
            signature_check: bool,
            select: frame_try_runtime::TryStateSelect,
        ) -> Weight {
            // NOTE: intentional unwrap: we don't want to propagate the error backwards, and want to
            // have a backtrace here.
            Executive::try_execute_block(block, state_root_check, signature_check, select).unwrap()
        }
    }
    impl pallet_collator_assignment_runtime_api::CollatorAssignmentApi<Block, AccountId, ParaId> for Runtime {
        /// Returns the list of `ParaId` of registered chains with at least some
        /// collators. This filters out parachains with no assigned collators.
        /// Since runtime APIs are called on top of a parent block, we need to be carefull
        /// at session boundaries. If the next block will change session, this function returns
        /// the parachains relevant for the next session.
        fn parachains_with_some_collators() -> Vec<ParaId> {
            use tp_traits::{GetContainerChainsWithCollators, ForSession};
            // We should return the container-chains for the session in which we are kicking in
            let parent_number = System::block_number();
            let should_end_session = <Runtime as pallet_session::Config>::ShouldEndSession::should_end_session(parent_number + 1);
            let for_session = if should_end_session { ForSession::Next } else { ForSession::Current };
            CollatorAssignment::container_chains_with_collators(for_session)
                .into_iter()
                .filter_map(
                    |(para_id, collators)| (!collators.is_empty()).then_some(para_id)
                ).collect()
        }
    }
    impl pallet_registrar_runtime_api::RegistrarApi<Block, ParaId> for Runtime {
        /// Return the registered para ids
5
        fn registered_paras() -> Vec<ParaId> {
            // We should return the container-chains for the session in which we are kicking in
5
            let parent_number = System::block_number();
5
            let should_end_session = <Runtime as pallet_session::Config>::ShouldEndSession::should_end_session(parent_number + 1);
5
            let session_index = if should_end_session {
                Session::current_index() +1
            }
            else {
5
                Session::current_index()
            };
5
            let container_chains = Registrar::session_container_chains(session_index);
5
            let mut para_ids = vec![];
5
            para_ids.extend(container_chains.parachains);
5
            para_ids.extend(container_chains.parathreads.into_iter().map(|(para_id, _)| para_id));
5
            para_ids
5
        }
        /// Fetch genesis data for this para id
7
        fn genesis_data(para_id: ParaId) -> Option<ContainerChainGenesisData> {
7
            Registrar::para_genesis_data(para_id)
7
        }
        /// Fetch boot_nodes for this para id
        fn boot_nodes(para_id: ParaId) -> Vec<Vec<u8>> {
            DataPreservers::assignments_profiles(para_id)
                .filter_map(|profile| profile.bootnode_url.map(Into::into))
                .collect()
        }
    }
    impl pallet_author_noting_runtime_api::AuthorNotingApi<Block, AccountId, BlockNumber, ParaId> for Runtime
        where
        AccountId: parity_scale_codec::Codec,
        BlockNumber: parity_scale_codec::Codec,
        ParaId: parity_scale_codec::Codec,
    {
1
        fn latest_block_number(para_id: ParaId) -> Option<BlockNumber> {
1
            AuthorNoting::latest_author(para_id).map(|info| info.block_number)
1
        }
1
        fn latest_author(para_id: ParaId) -> Option<AccountId> {
1
            AuthorNoting::latest_author(para_id).map(|info| info.author)
1
        }
    }
    impl dp_consensus::TanssiAuthorityAssignmentApi<Block, NimbusId> for Runtime {
        /// Return the current authorities assigned to a given paraId
1078
        fn para_id_authorities(para_id: ParaId) -> Option<Vec<NimbusId>> {
1078
            let parent_number = System::block_number();
1078
            let should_end_session = <Runtime as pallet_session::Config>::ShouldEndSession::should_end_session(parent_number + 1);
1078
            let session_index = if should_end_session {
99
                Session::current_index() +1
            }
            else {
979
                Session::current_index()
            };
1078
            let assigned_authorities = AuthorityAssignment::collator_container_chain(session_index)?;
1078
            let self_para_id = ParachainInfo::get();
1078
            if para_id == self_para_id {
1070
                Some(assigned_authorities.orchestrator_chain)
            } else {
8
                assigned_authorities.container_chains.get(&para_id).cloned()
            }
1078
        }
        /// Return the paraId assigned to a given authority
32
        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);
32
            let session_index = if should_end_session {
8
                Session::current_index() +1
            }
            else {
24
                Session::current_index()
            };
32
            let assigned_authorities = AuthorityAssignment::collator_container_chain(session_index)?;
32
            let self_para_id = ParachainInfo::get();
32
            assigned_authorities.para_id_of(&authority, self_para_id)
32
        }
        /// Return the paraId assigned to a given authority on the next session.
        /// On session boundary this returns the same as `check_para_id_assignment`.
12
        fn check_para_id_assignment_next_session(authority: NimbusId) -> Option<ParaId> {
12
            let session_index = Session::current_index() + 1;
12
            let assigned_authorities = AuthorityAssignment::collator_container_chain(session_index)?;
12
            let self_para_id = ParachainInfo::get();
12
            assigned_authorities.para_id_of(&authority, self_para_id)
12
        }
    }
    impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>
    for Runtime {
        fn query_info(
            uxt: <Block as BlockT>::Extrinsic,
            len: u32,
        ) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo<Balance> {
            TransactionPayment::query_info(uxt, len)
        }
        fn query_fee_details(
            uxt: <Block as BlockT>::Extrinsic,
            len: u32,
        ) -> pallet_transaction_payment::FeeDetails<Balance> {
            TransactionPayment::query_fee_details(uxt, len)
        }
        fn query_weight_to_fee(weight: Weight) -> Balance {
            TransactionPayment::weight_to_fee(weight)
        }
        fn query_length_to_fee(length: u32) -> Balance {
            TransactionPayment::length_to_fee(length)
        }
    }
    impl pallet_stream_payment_runtime_api::StreamPaymentApi<Block, StreamId, Balance, Balance>
    for Runtime {
        fn stream_payment_status(
            stream_id: StreamId,
            now: Option<Balance>,
        ) -> Result<StreamPaymentApiStatus<Balance>, StreamPaymentApiError> {
            match StreamPayment::stream_payment_status(stream_id, now) {
                Ok(pallet_stream_payment::StreamPaymentStatus {
                    payment, deposit_left, stalled
                }) => Ok(StreamPaymentApiStatus {
                    payment, deposit_left, stalled
                }),
                Err(pallet_stream_payment::Error::<Runtime>::UnknownStreamId)
                => Err(StreamPaymentApiError::UnknownStreamId),
                Err(e) => Err(StreamPaymentApiError::Other(format!("{e:?}")))
            }
        }
    }
    impl pallet_data_preservers_runtime_api::DataPreserversApi<Block, DataPreserversProfileId, ParaId> for Runtime {
        fn get_active_assignment(
            profile_id: DataPreserversProfileId,
        ) -> pallet_data_preservers_runtime_api::Assignment<ParaId> {
            use pallet_data_preservers_runtime_api::Assignment;
            use pallet_stream_payment::StreamPaymentStatus;
            let Some((para_id, witness)) = pallet_data_preservers::Profiles::<Runtime>::get(profile_id)
                .and_then(|x| x.assignment) else
            {
                return Assignment::NotAssigned;
            };
            match witness {
                tp_data_preservers_common::AssignmentWitness::Free => Assignment::Active(para_id),
                tp_data_preservers_common::AssignmentWitness::StreamPayment { stream_id } => {
                    // Error means no Stream exists with that ID or some issue occured when computing
                    // the status. In that case we cannot consider the assignment as active.
                    let Ok(StreamPaymentStatus { stalled, .. }) = StreamPayment::stream_payment_status( stream_id, None) else {
                        return Assignment::Inactive(para_id);
                    };
                    if stalled {
                        Assignment::Inactive(para_id)
                    } else {
                        Assignment::Active(para_id)
                    }
                },
            }
        }
    }
    impl async_backing_primitives::UnincludedSegmentApi<Block> for Runtime {
        fn can_build_upon(
            included_hash: <Block as BlockT>::Hash,
            slot: async_backing_primitives::Slot,
        ) -> bool {
            ConsensusHook::can_build_upon(included_hash, slot)
        }
    }
    impl dp_slot_duration_runtime_api::TanssiSlotDurationApi<Block> for Runtime {
        fn slot_duration() -> u64 {
            SLOT_DURATION
        }
    }
    impl pallet_services_payment_runtime_api::ServicesPaymentApi<Block, Balance, ParaId> for Runtime {
        fn block_cost(para_id: ParaId) -> Balance {
            let (block_production_costs, _) = <Runtime as pallet_services_payment::Config>::ProvideBlockProductionCost::block_cost(&para_id);
            block_production_costs
        }
        fn collator_assignment_cost(para_id: ParaId) -> Balance {
            let (collator_assignment_costs, _) = <Runtime as pallet_services_payment::Config>::ProvideCollatorAssignmentCost::collator_assignment_cost(&para_id);
            collator_assignment_costs
        }
    }
}
#[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,
                core::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
        }
    };
}