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

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

            
144
pub use {
145
    frame_system::Call as SystemCall,
146
    pallet_balances::Call as BalancesCall,
147
    primitives::{AccountId, Balance},
148
};
149

            
150
#[cfg(feature = "runtime-benchmarks")]
151
use snowbridge_core::{AgentId, TokenId};
152

            
153
/// Constant values used within the runtime.
154
use dancelight_runtime_constants::{currency::*, fee::*, snowbridge::EthereumLocation, time::*};
155

            
156
// XCM configurations.
157
pub mod xcm_config;
158

            
159
pub mod bridge_to_ethereum_config;
160

            
161
// Weights
162
mod weights;
163

            
164
// Governance and configurations.
165
pub mod governance;
166
use {
167
    governance::{
168
        pallet_custom_origins, AuctionAdmin, Fellows, GeneralAdmin, Treasurer, TreasurySpender,
169
    },
170
    pallet_collator_assignment::CoreAllocationConfiguration,
171
    xcm_runtime_apis::fees::Error as XcmPaymentApiError,
172
};
173

            
174
#[cfg(test)]
175
mod tests;
176

            
177
pub mod genesis_config_presets;
178

            
179
impl_runtime_weights!(dancelight_runtime_constants);
180

            
181
// Make the WASM binary available.
182
#[cfg(feature = "std")]
183
include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
184

            
185
/// Provides the `WASM_BINARY` build with `fast-runtime` feature enabled.
186
///
187
/// This is for example useful for local test chains.
188
#[cfg(feature = "std")]
189
pub mod fast_runtime_binary {
190
    include!(concat!(env!("OUT_DIR"), "/fast_runtime_binary.rs"));
191
}
192

            
193
/// Runtime version (Dancelight).
194
#[sp_version::runtime_version]
195
pub const VERSION: RuntimeVersion = RuntimeVersion {
196
    spec_name: create_runtime_str!("dancelight"),
197
    impl_name: create_runtime_str!("tanssi-dancelight-v2.0"),
198
    authoring_version: 0,
199
    spec_version: 1200,
200
    impl_version: 0,
201
    apis: RUNTIME_API_VERSIONS,
202
    transaction_version: 26,
203
    state_version: 1,
204
};
205

            
206
/// The BABE epoch configuration at genesis.
207
pub const BABE_GENESIS_EPOCH_CONFIG: babe_primitives::BabeEpochConfiguration =
208
    babe_primitives::BabeEpochConfiguration {
209
        c: PRIMARY_PROBABILITY,
210
        allowed_slots: babe_primitives::AllowedSlots::PrimaryAndSecondaryVRFSlots,
211
    };
