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

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

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

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

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

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

            
25
extern crate alloc;
26

            
27
pub mod xcm_config;
28

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

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

            
43
pub mod weights;
44

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

            
48
use {
49
    cumulus_pallet_parachain_system::{
50
        RelayChainStateProof, RelayNumberMonotonicallyIncreases, RelaychainDataProvider,
51
        RelaychainStateProvider,
52
    },
53
    cumulus_primitives_core::{
54
        relay_chain::{self, SessionIndex},
55
        AggregateMessageOrigin, BodyId, ParaId,
56
    },
57
    frame_support::{
58
        construct_runtime,
59
        dispatch::DispatchClass,
60
        genesis_builder_helper::{build_state, get_preset},
61
        pallet_prelude::DispatchResult,
62
        parameter_types,
63
        traits::{
64
            fungible::{Balanced, Credit, Inspect},
65
            tokens::{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, 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, Timer},
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
    polkadot_runtime_common::BlockHashCount,
97
    scale_info::prelude::format,
98
    smallvec::smallvec,
99
    sp_api::impl_runtime_apis,
100
    sp_consensus_aura::SlotDuration,
101
    sp_consensus_slots::Slot,
102
    sp_core::{crypto::KeyTypeId, Get, MaxEncodedLen, OpaqueMetadata, H256},
103
    sp_runtime::{
104
        generic, impl_opaque_keys,
105
        traits::{
106
            AccountIdConversion, AccountIdLookup, BlakeTwo256, Block as BlockT, ConvertInto,
107
            Hash as HashT, IdentityLookup, Verify,
108
        },
109
        transaction_validity::{TransactionSource, TransactionValidity},
110
        AccountId32, ApplyExtrinsicResult, Cow,
111
    },
112
    sp_std::{
113
        collections::{btree_map::BTreeMap, btree_set::BTreeSet},
114
        marker::PhantomData,
115
        prelude::*,
116
    },
117
    sp_version::RuntimeVersion,
118
    tp_stream_payment_common::StreamId,
119
    tp_traits::{
120
        apply, derive_storage_traits, GetContainerChainAuthor, GetHostConfiguration,
121
        GetSessionContainerChains, MaybeSelfChainBlockAuthor, ParaIdAssignmentHooks,
122
        RelayStorageRootProvider, RemoveInvulnerables, SlotFrequency,
123
    },
124
    tp_xcm_core_buyer::BuyCoreCollatorProof,
125
    xcm::{IntoVersion, VersionedAssetId, VersionedAssets, VersionedLocation, VersionedXcm},
126
    xcm_runtime_apis::{
127
        dry_run::{CallDryRunEffects, Error as XcmDryRunApiError, XcmDryRunEffects},
128
        fees::Error as XcmPaymentApiError,
129
    },
130
};
131
pub use {
132
    dp_core::{AccountId, Address, Balance, BlockNumber, Hash, Header, Index, Signature},
133
    sp_runtime::{MultiAddress, Perbill, Permill},
134
};
135

            
136
/// Block type as expected by this runtime.
137
pub type Block = generic::Block<Header, UncheckedExtrinsic>;
138
/// A Block signed with a Justification
139
pub type SignedBlock = generic::SignedBlock<Block>;
140
/// BlockId type as expected by this runtime.
141
pub type BlockId = generic::BlockId<Block>;
142

            
143
/// CollatorId type expected by this runtime.
144
pub type CollatorId = AccountId;
145

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

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

            
164
/// Extrinsic type that has already been checked.
165
pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, RuntimeCall, TxExtension>;
166

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

            
176
/// DANCE, the native token, uses 12 decimals of precision.
177
pub mod currency {
178
    use super::Balance;
179

            
180
    // Provide a common factor between runtimes based on a supply of 10_000_000 tokens.
181
    pub const SUPPLY_FACTOR: Balance = 100;
182

            
183
    pub const MICRODANCE: Balance = 1_000_000;
184
    pub const MILLIDANCE: Balance = 1_000_000_000;
185
    pub const DANCE: Balance = 1_000_000_000_000;
186
    pub const KILODANCE: Balance = 1_000_000_000_000_000;
187

            
188
    pub const STORAGE_BYTE_FEE: Balance = 100 * MICRODANCE * SUPPLY_FACTOR;
189
    pub const STORAGE_ITEM_FEE: Balance = 100 * MILLIDANCE * SUPPLY_FACTOR;
190

            
191
4376
    pub const fn deposit(items: u32, bytes: u32) -> Balance {
192
4376
        items as Balance * STORAGE_ITEM_FEE + (bytes as Balance) * STORAGE_BYTE_FEE
193
4376
    }
194
}
195

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

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

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

            
249
impl_opaque_keys! {
250
    pub struct SessionKeys {
251
        pub nimbus: Initializer,
252
    }
253
}
254

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

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

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

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

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

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

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

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

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

            
315
parameter_types! {
316
    pub const Version: RuntimeVersion = VERSION;
317

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

            
345
// Configure FRAME pallets to include in runtime.
346

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

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

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

            
420
27099
        if authorities.is_empty() {
421
            return false;
422
27099
        }
423
27099

            
424
27099
        let author_index = (*slot as usize) % authorities.len();
425
27099
        let expected_author = &authorities[author_index];
426
27099

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

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

            
445
parameter_types! {
446
    pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT;
447
}
448

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

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

            
472
impl pallet_transaction_payment::Config for Runtime {
473
    type RuntimeEvent = RuntimeEvent;
474
    type OnChargeTransaction =
475
        FungibleAdapter<Balances, tanssi_runtime_common::DealWithFees<Runtime>>;
476
    type OperationalFeeMultiplier = ConstU8<5>;
477
    type WeightToFee = WeightToFee;
478
    type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;
479
    type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Self>;
480
    type WeightInfo = weights::pallet_transaction_payment::SubstrateWeight<Runtime>;
481
}
482

            
483
parameter_types! {
484
    pub ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;
485
    pub ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;
486
    pub const RelayOrigin: AggregateMessageOrigin = AggregateMessageOrigin::Parent;
487
}
488

            
489
pub const RELAY_CHAIN_SLOT_DURATION_MILLIS: u32 = 6000;
490
pub const UNINCLUDED_SEGMENT_CAPACITY: u32 = 3;
491
pub const BLOCK_PROCESSING_VELOCITY: u32 = 1;
492

            
493
type ConsensusHook = pallet_async_backing::consensus_hook::FixedVelocityConsensusHook<
494
    Runtime,
495
    BLOCK_PROCESSING_VELOCITY,
496
    UNINCLUDED_SEGMENT_CAPACITY,
497
>;
498

            
499
impl cumulus_pallet_parachain_system::Config for Runtime {
500
    type WeightInfo = weights::cumulus_pallet_parachain_system::SubstrateWeight<Runtime>;
501
    type RuntimeEvent = RuntimeEvent;
502
    type OnSystemEvent = ();
503
    type SelfParaId = parachain_info::Pallet<Runtime>;
504
    type OutboundXcmpMessageSource = XcmpQueue;
505
    type DmpQueue = frame_support::traits::EnqueueWithOrigin<MessageQueue, RelayOrigin>;
506
    type ReservedDmpWeight = ReservedDmpWeight;
507
    type XcmpMessageHandler = XcmpQueue;
508
    type ReservedXcmpWeight = ReservedXcmpWeight;
509
    type CheckAssociatedRelayNumber = RelayNumberMonotonicallyIncreases;
510
    type ConsensusHook = ConsensusHook;
511
    type SelectCore = cumulus_pallet_parachain_system::DefaultCoreSelector<Runtime>;
512
}
513
pub struct ParaSlotProvider;
514
impl Get<(Slot, SlotDuration)> for ParaSlotProvider {
515
24511
    fn get() -> (Slot, SlotDuration) {
516
24511
        let slot = u64::from(<Runtime as pallet_author_inherent::Config>::SlotBeacon::slot());
517
24511
        (Slot::from(slot), SlotDuration::from_millis(SLOT_DURATION))
518
24511
    }
519
}
520

            
521
parameter_types! {
522
    pub const ExpectedBlockTime: u64 = MILLISECS_PER_BLOCK;
523
}
524

            
525
impl pallet_async_backing::Config for Runtime {
526
    type AllowMultipleBlocksPerSlot = ConstBool<true>;
527
    type GetAndVerifySlot =
528
        pallet_async_backing::ParaSlot<RELAY_CHAIN_SLOT_DURATION_MILLIS, ParaSlotProvider>;
529
    type ExpectedBlockTime = ExpectedBlockTime;
530
}
531

            
532
/// Only callable after `set_validation_data` is called which forms this proof the same way
533
2627
fn relay_chain_state_proof() -> RelayChainStateProof {
534
2627
    let relay_storage_root =
535
2627
        RelaychainDataProvider::<Runtime>::current_relay_chain_state().state_root;
536
2627
    let relay_chain_state = cumulus_pallet_parachain_system::RelayStateProof::<Runtime>::get()
537
2627
        .expect("set in `set_validation_data`");
538
2627
    RelayChainStateProof::new(ParachainInfo::get(), relay_storage_root, relay_chain_state)
539
2627
        .expect("Invalid relay chain state proof, already constructed in `set_validation_data`")
540
2627
}
541

            
542
pub struct BabeCurrentBlockRandomnessGetter;
543
impl BabeCurrentBlockRandomnessGetter {
544
2627
    fn get_block_randomness() -> Option<Hash> {
545
2627
        if cfg!(feature = "runtime-benchmarks") {
546
            // storage reads as per actual reads
547
            let _relay_storage_root =
548
                RelaychainDataProvider::<Runtime>::current_relay_chain_state().state_root;
549

            
550
            let _relay_chain_state =
551
                cumulus_pallet_parachain_system::RelayStateProof::<Runtime>::get();
552
            let benchmarking_babe_output = Hash::default();
553
            return Some(benchmarking_babe_output);
554
2627
        }
555
2627

            
556
2627
        relay_chain_state_proof()
557
2627
            .read_optional_entry::<Option<Hash>>(
558
2627
                relay_chain::well_known_keys::CURRENT_BLOCK_RANDOMNESS,
559
2627
            )
560
2627
            .ok()
561
2627
            .flatten()
562
2627
            .flatten()
563
2627
    }
564

            
565
    /// Return the block randomness from the relay mixed with the provided subject.
566
    /// This ensures that the randomness will be different on different pallets, as long as the subject is different.
567
    // TODO: audit usage of randomness API
568
    // https://github.com/paritytech/polkadot/issues/2601
569
2627
    fn get_block_randomness_mixed(subject: &[u8]) -> Option<Hash> {
570
2627
        Self::get_block_randomness()
571
2627
            .map(|random_hash| mix_randomness::<Runtime>(random_hash, subject))
572
2627
    }
573
}
574

            
575
/// Combines the vrf output of the previous relay block with the provided subject.
576
/// This ensures that the randomness will be different on different pallets, as long as the subject is different.
577
86
fn mix_randomness<T: frame_system::Config>(vrf_output: Hash, subject: &[u8]) -> T::Hash {
578
86
    let mut digest = Vec::new();
579
86
    digest.extend_from_slice(vrf_output.as_ref());
580
86
    digest.extend_from_slice(subject);
581
86

            
582
86
    T::Hashing::hash(digest.as_slice())
583
86
}
584

            
585
// Randomness trait
586
impl frame_support::traits::Randomness<Hash, BlockNumber> for BabeCurrentBlockRandomnessGetter {
587
    fn random(subject: &[u8]) -> (Hash, BlockNumber) {
588
        let block_number = frame_system::Pallet::<Runtime>::block_number();
589
        let randomness = Self::get_block_randomness_mixed(subject).unwrap_or_default();
590

            
591
        (randomness, block_number)
592
    }
593
}
594

            
595
pub struct OwnApplySession;
596
impl pallet_initializer::ApplyNewSession<Runtime> for OwnApplySession {
597
3339
    fn apply_new_session(
598
3339
        _changed: bool,
599
3339
        session_index: u32,
600
3339
        all_validators: Vec<(AccountId, NimbusId)>,
601
3339
        queued: Vec<(AccountId, NimbusId)>,
602
3339
    ) {
603
3339
        // We first initialize Configuration
604
3339
        Configuration::initializer_on_new_session(&session_index);
605
3339
        // Next: Registrar
606
3339
        Registrar::initializer_on_new_session(&session_index);
607
3339
        // Next: AuthorityMapping
608
3339
        AuthorityMapping::initializer_on_new_session(&session_index, &all_validators);
609
3339

            
610
11872
        let next_collators = queued.iter().map(|(k, _)| k.clone()).collect();
611
3339

            
612
3339
        // Next: CollatorAssignment
613
3339
        let assignments =
614
3339
            CollatorAssignment::initializer_on_new_session(&session_index, next_collators);
615
3339

            
616
3339
        let queued_id_to_nimbus_map = queued.iter().cloned().collect();
617
3339
        AuthorityAssignment::initializer_on_new_session(
618
3339
            &session_index,
619
3339
            &queued_id_to_nimbus_map,
620
3339
            &assignments.next_assignment,
621
3339
        );
622
3339

            
623
3339
        // Next: InactivityTracking
624
3339
        InactivityTracking::process_ended_session();
625
3339
    }
626

            
627
2609
    fn on_before_session_ending() {
628
2609
        InactivityTracking::on_before_session_ending();
629
2609
    }
630
}
631

            
632
impl pallet_initializer::Config for Runtime {
633
    type SessionIndex = u32;
634

            
635
    /// The identifier type for an authority.
636
    type AuthorityId = NimbusId;
637

            
638
    type SessionHandler = OwnApplySession;
639
}
640

            
641
impl parachain_info::Config for Runtime {}
642

            
643
/// Returns a list of collators by combining pallet_invulnerables and pallet_pooled_staking.
644
pub struct CollatorsFromInvulnerablesAndThenFromStaking;
645

            
646
/// Play the role of the session manager.
647
impl SessionManager<CollatorId> for CollatorsFromInvulnerablesAndThenFromStaking {
648
4069
    fn new_session(index: SessionIndex) -> Option<Vec<CollatorId>> {
649
4069
        if <frame_system::Pallet<Runtime>>::block_number() == 0 {
650
            // Do not show this log in genesis
651
1460
            log::debug!(
652
                "assembling new collators for new session {} at #{:?}",
653
                index,
654
                <frame_system::Pallet<Runtime>>::block_number(),
655
            );
656
        } else {
657
2609
            log::info!(
658
2232
                "assembling new collators for new session {} at #{:?}",
659
2232
                index,
660
2232
                <frame_system::Pallet<Runtime>>::block_number(),
661
            );
662
        }
663

            
664
4069
        let invulnerables = Invulnerables::invulnerables().to_vec();
665
4069
        let candidates_staking =
666
4069
            pallet_pooled_staking::SortedEligibleCandidates::<Runtime>::get().to_vec();
667
4069
        // Max number of collators is set in pallet_configuration
668
4069
        let target_session_index = index.saturating_add(1);
669
4069
        let max_collators =
670
4069
            <Configuration as GetHostConfiguration<u32>>::max_collators(target_session_index);
671
4069
        let collators = invulnerables
672
4069
            .iter()
673
4069
            .cloned()
674
4069
            .chain(candidates_staking.into_iter().filter_map(|elig| {
675
268
                let cand = elig.candidate;
676
268
                if invulnerables.contains(&cand) {
677
                    // If a candidate is both in pallet_invulnerables and pallet_staking, do not count it twice
678
80
                    None
679
                } else {
680
188
                    Some(cand)
681
                }
682
4069
            }))
683
4069
            .take(max_collators as usize)
684
4069
            .collect();
685
4069

            
686
4069
        // TODO: weight?
687
4069
        /*
688
4069
        frame_system::Pallet::<T>::register_extra_weight_unchecked(
689
4069
            T::WeightInfo::new_session(invulnerables.len() as u32),
690
4069
            DispatchClass::Mandatory,
691
4069
        );
692
4069
        */
693
4069
        Some(collators)
694
4069
    }
695
3339
    fn start_session(_: SessionIndex) {
696
3339
        // we don't care.
697
3339
    }
698
2609
    fn end_session(_: SessionIndex) {
699
2609
        // we don't care.
700
2609
    }
701
}
702

            
703
parameter_types! {
704
    pub const Period: u32 = prod_or_fast!(1 * HOURS, 1 * MINUTES);
705
    pub const Offset: u32 = 0;
706
}
707

            
708
impl pallet_session::Config for Runtime {
709
    type RuntimeEvent = RuntimeEvent;
710
    type ValidatorId = CollatorId;
711
    // we don't have stash and controller, thus we don't need the convert as well.
712
    type ValidatorIdOf = ConvertInto;
713
    type ShouldEndSession = pallet_session::PeriodicSessions<Period, Offset>;
714
    type NextSessionRotation = pallet_session::PeriodicSessions<Period, Offset>;
715
    type SessionManager = CollatorsFromInvulnerablesAndThenFromStaking;
716
    // Essentially just Aura, but let's be pedantic.
717
    type SessionHandler = <SessionKeys as sp_runtime::traits::OpaqueKeys>::KeyTypeIdProviders;
718
    type Keys = SessionKeys;
719
    type WeightInfo = weights::pallet_session::SubstrateWeight<Runtime>;
720
}
721

            
722
/// Read full_rotation_period from pallet_configuration
723
pub struct ConfigurationCollatorRotationSessionPeriod;
724

            
725
impl Get<u32> for ConfigurationCollatorRotationSessionPeriod {
726
5834
    fn get() -> u32 {
727
5834
        Configuration::config().full_rotation_period
728
5834
    }
729
}
730

            
731
pub struct BabeGetRandomnessForNextBlock;
732

            
733
impl GetRandomnessForNextBlock<u32> for BabeGetRandomnessForNextBlock {
734
54002
    fn should_end_session(n: u32) -> bool {
735
54002
        <Runtime as pallet_session::Config>::ShouldEndSession::should_end_session(n)
736
54002
    }
737

            
738
2627
    fn get_randomness() -> [u8; 32] {
739
2627
        let block_number = System::block_number();
740
2627
        let random_seed = if block_number != 0 {
741
86
            if let Some(random_hash) =
742
2627
                BabeCurrentBlockRandomnessGetter::get_block_randomness_mixed(b"CollatorAssignment")
743
            {
744
                // Return random_hash as a [u8; 32] instead of a Hash
745
86
                let mut buf = [0u8; 32];
746
86
                let len = sp_std::cmp::min(32, random_hash.as_ref().len());
747
86
                buf[..len].copy_from_slice(&random_hash.as_ref()[..len]);
748
86

            
749
86
                buf
750
            } else {
751
                // If there is no randomness (e.g when running in dev mode), return [0; 32]
752
2541
                [0; 32]
753
            }
754
        } else {
755
            // In block 0 (genesis) there is no randomness
756
            [0; 32]
757
        };
758

            
759
2627
        random_seed
760
2627
    }
761
}
762

            
763
pub struct RemoveInvulnerablesImpl;
764

            
765
impl RemoveInvulnerables<CollatorId> for RemoveInvulnerablesImpl {
766
4557
    fn remove_invulnerables(
767
4557
        collators: &mut Vec<CollatorId>,
768
4557
        num_invulnerables: usize,
769
4557
    ) -> Vec<CollatorId> {
770
4557
        if num_invulnerables == 0 {
771
            return vec![];
772
4557
        }
773
4557
        // TODO: check if this works on session changes
774
4557
        let all_invulnerables = pallet_invulnerables::Invulnerables::<Runtime>::get();
775
4557
        if all_invulnerables.is_empty() {
776
144
            return vec![];
777
4413
        }
778
4413
        let mut invulnerables = vec![];
779
4413
        // TODO: use binary_search when invulnerables are sorted
780
5513
        collators.retain(|x| {
781
5513
            if invulnerables.len() < num_invulnerables && all_invulnerables.contains(x) {
782
3593
                invulnerables.push(x.clone());
783
3593
                false
784
            } else {
785
1920
                true
786
            }
787
5513
        });
788
4413

            
789
4413
        invulnerables
790
4557
    }
791
}
792

            
793
pub struct ParaIdAssignmentHooksImpl;
794

            
795
impl ParaIdAssignmentHooksImpl {
796
7552
    fn charge_para_ids_internal(
797
7552
        blocks_per_session: tp_traits::BlockNumber,
798
7552
        para_id: ParaId,
799
7552
        currently_assigned: &BTreeSet<ParaId>,
800
7552
        maybe_tip: &Option<BalanceOf<Runtime>>,
801
7552
    ) -> Result<Weight, DispatchError> {
802
        use frame_support::traits::Currency;
803
        type ServicePaymentCurrency = <Runtime as pallet_services_payment::Config>::Currency;
804

            
805
        // Check if the container chain has enough credits for a session assignments
806
7389
        let maybe_assignment_imbalance =
807
7552
            if  pallet_services_payment::Pallet::<Runtime>::burn_collator_assignment_free_credit_for_para(&para_id).is_err() {
808
219
                let (amount_to_charge, _weight) =
809
219
                    <Runtime as pallet_services_payment::Config>::ProvideCollatorAssignmentCost::collator_assignment_cost(&para_id);
810
219
                Some(<ServicePaymentCurrency as Currency<AccountId>>::withdraw(
811
219
                    &pallet_services_payment::Pallet::<Runtime>::parachain_tank(para_id),
812
219
                    amount_to_charge,
813
219
                    WithdrawReasons::FEE,
814
219
                    ExistenceRequirement::KeepAlive,
815
219
                )?)
816
            } else {
817
7333
                None
818
            };
819

            
820
7389
        if let Some(tip) = maybe_tip {
821
4856
            if let Err(e) = pallet_services_payment::Pallet::<Runtime>::charge_tip(&para_id, tip) {
822
                // Return assignment imbalance to tank on error
823
13
                if let Some(assignment_imbalance) = maybe_assignment_imbalance {
824
                    <Runtime as pallet_services_payment::Config>::Currency::resolve_creating(
825
                        &pallet_services_payment::Pallet::<Runtime>::parachain_tank(para_id),
826
                        assignment_imbalance,
827
                    );
828
13
                }
829
13
                return Err(e);
830
4843
            }
831
2533
        }
832

            
833
7376
        if let Some(assignment_imbalance) = maybe_assignment_imbalance {
834
56
            <Runtime as pallet_services_payment::Config>::OnChargeForCollatorAssignment::on_unbalanced(assignment_imbalance);
835
7320
        }
836

            
837
        // If the para has been assigned collators for this session it must have enough block credits
838
        // for the current and the next session.
839
7376
        let block_credits_needed = if currently_assigned.contains(&para_id) {
840
6748
            blocks_per_session * 2
841
        } else {
842
628
            blocks_per_session
843
        };
844
        // Check if the container chain has enough credits for producing blocks
845
7376
        let free_block_credits =
846
7376
            pallet_services_payment::BlockProductionCredits::<Runtime>::get(para_id)
847
7376
                .unwrap_or_default();
848
7376
        let remaining_block_credits = block_credits_needed.saturating_sub(free_block_credits);
849
7376
        let (block_production_costs, _) =
850
7376
            <Runtime as pallet_services_payment::Config>::ProvideBlockProductionCost::block_cost(
851
7376
                &para_id,
852
7376
            );
853
7376
        // Check if we can withdraw
854
7376
        let remaining_block_credits_to_pay =
855
7376
            u128::from(remaining_block_credits).saturating_mul(block_production_costs);
856
7376
        let remaining_to_pay = remaining_block_credits_to_pay;
857
7376
        // This should take into account whether we tank goes below ED
858
7376
        // The true refers to keepAlive
859
7376
        Balances::can_withdraw(
860
7376
            &pallet_services_payment::Pallet::<Runtime>::parachain_tank(para_id),
861
7376
            remaining_to_pay,
862
7376
        )
863
7376
        .into_result(true)?;
864
        // TODO: Have proper weight
865
7212
        Ok(Weight::zero())
866
7552
    }
867
}
868

            
869
impl<AC> ParaIdAssignmentHooks<BalanceOf<Runtime>, AC> for ParaIdAssignmentHooksImpl {
870
6678
    fn pre_assignment(para_ids: &mut Vec<ParaId>, currently_assigned: &BTreeSet<ParaId>) {
871
6678
        let blocks_per_session = Period::get();
872
6678
        para_ids.retain(|para_id| {
873
4996
            with_transaction(|| {
874
4996
                let max_tip =
875
4996
                    pallet_services_payment::MaxTip::<Runtime>::get(para_id).unwrap_or_default();
876
4996
                TransactionOutcome::Rollback(Self::charge_para_ids_internal(
877
4996
                    blocks_per_session,
878
4996
                    *para_id,
879
4996
                    currently_assigned,
880
4996
                    &Some(max_tip),
881
4996
                ))
882
4996
            })
883
4996
            .is_ok()
884
6678
        });
885
6678
    }
886

            
887
3339
    fn post_assignment(
888
3339
        current_assigned: &BTreeSet<ParaId>,
889
3339
        new_assigned: &mut BTreeMap<ParaId, Vec<AC>>,
890
3339
        maybe_tip: &Option<BalanceOf<Runtime>>,
891
3339
    ) -> Weight {
892
3339
        let blocks_per_session = Period::get();
893
3339
        let mut total_weight = Weight::zero();
894
5272
        new_assigned.retain(|&para_id, collators| {
895
4656
            // Short-circuit in case collators are empty
896
4656
            if collators.is_empty() {
897
2100
                return true;
898
2556
            }
899
2556
            with_storage_layer(|| {
900
2556
                Self::charge_para_ids_internal(
901
2556
                    blocks_per_session,
902
2556
                    para_id,
903
2556
                    current_assigned,
904
2556
                    maybe_tip,
905
2556
                )
906
2556
            })
907
2556
            .inspect(|weight| {
908
2556
                total_weight += *weight;
909
2556
            })
910
2556
            .is_ok()
911
5272
        });
912
3339
        total_weight
913
3339
    }
914

            
915
    /// Make those para ids valid by giving them enough credits, for benchmarking.
916
    #[cfg(feature = "runtime-benchmarks")]
917
    fn make_valid_para_ids(para_ids: &[ParaId]) {
918
        use frame_support::assert_ok;
919

            
920
        let blocks_per_session = Period::get();
921
        // Enough credits to run any benchmark
922
        let block_credits = 20 * blocks_per_session;
923
        let session_credits = 20;
924

            
925
        for para_id in para_ids {
926
            assert_ok!(ServicesPayment::set_block_production_credits(
927
                RuntimeOrigin::root(),
928
                *para_id,
929
                block_credits,
930
            ));
931
            assert_ok!(ServicesPayment::set_collator_assignment_credits(
932
                RuntimeOrigin::root(),
933
                *para_id,
934
                session_credits,
935
            ));
936
        }
937
    }
938
}
939

            
940
impl pallet_collator_assignment::Config for Runtime {
941
    type RuntimeEvent = RuntimeEvent;
942
    type HostConfiguration = Configuration;
943
    type ContainerChains = Registrar;
944
    type SessionIndex = u32;
945
    type SelfParaId = ParachainInfo;
946
    type ShouldRotateAllCollators =
947
        RotateCollatorsEveryNSessions<ConfigurationCollatorRotationSessionPeriod>;
948
    type Randomness =
949
        pallet_collator_assignment::ParachainRandomness<BabeGetRandomnessForNextBlock, Runtime>;
950
    type RemoveInvulnerables = RemoveInvulnerablesImpl;
951
    type ParaIdAssignmentHooks = ParaIdAssignmentHooksImpl;
952
    type CollatorAssignmentTip = ServicesPayment;
953
    type Currency = Balances;
954
    type ForceEmptyOrchestrator = ConstBool<false>;
955
    type CoreAllocationConfiguration = ();
956
    type WeightInfo = weights::pallet_collator_assignment::SubstrateWeight<Runtime>;
957
}
958

            
959
impl pallet_authority_assignment::Config for Runtime {
960
    type SessionIndex = u32;
961
    type AuthorityId = NimbusId;
962
}
963

            
964
pub const FIXED_BLOCK_PRODUCTION_COST: u128 = 1 * currency::MICRODANCE;
965
pub const FIXED_COLLATOR_ASSIGNMENT_COST: u128 = 100 * currency::MICRODANCE;
966

            
967
pub struct BlockProductionCost<Runtime>(PhantomData<Runtime>);
968
impl ProvideBlockProductionCost<Runtime> for BlockProductionCost<Runtime> {
969
7784
    fn block_cost(_para_id: &ParaId) -> (u128, Weight) {
970
7784
        (FIXED_BLOCK_PRODUCTION_COST, Weight::zero())
971
7784
    }
972
}
973

            
974
pub struct CollatorAssignmentCost<Runtime>(PhantomData<Runtime>);
975
impl ProvideCollatorAssignmentCost<Runtime> for CollatorAssignmentCost<Runtime> {
976
229
    fn collator_assignment_cost(_para_id: &ParaId) -> (u128, Weight) {
977
229
        (FIXED_COLLATOR_ASSIGNMENT_COST, Weight::zero())
978
229
    }
979
}
980

            
981
parameter_types! {
982
    // 60 days worth of blocks
983
    pub const FreeBlockProductionCredits: BlockNumber = 60 * DAYS;
984
    // 60 days worth of blocks
985
    pub const FreeCollatorAssignmentCredits: u32 = FreeBlockProductionCredits::get()/Period::get();
986
}
987

            
988
impl pallet_services_payment::Config for Runtime {
989
    type RuntimeEvent = RuntimeEvent;
990
    /// Handler for fees
991
    type OnChargeForBlock = ();
992
    type OnChargeForCollatorAssignment = ();
993
    type OnChargeForCollatorAssignmentTip = ();
994
    /// Currency type for fee payment
995
    type Currency = Balances;
996
    /// Provider of a block cost which can adjust from block to block
997
    type ProvideBlockProductionCost = BlockProductionCost<Runtime>;
998
    /// Provider of a block cost which can adjust from block to block
999
    type ProvideCollatorAssignmentCost = CollatorAssignmentCost<Runtime>;
    /// The maximum number of block credits that can be accumulated
    type FreeBlockProductionCredits = FreeBlockProductionCredits;
    /// The maximum number of session credits that can be accumulated
    type FreeCollatorAssignmentCredits = FreeCollatorAssignmentCredits;
    type ManagerOrigin =
        EitherOfDiverse<pallet_registrar::EnsureSignedByManager<Runtime>, EnsureRoot<AccountId>>;
    type WeightInfo = weights::pallet_services_payment::SubstrateWeight<Runtime>;
}
parameter_types! {
    pub const ProfileDepositBaseFee: Balance = currency::STORAGE_ITEM_FEE;
    pub const ProfileDepositByteFee: Balance = currency::STORAGE_BYTE_FEE;
    #[derive(Clone)]
    pub const MaxAssignmentsPerParaId: u32 = 10;
    #[derive(Clone)]
    pub const MaxNodeUrlLen: u32 = 200;
}
pub type DataPreserversProfileId = u64;
impl pallet_data_preservers::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type RuntimeHoldReason = RuntimeHoldReason;
    type Currency = Balances;
    type WeightInfo = weights::pallet_data_preservers::SubstrateWeight<Runtime>;
    type ProfileId = DataPreserversProfileId;
    type ProfileDeposit = tp_traits::BytesDeposit<ProfileDepositBaseFee, ProfileDepositByteFee>;
    type AssignmentProcessor = tp_data_preservers_common::AssignmentProcessor<Runtime>;
    type AssignmentOrigin = pallet_registrar::EnsureSignedByManager<Runtime>;
    type ForceSetProfileOrigin = EnsureRoot<AccountId>;
    type MaxAssignmentsPerParaId = MaxAssignmentsPerParaId;
    type MaxNodeUrlLen = MaxNodeUrlLen;
    type MaxParaIdsVecLen = MaxLengthParaIds;
}
impl pallet_author_noting::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type ContainerChains = CollatorAssignment;
    type SlotBeacon = dp_consensus::AuraDigestSlotBeacon<Runtime>;
    type ContainerChainAuthor = CollatorAssignment;
    type AuthorNotingHook = (
        XcmCoreBuyer,
        InflationRewards,
        ServicesPayment,
        InactivityTracking,
    );
    type RelayOrPara = pallet_author_noting::ParaMode<
        cumulus_pallet_parachain_system::RelaychainDataProvider<Self>,
    >;
    type MaxContainerChains = MaxLengthParaIds;
    type WeightInfo = weights::pallet_author_noting::SubstrateWeight<Runtime>;
}
parameter_types! {
    pub const PotId: PalletId = PalletId(*b"PotStake");
    pub const MaxCandidates: u32 = 1000;
    pub const MinCandidates: u32 = 5;
    pub const SessionLength: BlockNumber = 5;
    pub const MaxInvulnerables: u32 = 100;
    pub const ExecutiveBody: BodyId = BodyId::Executive;
}
impl pallet_invulnerables::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type UpdateOrigin = EnsureRoot<AccountId>;
    type MaxInvulnerables = MaxInvulnerables;
    type CollatorId = <Self as frame_system::Config>::AccountId;
    type CollatorIdOf = ConvertInto;
    type CollatorRegistration = Session;
    type WeightInfo = weights::pallet_invulnerables::SubstrateWeight<Runtime>;
    #[cfg(feature = "runtime-benchmarks")]
    type Currency = Balances;
}
parameter_types! {
    #[derive(Clone)]
    pub const MaxLengthParaIds: u32 = 100u32;
    pub const MaxEncodedGenesisDataSize: u32 = 5_000_000u32; // 5MB
}
pub struct CurrentSessionIndexGetter;
impl tp_traits::GetSessionIndex<u32> for CurrentSessionIndexGetter {
    /// Returns current session index.
57059
    fn session_index() -> u32 {
57059
        Session::current_index()
57059
    }
    #[cfg(feature = "runtime-benchmarks")]
    fn skip_to_session(session_index: SessionIndex) {
        while Session::current_index() < session_index {
            Session::rotate_session();
        }
    }
}
impl pallet_configuration::Config for Runtime {
    type SessionDelay = ConstU32<2>;
    type SessionIndex = u32;
    type CurrentSessionIndex = CurrentSessionIndexGetter;
    type ForceEmptyOrchestrator = ConstBool<false>;
    type WeightInfo = weights::pallet_configuration::SubstrateWeight<Runtime>;
}
pub struct DanceboxRegistrarHooks;
impl RegistrarHooks for DanceboxRegistrarHooks {
153
    fn para_marked_valid_for_collating(para_id: ParaId) -> Weight {
153
        // Give free credits but only once per para id
153
        ServicesPayment::give_free_credits(&para_id)
153
    }
72
    fn para_deregistered(para_id: ParaId) -> Weight {
        // Clear pallet_author_noting storage
72
        if let Err(e) = AuthorNoting::kill_author_data(RuntimeOrigin::root(), para_id) {
            log::warn!(
                "Failed to kill_author_data after para id {} deregistered: {:?}",
                u32::from(para_id),
                e,
            );
72
        }
        // Remove bootnodes from pallet_data_preservers
72
        DataPreservers::para_deregistered(para_id);
72

            
72
        ServicesPayment::para_deregistered(para_id);
72

            
72
        XcmCoreBuyer::para_deregistered(para_id);
72

            
72
        Weight::default()
72
    }
154
    fn check_valid_for_collating(para_id: ParaId) -> DispatchResult {
154
        // To be able to call mark_valid_for_collating, a container chain must have bootnodes
154
        DataPreservers::check_valid_for_collating(para_id)
154
    }
    #[cfg(feature = "runtime-benchmarks")]
    fn benchmarks_ensure_valid_for_collating(para_id: ParaId) {
        use {
            frame_support::traits::EnsureOriginWithArg,
            pallet_data_preservers::{ParaIdsFilter, Profile, ProfileMode},
        };
        let profile = Profile {
            url: b"/ip4/127.0.0.1/tcp/33049/ws/p2p/12D3KooWHVMhQDHBpj9vQmssgyfspYecgV6e3hH1dQVDUkUbCYC9"
                    .to_vec()
                    .try_into()
                    .expect("to fit in BoundedVec"),
            para_ids: ParaIdsFilter::AnyParaId,
            mode: ProfileMode::Bootnode,
            assignment_request: tp_data_preservers_common::ProviderRequest::Free,
        };
        let profile_id = pallet_data_preservers::NextProfileId::<Runtime>::get();
        let profile_owner = AccountId::new([1u8; 32]);
        DataPreservers::force_create_profile(RuntimeOrigin::root(), profile, profile_owner)
            .expect("profile create to succeed");
        let para_manager =
            <Runtime as pallet_data_preservers::Config>::AssignmentOrigin::try_successful_origin(
                &para_id,
            )
            .expect("should be able to get para manager");
        DataPreservers::start_assignment(
            para_manager,
            profile_id,
            para_id,
            tp_data_preservers_common::AssignerExtra::Free,
        )
        .expect("assignement to work");
        assert!(
            pallet_data_preservers::Assignments::<Runtime>::get(para_id).contains(&profile_id),
            "profile should be correctly assigned"
        );
    }
}
pub struct PalletRelayStorageRootProvider;
impl RelayStorageRootProvider for PalletRelayStorageRootProvider {
12
    fn get_relay_storage_root(relay_block_number: u32) -> Option<H256> {
12
        pallet_relay_storage_roots::pallet::RelayStorageRoot::<Runtime>::get(relay_block_number)
12
    }
    #[cfg(feature = "runtime-benchmarks")]
    fn set_relay_storage_root(relay_block_number: u32, storage_root: Option<H256>) {
        pallet_relay_storage_roots::pallet::RelayStorageRootKeys::<Runtime>::mutate(|x| {
            if storage_root.is_some() {
                if x.is_full() {
                    let key = x.remove(0);
                    pallet_relay_storage_roots::pallet::RelayStorageRoot::<Runtime>::remove(key);
                }
                let pos = x.iter().position(|x| *x >= relay_block_number);
                if let Some(pos) = pos {
                    if x[pos] != relay_block_number {
                        x.try_insert(pos, relay_block_number).unwrap();
                    }
                } else {
                    // Push at end
                    x.try_push(relay_block_number).unwrap();
                }
            } else {
                let pos = x.iter().position(|x| *x == relay_block_number);
                if let Some(pos) = pos {
                    x.remove(pos);
                }
            }
        });
        pallet_relay_storage_roots::pallet::RelayStorageRoot::<Runtime>::set(
            relay_block_number,
            storage_root,
        );
    }
}
impl pallet_registrar::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type RegistrarOrigin =
        EitherOfDiverse<pallet_registrar::EnsureSignedByManager<Runtime>, EnsureRoot<AccountId>>;
    type MarkValidForCollatingOrigin = EnsureRoot<AccountId>;
    type MaxLengthParaIds = MaxLengthParaIds;
    type MaxGenesisDataSize = MaxEncodedGenesisDataSize;
    type RegisterWithRelayProofOrigin = EnsureSigned<AccountId>;
    type RelayStorageRootProvider = PalletRelayStorageRootProvider;
    type SessionDelay = ConstU32<2>;
    type SessionIndex = u32;
    type CurrentSessionIndex = CurrentSessionIndexGetter;
    type Currency = Balances;
    type RegistrarHooks = DanceboxRegistrarHooks;
    type RuntimeHoldReason = RuntimeHoldReason;
    type InnerRegistrar = ();
    type WeightInfo = weights::pallet_registrar::SubstrateWeight<Runtime>;
    type DataDepositPerByte = DataDepositPerByte;
}
impl pallet_authority_mapping::Config for Runtime {
    type SessionIndex = u32;
    type SessionRemovalBoundary = ConstU32<2>;
    type AuthorityId = NimbusId;
}
impl pallet_sudo::Config for Runtime {
    type RuntimeCall = RuntimeCall;
    type RuntimeEvent = RuntimeEvent;
    type WeightInfo = weights::pallet_sudo::SubstrateWeight<Runtime>;
}
impl pallet_utility::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type RuntimeCall = RuntimeCall;
    type PalletsOrigin = OriginCaller;
    type WeightInfo = weights::pallet_utility::SubstrateWeight<Runtime>;
}
/// The type used to represent the kinds of proxying allowed.
#[apply(derive_storage_traits)]
#[derive(Copy, Ord, PartialOrd, MaxEncodedLen)]
#[allow(clippy::unnecessary_cast)]
pub enum ProxyType {
181
    /// All calls can be proxied. This is the trivial/most permissive filter.
    Any = 0,
56
    /// Only extrinsics that do not transfer funds.
    NonTransfer = 1,
49
    /// Only extrinsics related to governance (democracy and collectives).
    Governance = 2,
43
    /// Only extrinsics related to staking.
    Staking = 3,
103
    /// Allow to veto an announced proxy call.
    CancelProxy = 4,
37
    /// Allow extrinsic related to Balances.
    Balances = 5,
37
    /// Allow extrinsics related to Registrar
    Registrar = 6,
31
    /// Allow extrinsics related to Registrar that needs to be called through Sudo
    SudoRegistrar = 7,
37
    /// Allow extrinsics from the Session pallet for key management.
    SessionKeyManagement = 8,
}
impl Default for ProxyType {
    fn default() -> Self {
        Self::Any
    }
}
impl InstanceFilter<RuntimeCall> for ProxyType {
94
    fn filter(&self, c: &RuntimeCall) -> bool {
94
        // Since proxy filters are respected in all dispatches of the Utility
94
        // pallet, it should never need to be filtered by any proxy.
94
        if let RuntimeCall::Utility(..) = c {
            return true;
94
        }
94

            
94
        match self {
25
            ProxyType::Any => true,
            ProxyType::NonTransfer => {
8
                matches!(
14
                    c,
                    RuntimeCall::System(..)
                        | RuntimeCall::ParachainSystem(..)
                        | RuntimeCall::Timestamp(..)
                        | RuntimeCall::Proxy(..)
                        | RuntimeCall::Registrar(..)
                )
            }
            // We don't have governance yet
1
            ProxyType::Governance => false,
            ProxyType::Staking => {
1
                matches!(c, RuntimeCall::Session(..) | RuntimeCall::PooledStaking(..))
            }
7
            ProxyType::CancelProxy => matches!(
6
                c,
                RuntimeCall::Proxy(pallet_proxy::Call::reject_announcement { .. })
            ),
            ProxyType::Balances => {
13
                matches!(c, RuntimeCall::Balances(..))
            }
            ProxyType::Registrar => {
1
                matches!(
13
                    c,
                    RuntimeCall::Registrar(..) | RuntimeCall::DataPreservers(..)
                )
            }
7
            ProxyType::SudoRegistrar => match c {
7
                RuntimeCall::Sudo(pallet_sudo::Call::sudo { call: ref x }) => {
1
                    matches!(
7
                        x.as_ref(),
                        &RuntimeCall::Registrar(..) | &RuntimeCall::DataPreservers(..)
                    )
                }
                _ => false,
            },
            ProxyType::SessionKeyManagement => {
7
                matches!(c, RuntimeCall::Session(..))
            }
        }
94
    }
    fn is_superset(&self, o: &Self) -> bool {
        match (self, o) {
            (x, y) if x == y => true,
            (ProxyType::Any, _) => true,
            (_, ProxyType::Any) => false,
            _ => false,
        }
    }
}
impl pallet_proxy::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type RuntimeCall = RuntimeCall;
    type Currency = Balances;
    type ProxyType = ProxyType;
    // One storage item; key size 32, value size 8
    type ProxyDepositBase = ConstU128<{ currency::deposit(1, 8) }>;
    // Additional storage item size of 33 bytes (32 bytes AccountId + 1 byte sizeof(ProxyType)).
    type ProxyDepositFactor = ConstU128<{ currency::deposit(0, 33) }>;
    type MaxProxies = ConstU32<32>;
    type MaxPending = ConstU32<32>;
    type CallHasher = BlakeTwo256;
    type AnnouncementDepositBase = ConstU128<{ currency::deposit(1, 8) }>;
    // Additional storage item size of 68 bytes:
    // - 32 bytes AccountId
    // - 32 bytes Hasher (Blake2256)
    // - 4 bytes BlockNumber (u32)
    type AnnouncementDepositFactor = ConstU128<{ currency::deposit(0, 68) }>;
    type WeightInfo = weights::pallet_proxy::SubstrateWeight<Runtime>;
}
pub struct XcmExecutionManager;
impl xcm_primitives::PauseXcmExecution for XcmExecutionManager {
42
    fn suspend_xcm_execution() -> DispatchResult {
42
        XcmpQueue::suspend_xcm_execution(RuntimeOrigin::root())
42
    }
36
    fn resume_xcm_execution() -> DispatchResult {
36
        XcmpQueue::resume_xcm_execution(RuntimeOrigin::root())
36
    }
}
impl pallet_migrations::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type MigrationsList = (tanssi_runtime_common::migrations::DanceboxMigrations<Runtime>,);
    type XcmExecutionManager = XcmExecutionManager;
}
parameter_types! {
    pub MbmServiceWeight: Weight = Perbill::from_percent(80) * RuntimeBlockWeights::get().max_block;
}
impl pallet_multiblock_migrations::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    #[cfg(not(feature = "runtime-benchmarks"))]
    type Migrations = ();
    // 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 {
