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
//! The Dancelight runtime for v1 parachains.
18

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

            
23
// Fix compile error in impl_runtime_weights! macro
24
use {
25
    authority_discovery_primitives::AuthorityId as AuthorityDiscoveryId,
26
    beefy_primitives::{
27
        ecdsa_crypto::{AuthorityId as BeefyId, Signature as BeefySignature},
28
        mmr::{BeefyDataProvider, MmrLeafVersion},
29
    },
30
    cumulus_primitives_core::relay_chain::{HeadData, ValidationCode},
31
    dp_container_chain_genesis_data::ContainerChainGenesisDataItem,
32
    frame_support::{
33
        dispatch::{DispatchErrorWithPostInfo, DispatchResult},
34
        dynamic_params::{dynamic_pallet_params, dynamic_params},
35
        traits::{
36
            fungible::Inspect,
37
            tokens::{PayFromAccount, UnityAssetBalanceConversion},
38
            ConstBool, Contains, EverythingBut,
39
        },
40
    },
41
    frame_system::{pallet_prelude::BlockNumberFor, EnsureNever},
42
    nimbus_primitives::NimbusId,
43
    pallet_collator_assignment::{GetRandomnessForNextBlock, RotateCollatorsEveryNSessions},
44
    pallet_initializer as tanssi_initializer,
45
    pallet_invulnerables::InvulnerableRewardDistribution,
46
    pallet_registrar::Error as ContainerRegistrarError,
47
    pallet_registrar_runtime_api::ContainerChainGenesisData,
48
    pallet_services_payment::{ProvideBlockProductionCost, ProvideCollatorAssignmentCost},
49
    parachains_scheduler::common::Assignment,
50
    parity_scale_codec::{Decode, Encode, MaxEncodedLen},
51
    primitives::{
52
        slashing, ApprovalVotingParams, BlockNumber, CandidateEvent, CandidateHash,
53
        CommittedCandidateReceipt, CoreIndex, CoreState, DisputeState, ExecutorParams,
54
        GroupRotationInfo, Hash, Id as ParaId, InboundDownwardMessage, InboundHrmpMessage, Moment,
55
        NodeFeatures, Nonce, OccupiedCoreAssumption, PersistedValidationData, ScrapedOnChainVotes,
56
        SessionInfo, Signature, ValidationCodeHash, ValidatorId, ValidatorIndex,
57
        PARACHAIN_KEY_TYPE_ID,
58
    },
59
    runtime_common::{
60
        self as polkadot_runtime_common, impl_runtime_weights, impls::ToAuthor, paras_registrar,
61
        paras_sudo_wrapper, traits::Registrar as RegistrarInterface, BlockHashCount, BlockLength,
62
        SlowAdjustingFeeUpdate,
63
    },
64
    runtime_parachains::{
65
        assigner_on_demand as parachains_assigner_on_demand,
66
        configuration as parachains_configuration,
67
        disputes::{self as parachains_disputes, slashing as parachains_slashing},
68
        dmp as parachains_dmp, hrmp as parachains_hrmp,
69
        inclusion::{self as parachains_inclusion, AggregateMessageOrigin, UmpQueueId},
70
        initializer as parachains_initializer, origin as parachains_origin,
71
        paras as parachains_paras, paras_inherent as parachains_paras_inherent,
72
        runtime_api_impl::{
73
            v10 as parachains_runtime_api_impl, vstaging as vstaging_parachains_runtime_api_impl,
74
        },
75
        scheduler as parachains_scheduler, session_info as parachains_session_info,
76
        shared as parachains_shared,
77
    },
78
    scale_info::TypeInfo,
79
    serde::{Deserialize, Serialize},
80
    sp_core::{storage::well_known_keys as StorageWellKnownKeys, Get},
81
    sp_genesis_builder::PresetId,
82
    sp_runtime::{traits::BlockNumberProvider, AccountId32},
83
    sp_std::{
84
        cmp::Ordering,
85
        collections::{btree_map::BTreeMap, btree_set::BTreeSet, vec_deque::VecDeque},
86
        marker::PhantomData,
87
        prelude::*,
88
    },
89
    tp_traits::{
90
        apply, derive_storage_traits, GetHostConfiguration, GetSessionContainerChains,
91
        RegistrarHandler, RemoveParaIdsWithNoCredits, Slot, SlotFrequency,
92
    },
93
};
94

            
95
#[cfg(any(feature = "std", test))]
96
use sp_version::NativeVersion;
97
use {
98
    frame_support::{
99
        construct_runtime, derive_impl,
100
        genesis_builder_helper::{build_state, get_preset},
101
        parameter_types,
102
        traits::{
103
            fungible::{Balanced, Credit, HoldConsideration},
104
            EitherOf, EitherOfDiverse, EnsureOriginWithArg, InstanceFilter, KeyOwnerProofSystem,
105
            LinearStoragePrice, PrivilegeCmp, ProcessMessage, ProcessMessageError,
106
        },
107
        weights::{ConstantMultiplier, WeightMeter, WeightToFee as _},
108
        PalletId,
109
    },
110
    frame_system::EnsureRoot,
111
    pallet_grandpa::{fg_primitives, AuthorityId as GrandpaId},
112
    pallet_identity::legacy::IdentityInfo,
113
    pallet_session::historical as session_historical,
114
    pallet_transaction_payment::{FeeDetails, FungibleAdapter, RuntimeDispatchInfo},
115
    sp_core::{OpaqueMetadata, H256},
116
    sp_runtime::{
117
        create_runtime_str, generic, impl_opaque_keys,
118
        traits::{
119
            AccountIdConversion, BlakeTwo256, Block as BlockT, ConstU32, Extrinsic as ExtrinsicT,
120
            Hash as HashT, IdentityLookup, Keccak256, OpaqueKeys, SaturatedConversion, Verify,
121
            Zero,
122
        },
123
        transaction_validity::{TransactionPriority, TransactionSource, TransactionValidity},
124
        ApplyExtrinsicResult, FixedU128, KeyTypeId, Perbill, Percent, Permill, RuntimeDebug,
125
    },
126
    sp_staking::SessionIndex,
127
    sp_version::RuntimeVersion,
128
    xcm::{
129
        latest::prelude::*, IntoVersion, VersionedAssetId, VersionedAssets, VersionedLocation,
130
        VersionedXcm,
131
    },
132
};
133

            
134
pub use {
135
    frame_system::Call as SystemCall,
136
    pallet_balances::Call as BalancesCall,
137
    primitives::{AccountId, Balance},
138
};
139

            
140
/// Constant values used within the runtime.
141
use dancelight_runtime_constants::{currency::*, fee::*, time::*};
142

            
143
// XCM configurations.
144
pub mod xcm_config;
145

            
146
// Weights
147
mod weights;
148

            
149
// Governance and configurations.
150
pub mod governance;
151
use {
152
    governance::{
153
        pallet_custom_origins, AuctionAdmin, Fellows, GeneralAdmin, Treasurer, TreasurySpender,
154
    },
155
    pallet_collator_assignment::CoreAllocationConfiguration,
156
    xcm_runtime_apis::fees::Error as XcmPaymentApiError,
157
};
158

            
159
#[cfg(test)]
160
mod tests;
161

            
162
pub mod genesis_config_presets;
163
mod validator_manager;
164

            
165
impl_runtime_weights!(dancelight_runtime_constants);
166

            
167
// Make the WASM binary available.
168
#[cfg(feature = "std")]
169
include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
170

            
171
/// Provides the `WASM_BINARY` build with `fast-runtime` feature enabled.
172
///
173
/// This is for example useful for local test chains.
174
#[cfg(feature = "std")]
175
pub mod fast_runtime_binary {
176
    include!(concat!(env!("OUT_DIR"), "/fast_runtime_binary.rs"));
177
}
178

            
179
/// Runtime version (Dancelight).
180
#[sp_version::runtime_version]
181
pub const VERSION: RuntimeVersion = RuntimeVersion {
182
    spec_name: create_runtime_str!("dancelight"),
183
    impl_name: create_runtime_str!("tanssi-dancelight-v2.0"),
184
    authoring_version: 0,
185
    spec_version: 1_011_000,
186
    impl_version: 0,
187
    apis: RUNTIME_API_VERSIONS,
188
    transaction_version: 25,
189
    state_version: 1,
190
};
191

            
192
/// The BABE epoch configuration at genesis.
193
pub const BABE_GENESIS_EPOCH_CONFIG: babe_primitives::BabeEpochConfiguration =
194
    babe_primitives::BabeEpochConfiguration {
195
        c: PRIMARY_PROBABILITY,
196
        allowed_slots: babe_primitives::AllowedSlots::PrimaryAndSecondaryVRFSlots,
197
    };