212

            
213
/// Native version.
214
#[cfg(any(feature = "std", test))]
215
pub fn native_version() -> NativeVersion {
216
    NativeVersion {
217
        runtime_version: VERSION,
218
        can_author_with: Default::default(),
219
    }
220
}
221

            
222
/// Aggregate message origin for the `MessageQueue` pallet.
223
///
224
/// Can be extended to serve further use-cases besides just UMP. Is stored in storage, so any change
225
/// to existing values will require a migration.
226
#[derive(Encode, Decode, Clone, MaxEncodedLen, Eq, PartialEq, RuntimeDebug, TypeInfo)]
227
pub enum AggregateMessageOrigin {
228
    /// Inbound upward message.
229
    #[codec(index = 0)]
230
    Ump(UmpQueueId),
231

            
232
94
    /// The message came from a snowbridge channel. It will be processed by `snowbridge_pallet_outbound_queue`.
233
    #[codec(index = 1)]
234
    Snowbridge(ChannelId),
235

            
236
394
    /// The message came from a snowbridge channel, and it's a custom message that only exists in Tanssi.
237
    /// This will be processed by `CustomProcessSnowbridgeMessage`.
238
    #[codec(index = 2)]
239
    SnowbridgeTanssi(ChannelId),
240
}
241

            
242
#[cfg(feature = "runtime-benchmarks")]
243
impl From<u32> for AggregateMessageOrigin {
244
    fn from(n: u32) -> Self {
245
        // Some dummy for the benchmarks.
246
        Self::Ump(UmpQueueId::Para(n.into()))
247
    }
248
}
249

            
250
pub struct GetAggregateMessageOrigin;
251

            
252
impl Convert<ChannelId, AggregateMessageOrigin> for GetAggregateMessageOrigin {
253
12
    fn convert(channel_id: ChannelId) -> AggregateMessageOrigin {
254
12
        AggregateMessageOrigin::Snowbridge(channel_id)
255
12
    }
256
}
257

            
258
impl Convert<UmpQueueId, AggregateMessageOrigin> for GetAggregateMessageOrigin {
259
18
    fn convert(queue_id: UmpQueueId) -> AggregateMessageOrigin {
260
18
        AggregateMessageOrigin::Ump(queue_id)
261
18
    }
262
}
263

            
264
pub struct GetAggregateMessageOriginTanssi;
265

            
266
impl Convert<ChannelId, AggregateMessageOrigin> for GetAggregateMessageOriginTanssi {
267
42
    fn convert(channel_id: ChannelId) -> AggregateMessageOrigin {
268
42
        AggregateMessageOrigin::SnowbridgeTanssi(channel_id)
269
42
    }
270
}
271

            
272
/// This is used by [parachains_inclusion::Pallet::on_queue_changed]
273
pub struct GetParaFromAggregateMessageOrigin;
274

            
275
impl Convert<AggregateMessageOrigin, ParaId> for GetParaFromAggregateMessageOrigin {
276
105
    fn convert(x: AggregateMessageOrigin) -> ParaId {
277
105
        match x {
278
            AggregateMessageOrigin::Ump(UmpQueueId::Para(para_id)) => para_id,
279
22
            AggregateMessageOrigin::Snowbridge(channel_id)
280
83
            | AggregateMessageOrigin::SnowbridgeTanssi(channel_id) => {
281
                // Read para id from EthereumSystem::channels storage map
282
105
                match EthereumSystem::channels(channel_id) {
283
105
                    Some(x) => x.para_id,
284
                    None => {
285
                        // This should be unreachable, but return para id 0 if channel does not exist
286
                        log::warn!(
287
                            "Got snowbridge message from channel that does not exist: {:?}",
288
                            channel_id
289
                        );
290
                        ParaId::from(0)
291
                    }
292
                }
293
            }
294
        }
295
105
    }
296
}
297

            
298
/// The relay register and deregister calls should no longer be necessary
299
/// Everything is handled by the containerRegistrar
300
pub struct IsRelayRegister;
301
impl Contains<RuntimeCall> for IsRelayRegister {
302
20
    fn contains(c: &RuntimeCall) -> bool {
303
19
        matches!(
304
2
            c,
305
            RuntimeCall::Registrar(paras_registrar::Call::register { .. })
306
18
        ) || matches!(
307
1
            c,
308
            RuntimeCall::Registrar(paras_registrar::Call::deregister { .. })
309
        )
310
20
    }
311
}
312

            
313
/// Dancelight shouold not permit parathread registration for now
314
/// TODO: remove once they are enabled
315
pub struct IsParathreadRegistrar;
316
impl Contains<RuntimeCall> for IsParathreadRegistrar {
317
18
    fn contains(c: &RuntimeCall) -> bool {
318
17
        matches!(
319
1
            c,
320
            RuntimeCall::ContainerRegistrar(pallet_registrar::Call::register_parathread { .. })
321
        )
322
18
    }
323
}
324

            
325
parameter_types! {
326
    pub const Version: RuntimeVersion = VERSION;
327
    pub const SS58Prefix: u8 = 42;
328
}
329

            
330
#[derive_impl(frame_system::config_preludes::RelayChainDefaultConfig)]
331
impl frame_system::Config for Runtime {
332
    type BaseCallFilter = EverythingBut<(IsRelayRegister, IsParathreadRegistrar)>;
333
    type BlockWeights = BlockWeights;
334
    type BlockLength = BlockLength;
335
    type DbWeight = RocksDbWeight;
336
    type Nonce = Nonce;
337
    type Hash = Hash;
338
    type AccountId = AccountId;
339
    type Block = Block;
340
    type BlockHashCount = BlockHashCount;
341
    type Version = Version;
342
    type AccountData = pallet_balances::AccountData<Balance>;
343
    type SystemWeightInfo = weights::frame_system::SubstrateWeight<Runtime>;
344
    type SS58Prefix = SS58Prefix;
345
    type MaxConsumers = frame_support::traits::ConstU32<16>;
346
    type MultiBlockMigrator = MultiBlockMigrations;
347
}
348

            
349
parameter_types! {
350
    pub MaximumSchedulerWeight: Weight = Perbill::from_percent(80) *
351
        BlockWeights::get().max_block;
352
    pub const MaxScheduledPerBlock: u32 = 50;
353
    pub const NoPreimagePostponement: Option<u32> = Some(10);
354
}
355

            
356
/// Used the compare the privilege of an origin inside the scheduler.
357
pub struct OriginPrivilegeCmp;
358

            
359
impl PrivilegeCmp<OriginCaller> for OriginPrivilegeCmp {
360
    fn cmp_privilege(left: &OriginCaller, right: &OriginCaller) -> Option<Ordering> {
361
        if left == right {
362
            return Some(Ordering::Equal);
363
        }
364

            
365
        match (left, right) {
366
            // Root is greater than anything.
367
            (OriginCaller::system(frame_system::RawOrigin::Root), _) => Some(Ordering::Greater),
368
            // For every other origin we don't care, as they are not used for `ScheduleOrigin`.
369
            _ => None,
370
        }
371
    }
372
}
373

            
374
/// Dynamic params that can be adjusted at runtime.
375
#[dynamic_params(RuntimeParameters, pallet_parameters::Parameters::<Runtime>)]
376
pub mod dynamic_params {
377
    use super::*;
378

            
379
    #[dynamic_pallet_params]
380
    #[codec(index = 0)]
381
    pub mod preimage {
382
        use super::*;
383

            
384
        #[codec(index = 0)]
385
        pub static BaseDeposit: Balance = deposit(2, 64);
386

            
387
        #[codec(index = 1)]
388
        pub static ByteDeposit: Balance = deposit(0, 1);
389
    }
390
}
391

            
392
#[cfg(feature = "runtime-benchmarks")]
393
impl Default for RuntimeParameters {
394
    fn default() -> Self {
395
        RuntimeParameters::Preimage(dynamic_params::preimage::Parameters::BaseDeposit(
396
            dynamic_params::preimage::BaseDeposit,
397
            Some(1u32.into()),
398
        ))
399
    }
400
}
401

            
402
/// Defines what origin can modify which dynamic parameters.
403
pub struct DynamicParameterOrigin;
404
impl EnsureOriginWithArg<RuntimeOrigin, RuntimeParametersKey> for DynamicParameterOrigin {
405
    type Success = ();
406

            
407
    fn try_origin(
408
        origin: RuntimeOrigin,
409
        key: &RuntimeParametersKey,
410
    ) -> Result<Self::Success, RuntimeOrigin> {
411
        use crate::RuntimeParametersKey::*;
412

            
413
        match key {
414
            Preimage(_) => frame_system::ensure_root(origin.clone()),
415
        }
416
        .map_err(|_| origin)
417
    }
418

            
419
    #[cfg(feature = "runtime-benchmarks")]
420
    fn try_successful_origin(_key: &RuntimeParametersKey) -> Result<RuntimeOrigin, ()> {
421
        // Provide the origin for the parameter returned by `Default`:
422
        Ok(RuntimeOrigin::root())
423
    }
424
}
425

            
426
impl pallet_scheduler::Config for Runtime {
427
    type RuntimeOrigin = RuntimeOrigin;
428
    type RuntimeEvent = RuntimeEvent;
429
    type PalletsOrigin = OriginCaller;
430
    type RuntimeCall = RuntimeCall;
431
    type MaximumWeight = MaximumSchedulerWeight;
432
    // The goal of having ScheduleOrigin include AuctionAdmin is to allow the auctions track of
433
    // OpenGov to schedule periodic auctions.
434
    type ScheduleOrigin = EitherOf<EnsureRoot<AccountId>, AuctionAdmin>;
435
    type MaxScheduledPerBlock = MaxScheduledPerBlock;
436
    type WeightInfo = weights::pallet_scheduler::SubstrateWeight<Runtime>;
437
    type OriginPrivilegeCmp = OriginPrivilegeCmp;
438
    type Preimages = Preimage;
439
}
440

            
441
parameter_types! {
442
    pub const PreimageHoldReason: RuntimeHoldReason = RuntimeHoldReason::Preimage(pallet_preimage::HoldReason::Preimage);
443
}
444

            
445
impl pallet_preimage::Config for Runtime {
446
    type WeightInfo = weights::pallet_preimage::SubstrateWeight<Runtime>;
447
    type RuntimeEvent = RuntimeEvent;
448
    type Currency = Balances;
449
    type ManagerOrigin = EnsureRoot<AccountId>;
450
    type Consideration = HoldConsideration<
451
        AccountId,
452
        Balances,
453
        PreimageHoldReason,
454
        LinearStoragePrice<
455
            dynamic_params::preimage::BaseDeposit,
456
            dynamic_params::preimage::ByteDeposit,
457
            Balance,
458
        >,
459
    >;
460
}
461

            
462
parameter_types! {
463
    pub const ExpectedBlockTime: Moment = MILLISECS_PER_BLOCK;
464
    pub ReportLongevity: u64 = u64::from(EpochDurationInBlocks::get()) * 10;
465
}
466

            
467
impl pallet_babe::Config for Runtime {
468
    type EpochDuration = EpochDurationInBlocks;
469
    type ExpectedBlockTime = ExpectedBlockTime;
470
    // session module is the trigger
471
    type EpochChangeTrigger = pallet_babe::ExternalTrigger;
472
    type DisabledValidators = Session;
473
    // Not benchmarked in Kusama
474
    type WeightInfo = ();
475
    type MaxAuthorities = MaxAuthorities;
476
    type MaxNominators = ConstU32<0>;
477
    type KeyOwnerProof = sp_session::MembershipProof;
478
    type EquivocationReportSystem =
479
        pallet_babe::EquivocationReportSystem<Self, Offences, Historical, ReportLongevity>;
480
}
481

            
482
parameter_types! {
483
    pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT;
484
    pub const MaxLocks: u32 = 50;
485
    pub const MaxReserves: u32 = 50;
486
}
487

            
488
impl pallet_balances::Config for Runtime {
489
    type Balance = Balance;
490
    type DustRemoval = ();
491
    type RuntimeEvent = RuntimeEvent;
492
    type ExistentialDeposit = ExistentialDeposit;
493
    type AccountStore = System;
494
    type MaxLocks = MaxLocks;
495
    type MaxReserves = MaxReserves;
496
    type ReserveIdentifier = [u8; 8];
497
    type WeightInfo = weights::pallet_balances::SubstrateWeight<Runtime>;
498
    type FreezeIdentifier = ();
499
    type RuntimeHoldReason = RuntimeHoldReason;
500
    type RuntimeFreezeReason = RuntimeFreezeReason;
501
    type MaxFreezes = ConstU32<1>;
502
}
503

            
504
parameter_types! {
505
    pub const TransactionByteFee: Balance = 10 * MILLICENTS;
506
    /// This value increases the priority of `Operational` transactions by adding
507
    /// a "virtual tip" that's equal to the `OperationalFeeMultiplier * final_fee`.
508
    pub const OperationalFeeMultiplier: u8 = 5;
509
}
510

            
511
impl pallet_transaction_payment::Config for Runtime {
512
    type RuntimeEvent = RuntimeEvent;
513
    type OnChargeTransaction = FungibleAdapter<Balances, ToAuthor<Runtime>>;
514
    type OperationalFeeMultiplier = OperationalFeeMultiplier;
515
    type WeightToFee = WeightToFee;
516
    type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;
517
    type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Self>;
518
}
519

            
520
parameter_types! {
521
    pub const MinimumPeriod: u64 = SLOT_DURATION / 2;
522
}
523
impl pallet_timestamp::Config for Runtime {
524
    type Moment = u64;
525
    type OnTimestampSet = Babe;
526
    type MinimumPeriod = MinimumPeriod;
527
    type WeightInfo = weights::pallet_timestamp::SubstrateWeight<Runtime>;
528
}
529

            
530
pub struct RewardPoints;
531

            
532
impl pallet_authorship::EventHandler<AccountId, BlockNumberFor<Runtime>> for RewardPoints {
533
3582
    fn note_author(author: AccountId) {
534
3582
        let whitelisted_validators =
535
3582
            pallet_external_validators::WhitelistedValidatorsActiveEra::<Runtime>::get();
536
3582
        // Do not reward whitelisted validators
537
3582
        if !whitelisted_validators.contains(&author) {
538
220
            ExternalValidatorsRewards::reward_by_ids(vec![(author, 20u32)])
539
3362
        }
540
3582
    }
541
}
542

            
543
impl pallet_authorship::Config for Runtime {
544
    type FindAuthor = pallet_session::FindAccountFromAuthorIndex<Self, Babe>;
545
    type EventHandler = RewardPoints;
546
}
547

            
548
impl_opaque_keys! {
549
    pub struct SessionKeys {
550
        pub grandpa: Grandpa,
551
        pub babe: Babe,
552
        pub para_validator: Initializer,
553
        pub para_assignment: ParaSessionInfo,
554
        pub authority_discovery: AuthorityDiscovery,
555
        pub beefy: Beefy,
556
        pub nimbus: TanssiInitializer,
557
    }
558
}
559

            
560
/// Special `ValidatorIdOf` implementation that is just returning the input as result.
561
pub struct ValidatorIdOf;
562
impl sp_runtime::traits::Convert<AccountId, Option<AccountId>> for ValidatorIdOf {
563
146
    fn convert(a: AccountId) -> Option<AccountId> {
564
146
        Some(a)
565
146
    }
566
}
567

            
568
impl pallet_session::Config for Runtime {
569
    type RuntimeEvent = RuntimeEvent;
570
    type ValidatorId = AccountId;
571
    type ValidatorIdOf = ValidatorIdOf;
572
    type ShouldEndSession = Babe;
573
    type NextSessionRotation = Babe;
574
    type SessionManager = pallet_session::historical::NoteHistoricalRoot<Self, ExternalValidators>;
575
    type SessionHandler = <SessionKeys as OpaqueKeys>::KeyTypeIdProviders;
576
    type Keys = SessionKeys;
577
    // TODO: Current benchmarking code for pallet_session requires that the runtime
578
    // uses pallet_staking, which we don't use. We need to make a PR to Substrate to
579
    // allow decoupling the benchmark from other pallets.
580
    // See https://github.com/paritytech/polkadot-sdk/blob/0845044454c005b577eab7afaea18583bd7e3dd3/substrate/frame/session/benchmarking/src/inner.rs#L38
581
    type WeightInfo = ();
582
}
583

            
584
pub struct FullIdentificationOf;
585
impl Convert<AccountId, Option<()>> for FullIdentificationOf {
586
755
    fn convert(_: AccountId) -> Option<()> {
587
755
        Some(())
588
755
    }
589
}
590

            
591
impl pallet_session::historical::Config for Runtime {
592
    type FullIdentification = ();
593
    type FullIdentificationOf = FullIdentificationOf;
594
}
595

            
596
parameter_types! {
597
    pub const BondingDuration: sp_staking::EraIndex = runtime_common::prod_or_fast!(28, 3);
598
}
599

            
600
parameter_types! {
601
    pub const ProposalBond: Permill = Permill::from_percent(5);
602
    pub const ProposalBondMinimum: Balance = 2000 * CENTS;
603
    pub const ProposalBondMaximum: Balance = 1 * GRAND;
604
    // We allow it to be 1 minute in fast mode to be able to test it
605
    pub const SpendPeriod: BlockNumber = runtime_common::prod_or_fast!(6 * DAYS, 1 * MINUTES);
606
    pub const Burn: Permill = Permill::from_perthousand(2);
607
    pub const TreasuryPalletId: PalletId = PalletId(*b"py/trsry");
608
    pub const PayoutSpendPeriod: BlockNumber = 30 * DAYS;
609
    // The asset's interior location for the paying account. This is the Treasury
610
    // pallet instance (which sits at index 18).
611
    pub TreasuryInteriorLocation: InteriorLocation = PalletInstance(18).into();
612

            
613
    pub const TipCountdown: BlockNumber = 1 * DAYS;
614
    pub const TipFindersFee: Percent = Percent::from_percent(20);
615
    pub const TipReportDepositBase: Balance = 100 * CENTS;
616
    pub const DataDepositPerByte: Balance = 1 * CENTS;
617
    pub const MaxApprovals: u32 = 100;
618
    pub const MaxAuthorities: u32 = 100_000;
619
    pub const MaxKeys: u32 = 10_000;
620
    pub const MaxPeerInHeartbeats: u32 = 10_000;
621
    pub const MaxBalance: Balance = Balance::max_value();
622
    pub TreasuryAccount: AccountId = Treasury::account_id();
623
}
624

            
625
#[cfg(feature = "runtime-benchmarks")]
626
pub struct TreasuryBenchmarkHelper<T>(PhantomData<T>);
627

            
628
#[cfg(feature = "runtime-benchmarks")]
629
use frame_support::traits::Currency;
630
use frame_support::traits::{
631
    ExistenceRequirement, OnUnbalanced, ValidatorRegistration, WithdrawReasons,
632
};
633
use pallet_services_payment::BalanceOf;
634
#[cfg(feature = "runtime-benchmarks")]
635
use pallet_treasury::ArgumentsFactory;
636
use runtime_parachains::configuration::HostConfiguration;
637
use sp_runtime::{DispatchError, TransactionOutcome};
638

            
639
#[cfg(feature = "runtime-benchmarks")]
640
impl<T> ArgumentsFactory<(), T::AccountId> for TreasuryBenchmarkHelper<T>
641
where
642
    T: pallet_treasury::Config,
