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
#[cfg(feature = "std")]
26
use sp_version::NativeVersion;
27
use {
28
    pallet_services_payment::ProvideCollatorAssignmentCost,
29
    polkadot_runtime_common::SlowAdjustingFeeUpdate,
30
};
31

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

            
35
pub mod weights;
36

            
37
use {
38
    cumulus_pallet_parachain_system::RelayNumberStrictlyIncreases,
39
    cumulus_primitives_core::{relay_chain::SessionIndex, BodyId, ParaId},
40
    frame_support::{
41
        construct_runtime,
42
        dispatch::{DispatchClass, DispatchErrorWithPostInfo},
43
        genesis_builder_helper::{build_state, get_preset},
44
        pallet_prelude::DispatchResult,
45
        parameter_types,
46
        traits::{
47
            fungible::{Balanced, Credit, Inspect, InspectHold, Mutate, MutateHold},
48
            tokens::{
49
                imbalance::ResolveTo, PayFromAccount, Precision, Preservation,
50
                UnityAssetBalanceConversion,
51
            },
52
            ConstBool, ConstU128, ConstU32, ConstU64, ConstU8, Contains, EitherOfDiverse,
53
            Imbalance, InsideBoth, InstanceFilter, OnUnbalanced,
54
        },
55
        weights::{
56
            constants::{
57
                BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight,
58
                WEIGHT_REF_TIME_PER_SECOND,
59
            },
60
            ConstantMultiplier, Weight, WeightToFeeCoefficient, WeightToFeeCoefficients,
61
            WeightToFeePolynomial,
62
        },
63
        PalletId,
64
    },
65
    frame_system::{
66
        limits::{BlockLength, BlockWeights},
67
        EnsureNever, EnsureRoot,
68
    },
69
    nimbus_primitives::{NimbusId, SlotBeacon},
70
    pallet_balances::NegativeImbalance,
71
    pallet_invulnerables::InvulnerableRewardDistribution,
72
    pallet_registrar::RegistrarHooks,
73
    pallet_registrar_runtime_api::ContainerChainGenesisData,
74
    pallet_services_payment::ProvideBlockProductionCost,
75
    pallet_session::{SessionManager, ShouldEndSession},
76
    pallet_stream_payment_runtime_api::{StreamPaymentApiError, StreamPaymentApiStatus},
77
    pallet_transaction_payment::FungibleAdapter,
78
    polkadot_runtime_common::BlockHashCount,
79
    scale_info::{prelude::format, TypeInfo},
80
    smallvec::smallvec,
81
    sp_api::impl_runtime_apis,
82
    sp_consensus_slots::{Slot, SlotDuration},
83
    sp_core::{crypto::KeyTypeId, Decode, Encode, Get, MaxEncodedLen, OpaqueMetadata, H256},
84
    sp_runtime::{
85
        create_runtime_str, generic, impl_opaque_keys,
86
        traits::{
87
            AccountIdConversion, AccountIdLookup, BlakeTwo256, Block as BlockT, IdentityLookup,
88
            Verify,
89
        },
90
        transaction_validity::{TransactionSource, TransactionValidity},
91
        AccountId32, ApplyExtrinsicResult, RuntimeDebug,
92
    },
93
    sp_std::{collections::btree_set::BTreeSet, marker::PhantomData, prelude::*},
94
    sp_version::RuntimeVersion,
95
    tp_traits::{
96
        GetContainerChainAuthor, GetHostConfiguration, GetSessionContainerChains,
97
        RelayStorageRootProvider, RemoveInvulnerables, RemoveParaIdsWithNoCredits,
98
        ShouldRotateAllCollators,
99
    },
100
};
101
pub use {
102
    dp_core::{AccountId, Address, Balance, BlockNumber, Hash, Header, Index, Signature},
103
    sp_runtime::{MultiAddress, Perbill, Permill},
104
};
105

            
106
/// Block type as expected by this runtime.
107
pub type Block = generic::Block<Header, UncheckedExtrinsic>;
108
/// A Block signed with a Justification
109
pub type SignedBlock = generic::SignedBlock<Block>;
110
/// BlockId type as expected by this runtime.
111
pub type BlockId = generic::BlockId<Block>;
112

            
113
/// CollatorId type expected by this runtime.
114
pub type CollatorId = AccountId;
115

            
116
/// The SignedExtension to the basic transaction logic.
117
pub type SignedExtra = (
118
    frame_system::CheckNonZeroSender<Runtime>,
119
    frame_system::CheckSpecVersion<Runtime>,
120
    frame_system::CheckTxVersion<Runtime>,
121
    frame_system::CheckGenesis<Runtime>,
122
    frame_system::CheckEra<Runtime>,
123
    frame_system::CheckNonce<Runtime>,
124
    frame_system::CheckWeight<Runtime>,
125
    pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
126
    cumulus_primitives_storage_weight_reclaim::StorageWeightReclaim<Runtime>,
127
);
128

            
129
/// Unchecked extrinsic type as expected by this runtime.
130
pub type UncheckedExtrinsic =
131
    generic::UncheckedExtrinsic<Address, RuntimeCall, Signature, SignedExtra>;
132

            
133
/// Extrinsic type that has already been checked.
134
pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, RuntimeCall, SignedExtra>;
135

            
136
/// Executive: handles dispatch to the various modules.
137
pub type Executive = frame_executive::Executive<
138
    Runtime,
139
    Block,
140
    frame_system::ChainContext<Runtime>,
141
    Runtime,
142
    AllPalletsWithSystem,
143
>;
144

            
145
/// DANCE, the native token, uses 12 decimals of precision.
146
pub mod currency {
147
    use super::Balance;
148

            
149
    // Provide a common factor between runtimes based on a supply of 10_000_000 tokens.
150
    pub const SUPPLY_FACTOR: Balance = 100;
151

            
152
    pub const MICRODANCE: Balance = 1_000_000;
153
    pub const MILLIDANCE: Balance = 1_000_000_000;
154
    pub const DANCE: Balance = 1_000_000_000_000;
155
    pub const KILODANCE: Balance = 1_000_000_000_000_000;
156

            
157
    pub const STORAGE_BYTE_FEE: Balance = 100 * MICRODANCE * SUPPLY_FACTOR;
158
    pub const STORAGE_ITEM_FEE: Balance = 100 * MILLIDANCE * SUPPLY_FACTOR;
159

            
160
2
    pub const fn deposit(items: u32, bytes: u32) -> Balance {
161
2
        items as Balance * STORAGE_ITEM_FEE + (bytes as Balance) * STORAGE_BYTE_FEE
162
2
    }
163
}
164

            
165
/// Handles converting a weight scalar to a fee value, based on the scale and granularity of the
166
/// node's balance type.
167
///
168
/// This should typically create a mapping between the following ranges:
169
///   - `[0, MAXIMUM_BLOCK_WEIGHT]`
170
///   - `[Balance::min, Balance::max]`
171
///
172
/// Yet, it can be used for any other sort of change to weight-fee. Some examples being:
173
///   - Setting it to `0` will essentially disable the weight fee.
174
///   - Setting it to `1` will cause the literal `#[weight = x]` values to be charged.
175
pub struct WeightToFee;
176
impl WeightToFeePolynomial for WeightToFee {
177
    type Balance = Balance;
178
    fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {
179
        // in Rococo, extrinsic base weight (smallest non-zero weight) is mapped to 1 MILLIUNIT:
180
        // in our template, we map to 1/10 of that, or 1/10 MILLIUNIT
181
        let p = MILLIUNIT / 10;
182
        let q = 100 * Balance::from(ExtrinsicBaseWeight::get().ref_time());
183
        smallvec![WeightToFeeCoefficient {
184
            degree: 1,
185
            negative: false,
186
            coeff_frac: Perbill::from_rational(p % q, q),
187
            coeff_integer: p / q,
188
        }]
189
    }
190
}
191

            
192
/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know
193
/// the specifics of the runtime. They can then be made to be agnostic over specific formats
194
/// of data like extrinsics, allowing for them to continue syncing the network through upgrades
195
/// to even the core data structures.
196
pub mod opaque {
197
    use {
198
        super::*,
199
        sp_runtime::{generic, traits::BlakeTwo256},
200
    };
201

            
202
    pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;
203
    /// Opaque block header type.
204
    pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
205
    /// Opaque block type.
206
    pub type Block = generic::Block<Header, UncheckedExtrinsic>;
207
    /// Opaque block identifier type.
208
    pub type BlockId = generic::BlockId<Block>;
209
}
210

            
211
impl_opaque_keys! {
212
    pub struct SessionKeys {
213
        pub nimbus: Initializer,
214
    }
215
}
216

            
217
#[sp_version::runtime_version]
218
pub const VERSION: RuntimeVersion = RuntimeVersion {
219
    spec_name: create_runtime_str!("flashbox"),
220
    impl_name: create_runtime_str!("flashbox"),
221
    authoring_version: 1,
222
    spec_version: 800,
223
    impl_version: 0,
224
    apis: RUNTIME_API_VERSIONS,
225
    transaction_version: 1,
226
    state_version: 1,
227
};
228

            
229
/// This determines the average expected block time that we are targeting.
230
/// Blocks will be produced at a minimum duration defined by `SLOT_DURATION`.
231
/// `SLOT_DURATION` is picked up by `pallet_timestamp` which is in turn picked
232
/// up by `pallet_aura` to implement `fn slot_duration()`.
233
///
234
/// Change this to adjust the block time.
235
pub const MILLISECS_PER_BLOCK: u64 = 6000;
236

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

            
241
// Time is measured by number of blocks.
242
pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);
243
pub const HOURS: BlockNumber = MINUTES * 60;
244
pub const DAYS: BlockNumber = HOURS * 24;
245

            
246
// Unit = the base number of indivisible units for balances
247
pub const UNIT: Balance = 1_000_000_000_000;
248
pub const MILLIUNIT: Balance = 1_000_000_000;
249
pub const MICROUNIT: Balance = 1_000_000;
250

            
251
/// The existential deposit. Set to 1/10 of the Connected Relay Chain.
252
pub const EXISTENTIAL_DEPOSIT: Balance = MILLIUNIT;
253

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

            
258
/// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used by
259
/// `Operational` extrinsics.
260
const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);
261

            
262
/// We allow for 0.5 of a second of compute with a 12 second average block time.
263
const MAXIMUM_BLOCK_WEIGHT: Weight = Weight::from_parts(
264
    WEIGHT_REF_TIME_PER_SECOND.saturating_div(2),
265
    cumulus_primitives_core::relay_chain::MAX_POV_SIZE as u64,
266
);
267

            
268
/// The version information used to identify this runtime when compiled natively.
269
#[cfg(feature = "std")]
270
pub fn native_version() -> NativeVersion {
271
    NativeVersion {
272
        runtime_version: VERSION,
273
        can_author_with: Default::default(),
274
    }
275
}
276

            
277
parameter_types! {
278
    pub const Version: RuntimeVersion = VERSION;
279

            
280
    // This part is copied from Substrate's `bin/node/runtime/src/lib.rs`.
281
    //  The `RuntimeBlockLength` and `RuntimeBlockWeights` exist here because the
282
    // `DeletionWeightLimit` and `DeletionQueueDepth` depend on those to parameterize
283
    // the lazy contract deletion.
284
    pub RuntimeBlockLength: BlockLength =
285
        BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);