198

            
199
/// Native version.
200
#[cfg(any(feature = "std", test))]
201
pub fn native_version() -> NativeVersion {
202
    NativeVersion {
203
        runtime_version: VERSION,
204
        can_author_with: Default::default(),
205
    }
206
}
207

            
208
/// The relay register and deregister calls should no longer be necessary
209
/// Everything is handled by the containerRegistrar
210
pub struct IsRelayRegister;
211
impl Contains<RuntimeCall> for IsRelayRegister {
212
19
    fn contains(c: &RuntimeCall) -> bool {
213
18
        matches!(
214
2
            c,
215
            RuntimeCall::Registrar(paras_registrar::Call::register { .. })
216
17
        ) || matches!(
217
1
            c,
218
            RuntimeCall::Registrar(paras_registrar::Call::deregister { .. })
219
        )
220
19
    }
221
}
222

            
223
/// Dancelight shouold not permit parathread registration for now
224
/// TODO: remove once they are enabled
225
pub struct IsParathreadRegistrar;
226
impl Contains<RuntimeCall> for IsParathreadRegistrar {
227
17
    fn contains(c: &RuntimeCall) -> bool {
228
16
        matches!(
229
1
            c,
230
            RuntimeCall::ContainerRegistrar(pallet_registrar::Call::register_parathread { .. })
231
        )
232
17
    }
233
}
234

            
235
parameter_types! {
236
    pub const Version: RuntimeVersion = VERSION;
237
    pub const SS58Prefix: u8 = 42;
238
}
239

            
240
#[derive_impl(frame_system::config_preludes::RelayChainDefaultConfig)]
241
impl frame_system::Config for Runtime {
242
    type BaseCallFilter = EverythingBut<(IsRelayRegister, IsParathreadRegistrar)>;
243
    type BlockWeights = BlockWeights;
244
    type BlockLength = BlockLength;
245
    type DbWeight = RocksDbWeight;
246
    type Nonce = Nonce;
247
    type Hash = Hash;
248
    type AccountId = AccountId;
249
    type Block = Block;
250
    type BlockHashCount = BlockHashCount;
251
    type Version = Version;
252
    type AccountData = pallet_balances::AccountData<Balance>;
253
    type SystemWeightInfo = weights::frame_system::SubstrateWeight<Runtime>;
254
    type SS58Prefix = SS58Prefix;
255
    type MaxConsumers = frame_support::traits::ConstU32<16>;
256
    type MultiBlockMigrator = MultiBlockMigrations;
257
}
258

            
259
parameter_types! {
260
    pub MaximumSchedulerWeight: Weight = Perbill::from_percent(80) *
261
        BlockWeights::get().max_block;
262
    pub const MaxScheduledPerBlock: u32 = 50;
263
    pub const NoPreimagePostponement: Option<u32> = Some(10);
264
}
265

            
266
/// Used the compare the privilege of an origin inside the scheduler.
267
pub struct OriginPrivilegeCmp;
268

            
269
impl PrivilegeCmp<OriginCaller> for OriginPrivilegeCmp {
270
    fn cmp_privilege(left: &OriginCaller, right: &OriginCaller) -> Option<Ordering> {
271
        if left == right {
272
            return Some(Ordering::Equal);
273
        }
274

            
275
        match (left, right) {
276
            // Root is greater than anything.
277
            (OriginCaller::system(frame_system::RawOrigin::Root), _) => Some(Ordering::Greater),
278
            // For every other origin we don't care, as they are not used for `ScheduleOrigin`.
279
            _ => None,
280
        }
281
    }
282
}
283

            
284
/// Dynamic params that can be adjusted at runtime.
285
#[dynamic_params(RuntimeParameters, pallet_parameters::Parameters::<Runtime>)]
286
pub mod dynamic_params {
287
    use super::*;
288

            
289
    #[dynamic_pallet_params]
290
    #[codec(index = 0)]
291
    pub mod preimage {
292
        use super::*;
293

            
294
        #[codec(index = 0)]
295
        pub static BaseDeposit: Balance = deposit(2, 64);
296

            
297
        #[codec(index = 1)]
298
        pub static ByteDeposit: Balance = deposit(0, 1);
299
    }
300
}
301

            
302
#[cfg(feature = "runtime-benchmarks")]
303
impl Default for RuntimeParameters {
304
    fn default() -> Self {
305
        RuntimeParameters::Preimage(dynamic_params::preimage::Parameters::BaseDeposit(
306
            dynamic_params::preimage::BaseDeposit,
307
            Some(1u32.into()),
308
        ))
309
    }
310
}
311

            
312
/// Defines what origin can modify which dynamic parameters.
313
pub struct DynamicParameterOrigin;
314
impl EnsureOriginWithArg<RuntimeOrigin, RuntimeParametersKey> for DynamicParameterOrigin {
315
    type Success = ();
316

            
317
    fn try_origin(
318
        origin: RuntimeOrigin,
319
        key: &RuntimeParametersKey,
320
    ) -> Result<Self::Success, RuntimeOrigin> {
321
        use crate::RuntimeParametersKey::*;
322

            
323
        match key {
324
            Preimage(_) => frame_system::ensure_root(origin.clone()),
325
        }
326
        .map_err(|_| origin)
327
    }
328

            
329
    #[cfg(feature = "runtime-benchmarks")]
330
    fn try_successful_origin(_key: &RuntimeParametersKey) -> Result<RuntimeOrigin, ()> {
331
        // Provide the origin for the parameter returned by `Default`:
332
        Ok(RuntimeOrigin::root())
333
    }
334
}
335

            
336
impl pallet_scheduler::Config for Runtime {
337
    type RuntimeOrigin = RuntimeOrigin;
338
    type RuntimeEvent = RuntimeEvent;
339
    type PalletsOrigin = OriginCaller;
340
    type RuntimeCall = RuntimeCall;
341
    type MaximumWeight = MaximumSchedulerWeight;
342
    // The goal of having ScheduleOrigin include AuctionAdmin is to allow the auctions track of
343
    // OpenGov to schedule periodic auctions.
344
    type ScheduleOrigin = EitherOf<EnsureRoot<AccountId>, AuctionAdmin>;
345
    type MaxScheduledPerBlock = MaxScheduledPerBlock;
346
    type WeightInfo = weights::pallet_scheduler::SubstrateWeight<Runtime>;
347
    type OriginPrivilegeCmp = OriginPrivilegeCmp;
348
    type Preimages = Preimage;
349
}
350

            
351
parameter_types! {
352
    pub const PreimageHoldReason: RuntimeHoldReason = RuntimeHoldReason::Preimage(pallet_preimage::HoldReason::Preimage);
353
}
354

            
355
impl pallet_preimage::Config for Runtime {
356
    type WeightInfo = weights::pallet_preimage::SubstrateWeight<Runtime>;
357
    type RuntimeEvent = RuntimeEvent;
358
    type Currency = Balances;
359
    type ManagerOrigin = EnsureRoot<AccountId>;
360
    type Consideration = HoldConsideration<
361
        AccountId,
362
        Balances,
363
        PreimageHoldReason,
364
        LinearStoragePrice<
365
            dynamic_params::preimage::BaseDeposit,
366
            dynamic_params::preimage::ByteDeposit,
367
            Balance,
368
        >,
369
    >;
370
}
371

            
372
parameter_types! {
373
    pub const ExpectedBlockTime: Moment = MILLISECS_PER_BLOCK;
374
    pub ReportLongevity: u64 = u64::from(EpochDurationInBlocks::get()) * 10;
375
}
376

            
377
impl pallet_babe::Config for Runtime {
378
    type EpochDuration = EpochDurationInBlocks;
379
    type ExpectedBlockTime = ExpectedBlockTime;
380
    // session module is the trigger
381
    type EpochChangeTrigger = pallet_babe::ExternalTrigger;
382
    type DisabledValidators = Session;
383
    type WeightInfo = ();
384
    type MaxAuthorities = MaxAuthorities;
385
    type MaxNominators = ConstU32<0>;
386
    type KeyOwnerProof = sp_session::MembershipProof;
387
    type EquivocationReportSystem =
388
        pallet_babe::EquivocationReportSystem<Self, Offences, Historical, ReportLongevity>;
389
}
390

            
391
parameter_types! {
392
    pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT;
393
    pub const MaxLocks: u32 = 50;
394
    pub const MaxReserves: u32 = 50;
395
}
396

            
397
impl pallet_balances::Config for Runtime {
398
    type Balance = Balance;
399
    type DustRemoval = ();
400
    type RuntimeEvent = RuntimeEvent;
401
    type ExistentialDeposit = ExistentialDeposit;
402
    type AccountStore = System;
403
    type MaxLocks = MaxLocks;
404
    type MaxReserves = MaxReserves;
405
    type ReserveIdentifier = [u8; 8];
406
    type WeightInfo = weights::pallet_balances::SubstrateWeight<Runtime>;
407
    type FreezeIdentifier = ();
408
    type RuntimeHoldReason = RuntimeHoldReason;
409
    type RuntimeFreezeReason = RuntimeFreezeReason;
410
    type MaxFreezes = ConstU32<1>;
411
}
412

            
413
parameter_types! {
414
    pub const TransactionByteFee: Balance = 10 * MILLICENTS;
415
    /// This value increases the priority of `Operational` transactions by adding
416
    /// a "virtual tip" that's equal to the `OperationalFeeMultiplier * final_fee`.
417
    pub const OperationalFeeMultiplier: u8 = 5;
418
}
419

            
420
impl pallet_transaction_payment::Config for Runtime {
421
    type RuntimeEvent = RuntimeEvent;
422
    type OnChargeTransaction = FungibleAdapter<Balances, ToAuthor<Runtime>>;
423
    type OperationalFeeMultiplier = OperationalFeeMultiplier;
424
    type WeightToFee = WeightToFee;
425
    type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;
426
    type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Self>;
427
}
428

            
429
parameter_types! {
430
    pub const MinimumPeriod: u64 = SLOT_DURATION / 2;
431
}
432
impl pallet_timestamp::Config for Runtime {
433
    type Moment = u64;
434
    type OnTimestampSet = Babe;
435
    type MinimumPeriod = MinimumPeriod;
436
    type WeightInfo = weights::pallet_timestamp::SubstrateWeight<Runtime>;
437
}
438

            
439
impl pallet_authorship::Config for Runtime {
440
    type FindAuthor = pallet_session::FindAccountFromAuthorIndex<Self, Babe>;
441
    type EventHandler = ();
442
}
443

            
444
impl_opaque_keys! {
445
    pub struct SessionKeys {
446
        pub grandpa: Grandpa,
447
        pub babe: Babe,
448
        pub para_validator: Initializer,
449
        pub para_assignment: ParaSessionInfo,
450
        pub authority_discovery: AuthorityDiscovery,
451
        pub beefy: Beefy,
452
        pub nimbus: TanssiInitializer,
453
    }
454
}
455

            
456
/// Special `ValidatorIdOf` implementation that is just returning the input as result.
457
pub struct ValidatorIdOf;
458
impl sp_runtime::traits::Convert<AccountId, Option<AccountId>> for ValidatorIdOf {
459
8
    fn convert(a: AccountId) -> Option<AccountId> {
460
8
        Some(a)
461
8
    }
462
}
463

            
464
impl pallet_session::Config for Runtime {
465
    type RuntimeEvent = RuntimeEvent;
466
    type ValidatorId = AccountId;
467
    type ValidatorIdOf = ValidatorIdOf;
468
    type ShouldEndSession = Babe;
469
    type NextSessionRotation = Babe;
470
    type SessionManager = pallet_session::historical::NoteHistoricalRoot<Self, ValidatorManager>;
471
    type SessionHandler = <SessionKeys as OpaqueKeys>::KeyTypeIdProviders;
472
    type Keys = SessionKeys;
473
    type WeightInfo = ();
474
}
475

            
476
pub struct FullIdentificationOf;
477
impl sp_runtime::traits::Convert<AccountId, Option<()>> for FullIdentificationOf {
478
526
    fn convert(_: AccountId) -> Option<()> {
479
526
        Some(())
480
526
    }
481
}
482

            
483
impl pallet_session::historical::Config for Runtime {
484
    type FullIdentification = ();
485
    type FullIdentificationOf = FullIdentificationOf;
486
}
487

            
488
parameter_types! {
489
    pub const SessionsPerEra: SessionIndex = 6;
490
    pub const BondingDuration: sp_staking::EraIndex = 28;
491
}
492

            
493
parameter_types! {
494
    pub const ProposalBond: Permill = Permill::from_percent(5);
495
    pub const ProposalBondMinimum: Balance = 2000 * CENTS;
496
    pub const ProposalBondMaximum: Balance = 1 * GRAND;
497
    // We allow it to be 1 minute in fast mode to be able to test it
498
    pub const SpendPeriod: BlockNumber = runtime_common::prod_or_fast!(6 * DAYS, 1 * MINUTES);
499
    pub const Burn: Permill = Permill::from_perthousand(2);
500
    pub const TreasuryPalletId: PalletId = PalletId(*b"py/trsry");
501
    pub const PayoutSpendPeriod: BlockNumber = 30 * DAYS;
502
    // The asset's interior location for the paying account. This is the Treasury
503
    // pallet instance (which sits at index 18).
504
    pub TreasuryInteriorLocation: InteriorLocation = PalletInstance(18).into();
505

            
506
    pub const TipCountdown: BlockNumber = 1 * DAYS;
507
    pub const TipFindersFee: Percent = Percent::from_percent(20);
508
    pub const TipReportDepositBase: Balance = 100 * CENTS;
509
    pub const DataDepositPerByte: Balance = 1 * CENTS;
510
    pub const MaxApprovals: u32 = 100;
511
    pub const MaxAuthorities: u32 = 100_000;
512
    pub const MaxKeys: u32 = 10_000;
513
    pub const MaxPeerInHeartbeats: u32 = 10_000;
514
    pub const MaxBalance: Balance = Balance::max_value();
515
    pub TreasuryAccount: AccountId = Treasury::account_id();
516
}
517

            
518
#[cfg(feature = "runtime-benchmarks")]
519
pub struct TreasuryBenchmarkHelper<T>(PhantomData<T>);
520

            
521
#[cfg(feature = "runtime-benchmarks")]
522
use frame_support::traits::Currency;
523
#[cfg(feature = "runtime-benchmarks")]
524
use pallet_treasury::ArgumentsFactory;
525
use runtime_parachains::configuration::HostConfiguration;
526

            
527
#[cfg(feature = "runtime-benchmarks")]
528
impl<T> ArgumentsFactory<(), T::AccountId> for TreasuryBenchmarkHelper<T>
529
where
530
    T: pallet_treasury::Config,
531
    T::AccountId: From<[u8; 32]>,
532
{
533
    fn create_asset_kind(_seed: u32) {}
534

            
535
    fn create_beneficiary(seed: [u8; 32]) -> T::AccountId {
536
        let account: T::AccountId = seed.into();
537
        let balance = T::Currency::minimum_balance();
538
        let _ = T::Currency::make_free_balance_be(&account, balance);
539
        account
540
    }
541
}
542

            
543
impl pallet_treasury::Config for Runtime {
544
    type PalletId = TreasuryPalletId;
545
    type Currency = Balances;
546
    type RejectOrigin = EitherOfDiverse<EnsureRoot<AccountId>, Treasurer>;
547
    type RuntimeEvent = RuntimeEvent;
548
    type SpendPeriod = SpendPeriod;
549
    type Burn = Burn;
550
    type BurnDestination = ();
551
    type MaxApprovals = MaxApprovals;
552
    type WeightInfo = weights::pallet_treasury::SubstrateWeight<Runtime>;
553
    type SpendFunds = ();
554
    type SpendOrigin = TreasurySpender;
555
    type AssetKind = ();
556
    type Beneficiary = AccountId;
557
    type BeneficiaryLookup = IdentityLookup<Self::Beneficiary>;
558
    type Paymaster = PayFromAccount<Balances, TreasuryAccount>;
559
    type BalanceConverter = UnityAssetBalanceConversion;
560
    type PayoutPeriod = PayoutSpendPeriod;
561
    #[cfg(feature = "runtime-benchmarks")]
562
    type BenchmarkHelper = TreasuryBenchmarkHelper<Runtime>;
563
}
564

            
565
impl pallet_offences::Config for Runtime {
566
    type RuntimeEvent = RuntimeEvent;
567
    type IdentificationTuple = pallet_session::historical::IdentificationTuple<Self>;
568
    type OnOffenceHandler = ();
569
}
570

            
571
impl pallet_authority_discovery::Config for Runtime {
572
    type MaxAuthorities = MaxAuthorities;
573
}
574

            
575
parameter_types! {
576
    pub const MaxSetIdSessionEntries: u32 = BondingDuration::get() * SessionsPerEra::get();
577
}
578

            
579
impl pallet_grandpa::Config for Runtime {
580
    type RuntimeEvent = RuntimeEvent;
581
    type WeightInfo = ();
582
    type MaxAuthorities = MaxAuthorities;
583
    type MaxNominators = ConstU32<0>;
584
    type MaxSetIdSessionEntries = MaxSetIdSessionEntries;
585
    type KeyOwnerProof = sp_session::MembershipProof;
586
    type EquivocationReportSystem =
587
        pallet_grandpa::EquivocationReportSystem<Self, Offences, Historical, ReportLongevity>;
588
}
589

            
590
/// Submits a transaction with the node's public and signature type. Adheres to the signed extension
591
/// format of the chain.
592
impl<LocalCall> frame_system::offchain::CreateSignedTransaction<LocalCall> for Runtime
593
where
594
    RuntimeCall: From<LocalCall>,
595
{
596
    fn create_transaction<C: frame_system::offchain::AppCrypto<Self::Public, Self::Signature>>(
597
        call: RuntimeCall,
598
        public: <Signature as Verify>::Signer,
599
        account: AccountId,
600
        nonce: <Runtime as frame_system::Config>::Nonce,
601
    ) -> Option<(
602
        RuntimeCall,
603
        <UncheckedExtrinsic as ExtrinsicT>::SignaturePayload,
604
    )> {
605
        use sp_runtime::traits::StaticLookup;
606
        // take the biggest period possible.
607
        let period = u64::from(
608
            BlockHashCount::get()
609
                .checked_next_power_of_two()
610
                .map(|c| c / 2)
611
                .unwrap_or(2),
612
        );
613

            
614
        let current_block = System::block_number()
615
            .saturated_into::<u64>()
616
            // The `System::block_number` is initialized with `n+1`,
617
            // so the actual block number is `n`.
618
            .saturating_sub(1);
619
        let tip = 0;
620
        let extra: SignedExtra = (
621
            frame_system::CheckNonZeroSender::<Runtime>::new(),
622
            frame_system::CheckSpecVersion::<Runtime>::new(),
623
            frame_system::CheckTxVersion::<Runtime>::new(),
624
            frame_system::CheckGenesis::<Runtime>::new(),
625
            frame_system::CheckMortality::<Runtime>::from(generic::Era::mortal(
626
                period,
627
                current_block,
628
            )),
629
            frame_system::CheckNonce::<Runtime>::from(nonce),
630
            frame_system::CheckWeight::<Runtime>::new(),
631
            pallet_transaction_payment::ChargeTransactionPayment::<Runtime>::from(tip),
632
        );
633
        let raw_payload = SignedPayload::new(call, extra)
634
            .map_err(|e| {
635
                log::warn!("Unable to create signed payload: {:?}", e);
636
            })
637
            .ok()?;
638
        let signature = raw_payload.using_encoded(|payload| C::sign(payload, public))?;
639
        let (call, extra, _) = raw_payload.deconstruct();
640
        let address = <Runtime as frame_system::Config>::Lookup::unlookup(account);
641
        Some((call, (address, signature, extra)))
642
    }
643
}
644

            
645
impl frame_system::offchain::SigningTypes for Runtime {
646
    type Public = <Signature as Verify>::Signer;
647
    type Signature = Signature;
648
}
649

            
650
impl<C> frame_system::offchain::SendTransactionTypes<C> for Runtime
651
where
652
    RuntimeCall: From<C>,
