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
extern crate alloc;
24

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

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

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

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

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

            
158
// XCM configurations.
159
pub mod xcm_config;
160

            
161
pub mod bridge_to_ethereum_config;
162

            
163
pub mod eth_chain_config;
164

            
165
// Weights
166
mod weights;
167

            
168
// Governance and configurations.
169
pub mod governance;
170
use {
171
    governance::{
172
        pallet_custom_origins, AuctionAdmin, Fellows, GeneralAdmin, Treasurer, TreasurySpender,
173
    },
174
    pallet_collator_assignment::CoreAllocationConfiguration,
175
};
176

            
177
#[cfg(test)]
178
mod tests;
179

            
180
pub mod genesis_config_presets;
181

            
182
impl_runtime_weights!(dancelight_runtime_constants);
183

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

            
188
/// Runtime version (Dancelight).
189
#[sp_version::runtime_version]
190
pub const VERSION: RuntimeVersion = RuntimeVersion {
191
    spec_name: Cow::Borrowed("dancelight"),
192
    impl_name: Cow::Borrowed("tanssi-dancelight-v2.0"),
193
    authoring_version: 0,
194
    spec_version: 1400,
195
    impl_version: 0,
196
    apis: RUNTIME_API_VERSIONS,
197
    transaction_version: 26,
198
    system_version: 1,
199
};
200

            
201
/// The BABE epoch configuration at genesis.
202
pub const BABE_GENESIS_EPOCH_CONFIG: babe_primitives::BabeEpochConfiguration =
203
    babe_primitives::BabeEpochConfiguration {
204
        c: PRIMARY_PROBABILITY,
205
        allowed_slots: babe_primitives::AllowedSlots::PrimaryAndSecondaryVRFSlots,
206
    };
207

            
208
/// Native version.
209
#[cfg(any(feature = "std", test))]
210
pub fn native_version() -> NativeVersion {
211
    NativeVersion {
212
        runtime_version: VERSION,
213
        can_author_with: Default::default(),
214
    }
215
}
216

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

            
227
109
    /// The message came from a snowbridge channel. It will be processed by `snowbridge_pallet_outbound_queue`.
228
    #[codec(index = 1)]
229
    Snowbridge(ChannelId),
