1
// Copyright (C) Moondance Labs Ltd.
2
// This file is part of Tanssi.
3

            
4
// Tanssi is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8

            
9
// Tanssi is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13

            
14
// You should have received a copy of the GNU General Public License
15
// along with Tanssi.  If not, see <http://www.gnu.org/licenses/>
16

            
17
#![cfg_attr(not(feature = "std"), no_std)]
18
// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.
19
#![recursion_limit = "256"]
20

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

            
25
extern crate alloc;
26

            
27
pub mod xcm_config;
28

            
29
#[cfg(feature = "std")]
30
use sp_version::NativeVersion;
31

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

            
36
pub mod weights;
37

            
38
pub mod genesis_config_presets;
39

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

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

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

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

            
167
/// Unchecked extrinsic type as expected by this runtime.
168
pub type UncheckedExtrinsic =
169
    generic::UncheckedExtrinsic<Address, RuntimeCall, Signature, TxExtension>;
170

            
171
/// Extrinsic type that has already been checked.
172
pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, RuntimeCall, TxExtension>;
173

            
174
/// Executive: handles dispatch to the various modules.
175
pub type Executive = frame_executive::Executive<
176
    Runtime,
177
    Block,
178
    frame_system::ChainContext<Runtime>,
179
    Runtime,
180
    AllPalletsWithSystem,
181
>;
182

            
183
/// DANCE, the native token, uses 12 decimals of precision.
184
pub mod currency {
185
    use super::Balance;
186

            
187
    // Provide a common factor between runtimes based on a supply of 10_000_000 tokens.
188
    pub const SUPPLY_FACTOR: Balance = 100;
189

            
190
    pub const MICRODANCE: Balance = 1_000_000;
191
    pub const MILLIDANCE: Balance = 1_000_000_000;
192
    pub const DANCE: Balance = 1_000_000_000_000;
193
    pub const KILODANCE: Balance = 1_000_000_000_000_000;
194

            
195
    pub const STORAGE_BYTE_FEE: Balance = 100 * MICRODANCE * SUPPLY_FACTOR;
196
    pub const STORAGE_ITEM_FEE: Balance = 100 * MILLIDANCE * SUPPLY_FACTOR;
197

            
198
20
    pub const fn deposit(items: u32, bytes: u32) -> Balance {
199
20
        items as Balance * STORAGE_ITEM_FEE + (bytes as Balance) * STORAGE_BYTE_FEE
200
20
    }
201
}
202

            
203
/// Handles converting a weight scalar to a fee value, based on the scale and granularity of the
204
/// node's balance type.
205
///
206
/// This should typically create a mapping between the following ranges:
207
///   - `[0, MAXIMUM_BLOCK_WEIGHT]`
208
///   - `[Balance::min, Balance::max]`
209
///
210
/// Yet, it can be used for any other sort of change to weight-fee. Some examples being:
211
///   - Setting it to `0` will essentially disable the weight fee.
212
///   - Setting it to `1` will cause the literal `#[weight = x]` values to be charged.
213
pub struct WeightToFee;
214
impl frame_support::weights::WeightToFee for WeightToFee {
215
    type Balance = Balance;
216

            
217
330
    fn weight_to_fee(weight: &Weight) -> Self::Balance {
218
330
        let time_poly: FeePolynomial<Balance> = RefTimeToFee::polynomial().into();
219
330
        let proof_poly: FeePolynomial<Balance> = ProofSizeToFee::polynomial().into();
220

            
221
        // Take the maximum instead of the sum to charge by the more scarce resource.
222
330
        time_poly
223
330
            .eval(weight.ref_time())
224
330
            .max(proof_poly.eval(weight.proof_size()))
225
330
    }
226
}
227
pub struct RefTimeToFee;
228
impl WeightToFeePolynomial for RefTimeToFee {
229
    type Balance = Balance;
230
330
    fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {
231
        // in Rococo, extrinsic base weight (smallest non-zero weight) is mapped to 1 MILLIUNIT:
232
        // in our template, we map to 1/10 of that, or 1/10 MILLIUNIT
233
330
        let p = MILLIUNIT / 10;
234
330
        let q = 100 * Balance::from(ExtrinsicBaseWeight::get().ref_time());
235
330
        smallvec![WeightToFeeCoefficient {
236
            degree: 1,
237
            negative: false,
238
            coeff_frac: Perbill::from_rational(p % q, q),
239
            coeff_integer: p / q,
240
        }]
241
330
    }
242
}
243

            
244
/// Maps the proof size component of `Weight` to a fee.
245
pub struct ProofSizeToFee;
246
impl WeightToFeePolynomial for ProofSizeToFee {
247
    type Balance = Balance;
248
330
    fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {
249
        // Map 10kb proof to 1 CENT.
250
330
        let p = MILLIUNIT / 10;
251
330
        let q = 10_000;
252

            
253
330
        smallvec![WeightToFeeCoefficient {
254
            degree: 1,
255
            negative: false,
256
            coeff_frac: Perbill::from_rational(p % q, q),
257
            coeff_integer: p / q,
258
        }]
259
330
    }
260
}
261

            
262
/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know
263
/// the specifics of the runtime. They can then be made to be agnostic over specific formats
264
/// of data like extrinsics, allowing for them to continue syncing the network through upgrades
265
/// to even the core data structures.
266
pub mod opaque {
267
    use {
268
        super::*,
269
        sp_runtime::{
270
            generic,
271
            traits::{BlakeTwo256, Hash as HashT},
272
        },
273
    };
274

            
275
    pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;
276
    /// Opaque block header type.
277
    pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
278
    /// Opaque block type.
279
    pub type Block = generic::Block<Header, UncheckedExtrinsic>;
280
    /// Opaque block identifier type.
281
    pub type BlockId = generic::BlockId<Block>;
282
    /// Opaque block hash type.
283
    pub type Hash = <BlakeTwo256 as HashT>::Output;
284
    /// Opaque signature type.
285
    pub use super::Signature;
286
}
287

            
288
impl_opaque_keys! {
289
    pub struct SessionKeys {
290
        pub nimbus: Initializer,
291
    }
292
}
293

            
294
#[sp_version::runtime_version]
295
pub const VERSION: RuntimeVersion = RuntimeVersion {
296
    spec_name: Cow::Borrowed("dancebox"),
297
    impl_name: Cow::Borrowed("dancebox"),
298
    authoring_version: 1,
299
    spec_version: 1700,
300
    impl_version: 0,
301
    apis: RUNTIME_API_VERSIONS,
302
    transaction_version: 1,
303
    system_version: 1,
304
};
305

            
306
/// This determines the average expected block time that we are targeting.
307
/// Blocks will be produced at a minimum duration defined by `SLOT_DURATION`.
308
/// `SLOT_DURATION` is picked up by `pallet_timestamp` which is in turn picked
309
/// up by `pallet_aura` to implement `fn slot_duration()`.
310
///
311
/// Change this to adjust the block time.
312
pub const MILLISECS_PER_BLOCK: u64 = 6000;
313

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

            
318
// Time is measured by number of blocks.
319
pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);
320
pub const HOURS: BlockNumber = MINUTES * 60;
321
pub const DAYS: BlockNumber = HOURS * 24;
322

            
323
// Unit = the base number of indivisible units for balances
324
pub const UNIT: Balance = 1_000_000_000_000;
325
pub const CENTS: Balance = UNIT / 30_000;
326
pub const MILLIUNIT: Balance = 1_000_000_000;
327
pub const MICROUNIT: Balance = 1_000_000;
328
/// The existential deposit. Set to 1/10 of the Connected Relay Chain.
329
pub const EXISTENTIAL_DEPOSIT: Balance = MILLIUNIT;
330

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

            
335
/// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used by
336
/// `Operational` extrinsics.
337
const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);
338

            
339
/// We allow for 2 seconds of compute with a 6 second average block time
340
const MAXIMUM_BLOCK_WEIGHT: Weight = Weight::from_parts(
341
    WEIGHT_REF_TIME_PER_SECOND.saturating_mul(2),
342
    cumulus_primitives_core::relay_chain::MAX_POV_SIZE as u64,
343
);
344

            
345
/// The version information used to identify this runtime when compiled natively.
346
#[cfg(feature = "std")]
347
pub fn native_version() -> NativeVersion {
348
    NativeVersion {
349
        runtime_version: VERSION,
350
        can_author_with: Default::default(),
351
    }
352
}
353

            
354
parameter_types! {
355
    pub const Version: RuntimeVersion = VERSION;
356

            
357
    // This part is copied from Substrate's `bin/node/runtime/src/lib.rs`.
358
    //  The `RuntimeBlockLength` and `RuntimeBlockWeights` exist here because the
359
    // `DeletionWeightLimit` and `DeletionQueueDepth` depend on those to parameterize
360
    // the lazy contract deletion.
361
    pub RuntimeBlockLength: BlockLength =
362
        BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);
363
    pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()
364
        .base_block(BlockExecutionWeight::get())
365
114261
        .for_class(DispatchClass::all(), |weights| {
366
114261
            weights.base_extrinsic = ExtrinsicBaseWeight::get();
367
114261
        })
368
38087
        .for_class(DispatchClass::Normal, |weights| {
369
38087
            weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);
370
38087
        })