696
    fn contains(c: &RuntimeCall) -> bool {
678
        !matches!(
696
            c,
            RuntimeCall::Balances(..)
                | RuntimeCall::Registrar(..)
                | RuntimeCall::Session(..)
                | RuntimeCall::System(..)
                | RuntimeCall::PooledStaking(..)
                | RuntimeCall::Utility(..)
                | RuntimeCall::PolkadotXcm(..)
        )
696
    }
}
/// Normal Call Filter
pub struct NormalFilter;
impl Contains<RuntimeCall> for NormalFilter {
96617
    fn contains(_c: &RuntimeCall) -> bool {
96617
        true
96617
    }
}
impl pallet_maintenance_mode::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    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 SessionTimer<Delay>(PhantomData<Delay>);
impl<Delay> Timer for SessionTimer<Delay>
where
    Delay: Get<u32>,
{
    type Instant = u32;
243
    fn now() -> Self::Instant {
243
        Session::current_index()
243
    }
85
    fn is_elapsed(instant: &Self::Instant) -> bool {
85
        let delay = Delay::get();
85
        let Some(end) = instant.checked_add(delay) else {
            return false;
        };
85
        end <= Self::now()
85
    }
    #[cfg(feature = "runtime-benchmarks")]
    fn elapsed_instant() -> Self::Instant {
        let delay = Delay::get();
        Self::now()
            .checked_add(delay)
            .expect("overflow when computing valid elapsed instant")
    }
    #[cfg(feature = "runtime-benchmarks")]
    fn skip_to_elapsed() {
        let session_to_reach = Self::elapsed_instant();
        while Self::now() < session_to_reach {
            Session::rotate_session();
        }
    }
}
pub struct CandidateHasRegisteredKeys;
impl IsCandidateEligible<AccountId> for CandidateHasRegisteredKeys {
139
    fn is_candidate_eligible(a: &AccountId) -> bool {
139
        <Session as ValidatorRegistration<AccountId>>::is_registered(a)
139
    }
    #[cfg(feature = "runtime-benchmarks")]
    fn make_candidate_eligible(a: &AccountId, eligible: bool) {
        use sp_core::crypto::UncheckedFrom;
        if eligible {
            let account_slice: &[u8; 32] = a.as_ref();
            let _ = Session::set_keys(
                RuntimeOrigin::signed(a.clone()),
                SessionKeys {
                    nimbus: NimbusId::unchecked_from(*account_slice),
                },
                vec![],
            );
        } else {
            let _ = Session::purge_keys(RuntimeOrigin::signed(a.clone()));
        }
    }
}
parameter_types! {
    pub const MaxCandidatesBufferSize: u32 = 100;
}
impl pallet_pooled_staking::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type Currency = Balances;
    type Balance = Balance;
    type StakingAccount = StakingAccount;
    type InitialManualClaimShareValue = InitialManualClaimShareValue;
    type InitialAutoCompoundingShareValue = InitialAutoCompoundingShareValue;
    type MinimumSelfDelegation = MinimumSelfDelegation;
    type RuntimeHoldReason = RuntimeHoldReason;
    type RewardsCollatorCommission = RewardsCollatorCommission;
    type JoiningRequestTimer = SessionTimer<StakingSessionDelay>;
    type LeavingRequestTimer = SessionTimer<StakingSessionDelay>;
    type EligibleCandidatesBufferSize = MaxCandidatesBufferSize;
    type EligibleCandidatesFilter = CandidateHasRegisteredKeys;
    type WeightInfo = weights::pallet_pooled_staking::SubstrateWeight<Runtime>;
}
parameter_types! {
    pub ParachainBondAccount: AccountId32 = PalletId(*b"ParaBond").into_account_truncating();
    pub PendingRewardsAccount: AccountId32 = PalletId(*b"PENDREWD").into_account_truncating();
    // The equation to solve is:
    // initial_supply * (1.05) = initial_supply * (1+x)^5_259_600
    // we should solve for x = (1.05)^(1/5_259_600) -1 -> 0.000000009 per block or 9/1_000_000_000
    // 1% in the case of dev mode
    // TODO: check if we can put the prod inflation for tests too
    // TODO: better calculus for going from annual to block inflation (if it can be done)
    pub const InflationRate: Perbill = prod_or_fast!(Perbill::from_parts(9), Perbill::from_percent(1));
    // 30% for parachain bond, so 70% for staking
    pub const RewardsPortion: Perbill = Perbill::from_percent(70);
}
pub struct GetSelfChainBlockAuthor;
impl MaybeSelfChainBlockAuthor<AccountId32> for GetSelfChainBlockAuthor {
79885
    fn get_block_author() -> Option<AccountId32> {
79885
        // TODO: we should do a refactor here, and use either authority-mapping or collator-assignemnt
79885
        // we should also make sure we actually account for the weight of these
79885
        // although most of these should be cached as they are read every block
79885
        let slot = u64::from(<Runtime as pallet_author_inherent::Config>::SlotBeacon::slot());
79885
        let self_para_id = ParachainInfo::get();
79885
        CollatorAssignment::author_for_slot(slot.into(), self_para_id)
79885
    }
}
pub struct OnUnbalancedInflation;
impl frame_support::traits::OnUnbalanced<Credit<AccountId, Balances>> for OnUnbalancedInflation {
27099
    fn on_nonzero_unbalanced(credit: Credit<AccountId, Balances>) {
27099
        let _ = <Balances as Balanced<_>>::resolve(&ParachainBondAccount::get(), credit);
27099
    }
}
impl pallet_inflation_rewards::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type Currency = Balances;
    type ContainerChains = Registrar;
    type GetSelfChainBlockAuthor = GetSelfChainBlockAuthor;
    type InflationRate = InflationRate;
    type OnUnbalanced = OnUnbalancedInflation;
    type PendingRewardsAccount = PendingRewardsAccount;
    type StakingRewardsDistributor = InvulnerableRewardDistribution<Self, Balances, PooledStaking>;
    type RewardsPortion = RewardsPortion;
}
impl pallet_tx_pause::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type RuntimeCall = RuntimeCall;
    type PauseOrigin = EnsureRoot<AccountId>;
    type UnpauseOrigin = EnsureRoot<AccountId>;
    type WhitelistedCalls = ();
    type MaxNameLen = ConstU32<256>;
    type WeightInfo = weights::pallet_tx_pause::SubstrateWeight<Runtime>;
}
parameter_types! {
    // 1 entry, storing 253 bytes on-chain in the worst case
    pub const OpenStreamHoldAmount: Balance = currency::deposit(1, 253);
}
impl pallet_stream_payment::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type StreamId = StreamId;
    type TimeUnit = tp_stream_payment_common::TimeUnit;
    type Balance = Balance;
    type AssetId = tp_stream_payment_common::AssetId;
    type AssetsManager = tp_stream_payment_common::AssetsManager<Runtime>;
    type Currency = Balances;
    type OpenStreamHoldAmount = OpenStreamHoldAmount;
    type RuntimeHoldReason = RuntimeHoldReason;
    type TimeProvider = tp_stream_payment_common::TimeProvider<Runtime>;
    type WeightInfo = weights::pallet_stream_payment::SubstrateWeight<Runtime>;
}
parameter_types! {
    // 1 entry, storing 258 bytes on-chain
    pub const BasicDeposit: Balance = currency::deposit(1, 258);
    // 1 entry, storing 53 bytes on-chain
    pub const SubAccountDeposit: Balance = currency::deposit(1, 53);
    // Additional bytes adds 0 entries, storing 1 byte on-chain
    pub const ByteDeposit: Balance = currency::deposit(0, 1);
    pub const UsernameDeposit: Balance = currency::deposit(0, 32);
    pub const MaxSubAccounts: u32 = 100;
    pub const MaxAdditionalFields: u32 = 100;
    pub const MaxRegistrars: u32 = 20;
}
impl pallet_identity::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type Currency = Balances;
    type BasicDeposit = BasicDeposit;
    type ByteDeposit = ByteDeposit;
    type UsernameDeposit = UsernameDeposit;
    type SubAccountDeposit = SubAccountDeposit;
    type MaxSubAccounts = MaxSubAccounts;
    type MaxRegistrars = MaxRegistrars;
    type IdentityInformation = pallet_identity::legacy::IdentityInfo<MaxAdditionalFields>;
    // Slashed balances are burnt
    type Slashed = ();
    type ForceOrigin = EnsureRoot<AccountId>;
    type RegistrarOrigin = EnsureRoot<AccountId>;
    type OffchainSignature = Signature;
    type SigningPublicKey = <Signature as Verify>::Signer;
    type UsernameAuthorityOrigin = EnsureRoot<Self::AccountId>;
    type PendingUsernameExpiration = ConstU32<{ 7 * DAYS }>;
    type UsernameGracePeriod = ConstU32<{ 30 * DAYS }>;
    type MaxSuffixLength = ConstU32<7>;
    type MaxUsernameLength = ConstU32<32>;
    type WeightInfo = weights::pallet_identity::SubstrateWeight<Runtime>;
}
parameter_types! {
    pub const TreasuryId: PalletId = PalletId(*b"tns/tsry");
    pub const ProposalBond: Permill = Permill::from_percent(5);
    pub TreasuryAccount: AccountId = Treasury::account_id();
    pub const MaxBalance: Balance = Balance::max_value();
    // We allow it to be 1 minute in fast mode to be able to test it
    pub const SpendPeriod: BlockNumber = prod_or_fast!(6 * DAYS, 1 * MINUTES);
    pub const DataDepositPerByte: Balance = 1 * CENTS;
}
impl pallet_treasury::Config for Runtime {
    type PalletId = TreasuryId;
    type Currency = Balances;
    type RejectOrigin = EnsureRoot<AccountId>;
    type RuntimeEvent = RuntimeEvent;
    // If proposal gets rejected, bond goes to treasury
    type SpendPeriod = SpendPeriod;
    type Burn = ();
    type BurnDestination = ();
    type MaxApprovals = ConstU32<100>;
    type WeightInfo = weights::pallet_treasury::SubstrateWeight<Runtime>;
    type SpendFunds = ();
    type SpendOrigin =
        frame_system::EnsureWithSuccess<EnsureRoot<AccountId>, AccountId, MaxBalance>;
    type AssetKind = ();
    type Beneficiary = AccountId;
    type BeneficiaryLookup = IdentityLookup<AccountId>;
    type Paymaster = PayFromAccount<Balances, TreasuryAccount>;
    // TODO: implement pallet-asset-rate to allow the treasury to spend other assets
    type BalanceConverter = UnityAssetBalanceConversion;
    type PayoutPeriod = ConstU32<{ 30 * DAYS }>;
    type BlockNumberProvider = System;
    #[cfg(feature = "runtime-benchmarks")]
    type BenchmarkHelper = tanssi_runtime_common::benchmarking::TreasuryBenchmarkHelper<Runtime>;
}
parameter_types! {
    // One storage item; key size 32; value is size 4+4+16+32. Total = 1 * (32 + 56)
    pub const DepositBase: Balance = currency::deposit(1, 88);
    // Additional storage item size of 32 bytes.
    pub const DepositFactor: Balance = currency::deposit(0, 32);
    pub const MaxSignatories: u32 = 100;
}
impl pallet_multisig::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type RuntimeCall = RuntimeCall;
    type Currency = Balances;
    type DepositBase = DepositBase;
    type DepositFactor = DepositFactor;
    type MaxSignatories = MaxSignatories;
    type WeightInfo = weights::pallet_multisig::SubstrateWeight<Runtime>;
}
parameter_types! {
    pub const MaxInactiveSessions: u32 = 5;
}
impl pallet_inactivity_tracking::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type CollatorId = CollatorId;
    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 WeightInfo = weights::pallet_inactivity_tracking::SubstrateWeight<Runtime>;
}
// Create the runtime by composing the FRAME pallets that were previously configured.
11356903
construct_runtime!(
1032979
    pub enum Runtime
1032979
    {
1032979
        // System support stuff.
1032979
        System: frame_system = 0,
1032979
        ParachainSystem: cumulus_pallet_parachain_system = 1,
1032979
        Timestamp: pallet_timestamp = 2,
1032979
        ParachainInfo: parachain_info = 3,
1032979
        Sudo: pallet_sudo = 4,
1032979
        Utility: pallet_utility = 5,
1032979
        Proxy: pallet_proxy = 6,
1032979
        Migrations: pallet_migrations = 7,
1032979
        MultiBlockMigrations: pallet_multiblock_migrations = 121,
1032979
        MaintenanceMode: pallet_maintenance_mode = 8,
1032979
        TxPause: pallet_tx_pause = 9,
1032979

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

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

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

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

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

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

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

            
1032979
        RootTesting: pallet_root_testing = 100,
1032979
        AsyncBacking: pallet_async_backing::{Pallet, Storage} = 110,
1032979
    }
11749690
);
#[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]
    );
}
27181
pub fn get_para_id_authorities(para_id: ParaId) -> Option<Vec<NimbusId>> {
27181
    let parent_number = System::block_number();
27181

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

            
27181
    if para_id == self_para_id {
27107
        Some(assigned_authorities.orchestrator_chain)
    } else {
74
        assigned_authorities.container_chains.get(&para_id).cloned()
    }
27181
}
396670
impl_runtime_apis! {
51256
    impl sp_consensus_aura::AuraApi<Block, NimbusId> for Runtime {
66832
        fn slot_duration() -> sp_consensus_aura::SlotDuration {
23982
            sp_consensus_aura::SlotDuration::from_millis(SLOT_DURATION)
23982
        }
51256

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

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

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

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

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

            
66464
        fn initialize_block(header: &<Block as BlockT>::Header) -> sp_runtime::ExtrinsicInclusionMode {
23430
            Executive::initialize_block(header)
23430
        }
51256
    }
51256

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

            
51256
        fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
528
            Runtime::metadata_at_version(version)
528
        }