653
{
654
    type Extrinsic = UncheckedExtrinsic;
655
    type OverarchingCall = RuntimeCall;
656
}
657

            
658
parameter_types! {
659
    // Minimum 100 bytes/STAR deposited (1 CENT/byte)
660
    pub const BasicDeposit: Balance = 1000 * CENTS;       // 258 bytes on-chain
661
    pub const ByteDeposit: Balance = deposit(0, 1);
662
    pub const SubAccountDeposit: Balance = 200 * CENTS;   // 53 bytes on-chain
663
    pub const MaxSubAccounts: u32 = 100;
664
    pub const MaxAdditionalFields: u32 = 100;
665
    pub const MaxRegistrars: u32 = 20;
666
}
667

            
668
impl pallet_identity::Config for Runtime {
669
    type RuntimeEvent = RuntimeEvent;
670
    type Currency = Balances;
671
    type BasicDeposit = BasicDeposit;
672
    type ByteDeposit = ByteDeposit;
673
    type SubAccountDeposit = SubAccountDeposit;
674
    type MaxSubAccounts = MaxSubAccounts;
675
    type IdentityInformation = IdentityInfo<MaxAdditionalFields>;
676
    type MaxRegistrars = MaxRegistrars;
677
    type Slashed = Treasury;
678
    type ForceOrigin = EitherOf<EnsureRoot<Self::AccountId>, GeneralAdmin>;
679
    type RegistrarOrigin = EitherOf<EnsureRoot<Self::AccountId>, GeneralAdmin>;
680
    type OffchainSignature = Signature;
681
    type SigningPublicKey = <Signature as Verify>::Signer;
682
    type UsernameAuthorityOrigin = EnsureRoot<Self::AccountId>;
683
    type PendingUsernameExpiration = ConstU32<{ 7 * DAYS }>;
684
    type MaxSuffixLength = ConstU32<7>;
685
    type MaxUsernameLength = ConstU32<32>;
686
    type WeightInfo = weights::pallet_identity::SubstrateWeight<Runtime>;
687
}
688

            
689
impl pallet_utility::Config for Runtime {
690
    type RuntimeEvent = RuntimeEvent;
691
    type RuntimeCall = RuntimeCall;
692
    type PalletsOrigin = OriginCaller;
693
    type WeightInfo = weights::pallet_utility::SubstrateWeight<Runtime>;
694
}
695

            
696
parameter_types! {
697
    // One storage item; key size is 32; value is size 4+4+16+32 bytes = 56 bytes.
698
    pub const DepositBase: Balance = deposit(1, 88);
699
    // Additional storage item size of 32 bytes.
700
    pub const DepositFactor: Balance = deposit(0, 32);
701
    pub const MaxSignatories: u32 = 100;
702
}
703

            
704
impl pallet_multisig::Config for Runtime {
705
    type RuntimeEvent = RuntimeEvent;
706
    type RuntimeCall = RuntimeCall;
707
    type Currency = Balances;
708
    type DepositBase = DepositBase;
709
    type DepositFactor = DepositFactor;
710
    type MaxSignatories = MaxSignatories;
711
    type WeightInfo = weights::pallet_multisig::SubstrateWeight<Runtime>;
712
}
713

            
714
parameter_types! {
715
    // One storage item; key size 32, value size 8; .
716
    pub const ProxyDepositBase: Balance = deposit(1, 8);
717
    // Additional storage item size of 33 bytes.
718
    pub const ProxyDepositFactor: Balance = deposit(0, 33);
719
    pub const MaxProxies: u16 = 32;
720
    pub const AnnouncementDepositBase: Balance = deposit(1, 8);
721
    pub const AnnouncementDepositFactor: Balance = deposit(0, 66);
722
    pub const MaxPending: u16 = 32;
723
}
724

            
725
/// The type used to represent the kinds of proxying allowed.
726
#[derive(
727
    Copy,
728
    Clone,
729
    Eq,
730
    PartialEq,
731
    Ord,
732
    PartialOrd,
733
    Encode,
734
    Decode,
735
    RuntimeDebug,
736
    MaxEncodedLen,
737
    TypeInfo,
738
)]
739
pub enum ProxyType {
740
    Any,
741
    NonTransfer,
742
    Governance,
743
    IdentityJudgement,
744
    CancelProxy,
745
    Auction,
746
    OnDemandOrdering,
747
}
748
impl Default for ProxyType {
749
    fn default() -> Self {
750
        Self::Any
751
    }
752
}
753
impl InstanceFilter<RuntimeCall> for ProxyType {
754
    fn filter(&self, c: &RuntimeCall) -> bool {
755
        match self {
756
            ProxyType::Any => true,
757
            ProxyType::NonTransfer => matches!(
758
                c,
759
                RuntimeCall::System(..) |
760
				RuntimeCall::Babe(..) |
761
				RuntimeCall::Timestamp(..) |
762
				// Specifically omitting Indices `transfer`, `force_transfer`
763
				// Specifically omitting the entire Balances pallet
764
				RuntimeCall::Session(..) |
765
				RuntimeCall::Grandpa(..) |
766
				RuntimeCall::Treasury(..) |
767
				RuntimeCall::ConvictionVoting(..) |
768
				RuntimeCall::Referenda(..) |
769
				RuntimeCall::FellowshipCollective(..) |
770
				RuntimeCall::FellowshipReferenda(..) |
771
				RuntimeCall::Whitelist(..) |
772
				RuntimeCall::Utility(..) |
773
				RuntimeCall::Identity(..) |
774
				RuntimeCall::Scheduler(..) |
775
				RuntimeCall::Proxy(..) |
776
				RuntimeCall::Multisig(..) |
777
				RuntimeCall::Registrar(paras_registrar::Call::register {..}) |
778
				RuntimeCall::Registrar(paras_registrar::Call::deregister {..}) |
779
				// Specifically omitting Registrar `swap`
780
				RuntimeCall::Registrar(paras_registrar::Call::reserve {..})
781
            ),
782
            ProxyType::Governance => matches!(
783
                c,
784
                RuntimeCall::Utility(..) |
785
					// OpenGov calls
786
					RuntimeCall::ConvictionVoting(..) |
787
					RuntimeCall::Referenda(..) |
788
					RuntimeCall::FellowshipCollective(..) |
789
					RuntimeCall::FellowshipReferenda(..) |
790
					RuntimeCall::Whitelist(..)
791
            ),
792
            ProxyType::IdentityJudgement => matches!(
793
                c,
794
                RuntimeCall::Identity(pallet_identity::Call::provide_judgement { .. })
795
                    | RuntimeCall::Utility(..)
796
            ),
797
            ProxyType::CancelProxy => {
798
                matches!(
799
                    c,
800
                    RuntimeCall::Proxy(pallet_proxy::Call::reject_announcement { .. })
801
                )
802
            }
803
            ProxyType::Auction => {
804
                matches!(c, RuntimeCall::Registrar { .. } | RuntimeCall::Multisig(..))
805
            }
806
            ProxyType::OnDemandOrdering => matches!(c, RuntimeCall::OnDemandAssignmentProvider(..)),
807
        }
808
    }
809
    fn is_superset(&self, o: &Self) -> bool {
810
        match (self, o) {
811
            (x, y) if x == y => true,
812
            (ProxyType::Any, _) => true,
813
            (_, ProxyType::Any) => false,
814
            (ProxyType::NonTransfer, _) => true,
815
            _ => false,
816
        }
817
    }
818
}
819

            
820
impl pallet_proxy::Config for Runtime {
821
    type RuntimeEvent = RuntimeEvent;
822
    type RuntimeCall = RuntimeCall;
823
    type Currency = Balances;
824
    type ProxyType = ProxyType;
825
    type ProxyDepositBase = ProxyDepositBase;
826
    type ProxyDepositFactor = ProxyDepositFactor;
827
    type MaxProxies = MaxProxies;
828
    type WeightInfo = weights::pallet_proxy::SubstrateWeight<Runtime>;
829
    type MaxPending = MaxPending;
830
    type CallHasher = BlakeTwo256;
831
    type AnnouncementDepositBase = AnnouncementDepositBase;
832
    type AnnouncementDepositFactor = AnnouncementDepositFactor;
833
}
834

            
835
impl parachains_origin::Config for Runtime {}
836

            
837
impl parachains_configuration::Config for Runtime {
838
    type WeightInfo = weights::runtime_parachains_configuration::SubstrateWeight<Runtime>;
839
}
840

            
841
impl parachains_shared::Config for Runtime {
842
    type DisabledValidators = Session;
843
}
844

            
845
impl parachains_session_info::Config for Runtime {
846
    type ValidatorSet = Historical;
847
}
848

            
849
/// Special `RewardValidators` that does nothing ;)
850
pub struct RewardValidators;
851
impl runtime_parachains::inclusion::RewardValidators for RewardValidators {
852
    fn reward_backing(_: impl IntoIterator<Item = ValidatorIndex>) {}
853
    fn reward_bitfields(_: impl IntoIterator<Item = ValidatorIndex>) {}
854
}
855

            
856
impl parachains_inclusion::Config for Runtime {
857
    type RuntimeEvent = RuntimeEvent;
858
    type DisputesHandler = ParasDisputes;
859
    type RewardValidators = RewardValidators;
860
    type MessageQueue = MessageQueue;
861
    type WeightInfo = weights::runtime_parachains_inclusion::SubstrateWeight<Runtime>;
862
}
863

            
864
parameter_types! {
865
    pub const ParasUnsignedPriority: TransactionPriority = TransactionPriority::max_value();
866
}
867

            
868
impl parachains_paras::Config for Runtime {
869
    type RuntimeEvent = RuntimeEvent;
870
    type WeightInfo = weights::runtime_parachains_paras::SubstrateWeight<Runtime>;
871
    type UnsignedPriority = ParasUnsignedPriority;
872
    type QueueFootprinter = ParaInclusion;
873
    type NextSessionRotation = Babe;
874
    type OnNewHead = Registrar;
875
    type AssignCoretime = ();
876
}
877

            
878
parameter_types! {
879
    /// Amount of weight that can be spent per block to service messages.
880
    ///
881
    /// # WARNING
882
    ///
883
    /// This is not a good value for para-chains since the `Scheduler` already uses up to 80% block weight.
884
    pub MessageQueueServiceWeight: Weight = Perbill::from_percent(20) * BlockWeights::get().max_block;
885
    pub const MessageQueueHeapSize: u32 = 32 * 1024;
886
    pub const MessageQueueMaxStale: u32 = 96;
887
}
888

            
889
/// Message processor to handle any messages that were enqueued into the `MessageQueue` pallet.
890
pub struct MessageProcessor;
891
impl ProcessMessage for MessageProcessor {
892
    type Origin = AggregateMessageOrigin;
893

            
894
    fn process_message(
895
        message: &[u8],
896
        origin: Self::Origin,
897
        meter: &mut WeightMeter,
898
        id: &mut [u8; 32],
899
    ) -> Result<bool, ProcessMessageError> {
900
        let para = match origin {
901
            AggregateMessageOrigin::Ump(UmpQueueId::Para(para)) => para,
902
        };
903
        xcm_builder::ProcessXcmMessage::<
904
            Junction,
905
            xcm_executor::XcmExecutor<xcm_config::XcmConfig>,
906
            RuntimeCall,
907
        >::process_message(message, Junction::Parachain(para.into()), meter, id)
908
    }
909
}
910

            
911
impl pallet_message_queue::Config for Runtime {
912
    type RuntimeEvent = RuntimeEvent;
913
    type Size = u32;
914
    type HeapSize = MessageQueueHeapSize;
915
    type MaxStale = MessageQueueMaxStale;
916
    type ServiceWeight = MessageQueueServiceWeight;
917
    type IdleMaxServiceWeight = MessageQueueServiceWeight;
918
    #[cfg(not(feature = "runtime-benchmarks"))]
919
    type MessageProcessor = MessageProcessor;
920
    #[cfg(feature = "runtime-benchmarks")]
921
    type MessageProcessor =
922
        pallet_message_queue::mock_helpers::NoopMessageProcessor<AggregateMessageOrigin>;
923
    type QueueChangeHandler = ParaInclusion;
924
    type QueuePausedQuery = ();
925
    type WeightInfo = weights::pallet_message_queue::SubstrateWeight<Runtime>;
926
}
927

            
928
impl parachains_dmp::Config for Runtime {}
929

            
930
parameter_types! {
931
    pub const HrmpChannelSizeAndCapacityWithSystemRatio: Percent = Percent::from_percent(100);
932
}
933

            
934
impl parachains_hrmp::Config for Runtime {
935
    type RuntimeOrigin = RuntimeOrigin;
936
    type RuntimeEvent = RuntimeEvent;
937
    type ChannelManager = EnsureRoot<AccountId>;
938
    type Currency = Balances;
939
    type DefaultChannelSizeAndCapacityWithSystem =
940
        parachains_configuration::ActiveConfigHrmpChannelSizeAndCapacityRatio<
941
            Runtime,
942
            HrmpChannelSizeAndCapacityWithSystemRatio,
943
        >;
944
    type WeightInfo = weights::runtime_parachains_hrmp::SubstrateWeight<Runtime>;
945
    type VersionWrapper = XcmPallet;
946
}
947

            
948
impl parachains_paras_inherent::Config for Runtime {
949
    type WeightInfo = weights::runtime_parachains_paras_inherent::SubstrateWeight<Runtime>;
950
}
951

            
952
impl parachains_scheduler::Config for Runtime {
953
    // If you change this, make sure the `Assignment` type of the new provider is binary compatible,
954
    // otherwise provide a migration.
955
    type AssignmentProvider = CollatorAssignmentProvider;
956
}
957

            
958
pub struct CollatorAssignmentProvider;
959
impl parachains_scheduler::common::AssignmentProvider<BlockNumberFor<Runtime>>
960
    for CollatorAssignmentProvider