643
    T::AccountId: From<[u8; 32]>,
644
{
645
    fn create_asset_kind(_seed: u32) {}
646

            
647
    fn create_beneficiary(seed: [u8; 32]) -> T::AccountId {
648
        let account: T::AccountId = seed.into();
649
        let balance = T::Currency::minimum_balance();
650
        let _ = T::Currency::make_free_balance_be(&account, balance);
651
        account
652
    }
653
}
654

            
655
impl pallet_treasury::Config for Runtime {
656
    type PalletId = TreasuryPalletId;
657
    type Currency = Balances;
658
    type RejectOrigin = EitherOfDiverse<EnsureRoot<AccountId>, Treasurer>;
659
    type RuntimeEvent = RuntimeEvent;
660
    type SpendPeriod = SpendPeriod;
661
    type Burn = Burn;
662
    type BurnDestination = ();
663
    type MaxApprovals = MaxApprovals;
664
    type WeightInfo = weights::pallet_treasury::SubstrateWeight<Runtime>;
665
    type SpendFunds = ();
666
    type SpendOrigin = TreasurySpender;
667
    type AssetKind = ();
668
    type Beneficiary = AccountId;
669
    type BeneficiaryLookup = IdentityLookup<Self::Beneficiary>;
670
    type Paymaster = PayFromAccount<Balances, TreasuryAccount>;
671
    type BalanceConverter = UnityAssetBalanceConversion;
672
    type PayoutPeriod = PayoutSpendPeriod;
673
    #[cfg(feature = "runtime-benchmarks")]
674
    type BenchmarkHelper = TreasuryBenchmarkHelper<Runtime>;
675
}
676

            
677
impl pallet_offences::Config for Runtime {
678
    type RuntimeEvent = RuntimeEvent;
679
    type IdentificationTuple = pallet_session::historical::IdentificationTuple<Self>;
680
    type OnOffenceHandler = ExternalValidatorSlashes;
681
}
682

            
683
impl pallet_authority_discovery::Config for Runtime {
684
    type MaxAuthorities = MaxAuthorities;
685
}
686

            
687
parameter_types! {
688
    pub const MaxSetIdSessionEntries: u32 = BondingDuration::get() * SessionsPerEra::get();
689
}
690

            
691
impl pallet_grandpa::Config for Runtime {
692
    type RuntimeEvent = RuntimeEvent;
693
    // Not benchmarked in Kusama, benchmarking code also don't match WeightInfo trait.
694
    type WeightInfo = ();
695
    type MaxAuthorities = MaxAuthorities;
696
    type MaxNominators = ConstU32<0>;
697
    type MaxSetIdSessionEntries = MaxSetIdSessionEntries;
698
    type KeyOwnerProof = sp_session::MembershipProof;
699
    type EquivocationReportSystem =
700
        pallet_grandpa::EquivocationReportSystem<Self, Offences, Historical, ReportLongevity>;
701
}
702

            
703
/// Submits a transaction with the node's public and signature type. Adheres to the signed extension
704
/// format of the chain.
705
impl<LocalCall> frame_system::offchain::CreateSignedTransaction<LocalCall> for Runtime
706
where
707
    RuntimeCall: From<LocalCall>,
708
{
709
    fn create_transaction<C: frame_system::offchain::AppCrypto<Self::Public, Self::Signature>>(
710
        call: RuntimeCall,
711
        public: <Signature as Verify>::Signer,
712
        account: AccountId,
713
        nonce: <Runtime as frame_system::Config>::Nonce,
714
    ) -> Option<(
715
        RuntimeCall,
716
        <UncheckedExtrinsic as ExtrinsicT>::SignaturePayload,
717
    )> {
718
        use sp_runtime::traits::StaticLookup;
719
        // take the biggest period possible.
720
        let period = u64::from(
721
            BlockHashCount::get()
722
                .checked_next_power_of_two()
723
                .map(|c| c / 2)
724
                .unwrap_or(2),
725
        );
726

            
727
        let current_block = System::block_number()
728
            .saturated_into::<u64>()
729
            // The `System::block_number` is initialized with `n+1`,
730
            // so the actual block number is `n`.
731
            .saturating_sub(1);
732
        let tip = 0;
733
        let extra: SignedExtra = (
734
            frame_system::CheckNonZeroSender::<Runtime>::new(),
735
            frame_system::CheckSpecVersion::<Runtime>::new(),
736
            frame_system::CheckTxVersion::<Runtime>::new(),
737
            frame_system::CheckGenesis::<Runtime>::new(),
738
            frame_system::CheckMortality::<Runtime>::from(generic::Era::mortal(
739
                period,
740
                current_block,
741
            )),
742
            frame_system::CheckNonce::<Runtime>::from(nonce),
743
            frame_system::CheckWeight::<Runtime>::new(),
744
            pallet_transaction_payment::ChargeTransactionPayment::<Runtime>::from(tip),
745
            frame_metadata_hash_extension::CheckMetadataHash::<Runtime>::new(false),
746
        );
747
        let raw_payload = SignedPayload::new(call, extra)
748
            .map_err(|e| {
749
                log::warn!("Unable to create signed payload: {:?}", e);
750
            })
751
            .ok()?;
752
        let signature = raw_payload.using_encoded(|payload| C::sign(payload, public))?;
753
        let (call, extra, _) = raw_payload.deconstruct();
754
        let address = <Runtime as frame_system::Config>::Lookup::unlookup(account);
755
        Some((call, (address, signature, extra)))
756
    }
757
}
758

            
759
impl frame_system::offchain::SigningTypes for Runtime {
760
    type Public = <Signature as Verify>::Signer;
761
    type Signature = Signature;
762
}
763

            
764
impl<C> frame_system::offchain::SendTransactionTypes<C> for Runtime
765
where
766
    RuntimeCall: From<C>,