51256

            
51256
        fn metadata_versions() -> Vec<u32> {
528
            Runtime::metadata_versions()
528
        }
51256
    }
51256

            
51256
    impl sp_block_builder::BlockBuilder<Block> for Runtime {
115064
        fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
96330
            Executive::apply_extrinsic(extrinsic)
96330
        }
51256

            
66464
        fn finalize_block() -> <Block as BlockT>::Header {
23430
            Executive::finalize_block()
23430
        }
51256

            
66464
        fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
23430
            data.create_extrinsics()
23430
        }
51256

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

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

            
51256
    impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
66464
        fn offchain_worker(header: &<Block as BlockT>::Header) {
23430
            Executive::offchain_worker(header)
23430
        }
51256
    }
51256

            
51256
    impl sp_session::SessionKeys<Block> for Runtime {
51272
        fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {
642
            SessionKeys::generate(seed)
642
        }
51256

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

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

            
51256
    impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {
66464
        fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {
23430
            ParachainSystem::collect_collation_info(header)
23430
        }
51256
    }
51256

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
51256
            add_benchmarks!(params, batches);
51256

            
51256
            Ok(batches)
51256
        }
51256
    }
51256

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

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

            
51256
    impl pallet_collator_assignment_runtime_api::CollatorAssignmentApi<Block, AccountId, ParaId> for Runtime {
51256
        /// Return the parachain that the given `AccountId` is collating for.
51256
        /// Returns `None` if the `AccountId` is not collating.
51264
        fn current_collator_parachain_assignment(account: AccountId) -> Option<ParaId> {
8
            let assigned_collators = CollatorAssignment::collator_container_chain();
8
            let self_para_id = ParachainInfo::get();
8

            
8
            assigned_collators.para_id_of(&account, self_para_id)
8
        }
51256

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

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

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

            
51262
        }