961
{
962
16
    fn pop_assignment_for_core(core_idx: CoreIndex) -> Option<Assignment> {
963
16
        let assigned_collators = TanssiCollatorAssignment::collator_container_chain();
964
16
        let assigned_paras: Vec<ParaId> = assigned_collators
965
16
            .container_chains
966
16
            .iter()
967
16
            .filter_map(|(&para_id, _)| {
968
16
                if Paras::is_parachain(para_id) {
969
6
                    Some(para_id)
970
                } else {
971
10
                    None
972
                }
973
16
            })
974
16
            .collect();
975
16
        log::debug!("pop assigned collators {:?}", assigned_paras);
976
16
        log::debug!("looking for core idx {:?}", core_idx);
977

            
978
16
        if let Some(para_id) = assigned_paras.get(core_idx.0 as usize) {
979
3
            log::debug!("outputing assignment for  {:?}", para_id);
980

            
981
3
            Some(Assignment::Bulk(*para_id))
982
        } else {
983
            // We dont want to assign affinity to a parathread that has not collators assigned
984
            // Even if we did they would need their own collators to produce blocks, but for now
985
            // I prefer to forbid.
986
            // In this case the parathread would have bought the core for nothing
987
5
            let assignment =
988
13
                parachains_assigner_on_demand::Pallet::<Runtime>::pop_assignment_for_core(
989
13
                    core_idx,
990
13
                )?;
991
5
            if assigned_collators
992
5
                .container_chains
993
5
                .contains_key(&assignment.para_id())
994
            {
995
5
                Some(assignment)
996
            } else {
997
                None
998
            }
999
        }
16
    }
    fn report_processed(assignment: Assignment) {
        match assignment {
            Assignment::Pool {
                para_id,
                core_index,
            } => parachains_assigner_on_demand::Pallet::<Runtime>::report_processed(
                para_id, core_index,
            ),
            Assignment::Bulk(_) => {}
        }
    }
    /// Push an assignment back to the front of the queue.
    ///
    /// The assignment has not been processed yet. Typically used on session boundaries.
    /// Parameters:
    /// - `assignment`: The on demand assignment.
2
    fn push_back_assignment(assignment: Assignment) {
2
        match assignment {
            Assignment::Pool {
2
                para_id,
2
                core_index,
2
            } => parachains_assigner_on_demand::Pallet::<Runtime>::push_back_assignment(
2
                para_id, core_index,
2
            ),
            Assignment::Bulk(_) => {
                // Session changes are rough. We just drop assignments that did not make it on a
                // session boundary. This seems sensible as bulk is region based. Meaning, even if
                // we made the effort catching up on those dropped assignments, this would very
                // likely lead to other assignments not getting served at the "end" (when our
                // assignment set gets replaced).
            }
        }
2
    }
    #[cfg(feature = "runtime-benchmarks")]
    fn get_mock_assignment(_: CoreIndex, para_id: primitives::Id) -> Assignment {
        // Given that we are not tracking anything in `Bulk` assignments, it is safe to always
        // return a bulk assignment.
        Assignment::Bulk(para_id)
    }
248
    fn session_core_count() -> u32 {
248
        let config = runtime_parachains::configuration::ActiveConfig::<Runtime>::get();
248
        log::debug!(
            "session core count is {:?}",
            config.scheduler_params.num_cores
        );
248
        config.scheduler_params.num_cores
248
    }
}
parameter_types! {
    pub const OnDemandTrafficDefaultValue: FixedU128 = FixedU128::from_u32(1);
    // Keep 2 blocks worth of revenue information.
    // We don't need this because it is only used by coretime and we don't have coretime,
    // but the pallet implicitly assumes that this bound is at least 1, so we use a low value
    // that won't cause problems.
    pub const MaxHistoricalRevenue: BlockNumber = 2;
    pub const OnDemandPalletId: PalletId = PalletId(*b"py/ondmd");
}
impl parachains_assigner_on_demand::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type Currency = Balances;
    type TrafficDefaultValue = OnDemandTrafficDefaultValue;
    type WeightInfo = weights::runtime_parachains_assigner_on_demand::SubstrateWeight<Runtime>;
    type MaxHistoricalRevenue = MaxHistoricalRevenue;
    type PalletId = OnDemandPalletId;
}
impl parachains_initializer::Config for Runtime {
    type Randomness = pallet_babe::RandomnessFromOneEpochAgo<Runtime>;
    type ForceOrigin = EnsureRoot<AccountId>;
    type WeightInfo = weights::runtime_parachains_initializer::SubstrateWeight<Runtime>;
    type CoretimeOnNewSession = ();
}
impl parachains_disputes::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type RewardValidators = ();
    type SlashingHandler = parachains_slashing::SlashValidatorsForDisputes<ParasSlashing>;
    type WeightInfo = weights::runtime_parachains_disputes::SubstrateWeight<Runtime>;
}
impl parachains_slashing::Config for Runtime {
    type KeyOwnerProofSystem = Historical;
    type KeyOwnerProof =
        <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, ValidatorId)>>::Proof;
    type KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(
        KeyTypeId,
        ValidatorId,
    )>>::IdentificationTuple;
    type HandleReports = parachains_slashing::SlashingReportHandler<
        Self::KeyOwnerIdentification,
        Offences,
        ReportLongevity,
    >;
    type WeightInfo = parachains_slashing::TestWeightInfo;
    type BenchmarkingConfig = parachains_slashing::BenchConfig<200>;
}
parameter_types! {
    pub const ParaDeposit: Balance = 40 * UNITS;
}
impl paras_registrar::Config for Runtime {
    type RuntimeOrigin = RuntimeOrigin;
    type RuntimeEvent = RuntimeEvent;
    type Currency = Balances;
    type OnSwap = ();
    type ParaDeposit = ParaDeposit;
    type DataDepositPerByte = DataDepositPerByte;
    type WeightInfo = weights::runtime_common_paras_registrar::SubstrateWeight<Runtime>;
}
impl pallet_parameters::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type RuntimeParameters = RuntimeParameters;
    type AdminOrigin = DynamicParameterOrigin;
    type WeightInfo = weights::pallet_parameters::SubstrateWeight<Runtime>;
}
parameter_types! {
    pub BeefySetIdSessionEntries: u32 = BondingDuration::get() * SessionsPerEra::get();
}
impl pallet_beefy::Config for Runtime {
    type BeefyId = BeefyId;
    type MaxAuthorities = MaxAuthorities;
    type MaxNominators = ConstU32<0>;
    type MaxSetIdSessionEntries = BeefySetIdSessionEntries;
    type OnNewValidatorSet = MmrLeaf;
    type WeightInfo = ();
    type KeyOwnerProof = <Historical as KeyOwnerProofSystem<(KeyTypeId, BeefyId)>>::Proof;
    type EquivocationReportSystem =
        pallet_beefy::EquivocationReportSystem<Self, Offences, Historical, ReportLongevity>;
    type AncestryHelper = MmrLeaf;
}
/// MMR helper types.
mod mmr {
    use super::Runtime;
    pub use pallet_mmr::primitives::*;
    pub type Leaf = <<Runtime as pallet_mmr::Config>::LeafData as LeafDataProvider>::LeafData;
    pub type Hashing = <Runtime as pallet_mmr::Config>::Hashing;
    pub type Hash = <Hashing as sp_runtime::traits::Hash>::Output;
}
impl pallet_mmr::Config for Runtime {
    const INDEXING_PREFIX: &'static [u8] = mmr::INDEXING_PREFIX;
    type Hashing = Keccak256;
    type OnNewRoot = pallet_beefy_mmr::DepositBeefyDigest<Runtime>;
    type WeightInfo = ();
    type LeafData = pallet_beefy_mmr::Pallet<Runtime>;
    type BlockHashProvider = pallet_mmr::DefaultBlockHashProvider<Runtime>;
}
parameter_types! {
    pub LeafVersion: MmrLeafVersion = MmrLeafVersion::new(0, 0);
}
pub struct ParaHeadsRootProvider;
impl BeefyDataProvider<H256> for ParaHeadsRootProvider {
    fn extra_data() -> H256 {
        let mut para_heads: Vec<(u32, Vec<u8>)> = parachains_paras::Parachains::<Runtime>::get()
            .into_iter()
            .filter_map(|id| {
                parachains_paras::Heads::<Runtime>::get(id).map(|head| (id.into(), head.0))
            })
            .collect();
        para_heads.sort();
        binary_merkle_tree::merkle_root::<mmr::Hashing, _>(
            para_heads.into_iter().map(|pair| pair.encode()),
        )
    }
}
impl pallet_beefy_mmr::Config for Runtime {
    type LeafVersion = LeafVersion;
    type BeefyAuthorityToMerkleLeaf = pallet_beefy_mmr::BeefyEcdsaToEthereum;
    type LeafExtra = H256;
    type BeefyDataProvider = ParaHeadsRootProvider;
}
impl paras_sudo_wrapper::Config for Runtime {}
parameter_types! {
    pub const PermanentSlotLeasePeriodLength: u32 = 365;
    pub const TemporarySlotLeasePeriodLength: u32 = 5;
    pub const MaxTemporarySlotPerLeasePeriod: u32 = 5;
}
impl validator_manager::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type PrivilegedOrigin = EnsureRoot<AccountId>;
}
impl pallet_sudo::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type RuntimeCall = RuntimeCall;
    type WeightInfo = weights::pallet_sudo::SubstrateWeight<Runtime>;
}
impl pallet_root_testing::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
}
impl pallet_asset_rate::Config for Runtime {
    type WeightInfo = weights::pallet_asset_rate::SubstrateWeight<Runtime>;
    type RuntimeEvent = RuntimeEvent;
    type CreateOrigin = EnsureRoot<AccountId>;
    type RemoveOrigin = EnsureRoot<AccountId>;
    type UpdateOrigin = EnsureRoot<AccountId>;
    type Currency = Balances;
    type AssetKind = <Runtime as pallet_treasury::Config>::AssetKind;
    #[cfg(feature = "runtime-benchmarks")]
    type BenchmarkHelper = ();
}
parameter_types! {
    pub const MaxInvulnerables: u32 = 100;
}
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 = pallet_invulnerables::IdentityCollator;
    type CollatorRegistration = Session;
    type WeightInfo = ();
    #[cfg(feature = "runtime-benchmarks")]
    type Currency = Balances;
}
pub struct CurrentSessionIndexGetter;
impl tp_traits::GetSessionIndex<SessionIndex> for CurrentSessionIndexGetter {
    /// Returns current session index.
43
    fn session_index() -> SessionIndex {
43
        Session::current_index()
43
    }
}
impl pallet_configuration::Config for Runtime {
    type SessionDelay = ConstU32<2>;
    type SessionIndex = SessionIndex;
    type CurrentSessionIndex = CurrentSessionIndexGetter;
    type ForceEmptyOrchestrator = ConstBool<true>;
    type WeightInfo = ();
}
impl pallet_migrations::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type MigrationsList = (tanssi_runtime_common::migrations::DancelightMigrations<Runtime>,);
    type XcmExecutionManager = ();
}
parameter_types! {
    pub MbmServiceWeight: Weight = Perbill::from_percent(80) * BlockWeights::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 = frame_support::migrations::FreezeChainOnFailedMigration;
    type MaxServiceWeight = MbmServiceWeight;
    type WeightInfo = ();
}
pub const FIXED_BLOCK_PRODUCTION_COST: u128 = 1 * MICROUNITS;
pub const FIXED_COLLATOR_ASSIGNMENT_COST: u128 = 100 * MICROUNITS;
pub struct BlockProductionCost<Runtime>(PhantomData<Runtime>);
impl ProvideBlockProductionCost<Runtime> for BlockProductionCost<Runtime> {
56
    fn block_cost(_para_id: &ParaId) -> (u128, Weight) {
56
        (FIXED_BLOCK_PRODUCTION_COST, Weight::zero())
56
    }
}
pub struct CollatorAssignmentCost<Runtime>(PhantomData<Runtime>);
impl ProvideCollatorAssignmentCost<Runtime> for CollatorAssignmentCost<Runtime> {
40
    fn collator_assignment_cost(_para_id: &ParaId) -> (u128, Weight) {
40
        (FIXED_COLLATOR_ASSIGNMENT_COST, Weight::zero())
40
    }
}
parameter_types! {
    // 60 days worth of blocks
    pub const FreeBlockProductionCredits: BlockNumber = 60 * DAYS;
    // 60 days worth of collator assignment
    pub const FreeCollatorAssignmentCredits: u32 = FreeBlockProductionCredits::get()/EpochDurationInBlocks::get();
}
impl pallet_services_payment::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    /// Handler for fees
    type OnChargeForBlock = ();
    type OnChargeForCollatorAssignment = ();
    type OnChargeForCollatorAssignmentTip = ();
    /// Currency type for fee payment
    type Currency = Balances;
    /// Provider of a block cost which can adjust from block to block
    type ProvideBlockProductionCost = BlockProductionCost<Runtime>;
    /// Provider of a block cost which can adjust from block to block
    type ProvideCollatorAssignmentCost = CollatorAssignmentCost<Runtime>;
    /// The maximum number of block credits that can be accumulated
    type FreeBlockProductionCredits = FreeBlockProductionCredits;
    /// The maximum number of session credits that can be accumulated
    type FreeCollatorAssignmentCredits = FreeCollatorAssignmentCredits;
    type ManagerOrigin = EnsureRoot<AccountId>;
    type WeightInfo = weights::pallet_services_payment::SubstrateWeight<Runtime>;
}
parameter_types! {
    pub const ProfileDepositBaseFee: Balance = STORAGE_ITEM_FEE;
    pub const ProfileDepositByteFee: Balance = STORAGE_BYTE_FEE;
    #[derive(Clone)]
    pub const MaxAssignmentsPerParaId: u32 = 10;
    #[derive(Clone)]
    pub const MaxNodeUrlLen: u32 = 200;
}
#[apply(derive_storage_traits)]
#[derive(Copy, Serialize, Deserialize, MaxEncodedLen)]
pub enum PreserversAssignmentPaymentRequest {
47
    Free,
    // TODO: Add Stream Payment (with config)
}
#[apply(derive_storage_traits)]
#[derive(Copy, Serialize, Deserialize)]
pub enum PreserversAssignmentPaymentExtra {
    Free,
    // TODO: Add Stream Payment (with deposit)
}
#[apply(derive_storage_traits)]
#[derive(Copy, Serialize, Deserialize, MaxEncodedLen)]
pub enum PreserversAssignmentPaymentWitness {
23
    Free,
    // TODO: Add Stream Payment (with stream id)
}
pub struct PreserversAssignmentPayment;
impl pallet_data_preservers::AssignmentPayment<AccountId> for PreserversAssignmentPayment {
    /// Providers requests which kind of payment it accepts.
    type ProviderRequest = PreserversAssignmentPaymentRequest;
    /// Extra parameter the assigner provides.
    type AssignerParameter = PreserversAssignmentPaymentExtra;
    /// Represents the succesful outcome of the assignment.
    type AssignmentWitness = PreserversAssignmentPaymentWitness;
24
    fn try_start_assignment(
24
        _assigner: AccountId,
24
        _provider: AccountId,
24
        request: &Self::ProviderRequest,
24
        extra: Self::AssignerParameter,
24
    ) -> Result<Self::AssignmentWitness, DispatchErrorWithPostInfo> {
24
        let witness = match (request, extra) {
24
            (Self::ProviderRequest::Free, Self::AssignerParameter::Free) => {
24
                Self::AssignmentWitness::Free
24
            }
24
        };
24

            
24
        Ok(witness)
24
    }
    fn try_stop_assignment(
        _provider: AccountId,
        witness: Self::AssignmentWitness,
    ) -> Result<(), DispatchErrorWithPostInfo> {
        match witness {
            Self::AssignmentWitness::Free => (),
        }
        Ok(())
    }
    /// Return the values for a free assignment if it is supported.
    /// This is required to perform automatic migration from old Bootnodes storage.
    fn free_variant_values() -> Option<(
        Self::ProviderRequest,
        Self::AssignerParameter,
        Self::AssignmentWitness,
    )> {
        Some((
            Self::ProviderRequest::Free,
            Self::AssignerParameter::Free,
            Self::AssignmentWitness::Free,
        ))
    }
    // The values returned by the following functions should match with each other.
    #[cfg(feature = "runtime-benchmarks")]
    fn benchmark_provider_request() -> Self::ProviderRequest {
        PreserversAssignmentPaymentRequest::Free
    }
    #[cfg(feature = "runtime-benchmarks")]
    fn benchmark_assigner_parameter() -> Self::AssignerParameter {
        PreserversAssignmentPaymentExtra::Free
    }
    #[cfg(feature = "runtime-benchmarks")]
    fn benchmark_assignment_witness() -> Self::AssignmentWitness {
        PreserversAssignmentPaymentWitness::Free
    }
}
impl pallet_data_preservers::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type RuntimeHoldReason = RuntimeHoldReason;
    type Currency = Balances;
    type WeightInfo = ();
    type ProfileId = u64;
    type ProfileDeposit = tp_traits::BytesDeposit<ProfileDepositBaseFee, ProfileDepositByteFee>;
    type AssignmentPayment = PreserversAssignmentPayment;
    type AssignmentOrigin = pallet_registrar::EnsureSignedByManager<Runtime>;
    type ForceSetProfileOrigin = EnsureRoot<AccountId>;
    type MaxAssignmentsPerParaId = MaxAssignmentsPerParaId;
    type MaxNodeUrlLen = MaxNodeUrlLen;
    type MaxParaIdsVecLen = MaxLengthParaIds;
}
parameter_types! {
    pub DancelightBondAccount: AccountId32 = PalletId(*b"StarBond").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)
    // TODO: check if we need to change inflation in the future
    pub const InflationRate: Perbill = runtime_common::prod_or_fast!(Perbill::from_parts(9), Perbill::from_percent(1));
    // 30% for dancelight bond, so 70% for staking
    pub const RewardsPortion: Perbill = Perbill::from_percent(70);
}
pub struct OnUnbalancedInflation;
impl frame_support::traits::OnUnbalanced<Credit<AccountId, Balances>> for OnUnbalancedInflation {
1085
    fn on_nonzero_unbalanced(credit: Credit<AccountId, Balances>) {
1085
        let _ = <Balances as Balanced<_>>::resolve(&DancelightBondAccount::get(), credit);
1085
    }
}
impl pallet_inflation_rewards::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type Currency = Balances;
    type ContainerChains = ContainerRegistrar;
    type GetSelfChainBlockAuthor = ();
    type InflationRate = InflationRate;
    type OnUnbalanced = OnUnbalancedInflation;
    type PendingRewardsAccount = PendingRewardsAccount;
    type StakingRewardsDistributor = InvulnerableRewardDistribution<Self, Balances, ()>;
    type RewardsPortion = RewardsPortion;
}
318947
construct_runtime! {
10504
    pub enum Runtime
10504
    {
10504
        // Basic stuff; balances is uncallable initially.
10504
        System: frame_system = 0,
10504

            
10504
        // Babe must be before session.
10504
        Babe: pallet_babe = 1,
10504

            
10504
        Timestamp: pallet_timestamp = 2,
10504
        Balances: pallet_balances = 3,
10504
        Parameters: pallet_parameters = 4,
10504
        TransactionPayment: pallet_transaction_payment = 5,
10504

            
10504
        // Consensus support.
10504
        // Authorship must be before session in order to note author in the correct session and era.
10504
        Authorship: pallet_authorship = 6,
10504
        Offences: pallet_offences = 7,
10504
        Historical: session_historical = 8,
10504

            
10504
        // Container stuff should go before session
10504
        // Container stuff starts at index 10
10504
        ContainerRegistrar: pallet_registrar = 10,
10504
        CollatorConfiguration: pallet_configuration = 11,
10504
        TanssiInitializer: tanssi_initializer = 12,
10504
        TanssiInvulnerables: pallet_invulnerables = 13,
10504
        TanssiCollatorAssignment: pallet_collator_assignment = 14,
10504
        TanssiAuthorityAssignment: pallet_authority_assignment = 15,
10504
        TanssiAuthorityMapping: pallet_authority_mapping = 16,
10504
        AuthorNoting: pallet_author_noting = 17,
10504
        ServicesPayment: pallet_services_payment = 18,
10504
        DataPreservers: pallet_data_preservers = 19,
10504

            
10504
        // Session management
10504
        Session: pallet_session = 30,
10504
        Grandpa: pallet_grandpa = 31,
10504
        AuthorityDiscovery: pallet_authority_discovery = 32,
10504

            
10504
        // InflationRewards must be after Session
10504
        InflationRewards: pallet_inflation_rewards = 33,
10504

            
10504
        // Governance stuff; uncallable initially.
10504
        Treasury: pallet_treasury = 40,
10504
        ConvictionVoting: pallet_conviction_voting = 41,
10504
        Referenda: pallet_referenda = 42,
10504
        //	pub type FellowshipCollectiveInstance = pallet_ranked_collective::Instance1;
10504
        FellowshipCollective: pallet_ranked_collective::<Instance1> = 43,
10504
        // pub type FellowshipReferendaInstance = pallet_referenda::Instance2;
10504
        FellowshipReferenda: pallet_referenda::<Instance2> = 44,
10504
        Origins: pallet_custom_origins = 45,
10504
        Whitelist: pallet_whitelist = 46,
10504

            
10504
        // Parachains pallets. Start indices at 50 to leave room.
10504
        ParachainsOrigin: parachains_origin = 50,
10504
        Configuration: parachains_configuration = 51,
10504
        ParasShared: parachains_shared = 52,
10504
        ParaInclusion: parachains_inclusion = 53,
10504
        ParaInherent: parachains_paras_inherent = 54,
10504
        ParaScheduler: parachains_scheduler = 55,
10504
        Paras: parachains_paras = 56,
10504
        Initializer: parachains_initializer = 57,
10504
        Dmp: parachains_dmp = 58,
10504
        Hrmp: parachains_hrmp = 60,
10504
        ParaSessionInfo: parachains_session_info = 61,
10504
        ParasDisputes: parachains_disputes = 62,
10504
        ParasSlashing: parachains_slashing = 63,
10504
        MessageQueue: pallet_message_queue = 64,
10504
        OnDemandAssignmentProvider: parachains_assigner_on_demand = 65,
10504

            
10504
        // Parachain Onboarding Pallets. Start indices at 70 to leave room.
10504
        Registrar: paras_registrar = 70,
10504

            
10504
        // Utility module.
10504
        Utility: pallet_utility = 80,
10504

            
10504
        // Less simple identity module.
10504
        Identity: pallet_identity = 81,
10504

            
10504
        // System scheduler.
10504
        Scheduler: pallet_scheduler = 82,
10504

            
10504
        // Proxy module. Late addition.
10504
        Proxy: pallet_proxy = 83,
10504

            
10504
        // Multisig module. Late addition.
10504
        Multisig: pallet_multisig = 84,
10504

            
10504
        // Preimage registrar.
10504
        Preimage: pallet_preimage = 85,
10504

            
10504
        // Asset rate.
10504
        AssetRate: pallet_asset_rate = 86,
10504

            
10504
        // Pallet for sending XCM.
10504
        XcmPallet: pallet_xcm = 90,
10504

            
10504
        // Migration stuff
10504
        Migrations: pallet_migrations = 120,
10504
        MultiBlockMigrations: pallet_multiblock_migrations = 121,
10504

            
10504
        // BEEFY Bridges support.
10504
        Beefy: pallet_beefy = 240,
10504
        // MMR leaf construction must be after session in order to have a leaf's next_auth_set
10504
        // refer to block<N>. See issue polkadot-fellows/runtimes#160 for details.
10504
        Mmr: pallet_mmr = 241,
10504
        MmrLeaf: pallet_beefy_mmr = 242,
10504

            
10504
        ParasSudoWrapper: paras_sudo_wrapper = 250,
10504

            
10504
        // Validator Manager pallet.
10504
        ValidatorManager: validator_manager = 252,
10504

            
10504
        // Root testing pallet.
10504
        RootTesting: pallet_root_testing = 249,
10504

            
10504
        // Sudo.
10504
        Sudo: pallet_sudo = 255,
10504
    }
319208
}
/// The address format for describing accounts.
pub type Address = sp_runtime::MultiAddress<AccountId, ()>;
/// Block header type as expected by this runtime.
pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
/// Block type as expected by this runtime.
pub type Block = generic::Block<Header, UncheckedExtrinsic>;
/// A Block signed with a Justification
pub type SignedBlock = generic::SignedBlock<Block>;
/// `BlockId` type as expected by this runtime.
pub type BlockId = generic::BlockId<Block>;
/// The `SignedExtension` to the basic transaction logic.
pub type SignedExtra = (
    frame_system::CheckNonZeroSender<Runtime>,
    frame_system::CheckSpecVersion<Runtime>,
    frame_system::CheckTxVersion<Runtime>,
    frame_system::CheckGenesis<Runtime>,
    frame_system::CheckMortality<Runtime>,
    frame_system::CheckNonce<Runtime>,
    frame_system::CheckWeight<Runtime>,
    pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
);
/// Unchecked extrinsic type as expected by this runtime.
pub type UncheckedExtrinsic =
    generic::UncheckedExtrinsic<Address, RuntimeCall, Signature, SignedExtra>;
