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::{
83
        traits::{BlockNumberProvider, ConvertInto},
84
        AccountId32,
85
    },
86
    sp_std::{
87
        cmp::Ordering,
88
        collections::{btree_map::BTreeMap, btree_set::BTreeSet, vec_deque::VecDeque},
89
        marker::PhantomData,
90
        prelude::*,
91
    },
92
    tp_traits::{
93
        apply, derive_storage_traits, EraIndex, GetHostConfiguration, GetSessionContainerChains,
94
        RegistrarHandler, RemoveParaIdsWithNoCredits, Slot, SlotFrequency,
95
    },
96
};
97

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

            
137
pub use {
138
    frame_system::Call as SystemCall,
139
    pallet_balances::Call as BalancesCall,
140
    primitives::{AccountId, Balance},
141
};
142

            
143
/// Constant values used within the runtime.
144
use dancelight_runtime_constants::{currency::*, fee::*, time::*};
145

            
146
// XCM configurations.
147
pub mod xcm_config;
148

            
149
pub mod bridge_to_ethereum_config;
150

            
151
// Weights
152
mod weights;
153

            
154
// Governance and configurations.
155
pub mod governance;
156
use {
157
    governance::{
158
        pallet_custom_origins, AuctionAdmin, Fellows, GeneralAdmin, Treasurer, TreasurySpender,
159
    },
160
    pallet_collator_assignment::CoreAllocationConfiguration,
161
    xcm_runtime_apis::fees::Error as XcmPaymentApiError,
162
};
163

            
164
#[cfg(test)]
165
mod tests;
166

            
167
pub mod genesis_config_presets;
168

            
169
impl_runtime_weights!(dancelight_runtime_constants);
170

            
171
// Make the WASM binary available.
172
#[cfg(feature = "std")]
173
include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
174

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

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

            
196
/// The BABE epoch configuration at genesis.
197
pub const BABE_GENESIS_EPOCH_CONFIG: babe_primitives::BabeEpochConfiguration =
198
    babe_primitives::BabeEpochConfiguration {
199
        c: PRIMARY_PROBABILITY,
200
        allowed_slots: babe_primitives::AllowedSlots::PrimaryAndSecondaryVRFSlots,
201
    };