767
{
768
    type Extrinsic = UncheckedExtrinsic;
769
    type OverarchingCall = RuntimeCall;
770
}
771

            
772
parameter_types! {
773
    // Minimum 100 bytes/STAR deposited (1 CENT/byte)
774
    pub const BasicDeposit: Balance = 1000 * CENTS;       // 258 bytes on-chain
775
    pub const ByteDeposit: Balance = deposit(0, 1);
776
    pub const SubAccountDeposit: Balance = 200 * CENTS;   // 53 bytes on-chain
777
    pub const MaxSubAccounts: u32 = 100;
778
    pub const MaxAdditionalFields: u32 = 100;
779
    pub const MaxRegistrars: u32 = 20;
780
}
781

            
782
impl pallet_identity::Config for Runtime {
783
    type RuntimeEvent = RuntimeEvent;
784
    type Currency = Balances;
785
    type BasicDeposit = BasicDeposit;
786
    type ByteDeposit = ByteDeposit;
787
    type SubAccountDeposit = SubAccountDeposit;
788
    type MaxSubAccounts = MaxSubAccounts;
789
    type IdentityInformation = IdentityInfo<MaxAdditionalFields>;
790
    type MaxRegistrars = MaxRegistrars;
791
    type Slashed = Treasury;
792
    type ForceOrigin = EitherOf<EnsureRoot<Self::AccountId>, GeneralAdmin>;
793
    type RegistrarOrigin = EitherOf<EnsureRoot<Self::AccountId>, GeneralAdmin>;
794
    type OffchainSignature = Signature;
795
    type SigningPublicKey = <Signature as Verify>::Signer;
796
    type UsernameAuthorityOrigin = EnsureRoot<Self::AccountId>;
797
    type PendingUsernameExpiration = ConstU32<{ 7 * DAYS }>;
798
    type MaxSuffixLength = ConstU32<7>;
799
    type MaxUsernameLength = ConstU32<32>;
800
    type WeightInfo = weights::pallet_identity::SubstrateWeight<Runtime>;
801
}
802

            
803
impl pallet_utility::Config for Runtime {
804
    type RuntimeEvent = RuntimeEvent;
805
    type RuntimeCall = RuntimeCall;
806
    type PalletsOrigin = OriginCaller;
807
    type WeightInfo = weights::pallet_utility::SubstrateWeight<Runtime>;
808
}
809

            
810
parameter_types! {
811
    // One storage item; key size is 32; value is size 4+4+16+32 bytes = 56 bytes.
812
    pub const DepositBase: Balance = deposit(1, 88);
813
    // Additional storage item size of 32 bytes.
814
    pub const DepositFactor: Balance = deposit(0, 32);
815
    pub const MaxSignatories: u32 = 100;
816
}
817

            
818
impl pallet_multisig::Config for Runtime {
819
    type RuntimeEvent = RuntimeEvent;
820
    type RuntimeCall = RuntimeCall;
821
    type Currency = Balances;
822
    type DepositBase = DepositBase;
823
    type DepositFactor = DepositFactor;
824
    type MaxSignatories = MaxSignatories;
825
    type WeightInfo = weights::pallet_multisig::SubstrateWeight<Runtime>;
826
}
827

            
828
parameter_types! {
829
    // One storage item; key size 32, value size 8; .
830
    pub const ProxyDepositBase: Balance = deposit(1, 8);
831
    // Additional storage item size of 33 bytes.
832
    pub const ProxyDepositFactor: Balance = deposit(0, 33);
833
    pub const MaxProxies: u16 = 32;
834
    pub const AnnouncementDepositBase: Balance = deposit(1, 8);
835
    pub const AnnouncementDepositFactor: Balance = deposit(0, 66);
836
    pub const MaxPending: u16 = 32;
837
}
838

            
839
/// The type used to represent the kinds of proxying allowed.
840
#[derive(
841
    Copy,
842
    Clone,
843
    Eq,
844
    PartialEq,
845
    Ord,
846
    PartialOrd,
847
    Encode,
848
    Decode,
849
    RuntimeDebug,
850
    MaxEncodedLen,
851
    TypeInfo,
852
)]
853
pub enum ProxyType {
854
    Any,
855
    NonTransfer,
856
    Governance,
857
    IdentityJudgement,
858
    CancelProxy,
859
    Auction,
860
    OnDemandOrdering,
861
    SudoRegistrar,
862
    SudoValidatorManagement,
863
    SessionKeyManagement,
864
    Staking,
865
}
866
impl Default for ProxyType {
867
    fn default() -> Self {
868
        Self::Any
869
    }
870
}
871
impl InstanceFilter<RuntimeCall> for ProxyType {
872
    fn filter(&self, c: &RuntimeCall) -> bool {
873
        match self {
874
            ProxyType::Any => true,
875
            ProxyType::NonTransfer => matches!(
876
                c,
877
                RuntimeCall::System(..) |
878
				RuntimeCall::Babe(..) |
879
				RuntimeCall::Timestamp(..) |
880
				// Specifically omitting Indices `transfer`, `force_transfer`
881
				// Specifically omitting the entire Balances pallet
882
				RuntimeCall::Session(..) |
883
				RuntimeCall::Grandpa(..) |
884
				RuntimeCall::Treasury(..) |
885
				RuntimeCall::ConvictionVoting(..) |
886
				RuntimeCall::Referenda(..) |
887
				RuntimeCall::FellowshipCollective(..) |
888
				RuntimeCall::FellowshipReferenda(..) |
889
				RuntimeCall::Whitelist(..) |
890
				RuntimeCall::Utility(..) |
891
				RuntimeCall::Identity(..) |
892
				RuntimeCall::Scheduler(..) |
893
				RuntimeCall::Proxy(..) |
894
				RuntimeCall::Multisig(..) |
895
				RuntimeCall::Registrar(paras_registrar::Call::register {..}) |
896
				RuntimeCall::Registrar(paras_registrar::Call::deregister {..}) |
897
				// Specifically omitting Registrar `swap`
898
				RuntimeCall::Registrar(paras_registrar::Call::reserve {..})
899
            ),
900
            ProxyType::Governance => matches!(
901
                c,
902
                RuntimeCall::Utility(..) |
903
					// OpenGov calls
904
					RuntimeCall::ConvictionVoting(..) |
905
					RuntimeCall::Referenda(..) |
906
					RuntimeCall::FellowshipCollective(..) |
907
					RuntimeCall::FellowshipReferenda(..) |
908
					RuntimeCall::Whitelist(..)
909
            ),
910
            ProxyType::IdentityJudgement => matches!(
911
                c,
912
                RuntimeCall::Identity(pallet_identity::Call::provide_judgement { .. })
913
                    | RuntimeCall::Utility(..)
914
            ),
915
            ProxyType::CancelProxy => {
916
                matches!(
917
                    c,
918
                    RuntimeCall::Proxy(pallet_proxy::Call::reject_announcement { .. })
919
                )
920
            }
921
            ProxyType::Auction => {
922
                matches!(c, RuntimeCall::Registrar { .. } | RuntimeCall::Multisig(..))
923
            }
924
            ProxyType::OnDemandOrdering => matches!(c, RuntimeCall::OnDemandAssignmentProvider(..)),
925
            ProxyType::SudoRegistrar => match c {
926
                RuntimeCall::Sudo(pallet_sudo::Call::sudo { call: ref x }) => {
927
                    matches!(
928
                        x.as_ref(),
929
                        &RuntimeCall::DataPreservers(..)
930
                            | &RuntimeCall::Registrar(..)
931
                            | &RuntimeCall::ContainerRegistrar(..)
932
                            | &RuntimeCall::Paras(..)
933
                            | &RuntimeCall::ParasSudoWrapper(..)
934
                    )
935
                }
936
                _ => false,
937
            },
938
            ProxyType::SudoValidatorManagement => match c {
939
                RuntimeCall::Sudo(pallet_sudo::Call::sudo { call: ref x }) => {
940
                    matches!(
941
                        x.as_ref(),
942
                        &RuntimeCall::ExternalValidators(..)
943
                            | &RuntimeCall::ExternalValidatorSlashes(..)
944
                    )
945
                }
946
                _ => false,
947
            },
948
            ProxyType::SessionKeyManagement => {
949
                matches!(c, RuntimeCall::Session(..))
950
            }
951
            ProxyType::Staking => {
952
                matches!(c, RuntimeCall::Session(..) | RuntimeCall::PooledStaking(..))
953
            }
954
        }
955
    }
956
    fn is_superset(&self, o: &Self) -> bool {
957
        match (self, o) {
958
            (x, y) if x == y => true,
959
            (ProxyType::Any, _) => true,
960
            (_, ProxyType::Any) => false,
961
            (ProxyType::NonTransfer, _) => true,
962
            _ => false,
963
        }
964
    }
965
}
966

            
967
impl pallet_proxy::Config for Runtime {
968
    type RuntimeEvent = RuntimeEvent;
969
    type RuntimeCall = RuntimeCall;
970
    type Currency = Balances;
971
    type ProxyType = ProxyType;
972
    type ProxyDepositBase = ProxyDepositBase;
973
    type ProxyDepositFactor = ProxyDepositFactor;
974
    type MaxProxies = MaxProxies;
975
    type WeightInfo = weights::pallet_proxy::SubstrateWeight<Runtime>;
976
    type MaxPending = MaxPending;
977
    type CallHasher = BlakeTwo256;
978
    type AnnouncementDepositBase = AnnouncementDepositBase;
979
    type AnnouncementDepositFactor = AnnouncementDepositFactor;
980
}
981

            
982
impl parachains_origin::Config for Runtime {}
983

            
984
impl parachains_configuration::Config for Runtime {
985
    type WeightInfo = weights::runtime_parachains_configuration::SubstrateWeight<Runtime>;
986
}
987

            
988
impl parachains_shared::Config for Runtime {
989
    type DisabledValidators = Session;
990
}
991

            
992
impl parachains_session_info::Config for Runtime {
993
    type ValidatorSet = Historical;
994
}
995

            
996
pub type RewardValidators =
997
    pallet_external_validators_rewards::RewardValidatorsWithEraPoints<Runtime>;