/// The runtime migrations per release.
#[allow(deprecated, missing_docs)]
pub mod migrations {
    /// Unreleased migrations. Add new ones here:
    pub type Unreleased = ();
}
/// Executive: handles dispatch to the various modules.
pub type Executive = frame_executive::Executive<
    Runtime,
    Block,
    frame_system::ChainContext<Runtime>,
    Runtime,
    AllPalletsWithSystem,
    migrations::Unreleased,
>;
/// The payload being signed in transactions.
pub type SignedPayload = generic::SignedPayload<RuntimeCall, SignedExtra>;
parameter_types! {
    pub const DepositAmount: Balance = 100 * UNITS;
    #[derive(Clone)]
    pub const MaxLengthParaIds: u32 = 100u32;
    pub const MaxEncodedGenesisDataSize: u32 = 5_000_000u32; // 5MB
}
pub struct InnerDancelightRegistrar<Runtime, AccountId, RegistrarManager, RegistrarWeightInfo>(
    PhantomData<(Runtime, AccountId, RegistrarManager, RegistrarWeightInfo)>,
);
impl<Runtime, AccountId, RegistrarManager, RegistrarWeightInfo> RegistrarHandler<AccountId>
    for InnerDancelightRegistrar<Runtime, AccountId, RegistrarManager, RegistrarWeightInfo>
where
    RegistrarManager: RegistrarInterface<AccountId = AccountId>,
    RegistrarWeightInfo: paras_registrar::WeightInfo,
    Runtime: pallet_registrar::Config,
{
28
    fn register(
28
        who: AccountId,
28
        id: ParaId,
28
        genesis_storage: &[ContainerChainGenesisDataItem],
28
        head_data: Option<HeadData>,
28
    ) -> DispatchResult {
        // Return early if head_data is not specified
28
        let genesis_head = match head_data {
28
            Some(data) => data,
            None => return Err(ContainerRegistrarError::<Runtime>::HeadDataNecessary.into()),
        };
        // Check if the wasm code is present in storage
28
        let validation_code = match genesis_storage
28
            .iter()
28
            .find(|item| item.key == StorageWellKnownKeys::CODE)
        {
28
            Some(item) => ValidationCode(item.value.clone()),
            None => return Err(ContainerRegistrarError::<Runtime>::WasmCodeNecessary.into()),
        };
        // Try to register the parachain
28
        RegistrarManager::register(who, id, genesis_head, validation_code)
28
    }
23
    fn schedule_para_upgrade(id: ParaId) -> DispatchResult {
23
        // Return Ok() if the paraId is already a parachain in the relay context
23
        if !RegistrarManager::is_parachain(id) {
23
            return RegistrarManager::make_parachain(id);
        }
        Ok(())
23
    }
7
    fn schedule_para_downgrade(id: ParaId) -> DispatchResult {
7
        // Return Ok() if the paraId is already a parathread in the relay context
7
        if !RegistrarManager::is_parathread(id) {
7
            return RegistrarManager::make_parathread(id);
        }
        Ok(())
7
    }
3
    fn deregister(id: ParaId) {
3
        if let Err(e) = RegistrarManager::deregister(id) {
            log::warn!(
                "Failed to deregister para id {} in relay chain: {:?}",
                u32::from(id),
                e,
            );
3
        }
3
    }
3
    fn deregister_weight() -> Weight {
3
        RegistrarWeightInfo::deregister()
3
    }
}
impl pallet_registrar::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type RegistrarOrigin = EnsureRoot<AccountId>;
    type MarkValidForCollatingOrigin = EnsureRoot<AccountId>;
    type MaxLengthParaIds = MaxLengthParaIds;
    type MaxGenesisDataSize = MaxEncodedGenesisDataSize;
    type RegisterWithRelayProofOrigin = EnsureNever<AccountId>;
    type RelayStorageRootProvider = ();
    type SessionDelay = ConstU32<2>;
    type SessionIndex = u32;
    type CurrentSessionIndex = CurrentSessionIndexGetter;
    type Currency = Balances;
    type DepositAmount = DepositAmount;
    type RegistrarHooks = DancelightRegistrarHooks;
    type RuntimeHoldReason = RuntimeHoldReason;
    // TODO: replace TestWeightInfo when we use proper weights on paras_registrar
    type InnerRegistrar =
        InnerDancelightRegistrar<Runtime, AccountId, Registrar, paras_registrar::TestWeightInfo>;
    type WeightInfo = pallet_registrar::weights::SubstrateWeight<Runtime>;
}
pub struct DancelightRegistrarHooks;
impl pallet_registrar::RegistrarHooks for DancelightRegistrarHooks {
23
    fn para_marked_valid_for_collating(para_id: ParaId) -> Weight {
23
        // Give free credits but only once per para id
23
        ServicesPayment::give_free_credits(&para_id)
23
    }
8
    fn para_deregistered(para_id: ParaId) -> Weight {
8
        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,
            );
8
        }
        /*
        XcmCoreBuyer::para_deregistered(para_id);
        */
        // Remove bootnodes from pallet_data_preservers
8
        DataPreservers::para_deregistered(para_id);
8

            
8
        ServicesPayment::para_deregistered(para_id);
8

            
8
        Weight::default()
8
    }