230

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

            
237
#[cfg(feature = "runtime-benchmarks")]
238
impl From<u32> for AggregateMessageOrigin {
239
    fn from(n: u32) -> Self {
240
        // Some dummy for the benchmarks.
241
        Self::Ump(UmpQueueId::Para(n.into()))
242
    }
243
}
244

            
245
pub struct GetAggregateMessageOrigin;
246

            
247
impl Convert<ChannelId, AggregateMessageOrigin> for GetAggregateMessageOrigin {
248
15
    fn convert(channel_id: ChannelId) -> AggregateMessageOrigin {
249
15
        AggregateMessageOrigin::Snowbridge(channel_id)
250
15
    }
251
}
252

            
253
impl Convert<UmpQueueId, AggregateMessageOrigin> for GetAggregateMessageOrigin {
254
13
    fn convert(queue_id: UmpQueueId) -> AggregateMessageOrigin {
255
13
        AggregateMessageOrigin::Ump(queue_id)
256
13
    }
257
}
258

            
259
pub struct GetAggregateMessageOriginTanssi;
260

            
261
impl Convert<ChannelId, AggregateMessageOrigin> for GetAggregateMessageOriginTanssi {
262
50
    fn convert(channel_id: ChannelId) -> AggregateMessageOrigin {
263
50
        AggregateMessageOrigin::SnowbridgeTanssi(channel_id)
264
50
    }
265
}
266

            
267
/// This is used by [parachains_inclusion::Pallet::on_queue_changed]
268
pub struct GetParaFromAggregateMessageOrigin;
269

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

            
293
/// The relay register and deregister calls should no longer be necessary
294
/// Everything is handled by the containerRegistrar
295
pub struct IsRelayRegister;
296
impl Contains<RuntimeCall> for IsRelayRegister {
297
108
    fn contains(c: &RuntimeCall) -> bool {
298
107
        matches!(
299
2
            c,
300
            RuntimeCall::Registrar(paras_registrar::Call::register { .. })
301
106
        ) || matches!(
302
1
            c,
303
            RuntimeCall::Registrar(paras_registrar::Call::deregister { .. })
304
        )
305
108
    }
306
}
307

            
308
/// Dancelight shouold not permit parathread registration for now
309
/// TODO: remove once they are enabled
310
pub struct IsParathreadRegistrar;
311
impl Contains<RuntimeCall> for IsParathreadRegistrar {
312
106
    fn contains(c: &RuntimeCall) -> bool {
313
105
        matches!(
314
1
            c,
315
            RuntimeCall::ContainerRegistrar(pallet_registrar::Call::register_parathread { .. })
316
        )
317
106
    }
318
}
319

            
320
parameter_types! {
321
    pub const Version: RuntimeVersion = VERSION;
322
    pub const SS58Prefix: u8 = 42;
323
}
324

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

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

            
352
/// Used the compare the privilege of an origin inside the scheduler.
353
pub struct OriginPrivilegeCmp;
354

            
355
impl PrivilegeCmp<OriginCaller> for OriginPrivilegeCmp {
356
    fn cmp_privilege(left: &OriginCaller, right: &OriginCaller) -> Option<Ordering> {
357
        if left == right {
358
            return Some(Ordering::Equal);
359
        }
360

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

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

            
375
    #[dynamic_pallet_params]
376
    #[codec(index = 0)]
377
    pub mod preimage {
378
        use super::*;
379

            
380
        #[codec(index = 0)]
381
        pub static BaseDeposit: Balance = deposit(2, 64);
382

            
383
        #[codec(index = 1)]
384
        pub static ByteDeposit: Balance = deposit(0, 1);
385
    }
386
}
387

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

            
398
/// Defines what origin can modify which dynamic parameters.
399
pub struct DynamicParameterOrigin;
400
impl EnsureOriginWithArg<RuntimeOrigin, RuntimeParametersKey> for DynamicParameterOrigin {
401
    type Success = ();
402

            
403
    fn try_origin(
404
        origin: RuntimeOrigin,
405
        key: &RuntimeParametersKey,
406
    ) -> Result<Self::Success, RuntimeOrigin> {
407
        use crate::RuntimeParametersKey::*;
408

            
409
        match key {
410
            Preimage(_) => frame_system::ensure_root(origin.clone()),
411
        }
412
        .map_err(|_| origin)
413
    }
414

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

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

            
437
parameter_types! {
438
    pub const PreimageHoldReason: RuntimeHoldReason = RuntimeHoldReason::Preimage(pallet_preimage::HoldReason::Preimage);
439
}
440

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

            
458
parameter_types! {
459
    pub const ExpectedBlockTime: Moment = MILLISECS_PER_BLOCK;
460
    pub ReportLongevity: u64 = u64::from(EpochDurationInBlocks::get()) * 10;
461
}
462

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

            
478
parameter_types! {
479
    pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT;
480
    pub const MaxLocks: u32 = 50;
481
    pub const MaxReserves: u32 = 50;
482
}
483

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

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

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

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

            
528
pub struct RewardPoints;
529

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

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

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

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

            
566
impl pallet_session::Config for Runtime {
567
    type RuntimeEvent = RuntimeEvent;
568
    type ValidatorId = AccountId;
569
    type ValidatorIdOf = ValidatorIdOf;
570
    type ShouldEndSession = Babe;
571
    type NextSessionRotation = Babe;
572
    type SessionManager = pallet_session::historical::NoteHistoricalRoot<Self, ExternalValidators>;
573
    type SessionHandler = <SessionKeys as OpaqueKeys>::KeyTypeIdProviders;
574
    type Keys = SessionKeys;
575
    type WeightInfo = weights::pallet_session::SubstrateWeight<Runtime>;
576
}
577

            
578
pub struct FullIdentificationOf;
579
impl Convert<AccountId, Option<()>> for FullIdentificationOf {
580
767
    fn convert(_: AccountId) -> Option<()> {
581
767
        Some(())
582
767
    }
583
}
584

            
585
impl pallet_session::historical::Config for Runtime {
586
    type FullIdentification = ();
587
    type FullIdentificationOf = FullIdentificationOf;
588
}
589

            
590
parameter_types! {
591
    pub const BondingDuration: sp_staking::EraIndex = runtime_common::prod_or_fast!(28, 3);
592
}
593

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

            
607
    pub const TipCountdown: BlockNumber = 1 * DAYS;
608
    pub const TipFindersFee: Percent = Percent::from_percent(20);
609
    pub const TipReportDepositBase: Balance = 100 * CENTS;
610
    pub const DataDepositPerByte: Balance = 1 * CENTS;
611
    pub const MaxApprovals: u32 = 100;
612
    pub const MaxAuthorities: u32 = 100_000;
613
    pub const MaxKeys: u32 = 10_000;
614
    pub const MaxPeerInHeartbeats: u32 = 10_000;
615
    pub const MaxBalance: Balance = Balance::max_value();
616
    pub TreasuryAccount: AccountId = Treasury::account_id();
617
    pub SnowbridgeFeesAccount: AccountId = PalletId(*b"sb/feeac").into_account_truncating();
618
}
619

            
620
#[cfg(feature = "runtime-benchmarks")]
621
pub struct TreasuryBenchmarkHelper<T>(PhantomData<T>);
622

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

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

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

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

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

            
681
impl pallet_authority_discovery::Config for Runtime {
682
    type MaxAuthorities = MaxAuthorities;
683
}
684

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

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

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

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

            
756
impl frame_system::offchain::SigningTypes for Runtime {
757
    type Public = <Signature as Verify>::Signer;
758
    type Signature = Signature;
759
}
760

            
761
impl<C> frame_system::offchain::CreateTransactionBase<C> for Runtime
762
where
763
    RuntimeCall: From<C>,
764
{
765
    type Extrinsic = UncheckedExtrinsic;
766
    type RuntimeCall = RuntimeCall;
767
}
768

            
769
impl<LocalCall> frame_system::offchain::CreateInherent<LocalCall> for Runtime
770
where
771
    RuntimeCall: From<LocalCall>,
772
{
773
    fn create_inherent(call: RuntimeCall) -> UncheckedExtrinsic {
774
        UncheckedExtrinsic::new_bare(call)
775
    }
776
}
777

            
778
parameter_types! {
779
    // Minimum 100 bytes/STAR deposited (1 CENT/byte)
780
    pub const BasicDeposit: Balance = 1000 * CENTS;       // 258 bytes on-chain
781
    pub const ByteDeposit: Balance = deposit(0, 1);
782
    pub const UsernameDeposit: Balance = deposit(0, 32);
783
    pub const SubAccountDeposit: Balance = 200 * CENTS;   // 53 bytes on-chain
784
    pub const MaxSubAccounts: u32 = 100;
785
    pub const MaxAdditionalFields: u32 = 100;
786
    pub const MaxRegistrars: u32 = 20;
787
}
788

            
789
impl pallet_identity::Config for Runtime {
790
    type RuntimeEvent = RuntimeEvent;
791
    type Currency = Balances;
792
    type BasicDeposit = BasicDeposit;
793
    type ByteDeposit = ByteDeposit;
794
    type UsernameDeposit = UsernameDeposit;
795
    type SubAccountDeposit = SubAccountDeposit;
796
    type MaxSubAccounts = MaxSubAccounts;
797
    type IdentityInformation = IdentityInfo<MaxAdditionalFields>;
798
    type MaxRegistrars = MaxRegistrars;
799
    type Slashed = Treasury;
800
    type ForceOrigin = EitherOf<EnsureRoot<Self::AccountId>, GeneralAdmin>;
801
    type RegistrarOrigin = EitherOf<EnsureRoot<Self::AccountId>, GeneralAdmin>;
802
    type OffchainSignature = Signature;
803
    type SigningPublicKey = <Signature as Verify>::Signer;
804
    type UsernameAuthorityOrigin = EnsureRoot<Self::AccountId>;
805
    type PendingUsernameExpiration = ConstU32<{ 7 * DAYS }>;
806
    type UsernameGracePeriod = ConstU32<{ 30 * DAYS }>;
807
    type MaxSuffixLength = ConstU32<7>;
808
    type MaxUsernameLength = ConstU32<32>;
809
    type WeightInfo = weights::pallet_identity::SubstrateWeight<Runtime>;
810
}
811

            
812
impl pallet_utility::Config for Runtime {
813
    type RuntimeEvent = RuntimeEvent;
814
    type RuntimeCall = RuntimeCall;
815
    type PalletsOrigin = OriginCaller;
816
    type WeightInfo = weights::pallet_utility::SubstrateWeight<Runtime>;
817
}
818

            
819
parameter_types! {
820
    // One storage item; key size is 32; value is size 4+4+16+32 bytes = 56 bytes.
821
    pub const DepositBase: Balance = deposit(1, 88);
822
    // Additional storage item size of 32 bytes.
823
    pub const DepositFactor: Balance = deposit(0, 32);
824
    pub const MaxSignatories: u32 = 100;
825
}
826

            
827
impl pallet_multisig::Config for Runtime {
828
    type RuntimeEvent = RuntimeEvent;
829
    type RuntimeCall = RuntimeCall;
830
    type Currency = Balances;
831
    type DepositBase = DepositBase;
832
    type DepositFactor = DepositFactor;
833
    type MaxSignatories = MaxSignatories;
834
    type WeightInfo = weights::pallet_multisig::SubstrateWeight<Runtime>;
835
}
836

            
837
parameter_types! {
838
    // One storage item; key size 32, value size 8; .
839
    pub const ProxyDepositBase: Balance = deposit(1, 8);
840
    // Additional storage item size of 33 bytes.
841
    pub const ProxyDepositFactor: Balance = deposit(0, 33);
842
    pub const MaxProxies: u16 = 32;
843
    pub const AnnouncementDepositBase: Balance = deposit(1, 8);
844
    pub const AnnouncementDepositFactor: Balance = deposit(0, 66);
845
    pub const MaxPending: u16 = 32;
846
}
847

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

            
976
impl pallet_proxy::Config for Runtime {
977
    type RuntimeEvent = RuntimeEvent;
978
    type RuntimeCall = RuntimeCall;
979
    type Currency = Balances;
980
    type ProxyType = ProxyType;
981
    type ProxyDepositBase = ProxyDepositBase;
982
    type ProxyDepositFactor = ProxyDepositFactor;
983
    type MaxProxies = MaxProxies;
984
    type WeightInfo = weights::pallet_proxy::SubstrateWeight<Runtime>;
985
    type MaxPending = MaxPending;
986
    type CallHasher = BlakeTwo256;
987
    type AnnouncementDepositBase = AnnouncementDepositBase;
988
    type AnnouncementDepositFactor = AnnouncementDepositFactor;
989
}
990

            
991
impl parachains_origin::Config for Runtime {}
992

            
993
impl parachains_configuration::Config for Runtime {
994
    type WeightInfo = weights::runtime_parachains_configuration::SubstrateWeight<Runtime>;
995
}
996

            
997
impl parachains_shared::Config for Runtime {
998
    type DisabledValidators = Session;
999
}
impl parachains_session_info::Config for Runtime {
    type ValidatorSet = Historical;
}
pub type RewardValidators =
    pallet_external_validators_rewards::RewardValidatorsWithEraPoints<Runtime>;
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;
63
    fn process_message(
63
        message: &[u8],
63
        origin: Self::Origin,
63
        meter: &mut WeightMeter,
63
        id: &mut [u8; 32],
63
    ) -> Result<bool, ProcessMessageError> {
63
        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(_) => {
11
                snowbridge_pallet_outbound_queue::Pallet::<Runtime>::process_message(
11
                    message, origin, meter, id,
11
                )
            }
            AggregateMessageOrigin::SnowbridgeTanssi(_) => {
52
                tp_bridge::CustomProcessSnowbridgeMessage::<Runtime>::process_message(
52
                    message, origin, meter, id,
52
                )
            }
        }
63
    }
}
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
{
2618
    fn pop_assignment_for_core(core_idx: CoreIndex) -> Option<Assignment> {
2618
        let assigned_collators = TanssiCollatorAssignment::collator_container_chain();
2618
        let assigned_paras: Vec<ParaId> = assigned_collators
2618
            .container_chains
2618
            .iter()
2618
            .filter_map(|(&para_id, collators)| {
1246
                if Paras::is_parachain(para_id) && collators.len() > 0 {
642
                    Some(para_id)
                } else {
604
                    None
                }
2618
            })
2618
            .collect();
2618
        log::debug!("pop assigned collators {:?}", assigned_paras);
2618
        log::debug!("looking for core idx {:?}", core_idx);
2618
        if let Some(para_id) = assigned_paras.get(core_idx.0 as usize) {
70
            log::debug!("outputing assignment for  {:?}", para_id);
70
            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 =
2548
                parachains_assigner_on_demand::Pallet::<Runtime>::pop_assignment_for_core(
2548
                    core_idx,
2548
                )?;
            // 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
            }
        }
2618
    }