202

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

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

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

            
239
parameter_types! {
240
    pub const Version: RuntimeVersion = VERSION;
241
    pub const SS58Prefix: u8 = 42;
242
}
243

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

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

            
270
/// Used the compare the privilege of an origin inside the scheduler.
271
pub struct OriginPrivilegeCmp;
272

            
273
impl PrivilegeCmp<OriginCaller> for OriginPrivilegeCmp {
274
    fn cmp_privilege(left: &OriginCaller, right: &OriginCaller) -> Option<Ordering> {
275
        if left == right {
276
            return Some(Ordering::Equal);
277
        }
278

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

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

            
293
    #[dynamic_pallet_params]
294
    #[codec(index = 0)]
295
    pub mod preimage {
296
        use super::*;
297

            
298
        #[codec(index = 0)]
299
        pub static BaseDeposit: Balance = deposit(2, 64);
300

            
301
        #[codec(index = 1)]
302
        pub static ByteDeposit: Balance = deposit(0, 1);
303
    }
304
}
305

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

            
316
/// Defines what origin can modify which dynamic parameters.
317
pub struct DynamicParameterOrigin;
318
impl EnsureOriginWithArg<RuntimeOrigin, RuntimeParametersKey> for DynamicParameterOrigin {
319
    type Success = ();
320

            
321
    fn try_origin(
322
        origin: RuntimeOrigin,
323
        key: &RuntimeParametersKey,
324
    ) -> Result<Self::Success, RuntimeOrigin> {
325
        use crate::RuntimeParametersKey::*;
326

            
327
        match key {
328
            Preimage(_) => frame_system::ensure_root(origin.clone()),
329
        }
330
        .map_err(|_| origin)
331
    }
332

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

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

            
355
parameter_types! {
356
    pub const PreimageHoldReason: RuntimeHoldReason = RuntimeHoldReason::Preimage(pallet_preimage::HoldReason::Preimage);
357
}
358

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

            
376
parameter_types! {
377
    pub const ExpectedBlockTime: Moment = MILLISECS_PER_BLOCK;
378
    pub ReportLongevity: u64 = u64::from(EpochDurationInBlocks::get()) * 10;
379
}
380

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

            
395
parameter_types! {
396
    pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT;
397
    pub const MaxLocks: u32 = 50;
398
    pub const MaxReserves: u32 = 50;
399
}
400

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

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

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

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

            
443
impl pallet_authorship::Config for Runtime {
444
    type FindAuthor = pallet_session::FindAccountFromAuthorIndex<Self, Babe>;
445
    type EventHandler = ();
446
}
447

            
448
impl_opaque_keys! {
449
    pub struct SessionKeys {
450
        pub grandpa: Grandpa,
451
        pub babe: Babe,
452
        pub para_validator: Initializer,
453
        pub para_assignment: ParaSessionInfo,
454
        pub authority_discovery: AuthorityDiscovery,
455
        pub beefy: Beefy,
456
        pub nimbus: TanssiInitializer,
457
    }
458
}
459

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

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

            
480
pub struct FullIdentificationOf;
481
impl sp_runtime::traits::Convert<AccountId, Option<()>> for FullIdentificationOf {
482
633
    fn convert(_: AccountId) -> Option<()> {
483
633
        Some(())
484
633
    }
485
}
486

            
487
impl pallet_session::historical::Config for Runtime {
488
    type FullIdentification = ();
489
    type FullIdentificationOf = FullIdentificationOf;
490
}
491

            
492
parameter_types! {
493
    pub const BondingDuration: sp_staking::EraIndex = runtime_common::prod_or_fast!(28, 3);
494
}
495

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

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

            
521
#[cfg(feature = "runtime-benchmarks")]
522
pub struct TreasuryBenchmarkHelper<T>(PhantomData<T>);
523

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

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

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

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

            
568
impl pallet_offences::Config for Runtime {
569
    type RuntimeEvent = RuntimeEvent;
570
    type IdentificationTuple = pallet_session::historical::IdentificationTuple<Self>;
571
    type OnOffenceHandler = ExternalValidatorSlashes;
572
}
573

            
574
impl pallet_authority_discovery::Config for Runtime {
575
    type MaxAuthorities = MaxAuthorities;
576
}
577

            
578
parameter_types! {
579
    pub const MaxSetIdSessionEntries: u32 = BondingDuration::get() * SessionsPerEra::get();
580
}
581

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

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

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

            
649
impl frame_system::offchain::SigningTypes for Runtime {
650
    type Public = <Signature as Verify>::Signer;
651
    type Signature = Signature;
652
}
653

            
654
impl<C> frame_system::offchain::SendTransactionTypes<C> for Runtime
655
where
656
    RuntimeCall: From<C>,
657
{
658
    type Extrinsic = UncheckedExtrinsic;
659
    type OverarchingCall = RuntimeCall;
660
}
661

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

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

            
693
impl pallet_utility::Config for Runtime {
694
    type RuntimeEvent = RuntimeEvent;
695
    type RuntimeCall = RuntimeCall;
696
    type PalletsOrigin = OriginCaller;
697
    type WeightInfo = weights::pallet_utility::SubstrateWeight<Runtime>;
698
}
699

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

            
708
impl pallet_multisig::Config for Runtime {
709
    type RuntimeEvent = RuntimeEvent;
710
    type RuntimeCall = RuntimeCall;
711
    type Currency = Balances;
712
    type DepositBase = DepositBase;
713
    type DepositFactor = DepositFactor;
714
    type MaxSignatories = MaxSignatories;
715
    type WeightInfo = weights::pallet_multisig::SubstrateWeight<Runtime>;
716
}
717

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

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

            
838
impl pallet_proxy::Config for Runtime {
839
    type RuntimeEvent = RuntimeEvent;
840
    type RuntimeCall = RuntimeCall;
841
    type Currency = Balances;
842
    type ProxyType = ProxyType;
843
    type ProxyDepositBase = ProxyDepositBase;
844
    type ProxyDepositFactor = ProxyDepositFactor;
845
    type MaxProxies = MaxProxies;
846
    type WeightInfo = weights::pallet_proxy::SubstrateWeight<Runtime>;
847
    type MaxPending = MaxPending;
848
    type CallHasher = BlakeTwo256;
849
    type AnnouncementDepositBase = AnnouncementDepositBase;
850
    type AnnouncementDepositFactor = AnnouncementDepositFactor;
851
}
852

            
853
impl parachains_origin::Config for Runtime {}
854

            
855
impl parachains_configuration::Config for Runtime {
856
    type WeightInfo = weights::runtime_parachains_configuration::SubstrateWeight<Runtime>;
857
}
858

            
859
impl parachains_shared::Config for Runtime {
860
    type DisabledValidators = Session;
861
}
862

            
863
impl parachains_session_info::Config for Runtime {
864
    type ValidatorSet = Historical;
865
}
866

            
867
pub type RewardValidators =
868
    pallet_external_validators_rewards::RewardValidatorsWithEraPoints<Runtime>;
869

            
870
impl parachains_inclusion::Config for Runtime {
871
    type RuntimeEvent = RuntimeEvent;
872
    type DisputesHandler = ParasDisputes;
873
    type RewardValidators = RewardValidators;
874
    type MessageQueue = MessageQueue;
875
    type WeightInfo = weights::runtime_parachains_inclusion::SubstrateWeight<Runtime>;
876
}
877

            
878
parameter_types! {
879
    pub const ParasUnsignedPriority: TransactionPriority = TransactionPriority::max_value();
880
}
881

            
882
impl parachains_paras::Config for Runtime {
883
    type RuntimeEvent = RuntimeEvent;
884
    type WeightInfo = weights::runtime_parachains_paras::SubstrateWeight<Runtime>;
885
    type UnsignedPriority = ParasUnsignedPriority;
886
    type QueueFootprinter = ParaInclusion;
887
    type NextSessionRotation = Babe;
888
    type OnNewHead = Registrar;
889
    type AssignCoretime = ();
890
}
891

            
892
parameter_types! {
893
    /// Amount of weight that can be spent per block to service messages.
894
    ///
895
    /// # WARNING
896
    ///
897
    /// This is not a good value for para-chains since the `Scheduler` already uses up to 80% block weight.
898
    pub MessageQueueServiceWeight: Weight = Perbill::from_percent(20) * BlockWeights::get().max_block;
899
    pub const MessageQueueHeapSize: u32 = 32 * 1024;
900
    pub const MessageQueueMaxStale: u32 = 96;
901
}
902

            
903
/// Message processor to handle any messages that were enqueued into the `MessageQueue` pallet.
904
pub struct MessageProcessor;
905
impl ProcessMessage for MessageProcessor {
906
    type Origin = AggregateMessageOrigin;
907

            
908
    fn process_message(
909
        message: &[u8],
910
        origin: Self::Origin,
911
        meter: &mut WeightMeter,
912
        id: &mut [u8; 32],
913
    ) -> Result<bool, ProcessMessageError> {
914
        let para = match origin {
915
            AggregateMessageOrigin::Ump(UmpQueueId::Para(para)) => para,
916
        };
917
        xcm_builder::ProcessXcmMessage::<
918
            Junction,
919
            xcm_executor::XcmExecutor<xcm_config::XcmConfig>,
920
            RuntimeCall,
921
        >::process_message(message, Junction::Parachain(para.into()), meter, id)
922
    }
923
}
924

            
925
impl pallet_message_queue::Config for Runtime {
926
    type RuntimeEvent = RuntimeEvent;
927
    type Size = u32;
928
    type HeapSize = MessageQueueHeapSize;
929
    type MaxStale = MessageQueueMaxStale;
930
    type ServiceWeight = MessageQueueServiceWeight;
931
    type IdleMaxServiceWeight = MessageQueueServiceWeight;
932
    #[cfg(not(feature = "runtime-benchmarks"))]
933
    type MessageProcessor = MessageProcessor;
934
    #[cfg(feature = "runtime-benchmarks")]
935
    type MessageProcessor =
936
        pallet_message_queue::mock_helpers::NoopMessageProcessor<AggregateMessageOrigin>;
937
    type QueueChangeHandler = ParaInclusion;
938
    type QueuePausedQuery = ();
939
    type WeightInfo = weights::pallet_message_queue::SubstrateWeight<Runtime>;
940
}
941

            
942
impl parachains_dmp::Config for Runtime {}
943

            
944
parameter_types! {
945
    pub const HrmpChannelSizeAndCapacityWithSystemRatio: Percent = Percent::from_percent(100);
946
}
947

            
948
impl parachains_hrmp::Config for Runtime {
949
    type RuntimeOrigin = RuntimeOrigin;
950
    type RuntimeEvent = RuntimeEvent;
951
    type ChannelManager = EnsureRoot<AccountId>;
952
    type Currency = Balances;
953
    type DefaultChannelSizeAndCapacityWithSystem =
954
        parachains_configuration::ActiveConfigHrmpChannelSizeAndCapacityRatio<
955
            Runtime,
956
            HrmpChannelSizeAndCapacityWithSystemRatio,
957
        >;
958
    type WeightInfo = weights::runtime_parachains_hrmp::SubstrateWeight<Runtime>;
959
    type VersionWrapper = XcmPallet;
960
}
961

            
962
impl parachains_paras_inherent::Config for Runtime {
963
    type WeightInfo = weights::runtime_parachains_paras_inherent::SubstrateWeight<Runtime>;
964
}
965

            
966
impl parachains_scheduler::Config for Runtime {
967
    // If you change this, make sure the `Assignment` type of the new provider is binary compatible,
968
    // otherwise provide a migration.
969
    type AssignmentProvider = CollatorAssignmentProvider;
970
}
971

            
972
pub struct CollatorAssignmentProvider;
973
impl parachains_scheduler::common::AssignmentProvider<BlockNumberFor<Runtime>>
974
    for CollatorAssignmentProvider
975
{
976
16
    fn pop_assignment_for_core(core_idx: CoreIndex) -> Option<Assignment> {
977
16
        let assigned_collators = TanssiCollatorAssignment::collator_container_chain();
978
16
        let assigned_paras: Vec<ParaId> = assigned_collators
979
16
            .container_chains
980
16
            .iter()
981
16
            .filter_map(|(&para_id, _)| {
982
16
                if Paras::is_parachain(para_id) {
983
6
                    Some(para_id)
984
                } else {
985
10
                    None
986
                }
987
16
            })
988
16
            .collect();
989
16
        log::debug!("pop assigned collators {:?}", assigned_paras);
990
16
        log::debug!("looking for core idx {:?}", core_idx);
991

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

            
995
3
            Some(Assignment::Bulk(*para_id))
996
        } else {
997
            // We dont want to assign affinity to a parathread that has not collators assigned
998
            // Even if we did they would need their own collators to produce blocks, but for now
999
            // I prefer to forbid.
            // In this case the parathread would have bought the core for nothing
5
            let assignment =
13
                parachains_assigner_on_demand::Pallet::<Runtime>::pop_assignment_for_core(
13
                    core_idx,
13
                )?;
5
            if assigned_collators
5
                .container_chains
5
                .contains_key(&assignment.para_id())
            {
5
                Some(assignment)
            } else {
                None
            }
        }
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)
    }
336
    fn session_core_count() -> u32 {
336
        let config = runtime_parachains::configuration::ActiveConfig::<Runtime>::get();
336
        log::debug!(
            "session core count is {:?}",
            config.scheduler_params.num_cores
        );
336
        config.scheduler_params.num_cores
336
    }
}
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 = 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! {
    // TODO: BondingDuration is set to 28 days on Polkadot,
    // check which value to use in Starlight.
    pub BeefySetIdSessionEntries: u32 = BondingDuration::get() * SessionsPerEra::get();
}
impl pallet_beefy::Config for Runtime {
    type BeefyId = BeefyId;
    type MaxAuthorities = MaxAuthorities;
    // MaxNominators is used in case we need to slash validators and check how many
    // nominators do they have as maximum.
    // This value is part of the parameters that are then used for extrinsics
    // weight computation.
    type MaxNominators = ConstU32<0>;
    type MaxSetIdSessionEntries = BeefySetIdSessionEntries;
    type OnNewValidatorSet = BeefyMmrLeaf;
    type WeightInfo = ();
    type KeyOwnerProof = <Historical as KeyOwnerProofSystem<(KeyTypeId, BeefyId)>>::Proof;
    type EquivocationReportSystem =
        pallet_beefy::EquivocationReportSystem<Self, Offences, Historical, ReportLongevity>;
    type AncestryHelper = BeefyMmrLeaf;
}
/// 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 {
2978
    fn extra_data() -> H256 {
2978
        let mut para_heads: Vec<(u32, Vec<u8>)> = parachains_paras::Parachains::<Runtime>::get()
2978
            .into_iter()
2978
            .filter_map(|id| {
2254
                parachains_paras::Heads::<Runtime>::get(id).map(|head| (id.into(), head.0))
2978
            })
2978
            .collect();
2978
        para_heads.sort();
2978
        binary_merkle_tree::merkle_root::<mmr::Hashing, _>(
2978
            para_heads.into_iter().map(|pair| pair.encode()),
2978
        )
2978
    }
}
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 {}
use pallet_staking::SessionInterface;
pub struct DancelightSessionInterface;
impl SessionInterface<AccountId> for DancelightSessionInterface {
    fn disable_validator(validator_index: u32) -> bool {
        Session::disable_index(validator_index)
    }
    fn validators() -> Vec<AccountId> {
        Session::validators()
    }
9
    fn prune_historical_up_to(up_to: SessionIndex) {
9
        Historical::prune_up_to(up_to);
9
    }
}
parameter_types! {
    pub const SessionsPerEra: SessionIndex = runtime_common::prod_or_fast!(6, 3);
    pub const SlashDeferDuration: EraIndex = runtime_common::prod_or_fast!(27, 2);
}
impl pallet_external_validators::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type UpdateOrigin = EnsureRoot<AccountId>;
    type HistoryDepth = ConstU32<84>;
    type MaxWhitelistedValidators = MaxWhitelistedValidators;
    type MaxExternalValidators = MaxExternalValidators;
    type ValidatorId = AccountId;
    type ValidatorIdOf = ValidatorIdOf;
    type ValidatorRegistration = Session;
    type UnixTime = Timestamp;
    type SessionsPerEra = SessionsPerEra;
    type OnEraStart = (ExternalValidatorSlashes, ExternalValidatorsRewards);
    type OnEraEnd = ();
    type WeightInfo = weights::pallet_external_validators::SubstrateWeight<Runtime>;
    #[cfg(feature = "runtime-benchmarks")]
    type Currency = Balances;
}
impl pallet_external_validators_rewards::Config for Runtime {
    type EraIndexProvider = ExternalValidators;
    type HistoryDepth = ConstU32<64>;
    type BackingPoints = ConstU32<20>;
    type DisputeStatementPoints = ConstU32<20>;
}
impl pallet_external_validator_slashes::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type ValidatorId = AccountId;
    type ValidatorIdOf = ValidatorIdOf;
    type SlashDeferDuration = SlashDeferDuration;
    type BondingDuration = BondingDuration;
    type SlashId = u32;
    type SessionInterface = DancelightSessionInterface;
    type EraIndexProvider = ExternalValidators;
    type InvulnerablesProvider = ExternalValidators;
    type WeightInfo = weights::pallet_external_validator_slashes::SubstrateWeight<Runtime>;
}
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;
    pub const MaxWhitelistedValidators: u32 = 100;
    pub const MaxExternalValidators: 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 = ConvertInto;
    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;
}
474846
construct_runtime! {
12458
    pub enum Runtime
12458
    {
12458
        // Basic stuff; balances is uncallable initially.
12458
        System: frame_system = 0,
12458

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

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

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

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

            
12458
        // Validator stuff
12458
        ExternalValidators: pallet_external_validators = 20,
12458
        ExternalValidatorSlashes: pallet_external_validator_slashes = 21,
12458
        ExternalValidatorsRewards: pallet_external_validators_rewards = 22,
12458

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
12458
        // BEEFY Bridges support.
12458
        Beefy: pallet_beefy = 240,
12458
        // MMR leaf construction must be after session in order to have a leaf's next_auth_set
12458
        // refer to block<N>.
12458
        Mmr: pallet_mmr = 241,
12458
        BeefyMmrLeaf: pallet_beefy_mmr = 242,
12458
        EthereumBeaconClient: snowbridge_pallet_ethereum_client = 243,
12458

            
12458
        ParasSudoWrapper: paras_sudo_wrapper = 250,
12458

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

            
12458
        // Sudo.
12458
        Sudo: pallet_sudo = 255,
12458
    }
475328
}
/// 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>,
    frame_metadata_hash_extension::CheckMetadataHash<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,
    sp_runtime::AccountId32: From<AccountId>,
{
31
    fn register(
31
        who: AccountId,
31
        id: ParaId,
31
        genesis_storage: &[ContainerChainGenesisDataItem],
31
        head_data: Option<HeadData>,
31
    ) -> DispatchResult {
        // Return early if head_data is not specified
31
        let genesis_head = match head_data {
31
            Some(data) => data,
            None => return Err(ContainerRegistrarError::<Runtime>::HeadDataNecessary.into()),
        };
        // Check if the wasm code is present in storage
31
        let validation_code = match genesis_storage
31
            .iter()
31
            .find(|item| item.key == StorageWellKnownKeys::CODE)
        {
31
            Some(item) => ValidationCode(item.value.clone()),
            None => return Err(ContainerRegistrarError::<Runtime>::WasmCodeNecessary.into()),
        };
        // Try to register the parachain
        // Using register extrinsic instead of `RegistrarInterface` trait because we want
        // to check that the para id has been reserved.
31
        Registrar::register(
31
            RuntimeOrigin::signed(who.into()),
31
            id,
31
            genesis_head,
31
            validation_code,
31
        )
31
    }
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
    }
    #[cfg(feature = "runtime-benchmarks")]
    fn bench_head_data() -> Option<HeadData> {
        let head_data = HeadData(vec![1; 10]);
        Some(head_data)
    }
    #[cfg(feature = "runtime-benchmarks")]
    fn add_trusted_validation_code(code: Vec<u8>) {
        Paras::add_trusted_validation_code(RuntimeOrigin::root(), code.into()).unwrap();
    }
    #[cfg(feature = "runtime-benchmarks")]
    fn registrar_new_session(session: u32) {
        benchmark_helpers::run_to_session(session)
    }
}
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;
    type InnerRegistrar =
        InnerDancelightRegistrar<Runtime, AccountId, Registrar, paras_registrar::TestWeightInfo>;
    type WeightInfo = weights::pallet_registrar::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]
        [pallet_registrar, ContainerRegistrar]
        [pallet_collator_assignment, TanssiCollatorAssignment]
        [pallet_external_validators, ExternalValidators]
        [pallet_external_validator_slashes, ExternalValidatorSlashes]
        // 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>]
        // Bridges
        [snowbridge_pallet_ethereum_client, EthereumBeaconClient]
    );
}
121597
sp_api::impl_runtime_apis! {
103355
    impl sp_api::Core<Block> for Runtime {
103355
        fn version() -> RuntimeVersion {
            VERSION
        }
103355

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
103355
        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,
            )
        }