371
38087
        .for_class(DispatchClass::Operational, |weights| {
372
38087
            weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);
373
            // Operational transactions have some extra reserved space, so that they
374
            // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.
375
38087
            weights.reserved = Some(
376
38087
                MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT
377
38087
            );
378
38087
        })
379
        .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)
380
        .build_or_panic();
381
    pub const SS58Prefix: u16 = 42;
382
}
383

            
384
// Configure FRAME pallets to include in runtime.
385

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

            
441
impl cumulus_pallet_weight_reclaim::Config for Runtime {
442
    type WeightInfo = weights::cumulus_pallet_weight_reclaim::SubstrateWeight<Runtime>;
443
}
444

            
445
impl pallet_timestamp::Config for Runtime {
446
    /// A timestamp: milliseconds since the unix epoch.
447
    type Moment = u64;
448
    type OnTimestampSet = dp_consensus::OnTimestampSet<
449
        <Self as pallet_author_inherent::Config>::SlotBeacon,
450
        ConstU64<{ SLOT_DURATION }>,
451
    >;
452
    type MinimumPeriod = ConstU64<{ SLOT_DURATION / 2 }>;
453
    type WeightInfo = weights::pallet_timestamp::SubstrateWeight<Runtime>;
454
}
455

            
456
pub struct CanAuthor;
457
impl nimbus_primitives::CanAuthor<NimbusId> for CanAuthor {
458
25260
    fn can_author(author: &NimbusId, slot: &u32) -> bool {
459
25260
        let authorities = AuthorityAssignment::collator_container_chain(Session::current_index())
460
25260
            .expect("authorities should be set")
461
25260
            .orchestrator_chain;
462

            
463
25260
        if authorities.is_empty() {
464
            return false;
465
25260
        }
466

            
467
25260
        let author_index = (*slot as usize) % authorities.len();
468
25260
        let expected_author = &authorities[author_index];
469

            
470
25260
        expected_author == author
471
25260
    }
472
    #[cfg(feature = "runtime-benchmarks")]
473
    fn get_authors(_slot: &u32) -> Vec<NimbusId> {
474
        AuthorityAssignment::collator_container_chain(Session::current_index())
475
            .expect("authorities should be set")
476
            .orchestrator_chain
477
    }
478
}
479

            
480
impl pallet_author_inherent::Config for Runtime {
481
    type AuthorId = NimbusId;
482
    type AccountLookup = dp_consensus::NimbusLookUp;
483
    type CanAuthor = CanAuthor;
484
    type SlotBeacon = dp_consensus::AuraDigestSlotBeacon<Runtime>;
485
    type WeightInfo = weights::pallet_author_inherent::SubstrateWeight<Runtime>;
486
}
487

            
488
parameter_types! {
489
    pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT;
490
}
491

            
492
impl pallet_balances::Config for Runtime {
493
    type MaxLocks = ConstU32<50>;
494
    /// The type for recording an account's balance.
495
    type Balance = Balance;
496
    /// The ubiquitous event type.
497
    type RuntimeEvent = RuntimeEvent;
498
    type DustRemoval = ();
499
    type ExistentialDeposit = ExistentialDeposit;
500
    type AccountStore = System;
501
    type MaxReserves = ConstU32<50>;
502
    type ReserveIdentifier = [u8; 8];
503
    type FreezeIdentifier = RuntimeFreezeReason;
504
    type MaxFreezes = ConstU32<10>;
505
    type RuntimeHoldReason = RuntimeHoldReason;
506
    type RuntimeFreezeReason = RuntimeFreezeReason;
507
    type DoneSlashHandler = ();
508
    type WeightInfo = weights::pallet_balances::SubstrateWeight<Runtime>;
509
}
510

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

            
515
impl pallet_transaction_payment::Config for Runtime {
516
    type RuntimeEvent = RuntimeEvent;
517
    type OnChargeTransaction =
518
        FungibleAdapter<Balances, tanssi_runtime_common::DealWithFees<Runtime>>;
519
    type OperationalFeeMultiplier = ConstU8<5>;
520
    type WeightToFee = WeightToFee;
521
    type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;
522
    type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Self>;
523
    type WeightInfo = weights::pallet_transaction_payment::SubstrateWeight<Runtime>;
524
}
525

            
526
parameter_types! {
527
    pub ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;
528
    pub ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;
529
    pub const RelayOrigin: AggregateMessageOrigin = AggregateMessageOrigin::Parent;
530
}
531

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

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

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

            
565
parameter_types! {
566
    pub const ExpectedBlockTime: u64 = MILLISECS_PER_BLOCK;
567
}
568

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

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

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

            
594
            let _relay_chain_state =
595
                cumulus_pallet_parachain_system::RelayStateProof::<Runtime>::get();
596
            let benchmarking_babe_output = Hash::default();
597
            return Some(benchmarking_babe_output);
598
2390
        }
599

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

            
609
    /// Return the block randomness from the relay mixed with the provided subject.
610
    /// This ensures that the randomness will be different on different pallets, as long as the subject is different.
611
2390
    fn get_block_randomness_mixed(subject: &[u8]) -> Option<Hash> {
612
2390
        Self::get_block_randomness()
613
2390
            .map(|random_hash| mix_randomness::<Runtime>(random_hash, subject))
614
2390
    }
615
}
616

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

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

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

            
633
        (randomness, block_number)
634
    }
635
}
636

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

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

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

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

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

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

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

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

            
680
    type SessionHandler = OwnApplySession;
681
}
682

            
683
impl parachain_info::Config for Runtime {}
684

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

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

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

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

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

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

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

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

            
774
pub struct BabeGetRandomnessForNextBlock;
775

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

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

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

            
802
2390
        random_seed
803
2390
    }
804
}
805

            
806
pub struct RemoveInvulnerablesImpl;
807

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

            
831
6650
        invulnerables
832
6650
    }
833
}
834

            
835
pub struct ParaIdAssignmentHooksImpl;
836

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

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

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

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

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

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

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

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

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

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

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

            
impl pallet_authority_assignment::Config for Runtime {
    type SessionIndex = u32;
    type AuthorityId = NimbusId;
}
pub const FIXED_BLOCK_PRODUCTION_COST: u128 = 1 * currency::MICRODANCE;
pub const FIXED_COLLATOR_ASSIGNMENT_COST: u128 = 100 * currency::MICRODANCE;
pub struct BlockProductionCost<Runtime>(PhantomData<Runtime>);
impl ProvideBlockProductionCost<Runtime> for BlockProductionCost<Runtime> {
7630
    fn block_cost(_para_id: &ParaId) -> (u128, Weight) {
7630
        (FIXED_BLOCK_PRODUCTION_COST, Weight::zero())
7630
    }
}
pub struct CollatorAssignmentCost<Runtime>(PhantomData<Runtime>);
impl ProvideCollatorAssignmentCost<Runtime> for CollatorAssignmentCost<Runtime> {
190
    fn collator_assignment_cost(_para_id: &ParaId) -> (u128, Weight) {
190
        (FIXED_COLLATOR_ASSIGNMENT_COST, Weight::zero())
190
    }
}
parameter_types! {
    // 60 days worth of blocks
    pub const FreeBlockProductionCredits: BlockNumber = 60 * DAYS;
    // 60 days worth of blocks
    pub const FreeCollatorAssignmentCredits: u32 = FreeBlockProductionCredits::get()/Period::get();
}
impl pallet_services_payment::Config for Runtime {
    /// Handler for fees
    type OnChargeForBlock = ();
    type OnChargeForCollatorAssignment = ();
    type OnChargeForCollatorAssignmentTip = ();
    /// Currency type for fee payment
    type Currency = Balances;
    /// Provider of a block cost which can adjust from block to block
    type ProvideBlockProductionCost = BlockProductionCost<Runtime>;
    /// Provider of a block cost which can adjust from block to block
    type ProvideCollatorAssignmentCost = CollatorAssignmentCost<Runtime>;
    /// The maximum number of block credits that can be accumulated
    type FreeBlockProductionCredits = FreeBlockProductionCredits;
    /// The maximum number of session credits that can be accumulated
    type FreeCollatorAssignmentCredits = FreeCollatorAssignmentCredits;
    type ManagerOrigin =
        EitherOfDiverse<pallet_registrar::EnsureSignedByManager<Runtime>, EnsureRoot<AccountId>>;
    type WeightInfo = weights::pallet_services_payment::SubstrateWeight<Runtime>;
}
parameter_types! {
    pub const ProfileDepositBaseFee: Balance = currency::STORAGE_ITEM_FEE;
    pub const ProfileDepositByteFee: Balance = currency::STORAGE_BYTE_FEE;
    #[derive(Clone)]
    pub const MaxAssignmentsPerParaId: u32 = 10;
    #[derive(Clone)]
    pub const MaxNodeUrlCount: u32 = 4;
    #[derive(Clone)]
    pub const MaxStringLen: u32 = 200;
}
pub type DataPreserversProfileId = u64;
impl pallet_data_preservers::Config for Runtime {
    type RuntimeHoldReason = RuntimeHoldReason;
    type Currency = Balances;
    type WeightInfo = weights::pallet_data_preservers::SubstrateWeight<Runtime>;
    type ProfileId = DataPreserversProfileId;
    type ProfileDeposit = tp_traits::BytesDeposit<ProfileDepositBaseFee, ProfileDepositByteFee>;
    type AssignmentProcessor = tp_data_preservers_common::AssignmentProcessor<Runtime>;
    type AssignmentOrigin = pallet_registrar::EnsureSignedByManager<Runtime>;
    type ForceSetProfileOrigin = EnsureRoot<AccountId>;
    type MaxAssignmentsPerParaId = MaxAssignmentsPerParaId;
    type MaxNodeUrlCount = MaxNodeUrlCount;
    type MaxStringLen = MaxStringLen;
    type MaxParaIdsVecLen = MaxLengthParaIds;
}
impl pallet_author_noting::Config for Runtime {
    type ContainerChains = CollatorAssignment;
    type SlotBeacon = dp_consensus::AuraDigestSlotBeacon<Runtime>;
    type ContainerChainAuthor = CollatorAssignment;
    type AuthorNotingHook = (
        XcmCoreBuyer,
        InflationRewards,
        ServicesPayment,
        InactivityTracking,
    );
    type RelayOrPara = pallet_author_noting::ParaMode<
        cumulus_pallet_parachain_system::RelaychainDataProvider<Self>,
    >;
    type MaxContainerChains = MaxLengthParaIds;
    type WeightInfo = weights::pallet_author_noting::SubstrateWeight<Runtime>;
}
parameter_types! {
    pub const PotId: PalletId = PalletId(*b"PotStake");
    pub const MaxCandidates: u32 = 1000;
    pub const MinCandidates: u32 = 5;
    pub const SessionLength: BlockNumber = 5;
    pub const MaxInvulnerables: u32 = 100;
    pub const ExecutiveBody: BodyId = BodyId::Executive;
}
impl pallet_invulnerables::Config for Runtime {
    type UpdateOrigin = EnsureRoot<AccountId>;
    type MaxInvulnerables = MaxInvulnerables;
    type CollatorId = <Self as frame_system::Config>::AccountId;
    type CollatorIdOf = ConvertInto;
    type CollatorRegistration = Session;
    type WeightInfo = weights::pallet_invulnerables::SubstrateWeight<Runtime>;
    #[cfg(feature = "runtime-benchmarks")]
    type Currency = Balances;
}
parameter_types! {
    #[derive(Clone)]
    pub const MaxLengthParaIds: u32 = 100u32;
    pub const MaxEncodedGenesisDataSize: u32 = 5_000_000u32; // 5MB
}
pub struct CurrentSessionIndexGetter;
impl tp_traits::GetSessionIndex<u32> for CurrentSessionIndexGetter {
    /// Returns current session index.
36691
    fn session_index() -> u32 {
36691
        Session::current_index()
36691
    }
    #[cfg(feature = "runtime-benchmarks")]
    fn skip_to_session(session_index: SessionIndex) {
        while Session::current_index() < session_index {
            Session::rotate_session();
        }
    }
}
impl pallet_configuration::Config for Runtime {
    type SessionDelay = ConstU32<2>;
    type SessionIndex = u32;
    type CurrentSessionIndex = CurrentSessionIndexGetter;
    type ForceEmptyOrchestrator = ConstBool<false>;
    type WeightInfo = weights::pallet_configuration::SubstrateWeight<Runtime>;
}
pub struct DanceboxRegistrarHooks;
impl RegistrarHooks for DanceboxRegistrarHooks {
330
    fn para_marked_valid_for_collating(para_id: ParaId) -> Weight {
        // Give free credits but only once per para id
330
        ServicesPayment::give_free_credits(&para_id)
330
    }
60
    fn para_deregistered(para_id: ParaId) -> Weight {
        // Clear pallet_author_noting storage
60
        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,
            );
60
        }
        // Remove bootnodes from pallet_data_preservers