51256

            
51256
        /// Return the list of collators of the given `ParaId`.
51256
        /// Returns `None` if the `ParaId` is not in the registrar.
51270
        fn parachain_collators(para_id: ParaId) -> Option<Vec<AccountId>> {
14
            let assigned_collators = CollatorAssignment::collator_container_chain();
14
            let self_para_id = ParachainInfo::get();
14

            
14
            if para_id == self_para_id {
51265
                Some(assigned_collators.orchestrator_chain)
51256
            } else {
51261
                assigned_collators.container_chains.get(&para_id).cloned()
51256
            }
51270
        }
51256

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

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

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

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

            
66469
            let session_index = if should_end_session {
52332
                Session::current_index() +1
51256
            }
51256
            else {
64981
                Session::current_index()
51256
            };
51256

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

            
23435
            para_ids
23435
        }
51256

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

            
51256
        /// Fetch boot_nodes for this para id
51256
        fn boot_nodes(para_id: ParaId) -> Vec<Vec<u8>> {
            DataPreservers::assignments_profiles(para_id)
                .filter(|profile| profile.mode == pallet_data_preservers::ProfileMode::Bootnode)
                .map(|profile| profile.url.into())
                .collect()
        }
51256
    }
51256

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

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

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

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

            
51256
        /// Return the paraId assigned to a given authority