13
    fn report_processed(assignment: Assignment) {
13
        match assignment {
            Assignment::Pool {
5
                para_id,
5
                core_index,
5
            } => parachains_assigner_on_demand::Pallet::<Runtime>::report_processed(
5
                para_id, core_index,
5
            ),
8
            Assignment::Bulk(_) => {}
        }
13
    }
    /// 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.
    fn push_back_assignment(assignment: Assignment) {
        match assignment {
            Assignment::Pool {
                para_id,
                core_index,
            } => parachains_assigner_on_demand::Pallet::<Runtime>::push_back_assignment(
                para_id, core_index,
            ),
            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).
            }
        }
    }
    #[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)
    }
    fn assignment_duplicated(assignment: &Assignment) {
        match assignment {
            Assignment::Pool {
                para_id,
                core_index,
            } => parachains_assigner_on_demand::Pallet::<Runtime>::assignment_duplicated(
                *para_id,
                *core_index,
            ),
            Assignment::Bulk(_) => {}
        }
    }
}
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 = weights::runtime_parachains_disputes_slashing::SubstrateWeight<Runtime>;
    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 {
3653
    fn extra_data() -> LeafExtraData {
3653
        let mut para_heads: Vec<(u32, Vec<u8>)> = parachains_paras::Parachains::<Runtime>::get()
3653
            .into_iter()
3653
            .filter_map(|id| {
3115
                parachains_paras::Heads::<Runtime>::get(id).map(|head| (id.into(), head.0))
3653
            })
3653
            .collect();
3653
        para_heads.sort();
3653
        let para_heads_root = binary_merkle_tree::merkle_root::<mmr::Hashing, _>(
3653
            para_heads.into_iter().map(|pair| pair.encode()),
3653
        );
3653

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

            
3653
        LeafExtraData {
3653
            para_heads_root,
3653
            commitment_root,
3653
        }
3653
    }
}
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},
    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
    }
}
prod_or_fast_parameter_types! {
    pub const SessionsPerEra: SessionIndex = { prod: 6, fast: 3 };
    pub const SlashDeferDuration: EraIndex = { prod: 0, fast: 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 Sepolia.
    // Output is: ce796ae65569a670d0c1cc1ac12515a3ce21b5fbf729d63d7b289baad070139d
    pub EthereumSovereignAccount: AccountId =
        tp_bridge::EthereumLocationsConverterFor::<AccountId>::convert_location(
            &EthereumLocation::get()
        ).expect("to convert EthereumSovereignAccount");
    pub ExternalRewardsEraInflationProvider: u128 = ValidatorsInflationRatePerEra::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) {}
}
// Pallet to reward validators.
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.
981
    fn session_index() -> SessionIndex {
981
        Session::current_index()
981
    }
    #[cfg(feature = "runtime-benchmarks")]
    fn skip_to_session(session_index: SessionIndex) {
        while Session::current_index() < session_index {
            Session::rotate_session();
        }
    }
}
impl pallet_configuration::Config for Runtime {
    type SessionDelay = ConstU32<2>;
    type SessionIndex = 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 = (
        pallet_identity::migration::v2::LazyMigrationV1ToV2<Runtime>,
        pallet_pooled_staking::migrations::MigrationGenerateSummaries<Runtime>,
    );
    // 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> {
785
    fn block_cost(_para_id: &ParaId) -> (u128, Weight) {
785
        (FIXED_BLOCK_PRODUCTION_COST, Weight::zero())
785
    }
}
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>;
}
pub const OPEN_STREAM_HOLD_AMOUNT: u32 = 253;
parameter_types! {
    // 1 entry, storing 253 bytes on-chain in the worst case
    pub const OpenStreamHoldAmount: Balance = deposit(1, OPEN_STREAM_HOLD_AMOUNT);
}
impl pallet_stream_payment::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type StreamId = tp_stream_payment_common::StreamId;
    type TimeUnit = tp_stream_payment_common::TimeUnit;
    type Balance = Balance;
    type AssetId = tp_stream_payment_common::AssetId;
    type AssetsManager = tp_stream_payment_common::AssetsManager<Runtime>;
    type Currency = Balances;
    type OpenStreamHoldAmount = OpenStreamHoldAmount;
    type RuntimeHoldReason = RuntimeHoldReason;
    type TimeProvider = tp_stream_payment_common::TimeProvider<Runtime>;
    type WeightInfo = weights::pallet_stream_payment::SubstrateWeight<Runtime>;
}
parameter_types! {
    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;
}
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 AssignmentProcessor = tp_data_preservers_common::AssignmentProcessor<Runtime>;
    type AssignmentOrigin = pallet_registrar::EnsureSignedByManager<Runtime>;
    type ForceSetProfileOrigin = EnsureRoot<AccountId>;
    type MaxAssignmentsPerParaId = MaxAssignmentsPerParaId;
    type MaxNodeUrlLen = MaxNodeUrlLen;
    type MaxParaIdsVecLen = MaxLengthParaIds;
}
parameter_types! {
    pub DancelightBondAccount: AccountId32 = PalletId(*b"StarBond").into_account_truncating();
    pub PendingRewardsAccount: AccountId32 = PalletId(*b"PENDREWD").into_account_truncating();
    // 30% for dancelight bond, so 70% for staking
    pub const RewardsPortion: Perbill = Perbill::from_percent(70);
}
// We want a global annual inflation rate of 10%.
// It is compounded throught era inflations, which itself is split between:
// - Inflation for collators per block
// - Inflation for validators per era
// Computation is implemented in tests/inflation_rates.rs, with a test ensuring values from the
// runtime match the formulas. We write the results as constants here to ensure we don't perform
// computations at runtime.
prod_or_fast_parameter_types! {
    pub const CollatorsInflationRatePerBlock: Perbill = { prod: Perbill::from_parts(9), fast: Perbill::from_parts(9) };
    pub const ValidatorsInflationRatePerEra: Perbill = { prod: Perbill::from_parts(32641), fast: Perbill::from_parts(272) };
}
pub struct OnUnbalancedInflation;
impl frame_support::traits::OnUnbalanced<Credit<AccountId, Balances>> for OnUnbalancedInflation {
1519
    fn on_nonzero_unbalanced(credit: Credit<AccountId, Balances>) {
1519
        let _ = <Balances as Balanced<_>>::resolve(&DancelightBondAccount::get(), credit);
1519
    }
}
// Pallet to reward container chains collators.
impl pallet_inflation_rewards::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type Currency = Balances;
    type ContainerChains = ContainerRegistrar;
    type GetSelfChainBlockAuthor = ();
    type InflationRate = CollatorsInflationRatePerBlock;
    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 = scale_info::prelude::format!("{:?}", a_u8);
            let authority_keys = get_authority_keys_from_seed(&seed);
            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>;
}
impl pallet_inactivity_tracking::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type CollatorId = AccountId;
    type MaxInactiveSessions = ConstU32<5>;
    type MaxCollatorsPerSession = ConstU32<100>;
    type CurrentSessionIndex = CurrentSessionIndexGetter;
    type CurrentCollatorsFetcher = TanssiCollatorAssignment;
    type GetSelfChainBlockAuthor = ();
    type WeightInfo = weights::pallet_inactivity_tracking::SubstrateWeight<Runtime>;
}
725354
construct_runtime! {
21665
    pub enum Runtime
21665
    {
21665
        // Basic stuff; balances is uncallable initially.
21665
        System: frame_system = 0,
21665

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

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

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

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

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

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

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

            
21665
        // InflationRewards must be after Session
21665
        InflationRewards: pallet_inflation_rewards = 33,
21665
        PooledStaking: pallet_pooled_staking = 34,
21665
        InactivityTracking: pallet_inactivity_tracking = 35,
21665

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

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

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

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

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

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

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

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

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

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

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

            
21665
        StreamPayment: pallet_stream_payment = 100,
21665

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

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

            
21665
        ParasSudoWrapper: paras_sudo_wrapper = 250,
21665

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

            
21665
        // Sudo.
21665
        Sudo: pallet_sudo = 255,
21665
    }
726499
}
/// 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 `TxExtension` to the basic transaction logic.
pub type TxExtension = (
    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, TxExtension>;
/// The runtime migrations per release.
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, TxExtension>;
parameter_types! {
    #[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>,
{
33
    fn register(
33
        who: AccountId,
33
        id: ParaId,
33
        genesis_storage: &[ContainerChainGenesisDataItem],
33
        head_data: Option<HeadData>,
33
    ) -> DispatchResult {
        // Return early if head_data is not specified
33
        let genesis_head = match head_data {
33
            Some(data) => data,
            None => return Err(ContainerRegistrarError::<Runtime>::HeadDataNecessary.into()),
        };
        // Check if the wasm code is present in storage
33
        let validation_code = match genesis_storage
33
            .iter()
33
            .find(|item| item.key == StorageWellKnownKeys::CODE)
        {
33
            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.
33
        Registrar::register(
33
            RuntimeOrigin::signed(who.into()),
33
            id,
33
            genesis_head,
33
            validation_code,
33
        )
33
    }
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 =
        EitherOfDiverse<pallet_registrar::EnsureSignedByManager<Runtime>, 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 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>;
    type DataDepositPerByte = DataDepositPerByte;
}
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: tp_data_preservers_common::ProviderRequest::Free,
        };
        let profile_id = pallet_data_preservers::NextProfileId::<Runtime>::get();
        let profile_owner = AccountId::new([1u8; 32]);
        DataPreservers::force_create_profile(RuntimeOrigin::root(), profile, profile_owner)
            .expect("profile create to succeed");
        let para_manager =
            <Runtime as pallet_data_preservers::Config>::AssignmentOrigin::try_successful_origin(
                &para_id,
            )
            .expect("should be able to get para manager");
        DataPreservers::start_assignment(
            para_manager,
            profile_id,
            para_id,
            tp_data_preservers_common::AssignerExtra::Free,
        )
        .expect("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;
9
    fn current_block_number() -> Self::BlockNumber {
9
        // TODO: nimbus_primitives::SlotBeacon requires u32, but this is a u64 in pallet_babe, and
9
        // also it gets converted to u64 in pallet_author_noting, so let's do something to remove
9
        // this intermediate u32 conversion, such as using a different trait
9
        u64::from(pallet_babe::CurrentSlot::<Runtime>::get()) as u32
9
    }
}
impl pallet_author_noting::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type ContainerChains = TanssiCollatorAssignment;
    type SlotBeacon = BabeSlotBeacon;
    type ContainerChainAuthor = TanssiCollatorAssignment;
    type AuthorNotingHook = (InflationRewards, ServicesPayment, InactivityTracking);
    type RelayOrPara = pallet_author_noting::RelayMode;
    type MaxContainerChains = MaxLengthParaIds;
    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]
        [runtime_parachains::disputes::slashing, pallet_alt_benchmarks::bench_parachains_slashing::Pallet::<Runtime>]
        // 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>]
        [frame_system_extensions, frame_system_benchmarking::extensions::Pallet::<Runtime>]
        [pallet_timestamp, Timestamp]
        [pallet_transaction_payment, TransactionPayment]
        [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]
        [pallet_session, cumulus_pallet_session_benchmarking::Pallet::<Runtime>]
        // 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_inactivity_tracking, InactivityTracking]
        [pallet_configuration, CollatorConfiguration]
        [pallet_stream_payment, StreamPayment]
        // 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]
    );
}
471882
sp_api::impl_runtime_apis! {
351012
    impl sp_api::Core<Block> for Runtime {
351012
        fn version() -> RuntimeVersion {
            VERSION
        }
351012

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
351016
        fn candidates_pending_availability(para_id: ParaId) -> Vec<CommittedCandidateReceiptV2<Hash>> {
4
            parachains_runtime_api_impl::candidates_pending_availability::<Runtime>(para_id)
4
        }
351012
    }
351012

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

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

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

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

            
351012
        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()?,
351012
                key_owner_proof.decode()?,
351012
            )