286
    pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()
287
        .base_block(BlockExecutionWeight::get())
288
6630
        .for_class(DispatchClass::all(), |weights| {
289
6630
            weights.base_extrinsic = ExtrinsicBaseWeight::get();
290
6630
        })
291
2210
        .for_class(DispatchClass::Normal, |weights| {
292
2210
            weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);
293
2210
        })
294
2210
        .for_class(DispatchClass::Operational, |weights| {
295
2210
            weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);
296
2210
            // Operational transactions have some extra reserved space, so that they
297
2210
            // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.
298
2210
            weights.reserved = Some(
299
2210
                MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT
300
2210
            );
301
2210
        })
302
        .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)
303
        .build_or_panic();
304
    pub const SS58Prefix: u16 = 42;
305
}
306

            
307
// Configure FRAME pallets to include in runtime.
308

            
309
impl frame_system::Config for Runtime {
310
    /// The identifier used to distinguish between accounts.
311
    type AccountId = AccountId;
312
    /// The aggregated dispatch type that is available for extrinsics.
313
    type RuntimeCall = RuntimeCall;
314
    /// The lookup mechanism to get account ID from whatever is passed in dispatchers.
315
    type Lookup = AccountIdLookup<AccountId, ()>;
316
    /// The index type for storing how many extrinsics an account has signed.
317
    type Nonce = Index;
318
    /// The index type for blocks.
319
    type Block = Block;
320
    /// The type for hashing blocks and tries.
321
    type Hash = Hash;
322
    /// The hashing algorithm used.
323
    type Hashing = BlakeTwo256;
324
    /// The ubiquitous event type.
325
    type RuntimeEvent = RuntimeEvent;
326
    /// The ubiquitous origin type.
327
    type RuntimeOrigin = RuntimeOrigin;
328
    /// Maximum number of block number to block hash mappings to keep (oldest pruned first).
329
    type BlockHashCount = BlockHashCount;
330
    /// Runtime version.
331
    type Version = Version;
332
    /// Converts a module to an index of this module in the runtime.
333
    type PalletInfo = PalletInfo;
334
    /// The data to be stored in an account.
335
    type AccountData = pallet_balances::AccountData<Balance>;
336
    /// What to do if a new account is created.
337
    type OnNewAccount = ();
338
    /// What to do if an account is fully reaped from the system.
339
    type OnKilledAccount = ();
340
    /// The weight of database operations that the runtime can invoke.
341
    type DbWeight = RocksDbWeight;
342
    /// The basic call filter to use in dispatchable.
343
    type BaseCallFilter = InsideBoth<MaintenanceMode, TxPause>;
344
    /// Weight information for the extrinsics of this pallet.
345
    type SystemWeightInfo = weights::frame_system::SubstrateWeight<Runtime>;
346
    /// Block & extrinsics weights: base values and limits.
347
    type BlockWeights = RuntimeBlockWeights;
348
    /// The maximum length of a block (in bytes).
349
    type BlockLength = RuntimeBlockLength;
350
    /// This is used as an identifier of the chain. 42 is the generic substrate prefix.
351
    type SS58Prefix = SS58Prefix;
352
    /// The action to take on a Runtime Upgrade
353
    type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;
354
    type MaxConsumers = frame_support::traits::ConstU32<16>;
355
    type RuntimeTask = RuntimeTask;
356
    type SingleBlockMigrations = ();
357
    type MultiBlockMigrator = ();
358
    type PreInherents = ();
359
    type PostInherents = ();
360
    type PostTransactions = ();
361
}
362

            
363
impl pallet_timestamp::Config for Runtime {
364
    /// A timestamp: milliseconds since the unix epoch.
365
    type Moment = u64;
366
    type OnTimestampSet = dp_consensus::OnTimestampSet<
367
        <Self as pallet_author_inherent::Config>::SlotBeacon,
368
        ConstU64<{ SLOT_DURATION }>,
369
    >;
370
    type MinimumPeriod = ConstU64<{ SLOT_DURATION / 2 }>;
371
    type WeightInfo = weights::pallet_timestamp::SubstrateWeight<Runtime>;
372
}
373

            
374
pub struct CanAuthor;
375
impl nimbus_primitives::CanAuthor<NimbusId> for CanAuthor {
376
2136
    fn can_author(author: &NimbusId, slot: &u32) -> bool {
377
2136
        let authorities = AuthorityAssignment::collator_container_chain(Session::current_index())
378
2136
            .expect("authorities should be set")
379
2136
            .orchestrator_chain;
380
2136

            
381
2136
        if authorities.is_empty() {
382
            return false;
383
2136
        }
384
2136

            
385
2136
        let author_index = (*slot as usize) % authorities.len();
386
2136
        let expected_author = &authorities[author_index];
387
2136

            
388
2136
        expected_author == author
389
2136
    }
390
    #[cfg(feature = "runtime-benchmarks")]
391
    fn get_authors(_slot: &u32) -> Vec<NimbusId> {
392
        AuthorityAssignment::collator_container_chain(Session::current_index())
393
            .expect("authorities should be set")
394
            .orchestrator_chain
395
    }
396
}
397

            
398
impl pallet_author_inherent::Config for Runtime {
399
    type AuthorId = NimbusId;
400
    type AccountLookup = dp_consensus::NimbusLookUp;
401
    type CanAuthor = CanAuthor;
402
    type SlotBeacon = dp_consensus::AuraDigestSlotBeacon<Runtime>;
403
    type WeightInfo = weights::pallet_author_inherent::SubstrateWeight<Runtime>;
404
}
405

            
406
parameter_types! {
407
    pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT;
408
}
409

            
410
impl pallet_balances::Config for Runtime {
411
    type MaxLocks = ConstU32<50>;
412
    /// The type for recording an account's balance.
413
    type Balance = Balance;
414
    /// The ubiquitous event type.
415
    type RuntimeEvent = RuntimeEvent;
416
    type DustRemoval = ();
417
    type ExistentialDeposit = ExistentialDeposit;
418
    type AccountStore = System;
419
    type MaxReserves = ConstU32<50>;
420
    type ReserveIdentifier = [u8; 8];
421
    type FreezeIdentifier = RuntimeFreezeReason;
422
    type MaxFreezes = ConstU32<10>;
423
    type RuntimeHoldReason = RuntimeHoldReason;
424
    type RuntimeFreezeReason = RuntimeFreezeReason;
425
    type WeightInfo = weights::pallet_balances::SubstrateWeight<Runtime>;
426
}
427

            
428
pub struct DealWithFees<R>(sp_std::marker::PhantomData<R>);
429
impl<R> OnUnbalanced<Credit<R::AccountId, pallet_balances::Pallet<R>>> for DealWithFees<R>
430
where
431
    R: pallet_balances::Config + pallet_treasury::Config + frame_system::Config,