103355

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
103355
        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,
            )
        }
103355

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
103355
        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,
                    )
                },
            )
        }
103355

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

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

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

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

            
103355
        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<()> {
103355
            let key_owner_proof = key_owner_proof.decode()?;
103355

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

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

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

            
103355
    impl babe_primitives::BabeApi<Block> for Runtime {
103355
        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,
            }
        }
103355

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

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

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

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

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

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

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

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

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

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

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

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

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

            
103355
        fn next_authority_set_proof() -> beefy_primitives::mmr::BeefyNextAuthoritySet<Hash> {
            BeefyMmrLeaf::next_authority_set_proof()
        }
103355
    }
103355

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

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

            
103355
    impl pallet_registrar_runtime_api::RegistrarApi<Block, ParaId> for Runtime {
103355
        /// Return the registered para ids
103365
        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
        }
103355

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

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

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

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

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

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

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

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

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

            
103355
    impl pallet_services_payment_runtime_api::ServicesPaymentApi<Block, Balance, ParaId> for Runtime {
103355
        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
        }
103355

            
103355
        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
        }
103355
    }
103355

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
103355
                type CheckedAccount = LocalCheckAccount;
103355
                type TrustedTeleporter = TrustedTeleporter;
103355
                type TrustedReserve = TrustedReserve;
