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
#[cfg(test)]
46
mod tests;
47

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

            
118
/// Block type as expected by this runtime.
119
pub type Block = generic::Block<Header, UncheckedExtrinsic>;
120
/// A Block signed with a Justification
121
pub type SignedBlock = generic::SignedBlock<Block>;
122
/// BlockId type as expected by this runtime.
123
pub type BlockId = generic::BlockId<Block>;
124

            
125
/// CollatorId type expected by this runtime.
126
pub type CollatorId = AccountId;
127

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

            
144
/// Unchecked extrinsic type as expected by this runtime.
145
pub type UncheckedExtrinsic =
146
    generic::UncheckedExtrinsic<Address, RuntimeCall, Signature, TxExtension>;
147

            
148
/// Extrinsic type that has already been checked.
149
pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, RuntimeCall, TxExtension>;
150

            
151
/// The runtime migrations per release.
152
pub mod migrations {
153
    /// Unreleased migrations. Add new ones here:
154
    pub type Unreleased = ();
155
}
156

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

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

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

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

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

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

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

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

            
224
    pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;
225
    /// Opaque block header type.
226
    pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
227
    /// Opaque block type.
228
    pub type Block = generic::Block<Header, UncheckedExtrinsic>;
229
    /// Opaque block identifier type.
230
    pub type BlockId = generic::BlockId<Block>;