351012
        }
351012

            
351012
        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()?,
351012
            )
351012
        }
351012

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
351012
    impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentCallApi<Block, Balance, RuntimeCall>
351012
        for Runtime
351012
    {
351012
        fn query_call_info(call: RuntimeCall, len: u32) -> RuntimeDispatchInfo<Balance> {
            TransactionPayment::query_call_info(call, len)
        }
351012
        fn query_call_fee_details(call: RuntimeCall, len: u32) -> FeeDetails<Balance> {
            TransactionPayment::query_call_fee_details(call, len)
        }
351012
        fn query_weight_to_fee(weight: Weight) -> Balance {
            TransactionPayment::weight_to_fee(weight)
        }
351012
        fn query_length_to_fee(length: u32) -> Balance {
            TransactionPayment::length_to_fee(length)
        }
351012
    }
351012

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
351012
                type CheckedAccount = LocalCheckAccount;
351012
                type TrustedTeleporter = ();
351012
                type TrustedReserve = ();
351012

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

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

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

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

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

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

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

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

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

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

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

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

            
351012
            pub struct SessionBenchValidators;
351012
            impl pallet_alt_benchmarks::bench_parachains_slashing::Validators<AccountId> for SessionBenchValidators {
351012
                /// Sets the validators to properly run a benchmark. Should take care of everything that
351012
                /// will make pallet_session use those validators, such as them having a balance.
351012
                fn set_validators(validators: &[AccountId]) {
351012
                    use frame_support::traits::fungible::Mutate;
351012
                    use tp_traits::ExternalIndexProvider;
351012

            
351012
                    ExternalValidators::set_external_validators_inner(
351012
                        validators.to_vec(),
351012
                        ExternalValidators::get_external_index()
351012
                    ).expect("to set validators");
351012

            
351012
                    for v in validators {
351012
                        Balances::set_balance(v, EXISTENTIAL_DEPOSIT);
351012
                    }
351012
                }
351012
            }