998

            
999
impl parachains_inclusion::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type DisputesHandler = ParasDisputes;
    type RewardValidators = RewardValidators;
    type AggregateMessageOrigin = AggregateMessageOrigin;
    type GetAggregateMessageOrigin = GetAggregateMessageOrigin;
    type GetParaFromAggregateMessageOrigin = GetParaFromAggregateMessageOrigin;
    type MessageQueue = MessageQueue;
    type WeightInfo = weights::runtime_parachains_inclusion::SubstrateWeight<Runtime>;
}
parameter_types! {
    pub const ParasUnsignedPriority: TransactionPriority = TransactionPriority::max_value();
}
impl parachains_paras::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type WeightInfo = weights::runtime_parachains_paras::SubstrateWeight<Runtime>;
    type UnsignedPriority = ParasUnsignedPriority;
    type QueueFootprinter = ParaInclusion;
    type NextSessionRotation = Babe;
    type OnNewHead = Registrar;
    type AssignCoretime = ();
}
parameter_types! {
    /// Amount of weight that can be spent per block to service messages.
    ///
    /// # WARNING
    ///
    /// This is not a good value for para-chains since the `Scheduler` already uses up to 80% block weight.
    pub MessageQueueServiceWeight: Weight = Perbill::from_percent(20) * BlockWeights::get().max_block;
    pub const MessageQueueHeapSize: u32 = 32 * 1024;
    pub const MessageQueueMaxStale: u32 = 96;
}
/// Message processor to handle any messages that were enqueued into the `MessageQueue` pallet.
pub struct MessageProcessor;
impl ProcessMessage for MessageProcessor {
    type Origin = AggregateMessageOrigin;
54
    fn process_message(
54
        message: &[u8],
54
        origin: Self::Origin,
54
        meter: &mut WeightMeter,
54
        id: &mut [u8; 32],
54
    ) -> Result<bool, ProcessMessageError> {
54
        match origin {
            AggregateMessageOrigin::Ump(UmpQueueId::Para(para)) => {
                xcm_builder::ProcessXcmMessage::<
                    Junction,
                    xcm_executor::XcmExecutor<xcm_config::XcmConfig>,
                    RuntimeCall,
                >::process_message(
                    message, Junction::Parachain(para.into()), meter, id
                )
            }
            AggregateMessageOrigin::Snowbridge(_) => {
10
                snowbridge_pallet_outbound_queue::Pallet::<Runtime>::process_message(
10
                    message, origin, meter, id,
10
                )
            }
            AggregateMessageOrigin::SnowbridgeTanssi(_) => {
44
                tp_bridge::CustomProcessSnowbridgeMessage::<Runtime>::process_message(
44
                    message, origin, meter, id,
44
                )
            }
        }
54
    }
}
impl pallet_message_queue::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type Size = u32;
    type HeapSize = MessageQueueHeapSize;
    type MaxStale = MessageQueueMaxStale;
    type ServiceWeight = MessageQueueServiceWeight;
    type IdleMaxServiceWeight = MessageQueueServiceWeight;
    #[cfg(not(feature = "runtime-benchmarks"))]
    type MessageProcessor = MessageProcessor;
    #[cfg(feature = "runtime-benchmarks")]
    type MessageProcessor =
        pallet_message_queue::mock_helpers::NoopMessageProcessor<AggregateMessageOrigin>;
    type QueueChangeHandler = ParaInclusion;
    type QueuePausedQuery = ();
    type WeightInfo = weights::pallet_message_queue::SubstrateWeight<Runtime>;
}
impl parachains_dmp::Config for Runtime {}
parameter_types! {
    pub const HrmpChannelSizeAndCapacityWithSystemRatio: Percent = Percent::from_percent(100);
}
impl parachains_hrmp::Config for Runtime {
    type RuntimeOrigin = RuntimeOrigin;
    type RuntimeEvent = RuntimeEvent;
    type ChannelManager = EnsureRoot<AccountId>;
    type Currency = Balances;
    type DefaultChannelSizeAndCapacityWithSystem =
        parachains_configuration::ActiveConfigHrmpChannelSizeAndCapacityRatio<
            Runtime,
            HrmpChannelSizeAndCapacityWithSystemRatio,
        >;
    type WeightInfo = weights::runtime_parachains_hrmp::SubstrateWeight<Runtime>;
    type VersionWrapper = XcmPallet;
}
impl parachains_paras_inherent::Config for Runtime {
    type WeightInfo = weights::runtime_parachains_paras_inherent::SubstrateWeight<Runtime>;
}
impl parachains_scheduler::Config for Runtime {
    // If you change this, make sure the `Assignment` type of the new provider is binary compatible,
    // otherwise provide a migration.
    type AssignmentProvider = CollatorAssignmentProvider;
}
pub struct CollatorAssignmentProvider;
impl parachains_scheduler::common::AssignmentProvider<BlockNumberFor<Runtime>>
    for CollatorAssignmentProvider
{
18
    fn pop_assignment_for_core(core_idx: CoreIndex) -> Option<Assignment> {
18
        let assigned_collators = TanssiCollatorAssignment::collator_container_chain();
18
        let assigned_paras: Vec<ParaId> = assigned_collators
18
            .container_chains
18
            .iter()
18
            .filter_map(|(&para_id, collators)| {
18
                if Paras::is_parachain(para_id) && collators.len() > 0 {
6
                    Some(para_id)
                } else {
12
                    None
                }
18
            })
18
            .collect();
18
        log::debug!("pop assigned collators {:?}", assigned_paras);
18
        log::debug!("looking for core idx {:?}", core_idx);
18
        if let Some(para_id) = assigned_paras.get(core_idx.0 as usize) {
3
            log::debug!("outputing assignment for  {:?}", para_id);
3
            Some(Assignment::Bulk(*para_id))
        } else {
            // We dont want to assign affinity to a parathread that has not collators assigned
            // Even if we did they would need their own collators to produce blocks, but for now
            // I prefer to forbid.
            // In this case the parathread would have bought the core for nothing
6
            let assignment =
15
                parachains_assigner_on_demand::Pallet::<Runtime>::pop_assignment_for_core(
15
                    core_idx,
15
                )?;
            // Let's check that we have collators before allowing an assignment
6
            if assigned_collators
6
                .container_chains
6
                .get(&assignment.para_id())
6
                .unwrap_or(&vec![])
6
                .len()
6
                > 0
            {
5
                Some(assignment)
            } else {
1
                None
            }
        }
18
    }
    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)
    }