51288
        fn check_para_id_assignment(authority: NimbusId) -> Option<ParaId> {
32
            let parent_number = System::block_number();
32
            let should_end_session = <Runtime as pallet_session::Config>::ShouldEndSession::should_end_session(parent_number + 1);
51256

            
51288
            let session_index = if should_end_session {
51264
                Session::current_index() +1
51256
            }
51256
            else {
51280
                Session::current_index()
51256
            };
51288
            let assigned_authorities = AuthorityAssignment::collator_container_chain(session_index)?;
51288
            let self_para_id = ParachainInfo::get();
32

            
32
            assigned_authorities.para_id_of(&authority, self_para_id)
51288
        }
51256

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

            
12
            assigned_authorities.para_id_of(&authority, self_para_id)
51268
        }
51256
    }
51256

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

            
51256
        fn query_fee_details(
12
            uxt: <Block as BlockT>::Extrinsic,
12
            len: u32,
12
        ) -> pallet_transaction_payment::FeeDetails<Balance> {
12
            TransactionPayment::query_fee_details(uxt, len)
12
        }
51256

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

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

            
51256
    impl pallet_stream_payment_runtime_api::StreamPaymentApi<Block, StreamId, Balance, Balance>
51256
    for Runtime {
51256
        fn stream_payment_status(
54
            stream_id: StreamId,
54
            now: Option<Balance>,
54
        ) -> Result<StreamPaymentApiStatus<Balance>, StreamPaymentApiError> {
54
            match StreamPayment::stream_payment_status(stream_id, now) {
51256
                Ok(pallet_stream_payment::StreamPaymentStatus {
51256
                    payment, deposit_left, stalled
42
                }) => Ok(StreamPaymentApiStatus {
42
                    payment, deposit_left, stalled
42
                }),
51256
                Err(pallet_stream_payment::Error::<Runtime>::UnknownStreamId)
51256
                => Err(StreamPaymentApiError::UnknownStreamId),
51256
                Err(e) => Err(StreamPaymentApiError::Other(format!("{e:?}")))
51256
            }
51256
        }
51256
    }