231
}
232

            
233
impl_opaque_keys! {
234
    pub struct SessionKeys {
235
        pub nimbus: Initializer,
236
    }
237
}
238

            
239
#[sp_version::runtime_version]
240
pub const VERSION: RuntimeVersion = RuntimeVersion {
241
    spec_name: Cow::Borrowed("flashbox"),
242
    impl_name: Cow::Borrowed("flashbox"),
243
    authoring_version: 1,
244
    spec_version: 1400,
245
    impl_version: 0,
246
    apis: RUNTIME_API_VERSIONS,
247
    transaction_version: 1,
248
    system_version: 1,
249
};
250

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

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

            
263
// Time is measured by number of blocks.
264
pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);
265
pub const HOURS: BlockNumber = MINUTES * 60;
266
pub const DAYS: BlockNumber = HOURS * 24;
267

            
268
// Unit = the base number of indivisible units for balances
269
pub const UNIT: Balance = 1_000_000_000_000;
270
pub const CENTS: Balance = UNIT / 30_000;
271
pub const MILLIUNIT: Balance = 1_000_000_000;
272
pub const MICROUNIT: Balance = 1_000_000;
273

            
274
/// The existential deposit. Set to 1/10 of the Connected Relay Chain.
275
pub const EXISTENTIAL_DEPOSIT: Balance = MILLIUNIT;
276

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

            
281
/// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used by
282
/// `Operational` extrinsics.
283
const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);
284

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

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

            
300
parameter_types! {
301
    pub const Version: RuntimeVersion = VERSION;
302

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

            
330
// Configure FRAME pallets to include in runtime.
331

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

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

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

            
405
1057
        if authorities.is_empty() {
406
            return false;
407
1057
        }
408
1057

            
409
1057
        let author_index = (*slot as usize) % authorities.len();
410
1057
        let expected_author = &authorities[author_index];
411
1057

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

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

            
430
parameter_types! {
431
    pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT;
432
}
433

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

            
453
parameter_types! {
454
    pub const TransactionByteFee: Balance = 1;
455
}
456

            
457
impl pallet_transaction_payment::Config for Runtime {
458
    type RuntimeEvent = RuntimeEvent;
459
    type OnChargeTransaction =
460
        FungibleAdapter<Balances, tanssi_runtime_common::DealWithFees<Runtime>>;
461
    type OperationalFeeMultiplier = ConstU8<5>;
462
    type WeightToFee = WeightToFee;
463
    type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;
464
    type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Self>;
465
    type WeightInfo = weights::pallet_transaction_payment::SubstrateWeight<Runtime>;
466
}
467

            
468
pub const RELAY_CHAIN_SLOT_DURATION_MILLIS: u32 = 6000;
469
pub const UNINCLUDED_SEGMENT_CAPACITY: u32 = 3;
470
pub const BLOCK_PROCESSING_VELOCITY: u32 = 1;
471

            
472
type ConsensusHook = pallet_async_backing::consensus_hook::FixedVelocityConsensusHook<
473
    Runtime,
474
    BLOCK_PROCESSING_VELOCITY,
475
    UNINCLUDED_SEGMENT_CAPACITY,
476
>;
477

            
478
impl cumulus_pallet_parachain_system::Config for Runtime {
479
    type WeightInfo = weights::cumulus_pallet_parachain_system::SubstrateWeight<Runtime>;
480
    type RuntimeEvent = RuntimeEvent;
481
    type OnSystemEvent = ();
482
    type SelfParaId = parachain_info::Pallet<Runtime>;
483
    type OutboundXcmpMessageSource = ();
484
    // Ignore all DMP messages by enqueueing them into `()`:
485
    type DmpQueue = frame_support::traits::EnqueueWithOrigin<(), sp_core::ConstU8<0>>;
486
    type ReservedDmpWeight = ();
487
    type XcmpMessageHandler = ();
488
    type ReservedXcmpWeight = ();
489
    type CheckAssociatedRelayNumber = RelayNumberMonotonicallyIncreases;
490
    type ConsensusHook = ConsensusHook;
491
    type SelectCore = cumulus_pallet_parachain_system::DefaultCoreSelector<Runtime>;
492
}
493

            
494
pub struct ParaSlotProvider;
495
impl Get<(Slot, SlotDuration)> for ParaSlotProvider {
496
71
    fn get() -> (Slot, SlotDuration) {
497
71
        let slot = u64::from(<Runtime as pallet_author_inherent::Config>::SlotBeacon::slot());
498
71
        (Slot::from(slot), SlotDuration::from_millis(SLOT_DURATION))
499
71
    }
500
}
501

            
502
parameter_types! {
503
    pub const ExpectedBlockTime: u64 = MILLISECS_PER_BLOCK;
504
}
505

            
506
impl pallet_async_backing::Config for Runtime {
507
    type AllowMultipleBlocksPerSlot = ConstBool<true>;
508
    type GetAndVerifySlot =
509
        pallet_async_backing::ParaSlot<RELAY_CHAIN_SLOT_DURATION_MILLIS, ParaSlotProvider>;
510
    type ExpectedBlockTime = ExpectedBlockTime;
511
}
512

            
513
pub struct OwnApplySession;
514
impl pallet_initializer::ApplyNewSession<Runtime> for OwnApplySession {
515
167
    fn apply_new_session(
516
167
        _changed: bool,
517
167
        session_index: u32,
518
167
        all_validators: Vec<(AccountId, NimbusId)>,
519
167
        queued: Vec<(AccountId, NimbusId)>,
520
167
    ) {
521
167
        // We first initialize Configuration
522
167
        Configuration::initializer_on_new_session(&session_index);
523
167
        // Next: Registrar
524
167
        Registrar::initializer_on_new_session(&session_index);
525
167
        // Next: AuthorityMapping
526
167
        AuthorityMapping::initializer_on_new_session(&session_index, &all_validators);
527
167

            
528
543
        let next_collators = queued.iter().map(|(k, _)| k.clone()).collect();
529
167

            
530
167
        // Next: CollatorAssignment
531
167
        let assignments =
532
167
            CollatorAssignment::initializer_on_new_session(&session_index, next_collators);
533
167

            
534
167
        let queued_id_to_nimbus_map = queued.iter().cloned().collect();
535
167
        AuthorityAssignment::initializer_on_new_session(
536
167
            &session_index,
537
167
            &queued_id_to_nimbus_map,
538
167
            &assignments.next_assignment,
539
167
        );
540
167
    }
541
95
    fn on_before_session_ending() {}
542
}
543

            
544
impl pallet_initializer::Config for Runtime {
545
    type SessionIndex = u32;
546

            
547
    /// The identifier type for an authority.
548
    type AuthorityId = NimbusId;
549

            
550
    type SessionHandler = OwnApplySession;
551
}
552

            
553
impl parachain_info::Config for Runtime {}
554

            
555
pub struct CollatorsFromInvulnerables;
556

            
557
/// Play the role of the session manager.
558
impl SessionManager<CollatorId> for CollatorsFromInvulnerables {
559
239
    fn new_session(index: SessionIndex) -> Option<Vec<CollatorId>> {
560
239
        log::info!(
561
            "assembling new collators for new session {} at #{:?}",
562
            index,
563
            <frame_system::Pallet<Runtime>>::block_number(),
564
        );
565

            
566
239
        let invulnerables = Invulnerables::invulnerables().to_vec();
567
239
        let target_session_index = index.saturating_add(1);
568
239
        let max_collators =
569
239
            <Configuration as GetHostConfiguration<u32>>::max_collators(target_session_index);
570
239
        let collators = invulnerables
571
239
            .iter()
572
239
            .take(max_collators as usize)
573
239
            .cloned()
574
239
            .collect();
575
239

            
576
239
        Some(collators)
577
239
    }
578
167
    fn start_session(_: SessionIndex) {
579
167
        // we don't care.
580
167
    }
581
95
    fn end_session(_: SessionIndex) {
582
95
        // we don't care.
583
95
    }
584
}
585

            
586
parameter_types! {
587
    pub const Period: u32 = prod_or_fast!(5 * MINUTES, 1 * MINUTES);
588
    pub const Offset: u32 = 0;
589
}
590

            
591
impl pallet_session::Config for Runtime {
592
    type RuntimeEvent = RuntimeEvent;
593
    type ValidatorId = <Self as frame_system::Config>::AccountId;
594
    // we don't have stash and controller, thus we don't need the convert as well.
595
    type ValidatorIdOf = ConvertInto;
596
    type ShouldEndSession = pallet_session::PeriodicSessions<Period, Offset>;
597
    type NextSessionRotation = pallet_session::PeriodicSessions<Period, Offset>;
598
    type SessionManager = CollatorsFromInvulnerables;
599
    // Essentially just Aura, but let's be pedantic.
600
    type SessionHandler = <SessionKeys as sp_runtime::traits::OpaqueKeys>::KeyTypeIdProviders;
601
    type Keys = SessionKeys;
602
    type WeightInfo = weights::pallet_session::SubstrateWeight<Runtime>;
603
    type DisablingStrategy = ();
604
}
605

            
606
pub struct RemoveInvulnerablesImpl;
607

            
608
impl RemoveInvulnerables<CollatorId> for RemoveInvulnerablesImpl {
609
255
    fn remove_invulnerables(
610
255
        collators: &mut Vec<CollatorId>,
611
255
        num_invulnerables: usize,
612
255
    ) -> Vec<CollatorId> {
613
255
        if num_invulnerables == 0 {
614
            return vec![];
615
255
        }
616
255
        let all_invulnerables = pallet_invulnerables::Invulnerables::<Runtime>::get();
617
255
        if all_invulnerables.is_empty() {
618
            return vec![];
619
255
        }
620
255
        let mut invulnerables = vec![];
621
255
        // TODO: use binary_search when invulnerables are sorted
622
399
        collators.retain(|x| {
623
399
            if invulnerables.len() < num_invulnerables && all_invulnerables.contains(x) {
624
319
                invulnerables.push(x.clone());
625
319
                false
626
            } else {
627
80
                true
628
            }
629
399
        });
630
255

            
631
255
        invulnerables
632
255
    }
633
}
634

            
635
pub struct ParaIdAssignmentHooksImpl;
636

            
637
impl ParaIdAssignmentHooksImpl {
638
252
    fn charge_para_ids_internal(
639
252
        blocks_per_session: tp_traits::BlockNumber,
640
252
        para_id: ParaId,
641
252
        currently_assigned: &BTreeSet<ParaId>,
642
252
        maybe_tip: &Option<BalanceOf<Runtime>>,
643
252
    ) -> Result<Weight, DispatchError> {
644
        use frame_support::traits::Currency;
645
        type ServicePaymentCurrency = <Runtime as pallet_services_payment::Config>::Currency;
646

            
647
        // Check if the container chain has enough credits for a session assignments
648
245
        let maybe_assignment_imbalance =
649
252
            if  pallet_services_payment::Pallet::<Runtime>::burn_collator_assignment_free_credit_for_para(&para_id).is_err() {
650
15
                let (amount_to_charge, _weight) =
651
15
                    <Runtime as pallet_services_payment::Config>::ProvideCollatorAssignmentCost::collator_assignment_cost(&para_id);
652
15
                Some(<ServicePaymentCurrency as Currency<AccountId>>::withdraw(
653
15
                    &pallet_services_payment::Pallet::<Runtime>::parachain_tank(para_id),
654
15
                    amount_to_charge,
655
15
                    WithdrawReasons::FEE,
656
15
                    ExistenceRequirement::KeepAlive,
657
15
                )?)
658
            } else {
659
237
                None
660
            };
661

            
662
245
        if let Some(tip) = maybe_tip {
663
197
            if let Err(e) = pallet_services_payment::Pallet::<Runtime>::charge_tip(&para_id, tip) {
664
                // Return assignment imbalance to tank on error
665
1
                if let Some(assignment_imbalance) = maybe_assignment_imbalance {
666
                    <Runtime as pallet_services_payment::Config>::Currency::resolve_creating(
667
                        &pallet_services_payment::Pallet::<Runtime>::parachain_tank(para_id),
668
                        assignment_imbalance,
669
                    );
670
1
                }
671
1
                return Err(e);
672
196
            }
673
48
        }
674

            
675
244
        if let Some(assignment_imbalance) = maybe_assignment_imbalance {
676
8
            <Runtime as pallet_services_payment::Config>::OnChargeForCollatorAssignment::on_unbalanced(assignment_imbalance);
677
236
        }
678

            
679
        // If the para has been assigned collators for this session it must have enough block credits
680
        // for the current and the next session.
681
244
        let block_credits_needed = if currently_assigned.contains(&para_id) {
682
129
            blocks_per_session * 2
683
        } else {
684
115
            blocks_per_session
685
        };
686
        // Check if the container chain has enough credits for producing blocks
687
244
        let free_block_credits =
688
244
            pallet_services_payment::BlockProductionCredits::<Runtime>::get(para_id)
689
244
                .unwrap_or_default();
690
244
        let remaining_block_credits = block_credits_needed.saturating_sub(free_block_credits);
691
244
        let (block_production_costs, _) =
692
244
            <Runtime as pallet_services_payment::Config>::ProvideBlockProductionCost::block_cost(
693
244
                &para_id,
694
244
            );
695
244
        // Check if we can withdraw
696
244
        let remaining_block_credits_to_pay =
697
244
            u128::from(remaining_block_credits).saturating_mul(block_production_costs);
698
244
        let remaining_to_pay = remaining_block_credits_to_pay;
699
244
        // This should take into account whether we tank goes below ED
700
244
        // The true refers to keepAlive
701
244
        Balances::can_withdraw(
702
244
            &pallet_services_payment::Pallet::<Runtime>::parachain_tank(para_id),
703
244
            remaining_to_pay,
704
244
        )
705
244
        .into_result(true)?;
706
        // TODO: Have proper weight
707
230
        Ok(Weight::zero())
708
252
    }
709
}
710

            
711
impl<AC> ParaIdAssignmentHooks<BalanceOf<Runtime>, AC> for ParaIdAssignmentHooksImpl {
712
334
    fn pre_assignment(para_ids: &mut Vec<ParaId>, currently_assigned: &BTreeSet<ParaId>) {
713
334
        let blocks_per_session = Period::get();
714
334
        para_ids.retain(|para_id| {
715
193
            with_transaction(|| {
716
193
                let max_tip =
717
193
                    pallet_services_payment::MaxTip::<Runtime>::get(para_id).unwrap_or_default();
718
193
                TransactionOutcome::Rollback(Self::charge_para_ids_internal(
719
193
                    blocks_per_session,
720
193
                    *para_id,
721
193
                    currently_assigned,
722
193
                    &Some(max_tip),
723
193
                ))
724
193
            })
725
193
            .is_ok()
726
334
        });
727
334
    }
728

            
729
167
    fn post_assignment(
730
167
        current_assigned: &BTreeSet<ParaId>,
731
167
        new_assigned: &mut BTreeMap<ParaId, Vec<AC>>,
732
167
        maybe_tip: &Option<BalanceOf<Runtime>>,
733
167
    ) -> Weight {
734
167
        let blocks_per_session = Period::get();
735
167
        let mut total_weight = Weight::zero();
736
171
        new_assigned.retain(|&para_id, collators| {
737
171
            // Short-circuit in case collators are empty
738
171
            if collators.is_empty() {
739
112
                return true;
740
59
            }
741
59
            with_storage_layer(|| {
742
59
                Self::charge_para_ids_internal(
743
59
                    blocks_per_session,
744
59
                    para_id,
745
59
                    current_assigned,
746
59
                    maybe_tip,
747
59
                )
748
59
            })
749
59
            .inspect(|weight| {
750
59
                total_weight += *weight;
751
59
            })
752
59
            .is_ok()
753
171
        });
754
167
        total_weight
755
167
    }
756

            
757
    /// Make those para ids valid by giving them enough credits, for benchmarking.
758
    #[cfg(feature = "runtime-benchmarks")]
759
    fn make_valid_para_ids(para_ids: &[ParaId]) {
760
        use frame_support::assert_ok;
761

            
762
        let blocks_per_session = Period::get();
763
        // Enough credits to run any benchmark
764
        let block_credits = 20 * blocks_per_session;
765
        let session_credits = 20;
766

            
767
        for para_id in para_ids {
768
            assert_ok!(ServicesPayment::set_block_production_credits(
769
                RuntimeOrigin::root(),
770
                *para_id,
771
                block_credits,
772
            ));
773
            assert_ok!(ServicesPayment::set_collator_assignment_credits(
774
                RuntimeOrigin::root(),
775
                *para_id,
776
                session_credits,
777
            ));
778
        }
779
    }
780
}
781

            
782
pub struct NeverRotateCollators;
783

            
784
impl ShouldRotateAllCollators<u32> for NeverRotateCollators {
785
167
    fn should_rotate_all_collators(_: u32) -> bool {
786
167
        false
787
167
    }
788
}
789

            
790
impl pallet_collator_assignment::Config for Runtime {
791
    type RuntimeEvent = RuntimeEvent;
792
    type HostConfiguration = Configuration;
793
    type ContainerChains = Registrar;
794
    type SessionIndex = u32;
795
    type SelfParaId = ParachainInfo;
796
    type ShouldRotateAllCollators = NeverRotateCollators;
797
    type Randomness = ();
798
    type RemoveInvulnerables = RemoveInvulnerablesImpl;
799
    type ParaIdAssignmentHooks = ParaIdAssignmentHooksImpl;
800
    type CollatorAssignmentTip = ServicesPayment;
801
    type Currency = Balances;
802
    type ForceEmptyOrchestrator = ConstBool<false>;
803
    type CoreAllocationConfiguration = ();
804
    type WeightInfo = weights::pallet_collator_assignment::SubstrateWeight<Runtime>;
805
}
806

            
807
impl pallet_authority_assignment::Config for Runtime {
808
    type SessionIndex = u32;
809
    type AuthorityId = NimbusId;
810
}
811

            
812
pub const FIXED_BLOCK_PRODUCTION_COST: u128 = 1 * currency::MICRODANCE;
813
pub const FIXED_COLLATOR_ASSIGNMENT_COST: u128 = 100 * currency::MICRODANCE;
814

            
815
pub struct BlockProductionCost<Runtime>(PhantomData<Runtime>);
816
impl ProvideBlockProductionCost<Runtime> for BlockProductionCost<Runtime> {
817
262
    fn block_cost(_para_id: &ParaId) -> (u128, Weight) {
818
262
        (FIXED_BLOCK_PRODUCTION_COST, Weight::zero())
819
262
    }
820
}
821

            
822
pub struct CollatorAssignmentCost<Runtime>(PhantomData<Runtime>);
823
impl ProvideCollatorAssignmentCost<Runtime> for CollatorAssignmentCost<Runtime> {
824
19
    fn collator_assignment_cost(_para_id: &ParaId) -> (u128, Weight) {
825
19
        (FIXED_COLLATOR_ASSIGNMENT_COST, Weight::zero())
826
19
    }
827
}
828

            
829
parameter_types! {
830
    // 60 days worth of blocks
831
    pub const FreeBlockProductionCredits: BlockNumber = 60 * DAYS;
832
    // 60 days worth of blocks
833
    pub const FreeCollatorAssignmentCredits: u32 = FreeBlockProductionCredits::get()/Period::get();
834
}
835

            
836
impl pallet_services_payment::Config for Runtime {
837
    type RuntimeEvent = RuntimeEvent;
838
    /// Handler for fees
839
    type OnChargeForBlock = ();
840
    type OnChargeForCollatorAssignment = ();
841
    type OnChargeForCollatorAssignmentTip = ();
842
    /// Currency type for fee payment
843
    type Currency = Balances;
844
    /// Provider of a block cost which can adjust from block to block
845
    type ProvideBlockProductionCost = BlockProductionCost<Runtime>;
846
    /// Provider of a block cost which can adjust from block to block
847
    type ProvideCollatorAssignmentCost = CollatorAssignmentCost<Runtime>;
848
    /// The maximum number of block credits that can be accumulated
849
    type FreeBlockProductionCredits = FreeBlockProductionCredits;
850
    /// The maximum number of session credits that can be accumulated
851
    type FreeCollatorAssignmentCredits = FreeCollatorAssignmentCredits;
852
    type ManagerOrigin =
853
        EitherOfDiverse<pallet_registrar::EnsureSignedByManager<Runtime>, EnsureRoot<AccountId>>;
854
    type WeightInfo = weights::pallet_services_payment::SubstrateWeight<Runtime>;
855
}
856

            
857
parameter_types! {
858
    pub const ProfileDepositBaseFee: Balance = currency::STORAGE_ITEM_FEE;
859
    pub const ProfileDepositByteFee: Balance = currency::STORAGE_BYTE_FEE;
860
    #[derive(Clone)]
861
    pub const MaxAssignmentsPerParaId: u32 = 10;
862
    #[derive(Clone)]
863
    pub const MaxNodeUrlLen: u32 = 200;
864
}
865

            
866
pub type DataPreserversProfileId = u64;
867

            
868
impl pallet_data_preservers::Config for Runtime {
869
    type RuntimeEvent = RuntimeEvent;
870
    type RuntimeHoldReason = RuntimeHoldReason;
871
    type Currency = Balances;
872
    type WeightInfo = weights::pallet_data_preservers::SubstrateWeight<Runtime>;
873

            
874
    type ProfileId = DataPreserversProfileId;
875
    type ProfileDeposit = tp_traits::BytesDeposit<ProfileDepositBaseFee, ProfileDepositByteFee>;
876
    type AssignmentProcessor = tp_data_preservers_common::AssignmentProcessor<Runtime>;
877

            
878
    type AssignmentOrigin = pallet_registrar::EnsureSignedByManager<Runtime>;
879
    type ForceSetProfileOrigin = EnsureRoot<AccountId>;
880

            
881
    type MaxAssignmentsPerParaId = MaxAssignmentsPerParaId;
882
    type MaxNodeUrlLen = MaxNodeUrlLen;
883
    type MaxParaIdsVecLen = MaxLengthParaIds;
884
}
885

            
886
impl pallet_author_noting::Config for Runtime {
887
    type RuntimeEvent = RuntimeEvent;
888
    type ContainerChains = CollatorAssignment;
889
    type SlotBeacon = dp_consensus::AuraDigestSlotBeacon<Runtime>;
890
    type ContainerChainAuthor = CollatorAssignment;
891
    type AuthorNotingHook = (InflationRewards, ServicesPayment);
892
    type RelayOrPara = pallet_author_noting::ParaMode<
893
        cumulus_pallet_parachain_system::RelaychainDataProvider<Self>,
894
    >;
895
    type MaxContainerChains = MaxLengthParaIds;
896
    type WeightInfo = weights::pallet_author_noting::SubstrateWeight<Runtime>;
897
}
898

            
899
parameter_types! {
900
    pub const PotId: PalletId = PalletId(*b"PotStake");
901
    pub const MaxCandidates: u32 = 1000;
902
    pub const MinCandidates: u32 = 5;
903
    pub const SessionLength: BlockNumber = 5;
904
    pub const MaxInvulnerables: u32 = 200;
905
    pub const ExecutiveBody: BodyId = BodyId::Executive;
906
}
907

            
908
impl pallet_invulnerables::Config for Runtime {
909
    type RuntimeEvent = RuntimeEvent;
910
    type UpdateOrigin = EnsureRoot<AccountId>;
911
    type MaxInvulnerables = MaxInvulnerables;
912
    type CollatorId = CollatorId;
913
    type CollatorIdOf = ConvertInto;
914
    type CollatorRegistration = Session;
915
    type WeightInfo = weights::pallet_invulnerables::SubstrateWeight<Runtime>;
916
    #[cfg(feature = "runtime-benchmarks")]
917
    type Currency = Balances;
918
}
919

            
920
parameter_types! {
921
    #[derive(Clone)]
922
    pub const MaxLengthParaIds: u32 = 200u32;
923
    pub const MaxEncodedGenesisDataSize: u32 = 5_000_000u32; // 5MB
924
}
925

            
926
pub struct CurrentSessionIndexGetter;
927

            
928
impl tp_traits::GetSessionIndex<u32> for CurrentSessionIndexGetter {
929
    /// Returns current session index.
930
42
    fn session_index() -> u32 {
931
42
        Session::current_index()
932
42
    }
933

            
934
    #[cfg(feature = "runtime-benchmarks")]
935
    fn skip_to_session(_session_index: SessionIndex) {}
936
}
937

            
938
impl pallet_configuration::Config for Runtime {
939
    type SessionDelay = ConstU32<2>;
940
    type SessionIndex = u32;
941
    type CurrentSessionIndex = CurrentSessionIndexGetter;
942
    type ForceEmptyOrchestrator = ConstBool<false>;
943
    type WeightInfo = weights::pallet_configuration::SubstrateWeight<Runtime>;
944
}
945

            
946
pub struct FlashboxRegistrarHooks;
947

            
948
impl RegistrarHooks for FlashboxRegistrarHooks {
949
20
    fn para_marked_valid_for_collating(para_id: ParaId) -> Weight {
950
20
        // Give free credits but only once per para id
951
20
        ServicesPayment::give_free_credits(&para_id)
952
20
    }
953

            
954
6
    fn para_deregistered(para_id: ParaId) -> Weight {
955
        // Clear pallet_author_noting storage
956
6
        if let Err(e) = AuthorNoting::kill_author_data(RuntimeOrigin::root(), para_id) {
957
            log::warn!(
958
                "Failed to kill_author_data after para id {} deregistered: {:?}",
959
                u32::from(para_id),
960
                e,
961
            );
962
6
        }
963
        // Remove bootnodes from pallet_data_preservers
964
6
        DataPreservers::para_deregistered(para_id);
965
6

            
966
6
        ServicesPayment::para_deregistered(para_id);
967
6

            
968
6
        Weight::default()
969
6
    }
970

            
971
21
    fn check_valid_for_collating(para_id: ParaId) -> DispatchResult {
972
21
        // To be able to call mark_valid_for_collating, a container chain must have bootnodes
973
21
        DataPreservers::check_valid_for_collating(para_id)
974
21
    }
975

            
976
    #[cfg(feature = "runtime-benchmarks")]
977
    fn benchmarks_ensure_valid_for_collating(para_id: ParaId) {
978
        use {
979
            frame_support::traits::EnsureOriginWithArg,
980
            pallet_data_preservers::{ParaIdsFilter, Profile, ProfileMode},
981
        };
982

            
983
        let profile = Profile {
984
            url: b"/ip4/127.0.0.1/tcp/33049/ws/p2p/12D3KooWHVMhQDHBpj9vQmssgyfspYecgV6e3hH1dQVDUkUbCYC9"
985
                    .to_vec()
986
                    .try_into()
987
                    .expect("to fit in BoundedVec"),
988
            para_ids: ParaIdsFilter::AnyParaId,
989
            mode: ProfileMode::Bootnode,
990
            assignment_request: tp_data_preservers_common::ProviderRequest::Free,
991
        };
992

            
993
        let profile_id = pallet_data_preservers::NextProfileId::<Runtime>::get();
994
        let profile_owner = AccountId::new([1u8; 32]);
995
        DataPreservers::force_create_profile(RuntimeOrigin::root(), profile, profile_owner)
996
            .expect("profile create to succeed");
997

            
998
        let para_manager =
999
            <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 RuntimeEvent = RuntimeEvent;
    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 {
1
    /// All calls can be proxied. This is the trivial/most permissive filter.
    Any = 0,
2
    /// Only extrinsics that do not transfer funds.
    NonTransfer = 1,
1
    /// Only extrinsics related to governance (democracy and collectives).
    Governance = 2,
1
    /// Only extrinsics related to staking.
    Staking = 3,
1
    /// Allow to veto an announced proxy call.
    CancelProxy = 4,
1
    /// Allow extrinsic related to Balances.
    Balances = 5,
1
    /// Allow extrinsics related to Registrar
    Registrar = 6,
1
    /// 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 {
9
        // Since proxy filters are respected in all dispatches of the Utility
9
        // pallet, it should never need to be filtered by any proxy.
9
        if let RuntimeCall::Utility(..) = c {
            return true;
9
        }
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 RuntimeEvent = RuntimeEvent;
    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 {
89
    fn contains(c: &RuntimeCall) -> bool {
88
        matches!(
1
            c,
            RuntimeCall::Registrar(pallet_registrar::Call::register_parathread { .. })
        )
89
    }
}
type NormalFilter = EverythingBut<IsRegisterParathreads>;
impl pallet_maintenance_mode::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    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 {
2114
    fn get_block_author() -> Option<AccountId32> {
2114
        // TODO: we should do a refactor here, and use either authority-mapping or collator-assignemnt
2114
        // we should also make sure we actually account for the weight of these
2114
        // although most of these should be cached as they are read every block
2114
        let slot = u64::from(<Runtime as pallet_author_inherent::Config>::SlotBeacon::slot());
2114
        let self_para_id = ParachainInfo::get();
2114
        CollatorAssignment::author_for_slot(slot.into(), self_para_id)
2114
    }
}
pub struct OnUnbalancedInflation;
impl frame_support::traits::OnUnbalanced<Credit<AccountId, Balances>> for OnUnbalancedInflation {
1057
    fn on_nonzero_unbalanced(credit: Credit<AccountId, Balances>) {
1057
        let _ = <Balances as Balanced<_>>::resolve(&ParachainBondAccount::get(), credit);
1057
    }
}
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, ()>;
    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();
    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.
18101
construct_runtime!(
18101
    pub enum Runtime
18101
    {
18101
        // System support stuff.
18101
        System: frame_system = 0,
18101
        ParachainSystem: cumulus_pallet_parachain_system = 1,
18101
        Timestamp: pallet_timestamp = 2,
18101
        ParachainInfo: parachain_info = 3,
18101
        Sudo: pallet_sudo = 4,
18101
        Utility: pallet_utility = 5,
18101
        Proxy: pallet_proxy = 6,
18101
        Migrations: pallet_migrations = 7,
18101
        MultiBlockMigrations: pallet_multiblock_migrations = 121,
18101
        MaintenanceMode: pallet_maintenance_mode = 8,
18101
        TxPause: pallet_tx_pause = 9,
18101

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

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

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

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

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

            
18101
        // More system support stuff
18101
        RelayStorageRoots: pallet_relay_storage_roots = 60,
18101
        WeightReclaim: cumulus_pallet_weight_reclaim = 61,
18101

            
18101
        RootTesting: pallet_root_testing = 100,
18101
        AsyncBacking: pallet_async_backing::{Pallet, Storage} = 110,
18101
    }
18101
);
#[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, |_| None)
        }
        fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
            vec![]
        }
    }
    #[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: &sp_std::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 {
        /// Return the parachain that the given `AccountId` is collating for.
        /// Returns `None` if the `AccountId` is not collating.
8
        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
        }
        /// Return the parachain that the given `AccountId` will be collating for
        /// in the next session change.
        /// Returns `None` if the `AccountId` will not be collating.
6
        fn future_collator_parachain_assignment(account: AccountId) -> Option<ParaId> {
6
            let assigned_collators = CollatorAssignment::pending_collator_container_chain();
6

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

            
4
                    assigned_collators.para_id_of(&account, self_para_id)
                }
                None => {
2
                    Self::current_collator_parachain_assignment(account)
                }
            }
6
        }
        /// Return the list of collators of the given `ParaId`.
        /// Returns `None` if the `ParaId` is not in the registrar.
14
        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 {
9
                Some(assigned_collators.orchestrator_chain)
            } else {
5
                assigned_collators.container_chains.get(&para_id).cloned()
            }
14
        }
        /// 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> {
5
            // 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

            
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(|profile| profile.mode == pallet_data_preservers::ProfileMode::Bootnode)
                .map(|profile| profile.url.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
1073
        fn para_id_authorities(para_id: ParaId) -> Option<Vec<NimbusId>> {
1073
            let parent_number = System::block_number();
1073

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

            
1073
            if para_id == self_para_id {
1065
                Some(assigned_authorities.orchestrator_chain)
            } else {
8
                assigned_authorities.container_chains.get(&para_id).cloned()
            }
1073
        }
        /// 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

            
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

            
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,
                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
        }
    };
}