432
    pallet_treasury::NegativeImbalanceOf<R>: From<NegativeImbalance<R>>,
433
{
434
    // this seems to be called for substrate-based transactions
435
    fn on_unbalanceds<B>(
436
        mut fees_then_tips: impl Iterator<Item = Credit<R::AccountId, pallet_balances::Pallet<R>>>,
437
    ) {
438
        if let Some(fees) = fees_then_tips.next() {
439
            // 80% is burned, 20% goes to the treasury
440
            // Same policy applies for tips as well
441
            let burn_percentage = 80;
442
            let treasury_percentage = 20;
443

            
444
            let (_, to_treasury) = fees.ration(burn_percentage, treasury_percentage);
445
            ResolveTo::<pallet_treasury::TreasuryAccountId<R>, pallet_balances::Pallet<R>>::on_unbalanced(to_treasury);
446
            // Balances pallet automatically burns dropped Negative Imbalances by decreasing total_supply accordingly
447
            // We need to convert the new Credit type to a negative imbalance
448
            // handle tip if there is one
449
            if let Some(tip) = fees_then_tips.next() {
450
                let (_, to_treasury) = tip.ration(burn_percentage, treasury_percentage);
451
                ResolveTo::<pallet_treasury::TreasuryAccountId<R>, pallet_balances::Pallet<R>>::on_unbalanced(to_treasury);
452
            }
453
        }
454
    }
455

            
456
    // this is called from pallet_evm for Ethereum-based transactions
457
    // (technically, it calls on_unbalanced, which calls this when non-zero)
458
    fn on_nonzero_unbalanced(amount: Credit<R::AccountId, pallet_balances::Pallet<R>>) {
459
        // 80% is burned, 20% goes to the treasury
460
        let burn_percentage = 80;
461
        let treasury_percentage = 20;
462

            
463
        let (_, to_treasury) = amount.ration(burn_percentage, treasury_percentage);
464
        ResolveTo::<pallet_treasury::TreasuryAccountId<R>, pallet_balances::Pallet<R>>::on_unbalanced(to_treasury);
465
    }
466
}
467

            
468
parameter_types! {
469
    pub const TransactionByteFee: Balance = 1;
470
}
471

            
472
impl pallet_transaction_payment::Config for Runtime {
473
    type RuntimeEvent = RuntimeEvent;
474
    // This will burn the fees
475
    type OnChargeTransaction = FungibleAdapter<Balances, DealWithFees<Runtime>>;
476
    type OperationalFeeMultiplier = ConstU8<5>;
477
    type WeightToFee = WeightToFee;
478
    type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;
479
    type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Self>;
480
}
481

            
482
pub const RELAY_CHAIN_SLOT_DURATION_MILLIS: u32 = 6000;
483
pub const UNINCLUDED_SEGMENT_CAPACITY: u32 = 3;
484
pub const BLOCK_PROCESSING_VELOCITY: u32 = 1;
485

            
486
type ConsensusHook = pallet_async_backing::consensus_hook::FixedVelocityConsensusHook<
487
    Runtime,
488
    BLOCK_PROCESSING_VELOCITY,
489
    UNINCLUDED_SEGMENT_CAPACITY,