51256

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

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

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

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

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

            
51256
    impl pallet_services_payment_runtime_api::ServicesPaymentApi<Block, Balance, ParaId> for Runtime {
51256
        fn block_cost(para_id: ParaId) -> Balance {
6
            let (block_production_costs, _) = <Runtime as pallet_services_payment::Config>::ProvideBlockProductionCost::block_cost(&para_id);
6
            block_production_costs
6
        }
51256

            
51256
        fn collator_assignment_cost(para_id: ParaId) -> Balance {
6
            let (collator_assignment_costs, _) = <Runtime as pallet_services_payment::Config>::ProvideCollatorAssignmentCost::collator_assignment_cost(&para_id);
6
            collator_assignment_costs
6
        }
51256
    }
51256

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

            
51256
        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)
        }
51256

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

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

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

            
6
            Ok([VersionedAssetId::V5(xcm_config::SelfReserve::get().into())]
6
                .into_iter()
6
                .chain(
6
                    pallet_asset_rate::ConversionRateToNative::<Runtime>::iter_keys().filter_map(|asset_id_u16| {
6
                        pallet_foreign_asset_creator::AssetIdToForeignAsset::<Runtime>::get(asset_id_u16).map(|location| {
6
                            VersionedAssetId::V5(location.into())
6
                        }).or_else(|| {
                            log::warn!("Asset `{}` is present in pallet_asset_rate but not in pallet_foreign_asset_creator", asset_id_u16);
51256
                            None
6
                        })
6
                    })
6
                )
12
                .filter_map(|asset| asset.into_version(xcm_version).map_err(|e| {
                    log::warn!("Failed to convert asset to version {}: {:?}", xcm_version, e);
51256
                }).ok())
6
                .collect())