24
    fn check_valid_for_collating(para_id: ParaId) -> DispatchResult {
24
        // To be able to call mark_valid_for_collating, a container chain must have bootnodes
24
        DataPreservers::check_valid_for_collating(para_id)
24
    }
    #[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: PreserversAssignmentPaymentRequest::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,
            PreserversAssignmentPaymentExtra::Free,
        )
        .expect("assignment to work");
        assert!(
            pallet_data_preservers::Assignments::<Runtime>::get(para_id).contains(&profile_id),
            "profile should be correctly assigned"
        );
    }
}
pub struct BabeSlotBeacon;
impl BlockNumberProvider for BabeSlotBeacon {
    type BlockNumber = u32;
8
    fn current_block_number() -> Self::BlockNumber {
8
        // TODO: nimbus_primitives::SlotBeacon requires u32, but this is a u64 in pallet_babe, and
8
        // also it gets converted to u64 in pallet_author_noting, so let's do something to remove
8
        // this intermediate u32 conversion, such as using a different trait
8
        u64::from(pallet_babe::CurrentSlot::<Runtime>::get()) as u32
8
    }
}
impl pallet_author_noting::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type ContainerChains = ContainerRegistrar;
    type SlotBeacon = BabeSlotBeacon;
    type ContainerChainAuthor = TanssiCollatorAssignment;
    // We benchmark each hook individually, so for runtime-benchmarks this should be empty
    #[cfg(feature = "runtime-benchmarks")]
    type AuthorNotingHook = ();
    #[cfg(not(feature = "runtime-benchmarks"))]
    type AuthorNotingHook = (InflationRewards, ServicesPayment);
    type RelayOrPara = pallet_author_noting::RelayMode;
    type WeightInfo = weights::pallet_author_noting::SubstrateWeight<Runtime>;
}
frame_support::ord_parameter_types! {
    pub const MigController: AccountId = AccountId::from(hex_literal::hex!("52bc71c1eca5353749542dfdf0af97bf764f9c2f44e860cd485f1cd86400f649"));
}
#[cfg(feature = "runtime-benchmarks")]
mod benches {
    frame_benchmarking::define_benchmarks!(
        // Polkadot
        // NOTE: Make sure to prefix these with `runtime_common::` so
        // the that path resolves correctly in the generated file.
        [runtime_common::paras_registrar, Registrar]
        [runtime_parachains::configuration, Configuration]
        [runtime_parachains::hrmp, Hrmp]
        [runtime_parachains::disputes, ParasDisputes]
        [runtime_parachains::inclusion, ParaInclusion]
        [runtime_parachains::initializer, Initializer]
        [runtime_parachains::paras_inherent, ParaInherent]
        [runtime_parachains::paras, Paras]
        [runtime_parachains::assigner_on_demand, OnDemandAssignmentProvider]
        // Substrate
        [pallet_balances, Balances]
        [frame_benchmarking::baseline, Baseline::<Runtime>]
        [pallet_conviction_voting, ConvictionVoting]
        [pallet_identity, Identity]
        [pallet_message_queue, MessageQueue]
        [pallet_multisig, Multisig]
        [pallet_parameters, Parameters]
        [pallet_preimage, Preimage]
        [pallet_proxy, Proxy]
        [pallet_ranked_collective, FellowshipCollective]
        [pallet_referenda, Referenda]
        [pallet_scheduler, Scheduler]
        [pallet_sudo, Sudo]
        [frame_system, SystemBench::<Runtime>]
        [pallet_timestamp, Timestamp]
        [pallet_treasury, Treasury]
        [pallet_utility, Utility]
        [pallet_asset_rate, AssetRate]
        [pallet_whitelist, Whitelist]
        [pallet_services_payment, ServicesPayment]
        // Tanssi
        [pallet_author_noting, AuthorNoting]
        // 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>]
    );
}
52563
sp_api::impl_runtime_apis! {
37961
    impl sp_api::Core<Block> for Runtime {
37961
        fn version() -> RuntimeVersion {
            VERSION
        }
37961

            
37961
        fn execute_block(block: Block) {
            Executive::execute_block(block);
        }
37961

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

            
37961
    impl xcm_runtime_apis::fees::XcmPaymentApi<Block> for Runtime {
37961
        fn query_acceptable_payment_assets(xcm_version: xcm::Version) -> Result<Vec<VersionedAssetId>, XcmPaymentApiError> {
37961
            if !matches!(xcm_version, 3 | 4) {
37961
                return Err(XcmPaymentApiError::UnhandledXcmVersion);
37961
            }
            Ok([VersionedAssetId::V4(xcm_config::TokenLocation::get().into())]
                .into_iter()
                .filter_map(|asset| asset.into_version(xcm_version).ok())
                .collect())
37961
        }
37961

            
37961
        fn query_weight_to_asset_fee(weight: Weight, asset: VersionedAssetId) -> Result<u128, XcmPaymentApiError> {
            let local_asset = VersionedAssetId::V4(xcm_config::TokenLocation::get().into());
37961
            let asset = asset
                .into_version(4)
                .map_err(|_| XcmPaymentApiError::VersionedConversionFailed)?;
37961

            
37961
            if  asset != local_asset { return Err(XcmPaymentApiError::AssetNotFound); }
            Ok(WeightToFee::weight_to_fee(&weight))
37961
        }
37961

            
37961
        fn query_xcm_weight(message: VersionedXcm<()>) -> Result<Weight, XcmPaymentApiError> {
            XcmPallet::query_xcm_weight(message)
        }
37961

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

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

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

            
37961
        fn metadata_versions() -> sp_std::vec::Vec<u32> {
            Runtime::metadata_versions()
        }
37961
    }
37961

            
37961
    impl block_builder_api::BlockBuilder<Block> for Runtime {
37961
        fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
            Executive::apply_extrinsic(extrinsic)
        }
37961

            
37961
        fn finalize_block() -> <Block as BlockT>::Header {
            Executive::finalize_block()
        }
37961

            
37961
        fn inherent_extrinsics(data: inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
            data.create_extrinsics()
        }
37961

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

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

            
37961
    impl offchain_primitives::OffchainWorkerApi<Block> for Runtime {
37961
        fn offchain_worker(header: &<Block as BlockT>::Header) {
            Executive::offchain_worker(header)
        }
37961
    }
37961

            
37961
    #[api_version(11)]
37961
    impl primitives::runtime_api::ParachainHost<Block> for Runtime {
37961
        fn validators() -> Vec<ValidatorId> {
            parachains_runtime_api_impl::validators::<Runtime>()
        }
37961

            
37961
        fn validator_groups() -> (Vec<Vec<ValidatorIndex>>, GroupRotationInfo<BlockNumber>) {
            parachains_runtime_api_impl::validator_groups::<Runtime>()
        }
37961

            
37961
        fn availability_cores() -> Vec<CoreState<Hash, BlockNumber>> {
            parachains_runtime_api_impl::availability_cores::<Runtime>()
        }
37961

            
37961
        fn persisted_validation_data(para_id: ParaId, assumption: OccupiedCoreAssumption)
            -> Option<PersistedValidationData<Hash, BlockNumber>> {
            parachains_runtime_api_impl::persisted_validation_data::<Runtime>(para_id, assumption)
        }
37961

            
37961
        fn assumed_validation_data(
            para_id: ParaId,
            expected_persisted_validation_data_hash: Hash,
        ) -> Option<(PersistedValidationData<Hash, BlockNumber>, ValidationCodeHash)> {
            parachains_runtime_api_impl::assumed_validation_data::<Runtime>(
                para_id,
                expected_persisted_validation_data_hash,
            )
        }
37961

            
37961
        fn check_validation_outputs(
            para_id: ParaId,
            outputs: primitives::CandidateCommitments,
        ) -> bool {
            parachains_runtime_api_impl::check_validation_outputs::<Runtime>(para_id, outputs)
        }
37961

            
37961
        fn session_index_for_child() -> SessionIndex {
            parachains_runtime_api_impl::session_index_for_child::<Runtime>()
        }
37961

            
37961
        fn validation_code(para_id: ParaId, assumption: OccupiedCoreAssumption)
            -> Option<ValidationCode> {
            parachains_runtime_api_impl::validation_code::<Runtime>(para_id, assumption)
        }
37961

            
37961
        fn candidate_pending_availability(para_id: ParaId) -> Option<CommittedCandidateReceipt<Hash>> {
            #[allow(deprecated)]
            parachains_runtime_api_impl::candidate_pending_availability::<Runtime>(para_id)
        }
37961

            
37961
        fn candidate_events() -> Vec<CandidateEvent<Hash>> {
            parachains_runtime_api_impl::candidate_events::<Runtime, _>(|ev| {
                match ev {
37961
                    RuntimeEvent::ParaInclusion(ev) => {
                        Some(ev)
37961
                    }
37961
                    _ => None,
37961
                }
37961
            })
        }
37961

            
37961
        fn session_info(index: SessionIndex) -> Option<SessionInfo> {
            parachains_runtime_api_impl::session_info::<Runtime>(index)
        }
37961

            
37961
        fn session_executor_params(session_index: SessionIndex) -> Option<ExecutorParams> {
            parachains_runtime_api_impl::session_executor_params::<Runtime>(session_index)
        }
37961

            
37961
        fn dmq_contents(recipient: ParaId) -> Vec<InboundDownwardMessage<BlockNumber>> {
            parachains_runtime_api_impl::dmq_contents::<Runtime>(recipient)
        }
37961

            
37961
        fn inbound_hrmp_channels_contents(
            recipient: ParaId
        ) -> BTreeMap<ParaId, Vec<InboundHrmpMessage<BlockNumber>>> {
            parachains_runtime_api_impl::inbound_hrmp_channels_contents::<Runtime>(recipient)
        }
37961

            
37961
        fn validation_code_by_hash(hash: ValidationCodeHash) -> Option<ValidationCode> {
            parachains_runtime_api_impl::validation_code_by_hash::<Runtime>(hash)
        }
37961

            
37961
        fn on_chain_votes() -> Option<ScrapedOnChainVotes<Hash>> {
            parachains_runtime_api_impl::on_chain_votes::<Runtime>()
        }
37961

            
37961
        fn submit_pvf_check_statement(
            stmt: primitives::PvfCheckStatement,
            signature: primitives::ValidatorSignature
        ) {
            parachains_runtime_api_impl::submit_pvf_check_statement::<Runtime>(stmt, signature)
        }
37961

            
37961
        fn pvfs_require_precheck() -> Vec<ValidationCodeHash> {
            parachains_runtime_api_impl::pvfs_require_precheck::<Runtime>()
        }
37961

            
37961
        fn validation_code_hash(para_id: ParaId, assumption: OccupiedCoreAssumption)
            -> Option<ValidationCodeHash>
        {
            parachains_runtime_api_impl::validation_code_hash::<Runtime>(para_id, assumption)
        }
37961

            
37961
        fn disputes() -> Vec<(SessionIndex, CandidateHash, DisputeState<BlockNumber>)> {
            parachains_runtime_api_impl::get_session_disputes::<Runtime>()
        }
37961

            
37961
        fn unapplied_slashes(
        ) -> Vec<(SessionIndex, CandidateHash, slashing::PendingSlashes)> {
            parachains_runtime_api_impl::unapplied_slashes::<Runtime>()
        }
37961

            
37961
        fn key_ownership_proof(
            validator_id: ValidatorId,
        ) -> Option<slashing::OpaqueKeyOwnershipProof> {
37961
            use parity_scale_codec::Encode;
37961

            
37961
            Historical::prove((PARACHAIN_KEY_TYPE_ID, validator_id))
                .map(|p| p.encode())
                .map(slashing::OpaqueKeyOwnershipProof::new)
        }
37961

            
37961
        fn submit_report_dispute_lost(
            dispute_proof: slashing::DisputeProof,
            key_ownership_proof: slashing::OpaqueKeyOwnershipProof,
        ) -> Option<()> {
            parachains_runtime_api_impl::submit_unsigned_slashing_report::<Runtime>(
                dispute_proof,
                key_ownership_proof,
            )
        }
37961

            
37961
        fn minimum_backing_votes() -> u32 {
            parachains_runtime_api_impl::minimum_backing_votes::<Runtime>()
        }
37961

            
37961
        fn para_backing_state(para_id: ParaId) -> Option<primitives::async_backing::BackingState> {
            parachains_runtime_api_impl::backing_state::<Runtime>(para_id)
        }
37961

            
37961
        fn async_backing_params() -> primitives::AsyncBackingParams {
            parachains_runtime_api_impl::async_backing_params::<Runtime>()
        }
37961

            
37961
        fn approval_voting_params() -> ApprovalVotingParams {
            parachains_runtime_api_impl::approval_voting_params::<Runtime>()
        }
37961

            
37961
        fn disabled_validators() -> Vec<ValidatorIndex> {
            parachains_runtime_api_impl::disabled_validators::<Runtime>()
        }
37961

            
37961
        fn node_features() -> NodeFeatures {
            parachains_runtime_api_impl::node_features::<Runtime>()
        }
37961

            
37961
        fn claim_queue() -> BTreeMap<CoreIndex, VecDeque<ParaId>> {
            vstaging_parachains_runtime_api_impl::claim_queue::<Runtime>()
        }
37961

            
37965
        fn candidates_pending_availability(para_id: ParaId) -> Vec<CommittedCandidateReceipt<Hash>> {
4
            vstaging_parachains_runtime_api_impl::candidates_pending_availability::<Runtime>(para_id)
4
        }
37961
    }
37961

            
37961
    #[api_version(4)]
37961
    impl beefy_primitives::BeefyApi<Block, BeefyId> for Runtime {
37961
        fn beefy_genesis() -> Option<BlockNumber> {
            pallet_beefy::GenesisBlock::<Runtime>::get()
        }
37961

            
37961
        fn validator_set() -> Option<beefy_primitives::ValidatorSet<BeefyId>> {
            Beefy::validator_set()
        }
37961

            
37961
        fn submit_report_double_voting_unsigned_extrinsic(
            equivocation_proof: beefy_primitives::DoubleVotingProof<
                BlockNumber,
                BeefyId,
                BeefySignature,
            >,
            key_owner_proof: beefy_primitives::OpaqueKeyOwnershipProof,
        ) -> Option<()> {
37961
            let key_owner_proof = key_owner_proof.decode()?;
37961

            
37961
            Beefy::submit_unsigned_double_voting_report(
                equivocation_proof,
                key_owner_proof,
            )
37961
        }
37961

            
37961
        fn generate_key_ownership_proof(
            _set_id: beefy_primitives::ValidatorSetId,
            authority_id: BeefyId,
        ) -> Option<beefy_primitives::OpaqueKeyOwnershipProof> {
            Historical::prove((beefy_primitives::KEY_TYPE, authority_id))
                .map(|p| p.encode())
                .map(beefy_primitives::OpaqueKeyOwnershipProof::new)
        }
37961
    }
37961

            
37961
    #[api_version(2)]
37961
    impl mmr::MmrApi<Block, mmr::Hash, BlockNumber> for Runtime {
37961
        fn mmr_root() -> Result<mmr::Hash, mmr::Error> {
            Ok(pallet_mmr::RootHash::<Runtime>::get())
        }
37961

            
37961
        fn mmr_leaf_count() -> Result<mmr::LeafIndex, mmr::Error> {
            Ok(pallet_mmr::NumberOfLeaves::<Runtime>::get())
        }
37961

            
37961
        fn generate_proof(
            block_numbers: Vec<BlockNumber>,
            best_known_block_number: Option<BlockNumber>,
        ) -> Result<(Vec<mmr::EncodableOpaqueLeaf>, mmr::LeafProof<mmr::Hash>), mmr::Error> {
            Mmr::generate_proof(block_numbers, best_known_block_number).map(
                |(leaves, proof)| {
                    (
                        leaves
                            .into_iter()
                            .map(|leaf| mmr::EncodableOpaqueLeaf::from_leaf(&leaf))
                            .collect(),
                        proof,
                    )
                },
            )
        }
37961

            
37961
        fn verify_proof(leaves: Vec<mmr::EncodableOpaqueLeaf>, proof: mmr::LeafProof<mmr::Hash>)
            -> Result<(), mmr::Error>
        {
37961
            let leaves = leaves.into_iter().map(|leaf|
37961
                leaf.into_opaque_leaf()
                .try_decode()
                .ok_or(mmr::Error::Verify)).collect::<Result<Vec<mmr::Leaf>, mmr::Error>>()?;
37961
            Mmr::verify_leaves(leaves, proof)
37961
        }
37961

            
37961
        fn verify_proof_stateless(
            root: mmr::Hash,
            leaves: Vec<mmr::EncodableOpaqueLeaf>,
            proof: mmr::LeafProof<mmr::Hash>
        ) -> Result<(), mmr::Error> {
            let nodes = leaves.into_iter().map(|leaf|mmr::DataOrHash::Data(leaf.into_opaque_leaf())).collect();
            pallet_mmr::verify_leaves_proof::<mmr::Hashing, _>(root, nodes, proof)
        }
37961
    }
37961

            
37961
    impl fg_primitives::GrandpaApi<Block> for Runtime {
37961
        fn grandpa_authorities() -> Vec<(GrandpaId, u64)> {
            Grandpa::grandpa_authorities()
        }
37961

            
37961
        fn current_set_id() -> fg_primitives::SetId {
            Grandpa::current_set_id()
        }
37961

            
37961
        fn submit_report_equivocation_unsigned_extrinsic(
            equivocation_proof: fg_primitives::EquivocationProof<
                <Block as BlockT>::Hash,
                sp_runtime::traits::NumberFor<Block>,
            >,
            key_owner_proof: fg_primitives::OpaqueKeyOwnershipProof,
        ) -> Option<()> {
37961
            let key_owner_proof = key_owner_proof.decode()?;
37961

            
37961
            Grandpa::submit_unsigned_equivocation_report(
                equivocation_proof,
                key_owner_proof,
            )
37961
        }
37961

            
37961
        fn generate_key_ownership_proof(
            _set_id: fg_primitives::SetId,
            authority_id: fg_primitives::AuthorityId,
        ) -> Option<fg_primitives::OpaqueKeyOwnershipProof> {
37961
            use parity_scale_codec::Encode;
37961

            
37961
            Historical::prove((fg_primitives::KEY_TYPE, authority_id))
                .map(|p| p.encode())
                .map(fg_primitives::OpaqueKeyOwnershipProof::new)
        }
37961
    }
37961

            
37961
    impl babe_primitives::BabeApi<Block> for Runtime {
37961
        fn configuration() -> babe_primitives::BabeConfiguration {
            let epoch_config = Babe::epoch_config().unwrap_or(BABE_GENESIS_EPOCH_CONFIG);
            babe_primitives::BabeConfiguration {
                slot_duration: Babe::slot_duration(),
                epoch_length: EpochDurationInBlocks::get().into(),
                c: epoch_config.c,
                authorities: Babe::authorities().to_vec(),
                randomness: Babe::randomness(),
                allowed_slots: epoch_config.allowed_slots,
            }
        }
37961

            
37961
        fn current_epoch_start() -> babe_primitives::Slot {
            Babe::current_epoch_start()
        }
37961

            
37961
        fn current_epoch() -> babe_primitives::Epoch {
            Babe::current_epoch()
        }
37961

            
37961
        fn next_epoch() -> babe_primitives::Epoch {
            Babe::next_epoch()
        }
37961

            
37961
        fn generate_key_ownership_proof(
            _slot: babe_primitives::Slot,
            authority_id: babe_primitives::AuthorityId,
        ) -> Option<babe_primitives::OpaqueKeyOwnershipProof> {
37961
            use parity_scale_codec::Encode;
37961

            
37961
            Historical::prove((babe_primitives::KEY_TYPE, authority_id))
                .map(|p| p.encode())
                .map(babe_primitives::OpaqueKeyOwnershipProof::new)
        }
37961

            
37961
        fn submit_report_equivocation_unsigned_extrinsic(
            equivocation_proof: babe_primitives::EquivocationProof<<Block as BlockT>::Header>,
            key_owner_proof: babe_primitives::OpaqueKeyOwnershipProof,
        ) -> Option<()> {
37961
            let key_owner_proof = key_owner_proof.decode()?;
37961

            
37961
            Babe::submit_unsigned_equivocation_report(
                equivocation_proof,
                key_owner_proof,
            )
37961
        }
37961
    }
37961

            
37961
    impl authority_discovery_primitives::AuthorityDiscoveryApi<Block> for Runtime {
37961
        fn authorities() -> Vec<AuthorityDiscoveryId> {
            parachains_runtime_api_impl::relevant_authority_ids::<Runtime>()
        }
37961
    }
37961

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

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

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

            
37961
    impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<
37961
        Block,
37961
        Balance,
37961
    > for Runtime {
37961
        fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {
            TransactionPayment::query_info(uxt, len)
        }
37961
        fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {
            TransactionPayment::query_fee_details(uxt, len)
        }
37961
        fn query_weight_to_fee(weight: Weight) -> Balance {
            TransactionPayment::weight_to_fee(weight)
        }
37961
        fn query_length_to_fee(length: u32) -> Balance {
            TransactionPayment::length_to_fee(length)
        }
37961
    }
37961

            
37961
    impl pallet_beefy_mmr::BeefyMmrApi<Block, Hash> for RuntimeApi {
37961
        fn authority_set_proof() -> beefy_primitives::mmr::BeefyAuthoritySet<Hash> {
            MmrLeaf::authority_set_proof()
        }
37961

            
37961
        fn next_authority_set_proof() -> beefy_primitives::mmr::BeefyNextAuthoritySet<Hash> {
            MmrLeaf::next_authority_set_proof()
        }
37961
    }
37961

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

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

            
37961
    impl pallet_registrar_runtime_api::RegistrarApi<Block, ParaId> for Runtime {
37961
        /// Return the registered para ids
37971
        fn registered_paras() -> Vec<ParaId> {
10
            // We should return the container-chains for the session in which we are kicking in
10
            // We could potentially predict whether the next block will yield a session change as in dancebox but this
10
            // is innecesary: the dancelight blocks are being produced by validators, and therefore it should never
10
            // stall because of any collator-rotation. Therefore it suffices for collators to predict the chain in
10
            // which they have to collate after the session-change block.
10
            let session_index = Session::current_index();
10
            let container_chains = ContainerRegistrar::session_container_chains(session_index);
10
            let mut para_ids = vec![];
10
            para_ids.extend(container_chains.parachains);
10
            para_ids.extend(container_chains.parathreads.into_iter().map(|(para_id, _)| para_id));
10

            
10
            para_ids
10
        }
37961

            
37961
        /// Fetch genesis data for this para id
37980
        fn genesis_data(para_id: ParaId) -> Option<ContainerChainGenesisData> {
19
            ContainerRegistrar::para_genesis_data(para_id)
19
        }
37961

            
37961
        /// Fetch boot_nodes for this para id
37961
        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()
        }
37961
    }
37961

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

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

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

            
37961
    impl dp_consensus::TanssiAuthorityAssignmentApi<Block, NimbusId> for Runtime {
37961
        /// Return the current authorities assigned to a given paraId
37961
        fn para_id_authorities(para_id: ParaId) -> Option<Vec<NimbusId>> {
            let session_index = Session::current_index();
37961
            let assigned_authorities = TanssiAuthorityAssignment::collator_container_chain(session_index)?;
37961

            
37961
            assigned_authorities.container_chains.get(&para_id).cloned()
37961
        }
37961

            
37961
        /// Return the paraId assigned to a given authority
37961
        fn check_para_id_assignment(authority: NimbusId) -> Option<ParaId> {
            let session_index = Session::current_index();
37961
            let assigned_authorities = TanssiAuthorityAssignment::collator_container_chain(session_index)?;
37961
            // This self_para_id is used to detect assignments to orchestrator, in this runtime the
37961
            // orchestrator will always be empty so we can set it to any value
37961
            let self_para_id = 0u32.into();
            assigned_authorities.para_id_of(&authority, self_para_id)
37961
        }
37961

            
37961
        /// Return the paraId assigned to a given authority on the next session.
37961
        /// On session boundary this returns the same as `check_para_id_assignment`.
37961
        fn check_para_id_assignment_next_session(authority: NimbusId) -> Option<ParaId> {
            let session_index = Session::current_index() + 1;
37961
            let assigned_authorities = TanssiAuthorityAssignment::collator_container_chain(session_index)?;
37961
            // This self_para_id is used to detect assignments to orchestrator, in this runtime the
37961
            // orchestrator will always be empty so we can set it to any value
37961
            let self_para_id = 0u32.into();
            assigned_authorities.para_id_of(&authority, self_para_id)
37961
        }
37961
    }
37961

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

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

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

            
37961
            use frame_system_benchmarking::Pallet as SystemBench;
37961
            use frame_benchmarking::baseline::Pallet as Baseline;
37961

            
37961
            use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
37961

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

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

            
37961
        fn dispatch_benchmark(
37961
            config: frame_benchmarking::BenchmarkConfig,
37961
        ) -> Result<
37961
            Vec<frame_benchmarking::BenchmarkBatch>,
37961
            sp_runtime::RuntimeString,
37961
        > {
37961
            use frame_support::traits::WhitelistedStorageKeys;
37961
            use frame_benchmarking::{Benchmarking, BenchmarkBatch, BenchmarkError};
37961
            use frame_system_benchmarking::Pallet as SystemBench;
37961
            use frame_benchmarking::baseline::Pallet as Baseline;
37961
            use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
37961
            use sp_storage::TrackedStorageKey;
37961
            use xcm::latest::prelude::*;
37961
            use xcm_config::{
37961
                AssetHub, LocalCheckAccount, LocationConverter, TokenLocation, XcmConfig,
37961
            };
37961

            
37961
            parameter_types! {
37961
                pub ExistentialDepositAsset: Option<Asset> = Some((
37961
                    TokenLocation::get(),
37961
                    ExistentialDeposit::get()
37961
                ).into());
37961
                pub AssetHubParaId: ParaId = dancelight_runtime_constants::system_parachain::ASSET_HUB_ID.into();
37961
                pub const RandomParaId: ParaId = ParaId::new(43211234);
37961
            }
37961

            
37961
            impl frame_system_benchmarking::Config for Runtime {}
37961
            impl frame_benchmarking::baseline::Config for Runtime {}
37961
            impl pallet_xcm::benchmarking::Config for Runtime {
37961
                type DeliveryHelper = (
37961
                    runtime_common::xcm_sender::ToParachainDeliveryHelper<
37961
                        XcmConfig,
37961
                        ExistentialDepositAsset,
37961
                        xcm_config::PriceForChildParachainDelivery,
37961
                        AssetHubParaId,
37961
                        (),
37961
                    >,
37961
                    runtime_common::xcm_sender::ToParachainDeliveryHelper<
37961
                        XcmConfig,
37961
                        ExistentialDepositAsset,
37961
                        xcm_config::PriceForChildParachainDelivery,
37961
                        RandomParaId,
37961
                        (),
37961
                    >
37961
                );
37961

            
37961
                fn reachable_dest() -> Option<Location> {
37961
                    Some(crate::xcm_config::AssetHub::get())
37961
                }
37961

            
37961
                fn teleportable_asset_and_dest() -> Option<(Asset, Location)> {
37961
                    // Relay/native token can be teleported to/from AH.
37961
                    Some((
37961
                        Asset {
37961
                            fun: Fungible(ExistentialDeposit::get()),
37961
                            id: AssetId(Here.into())
37961
                        },
37961
                        crate::xcm_config::AssetHub::get(),
37961
                    ))
37961
                }
37961

            
37961
                fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> {
37961
                    // Relay can reserve transfer native token to some random parachain.
37961
                    Some((
37961
                        Asset {
37961
                            fun: Fungible(ExistentialDeposit::get()),
37961
                            id: AssetId(Here.into())
37961
                        },
37961
                        Parachain(RandomParaId::get().into()).into(),
37961
                    ))
37961
                }
37961

            
37961
                fn set_up_complex_asset_transfer(
37961
                ) -> Option<(Assets, u32, Location, Box<dyn FnOnce()>)> {
37961
                    // Relay supports only native token, either reserve transfer it to non-system parachains,
37961
                    // or teleport it to system parachain. Use the teleport case for benchmarking as it's
37961
                    // slightly heavier.
37961
                    // Relay/native token can be teleported to/from AH.
37961
                    let native_location = Here.into();
37961
                    let dest = crate::xcm_config::AssetHub::get();
37961
                    pallet_xcm::benchmarking::helpers::native_teleport_as_asset_transfer::<Runtime>(
37961
                        native_location,
37961
                        dest
37961
                    )
37961
                }
37961

            
37961
                fn get_asset() -> Asset {
37961
                    Asset {
37961
                        id: AssetId(Location::here()),
37961
                        fun: Fungible(ExistentialDeposit::get()),
37961
                    }
37961
                }
37961
            }
37961
            impl pallet_xcm_benchmarks::Config for Runtime {
37961
                type XcmConfig = XcmConfig;
37961
                type AccountIdConverter = LocationConverter;
37961
                type DeliveryHelper = runtime_common::xcm_sender::ToParachainDeliveryHelper<
37961
                    XcmConfig,
37961
                    ExistentialDepositAsset,
37961
                    xcm_config::PriceForChildParachainDelivery,
37961
                    AssetHubParaId,
37961
                    (),
37961
                >;
37961
                fn valid_destination() -> Result<Location, BenchmarkError> {
37961
                    Ok(AssetHub::get())
37961
                }
37961
                fn worst_case_holding(_depositable_count: u32) -> Assets {
37961
                    // Dancelight only knows about STAR
37961
                    vec![Asset{
37961
                        id: AssetId(TokenLocation::get()),
37961
                        fun: Fungible(1_000_000 * UNITS),
37961
                    }].into()
37961
                }
37961
            }
37961

            
37961
            parameter_types! {
37961
                pub TrustedTeleporter: Option<(Location, Asset)> = Some((
37961
                    AssetHub::get(),
37961
                    Asset { fun: Fungible(1 * UNITS), id: AssetId(TokenLocation::get()) },
37961
                ));
37961
                pub TrustedReserve: Option<(Location, Asset)> = None;
37961
            }
37961

            
37961
            impl pallet_xcm_benchmarks::fungible::Config for Runtime {
37961
                type TransactAsset = Balances;
37961

            
37961
                type CheckedAccount = LocalCheckAccount;
37961
                type TrustedTeleporter = TrustedTeleporter;
37961
                type TrustedReserve = TrustedReserve;
37961

            
37961
                fn get_asset() -> Asset {
37961
                    Asset {
37961
                        id: AssetId(TokenLocation::get()),
37961
                        fun: Fungible(1 * UNITS),
37961
                    }
37961
                }
37961
            }
37961

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

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

            
37961
                fn worst_case_asset_exchange() -> Result<(Assets, Assets), BenchmarkError> {
37961
                    // Dancelight doesn't support asset exchanges
37961
                    Err(BenchmarkError::Skip)
37961
                }
37961

            
37961
                fn universal_alias() -> Result<(Location, Junction), BenchmarkError> {
37961
                    // The XCM executor of Dancelight doesn't have a configured `UniversalAliases`
37961
                    Err(BenchmarkError::Skip)
37961
                }
37961

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

            
37961
                fn subscribe_origin() -> Result<Location, BenchmarkError> {
37961
                    Ok(AssetHub::get())
37961
                }
37961

            
37961
                fn claimable_asset() -> Result<(Location, Location, Assets), BenchmarkError> {
37961
                    let origin = AssetHub::get();
37961
                    let assets: Assets = (AssetId(TokenLocation::get()), 1_000 * UNITS).into();
37961
                    let ticket = Location { parents: 0, interior: Here };
37961
                    Ok((origin, ticket, assets))
37961
                }
37961

            
37961
                fn fee_asset() -> Result<Asset, BenchmarkError> {
37961
                    Ok(Asset {
37961
                        id: AssetId(TokenLocation::get()),
37961
                        fun: Fungible(1_000_000 * UNITS),
37961
                    })
37961
                }
37961

            
37961
                fn unlockable_asset() -> Result<(Location, Location, Asset), BenchmarkError> {
37961
                    // Dancelight doesn't support asset locking
37961
                    Err(BenchmarkError::Skip)
37961
                }
37961

            
37961
                fn export_message_origin_and_destination(
37961
                ) -> Result<(Location, NetworkId, InteriorLocation), BenchmarkError> {
37961
                    // Dancelight doesn't support exporting messages
37961
                    Err(BenchmarkError::Skip)
37961
                }
37961

            
37961
                fn alias_origin() -> Result<(Location, Location), BenchmarkError> {
37961
                    // The XCM executor of Dancelight doesn't have a configured `Aliasers`
37961
                    Err(BenchmarkError::Skip)
37961
                }
37961
            }
37961

            
37961
            let mut whitelist: Vec<TrackedStorageKey> = AllPalletsWithSystem::whitelisted_storage_keys();
37961
            let treasury_key = frame_system::Account::<Runtime>::hashed_key_for(Treasury::account_id());
37961
            whitelist.push(treasury_key.to_vec().into());
37961

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

            
37961
            add_benchmarks!(params, batches);
37961

            
37961
            Ok(batches)
37961
        }