60
        DataPreservers::para_deregistered(para_id);
60
        ServicesPayment::para_deregistered(para_id);
60
        XcmCoreBuyer::para_deregistered(para_id);
60
        Weight::default()
60
    }
340
    fn check_valid_for_collating(para_id: ParaId) -> DispatchResult {
        // To be able to call mark_valid_for_collating, a container chain must have bootnodes
340
        DataPreservers::check_valid_for_collating(para_id)
340
    }
    #[cfg(feature = "runtime-benchmarks")]
    fn benchmarks_ensure_valid_for_collating(para_id: ParaId) {
        use {
            frame_support::traits::EnsureOriginWithArg,
            pallet_data_preservers::{NodeType, ParaIdsFilter, Profile},
        };
        let profile = Profile {
            bootnode_url: Some(b"/ip4/127.0.0.1/tcp/33049/ws/p2p/12D3KooWHVMhQDHBpj9vQmssgyfspYecgV6e3hH1dQVDUkUbCYC9"
                    .to_vec()
                    .try_into()
                    .expect("to fit in BoundedVec")),
            direct_rpc_urls: Default::default(),
            proxy_rpc_urls: Default::default(),
            para_ids: ParaIdsFilter::AnyParaId,
            node_type: NodeType::Substrate,
            assignment_request: tp_data_preservers_common::ProviderRequest::Free,
            additional_info: Default::default(),
        };
        let profile_id = pallet_data_preservers::NextProfileId::<Runtime>::get();
        let profile_owner = AccountId::new([1u8; 32]);
        DataPreservers::force_create_profile(RuntimeOrigin::root(), profile, profile_owner)
            .expect("profile create to succeed");
        let para_manager =
            <Runtime as pallet_data_preservers::Config>::AssignmentOrigin::try_successful_origin(
                &para_id,
            )
            .expect("should be able to get para manager");
        DataPreservers::start_assignment(
            para_manager,
            profile_id,
            para_id,
            tp_data_preservers_common::AssignerExtra::Free,
        )
        .expect("assignement to work");
        assert!(
            pallet_data_preservers::Assignments::<Runtime>::get(para_id).contains(&profile_id),
            "profile should be correctly assigned"
        );
    }
}
pub struct PalletRelayStorageRootProvider;
impl RelayStorageRootProvider for PalletRelayStorageRootProvider {
    fn get_relay_storage_root(relay_block_number: u32) -> Option<H256> {
        pallet_relay_storage_roots::pallet::RelayStorageRoot::<Runtime>::get(relay_block_number)
    }
    #[cfg(feature = "runtime-benchmarks")]
    fn set_relay_storage_root(relay_block_number: u32, storage_root: Option<H256>) {
        pallet_relay_storage_roots::pallet::RelayStorageRootKeys::<Runtime>::mutate(|x| {
            if storage_root.is_some() {
                if x.is_full() {
                    let key = x.remove(0);
                    pallet_relay_storage_roots::pallet::RelayStorageRoot::<Runtime>::remove(key);
                }
                let pos = x.iter().position(|x| *x >= relay_block_number);
                if let Some(pos) = pos {
                    if x[pos] != relay_block_number {
                        x.try_insert(pos, relay_block_number).unwrap();
                    }
                } else {
                    // Push at end
                    x.try_push(relay_block_number).unwrap();
                }
            } else {
                let pos = x.iter().position(|x| *x == relay_block_number);
                if let Some(pos) = pos {
                    x.remove(pos);
                }
            }
        });
        pallet_relay_storage_roots::pallet::RelayStorageRoot::<Runtime>::set(
            relay_block_number,
            storage_root,
        );
    }
}
impl pallet_registrar::Config for Runtime {
    type RegistrarOrigin =
        EitherOfDiverse<pallet_registrar::EnsureSignedByManager<Runtime>, EnsureRoot<AccountId>>;
    type MarkValidForCollatingOrigin = EnsureRoot<AccountId>;
    type MaxLengthParaIds = MaxLengthParaIds;
    type MaxGenesisDataSize = MaxEncodedGenesisDataSize;
    type RegisterWithRelayProofOrigin = EnsureSigned<AccountId>;
    type RelayStorageRootProvider = PalletRelayStorageRootProvider;
    type SessionDelay = ConstU32<2>;
    type SessionIndex = u32;
    type CurrentSessionIndex = CurrentSessionIndexGetter;
    type Currency = Balances;
    type RegistrarHooks = DanceboxRegistrarHooks;
    type RuntimeHoldReason = RuntimeHoldReason;
    type InnerRegistrar = ();
    type WeightInfo = weights::pallet_registrar::SubstrateWeight<Runtime>;
    type DataDepositPerByte = DataDepositPerByte;
}
impl pallet_authority_mapping::Config for Runtime {
    type SessionIndex = u32;
    type SessionRemovalBoundary = ConstU32<2>;
    type AuthorityId = NimbusId;
}
impl pallet_sudo::Config for Runtime {
    type RuntimeCall = RuntimeCall;
    type RuntimeEvent = RuntimeEvent;
    type WeightInfo = weights::pallet_sudo::SubstrateWeight<Runtime>;
}
impl pallet_utility::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type RuntimeCall = RuntimeCall;
    type PalletsOrigin = OriginCaller;
    type WeightInfo = weights::pallet_utility::SubstrateWeight<Runtime>;
}
/// The type used to represent the kinds of proxying allowed.
#[apply(derive_storage_traits)]
#[derive(Copy, Ord, PartialOrd, MaxEncodedLen, DecodeWithMemTracking)]
#[allow(clippy::unnecessary_cast)]
pub enum ProxyType {
    /// All calls can be proxied. This is the trivial/most permissive filter.
    Any = 0,
    /// Only extrinsics that do not transfer funds.
    NonTransfer = 1,
    /// Only extrinsics related to governance (democracy and collectives).
    Governance = 2,
    /// Only extrinsics related to staking.
    Staking = 3,
    /// Allow to veto an announced proxy call.
    CancelProxy = 4,
    /// Allow extrinsic related to Balances.
    Balances = 5,
    /// Allow extrinsics related to Registrar
    Registrar = 6,
    /// Allow extrinsics related to Registrar that needs to be called through Sudo
    SudoRegistrar = 7,
    /// Allow extrinsics from the Session pallet for key management.
    SessionKeyManagement = 8,
}
impl Default for ProxyType {
    fn default() -> Self {
        Self::Any
    }
}
impl InstanceFilter<RuntimeCall> for ProxyType {
100
    fn filter(&self, c: &RuntimeCall) -> bool {
        // Since proxy filters are respected in all dispatches of the Utility
        // pallet, it should never need to be filtered by any proxy.
100
        if let RuntimeCall::Utility(..) = c {
            return true;
100
        }
100
        match self {
10
            ProxyType::Any => true,
            ProxyType::NonTransfer => {
20
                matches!(
20
                    c,
                    RuntimeCall::System(..)
                        | RuntimeCall::ParachainSystem(..)
                        | RuntimeCall::Timestamp(..)
                        | RuntimeCall::Proxy(..)
                        | RuntimeCall::Registrar(..)
                )
            }
            // We don't have governance yet
10
            ProxyType::Governance => false,
            ProxyType::Staking => {
10
                matches!(c, RuntimeCall::Session(..) | RuntimeCall::PooledStaking(..))
            }
10
            ProxyType::CancelProxy => matches!(
                c,
                RuntimeCall::Proxy(pallet_proxy::Call::reject_announcement { .. })
            ),
            ProxyType::Balances => {
10
                matches!(c, RuntimeCall::Balances(..))
            }
            ProxyType::Registrar => {
10
                matches!(
10
                    c,
                    RuntimeCall::Registrar(..) | RuntimeCall::DataPreservers(..)
                )
            }
10
            ProxyType::SudoRegistrar => match c {
10
                RuntimeCall::Sudo(pallet_sudo::Call::sudo { call: ref x }) => {
10
                    matches!(
10
                        x.as_ref(),
                        &RuntimeCall::Registrar(..) | &RuntimeCall::DataPreservers(..)
                    )
                }
                _ => false,
            },
            ProxyType::SessionKeyManagement => {
10
                matches!(c, RuntimeCall::Session(..))
            }
        }
100
    }
    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;
}
pub struct XcmExecutionManager;
impl xcm_primitives::PauseXcmExecution for XcmExecutionManager {
    fn suspend_xcm_execution() -> DispatchResult {
        XcmpQueue::suspend_xcm_execution(RuntimeOrigin::root())
    }
    fn resume_xcm_execution() -> DispatchResult {
        XcmpQueue::resume_xcm_execution(RuntimeOrigin::root())
    }
}
impl pallet_migrations::Config for Runtime {
    type MigrationsList = (tanssi_runtime_common::migrations::DanceboxMigrations<Runtime>,);
    type XcmExecutionManager = XcmExecutionManager;
}
parameter_types! {
    pub MbmServiceWeight: Weight = Perbill::from_percent(80) * RuntimeBlockWeights::get().max_block;
}
impl pallet_multiblock_migrations::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    #[cfg(not(feature = "runtime-benchmarks"))]
    type Migrations = ();
    // 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::PooledStaking(..)
                | RuntimeCall::Utility(..)
                | RuntimeCall::PolkadotXcm(..)
        )
    }
}
/// Normal Call Filter
pub struct NormalFilter;
impl Contains<RuntimeCall> for NormalFilter {
4300
    fn contains(_c: &RuntimeCall) -> bool {
4300
        true
4300
    }
}
impl pallet_maintenance_mode::Config for Runtime {
    type NormalCallFilter = NormalFilter;
    type MaintenanceCallFilter = InsideBoth<MaintenanceFilter, NormalFilter>;
    type MaintenanceOrigin = EnsureRoot<AccountId>;
    type XcmExecutionManager = XcmExecutionManager;
}
parameter_types! {
    pub const MaxStorageRoots: u32 = 10; // 1 minute of relay blocks
}
impl pallet_relay_storage_roots::Config for Runtime {
    type RelaychainStateProvider = cumulus_pallet_parachain_system::RelaychainDataProvider<Self>;
    type MaxStorageRoots = MaxStorageRoots;
    type WeightInfo = weights::pallet_relay_storage_roots::SubstrateWeight<Runtime>;
}
impl pallet_root_testing::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
}
parameter_types! {
    pub StakingAccount: AccountId32 = PalletId(*b"POOLSTAK").into_account_truncating();
    pub const InitialManualClaimShareValue: u128 = currency::MILLIDANCE;
    pub const InitialAutoCompoundingShareValue: u128 = currency::MILLIDANCE;
    pub const MinimumSelfDelegation: u128 = 10 * currency::KILODANCE;
    pub const RewardsCollatorCommission: Perbill = Perbill::from_percent(20);
    // Need to wait 2 sessions before being able to join or leave staking pools
    pub const StakingSessionDelay: u32 = 2;
}
pub struct CandidateIsOnlineAndHasRegisteredKeys;
impl IsCandidateEligible<AccountId> for CandidateIsOnlineAndHasRegisteredKeys {
480
    fn is_candidate_eligible(a: &AccountId) -> bool {
480
        <Session as ValidatorRegistration<AccountId>>::is_registered(a)
440
            && !InactivityTracking::is_node_offline(a)
480
    }
    #[cfg(feature = "runtime-benchmarks")]
    fn make_candidate_eligible(a: &AccountId, eligible: bool) {
        use sp_core::crypto::UncheckedFrom;
        if eligible {
            let account_slice: &[u8; 32] = a.as_ref();
            let _ = Session::set_keys(
                RuntimeOrigin::signed(a.clone()),
                SessionKeys {
                    nimbus: NimbusId::unchecked_from(*account_slice),
                },
                vec![],
            );
        } else {
            let _ = Session::purge_keys(RuntimeOrigin::signed(a.clone()));
        }
        if InactivityTracking::is_node_offline(a) {
            InactivityTracking::make_node_online(a);
        }
    }
}
parameter_types! {
    pub const MaxCandidatesBufferSize: u32 = 100;
}
impl pallet_pooled_staking::Config for Runtime {
    type Currency = Balances;
    type Balance = Balance;
    type StakingAccount = StakingAccount;
    type InitialManualClaimShareValue = InitialManualClaimShareValue;
    type InitialAutoCompoundingShareValue = InitialAutoCompoundingShareValue;
    type MinimumSelfDelegation = MinimumSelfDelegation;
    type RuntimeHoldReason = RuntimeHoldReason;
    type RewardsCollatorCommission = RewardsCollatorCommission;
    type JoiningRequestTimer = SessionTimer<Runtime, StakingSessionDelay>;
    type LeavingRequestTimer = SessionTimer<Runtime, StakingSessionDelay>;
    type EligibleCandidatesBufferSize = MaxCandidatesBufferSize;
    type EligibleCandidatesFilter = CandidateIsOnlineAndHasRegisteredKeys;
    type WeightInfo = weights::pallet_pooled_staking::SubstrateWeight<Runtime>;
}
parameter_types! {
    pub ParachainBondAccount: AccountId32 = PalletId(*b"ParaBond").into_account_truncating();
    pub PendingRewardsAccount: AccountId32 = PalletId(*b"PENDREWD").into_account_truncating();
    // The equation to solve is:
    // initial_supply * (1.05) = initial_supply * (1+x)^5_259_600
    // we should solve for x = (1.05)^(1/5_259_600) -1 -> 0.000000009 per block or 9/1_000_000_000
    // 1% in the case of dev mode
    // TODO: 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 {
79940
    fn get_block_author() -> Option<AccountId32> {
        // TODO: we should do a refactor here, and use either authority-mapping or collator-assignemnt
        // we should also make sure we actually account for the weight of these
        // although most of these should be cached as they are read every block
79940
        let slot = u64::from(<Runtime as pallet_author_inherent::Config>::SlotBeacon::slot());
79940
        let self_para_id = ParachainInfo::get();
79940
        CollatorAssignment::author_for_slot(slot.into(), self_para_id)
79940
    }
}
pub struct OnUnbalancedInflation;
impl frame_support::traits::OnUnbalanced<Credit<AccountId, Balances>> for OnUnbalancedInflation {
26640
    fn on_nonzero_unbalanced(credit: Credit<AccountId, Balances>) {
26640
        let _ = <Balances as Balanced<_>>::resolve(&ParachainBondAccount::get(), credit);
26640
    }
}
impl pallet_inflation_rewards::Config for Runtime {
    type Currency = Balances;
    type ContainerChains = CollatorAssignment;
    type MaxContainerChains = MaxLengthParaIds;
    type GetSelfChainBlockAuthor = GetSelfChainBlockAuthor;
    type InflationRate = InflationRate;
    type OnUnbalanced = OnUnbalancedInflation;
    type PendingRewardsAccount = PendingRewardsAccount;
    type StakingRewardsDistributor = InvulnerableRewardDistribution<Self, Balances, PooledStaking>;
    type RewardsPortion = RewardsPortion;
}
impl pallet_tx_pause::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type RuntimeCall = RuntimeCall;
    type PauseOrigin = EnsureRoot<AccountId>;
    type UnpauseOrigin = EnsureRoot<AccountId>;
    type WhitelistedCalls = ();
    type MaxNameLen = ConstU32<256>;
    type WeightInfo = weights::pallet_tx_pause::SubstrateWeight<Runtime>;
}
parameter_types! {
    // 1 entry, storing 253 bytes on-chain in the worst case
    pub const OpenStreamHoldAmount: Balance = currency::deposit(1, 253);
}
impl pallet_stream_payment::Config for Runtime {
    type StreamId = StreamId;
    type TimeUnit = tp_stream_payment_common::TimeUnit;
    type Balance = Balance;
    type AssetId = tp_stream_payment_common::AssetId;
    type AssetsManager = tp_stream_payment_common::AssetsManager<Runtime>;
    type Currency = Balances;
    type OpenStreamHoldAmount = OpenStreamHoldAmount;
    type RuntimeHoldReason = RuntimeHoldReason;
    type TimeProvider = tp_stream_payment_common::TimeProvider<Runtime>;
    type WeightInfo = weights::pallet_stream_payment::SubstrateWeight<Runtime>;
}
parameter_types! {
    // 1 entry, storing 258 bytes on-chain
    pub const BasicDeposit: Balance = currency::deposit(1, 258);
    // 1 entry, storing 53 bytes on-chain
    pub const SubAccountDeposit: Balance = currency::deposit(1, 53);
    // Additional bytes adds 0 entries, storing 1 byte on-chain
    pub const ByteDeposit: Balance = currency::deposit(0, 1);
    pub const UsernameDeposit: Balance = currency::deposit(0, 32);
    pub const MaxSubAccounts: u32 = 100;
    pub const MaxAdditionalFields: u32 = 100;
    pub const MaxRegistrars: u32 = 20;
}
impl pallet_identity::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type Currency = Balances;
    type BasicDeposit = BasicDeposit;
    type ByteDeposit = ByteDeposit;
    type UsernameDeposit = UsernameDeposit;
    type SubAccountDeposit = SubAccountDeposit;
    type MaxSubAccounts = MaxSubAccounts;
    type MaxRegistrars = MaxRegistrars;
    type IdentityInformation = pallet_identity::legacy::IdentityInfo<MaxAdditionalFields>;
    // Slashed balances are burnt
    type Slashed = ();
    type ForceOrigin = EnsureRoot<AccountId>;
    type RegistrarOrigin = EnsureRoot<AccountId>;
    type OffchainSignature = Signature;
    type SigningPublicKey = <Signature as Verify>::Signer;
    type UsernameAuthorityOrigin = EnsureRoot<Self::AccountId>;
    type PendingUsernameExpiration = ConstU32<{ 7 * DAYS }>;
    type UsernameGracePeriod = ConstU32<{ 30 * DAYS }>;
    type MaxSuffixLength = ConstU32<7>;
    type MaxUsernameLength = ConstU32<32>;
    #[cfg(feature = "runtime-benchmarks")]
    type BenchmarkHelper = ();
    type WeightInfo = weights::pallet_identity::SubstrateWeight<Runtime>;
}
parameter_types! {
    pub const TreasuryId: PalletId = PalletId(*b"tns/tsry");
    pub const ProposalBond: Permill = Permill::from_percent(5);
    pub TreasuryAccount: AccountId = Treasury::account_id();
    pub const MaxBalance: Balance = Balance::MAX;
    // We allow it to be 1 minute in fast mode to be able to test it
    pub const SpendPeriod: BlockNumber = prod_or_fast!(6 * DAYS, 1 * MINUTES);
    pub const DataDepositPerByte: Balance = 1 * CENTS;
}
impl pallet_treasury::Config for Runtime {
    type PalletId = TreasuryId;
    type Currency = Balances;
    type RejectOrigin = EnsureRoot<AccountId>;
    type RuntimeEvent = RuntimeEvent;
    // If proposal gets rejected, bond goes to treasury
    type SpendPeriod = SpendPeriod;
    type Burn = ();
    type BurnDestination = ();
    type MaxApprovals = ConstU32<100>;
    type WeightInfo = weights::pallet_treasury::SubstrateWeight<Runtime>;
    type SpendFunds = ();
    type SpendOrigin =
        frame_system::EnsureWithSuccess<EnsureRoot<AccountId>, AccountId, MaxBalance>;
    type AssetKind = ();
    type Beneficiary = AccountId;
    type BeneficiaryLookup = IdentityLookup<AccountId>;
    type Paymaster = PayFromAccount<Balances, TreasuryAccount>;
    // TODO: implement pallet-asset-rate to allow the treasury to spend other assets
    type BalanceConverter = UnityAssetBalanceConversion;
    type PayoutPeriod = ConstU32<{ 30 * DAYS }>;
    type BlockNumberProvider = System;
    #[cfg(feature = "runtime-benchmarks")]
    type BenchmarkHelper = tanssi_runtime_common::benchmarking::TreasuryBenchmarkHelper<Runtime>;
}
parameter_types! {
    // One storage item; key size 32; value is size 4+4+16+32. Total = 1 * (32 + 56)
    pub const DepositBase: Balance = currency::deposit(1, 88);
    // Additional storage item size of 32 bytes.
    pub const DepositFactor: Balance = currency::deposit(0, 32);
    pub const MaxSignatories: u32 = 100;
}
impl pallet_multisig::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type RuntimeCall = RuntimeCall;
    type Currency = Balances;
    type DepositBase = DepositBase;
    type DepositFactor = DepositFactor;
    type MaxSignatories = MaxSignatories;
    type WeightInfo = weights::pallet_multisig::SubstrateWeight<Runtime>;
    type BlockNumberProvider = System;
}
parameter_types! {
    pub const MaxInactiveSessions: u32 = 5;
    pub const CooldownLenghtInSessions: u32 = 2;
}
impl pallet_inactivity_tracking::Config for Runtime {
    type MaxInactiveSessions = MaxInactiveSessions;
    type MaxCollatorsPerSession = MaxCandidatesBufferSize;
    type MaxContainerChains = MaxLengthParaIds;
    type CurrentSessionIndex = CurrentSessionIndexGetter;
    type CurrentCollatorsFetcher = CollatorAssignment;
    type GetSelfChainBlockAuthor = GetSelfChainBlockAuthor;
    type ParaFilter = tp_parathread_filter_common::ExcludeAllParathreadsFilter<Runtime>;
    type InvulnerablesFilter = tp_invulnerables_filter_common::InvulnerablesFilter<Runtime>;
    type CollatorStakeHelper = PooledStaking;
    type CooldownLength = CooldownLenghtInSessions;
    type WeightInfo = weights::pallet_inactivity_tracking::SubstrateWeight<Runtime>;
}
// Create the runtime by composing the FRAME pallets that were previously configured.
construct_runtime!(
    pub enum Runtime
    {
        // System support stuff.
        System: frame_system = 0,
        ParachainSystem: cumulus_pallet_parachain_system = 1,
        Timestamp: pallet_timestamp = 2,
        ParachainInfo: parachain_info = 3,
        Sudo: pallet_sudo = 4,
        Utility: pallet_utility = 5,
        Proxy: pallet_proxy = 6,
        Migrations: pallet_migrations = 7,
        MultiBlockMigrations: pallet_multiblock_migrations = 121,
        MaintenanceMode: pallet_maintenance_mode = 8,
        TxPause: pallet_tx_pause = 9,
        // Monetary stuff.
        Balances: pallet_balances = 10,
        TransactionPayment: pallet_transaction_payment = 11,
        StreamPayment: pallet_stream_payment = 12,
        // Other utilities
        Identity: pallet_identity = 15,
        Multisig: pallet_multisig = 16,
        // ContainerChain management. It should go before Session for Genesis
        Registrar: pallet_registrar = 20,
        Configuration: pallet_configuration = 21,
        CollatorAssignment: pallet_collator_assignment = 22,
        Initializer: pallet_initializer = 23,
        AuthorNoting: pallet_author_noting = 24,
        AuthorityAssignment: pallet_authority_assignment = 25,
        ServicesPayment: pallet_services_payment = 26,
        DataPreservers: pallet_data_preservers = 27,
        // Collator support. The order of these 6 are important and shall not change.
        Invulnerables: pallet_invulnerables = 30,
        Session: pallet_session = 31,
        AuthorityMapping: pallet_authority_mapping = 32,
        AuthorInherent: pallet_author_inherent = 33,
        PooledStaking: pallet_pooled_staking = 34,
        // InflationRewards must be after Session and AuthorInherent
        InflationRewards: pallet_inflation_rewards = 35,
        InactivityTracking: pallet_inactivity_tracking = 36,
        // Treasury stuff.
        Treasury: pallet_treasury::{Pallet, Storage, Config<T>, Event<T>, Call} = 40,
        //XCM
        XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 50,
        CumulusXcm: cumulus_pallet_xcm::{Pallet, Event<T>, Origin} = 51,
        PolkadotXcm: pallet_xcm::{Pallet, Call, Storage, Event<T>, Origin, Config<T>} = 53,
        ForeignAssets: pallet_assets::<Instance1>::{Pallet, Call, Storage, Event<T>} = 54,
        ForeignAssetsCreator: pallet_foreign_asset_creator::{Pallet, Call, Storage, Event<T>} = 55,
        AssetRate: pallet_asset_rate::{Pallet, Call, Storage, Event<T>} = 56,
        MessageQueue: pallet_message_queue::{Pallet, Call, Storage, Event<T>} = 57,
        XcmCoreBuyer: pallet_xcm_core_buyer = 58,
        // More system support stuff
        RelayStorageRoots: pallet_relay_storage_roots = 60,
        WeightReclaim: cumulus_pallet_weight_reclaim = 61,
        RootTesting: pallet_root_testing = 100,
        AsyncBacking: pallet_async_backing::{Pallet, Storage} = 110,
    }
);
#[cfg(feature = "runtime-benchmarks")]
mod benches {
    frame_benchmarking::define_benchmarks!(
        [frame_system, frame_system_benchmarking::Pallet::<Runtime>]
        [frame_system_extensions, frame_system_benchmarking::extensions::Pallet::<Runtime>]
        [cumulus_pallet_parachain_system, ParachainSystem]
        [pallet_timestamp, Timestamp]
        [pallet_sudo, Sudo]
        [pallet_utility, Utility]
        [pallet_proxy, Proxy]
        [pallet_transaction_payment, TransactionPayment]
        [pallet_tx_pause, TxPause]
        [pallet_balances, Balances]
        [pallet_stream_payment, StreamPayment]
        [pallet_identity, Identity]
        [pallet_multiblock_migrations, MultiBlockMigrations]
        [pallet_multisig, Multisig]
        [pallet_registrar, Registrar]
        [pallet_configuration, Configuration]
        [pallet_collator_assignment, CollatorAssignment]
        [pallet_author_noting, AuthorNoting]
        [pallet_services_payment, ServicesPayment]
        [pallet_data_preservers, DataPreservers]
        [pallet_invulnerables, Invulnerables]
        [pallet_session, SessionBench::<Runtime>]
        [pallet_author_inherent, AuthorInherent]
        [pallet_pooled_staking, PooledStaking]
        [pallet_inactivity_tracking, InactivityTracking]
        [pallet_treasury, Treasury]
        [cumulus_pallet_xcmp_queue, XcmpQueue]
        // XCM
        [pallet_xcm, PalletXcmExtrinsicsBenchmark::<Runtime>]
        [pallet_xcm_benchmarks::fungible, pallet_xcm_benchmarks::fungible::Pallet::<Runtime>]
        [pallet_xcm_benchmarks::generic, pallet_xcm_benchmarks::generic::Pallet::<Runtime>]
        [pallet_assets, ForeignAssets]
        [pallet_foreign_asset_creator, ForeignAssetsCreator]
        [pallet_asset_rate, AssetRate]
        [pallet_message_queue, MessageQueue]
        [pallet_xcm_core_buyer, XcmCoreBuyer]
        [pallet_relay_storage_roots, RelayStorageRoots]
        [cumulus_pallet_weight_reclaim, WeightReclaim]
    );
}
25480
pub fn get_para_id_authorities(para_id: ParaId) -> Option<Vec<NimbusId>> {
25480
    let parent_number = System::block_number();
25480
    let should_end_session =
25480
        <Runtime as pallet_session::Config>::ShouldEndSession::should_end_session(
25480
            parent_number + 1,
        );
25480
    let session_index = if should_end_session {
2430
        Session::current_index() + 1
    } else {
23050
        Session::current_index()
    };
25480
    let assigned_authorities = AuthorityAssignment::collator_container_chain(session_index)?;
25480
    let self_para_id = ParachainInfo::get();
25480
    if para_id == self_para_id {
25340
        Some(assigned_authorities.orchestrator_chain)
    } else {
140
        assigned_authorities.container_chains.get(&para_id).cloned()
    }
25480
}
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 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 sp_genesis_builder::GenesisBuilder<Block> for Runtime {
        fn build_state(config: Vec<u8>) -> sp_genesis_builder::Result {
            build_state::<RuntimeGenesisConfig>(config)
        }
       fn get_preset(id: &Option<sp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
            get_preset::<RuntimeGenesisConfig>(id, |id: &sp_genesis_builder::PresetId| {
                let para_id: ParaId = 1000.into();
                let mock_container_chains: Vec<ParaId> =
                    vec![2000, 2001].iter().map(|&x| x.into()).collect();
                let invulnerables = vec![
                    "Alice".to_string(),
                    "Bob".to_string(),
                    "Charlie".to_string(),
                    "Dave".to_string(),
                ];
                let patch = match id.as_ref() {
                    "development" => genesis_config_presets::development(para_id, vec![], mock_container_chains, invulnerables),
                    _ => return None,
                };
                Some(
                    serde_json::to_string(&patch)
                        .expect("serialization to json is expected to work. qed.")
                        .into_bytes(),
                )
            })
        }
        fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
            vec!["development".into()]
        }
    }
    #[cfg(feature = "runtime-benchmarks")]
    impl frame_benchmarking::Benchmark<Block> for Runtime {
        fn benchmark_metadata(
            extra: bool,
        ) -> (
            Vec<frame_benchmarking::BenchmarkList>,
            Vec<frame_support::traits::StorageInfo>,
        ) {
            use cumulus_pallet_session_benchmarking::Pallet as SessionBench;
            use frame_benchmarking::{BenchmarkList};
            use frame_support::traits::StorageInfoTrait;
            use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
            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;
            use cumulus_pallet_session_benchmarking::Pallet as SessionBench;
            impl cumulus_pallet_session_benchmarking::Config for Runtime {}
            impl frame_system_benchmarking::Config for Runtime {
                fn setup_set_code_requirements(code: &alloc::vec::Vec<u8>) -> Result<(), BenchmarkError> {
                    ParachainSystem::initialize_for_set_code_benchmark(code.len() as u32);
                    Ok(())
                }
                fn verify_set_code() {
                    System::assert_last_event(cumulus_pallet_parachain_system::Event::<Runtime>::ValidationFunctionStored.into());
                }
            }
            use xcm::latest::prelude::*;
            use crate::xcm_config::SelfReserve;
            parameter_types! {
                pub ExistentialDepositAsset: Option<Asset> = Some((
                    SelfReserve::get(),
                    ExistentialDeposit::get()
                ).into());
                pub TrustedReserve: Option<(Location, Asset)> = Some(
                    (
                        Location::parent(),
                        Asset {
                            id: AssetId(Location::parent()),
                            fun: Fungible(ExistentialDeposit::get() * 100),
                        },
                    )
                );
            }
            impl pallet_xcm_benchmarks::fungible::Config for Runtime {
                type TransactAsset = Balances;
                type CheckedAccount = ();
                type TrustedTeleporter = ();
                type TrustedReserve = TrustedReserve;
                fn get_asset() -> Asset {
                    use frame_support::{assert_ok, traits::tokens::fungible::{Inspect, Mutate}};
                    use xcm::latest::prelude::Junctions::X2;
                    let (account, _) = pallet_xcm_benchmarks::account_and_location::<Runtime>(1);
                    assert_ok!(<Balances as Mutate<_>>::mint_into(
                        &account,
                        <Balances as Inspect<_>>::minimum_balance(),
                    ));
                    let asset_id = 42u16;
                    let asset_location = Location {
                        parents: 1,
                        interior: X2([
                            GlobalConsensus(NetworkId::Ethereum { chain_id: 1 }),
                            AccountKey20 {
                                network: Some(NetworkId::Ethereum { chain_id: 1 }),
                                key: [0; 20],
                            },
                        ]
                        .into()),
                    };
                    assert_ok!(ForeignAssetsCreator::create_foreign_asset(
                        RuntimeOrigin::root(),
                        asset_location.clone(),
                        asset_id,
                        account.clone(),
                        true,
                        1u128,
                    ));
                    Asset {
                        id: AssetId(asset_location),
                        fun: Fungible(ExistentialDeposit::get() * 100),
                    }
                }
            }
            impl pallet_xcm_benchmarks::Config for Runtime {
                type XcmConfig = xcm_config::XcmConfig;
                type AccountIdConverter = xcm_config::LocationToAccountId;
                type DeliveryHelper = cumulus_primitives_utility::ToParentDeliveryHelper<
                xcm_config::XcmConfig,
                ExistentialDepositAsset,
                xcm_config::PriceForParentDelivery,
                >;
                fn valid_destination() -> Result<Location, BenchmarkError> {
                    Ok(Location::parent())
                }
                fn worst_case_holding(_depositable_count: u32) -> Assets {
                    // We only care for native asset until we support others
                    // TODO: refactor this case once other assets are supported
                    vec![Asset{
                        id: AssetId(SelfReserve::get()),
                        fun: Fungible(u128::MAX),
                    }].into()
                }
            }
            impl pallet_xcm_benchmarks::generic::Config for Runtime {
                type TransactAsset = Balances;
                type RuntimeCall = RuntimeCall;
                fn worst_case_response() -> (u64, Response) {
                    (0u64, Response::Version(Default::default()))
                }
                fn worst_case_asset_exchange() -> Result<(Assets, Assets), BenchmarkError> {
                    Err(BenchmarkError::Skip)
                }
                fn universal_alias() -> Result<(Location, Junction), BenchmarkError> {
                    Err(BenchmarkError::Skip)
                }
                fn transact_origin_and_runtime_call() -> Result<(Location, RuntimeCall), BenchmarkError> {
                    Ok((Location::parent(), frame_system::Call::remark_with_event { remark: vec![] }.into()))
                }
                fn subscribe_origin() -> Result<Location, BenchmarkError> {
                    Ok(Location::parent())
                }
                fn worst_case_for_trader() -> Result<(Asset, WeightLimit), BenchmarkError> {
                    Ok((Asset {
                        id: AssetId(SelfReserve::get()),
                        fun: Fungible(ExistentialDeposit::get()*100),
                    }, WeightLimit::Unlimited))
                }
                fn claimable_asset() -> Result<(Location, Location, Assets), BenchmarkError> {
                    let origin = Location::parent();
                    let assets: Assets = (Location::parent(), 1_000u128).into();
                    let ticket = Location { parents: 0, interior: Here };
                    Ok((origin, ticket, assets))
                }
                fn unlockable_asset() -> Result<(Location, Location, Asset), BenchmarkError> {
                    Err(BenchmarkError::Skip)
                }
                fn export_message_origin_and_destination(
                ) -> Result<(Location, NetworkId, InteriorLocation), BenchmarkError> {
                    Err(BenchmarkError::Skip)
                }
                fn alias_origin() -> Result<(Location, Location), BenchmarkError> {
                    Err(BenchmarkError::Skip)
                }
            }
            use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
            impl pallet_xcm::benchmarking::Config for Runtime {
                type DeliveryHelper = cumulus_primitives_utility::ToParentDeliveryHelper<
                xcm_config::XcmConfig,
                ExistentialDepositAsset,
                xcm_config::PriceForParentDelivery,
                >;
                fn get_asset() -> Asset {
                    Asset {
                        id: AssetId(SelfReserve::get()),
                        fun: Fungible(ExistentialDeposit::get()),
                    }
                }
                fn reachable_dest() -> Option<Location> {
                    Some(Parent.into())
                }
                fn teleportable_asset_and_dest() -> Option<(Asset, Location)> {
                    // Relay/native token can be teleported between AH and Relay.
                    Some((
                        Asset {
                            fun: Fungible(EXISTENTIAL_DEPOSIT),
                            id: Parent.into()
                        },
                        Parent.into(),
                    ))
                }
                fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> {
                    use xcm_config::SelfReserve;
                    // AH can reserve transfer native token to some random parachain.
                    let random_para_id = 43211234;
                    ParachainSystem::open_outbound_hrmp_channel_for_benchmarks_or_tests(
                        random_para_id.into()
                    );
                    let who = frame_benchmarking::whitelisted_caller();
                    // Give some multiple of the existential deposit
                    let balance = EXISTENTIAL_DEPOSIT * 1000;
                    let _ = <Balances as frame_support::traits::Currency<_>>::make_free_balance_be(
                        &who, balance,
                    );
                    Some((
                        Asset {
                            fun: Fungible(EXISTENTIAL_DEPOSIT),
                            id: AssetId(SelfReserve::get())
                        },
                        ParentThen(Parachain(random_para_id).into()).into(),
                    ))
                }
                fn set_up_complex_asset_transfer(
                ) -> Option<(Assets, u32, Location, Box<dyn FnOnce()>)> {
                    use xcm_config::SelfReserve;
                    // Transfer to Relay some local AH asset (local-reserve-transfer) while paying
                    // fees using teleported native token.
                    // (We don't care that Relay doesn't accept incoming unknown AH local asset)
                    let dest = Parent.into();
                    let fee_amount = EXISTENTIAL_DEPOSIT;
                    let fee_asset: Asset = (SelfReserve::get(), fee_amount).into();
                    let who = frame_benchmarking::whitelisted_caller();
                    // Give some multiple of the existential deposit
                    let balance = fee_amount + EXISTENTIAL_DEPOSIT * 1000;
                    let _ = <Balances as frame_support::traits::Currency<_>>::make_free_balance_be(
                        &who, balance,
                    );
                    // verify initial balance
                    assert_eq!(Balances::free_balance(&who), balance);
                    // set up local asset
                    let asset_amount = 10u128;
                    let initial_asset_amount = asset_amount * 10;
                    // inject it into pallet-foreign-asset-creator.
                    // we cannot use the parent token directly because the extrinsic does not allow transferring the
                    // parent token to the parent chain anymore, because of an assets hub migration. We bypass that
                    // by adding a pallet instance to the token location.
                    let (asset_id, asset_location) = pallet_foreign_asset_creator::benchmarks::create_minted_asset::<Runtime>(
                        initial_asset_amount,
                        who.clone(),
                        Some(ParentThen(PalletInstance(8).into()).into()),
                    );
                    let transfer_asset: Asset = (asset_location, asset_amount).into();
                    let assets: Assets = vec![fee_asset.clone(), transfer_asset].into();
                    let fee_index = if assets.get(0).unwrap().eq(&fee_asset) { 0 } else { 1 };
                    // verify transferred successfully
                    let verify = Box::new(move || {
                        // verify native balance after transfer, decreased by transferred fee amount
                        // (plus transport fees)
                        assert!(Balances::free_balance(&who) <= balance - fee_amount);
                        // verify asset balance decreased by exactly transferred amount
                        assert_eq!(
                            ForeignAssets::balance(asset_id, &who),
                            initial_asset_amount - asset_amount,
                        );
                    });
                    Some((assets, fee_index, dest, verify))
                }
            }
            let whitelist: Vec<TrackedStorageKey> = vec![
                // Block Number
                hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac")
                    .to_vec()
                    .into(),
                // Total Issuance
                hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80")
                    .to_vec()
                    .into(),
                // Execution Phase
                hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a")
                    .to_vec()
                    .into(),
                // Event Count
                hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850")
                    .to_vec()
                    .into(),
                // System Events
                hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7")
                    .to_vec()
                    .into(),
                // The transactional storage limit.
                hex_literal::hex!("3a7472616e73616374696f6e5f6c6576656c3a")
                    .to_vec()
                    .into(),
                // ParachainInfo ParachainId
                hex_literal::hex!(  "0d715f2646c8f85767b5d2764bb2782604a74d81251e398fd8a0a4d55023bb3f")
                    .to_vec()
                    .into(),
            ];
            let mut batches = Vec::<BenchmarkBatch>::new();
            let params = (&config, &whitelist);
            add_benchmarks!(params, batches);
            Ok(batches)
        }
    }
    #[cfg(feature = "try-runtime")]
    impl frame_try_runtime::TryRuntime<Block> for Runtime {
        fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) {
            let weight = Executive::try_runtime_upgrade(checks).unwrap();
            (weight, RuntimeBlockWeights::get().max_block)
        }
        fn execute_block(
            block: Block,
            state_root_check: bool,
            signature_check: bool,
            select: frame_try_runtime::TryStateSelect,
        ) -> Weight {
            // NOTE: intentional unwrap: we don't want to propagate the error backwards, and want to
            // have a backtrace here.
            Executive::try_execute_block(block, state_root_check, signature_check, select).unwrap()
        }
    }
    impl pallet_collator_assignment_runtime_api::CollatorAssignmentApi<Block, AccountId, ParaId> for Runtime {
        /// Returns the list of `ParaId` of registered chains with at least some
        /// collators. This filters out parachains with no assigned collators.
        /// Since runtime APIs are called on top of a parent block, we need to be carefull
        /// at session boundaries. If the next block will change session, this function returns
        /// the parachains relevant for the next session.
        fn parachains_with_some_collators() -> Vec<ParaId> {
            use tp_traits::{GetContainerChainsWithCollators, ForSession};
            // We should return the container-chains for the session in which we are kicking in
            let parent_number = System::block_number();
            let should_end_session = <Runtime as pallet_session::Config>::ShouldEndSession::should_end_session(parent_number + 1);
            let for_session = if should_end_session { ForSession::Next } else { ForSession::Current };
            CollatorAssignment::container_chains_with_collators(for_session)
                .into_iter()
                .filter_map(
                    |(para_id, collators)| (!collators.is_empty()).then_some(para_id)
                ).collect()
        }
    }
    impl pallet_registrar_runtime_api::RegistrarApi<Block, ParaId> for Runtime {
        /// Return the registered para ids
50
        fn registered_paras() -> Vec<ParaId> {
            // We should return the container-chains for the session in which we are kicking in
50
            let parent_number = System::block_number();
50
            let should_end_session = <Runtime as pallet_session::Config>::ShouldEndSession::should_end_session(parent_number + 1);
50
            let session_index = if should_end_session {
                Session::current_index() +1
            }
            else {
50
                Session::current_index()
            };
50
            let container_chains = Registrar::session_container_chains(session_index);
50
            let mut para_ids = vec![];
50
            para_ids.extend(container_chains.parachains);
50
            para_ids.extend(container_chains.parathreads.into_iter().map(|(para_id, _)| para_id));
50
            para_ids
50
        }
        /// Fetch genesis data for this para id
70
        fn genesis_data(para_id: ParaId) -> Option<ContainerChainGenesisData> {
70
            Registrar::para_genesis_data(para_id)
70
        }
        /// Fetch boot_nodes for this para id
        fn boot_nodes(para_id: ParaId) -> Vec<Vec<u8>> {
            DataPreservers::assignments_profiles(para_id)
                .filter_map(|profile| profile.bootnode_url.map(Into::into))
                .collect()
        }
    }
    impl pallet_registrar_runtime_api::OnDemandBlockProductionApi<Block, ParaId, Slot> for Runtime {
        /// Returns slot frequency for particular para thread. Slot frequency specifies amount of slot
        /// need to be passed between two parathread blocks. It is expressed as `(min, max)` pair where `min`
        /// indicates amount of slot must pass before we produce another block and `max` indicates amount of
        /// blocks before this parathread must produce the block.
        ///
        /// Simply put, parathread must produce a block after `min`  but before `(min+max)` slots.
        ///
        /// # Returns
        ///
        /// * `Some(slot_frequency)`.
        /// * `None` if the `para_id` is not a parathread.
        fn parathread_slot_frequency(para_id: ParaId) -> Option<SlotFrequency> {
            Registrar::parathread_params(para_id).map(|params| {
                params.slot_frequency
            })
        }
    }
    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,
    {
10
        fn latest_block_number(para_id: ParaId) -> Option<BlockNumber> {
10
            AuthorNoting::latest_author(para_id).map(|info| info.block_number)
10
        }
10
        fn latest_author(para_id: ParaId) -> Option<AccountId> {
10
            AuthorNoting::latest_author(para_id).map(|info| info.author)
10
        }
    }
    impl dp_consensus::TanssiAuthorityAssignmentApi<Block, NimbusId> for Runtime {
        /// Return the current authorities assigned to a given paraId
25420
        fn para_id_authorities(para_id: ParaId) -> Option<Vec<NimbusId>> {
25420
            get_para_id_authorities(para_id)
25420
        }
        /// Return the paraId assigned to a given authority
320
        fn check_para_id_assignment(authority: NimbusId) -> Option<ParaId> {
320
            let parent_number = System::block_number();
320
            let should_end_session = <Runtime as pallet_session::Config>::ShouldEndSession::should_end_session(parent_number + 1);
320
            let session_index = if should_end_session {
80
                Session::current_index() +1
            }
            else {
240
                Session::current_index()
            };
320
            let assigned_authorities = AuthorityAssignment::collator_container_chain(session_index)?;
320
            let self_para_id = ParachainInfo::get();
320
            assigned_authorities.para_id_of(&authority, self_para_id)
320
        }
        /// Return the paraId assigned to a given authority on the next session.
        /// On session boundary this returns the same as `check_para_id_assignment`.
120
        fn check_para_id_assignment_next_session(authority: NimbusId) -> Option<ParaId> {
120
            let session_index = Session::current_index() + 1;
120
            let assigned_authorities = AuthorityAssignment::collator_container_chain(session_index)?;
120
            let self_para_id = ParachainInfo::get();
120
            assigned_authorities.para_id_of(&authority, self_para_id)
120
        }
    }
    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 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
        }
    }
    impl pallet_xcm_core_buyer_runtime_api::XCMCoreBuyerApi<Block, BlockNumber, ParaId, NimbusId> for Runtime {
        fn is_core_buying_allowed(para_id: ParaId, collator_public_key: NimbusId) -> Result<(), BuyingError<BlockNumber>> {
            XcmCoreBuyer::is_core_buying_allowed(para_id, Some(collator_public_key))
        }
        fn create_buy_core_unsigned_extrinsic(para_id: ParaId, proof: BuyCoreCollatorProof<NimbusId>) -> Box<<Block as BlockT>::Extrinsic> {
            let call = RuntimeCall::XcmCoreBuyer(pallet_xcm_core_buyer::Call::buy_core {
                para_id,
                proof
            });
            let unsigned_extrinsic = UncheckedExtrinsic::new_bare(call);
            Box::new(unsigned_extrinsic)
        }
        fn get_buy_core_signature_nonce(para_id: ParaId) -> u64 {
            pallet_xcm_core_buyer::CollatorSignatureNonce::<Runtime>::get(para_id)
        }
        fn get_buy_core_slot_drift() -> Slot {
            <Runtime as pallet_xcm_core_buyer::Config>::BuyCoreSlotDrift::get()
        }
    }
    impl xcm_runtime_apis::fees::XcmPaymentApi<Block> for Runtime {
        fn query_acceptable_payment_assets(xcm_version: xcm::Version) -> Result<Vec<VersionedAssetId>, XcmPaymentApiError> {
            if !matches!(xcm_version, 3..=5) {
                return Err(XcmPaymentApiError::UnhandledXcmVersion);
            }
            Ok([VersionedAssetId::V5(xcm_config::SelfReserve::get().into())]
                .into_iter()
                .chain(
                    pallet_asset_rate::ConversionRateToNative::<Runtime>::iter_keys().filter_map(|asset_id_u16| {
                        pallet_foreign_asset_creator::AssetIdToForeignAsset::<Runtime>::get(asset_id_u16).map(|location| {
                            VersionedAssetId::V5(location.into())
                        }).or_else(|| {
                            log::warn!("Asset `{}` is present in pallet_asset_rate but not in pallet_foreign_asset_creator", asset_id_u16);
                            None
                        })
                    })
                )
                .filter_map(|asset| asset.into_version(xcm_version).map_err(|e| {
                    log::warn!("Failed to convert asset to version {}: {:?}", xcm_version, e);
                }).ok())
                .collect())
        }
        fn query_weight_to_asset_fee(weight: Weight, asset: VersionedAssetId) -> Result<u128, XcmPaymentApiError> {
            let local_asset = VersionedAssetId::V5(xcm_config::SelfReserve::get().into());
            let asset = asset
                .into_version(5)
                .map_err(|_| XcmPaymentApiError::VersionedConversionFailed)?;
            if asset == local_asset {
                Ok(WeightToFee::weight_to_fee(&weight))
            } else {
                let native_fee = WeightToFee::weight_to_fee(&weight);
                let asset_v5: xcm::latest::AssetId = asset.try_into().map_err(|_| XcmPaymentApiError::VersionedConversionFailed)?;
                let location: xcm::latest::Location = asset_v5.0;
                let asset_id = pallet_foreign_asset_creator::ForeignAssetToAssetId::<Runtime>::get(location).ok_or(XcmPaymentApiError::AssetNotFound)?;
                let asset_rate = AssetRate::to_asset_balance(native_fee, asset_id);
                match asset_rate {
                    Ok(x) => Ok(x),
                    Err(pallet_asset_rate::Error::UnknownAssetKind) => Err(XcmPaymentApiError::AssetNotFound),
                    // Error when converting native balance to asset balance, probably overflow
                    Err(_e) => Err(XcmPaymentApiError::WeightNotComputable),
                }
            }
        }
        fn query_xcm_weight(message: VersionedXcm<()>) -> Result<Weight, XcmPaymentApiError> {
            PolkadotXcm::query_xcm_weight(message)
        }
        fn query_delivery_fees(destination: VersionedLocation, message: VersionedXcm<()>) -> Result<VersionedAssets, XcmPaymentApiError> {
            PolkadotXcm::query_delivery_fees(destination, message)
        }
    }
    impl xcm_runtime_apis::dry_run::DryRunApi<Block, RuntimeCall, RuntimeEvent, OriginCaller> for Runtime {
        fn dry_run_call(origin: OriginCaller, call: RuntimeCall, result_xcms_version: XcmVersion) -> Result<CallDryRunEffects<RuntimeEvent>, XcmDryRunApiError> {
            PolkadotXcm::dry_run_call::<Runtime, xcm_config::XcmRouter, OriginCaller, RuntimeCall>(origin, call, result_xcms_version)
        }
        fn dry_run_xcm(origin_location: VersionedLocation, xcm: VersionedXcm<RuntimeCall>) -> Result<XcmDryRunEffects<RuntimeEvent>, XcmDryRunApiError> {
            PolkadotXcm::dry_run_xcm::<Runtime, xcm_config::XcmRouter, RuntimeCall, xcm_config::XcmConfig>(origin_location, xcm)
        }
    }
    impl xcm_runtime_apis::conversions::LocationToAccountApi<Block, AccountId> for Runtime {
        fn convert_location(location: VersionedLocation) -> Result<
            AccountId,
            xcm_runtime_apis::conversions::Error
        > {
            xcm_runtime_apis::conversions::LocationToAccountHelper::<
                AccountId,
                xcm_config::LocationToAccountId,
            >::convert_location(location)
        }
    }