51256
        }
51256

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

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

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

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

            
51256
    impl xcm_runtime_apis::dry_run::DryRunApi<Block, RuntimeCall, RuntimeEvent, OriginCaller> for Runtime {
51256
        fn dry_run_call(origin: OriginCaller, call: RuntimeCall) -> Result<CallDryRunEffects<RuntimeEvent>, XcmDryRunApiError> {
6
            PolkadotXcm::dry_run_call::<Runtime, xcm_config::XcmRouter, OriginCaller, RuntimeCall>(origin, call)
6
        }
51256

            
51256
        fn dry_run_xcm(origin_location: VersionedLocation, xcm: VersionedXcm<RuntimeCall>) -> Result<XcmDryRunEffects<RuntimeEvent>, XcmDryRunApiError> {
6
            PolkadotXcm::dry_run_xcm::<Runtime, xcm_config::XcmRouter, RuntimeCall, xcm_config::XcmConfig>(origin_location, xcm)
6
        }
51256
    }
51256

            
51256
    impl xcm_runtime_apis::conversions::LocationToAccountApi<Block, AccountId> for Runtime {
51256
        fn convert_location(location: VersionedLocation) -> Result<
6
            AccountId,
6
            xcm_runtime_apis::conversions::Error
6
        > {
6
            xcm_runtime_apis::conversions::LocationToAccountHelper::<
6
                AccountId,
6
                xcm_config::LocationToAccountId,
6
            >::convert_location(location)
6
        }
51256
    }