351012
            impl pallet_alt_benchmarks::bench_parachains_slashing::Config for Runtime {
351012
                type Validators = SessionBenchValidators;
351012
            }
351012

            
351012
            impl cumulus_pallet_session_benchmarking::Config for Runtime { }
351012

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

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

            
351012
            add_benchmarks!(params, batches);
351012

            
351012
            Ok(batches)
351012
        }
351012
    }
351012

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

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

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

            
577
        let invulnerables = TanssiInvulnerables::invulnerables().to_vec();
577
        let candidates_staking =
577
            pallet_pooled_staking::SortedEligibleCandidates::<Runtime>::get().to_vec();
577
        // Max number of collators is set in pallet_configuration
577
        let target_session_index = session_index.saturating_add(1);
577
        let max_collators = <CollatorConfiguration as GetHostConfiguration<u32>>::max_collators(
577
            target_session_index,
577
        );
577
        let next_collators: Vec<_> = invulnerables
577
            .iter()
577
            .cloned()
577
            .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)
                }
577
            }))
577
            .take(max_collators as usize)
577
            .collect();
577

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

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

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

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

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

            
577
        // 5. AuthorityAssignment
577
        let queued_id_to_nimbus_map = queued_amalgamated.iter().cloned().collect();
577
        TanssiAuthorityAssignment::initializer_on_new_session(
577
            &session_index,
577
            &queued_id_to_nimbus_map,
577
            &assignments.next_assignment,
577
        );