490
>;
491

            
492
impl cumulus_pallet_parachain_system::Config for Runtime {
493
    type WeightInfo = weights::cumulus_pallet_parachain_system::SubstrateWeight<Runtime>;
494
    type RuntimeEvent = RuntimeEvent;
495
    type OnSystemEvent = ();
496
    type SelfParaId = parachain_info::Pallet<Runtime>;
497
    type OutboundXcmpMessageSource = ();
498
    // Ignore all DMP messages by enqueueing them into `()`:
499
    type DmpQueue = frame_support::traits::EnqueueWithOrigin<(), sp_core::ConstU8<0>>;
500
    type ReservedDmpWeight = ();
501
    type XcmpMessageHandler = ();
502
    type ReservedXcmpWeight = ();
503
    type CheckAssociatedRelayNumber = RelayNumberStrictlyIncreases;
504
    type ConsensusHook = ConsensusHook;
505
}
506

            
507
pub struct ParaSlotProvider;
508
impl Get<(Slot, SlotDuration)> for ParaSlotProvider {
509
128
    fn get() -> (Slot, SlotDuration) {
510
128
        let slot = u64::from(<Runtime as pallet_author_inherent::Config>::SlotBeacon::slot());
511
128
        (Slot::from(slot), SlotDuration::from_millis(SLOT_DURATION))
512
128
    }
513
}
514

            
515
parameter_types! {
516
    pub const ExpectedBlockTime: u64 = MILLISECS_PER_BLOCK;
517
}
518

            
519
impl pallet_async_backing::Config for Runtime {
520
    type AllowMultipleBlocksPerSlot = ConstBool<true>;
521
    type GetAndVerifySlot =
522
        pallet_async_backing::ParaSlot<RELAY_CHAIN_SLOT_DURATION_MILLIS, ParaSlotProvider>;
523
    type ExpectedBlockTime = ExpectedBlockTime;
524
}
525

            
526
pub struct OwnApplySession;
527
impl pallet_initializer::ApplyNewSession<Runtime> for OwnApplySession {
528
323
    fn apply_new_session(
529
323
        _changed: bool,
530
323
        session_index: u32,
531
323
        all_validators: Vec<(AccountId, NimbusId)>,
532
323
        queued: Vec<(AccountId, NimbusId)>,
533
323
    ) {
534
323
        // We first initialize Configuration
535
323
        Configuration::initializer_on_new_session(&session_index);
536
323
        // Next: Registrar
537
323
        Registrar::initializer_on_new_session(&session_index);
538
323
        // Next: AuthorityMapping
539
323
        AuthorityMapping::initializer_on_new_session(&session_index, &all_validators);
540
323

            
541
1071
        let next_collators = queued.iter().map(|(k, _)| k.clone()).collect();
542
323

            
543
323
        // Next: CollatorAssignment
544
323
        let assignments =
545
323
            CollatorAssignment::initializer_on_new_session(&session_index, next_collators);
546
323

            
547
323
        let queued_id_to_nimbus_map = queued.iter().cloned().collect();
548
323
        AuthorityAssignment::initializer_on_new_session(
549
323
            &session_index,
550
323
            &queued_id_to_nimbus_map,
551
323
            &assignments.next_assignment,
552
323
        );
553
323
    }
554
}
555

            
556
impl pallet_initializer::Config for Runtime {
557
    type SessionIndex = u32;
558

            
559
    /// The identifier type for an authority.
560
    type AuthorityId = NimbusId;
561

            
562
    type SessionHandler = OwnApplySession;
563
}
564

            
565
impl parachain_info::Config for Runtime {}
566

            
567
pub struct CollatorsFromInvulnerables;
568

            
569
/// Play the role of the session manager.
570
impl SessionManager<CollatorId> for CollatorsFromInvulnerables {
571
452
    fn new_session(index: SessionIndex) -> Option<Vec<CollatorId>> {
572
452
        log::info!(
573
            "assembling new collators for new session {} at #{:?}",
574
            index,
575
            <frame_system::Pallet<Runtime>>::block_number(),
576
        );
577

            
578
452
        let invulnerables = Invulnerables::invulnerables().to_vec();
579
452
        let target_session_index = index.saturating_add(1);
580
452
        let max_collators =
581
452
            <Configuration as GetHostConfiguration<u32>>::max_collators(target_session_index);
582
452
        let collators = invulnerables
583
452
            .iter()
584
452
            .take(max_collators as usize)
585
452
            .cloned()
586
452
            .collect();
587
452

            
588
452
        Some(collators)
589
452
    }
590
323
    fn start_session(_: SessionIndex) {
591
323
        // we don't care.
592
323
    }
593
194
    fn end_session(_: SessionIndex) {
594
194
        // we don't care.
595
194
    }
596
}
597

            
598
parameter_types! {
599
    pub const Period: u32 = prod_or_fast!(5 * MINUTES, 1 * MINUTES);
600
    pub const Offset: u32 = 0;
601
}
602

            
603
impl pallet_session::Config for Runtime {
604
    type RuntimeEvent = RuntimeEvent;
605
    type ValidatorId = <Self as frame_system::Config>::AccountId;
606
    // we don't have stash and controller, thus we don't need the convert as well.
607
    type ValidatorIdOf = pallet_invulnerables::IdentityCollator;
608
    type ShouldEndSession = pallet_session::PeriodicSessions<Period, Offset>;
609
    type NextSessionRotation = pallet_session::PeriodicSessions<Period, Offset>;
610
    type SessionManager = CollatorsFromInvulnerables;
611
    // Essentially just Aura, but let's be pedantic.
612
    type SessionHandler = <SessionKeys as sp_runtime::traits::OpaqueKeys>::KeyTypeIdProviders;
613
    type Keys = SessionKeys;
614
    type WeightInfo = weights::pallet_session::SubstrateWeight<Runtime>;
615
}
616

            
617
pub struct RemoveInvulnerablesImpl;
618

            
619
impl RemoveInvulnerables<CollatorId> for RemoveInvulnerablesImpl {
620
486
    fn remove_invulnerables(
621
486
        collators: &mut Vec<CollatorId>,
622
486
        num_invulnerables: usize,
623
486
    ) -> Vec<CollatorId> {
624
486
        if num_invulnerables == 0 {
625
            return vec![];
626
486
        }
627
486
        // TODO: check if this works on session changes
628
486
        let all_invulnerables = pallet_invulnerables::Invulnerables::<Runtime>::get();
629
486
        if all_invulnerables.is_empty() {
630
            return vec![];
631
486
        }
632
486
        let mut invulnerables = vec![];
633
486
        // TODO: use binary_search when invulnerables are sorted
634
774
        collators.retain(|x| {
635
774
            if invulnerables.len() < num_invulnerables && all_invulnerables.contains(x) {
636
618
                invulnerables.push(x.clone());
637
618
                false
638
            } else {
639
156
                true
640
            }
641
774
        });
642
486

            
643
486
        invulnerables
644
486
    }
645
}
646

            
647
pub struct RemoveParaIdsWithNoCreditsImpl;
648

            
649
impl RemoveParaIdsWithNoCredits for RemoveParaIdsWithNoCreditsImpl {
650
646
    fn remove_para_ids_with_no_credits(
651
646
        para_ids: &mut Vec<ParaId>,
652
646
        currently_assigned: &BTreeSet<ParaId>,
653
646
    ) {
654
646
        let blocks_per_session = Period::get();
655
646

            
656
646
        para_ids.retain(|para_id| {
657
            // If the para has been assigned collators for this session it must have enough block credits
658
            // for the current and the next session.
659
386
            let block_credits_needed = if currently_assigned.contains(para_id) {
660
206
                blocks_per_session * 2
661
            } else {
662
180
                blocks_per_session
663
            };
664

            
665
            // Check if the container chain has enough credits for producing blocks
666
386
            let free_block_credits = pallet_services_payment::BlockProductionCredits::<Runtime>::get(para_id)
667
386
                .unwrap_or_default();
668
386

            
669
386
            // Check if the container chain has enough credits for a session assignments
670
386
            let free_session_credits = pallet_services_payment::CollatorAssignmentCredits::<Runtime>::get(para_id)
671
386
                .unwrap_or_default();
672
386

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

            
676
386
            // Return if we can survive with free credits
677
386
            if free_block_credits >= block_credits_needed && free_session_credits >= 1 {
678
                // Max tip should always be checked, as it can be withdrawn even if free credits were used
679
322
                return Balances::can_withdraw(&pallet_services_payment::Pallet::<Runtime>::parachain_tank(*para_id), max_tip).into_result(true).is_ok()
680
64
            }
681
64

            
682
64
            let remaining_block_credits = block_credits_needed.saturating_sub(free_block_credits);
683
64
            let remaining_session_credits = 1u32.saturating_sub(free_session_credits);
684
64

            
685
64
            let (block_production_costs, _) = <Runtime as pallet_services_payment::Config>::ProvideBlockProductionCost::block_cost(para_id);
686
64
            let (collator_assignment_costs, _) = <Runtime as pallet_services_payment::Config>::ProvideCollatorAssignmentCost::collator_assignment_cost(para_id);
687
64
            // let's check if we can withdraw
688
64
            let remaining_block_credits_to_pay = u128::from(remaining_block_credits).saturating_mul(block_production_costs);
689
64
            let remaining_session_credits_to_pay = u128::from(remaining_session_credits).saturating_mul(collator_assignment_costs);
690
64

            
691
64
            let remaining_to_pay = remaining_block_credits_to_pay.saturating_add(remaining_session_credits_to_pay).saturating_add(max_tip);
692
64

            
693
64
            // This should take into account whether we tank goes below ED
694
64
            // The true refers to keepAlive
695
64
            Balances::can_withdraw(&pallet_services_payment::Pallet::<Runtime>::parachain_tank(*para_id), remaining_to_pay).into_result(true).is_ok()
696
646
        });
697
646
    }
698

            
699
    /// Make those para ids valid by giving them enough credits, for benchmarking.
700
    #[cfg(feature = "runtime-benchmarks")]
701
    fn make_valid_para_ids(para_ids: &[ParaId]) {
702
        use frame_support::assert_ok;
703

            
704
        let blocks_per_session = Period::get();
705
        // Enough credits to run any benchmark
706
        let block_credits = 20 * blocks_per_session;
707
        let session_credits = 20;
708

            
709
        for para_id in para_ids {
710
            assert_ok!(ServicesPayment::set_block_production_credits(
711
                RuntimeOrigin::root(),
712
                *para_id,
713
                block_credits,
714
            ));
715
            assert_ok!(ServicesPayment::set_collator_assignment_credits(
716
                RuntimeOrigin::root(),
717
                *para_id,
718
                session_credits,
719
            ));
720
        }
721
    }
722
}
723

            
724
pub struct NeverRotateCollators;
725

            
726
impl ShouldRotateAllCollators<u32> for NeverRotateCollators {
727
323
    fn should_rotate_all_collators(_: u32) -> bool {
728
323
        false
729
323
    }
730
}
731

            
732
impl pallet_collator_assignment::Config for Runtime {
733
    type RuntimeEvent = RuntimeEvent;
734
    type HostConfiguration = Configuration;
735
    type ContainerChains = Registrar;
736
    type SessionIndex = u32;
737
    type SelfParaId = ParachainInfo;
738
    type ShouldRotateAllCollators = NeverRotateCollators;
739
    type GetRandomnessForNextBlock = ();
740
    type RemoveInvulnerables = RemoveInvulnerablesImpl;
741
    type RemoveParaIdsWithNoCredits = RemoveParaIdsWithNoCreditsImpl;
742
    type CollatorAssignmentHook = ServicesPayment;
743
    type CollatorAssignmentTip = ServicesPayment;
744
    type Currency = Balances;
745
    type WeightInfo = weights::pallet_collator_assignment::SubstrateWeight<Runtime>;
746
}
747

            
748
impl pallet_authority_assignment::Config for Runtime {
749
    type SessionIndex = u32;
750
    type AuthorityId = NimbusId;
751
}
752

            
753
pub const FIXED_BLOCK_PRODUCTION_COST: u128 = 1 * currency::MICRODANCE;
754
pub const FIXED_COLLATOR_ASSIGNMENT_COST: u128 = 100 * currency::MICRODANCE;
755

            
756
pub struct BlockProductionCost<Runtime>(PhantomData<Runtime>);
757
impl ProvideBlockProductionCost<Runtime> for BlockProductionCost<Runtime> {
758
100
    fn block_cost(_para_id: &ParaId) -> (u128, Weight) {
759
100
        (FIXED_BLOCK_PRODUCTION_COST, Weight::zero())
760
100
    }
761
}
762

            
763
pub struct CollatorAssignmentCost<Runtime>(PhantomData<Runtime>);
764
impl ProvideCollatorAssignmentCost<Runtime> for CollatorAssignmentCost<Runtime> {
765
80
    fn collator_assignment_cost(_para_id: &ParaId) -> (u128, Weight) {
766
80
        (FIXED_COLLATOR_ASSIGNMENT_COST, Weight::zero())
767
80
    }
768
}
769

            
770
parameter_types! {
771
    // 60 days worth of blocks
772
    pub const FreeBlockProductionCredits: BlockNumber = 60 * DAYS;
773
    // 60 days worth of blocks
774
    pub const FreeCollatorAssignmentCredits: u32 = FreeBlockProductionCredits::get()/Period::get();
775
}
776

            
777
impl pallet_services_payment::Config for Runtime {
778
    type RuntimeEvent = RuntimeEvent;
779
    /// Handler for fees
780
    type OnChargeForBlock = ();
781
    type OnChargeForCollatorAssignment = ();
782
    type OnChargeForCollatorAssignmentTip = ();
783
    /// Currency type for fee payment
784
    type Currency = Balances;
785
    /// Provider of a block cost which can adjust from block to block
786
    type ProvideBlockProductionCost = BlockProductionCost<Runtime>;
787
    /// Provider of a block cost which can adjust from block to block
788
    type ProvideCollatorAssignmentCost = CollatorAssignmentCost<Runtime>;
789
    /// The maximum number of block credits that can be accumulated
790
    type FreeBlockProductionCredits = FreeBlockProductionCredits;
791
    /// The maximum number of session credits that can be accumulated
792
    type FreeCollatorAssignmentCredits = FreeCollatorAssignmentCredits;
793
    type ManagerOrigin =
794
        EitherOfDiverse<pallet_registrar::EnsureSignedByManager<Runtime>, EnsureRoot<AccountId>>;
795
    type WeightInfo = weights::pallet_services_payment::SubstrateWeight<Runtime>;
796
}
797

            
798
parameter_types! {
799
    pub const ProfileDepositBaseFee: Balance = currency::STORAGE_ITEM_FEE;
800
    pub const ProfileDepositByteFee: Balance = currency::STORAGE_BYTE_FEE;
801
    #[derive(Clone)]
802
    pub const MaxAssignmentsPerParaId: u32 = 10;
803
    #[derive(Clone)]
804
    pub const MaxNodeUrlLen: u32 = 200;
805
}
806

            
807
#[derive(
808
    RuntimeDebug,