432
    fn session_core_count() -> u32 {
432
        let config = runtime_parachains::configuration::ActiveConfig::<Runtime>::get();
432
        log::debug!(
            "session core count is {:?}",
            config.scheduler_params.num_cores
        );
432
        config.scheduler_params.num_cores
432
    }
}
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;
    // There are currently no benchmarks for pallet_beefy.
    // https://github.com/paritytech/polkadot-sdk/tree/master/substrate/frame/beefy/src
    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 = weights::pallet_mmr::SubstrateWeight<Runtime>;
    type LeafData = pallet_beefy_mmr::Pallet<Runtime>;
    type BlockHashProvider = pallet_mmr::DefaultBlockHashProvider<Runtime>;
    #[cfg(feature = "runtime-benchmarks")]
    type BenchmarkHelper = ();
}
parameter_types! {
    pub LeafVersion: MmrLeafVersion = MmrLeafVersion::new(0, 0);
}
#[derive(Debug, PartialEq, Eq, Clone, Encode, Decode)]
pub struct LeafExtraData {
    para_heads_root: H256,
    commitment_root: H256,
}
pub struct LeafExtraDataProvider;
impl BeefyDataProvider<LeafExtraData> for LeafExtraDataProvider {
3578
    fn extra_data() -> LeafExtraData {
3578
        let mut para_heads: Vec<(u32, Vec<u8>)> = parachains_paras::Parachains::<Runtime>::get()
3578
            .into_iter()
3578
            .filter_map(|id| {
2989
                parachains_paras::Heads::<Runtime>::get(id).map(|head| (id.into(), head.0))
3578
            })
3578
            .collect();
3578
        para_heads.sort();
3578
        let para_heads_root = binary_merkle_tree::merkle_root::<mmr::Hashing, _>(
3578
            para_heads.into_iter().map(|pair| pair.encode()),
3578
        );
3578

            
3578
        let commitment_root =
3578
            OutboundMessageCommitmentRecorder::take_commitment_root().unwrap_or_default();
3578

            
3578
        LeafExtraData {
3578
            para_heads_root,
3578
            commitment_root,
3578
        }
3578
    }
}
impl pallet_beefy_mmr::Config for Runtime {
    type LeafVersion = LeafVersion;
    type BeefyAuthorityToMerkleLeaf = pallet_beefy_mmr::BeefyEcdsaToEthereum;
    type LeafExtra = LeafExtraData;
    type BeefyDataProvider = LeafExtraDataProvider;
    type WeightInfo = weights::pallet_beefy_mmr::SubstrateWeight<Runtime>;
}
impl paras_sudo_wrapper::Config for Runtime {}
use pallet_pooled_staking::traits::{IsCandidateEligible, Timer};
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()
    }