37961
    }
37961

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

            
37961
        fn get_preset(id: &Option<PresetId>) -> Option<Vec<u8>> {
            get_preset::<RuntimeGenesisConfig>(id, &genesis_config_presets::get_preset)
        }
37961

            
37961
        fn preset_names() -> Vec<PresetId> {
            vec![
                PresetId::from("local_testnet"),
                PresetId::from("development"),
                PresetId::from("staging_testnet"),
                PresetId::from("wococo_local_testnet"),
                PresetId::from("versi_local_testnet"),
            ]
        }
37961
    }
52563
}
pub struct OwnApplySession;
impl tanssi_initializer::ApplyNewSession<Runtime> for OwnApplySession {
283
    fn apply_new_session(
283
        _changed: bool,
283
        session_index: u32,
283
        _all_validators: Vec<(AccountId, nimbus_primitives::NimbusId)>,
283
        _queued: Vec<(AccountId, nimbus_primitives::NimbusId)>,
283
    ) {
283
        // Order is same as in tanssi
283
        // 1.
283
        // We first initialize Configuration
283
        CollatorConfiguration::initializer_on_new_session(&session_index);
283
        // 2. Second, registrar
283
        ContainerRegistrar::initializer_on_new_session(&session_index);
283

            
283
        let invulnerables = TanssiInvulnerables::invulnerables().to_vec();
283

            
283
        let next_collators = invulnerables;
283

            
283
        // Queue next session keys.
283
        let queued_amalgamated = next_collators
283
            .into_iter()
585
            .filter_map(|a| {
585
                let k = pallet_session::NextKeys::<Runtime>::get(&a)?;
585
                Some((a, k.nimbus))
585
            })
283
            .collect::<Vec<_>>();
283

            
585
        let next_collators_accounts = queued_amalgamated.iter().map(|(a, _)| a.clone()).collect();
283

            
283
        // 3. AuthorityMapping
283
        if session_index.is_zero() {
69
            // On the genesis sesion index we need to store current as well
69
            TanssiAuthorityMapping::initializer_on_new_session(&session_index, &queued_amalgamated);
214
        }
        // Otherwise we always store one sessio ahead
        // IMPORTANT: this changes with respect to dancebox/flashbox because here we dont have
        // the current collators and their keys.
        // In contrast, we have the keys for the validators only
283
        TanssiAuthorityMapping::initializer_on_new_session(
283
            &(session_index + 1),
283
            &queued_amalgamated,
283
        );
283

            
283
        // 4. CollatorAssignment
283
        // Unlike in tanssi, where the input to this function are the correct
283
        // queued keys & collators, here we get the input refers to the validators
283
        // and not the collators. Therefore we need to do a similar thing that
283
        // pallet-session does but in this function
283
        // This is, get the collators, fetch their respective keys, and queue the
283
        // assignment
283

            
283
        // CollatorAssignment
283
        let assignments = TanssiCollatorAssignment::initializer_on_new_session(
283
            &session_index,
283
            next_collators_accounts,
283
        );
283

            
283
        // 5. AuthorityAssignment
283
        let queued_id_to_nimbus_map = queued_amalgamated.iter().cloned().collect();
283
        TanssiAuthorityAssignment::initializer_on_new_session(
283
            &session_index,
283
            &queued_id_to_nimbus_map,
283
            &assignments.next_assignment,
283
        );
283
    }
}
parameter_types! {
    pub MockParaId :ParaId = 0u32.into();
}
impl tanssi_initializer::Config for Runtime {
    type SessionIndex = u32;
    /// The identifier type for an authority.
    type AuthorityId = nimbus_primitives::NimbusId;
    type SessionHandler = OwnApplySession;
}
pub struct BabeCurrentBlockRandomnessGetter;
impl BabeCurrentBlockRandomnessGetter {
215
    fn get_block_randomness() -> Option<[u8; 32]> {
215
        // In a relay context we get block randomness from Babe's AuthorVrfRandomness
215
        Babe::author_vrf_randomness()
215
    }
215
    fn get_block_randomness_mixed(subject: &[u8]) -> Option<Hash> {
215
        Self::get_block_randomness()
215
            .map(|random_hash| mix_randomness::<Runtime>(random_hash, subject))
215
    }
}
/// Combines the vrf output of the previous block with the provided subject.
/// This ensures that the randomness will be different on different pallets, as long as the subject is different.
3
pub fn mix_randomness<T: frame_system::Config>(vrf_output: [u8; 32], subject: &[u8]) -> T::Hash {
3
    let mut digest = Vec::new();
3
    digest.extend_from_slice(vrf_output.as_ref());
3
    digest.extend_from_slice(subject);
3

            
3
    T::Hashing::hash(digest.as_slice())
3
}
/// Read full_rotation_period from pallet_configuration
pub struct ConfigurationCollatorRotationSessionPeriod;
impl Get<u32> for ConfigurationCollatorRotationSessionPeriod {
362
    fn get() -> u32 {
362
        CollatorConfiguration::config().full_rotation_period
362
    }
}
// CollatorAssignment expects to set up the rotation's randomness seed on the
// on_finalize hook of the block prior to the actual session change.
// So should_end_session should be true on the last block of the current session
pub struct BabeGetRandomnessForNextBlock;
impl GetRandomnessForNextBlock<u32> for BabeGetRandomnessForNextBlock {
4397
    fn should_end_session(n: u32) -> bool {
4397
        // Check if next slot there is a session change
4397
        n != 1 && {
4397
            let diff = Babe::current_slot()
4397
                .saturating_add(1u64)
4397
                .saturating_sub(Babe::current_epoch_start());
4397
            *diff >= Babe::current_epoch().duration
        }
4397
    }
214
    fn get_randomness() -> [u8; 32] {
214
        let block_number = System::block_number();
214
        let random_seed = if block_number != 0 {
214
            if let Some(random_hash) = {
214
                BabeCurrentBlockRandomnessGetter::get_block_randomness_mixed(b"CollatorAssignment")
214
            } {
                // Return random_hash as a [u8; 32] instead of a Hash
2
                let mut buf = [0u8; 32];
2
                let len = sp_std::cmp::min(32, random_hash.as_ref().len());
2
                buf[..len].copy_from_slice(&random_hash.as_ref()[..len]);
2

            
2
                buf
            } else {
                // If there is no randomness return [0; 32]
212
                [0; 32]
            }
        } else {
            // In block 0 (genesis) there is no randomness
            [0; 32]
        };
214
        random_seed
214
    }
}
// Randomness trait
impl frame_support::traits::Randomness<Hash, BlockNumber> for BabeCurrentBlockRandomnessGetter {
    fn random(subject: &[u8]) -> (Hash, BlockNumber) {
        let block_number = frame_system::Pallet::<Runtime>::block_number();
        let randomness = Self::get_block_randomness_mixed(subject).unwrap_or_default();
        (randomness, block_number)
    }
}
pub struct RemoveParaIdsWithNoCreditsImpl;
impl RemoveParaIdsWithNoCredits for RemoveParaIdsWithNoCreditsImpl {
566
    fn remove_para_ids_with_no_credits(
566
        para_ids: &mut Vec<ParaId>,
566
        currently_assigned: &BTreeSet<ParaId>,
566
    ) {
566
        let blocks_per_session = EpochDurationInBlocks::get();
566

            
566
        para_ids.retain(|para_id| {
            // If the para has been assigned collators for this session it must have enough block credits
            // for the current and the next session.
351
            let block_credits_needed = if currently_assigned.contains(para_id) {
218
                blocks_per_session * 2
            } else {
133
                blocks_per_session
            };
            // Check if the container chain has enough credits for producing blocks
351
            let free_block_credits = pallet_services_payment::BlockProductionCredits::<Runtime>::get(para_id)
351
                .unwrap_or_default();
351

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

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

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

            
32
            let remaining_block_credits = block_credits_needed.saturating_sub(free_block_credits);
32
            let remaining_session_credits = 1u32.saturating_sub(free_session_credits);
32

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

            
32
            let remaining_to_pay = remaining_block_credits_to_pay.saturating_add(remaining_session_credits_to_pay).saturating_add(max_tip);
32

            
32
            // This should take into account whether we tank goes below ED
32
            // The true refers to keepAlive
32
            Balances::can_withdraw(&pallet_services_payment::Pallet::<Runtime>::parachain_tank(*para_id), remaining_to_pay).into_result(true).is_ok()
566
        });
566
    }
    /// Make those para ids valid by giving them enough credits, for benchmarking.
    #[cfg(feature = "runtime-benchmarks")]
    fn make_valid_para_ids(para_ids: &[ParaId]) {
        use frame_support::assert_ok;
        let blocks_per_session = EpochDurationInBlocks::get();
        // Enough credits to run any benchmark
        let block_credits = 20 * blocks_per_session;
        let session_credits = 20;
        for para_id in para_ids {
            assert_ok!(ServicesPayment::set_block_production_credits(
                RuntimeOrigin::root(),
                *para_id,
                block_credits,
            ));
            assert_ok!(ServicesPayment::set_collator_assignment_credits(
                RuntimeOrigin::root(),
                *para_id,
                session_credits,
            ));
        }
    }
}
286
fn host_config_at_session(
286
    session_index_to_consider: SessionIndex,
286
) -> HostConfiguration<BlockNumber> {
286
    let active_config = runtime_parachains::configuration::ActiveConfig::<Runtime>::get();
286

            
286
    let mut pending_configs = runtime_parachains::configuration::PendingConfigs::<Runtime>::get();
286

            
286
    // We are not making any assumptions about number of configurations existing in pending config
286
    // storage item.
286
    // First remove any pending configs greater than session index in consideration
286
    pending_configs = pending_configs
286
        .into_iter()
286
        .filter(|element| element.0 <= session_index_to_consider)
286
        .collect::<Vec<_>>();
286
    // Reverse sorting by the session index
286
    pending_configs.sort_by(|a, b| b.0.cmp(&a.0));
286

            
286
    if pending_configs.is_empty() {
280
        active_config
    } else {
        // We will take first pending config which should be as close to the session index as possible
6
        pending_configs
6
            .first()
6
            .expect("already checked for emptiness above")
6
            .1
6
            .clone()
    }
286
}
pub struct GetCoreAllocationConfigurationImpl;
impl Get<Option<CoreAllocationConfiguration>> for GetCoreAllocationConfigurationImpl {
286
    fn get() -> Option<CoreAllocationConfiguration> {
286
        // We do not have to check for session ending as new session always starts at block initialization which means
286
        // whenever this is called, we are either in old session or in start of a one
286
        // as on block initialization epoch index have been incremented and by extension session has been changed.
286
        let session_index_to_consider = Session::current_index() + 1;
286

            
286
        let max_parachain_percentage =
286
            CollatorConfiguration::max_parachain_cores_percentage(session_index_to_consider)
286
                .unwrap_or(Perbill::from_percent(50));
286

            
286
        let config_to_consider = host_config_at_session(session_index_to_consider);
286

            
286
        Some(CoreAllocationConfiguration {
286
            core_count: config_to_consider.scheduler_params.num_cores,
286
            max_parachain_percentage,
286
        })
286
    }
}
impl pallet_collator_assignment::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type HostConfiguration = CollatorConfiguration;
    type ContainerChains = ContainerRegistrar;
    type SessionIndex = u32;
    type SelfParaId = MockParaId;
    type ShouldRotateAllCollators =
        RotateCollatorsEveryNSessions<ConfigurationCollatorRotationSessionPeriod>;
    type GetRandomnessForNextBlock = BabeGetRandomnessForNextBlock;
    type RemoveInvulnerables = ();
    type RemoveParaIdsWithNoCredits = RemoveParaIdsWithNoCreditsImpl;
    type CollatorAssignmentHook = ServicesPayment;
    type CollatorAssignmentTip = ServicesPayment;
    type Currency = Balances;
    type ForceEmptyOrchestrator = ConstBool<true>;
    type CoreAllocationConfiguration = GetCoreAllocationConfigurationImpl;
    type WeightInfo = ();
}
impl pallet_authority_assignment::Config for Runtime {
    type SessionIndex = u32;
    type AuthorityId = nimbus_primitives::NimbusId;
}
impl pallet_authority_mapping::Config for Runtime {
    type SessionIndex = u32;
    type SessionRemovalBoundary = ConstU32<3>;
    type AuthorityId = nimbus_primitives::NimbusId;
}
#[cfg(all(test, feature = "try-runtime"))]
mod remote_tests {
    use {
        super::*,
        frame_try_runtime::{runtime_decl_for_try_runtime::TryRuntime, UpgradeCheckSelect},
        remote_externalities::{
            Builder, Mode, OfflineConfig, OnlineConfig, SnapshotConfig, Transport,
        },
        std::env::var,
    };
    #[tokio::test]
    async fn run_migrations() {
        if var("RUN_MIGRATION_TESTS").is_err() {
            return;
        }
        sp_tracing::try_init_simple();
        let transport: Transport = var("WS")
            .unwrap_or("wss://dancelight-rpc.polkadot.io:443".to_string())
            .into();
        let maybe_state_snapshot: Option<SnapshotConfig> = var("SNAP").map(|s| s.into()).ok();
        let mut ext = Builder::<Block>::default()
            .mode(if let Some(state_snapshot) = maybe_state_snapshot {
                Mode::OfflineOrElseOnline(
                    OfflineConfig {
                        state_snapshot: state_snapshot.clone(),
                    },
                    OnlineConfig {
                        transport,
                        state_snapshot: Some(state_snapshot),
                        ..Default::default()
                    },
                )
            } else {
                Mode::Online(OnlineConfig {
                    transport,
                    ..Default::default()
                })
            })
            .build()
            .await
            .unwrap();
        ext.execute_with(|| Runtime::on_runtime_upgrade(UpgradeCheckSelect::PreAndPost));
    }
}