103355

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
103355
            add_benchmarks!(params, batches);
103355

            
103355
            Ok(batches)
103355
        }
103355
    }
103355

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

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

            
103355
        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"),
            ]
        }
103355
    }
121597
}
pub struct OwnApplySession;
impl tanssi_initializer::ApplyNewSession<Runtime> for OwnApplySession {
385
    fn apply_new_session(
385
        _changed: bool,
385
        session_index: u32,
385
        _all_validators: Vec<(AccountId, nimbus_primitives::NimbusId)>,
385
        _queued: Vec<(AccountId, nimbus_primitives::NimbusId)>,
385
    ) {
385
        // Order is same as in tanssi
385
        // 1.
385
        // We first initialize Configuration
385
        CollatorConfiguration::initializer_on_new_session(&session_index);
385
        // 2. Second, registrar
385
        ContainerRegistrar::initializer_on_new_session(&session_index);
385

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

            
385
        let next_collators = invulnerables;
385

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

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

            
385
        // 3. AuthorityMapping
385
        if session_index.is_zero() {
100
            // On the genesis sesion index we need to store current as well
100
            TanssiAuthorityMapping::initializer_on_new_session(&session_index, &queued_amalgamated);
285
        }
        // 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
385
        TanssiAuthorityMapping::initializer_on_new_session(
385
            &(session_index + 1),
385
            &queued_amalgamated,
385
        );
385

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

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

            
385
        // 5. AuthorityAssignment
385
        let queued_id_to_nimbus_map = queued_amalgamated.iter().cloned().collect();
385
        TanssiAuthorityAssignment::initializer_on_new_session(
385
            &session_index,
385
            &queued_id_to_nimbus_map,
385
            &assignments.next_assignment,
385
        );
385
    }
}
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 {
286
    fn get_block_randomness() -> Option<[u8; 32]> {
286
        // In a relay context we get block randomness from Babe's AuthorVrfRandomness
286
        Babe::author_vrf_randomness()
286
    }
286
    fn get_block_randomness_mixed(subject: &[u8]) -> Option<Hash> {
286
        Self::get_block_randomness()
286
            .map(|random_hash| mix_randomness::<Runtime>(random_hash, subject))
286
    }
}
/// 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 {
464
    fn get() -> u32 {
464
        CollatorConfiguration::config().full_rotation_period
464
    }
}
// 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 {
5864
    fn should_end_session(n: u32) -> bool {
5864
        // Check if next slot there is a session change
5864
        n != 1 && {
5864
            let diff = Babe::current_slot()
5864
                .saturating_add(1u64)
5864
                .saturating_sub(Babe::current_epoch_start());
5864
            *diff >= Babe::current_epoch().duration
        }
5864
    }