577
        // 6. InactivityTracking
577
        InactivityTracking::process_ended_session();
577
    }
342
    fn on_before_session_ending() {
342
        InactivityTracking::on_before_session_ending();
342
    }
}
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 {
343
    fn get_block_randomness() -> Option<[u8; 32]> {
343
        // In a relay context we get block randomness from Babe's AuthorVrfRandomness
343
        Babe::author_vrf_randomness()
343
    }
343
    fn get_block_randomness_mixed(subject: &[u8]) -> Option<Hash> {
343
        Self::get_block_randomness()
343
            .map(|random_hash| mix_randomness::<Runtime>(random_hash, subject))
343
    }
}
/// 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 {
729
    fn get() -> u32 {
729
        CollatorConfiguration::config().full_rotation_period
729
    }
}
// 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 {
7152
    fn should_end_session(n: u32) -> bool {
7152
        // Check if next slot there is a session change
7152
        n != 1 && {
7152
            let diff = Babe::current_slot()
7152
                .saturating_add(1u64)
7152
                .saturating_sub(Babe::current_epoch_start());
7152
            *diff >= Babe::current_epoch().duration
        }
7152
    }
342
    fn get_randomness() -> [u8; 32] {
342
        let block_number = System::block_number();
342
        let random_seed = if block_number != 0 {
342
            if let Some(random_hash) = {
342
                BabeCurrentBlockRandomnessGetter::get_block_randomness_mixed(b"CollatorAssignment")
342
            } {
                // 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]
340
                [0; 32]
            }
        } else {
            // In block 0 (genesis) there is no randomness
            [0; 32]
        };
342
        random_seed
342
    }
}
// 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 {
769
    fn charge_para_ids_internal(
769
        blocks_per_session: BlockNumber,
769
        para_id: ParaId,
769
        currently_assigned: &BTreeSet<ParaId>,
769
        maybe_tip: &Option<BalanceOf<Runtime>>,
769
    ) -> 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