7
    fn prune_historical_up_to(up_to: SessionIndex) {
7
        Historical::prune_up_to(up_to);
7
    }
}
parameter_types! {
    pub const SessionsPerEra: SessionIndex = runtime_common::prod_or_fast!(6, 3);
    pub const SlashDeferDuration: EraIndex = runtime_common::prod_or_fast!(0, 0);
}
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 = ExternalValidatorsRewards;
    type WeightInfo = weights::pallet_external_validators::SubstrateWeight<Runtime>;
    #[cfg(feature = "runtime-benchmarks")]
    type Currency = Balances;
}
pub struct TimestampProvider;
impl Get<u64> for TimestampProvider {
    fn get() -> u64 {
        Timestamp::get()
    }
}
parameter_types! {
    // Chain ID of Holesky.
    // Output is: 34cdd3f84040fb44d70e83b892797846a8c0a556ce08cd470bf6d4cf7b94ff77
    pub EthereumSovereignAccount: AccountId =
        tp_bridge::EthereumLocationsConverterFor::<AccountId>::convert_location(
            &EthereumLocation::get()
        ).expect("to convert EthereumSovereignAccount");
    // TODO: Use a potentially different formula/inflation rate. We need the output to be non-zero
    // to properly write integration tests.
    pub ExternalRewardsEraInflationProvider: u128 = InflationRate::get() * Balances::total_issuance();
    pub TokenLocationReanchored: Location = xcm_config::TokenLocation::get().reanchored(
        &EthereumLocation::get(),
        &xcm_config::UniversalLocation::get()
    ).expect("unable to reanchor reward token");
}
pub struct GetWhitelistedValidators;
impl Get<Vec<AccountId>> for GetWhitelistedValidators {
9
    fn get() -> Vec<AccountId> {
9
        pallet_external_validators::WhitelistedValidatorsActiveEra::<Runtime>::get().into()
9
    }
}
#[cfg(feature = "runtime-benchmarks")]
pub struct RewardsBenchHelper;
#[cfg(feature = "runtime-benchmarks")]
impl tp_bridge::TokenChannelSetterBenchmarkHelperTrait for RewardsBenchHelper {
    fn set_up_token(location: Location, token_id: TokenId) {
        snowbridge_pallet_system::ForeignToNativeId::<Runtime>::insert(&token_id, &location);
        snowbridge_pallet_system::NativeToForeignId::<Runtime>::insert(&location, &token_id);
    }
    fn set_up_channel(_channel_id: ChannelId, _para_id: ParaId, _agent_id: AgentId) {}
}
impl pallet_external_validators_rewards::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type EraIndexProvider = ExternalValidators;
    type HistoryDepth = ConstU32<64>;
    type BackingPoints = ConstU32<20>;
    type DisputeStatementPoints = ConstU32<20>;
    // TODO: add a proper way to retrieve the inflated tokens.
    // Will likely be through InflationRewards.
    type EraInflationProvider = ExternalRewardsEraInflationProvider;
    type ExternalIndexProvider = ExternalValidators;
    type GetWhitelistedValidators = GetWhitelistedValidators;
    type Hashing = Keccak256;
    type ValidateMessage = tp_bridge::MessageValidator<Runtime>;
    type OutboundQueue = tp_bridge::CustomSendMessage<Runtime, GetAggregateMessageOriginTanssi>;
    type Currency = Balances;
    type RewardsEthereumSovereignAccount = EthereumSovereignAccount;
    type TokenLocationReanchored = TokenLocationReanchored;
    type TokenIdFromLocation = EthereumSystem;
    type WeightInfo = weights::pallet_external_validators_rewards::SubstrateWeight<Runtime>;
    #[cfg(feature = "runtime-benchmarks")]
    type BenchmarkHelper = RewardsBenchHelper;
}
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 ValidateMessage = tp_bridge::MessageValidator<Runtime>;
    type OutboundQueue = tp_bridge::CustomSendMessage<Runtime, GetAggregateMessageOriginTanssi>;
    type ExternalIndexProvider = ExternalValidators;
    type QueuedSlashesProcessedPerBlock = ConstU32<10>;
    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 = weights::pallet_invulnerables::SubstrateWeight<Runtime>;
    #[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 = weights::pallet_configuration::SubstrateWeight<Runtime>;
}
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 = weights::pallet_multiblock_migrations::SubstrateWeight<Runtime>;
}
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> {
756
    fn block_cost(_para_id: &ParaId) -> (u128, Weight) {
756
        (FIXED_BLOCK_PRODUCTION_COST, Weight::zero())
756
    }
}
pub struct CollatorAssignmentCost<Runtime>(PhantomData<Runtime>);
impl ProvideCollatorAssignmentCost<Runtime> for CollatorAssignmentCost<Runtime> {
19
    fn collator_assignment_cost(_para_id: &ParaId) -> (u128, Weight) {
19
        (FIXED_COLLATOR_ASSIGNMENT_COST, Weight::zero())
19
    }
}
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 successful 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 = weights::pallet_data_preservers::SubstrateWeight<Runtime>;
    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 {
1455
    fn on_nonzero_unbalanced(credit: Credit<AccountId, Balances>) {
1455
        let _ = <Balances as Balanced<_>>::resolve(&DancelightBondAccount::get(), credit);
1455
    }
}
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, PooledStaking>;
    type RewardsPortion = RewardsPortion;
}
parameter_types! {
    pub StakingAccount: AccountId32 = PalletId(*b"POOLSTAK").into_account_truncating();
    pub const InitialManualClaimShareValue: u128 = MILLIUNITS;
    pub const InitialAutoCompoundingShareValue: u128 = MILLIUNITS;
    pub const MinimumSelfDelegation: u128 = 10_000 * UNITS;
    pub const RewardsCollatorCommission: Perbill = Perbill::from_percent(20);
    // Need to wait 2 sessions before being able to join or leave staking pools
    pub const StakingSessionDelay: u32 = 2;
}
pub struct SessionTimer<Delay>(PhantomData<Delay>);
impl<Delay> Timer for SessionTimer<Delay>
where
    Delay: Get<u32>,
{
    type Instant = u32;
47
    fn now() -> Self::Instant {
47
        Session::current_index()
47
    }
16
    fn is_elapsed(instant: &Self::Instant) -> bool {
16
        let delay = Delay::get();
16
        let Some(end) = instant.checked_add(delay) else {
            return false;
        };
16
        end <= Self::now()
16
    }
    #[cfg(feature = "runtime-benchmarks")]
    fn elapsed_instant() -> Self::Instant {
        let delay = Delay::get();
        Self::now()
            .checked_add(delay)
            .expect("overflow when computing valid elapsed instant")
    }
    #[cfg(feature = "runtime-benchmarks")]
    fn skip_to_elapsed() {
        let session_to_reach = Self::elapsed_instant();
        while Self::now() < session_to_reach {
            Session::rotate_session();
        }
    }
}
pub struct CandidateHasRegisteredKeys;
impl IsCandidateEligible<AccountId> for CandidateHasRegisteredKeys {
24
    fn is_candidate_eligible(a: &AccountId) -> bool {
24
        <Session as ValidatorRegistration<AccountId>>::is_registered(a)
24
    }
    #[cfg(feature = "runtime-benchmarks")]
    fn make_candidate_eligible(a: &AccountId, eligible: bool) {
        use crate::genesis_config_presets::get_authority_keys_from_seed;
        if eligible {
            let a_u8: &[u8] = a.as_ref();
            let seed = sp_runtime::format!("{:?}", a_u8);
            let authority_keys = get_authority_keys_from_seed(&seed, None);
            let _ = Session::set_keys(
                RuntimeOrigin::signed(a.clone()),
                SessionKeys {
                    grandpa: authority_keys.grandpa,
                    babe: authority_keys.babe,
                    para_validator: authority_keys.para_validator,
                    para_assignment: authority_keys.para_assignment,
                    authority_discovery: authority_keys.authority_discovery,
                    beefy: authority_keys.beefy,
                    nimbus: authority_keys.nimbus,
                },
                vec![],
            );
        } else {
            let _ = Session::purge_keys(RuntimeOrigin::signed(a.clone()));
        }
    }
}
impl pallet_pooled_staking::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type Currency = Balances;
    type Balance = Balance;
    type StakingAccount = StakingAccount;
    type InitialManualClaimShareValue = InitialManualClaimShareValue;
    type InitialAutoCompoundingShareValue = InitialAutoCompoundingShareValue;
    type MinimumSelfDelegation = MinimumSelfDelegation;
    type RuntimeHoldReason = RuntimeHoldReason;
    type RewardsCollatorCommission = RewardsCollatorCommission;
    type JoiningRequestTimer = SessionTimer<StakingSessionDelay>;
    type LeavingRequestTimer = SessionTimer<StakingSessionDelay>;
    type EligibleCandidatesBufferSize = ConstU32<100>;
    type EligibleCandidatesFilter = CandidateHasRegisteredKeys;
    type WeightInfo = weights::pallet_pooled_staking::SubstrateWeight<Runtime>;
}
656866
construct_runtime! {
18811
    pub enum Runtime
18811
    {
18811
        // Basic stuff; balances is uncallable initially.
18811
        System: frame_system = 0,
18811

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

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

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

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

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

            
18811
        // Bridging stuff - 1
18811
        EthereumOutboundQueue: snowbridge_pallet_outbound_queue = 23,
18811
        EthereumInboundQueue: snowbridge_pallet_inbound_queue = 24,
18811
        EthereumSystem: snowbridge_pallet_system = 25,
18811
        OutboundMessageCommitmentRecorder: pallet_outbound_message_commitment_recorder = 26,
18811
        EthereumTokenTransfers: pallet_ethereum_token_transfers = 27,
18811

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

            
18811
        // InflationRewards must be after Session
18811
        InflationRewards: pallet_inflation_rewards = 33,
18811
        PooledStaking: pallet_pooled_staking = 34,
18811

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

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

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

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

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

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

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

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

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

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

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

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

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

            
18811
        ParasSudoWrapper: paras_sudo_wrapper = 250,
18811

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

            
18811
        // Sudo.
18811
        Sudo: pallet_sudo = 255,
18811
    }
657787
}
/// 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 + paras_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)
    }
    #[cfg(feature = "runtime-benchmarks")]
    fn prepare_chain_registration(id: ParaId, who: AccountId) {
        use frame_support::assert_ok;
        paras_registrar::NextFreeParaId::<Runtime>::put(id);
        assert_eq!(paras_registrar::NextFreeParaId::<Runtime>::get(), id);
        assert_ok!(Registrar::reserve(RuntimeOrigin::signed(who.into())));
    }
}
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,
        weights::runtime_common_paras_registrar::SubstrateWeight<Runtime>,
    >;
    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;
    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_multiblock_migrations, MultiBlockMigrations]
        [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]
        [pallet_mmr, Mmr]
        [pallet_beefy_mmr, BeefyMmrLeaf]
        [pallet_multiblock_migrations, MultiBlockMigrations]
        // Tanssi
        [pallet_author_noting, AuthorNoting]
        [pallet_registrar, ContainerRegistrar]
        [pallet_collator_assignment, TanssiCollatorAssignment]
        [pallet_external_validators, ExternalValidators]
        [pallet_external_validators_rewards, ExternalValidatorsRewards]
        [pallet_external_validator_slashes, ExternalValidatorSlashes]
        [pallet_invulnerables, TanssiInvulnerables]
        [pallet_data_preservers, DataPreservers]
        [pallet_pooled_staking, PooledStaking]
        [pallet_configuration, CollatorConfiguration]
        // 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
        [pallet_ethereum_token_transfers, EthereumTokenTransfers]
        [snowbridge_pallet_ethereum_client, EthereumBeaconClient]
        [snowbridge_pallet_outbound_queue, EthereumOutboundQueue]
        [snowbridge_pallet_system, EthereumSystem]
        [snowbridge_pallet_inbound_queue, EthereumInboundQueue]
    );
}
371798
sp_api::impl_runtime_apis! {
262451
    impl sp_api::Core<Block> for Runtime {
262451
        fn version() -> RuntimeVersion {
            VERSION
        }
262451

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

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

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

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

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

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

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

            
262451
    impl xcm_runtime_apis::conversions::LocationToAccountApi<Block, AccountId> for Runtime {
262451
        fn convert_location(location: VersionedLocation) -> Result<
            AccountId,
            xcm_runtime_apis::conversions::Error
        > {
            xcm_runtime_apis::conversions::LocationToAccountHelper::<
                AccountId,
                xcm_config::LocationConverter,
            >::convert_location(location)
        }
262451
    }
262451

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
262451
        fn submit_report_fork_voting_unsigned_extrinsic(
            equivocation_proof:
                beefy_primitives::ForkVotingProof<
                    <Block as BlockT>::Header,
                    BeefyId,
                    sp_runtime::OpaqueValue
                >,
            key_owner_proof: beefy_primitives::OpaqueKeyOwnershipProof,
        ) -> Option<()> {
            Beefy::submit_unsigned_fork_voting_report(
                equivocation_proof.try_into()?,
262451
                key_owner_proof.decode()?,
262451
            )
262451
        }
262451

            
262451
        fn submit_report_future_block_voting_unsigned_extrinsic(
            equivocation_proof: beefy_primitives::FutureBlockVotingProof<BlockNumber, BeefyId>,
            key_owner_proof: beefy_primitives::OpaqueKeyOwnershipProof,
        ) -> Option<()> {
            Beefy::submit_unsigned_future_block_voting_report(
                equivocation_proof,
                key_owner_proof.decode()?,
262451
            )
262451
        }
262451

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

            
262451
        fn generate_ancestry_proof(
            prev_block_number: BlockNumber,
            best_known_block_number: Option<BlockNumber>,
        ) -> Option<sp_runtime::OpaqueValue> {
262451
            use beefy_primitives::AncestryHelper;
262451

            
262451
            BeefyMmrLeaf::generate_proof(prev_block_number, best_known_block_number)
                .map(|p| p.encode())
                .map(sp_runtime::OpaqueValue::new)
        }
262451
    }
262451

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
262451
    impl pallet_external_validators_rewards_runtime_api::ExternalValidatorsRewardsApi<Block, AccountId, EraIndex> for Runtime
262451
        where
262451
        EraIndex: parity_scale_codec::Codec,
262451
    {
262451
        fn generate_rewards_merkle_proof(account_id: AccountId, era_index: EraIndex) -> Option<MerkleProof> {
            ExternalValidatorsRewards::generate_rewards_merkle_proof(account_id, era_index)
        }
262451

            
262451
        fn verify_rewards_merkle_proof(merkle_proof: MerkleProof) -> bool {
            ExternalValidatorsRewards::verify_rewards_merkle_proof(merkle_proof)
        }
262451
    }
262451

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

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

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

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

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

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

            
262451
    impl snowbridge_outbound_queue_runtime_api::OutboundQueueApi<Block, Balance> for Runtime {
262451
        fn prove_message(leaf_index: u64) -> Option<MerkleProof> {
            snowbridge_pallet_outbound_queue::api::prove_message::<Runtime>(leaf_index)
        }
262451

            
262451
        fn calculate_fee(command: Command, parameters: Option<PricingParameters<Balance>>) -> Fee<Balance> {
            snowbridge_pallet_outbound_queue::api::calculate_fee::<Runtime>(command, parameters)
        }
262451
    }
262451

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
262451
                type CheckedAccount = LocalCheckAccount;
262451
                type TrustedTeleporter = TrustedTeleporter;
262451
                type TrustedReserve = TrustedReserve;
262451

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
262451
            add_benchmarks!(params, batches);
262451

            
262451
            Ok(batches)
262451
        }