153702
}
#[allow(dead_code)]
struct CheckInherents;
// TODO: this should be removed but currently if we remove it the relay does not check anything
// related to other inherents that are not parachain-system
#[allow(deprecated)]
impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {
    fn check_inherents(
        block: &Block,
        relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,
    ) -> sp_inherents::CheckInherentsResult {
        let relay_chain_slot = relay_state_proof
            .read_slot()
            .expect("Could not read the relay chain slot from the proof");
        let inherent_data =
            cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(
                relay_chain_slot,
                core::time::Duration::from_secs(6),
            )
            .create_inherent_data()
            .expect("Could not create the timestamp inherent data");
        inherent_data.check_extrinsics(block)
    }
}
cumulus_pallet_parachain_system::register_validate_block! {
    Runtime = Runtime,
    CheckInherents = CheckInherents,
    BlockExecutor = pallet_author_inherent::BlockExecutor::<Runtime, Executive>,
}
#[macro_export]
macro_rules! prod_or_fast {
    ($prod:expr, $test:expr) => {
        if cfg!(feature = "fast-runtime") {
            $test
        } else {
            $prod
        }
    };
    ($prod:expr, $test:expr, $env:expr) => {
        if cfg!(feature = "fast-runtime") {
            core::option_env!($env)
                .map(|s| s.parse().ok())
                .flatten()
                .unwrap_or($test)
        } else {
            $prod
        }
    };
}