762
        let maybe_assignment_imbalance =
769
            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 {
754
                None
            };
762
        if let Some(tip) = maybe_tip {
500
            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);
499
            }
262
        }
761
        if let Some(assignment_imbalance) = maybe_assignment_imbalance {
8
            <Runtime as pallet_services_payment::Config>::OnChargeForCollatorAssignment::on_unbalanced(assignment_imbalance);
753
        }
        // If the para has been assigned collators for this session it must have enough block credits
        // for the current and the next session.
761
        let block_credits_needed = if currently_assigned.contains(&para_id) {
481
            blocks_per_session.saturating_mul(2)
        } else {
280
            blocks_per_session
        };
        // Check if the container chain has enough credits for producing blocks
761
        let free_block_credits =
761
            pallet_services_payment::BlockProductionCredits::<Runtime>::get(para_id)
761
                .unwrap_or_default();
761
        let remaining_block_credits = block_credits_needed.saturating_sub(free_block_credits);
761
        let (block_production_costs, _) =
761
            <Runtime as pallet_services_payment::Config>::ProvideBlockProductionCost::block_cost(
761
                &para_id,
761
            );
761
        // Check if we can withdraw
761
        let remaining_block_credits_to_pay =
761
            u128::from(remaining_block_credits).saturating_mul(block_production_costs);