285
    fn get_randomness() -> [u8; 32] {
285
        let block_number = System::block_number();
285
        let random_seed = if block_number != 0 {
285
            if let Some(random_hash) = {
285
                BabeCurrentBlockRandomnessGetter::get_block_randomness_mixed(b"CollatorAssignment")
285
            } {
                // 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]
283
                [0; 32]
            }
        } else {
            // In block 0 (genesis) there is no randomness
            [0; 32]
        };
285
        random_seed
285
    }
}
// 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 {
770
    fn remove_para_ids_with_no_credits(
770
        para_ids: &mut Vec<ParaId>,
770
        currently_assigned: &BTreeSet<ParaId>,
770
    ) {
770
        let blocks_per_session = EpochDurationInBlocks::get();
770

            
770
        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()
770
        });
770
    }
    /// 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,
            ));
        }
    }
}
388
fn host_config_at_session(
388
    session_index_to_consider: SessionIndex,
388
) -> HostConfiguration<BlockNumber> {
388
    let active_config = runtime_parachains::configuration::ActiveConfig::<Runtime>::get();
388

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

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

            
388
    if pending_configs.is_empty() {
382
        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()
    }
388
}
pub struct GetCoreAllocationConfigurationImpl;
impl Get<Option<CoreAllocationConfiguration>> for GetCoreAllocationConfigurationImpl {
388
    fn get() -> Option<CoreAllocationConfiguration> {
388
        // We do not have to check for session ending as new session always starts at block initialization which means
388
        // whenever this is called, we are either in old session or in start of a one
388
        // as on block initialization epoch index have been incremented and by extension session has been changed.
388
        let session_index_to_consider = Session::current_index() + 1;
388

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

            
388
        let config_to_consider = host_config_at_session(session_index_to_consider);
388

            
388
        Some(CoreAllocationConfiguration {
388
            core_count: config_to_consider.scheduler_params.num_cores,
388
            max_parachain_percentage,
388
        })
388
    }
}
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 = weights::pallet_collator_assignment::SubstrateWeight<Runtime>;
}
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(feature = "runtime-benchmarks")]
mod benchmark_helpers {
    use {
        super::*,
        babe_primitives::{
            digests::{PreDigest, SecondaryPlainPreDigest},
            BABE_ENGINE_ID,
        },
        frame_support::traits::Hooks,
        sp_runtime::{Digest, DigestItem},
    };
    fn end_block() {
        Babe::on_finalize(System::block_number());
        Session::on_finalize(System::block_number());
        Grandpa::on_finalize(System::block_number());
        TransactionPayment::on_finalize(System::block_number());
        Initializer::on_finalize(System::block_number());
        ContainerRegistrar::on_finalize(System::block_number());
        TanssiCollatorAssignment::on_finalize(System::block_number());
    }
    pub fn insert_authorities_and_slot_digests(slot: u64) {
        let pre_digest = Digest {
            logs: vec![DigestItem::PreRuntime(
                BABE_ENGINE_ID,
                PreDigest::SecondaryPlain(SecondaryPlainPreDigest {
                    slot: slot.into(),
                    authority_index: 0,
                })
                .encode(),
            )],
        };
        System::reset_events();
        System::initialize(
            &(System::block_number() + 1),
            &System::parent_hash(),
            &pre_digest,
        );
    }
    pub fn current_slot() -> u64 {
        Babe::current_slot().into()
    }
    fn start_block() {
        insert_authorities_and_slot_digests(current_slot() + 1);
        // Initialize the new block
        Babe::on_initialize(System::block_number());
        ContainerRegistrar::on_initialize(System::block_number());
        Session::on_initialize(System::block_number());
        Initializer::on_initialize(System::block_number());
        TanssiCollatorAssignment::on_initialize(System::block_number());
        InflationRewards::on_initialize(System::block_number());
    }
    pub fn session_to_block(n: u32) -> u32 {
        // let block_number = flashbox_runtime::Period::get() * n;
        let block_number = Babe::current_epoch().duration.saturated_into::<u32>() * n;
        // Add 1 because the block that emits the NewSession event cannot contain any extrinsics,
        // so this is the first block of the new session that can actually be used
        block_number + 1
    }
    pub fn run_to_block(n: u32) {
        while System::block_number() < n {
            run_block();
        }
    }
    pub fn run_block() {
        end_block();
        start_block()
    }
    pub fn run_to_session(n: u32) {
        run_to_block(session_to_block(n));
    }
}
#[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));
    }
}