396670
}
#[allow(dead_code)]
struct CheckInherents;
// TODO: this should be removed but currently if we remove it the relay does not check anything
// related to other inherents that are not parachain-system
#[allow(deprecated)]
impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {
    fn check_inherents(
        block: &Block,
        relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,
    ) -> sp_inherents::CheckInherentsResult {
        let relay_chain_slot = relay_state_proof
            .read_slot()
            .expect("Could not read the relay chain slot from the proof");
        let inherent_data =
            cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(
                relay_chain_slot,
                sp_std::time::Duration::from_secs(6),
            )
            .create_inherent_data()
            .expect("Could not create the timestamp inherent data");
        inherent_data.check_extrinsics(block)
    }
}
cumulus_pallet_parachain_system::register_validate_block! {
    Runtime = Runtime,
    CheckInherents = CheckInherents,
    BlockExecutor = pallet_author_inherent::BlockExecutor::<Runtime, Executive>,
}
#[macro_export]
macro_rules! prod_or_fast {
    ($prod:expr, $test:expr) => {
        if cfg!(feature = "fast-runtime") {
            $test
        } else {
            $prod
        }
    };
    ($prod:expr, $test:expr, $env:expr) => {
        if cfg!(feature = "fast-runtime") {
            core::option_env!($env)
                .map(|s| s.parse().ok())
                .flatten()
                .unwrap_or($test)
        } else {
            $prod
        }
    };
}