761
        let remaining_to_pay = remaining_block_credits_to_pay;
761
        // This should take into account whether we tank goes below ED
761
        // The true refers to keepAlive
761
        Balances::can_withdraw(
761
            &pallet_services_payment::Pallet::<Runtime>::parachain_tank(para_id),
761
            remaining_to_pay,
761
        )
761
        .into_result(true)?;
        // TODO: Have proper weight
747
        Ok(Weight::zero())
769
    }
}
impl<AC> ParaIdAssignmentHooks<BalanceOf<Runtime>, AC> for ParaIdAssignmentHooksImpl {
1154
    fn pre_assignment(para_ids: &mut Vec<ParaId>, currently_assigned: &BTreeSet<ParaId>) {
1154
        let blocks_per_session = EpochDurationInBlocks::get();
1154
        para_ids.retain(|para_id| {
475
            with_transaction(|| {
475
                let max_tip =
475
                    pallet_services_payment::MaxTip::<Runtime>::get(para_id).unwrap_or_default();
475
                TransactionOutcome::Rollback(Self::charge_para_ids_internal(
475
                    blocks_per_session,
475
                    *para_id,
475
                    currently_assigned,
475
                    &Some(max_tip),
475
                ))
475
            })
475
            .is_ok()
1154
        });
1154
    }
577
    fn post_assignment(
577
        current_assigned: &BTreeSet<ParaId>,
577
        new_assigned: &mut BTreeMap<ParaId, Vec<AC>>,
577
        maybe_tip: &Option<BalanceOf<Runtime>>,
577
    ) -> Weight {
577
        let blocks_per_session = EpochDurationInBlocks::get();
577
        let mut total_weight = Weight::zero();
577
        new_assigned.retain(|&para_id, collators| {
437
            // Short-circuit in case collators are empty
437
            if collators.is_empty() {
143
                return true;
294
            }
294
            with_storage_layer(|| {
294
                Self::charge_para_ids_internal(
294
                    blocks_per_session,
294
                    para_id,
294
                    current_assigned,
294
                    maybe_tip,
294
                )
294
            })
294
            .inspect(|weight| {
294
                total_weight.saturating_accrue(*weight);
294
            })
294
            .is_ok()
577
        });
577
        total_weight
577
    }
    /// 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 = blocks_per_session.saturating_mul(20);
        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,
            ));
        }
    }
}
580
fn host_config_at_session(
580
    session_index_to_consider: SessionIndex,
580
) -> HostConfiguration<BlockNumber> {
580
    let active_config = runtime_parachains::configuration::ActiveConfig::<Runtime>::get();
580

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

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

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

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

            
580
        let config_to_consider = host_config_at_session(session_index_to_consider);
580

            
580
        Some(CoreAllocationConfiguration {
580
            core_count: config_to_consider.scheduler_params.num_cores,
580
            max_parachain_percentage,
580
        })
580
    }
}
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().saturating_add(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().saturating_add(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>()
            .saturating_mul(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.saturating_add(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));
    }
}