809
    PartialEq,
810
    Eq,
811
    Encode,
812
    Decode,
813
    Copy,
814
    Clone,
815
    TypeInfo,
816
    serde::Serialize,
817
    serde::Deserialize,
818
)]
819
pub enum PreserversAssignementPaymentRequest {
820
71
    Free,
821
    // TODO: Add Stream Payment (with config)
822
}
823

            
824
#[derive(
825
    RuntimeDebug,
826
    PartialEq,
827
    Eq,
828
    Encode,
829
    Decode,
830
    Copy,
831
    Clone,
832
    TypeInfo,
833
    serde::Serialize,
834
    serde::Deserialize,
835
)]
836
pub enum PreserversAssignementPaymentExtra {
837
    Free,
838
    // TODO: Add Stream Payment (with deposit)
839
}
840

            
841
#[derive(
842
    RuntimeDebug,
843
    PartialEq,
844
    Eq,
845
    Encode,
846
    Decode,
847
    Copy,
848
    Clone,
849
    TypeInfo,
850
    serde::Serialize,
851
    serde::Deserialize,
852
)]
853
pub enum PreserversAssignementPaymentWitness {
854
46
    Free,
855
    // TODO: Add Stream Payment (with stream id)
856
}
857

            
858
pub struct PreserversAssignementPayment;
859

            
860
impl pallet_data_preservers::AssignmentPayment<AccountId> for PreserversAssignementPayment {
861
    /// Providers requests which kind of payment it accepts.
862
    type ProviderRequest = PreserversAssignementPaymentRequest;
863
    /// Extra parameter the assigner provides.
864
    type AssignerParameter = PreserversAssignementPaymentExtra;
865
    /// Represents the succesful outcome of the assignment.
866
    type AssignmentWitness = PreserversAssignementPaymentWitness;
867

            
868
42
    fn try_start_assignment(
869
42
        _assigner: AccountId,
870
42
        _provider: AccountId,
871
42
        request: &Self::ProviderRequest,
872
42
        extra: Self::AssignerParameter,
873
42
    ) -> Result<Self::AssignmentWitness, DispatchErrorWithPostInfo> {
874
42
        let witness = match (request, extra) {
875
42
            (Self::ProviderRequest::Free, Self::AssignerParameter::Free) => {
876
42
                Self::AssignmentWitness::Free
877
42
            }
878
42
        };
879
42

            
880
42
        Ok(witness)
881
42
    }
882

            
883
    fn try_stop_assignment(
884
        _provider: AccountId,
885
        witness: Self::AssignmentWitness,
886
    ) -> Result<(), DispatchErrorWithPostInfo> {
887
        match witness {
888
            Self::AssignmentWitness::Free => (),
889
        }
890

            
891
        Ok(())
892
    }
893

            
894
    /// Return the values for a free assignment if it is supported.
895
    /// This is required to perform automatic migration from old Bootnodes storage.
896
2
    fn free_variant_values() -> Option<(
897
2
        Self::ProviderRequest,
898
2
        Self::AssignerParameter,
899
2
        Self::AssignmentWitness,
900
2
    )> {
901
2
        Some((
902
2
            Self::ProviderRequest::Free,
903
2
            Self::AssignerParameter::Free,
904
2
            Self::AssignmentWitness::Free,
905
2
        ))
906
2
    }
907

            
908
    // The values returned by the following functions should match with each other.
909
    #[cfg(feature = "runtime-benchmarks")]
910
    fn benchmark_provider_request() -> Self::ProviderRequest {
911
        PreserversAssignementPaymentRequest::Free
912
    }
913

            
914
    #[cfg(feature = "runtime-benchmarks")]
915
    fn benchmark_assigner_parameter() -> Self::AssignerParameter {
916
        PreserversAssignementPaymentExtra::Free
917
    }
918

            
919
    #[cfg(feature = "runtime-benchmarks")]
920
    fn benchmark_assignment_witness() -> Self::AssignmentWitness {
921
        PreserversAssignementPaymentWitness::Free
922
    }
923
}
924

            
925
impl pallet_data_preservers::Config for Runtime {
926
    type RuntimeEvent = RuntimeEvent;
927
    type RuntimeHoldReason = RuntimeHoldReason;
928
    type Currency = Balances;
929
    type WeightInfo = weights::pallet_data_preservers::SubstrateWeight<Runtime>;
930

            
931
    type ProfileId = u64;
932
    type ProfileDeposit = tp_traits::BytesDeposit<ProfileDepositBaseFee, ProfileDepositByteFee>;
933
    type AssignmentPayment = PreserversAssignementPayment;
934

            
935
    type AssignmentOrigin = pallet_registrar::EnsureSignedByManager<Runtime>;
936
    type ForceSetProfileOrigin = EnsureRoot<AccountId>;
937

            
938
    type MaxAssignmentsPerParaId = MaxAssignmentsPerParaId;
939
    type MaxNodeUrlLen = MaxNodeUrlLen;
940
    type MaxParaIdsVecLen = MaxLengthParaIds;
941
}
942

            
943
impl pallet_author_noting::Config for Runtime {
944
    type RuntimeEvent = RuntimeEvent;
945
    type ContainerChains = Registrar;
946
    type SelfParaId = parachain_info::Pallet<Runtime>;
947
    type SlotBeacon = dp_consensus::AuraDigestSlotBeacon<Runtime>;
948
    type ContainerChainAuthor = CollatorAssignment;
949
    type RelayChainStateProvider = cumulus_pallet_parachain_system::RelaychainDataProvider<Self>;
950
    // We benchmark each hook individually, so for runtime-benchmarks this should be empty
951
    #[cfg(feature = "runtime-benchmarks")]
952
    type AuthorNotingHook = ();
953
    #[cfg(not(feature = "runtime-benchmarks"))]
954
    type AuthorNotingHook = (InflationRewards, ServicesPayment);
955
    type WeightInfo = weights::pallet_author_noting::SubstrateWeight<Runtime>;
956
}
957

            
958
parameter_types! {
959
    pub const PotId: PalletId = PalletId(*b"PotStake");
960
    pub const MaxCandidates: u32 = 1000;
961
    pub const MinCandidates: u32 = 5;
962
    pub const SessionLength: BlockNumber = 5;
963
    pub const MaxInvulnerables: u32 = 200;
964
    pub const ExecutiveBody: BodyId = BodyId::Executive;
965
}
966

            
967
impl pallet_invulnerables::Config for Runtime {
968
    type RuntimeEvent = RuntimeEvent;
969
    type UpdateOrigin = EnsureRoot<AccountId>;
970
    type MaxInvulnerables = MaxInvulnerables;
971
    type CollatorId = CollatorId;
972
    type CollatorIdOf = pallet_invulnerables::IdentityCollator;
973
    type CollatorRegistration = Session;
974
    type WeightInfo = weights::pallet_invulnerables::SubstrateWeight<Runtime>;
975
    #[cfg(feature = "runtime-benchmarks")]
976
    type Currency = Balances;
977
}
978

            
979
parameter_types! {
980
    #[derive(Clone)]
981
    pub const MaxLengthParaIds: u32 = 200u32;
982
    pub const MaxEncodedGenesisDataSize: u32 = 5_000_000u32; // 5MB
983
}
984

            
985
pub struct CurrentSessionIndexGetter;
986

            
987
impl tp_traits::GetSessionIndex<u32> for CurrentSessionIndexGetter {
988
    /// Returns current session index.
989
82
    fn session_index() -> u32 {
990
82
        Session::current_index()
991
82
    }
992
}
993

            
994
impl pallet_configuration::Config for Runtime {
995
    type SessionDelay = ConstU32<2>;
996
    type SessionIndex = u32;
997
    type CurrentSessionIndex = CurrentSessionIndexGetter;
998
    type AuthorityId = NimbusId;
999
    type WeightInfo = weights::pallet_configuration::SubstrateWeight<Runtime>;
}
pub struct FlashboxRegistrarHooks;
impl RegistrarHooks for FlashboxRegistrarHooks {
42
    fn para_marked_valid_for_collating(para_id: ParaId) -> Weight {
42
        // Give free credits but only once per para id
42
        ServicesPayment::give_free_credits(&para_id)
42
    }
10
    fn para_deregistered(para_id: ParaId) -> Weight {
        // Clear pallet_author_noting storage
10
        if let Err(e) = AuthorNoting::kill_author_data(RuntimeOrigin::root(), para_id) {
            log::warn!(
                "Failed to kill_author_data after para id {} deregistered: {:?}",
                u32::from(para_id),
                e,
            );
10
        }
        // Remove bootnodes from pallet_data_preservers
10
        DataPreservers::para_deregistered(para_id);
10

            
10
        ServicesPayment::para_deregistered(para_id);
10

            
10
        Weight::default()
10
    }
44
    fn check_valid_for_collating(para_id: ParaId) -> DispatchResult {
44
        // To be able to call mark_valid_for_collating, a container chain must have bootnodes
44
        DataPreservers::check_valid_for_collating(para_id)
44
    }
    #[cfg(feature = "runtime-benchmarks")]
    fn benchmarks_ensure_valid_for_collating(para_id: ParaId) {
        use {
            frame_support::traits::EnsureOriginWithArg,
            pallet_data_preservers::{ParaIdsFilter, Profile, ProfileMode},
        };
        let profile = Profile {
            url: b"/ip4/127.0.0.1/tcp/33049/ws/p2p/12D3KooWHVMhQDHBpj9vQmssgyfspYecgV6e3hH1dQVDUkUbCYC9"
                    .to_vec()
                    .try_into()
                    .expect("to fit in BoundedVec"),
            para_ids: ParaIdsFilter::AnyParaId,
            mode: ProfileMode::Bootnode,
            assignment_request: PreserversAssignementPaymentRequest::Free,
        };
        let profile_id = pallet_data_preservers::NextProfileId::<Runtime>::get();
        let profile_owner = AccountId::new([1u8; 32]);
        DataPreservers::force_create_profile(RuntimeOrigin::root(), profile, profile_owner)
            .expect("profile create to succeed");
        let para_manager =
            <Runtime as pallet_data_preservers::Config>::AssignmentOrigin::try_successful_origin(
                &para_id,
            )
            .expect("should be able to get para manager");
        DataPreservers::start_assignment(
            para_manager,
            profile_id,
            para_id,
            PreserversAssignementPaymentExtra::Free,
        )
        .expect("assignement to work");
        assert!(
            pallet_data_preservers::Assignments::<Runtime>::get(para_id).contains(&profile_id),
            "profile should be correctly assigned"
        );
    }
}
pub struct PalletRelayStorageRootProvider;
impl RelayStorageRootProvider for PalletRelayStorageRootProvider {
    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,
        );
    }
}
parameter_types! {
    pub const DepositAmount: Balance = 100 * UNIT;
    pub const MaxLengthTokenSymbol: u32 = 255;
}
impl pallet_registrar::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type RegistrarOrigin = EnsureRoot<AccountId>;
    type MarkValidForCollatingOrigin = EnsureRoot<AccountId>;
    type MaxLengthParaIds = MaxLengthParaIds;
    type MaxGenesisDataSize = MaxEncodedGenesisDataSize;
    type MaxLengthTokenSymbol = MaxLengthTokenSymbol;
    type RegisterWithRelayProofOrigin = EnsureNever<AccountId>;
    type RelayStorageRootProvider = PalletRelayStorageRootProvider;
    type SessionDelay = ConstU32<2>;
    type SessionIndex = u32;
    type CurrentSessionIndex = CurrentSessionIndexGetter;
    type Currency = Balances;
    type DepositAmount = DepositAmount;
    type RegistrarHooks = FlashboxRegistrarHooks;
    type WeightInfo = weights::pallet_registrar::SubstrateWeight<Runtime>;
}
impl pallet_authority_mapping::Config for Runtime {
    type SessionIndex = u32;
    type SessionRemovalBoundary = ConstU32<2>;
    type AuthorityId = NimbusId;
}
impl pallet_sudo::Config for Runtime {
    type RuntimeCall = RuntimeCall;
    type RuntimeEvent = RuntimeEvent;
    type WeightInfo = weights::pallet_sudo::SubstrateWeight<Runtime>;
}
impl pallet_utility::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type RuntimeCall = RuntimeCall;
    type PalletsOrigin = OriginCaller;
    type WeightInfo = weights::pallet_utility::SubstrateWeight<Runtime>;
}
/// The type used to represent the kinds of proxies allowed.
#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))]
#[derive(
    Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, Debug, MaxEncodedLen, TypeInfo,
)]
#[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 {
18
    fn filter(&self, c: &RuntimeCall) -> bool {
18
        // Since proxy filters are respected in all dispatches of the Utility
18
        // pallet, it should never need to be filtered by any proxy.
18
        if let RuntimeCall::Utility(..) = c {
            return true;
18
        }
18

            
18
        match self {
2
            ProxyType::Any => true,
            ProxyType::NonTransfer => {
4
                matches!(
4
                    c,
                    RuntimeCall::System(..)
                        | RuntimeCall::ParachainSystem(..)
                        | RuntimeCall::Timestamp(..)
                        | RuntimeCall::Proxy(..)
                        | RuntimeCall::Registrar(..)
                )
            }
            // We don't have governance yet
2
            ProxyType::Governance => false,
2
            ProxyType::Staking => matches!(c, RuntimeCall::Session(..)),
2
            ProxyType::CancelProxy => matches!(
                c,
                RuntimeCall::Proxy(pallet_proxy::Call::reject_announcement { .. })
            ),
            ProxyType::Balances => {
2
                matches!(c, RuntimeCall::Balances(..))
            }
            ProxyType::Registrar => {
2
                matches!(
2
                    c,
                    RuntimeCall::Registrar(..) | RuntimeCall::DataPreservers(..)
                )
            }
2
            ProxyType::SudoRegistrar => match c {
2
                RuntimeCall::Sudo(pallet_sudo::Call::sudo { call: ref x }) => {
2
                    matches!(
2
                        x.as_ref(),
                        &RuntimeCall::Registrar(..) | &RuntimeCall::DataPreservers(..)
                    )
                }
                _ => false,
            },
        }
18
    }
    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>;
}
impl pallet_migrations::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type MigrationsList = (tanssi_runtime_common::migrations::FlashboxMigrations<Runtime>,);
    type XcmExecutionManager = ();
}
/// 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(..)
        )
    }
}
/// Normal Call Filter
pub struct NormalFilter;
impl Contains<RuntimeCall> for NormalFilter {
162
    fn contains(_c: &RuntimeCall) -> bool {
162
        true
162
    }
}
impl pallet_maintenance_mode::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type NormalCallFilter = NormalFilter;
    type MaintenanceCallFilter = MaintenanceFilter;
    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: check if we can put the prod inflation for tests too
    // TODO: better calculus for going from annual to block inflation (if it can be done)
    pub const InflationRate: Perbill = prod_or_fast!(Perbill::from_parts(9), Perbill::from_percent(1));
    // 30% for parachain bond, so 70% for staking
    pub const RewardsPortion: Perbill = Perbill::from_percent(70);
}
pub struct GetSelfChainBlockAuthor;
impl Get<AccountId32> for GetSelfChainBlockAuthor {
2136
    fn get() -> AccountId32 {
2136
        // TODO: we should do a refactor here, and use either authority-mapping or collator-assignemnt
2136
        // we should also make sure we actually account for the weight of these
2136
        // although most of these should be cached as they are read every block
2136
        let slot = u64::from(<Runtime as pallet_author_inherent::Config>::SlotBeacon::slot());
2136
        let self_para_id = ParachainInfo::get();
2136
        let author = CollatorAssignment::author_for_slot(slot.into(), self_para_id);
2136
        author.expect("author should be set")
2136
    }
}
pub struct OnUnbalancedInflation;
impl frame_support::traits::OnUnbalanced<Credit<AccountId, Balances>> for OnUnbalancedInflation {
2136
    fn on_nonzero_unbalanced(credit: Credit<AccountId, Balances>) {
2136
        let _ = <Balances as Balanced<_>>::resolve(&ParachainBondAccount::get(), credit);
2136
    }
}
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>;
}
#[derive(RuntimeDebug, PartialEq, Eq, Encode, Decode, Copy, Clone, TypeInfo, MaxEncodedLen)]
pub enum StreamPaymentAssetId {
5
    Native,
}
pub struct StreamPaymentAssets;
impl pallet_stream_payment::Assets<AccountId, StreamPaymentAssetId, Balance>
    for StreamPaymentAssets
{
4
    fn transfer_deposit(
4
        asset_id: &StreamPaymentAssetId,
4
        from: &AccountId,
4
        to: &AccountId,
4
        amount: Balance,
4
    ) -> frame_support::pallet_prelude::DispatchResult {
4
        match asset_id {
4
            StreamPaymentAssetId::Native => {
4
                // We remove the hold before transfering.
4
                Self::decrease_deposit(asset_id, from, amount)?;
4
                Balances::transfer(from, to, amount, Preservation::Preserve).map(|_| ())
            }
        }
4
    }
2
    fn increase_deposit(
2
        asset_id: &StreamPaymentAssetId,
2
        account: &AccountId,
2
        amount: Balance,
2
    ) -> frame_support::pallet_prelude::DispatchResult {
2
        match asset_id {
2
            StreamPaymentAssetId::Native => Balances::hold(
2
                &pallet_stream_payment::HoldReason::StreamPayment.into(),
2
                account,
2
                amount,
2
            ),
2
        }
2
    }
6
    fn decrease_deposit(
6
        asset_id: &StreamPaymentAssetId,
6
        account: &AccountId,
6
        amount: Balance,
6
    ) -> frame_support::pallet_prelude::DispatchResult {
6
        match asset_id {
6
            StreamPaymentAssetId::Native => Balances::release(
6
                &pallet_stream_payment::HoldReason::StreamPayment.into(),
6
                account,
6
                amount,
6
                Precision::Exact,
6
            )
6
            .map(|_| ()),
6
        }
6
    }
    fn get_deposit(asset_id: &StreamPaymentAssetId, account: &AccountId) -> Balance {
        match asset_id {
            StreamPaymentAssetId::Native => Balances::balance_on_hold(
                &pallet_stream_payment::HoldReason::StreamPayment.into(),
                account,
            ),
        }
    }
    /// Benchmarks: should return the asset id which has the worst performance when interacting
    /// with it.
    #[cfg(feature = "runtime-benchmarks")]
    fn bench_worst_case_asset_id() -> StreamPaymentAssetId {
        StreamPaymentAssetId::Native
    }
    /// Benchmarks: should return the another asset id which has the worst performance when interacting
    /// with it afther `bench_worst_case_asset_id`. This is to benchmark the worst case when changing config
    /// from one asset to another.
    #[cfg(feature = "runtime-benchmarks")]
    fn bench_worst_case_asset_id2() -> StreamPaymentAssetId {
        StreamPaymentAssetId::Native
    }
    /// Benchmarks: should set the balance for the asset id returned by `bench_worst_case_asset_id`.
    #[cfg(feature = "runtime-benchmarks")]
    fn bench_set_balance(asset_id: &StreamPaymentAssetId, account: &AccountId, amount: Balance) {
        // only one asset id
        let StreamPaymentAssetId::Native = asset_id;
        Balances::set_balance(account, amount);
    }
}
#[derive(RuntimeDebug, PartialEq, Eq, Encode, Decode, Copy, Clone, TypeInfo, MaxEncodedLen)]
pub enum TimeUnit {
5
    BlockNumber,
    Timestamp,
    // TODO: Container chains/relay block number.
}
pub struct TimeProvider;
impl pallet_stream_payment::TimeProvider<TimeUnit, Balance> for TimeProvider {
8
    fn now(unit: &TimeUnit) -> Option<Balance> {
8
        match *unit {
8
            TimeUnit::BlockNumber => Some(System::block_number().into()),
            TimeUnit::Timestamp => Some(Timestamp::now().into()),
        }
8
    }
    /// Benchmarks: should return the time unit which has the worst performance calling
    /// `TimeProvider::now(unit)` with.
    #[cfg(feature = "runtime-benchmarks")]
    fn bench_worst_case_time_unit() -> TimeUnit {
        // Both BlockNumber and Timestamp cost the same (1 db read), but overriding timestamp
        // doesn't work well in benches, while block number works fine.
        TimeUnit::BlockNumber
    }
    /// Benchmarks: sets the "now" time for time unit returned by `worst_case_time_unit`.
    #[cfg(feature = "runtime-benchmarks")]
    fn bench_set_now(instant: Balance) {
        System::set_block_number(instant as u32)
    }
}
type StreamId = u64;
parameter_types! {
    // 1 entry, storing 173 bytes on-chain
    pub const OpenStreamHoldAmount: Balance = currency::deposit(1, 173);
}
impl pallet_stream_payment::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type StreamId = StreamId;
    type TimeUnit = TimeUnit;
    type Balance = Balance;
    type AssetId = StreamPaymentAssetId;
    type Assets = StreamPaymentAssets;
    type Currency = Balances;
    type OpenStreamHoldAmount = OpenStreamHoldAmount;
    type RuntimeHoldReason = RuntimeHoldReason;
    type TimeProvider = TimeProvider;
    type WeightInfo = weights::pallet_stream_payment::SubstrateWeight<Runtime>;
}
parameter_types! {
    // 1 entry, storing 258 bytes on-chain
    pub const BasicDeposit: Balance = currency::deposit(1, 258);
    // 1 entry, storing 53 bytes on-chain
    pub const SubAccountDeposit: Balance = currency::deposit(1, 53);
    // Additional bytes adds 0 entries, storing 1 byte on-chain
    pub const ByteDeposit: Balance = currency::deposit(0, 1);
    pub const MaxSubAccounts: u32 = 100;
    pub const MaxAdditionalFields: u32 = 100;
    pub const MaxRegistrars: u32 = 20;
}
impl pallet_identity::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type Currency = Balances;
    type BasicDeposit = BasicDeposit;
    type ByteDeposit = ByteDeposit;
    type SubAccountDeposit = SubAccountDeposit;
    type MaxSubAccounts = MaxSubAccounts;
    type MaxRegistrars = MaxRegistrars;
    type IdentityInformation = pallet_identity::legacy::IdentityInfo<MaxAdditionalFields>;
    // Slashed balances are burnt
    type Slashed = ();
    type ForceOrigin = EnsureRoot<AccountId>;
    type RegistrarOrigin = EnsureRoot<AccountId>;
    type OffchainSignature = Signature;
    type SigningPublicKey = <Signature as Verify>::Signer;
    type UsernameAuthorityOrigin = EnsureRoot<Self::AccountId>;
    type PendingUsernameExpiration = ConstU32<{ 7 * DAYS }>;
    type MaxSuffixLength = ConstU32<7>;
    type MaxUsernameLength = ConstU32<32>;
    type WeightInfo = weights::pallet_identity::SubstrateWeight<Runtime>;
}
parameter_types! {
    pub const TreasuryId: PalletId = PalletId(*b"tns/tsry");
    pub const ProposalBond: Permill = Permill::from_percent(5);
    pub TreasuryAccount: AccountId = Treasury::account_id();
    pub const MaxBalance: Balance = Balance::max_value();
}
impl pallet_treasury::Config for Runtime {
    type PalletId = TreasuryId;
    type Currency = Balances;
    type ApproveOrigin = EnsureRoot<AccountId>;
    type RejectOrigin = EnsureRoot<AccountId>;
    type RuntimeEvent = RuntimeEvent;
    // If proposal gets rejected, bond goes to treasury
    type OnSlash = Treasury;
    type ProposalBond = ProposalBond;
    type ProposalBondMinimum = ConstU128<{ 1 * currency::DANCE * currency::SUPPLY_FACTOR }>;
    type SpendPeriod = ConstU32<{ 6 * DAYS }>;
    type Burn = ();
    type BurnDestination = ();
    type MaxApprovals = ConstU32<100>;
    type WeightInfo = weights::pallet_treasury::SubstrateWeight<Runtime>;
    type SpendFunds = ();
    type ProposalBondMaximum = ();
    #[cfg(not(feature = "runtime-benchmarks"))]
    type SpendOrigin = frame_support::traits::NeverEnsureOrigin<Balance>; // Disabled, no spending
    #[cfg(feature = "runtime-benchmarks")]
    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 }>;
    #[cfg(feature = "runtime-benchmarks")]
    type BenchmarkHelper = tanssi_runtime_common::benchmarking::TreasurtBenchmarkHelper<Runtime>;
}
parameter_types! {
    // One storage item; key size 32; value is size 4+4+16+32. Total = 1 * (32 + 56)
    pub const DepositBase: Balance = currency::deposit(1, 88);
    // Additional storage item size of 32 bytes.
    pub const DepositFactor: Balance = currency::deposit(0, 32);
    pub const MaxSignatories: u32 = 100;
}
impl pallet_multisig::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type RuntimeCall = RuntimeCall;
    type Currency = Balances;
    type DepositBase = DepositBase;
    type DepositFactor = DepositFactor;
    type MaxSignatories = MaxSignatories;
    type WeightInfo = weights::pallet_multisig::SubstrateWeight<Runtime>;
}
// Create the runtime by composing the FRAME pallets that were previously configured.
225594
construct_runtime!(
38296
    pub enum Runtime
38296
    {
38296
        // System support stuff.
38296
        System: frame_system = 0,
38296
        ParachainSystem: cumulus_pallet_parachain_system = 1,
38296
        Timestamp: pallet_timestamp = 2,
38296
        ParachainInfo: parachain_info = 3,
38296
        Sudo: pallet_sudo = 4,
38296
        Utility: pallet_utility = 5,
38296
        Proxy: pallet_proxy = 6,
38296
        Migrations: pallet_migrations = 7,
38296
        MaintenanceMode: pallet_maintenance_mode = 8,
38296
        TxPause: pallet_tx_pause = 9,
38296

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

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

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

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

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

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

            
38296
        RootTesting: pallet_root_testing = 100,
38296
        AsyncBacking: pallet_async_backing::{Pallet, Storage} = 110,
38296
    }
225594
);
#[cfg(feature = "runtime-benchmarks")]
mod benches {
    frame_benchmarking::define_benchmarks!(
        [frame_system, frame_system_benchmarking::Pallet::<Runtime>]
        [cumulus_pallet_parachain_system, ParachainSystem]
        [pallet_timestamp, Timestamp]
        [pallet_sudo, Sudo]
        [pallet_utility, Utility]
        [pallet_proxy, Proxy]
        [pallet_tx_pause, TxPause]
        [pallet_balances, Balances]
        [pallet_stream_payment, StreamPayment]
        [pallet_identity, Identity]
        [pallet_multisig, Multisig]
        [pallet_registrar, Registrar]
        [pallet_configuration, Configuration]
        [pallet_collator_assignment, CollatorAssignment]
        [pallet_author_noting, AuthorNoting]
        [pallet_services_payment, ServicesPayment]
        [pallet_data_preservers, DataPreservers]
        [pallet_invulnerables, Invulnerables]
        [pallet_session, SessionBench::<Runtime>]
        [pallet_author_inherent, AuthorInherent]
        [pallet_treasury, Treasury]
        [pallet_relay_storage_roots, RelayStorageRoots]
    );
}
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::{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)
        }
        fn dispatch_benchmark(
            config: frame_benchmarking::BenchmarkConfig,
        ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {
            use frame_benchmarking::{BenchmarkBatch, Benchmarking, 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.
16
        fn current_collator_parachain_assignment(account: AccountId) -> Option<ParaId> {
16
            let assigned_collators = CollatorAssignment::collator_container_chain();
16
            let self_para_id = ParachainInfo::get();
16

            
16
            assigned_collators.para_id_of(&account, self_para_id)
16
        }
        /// 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.
12
        fn future_collator_parachain_assignment(account: AccountId) -> Option<ParaId> {
12
            let assigned_collators = CollatorAssignment::pending_collator_container_chain();
12

            
12
            match assigned_collators {
8
                Some(assigned_collators) => {
8
                    let self_para_id = ParachainInfo::get();
8

            
8
                    assigned_collators.para_id_of(&account, self_para_id)
                }
                None => {
4
                    Self::current_collator_parachain_assignment(account)
                }
            }
12
        }
        /// Return the list of collators of the given `ParaId`.
        /// Returns `None` if the `ParaId` is not in the registrar.
28
        fn parachain_collators(para_id: ParaId) -> Option<Vec<AccountId>> {
28
            let assigned_collators = CollatorAssignment::collator_container_chain();
28
            let self_para_id = ParachainInfo::get();
28

            
28
            if para_id == self_para_id {
18
                Some(assigned_collators.orchestrator_chain)
            } else {
10
                assigned_collators.container_chains.get(&para_id).cloned()
            }
28
        }
    }
    impl pallet_registrar_runtime_api::RegistrarApi<Block, ParaId, MaxLengthTokenSymbol> for Runtime {
        /// Return the registered para ids
10
        fn registered_paras() -> Vec<ParaId> {
10
            // We should return the container-chains for the session in which we are kicking in
10
            let parent_number = System::block_number();
10
            let should_end_session = <Runtime as pallet_session::Config>::ShouldEndSession::should_end_session(parent_number + 1);
10
            let session_index = if should_end_session {
                Session::current_index() +1
            }
            else {
10
                Session::current_index()
            };
10
            let container_chains = Registrar::session_container_chains(session_index);
10
            let mut para_ids = vec![];
10
            para_ids.extend(container_chains.parachains);
10
            para_ids.extend(container_chains.parathreads.into_iter().map(|(para_id, _)| para_id));
10

            
10
            para_ids
10
        }
        /// Fetch genesis data for this para id
14
        fn genesis_data(para_id: ParaId) -> Option<ContainerChainGenesisData<MaxLengthTokenSymbol>> {
14
            Registrar::para_genesis_data(para_id)
14
        }
        /// 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,
    {
2
        fn latest_block_number(para_id: ParaId) -> Option<BlockNumber> {
2
            AuthorNoting::latest_author(para_id).map(|info| info.block_number)
2
        }
2
        fn latest_author(para_id: ParaId) -> Option<AccountId> {
2
            AuthorNoting::latest_author(para_id).map(|info| info.author)
2
        }
    }
    impl dp_consensus::TanssiAuthorityAssignmentApi<Block, NimbusId> for Runtime {
        /// Return the current authorities assigned to a given paraId
2168
        fn para_id_authorities(para_id: ParaId) -> Option<Vec<NimbusId>> {
2168
            let parent_number = System::block_number();
2168

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

            
2168
            if para_id == self_para_id {
2152
                Some(assigned_authorities.orchestrator_chain)
            } else {
16
                assigned_authorities.container_chains.get(&para_id).cloned()
            }
2168
        }
        /// Return the paraId assigned to a given authority
64
        fn check_para_id_assignment(authority: NimbusId) -> Option<ParaId> {
64
            let parent_number = System::block_number();
64
            let should_end_session = <Runtime as pallet_session::Config>::ShouldEndSession::should_end_session(parent_number + 1);
64
            let session_index = if should_end_session {
16
                Session::current_index() +1
            }
            else {
48
                Session::current_index()
            };
64
            let assigned_authorities = AuthorityAssignment::collator_container_chain(session_index)?;
64
            let self_para_id = ParachainInfo::get();
64

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

            
24
            assigned_authorities.para_id_of(&authority, self_para_id)
24
        }
    }
    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 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
        }
    };
}