262451
    }
262451

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

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

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

            
497
        let invulnerables = TanssiInvulnerables::invulnerables().to_vec();
497
        let candidates_staking =
497
            pallet_pooled_staking::SortedEligibleCandidates::<Runtime>::get().to_vec();
497
        // Max number of collators is set in pallet_configuration
497
        let target_session_index = session_index.saturating_add(1);
497
        let max_collators = <CollatorConfiguration as GetHostConfiguration<u32>>::max_collators(
497
            target_session_index,
497
        );
497
        let next_collators: Vec<_> = invulnerables
497
            .iter()
497
            .cloned()
497
            .chain(candidates_staking.into_iter().filter_map(|elig| {
26
                let cand = elig.candidate;
26
                if invulnerables.contains(&cand) {
                    // If a candidate is both in pallet_invulnerables and pallet_staking, do not count it twice
26
                    None
                } else {
                    Some(cand)
                }
497
            }))
497
            .take(max_collators as usize)
497
            .collect();
497

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

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

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

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

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

            
497
        // 5. AuthorityAssignment
497
        let queued_id_to_nimbus_map = queued_amalgamated.iter().cloned().collect();
497
        TanssiAuthorityAssignment::initializer_on_new_session(
497
            &session_index,
497
            &queued_id_to_nimbus_map,
497
            &assignments.next_assignment,
497
        );
497
    }
}
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 {
337
    fn get_block_randomness() -> Option<[u8; 32]> {
337
        // In a relay context we get block randomness from Babe's AuthorVrfRandomness
337
        Babe::author_vrf_randomness()
337
    }
337
    fn get_block_randomness_mixed(subject: &[u8]) -> Option<Hash> {
337
        Self::get_block_randomness()
337
            .map(|random_hash| mix_randomness::<Runtime>(random_hash, subject))
337
    }
}
/// 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 {
577
    fn get() -> u32 {
577
        CollatorConfiguration::config().full_rotation_period
577
    }
}
// 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 {
7011
    fn should_end_session(n: u32) -> bool {
7011
        // Check if next slot there is a session change
7011
        n != 1 && {
7011
            let diff = Babe::current_slot()
7011
                .saturating_add(1u64)
7011
                .saturating_sub(Babe::current_epoch_start());
7011
            *diff >= Babe::current_epoch().duration
        }
7011
    }
336
    fn get_randomness() -> [u8; 32] {
336
        let block_number = System::block_number();
336
        let random_seed = if block_number != 0 {
336
            if let Some(random_hash) = {
336
                BabeCurrentBlockRandomnessGetter::get_block_randomness_mixed(b"CollatorAssignment")
336
            } {
                // 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]
334
                [0; 32]
            }
        } else {
            // In block 0 (genesis) there is no randomness
            [0; 32]
        };
336
        random_seed
336
    }
}
// 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 ParaIdAssignmentHooksImpl;
impl ParaIdAssignmentHooksImpl {
740
    fn charge_para_ids_internal(
740
        blocks_per_session: BlockNumber,
740
        para_id: ParaId,
740
        currently_assigned: &BTreeSet<ParaId>,
740
        maybe_tip: &Option<BalanceOf<Runtime>>,
740
    ) -> Result<Weight, DispatchError> {
        use frame_support::traits::Currency;
        type ServicePaymentCurrency = <Runtime as pallet_services_payment::Config>::Currency;
        // Check if the container chain has enough credits for a session assignments
733
        let maybe_assignment_imbalance =
740
            if  pallet_services_payment::Pallet::<Runtime>::burn_collator_assignment_free_credit_for_para(&para_id).is_err() {
15
                let (amount_to_charge, _weight) =
15
                    <Runtime as pallet_services_payment::Config>::ProvideCollatorAssignmentCost::collator_assignment_cost(&para_id);
15
                Some(<ServicePaymentCurrency as Currency<AccountId>>::withdraw(
15
                    &pallet_services_payment::Pallet::<Runtime>::parachain_tank(para_id),
15
                    amount_to_charge,
15
                    WithdrawReasons::FEE,
15
                    ExistenceRequirement::KeepAlive,
15
                )?)
            } else {
725
                None
            };
733
        if let Some(tip) = maybe_tip {
485
            if let Err(e) = pallet_services_payment::Pallet::<Runtime>::charge_tip(&para_id, tip) {
                // Return assignment imbalance to tank on error
1
                if let Some(assignment_imbalance) = maybe_assignment_imbalance {
                    <Runtime as pallet_services_payment::Config>::Currency::resolve_creating(
                        &pallet_services_payment::Pallet::<Runtime>::parachain_tank(para_id),
                        assignment_imbalance,
                    );
1
                }
1
                return Err(e);
484
            }
248
        }
732
        if let Some(assignment_imbalance) = maybe_assignment_imbalance {
8
            <Runtime as pallet_services_payment::Config>::OnChargeForCollatorAssignment::on_unbalanced(assignment_imbalance);
724
        }
        // If the para has been assigned collators for this session it must have enough block credits
        // for the current and the next session.
732
        let block_credits_needed = if currently_assigned.contains(&para_id) {
457
            blocks_per_session * 2
        } else {
275
            blocks_per_session
        };
        // Check if the container chain has enough credits for producing blocks
732
        let free_block_credits =
732
            pallet_services_payment::BlockProductionCredits::<Runtime>::get(para_id)
732
                .unwrap_or_default();
732
        let remaining_block_credits = block_credits_needed.saturating_sub(free_block_credits);
732
        let (block_production_costs, _) =
732
            <Runtime as pallet_services_payment::Config>::ProvideBlockProductionCost::block_cost(
732
                &para_id,
732
            );
732
        // Check if we can withdraw
732
        let remaining_block_credits_to_pay =
732
            u128::from(remaining_block_credits).saturating_mul(block_production_costs);
732
        let remaining_to_pay = remaining_block_credits_to_pay;
732
        // This should take into account whether we tank goes below ED
732
        // The true refers to keepAlive
732
        Balances::can_withdraw(
732
            &pallet_services_payment::Pallet::<Runtime>::parachain_tank(para_id),
732
            remaining_to_pay,
732
        )
732
        .into_result(true)?;
        // TODO: Have proper weight
718
        Ok(Weight::zero())
740
    }
}
impl<AC> ParaIdAssignmentHooks<BalanceOf<Runtime>, AC> for ParaIdAssignmentHooksImpl {
994
    fn pre_assignment(para_ids: &mut Vec<ParaId>, currently_assigned: &BTreeSet<ParaId>) {
994
        let blocks_per_session = EpochDurationInBlocks::get();
994
        para_ids.retain(|para_id| {
460
            with_transaction(|| {
460
                let max_tip =
460
                    pallet_services_payment::MaxTip::<Runtime>::get(para_id).unwrap_or_default();
460
                TransactionOutcome::Rollback(Self::charge_para_ids_internal(
460
                    blocks_per_session,
460
                    *para_id,
460
                    currently_assigned,
460
                    &Some(max_tip),
460
                ))
460
            })
460
            .is_ok()
994
        });
994
    }
497
    fn post_assignment(
497
        current_assigned: &BTreeSet<ParaId>,
497
        new_assigned: &mut BTreeMap<ParaId, Vec<AC>>,
497
        maybe_tip: &Option<BalanceOf<Runtime>>,
497
    ) -> Weight {
497
        let blocks_per_session = EpochDurationInBlocks::get();
497
        let mut total_weight = Weight::zero();
497
        new_assigned.retain(|&para_id, collators| {
422
            // Short-circuit in case collators are empty
422
            if collators.is_empty() {
142
                return true;
280
            }
280
            with_storage_layer(|| {
280
                Self::charge_para_ids_internal(
280
                    blocks_per_session,
280
                    para_id,
280
                    current_assigned,
280
                    maybe_tip,
280
                )
280
            })
280
            .inspect(|weight| {
280
                total_weight += *weight;
280
            })
280
            .is_ok()
497
        });
497
        total_weight
497
    }
    /// 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,
            ));
        }
    }
}
500
fn host_config_at_session(
500
    session_index_to_consider: SessionIndex,
500
) -> HostConfiguration<BlockNumber> {
500
    let active_config = runtime_parachains::configuration::ActiveConfig::<Runtime>::get();
500

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

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

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

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

            
500
        let config_to_consider = host_config_at_session(session_index_to_consider);
500

            
500
        Some(CoreAllocationConfiguration {
500
            core_count: config_to_consider.scheduler_params.num_cores,
500
            max_parachain_percentage,
500
        })
500
    }
}
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 ParaIdAssignmentHooks = ParaIdAssignmentHooksImpl;
    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));
    }
}