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 Starlight 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
    alloc::{
29
        collections::{btree_map::BTreeMap, btree_set::BTreeSet, vec_deque::VecDeque},
30
        vec,
31
        vec::Vec,
32
    },
33
    authority_discovery_primitives::AuthorityId as AuthorityDiscoveryId,
34
    beefy_primitives::{
35
        ecdsa_crypto::{AuthorityId as BeefyId, Signature as BeefySignature},
36
        mmr::{BeefyDataProvider, MmrLeafVersion},
37
    },
38
    core::{cmp::Ordering, marker::PhantomData},
39
    cumulus_primitives_core::relay_chain::{HeadData, ValidationCode},
40
    dp_container_chain_genesis_data::ContainerChainGenesisDataItem,
41
    frame_support::{
42
        dispatch::DispatchResult,
43
        dynamic_params::{dynamic_pallet_params, dynamic_params},
44
        traits::{
45
            fungible::Inspect,
46
            tokens::{PayFromAccount, UnityAssetBalanceConversion},
47
            ConstBool, Contains, EverythingBut, InsideBoth,
48
        },
49
    },
50
    frame_system::{pallet_prelude::BlockNumberFor, EnsureNever},
51
    nimbus_primitives::NimbusId,
52
    pallet_collator_assignment::RotateCollatorsEveryNSessions,
53
    pallet_initializer as tanssi_initializer,
54
    pallet_invulnerables::InvulnerableRewardDistribution,
55
    pallet_registrar::Error as ContainerRegistrarError,
56
    pallet_registrar_runtime_api::ContainerChainGenesisData,
57
    pallet_services_payment::{ProvideBlockProductionCost, ProvideCollatorAssignmentCost},
58
    pallet_stream_payment_runtime_api::{StreamPaymentApiError, StreamPaymentApiStatus},
59
    parachains_scheduler::common::Assignment,
60
    parity_scale_codec::{Decode, DecodeWithMemTracking, Encode, MaxEncodedLen},
61
    primitives::{
62
        slashing, vstaging::async_backing::Constraints, vstaging::CandidateEvent,
63
        vstaging::CommittedCandidateReceiptV2, vstaging::CoreState, vstaging::ScrapedOnChainVotes,
64
        ApprovalVotingParams, BlockNumber, CandidateHash, CoreIndex, DisputeState, ExecutorParams,
65
        GroupRotationInfo, Hash, Id as ParaId, InboundDownwardMessage, InboundHrmpMessage, Moment,
66
        NodeFeatures, Nonce, OccupiedCoreAssumption, PersistedValidationData, SessionInfo,
67
        Signature, ValidationCodeHash, ValidatorId, ValidatorIndex, PARACHAIN_KEY_TYPE_ID,
68
    },
69
    runtime_common::{
70
        self as polkadot_runtime_common, impl_runtime_weights, paras_registrar, paras_sudo_wrapper,
71
        traits::Registrar as RegistrarInterface, BlockHashCount, BlockLength,
72
        SlowAdjustingFeeUpdate,
73
    },
74
    runtime_parachains::{
75
        configuration as parachains_configuration,
76
        disputes::{self as parachains_disputes, slashing as parachains_slashing},
77
        dmp as parachains_dmp, hrmp as parachains_hrmp,
78
        inclusion::{
79
            self as parachains_inclusion,
80
            AggregateMessageOrigin as ParaInclusionAggregateMessageOrigin, UmpQueueId,
81
        },
82
        initializer as parachains_initializer, on_demand as parachains_assigner_on_demand,
83
        origin as parachains_origin, paras as parachains_paras,
84
        paras_inherent as parachains_paras_inherent,
85
        runtime_api_impl::{
86
            v11 as parachains_runtime_api_impl, vstaging as parachains_staging_runtime_api_impl,
87
        },
88
        scheduler as parachains_scheduler, session_info as parachains_session_info,
89
        shared as parachains_shared,
90
    },
91
    scale_info::TypeInfo,
92
    snowbridge_core::{ChannelId, PricingParameters},
93
    snowbridge_merkle_tree::MerkleProof,
94
    snowbridge_outbound_queue_primitives::v1::Command,
95
    snowbridge_outbound_queue_primitives::v1::Fee,
96
    sp_core::{storage::well_known_keys as StorageWellKnownKeys, Get},
97
    sp_core::{ConstUint, OpaqueMetadata, H256},
98
    sp_genesis_builder::PresetId,
99
    sp_runtime::{traits::ConvertInto, AccountId32},
100
    tanssi_runtime_common::{
101
        relay::{BabeGetCollatorAssignmentRandomness, BabeSlotBeacon},
102
        SessionTimer,
103
    },
104
    tp_bridge::ConvertLocation,
105
    tp_message_queue::{MessageQueueWrapper, OnQueueChangedWrapper},
106
    tp_stream_payment_common::StreamId,
107
    tp_traits::{
108
        prod_or_fast_parameter_types, EraIndex, GetHostConfiguration, GetSessionContainerChains,
109
        NodeActivityTrackingHelper, ParaIdAssignmentHooks, RegistrarHandler, Slot, SlotFrequency,
110
    },
111
    xcm::Version as XcmVersion,
112
    xcm_runtime_apis::{
113
        dry_run::{CallDryRunEffects, Error as XcmDryRunApiError, XcmDryRunEffects},
114
        fees::Error as XcmPaymentApiError,
115
    },
116
};
117

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

            
156
pub use {
157
    frame_system::Call as SystemCall,
158
    pallet_balances::Call as BalancesCall,
159
    primitives::{AccountId, Balance},
160
};
161

            
162
#[cfg(feature = "runtime-benchmarks")]
163
use {
164
    snowbridge_core::{AgentId, TokenId},
165
    xcm::latest::Junctions::*,
166
};
167

            
168
/// Constant values used within the runtime.
169
use starlight_runtime_constants::{currency::*, fee::*, snowbridge::EthereumLocation, time::*};
170

            
171
// XCM configurations.
172
pub mod xcm_config;
173

            
174
pub mod bridge_to_ethereum_config;
175

            
176
pub mod eth_chain_config;
177

            
178
// Weights
179
mod weights;
180

            
181
// Governance and configurations.
182
pub mod governance;
183
use {
184
    governance::{
185
        pallet_custom_origins, AuctionAdmin, Fellows, GeneralAdmin, Treasurer, TreasurySpender,
186
    },
187
    pallet_collator_assignment::CoreAllocationConfiguration,
188
};
189

            
190
#[cfg(test)]
191
mod tests;
192

            
193
#[cfg(not(feature = "disable-genesis-builder"))]
194
pub mod genesis_config_presets;
195

            
196
impl_runtime_weights!(starlight_runtime_constants);
197

            
198
// Make the WASM binary available.
199
#[cfg(feature = "std")]
200
include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
201

            
202
/// Runtime version (Starlight).
203
#[sp_version::runtime_version]
204
pub const VERSION: RuntimeVersion = RuntimeVersion {
205
    spec_name: Cow::Borrowed("starlight"),
206
    impl_name: Cow::Borrowed("tanssi-starlight-v2.0"),
207
    authoring_version: 0,
208
    spec_version: 1700,
209
    impl_version: 0,
210
    apis: RUNTIME_API_VERSIONS,
211
    transaction_version: 27,
212
    system_version: 1,
213
};
214

            
215
/// The BABE epoch configuration at genesis.
216
pub const BABE_GENESIS_EPOCH_CONFIG: babe_primitives::BabeEpochConfiguration =
217
    babe_primitives::BabeEpochConfiguration {
218
        c: PRIMARY_PROBABILITY,
219
        allowed_slots: babe_primitives::AllowedSlots::PrimaryAndSecondaryVRFSlots,
220
    };
221

            
222
/// Native version.
223
#[cfg(any(feature = "std", test))]
224
pub fn native_version() -> NativeVersion {
225
    NativeVersion {
226
        runtime_version: VERSION,
227
        can_author_with: Default::default(),
228
    }
229
}
230

            
231
/// Aggregate message origin for the `MessageQueue` pallet.
232
///
233
/// Can be extended to serve further use-cases besides just UMP. Is stored in storage, so any change
234
/// to existing values will require a migration.
235
#[derive(
236
    Encode,
237
    Decode,
238
    Clone,
239
    MaxEncodedLen,
240
    Eq,
241
    PartialEq,
242
    RuntimeDebug,
243
    TypeInfo,
244
    DecodeWithMemTracking,
245
)]
246
pub enum TanssiAggregateMessageOrigin {
247
    /// Inbound upward message.
248
    #[codec(index = 0)]
249
    Ump(UmpQueueId),
250

            
251
    /// The message came from a snowbridge channel. It will be processed by `snowbridge_pallet_outbound_queue`.
252
    #[codec(index = 1)]
253
    Snowbridge(ChannelId),
254

            
255
    /// The message came from a snowbridge channel, and it's a custom message that only exists in Tanssi.
256
    /// This will be processed by `CustomProcessSnowbridgeMessage`.
257
    #[codec(index = 2)]
258
    SnowbridgeTanssi(ChannelId),
259
}
260

            
261
#[cfg(feature = "runtime-benchmarks")]
262
impl From<u32> for TanssiAggregateMessageOrigin {
263
    fn from(n: u32) -> Self {
264
        // Some dummy for the benchmarks.
265
        Self::Ump(UmpQueueId::Para(n.into()))
266
    }
267
}
268

            
269
impl From<ParaInclusionAggregateMessageOrigin> for TanssiAggregateMessageOrigin {
270
13
    fn from(origin: ParaInclusionAggregateMessageOrigin) -> Self {
271
13
        let para = match origin {
272
13
            ParaInclusionAggregateMessageOrigin::Ump(UmpQueueId::Para(p)) => p,
273
        };
274
13
        Self::Ump(UmpQueueId::Para(para))
275
13
    }
276
}
277

            
278
impl TryFrom<TanssiAggregateMessageOrigin> for ParaInclusionAggregateMessageOrigin {
279
    type Error = ();
280
134
    fn try_from(origin: TanssiAggregateMessageOrigin) -> Result<Self, ()> {
281
        // Before this change we had a bug in which we entered parachains_inclusion pallet
282
        // OnQueueChanged hook with origins that where not UMP. using the OnQueueChangedWrapper
283
        // and erroring for origins that are not UMP will allow us to NOT DO ANYTHING and therefore
284
        // not enter the hook for non-desired origins
285
134
        match origin {
286
            TanssiAggregateMessageOrigin::Ump(UmpQueueId::Para(p)) => Ok(
287
                ParaInclusionAggregateMessageOrigin::Ump(UmpQueueId::Para(p)),
288
            ),
289
134
            _ => Err(()),
290
        }
291
134
    }
292
}
293

            
294
pub struct GetAggregateMessageOrigin;
295

            
296
impl Convert<ChannelId, TanssiAggregateMessageOrigin> for GetAggregateMessageOrigin {
297
21
    fn convert(channel_id: ChannelId) -> TanssiAggregateMessageOrigin {
298
21
        TanssiAggregateMessageOrigin::Snowbridge(channel_id)
299
21
    }
300
}
301

            
302
impl Convert<UmpQueueId, TanssiAggregateMessageOrigin> for GetAggregateMessageOrigin {
303
    fn convert(queue_id: UmpQueueId) -> TanssiAggregateMessageOrigin {
304
        TanssiAggregateMessageOrigin::Ump(queue_id)
305
    }
306
}
307

            
308
pub struct GetAggregateMessageOriginTanssi;
309

            
310
impl Convert<ChannelId, TanssiAggregateMessageOrigin> for GetAggregateMessageOriginTanssi {
311
51
    fn convert(channel_id: ChannelId) -> TanssiAggregateMessageOrigin {
312
51
        TanssiAggregateMessageOrigin::SnowbridgeTanssi(channel_id)
313
51
    }
314
}
315

            
316
pub struct IsDemocracyExtrinsics;
317
impl Contains<RuntimeCall> for IsDemocracyExtrinsics {
318
110
    fn contains(c: &RuntimeCall) -> bool {
319
103
        matches!(
320
110
            c,
321
            RuntimeCall::Treasury(_)
322
                | RuntimeCall::ConvictionVoting(_)
323
                | RuntimeCall::Referenda(_)
324
                | RuntimeCall::FellowshipCollective(_)
325
                | RuntimeCall::FellowshipReferenda(_)
326
                | RuntimeCall::Whitelist(_)
327
                | RuntimeCall::Preimage(_)
328
        )
329
110
    }
330
}
331

            
332
/// The relay register and deregister calls should no longer be necessary
333
/// Everything is handled by the ContainerRegistrar
334
pub struct IsRelayRegister;
335
impl Contains<RuntimeCall> for IsRelayRegister {
336
113
    fn contains(c: &RuntimeCall) -> bool {
337
112
        matches!(
338
3
            c,
339
            RuntimeCall::Registrar(paras_registrar::Call::register { .. })
340
111
        ) || matches!(
341
2
            c,
342
            RuntimeCall::Registrar(paras_registrar::Call::deregister { .. })
343
        )
344
113
    }
345
}
346

            
347
/// Starlight shouold not permit parathread registration for now
348
/// TODO: remove once they are enabled
349
pub struct IsParathreadRegistrar;
350
impl Contains<RuntimeCall> for IsParathreadRegistrar {
351
111
    fn contains(c: &RuntimeCall) -> bool {
352
110
        matches!(
353
2
            c,
354
            RuntimeCall::ContainerRegistrar(pallet_registrar::Call::register_parathread { .. })
355
        )
356
111
    }
357
}
358

            
359
parameter_types! {
360
    pub const Version: RuntimeVersion = VERSION;
361
    pub const SS58Prefix: u8 = 42;
362
}
363

            
364
#[derive_impl(frame_system::config_preludes::RelayChainDefaultConfig)]
365
impl frame_system::Config for Runtime {
366
    type BaseCallFilter = MaintenanceMode;
367
    type BlockWeights = BlockWeights;
368
    type BlockLength = BlockLength;
369
    type DbWeight = RocksDbWeight;
370
    type Nonce = Nonce;
371
    type Hash = Hash;
372
    type AccountId = AccountId;
373
    type Block = Block;
374
    type BlockHashCount = BlockHashCount;
375
    type Version = Version;
376
    type AccountData = pallet_balances::AccountData<Balance>;
377
    type SystemWeightInfo = weights::frame_system::SubstrateWeight<Runtime>;
378
    type SS58Prefix = SS58Prefix;
379
    type MaxConsumers = frame_support::traits::ConstU32<16>;
380
    type MultiBlockMigrator = MultiBlockMigrations;
381
    type ExtensionsWeightInfo = weights::frame_system_extensions::SubstrateWeight<Runtime>;
382
}
383

            
384
parameter_types! {
385
    pub MaximumSchedulerWeight: Weight = Perbill::from_percent(80) *
386
        BlockWeights::get().max_block;
387
    pub const MaxScheduledPerBlock: u32 = 50;
388
    pub const NoPreimagePostponement: Option<u32> = Some(10);
389
}
390

            
391
/// Used the compare the privilege of an origin inside the scheduler.
392
pub struct OriginPrivilegeCmp;
393

            
394
impl PrivilegeCmp<OriginCaller> for OriginPrivilegeCmp {
395
    fn cmp_privilege(left: &OriginCaller, right: &OriginCaller) -> Option<Ordering> {
396
        if left == right {
397
            return Some(Ordering::Equal);
398
        }
399

            
400
        match (left, right) {
401
            // Root is greater than anything.
402
            (OriginCaller::system(frame_system::RawOrigin::Root), _) => Some(Ordering::Greater),
403
            // For every other origin we don't care, as they are not used for `ScheduleOrigin`.
404
            _ => None,
405
        }
406
    }
407
}
408

            
409
/// Dynamic params that can be adjusted at runtime.
410
#[dynamic_params(RuntimeParameters, pallet_parameters::Parameters::<Runtime>)]
411
pub mod dynamic_params {
412
    use super::*;
413

            
414
    #[dynamic_pallet_params]
415
    #[codec(index = 0)]
416
    pub mod preimage {
417
        use super::*;
418

            
419
        #[codec(index = 0)]
420
        pub static BaseDeposit: Balance = deposit(2, 64);
421

            
422
        #[codec(index = 1)]
423
        pub static ByteDeposit: Balance = deposit(0, 1);
424
    }
425
}
426

            
427
#[cfg(feature = "runtime-benchmarks")]
428
impl Default for RuntimeParameters {
429
    fn default() -> Self {
430
        RuntimeParameters::Preimage(dynamic_params::preimage::Parameters::BaseDeposit(
431
            dynamic_params::preimage::BaseDeposit,
432
            Some(1u32.into()),
433
        ))
434
    }
435
}
436

            
437
/// Defines what origin can modify which dynamic parameters.
438
pub struct DynamicParameterOrigin;
439
impl EnsureOriginWithArg<RuntimeOrigin, RuntimeParametersKey> for DynamicParameterOrigin {
440
    type Success = ();
441

            
442
    fn try_origin(
443
        origin: RuntimeOrigin,
444
        key: &RuntimeParametersKey,
445
    ) -> Result<Self::Success, RuntimeOrigin> {
446
        use crate::RuntimeParametersKey::*;
447

            
448
        match key {
449
            Preimage(_) => frame_system::ensure_root(origin.clone()),
450
        }
451
        .map_err(|_| origin)
452
    }
453

            
454
    #[cfg(feature = "runtime-benchmarks")]
455
    fn try_successful_origin(_key: &RuntimeParametersKey) -> Result<RuntimeOrigin, ()> {
456
        // Provide the origin for the parameter returned by `Default`:
457
        Ok(RuntimeOrigin::root())
458
    }
459
}
460

            
461
impl pallet_scheduler::Config for Runtime {
462
    type RuntimeOrigin = RuntimeOrigin;
463
    type RuntimeEvent = RuntimeEvent;
464
    type PalletsOrigin = OriginCaller;
465
    type RuntimeCall = RuntimeCall;
466
    type MaximumWeight = MaximumSchedulerWeight;
467
    // The goal of having ScheduleOrigin include AuctionAdmin is to allow the auctions track of
468
    // OpenGov to schedule periodic auctions.
469
    type ScheduleOrigin = EitherOf<EnsureRoot<AccountId>, AuctionAdmin>;
470
    type MaxScheduledPerBlock = MaxScheduledPerBlock;
471
    type WeightInfo = weights::pallet_scheduler::SubstrateWeight<Runtime>;
472
    type OriginPrivilegeCmp = OriginPrivilegeCmp;
473
    type Preimages = Preimage;
474
    type BlockNumberProvider = System;
475
}
476

            
477
parameter_types! {
478
    pub const PreimageHoldReason: RuntimeHoldReason = RuntimeHoldReason::Preimage(pallet_preimage::HoldReason::Preimage);
479
}
480

            
481
impl pallet_preimage::Config for Runtime {
482
    type WeightInfo = weights::pallet_preimage::SubstrateWeight<Runtime>;
483
    type RuntimeEvent = RuntimeEvent;
484
    type Currency = Balances;
485
    type ManagerOrigin = EnsureRoot<AccountId>;
486
    type Consideration = HoldConsideration<
487
        AccountId,
488
        Balances,
489
        PreimageHoldReason,
490
        LinearStoragePrice<
491
            dynamic_params::preimage::BaseDeposit,
492
            dynamic_params::preimage::ByteDeposit,
493
            Balance,
494
        >,
495
    >;
496
}
497

            
498
parameter_types! {
499
    pub const ExpectedBlockTime: Moment = MILLISECS_PER_BLOCK;
500
    pub ReportLongevity: u64 = u64::from(EpochDurationInBlocks::get()) * 10;
501
}
502

            
503
impl pallet_babe::Config for Runtime {
504
    type EpochDuration = EpochDurationInBlocks;
505
    type ExpectedBlockTime = ExpectedBlockTime;
506
    // session module is the trigger
507
    type EpochChangeTrigger = pallet_babe::ExternalTrigger;
508
    type DisabledValidators = Session;
509
    // Not benchmarked in Kusama
510
    type WeightInfo = ();
511
    type MaxAuthorities = MaxAuthorities;
512
    type MaxNominators = ConstU32<0>;
513
    type KeyOwnerProof = sp_session::MembershipProof;
514
    type EquivocationReportSystem =
515
        pallet_babe::EquivocationReportSystem<Self, Offences, Historical, ReportLongevity>;
516
}
517

            
518
parameter_types! {
519
    pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT;
520
    pub const MaxLocks: u32 = 50;
521
    pub const MaxReserves: u32 = 50;
522
}
523

            
524
impl pallet_balances::Config for Runtime {
525
    type Balance = Balance;
526
    type DustRemoval = ();
527
    type RuntimeEvent = RuntimeEvent;
528
    type ExistentialDeposit = ExistentialDeposit;
529
    type AccountStore = System;
530
    type MaxLocks = MaxLocks;
531
    type MaxReserves = MaxReserves;
532
    type ReserveIdentifier = [u8; 8];
533
    type WeightInfo = weights::pallet_balances::SubstrateWeight<Runtime>;
534
    type FreezeIdentifier = ();
535
    type RuntimeHoldReason = RuntimeHoldReason;
536
    type RuntimeFreezeReason = RuntimeFreezeReason;
537
    type MaxFreezes = ConstU32<1>;
538
    type DoneSlashHandler = ();
539
}
540

            
541
parameter_types! {
542
    pub const TransactionByteFee: Balance = 10 * MILLICENTS;
543
    /// This value increases the priority of `Operational` transactions by adding
544
    /// a "virtual tip" that's equal to the `OperationalFeeMultiplier * final_fee`.
545
    pub const OperationalFeeMultiplier: u8 = 5;
546
}
547

            
548
impl pallet_transaction_payment::Config for Runtime {
549
    type RuntimeEvent = RuntimeEvent;
550
    type OnChargeTransaction =
551
        FungibleAdapter<Balances, tanssi_runtime_common::DealWithFees<Runtime>>;
552
    type OperationalFeeMultiplier = OperationalFeeMultiplier;
553
    type WeightToFee = WeightToFee;
554
    type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;
555
    type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Self>;
556
    type WeightInfo = weights::pallet_transaction_payment::SubstrateWeight<Runtime>;
557
}
558

            
559
parameter_types! {
560
    pub const MinimumPeriod: u64 = SLOT_DURATION / 2;
561
}
562
impl pallet_timestamp::Config for Runtime {
563
    type Moment = u64;
564
    type OnTimestampSet = Babe;
565
    type MinimumPeriod = MinimumPeriod;
566
    type WeightInfo = weights::pallet_timestamp::SubstrateWeight<Runtime>;
567
}
568

            
569
pub struct RewardPoints;
570

            
571
impl pallet_authorship::EventHandler<AccountId, BlockNumberFor<Runtime>> for RewardPoints {
572
3776
    fn note_author(author: AccountId) {
573
3776
        let whitelisted_validators =
574
3776
            pallet_external_validators::WhitelistedValidatorsActiveEra::<Runtime>::get();
575
        // Do not reward whitelisted validators
576
3776
        if !whitelisted_validators.contains(&author) {
577
220
            ExternalValidatorsRewards::reward_by_ids(vec![(author, 20u32)])
578
3556
        }
579
3776
    }
580
}
581

            
582
impl pallet_authorship::Config for Runtime {
583
    type FindAuthor = pallet_session::FindAccountFromAuthorIndex<Self, Babe>;
584
    type EventHandler = RewardPoints;
585
}
586

            
587
impl_opaque_keys! {
588
    pub struct SessionKeys {
589
        pub grandpa: Grandpa,
590
        pub babe: Babe,
591
        pub para_validator: Initializer,
592
        pub para_assignment: ParaSessionInfo,
593
        pub authority_discovery: AuthorityDiscovery,
594
        pub beefy: Beefy,
595
        pub nimbus: TanssiInitializer,
596
    }
597
}
598

            
599
/// Special `ValidatorIdOf` implementation that is just returning the input as result.
600
pub struct ValidatorIdOf;
601
impl sp_runtime::traits::Convert<AccountId, Option<AccountId>> for ValidatorIdOf {
602
146
    fn convert(a: AccountId) -> Option<AccountId> {
603
146
        Some(a)
604
146
    }
605
}
606

            
607
impl pallet_session::Config for Runtime {
608
    type RuntimeEvent = RuntimeEvent;
609
    type ValidatorId = AccountId;
610
    type ValidatorIdOf = ValidatorIdOf;
611
    type ShouldEndSession = Babe;
612
    type NextSessionRotation = Babe;
613
    type SessionManager = pallet_session::historical::NoteHistoricalRoot<Self, ExternalValidators>;
614
    type SessionHandler = <SessionKeys as OpaqueKeys>::KeyTypeIdProviders;
615
    type Keys = SessionKeys;
616
    type WeightInfo = weights::pallet_session::SubstrateWeight<Runtime>;
617
    type DisablingStrategy = ();
618
}
619

            
620
pub struct FullIdentificationOf;
621
impl Convert<AccountId, Option<()>> for FullIdentificationOf {
622
782
    fn convert(_: AccountId) -> Option<()> {
623
782
        Some(())
624
782
    }
625
}
626

            
627
impl pallet_session::historical::Config for Runtime {
628
    type RuntimeEvent = RuntimeEvent;
629
    type FullIdentification = ();
630
    type FullIdentificationOf = FullIdentificationOf;
631
}
632

            
633
parameter_types! {
634
    pub const BondingDuration: sp_staking::EraIndex = runtime_common::prod_or_fast!(28, 3);
635
}
636

            
637
parameter_types! {
638
    pub const ProposalBond: Permill = Permill::from_percent(5);
639
    pub const ProposalBondMinimum: Balance = 2000 * CENTS;
640
    pub const ProposalBondMaximum: Balance = 1 * GRAND;
641
    // We allow it to be 1 minute in fast mode to be able to test it
642
    pub const SpendPeriod: BlockNumber = runtime_common::prod_or_fast!(6 * DAYS, 1 * MINUTES);
643
    pub const TreasuryPalletId: PalletId = PalletId(*b"py/trsry");
644
    pub const PayoutSpendPeriod: BlockNumber = 30 * DAYS;
645
    // The asset's interior location for the paying account. This is the Treasury
646
    // pallet instance (which sits at index 18).
647
    pub TreasuryInteriorLocation: InteriorLocation = PalletInstance(18).into();
648

            
649
    pub const TipCountdown: BlockNumber = 1 * DAYS;
650
    pub const TipFindersFee: Percent = Percent::from_percent(20);
651
    pub const TipReportDepositBase: Balance = 100 * CENTS;
652
    pub const DataDepositPerByte: Balance = 1 * CENTS;
653
    pub const MaxApprovals: u32 = 100;
654
    pub const MaxAuthorities: u32 = 100_000;
655
    pub const MaxKeys: u32 = 10_000;
656
    pub const MaxPeerInHeartbeats: u32 = 10_000;
657
    pub const MaxBalance: Balance = Balance::MAX;
658
    pub TreasuryAccount: AccountId = Treasury::account_id();
659
    pub SnowbridgeFeesAccount: AccountId = PalletId(*b"sb/feeac").into_account_truncating();
660
}
661

            
662
#[cfg(feature = "runtime-benchmarks")]
663
pub struct TreasuryBenchmarkHelper<T>(PhantomData<T>);
664

            
665
#[cfg(feature = "runtime-benchmarks")]
666
use frame_support::traits::Currency;
667
#[cfg(feature = "runtime-benchmarks")]
668
use pallet_treasury::ArgumentsFactory;
669
use {
670
    frame_support::traits::{
671
        ExistenceRequirement, OnUnbalanced, ValidatorRegistration, WithdrawReasons,
672
    },
673
    pallet_services_payment::BalanceOf,
674
    runtime_parachains::configuration::HostConfiguration,
675
    sp_runtime::{DispatchError, TransactionOutcome},
676
};
677

            
678
#[cfg(feature = "runtime-benchmarks")]
679
impl<T> ArgumentsFactory<(), T::AccountId> for TreasuryBenchmarkHelper<T>
680
where
681
    T: pallet_treasury::Config,
682
    T::AccountId: From<[u8; 32]>,
683
{
684
    fn create_asset_kind(_seed: u32) {}
685

            
686
    fn create_beneficiary(seed: [u8; 32]) -> T::AccountId {
687
        let account: T::AccountId = seed.into();
688
        let balance = T::Currency::minimum_balance();
689
        let _ = T::Currency::make_free_balance_be(&account, balance);
690
        account
691
    }
692
}
693

            
694
impl pallet_treasury::Config for Runtime {
695
    type PalletId = TreasuryPalletId;
696
    type Currency = Balances;
697
    type RejectOrigin = EitherOfDiverse<EnsureRoot<AccountId>, Treasurer>;
698
    type RuntimeEvent = RuntimeEvent;
699
    type SpendPeriod = SpendPeriod;
700
    type Burn = ();
701
    type BurnDestination = ();
702
    type MaxApprovals = MaxApprovals;
703
    type WeightInfo = weights::pallet_treasury::SubstrateWeight<Runtime>;
704
    type SpendFunds = ();
705
    type SpendOrigin = TreasurySpender;
706
    type AssetKind = ();
707
    type Beneficiary = AccountId;
708
    type BeneficiaryLookup = IdentityLookup<Self::Beneficiary>;
709
    type Paymaster = PayFromAccount<Balances, TreasuryAccount>;
710
    type BalanceConverter = UnityAssetBalanceConversion;
711
    type PayoutPeriod = PayoutSpendPeriod;
712
    type BlockNumberProvider = System;
713
    #[cfg(feature = "runtime-benchmarks")]
714
    type BenchmarkHelper = TreasuryBenchmarkHelper<Runtime>;
715
}
716

            
717
impl pallet_offences::Config for Runtime {
718
    type RuntimeEvent = RuntimeEvent;
719
    type IdentificationTuple = pallet_session::historical::IdentificationTuple<Self>;
720
    type OnOffenceHandler = ExternalValidatorSlashes;
721
}
722

            
723
impl pallet_authority_discovery::Config for Runtime {
724
    type MaxAuthorities = MaxAuthorities;
725
}
726

            
727
parameter_types! {
728
    pub const MaxSetIdSessionEntries: u32 = BondingDuration::get() * SessionsPerEra::get();
729
}
730

            
731
impl pallet_grandpa::Config for Runtime {
732
    type RuntimeEvent = RuntimeEvent;
733
    // Not benchmarked in Kusama, benchmarking code also don't match WeightInfo trait.
734
    type WeightInfo = ();
735
    type MaxAuthorities = MaxAuthorities;
736
    type MaxNominators = ConstU32<0>;
737
    type MaxSetIdSessionEntries = MaxSetIdSessionEntries;
738
    type KeyOwnerProof = sp_session::MembershipProof;
739
    type EquivocationReportSystem =
740
        pallet_grandpa::EquivocationReportSystem<Self, Offences, Historical, ReportLongevity>;
741
}
742

            
743
/// Submits a transaction with the node's public and signature type. Adheres to the signed extension
744
/// format of the chain.
745
impl<LocalCall> frame_system::offchain::CreateSignedTransaction<LocalCall> for Runtime
746
where
747
    RuntimeCall: From<LocalCall>,
748
{
749
    fn create_signed_transaction<
750
        C: frame_system::offchain::AppCrypto<Self::Public, Self::Signature>,
751
    >(
752
        call: RuntimeCall,
753
        public: <Signature as Verify>::Signer,
754
        account: AccountId,
755
        nonce: <Runtime as frame_system::Config>::Nonce,
756
    ) -> Option<UncheckedExtrinsic> {
757
        use sp_runtime::traits::StaticLookup;
758
        // take the biggest period possible.
759
        let period = u64::from(
760
            BlockHashCount::get()
761
                .checked_next_power_of_two()
762
                .map(|c| c / 2)
763
                .unwrap_or(2),
764
        );
765

            
766
        let current_block = System::block_number()
767
            .saturated_into::<u64>()
768
            // The `System::block_number` is initialized with `n+1`,
769
            // so the actual block number is `n`.
770
            .saturating_sub(1);
771
        let tip = 0;
772
        let tx_ext: TxExtension = (
773
            frame_system::CheckNonZeroSender::<Runtime>::new(),
774
            frame_system::CheckSpecVersion::<Runtime>::new(),
775
            frame_system::CheckTxVersion::<Runtime>::new(),
776
            frame_system::CheckGenesis::<Runtime>::new(),
777
            frame_system::CheckMortality::<Runtime>::from(generic::Era::mortal(
778
                period,
779
                current_block,
780
            )),
781
            frame_system::CheckNonce::<Runtime>::from(nonce),
782
            frame_system::CheckWeight::<Runtime>::new(),
783
            pallet_transaction_payment::ChargeTransactionPayment::<Runtime>::from(tip),
784
            //cumulus_primitives_storage_weight_reclaim::StorageWeightReclaim::<Runtime>::new(),
785
            frame_metadata_hash_extension::CheckMetadataHash::new(true),
786
            frame_system::WeightReclaim::new(),
787
        );
788
        let raw_payload = SignedPayload::new(call, tx_ext)
789
            .map_err(|e| {
790
                log::warn!("Unable to create signed payload: {:?}", e);
791
            })
792
            .ok()?;
793
        let signature = raw_payload.using_encoded(|payload| C::sign(payload, public))?;
794
        let (call, tx_ext, _) = raw_payload.deconstruct();
795
        let address = <Runtime as frame_system::Config>::Lookup::unlookup(account);
796
        let transaction = UncheckedExtrinsic::new_signed(call, address, signature, tx_ext);
797
        Some(transaction)
798
    }
799
}
800

            
801
impl frame_system::offchain::SigningTypes for Runtime {
802
    type Public = <Signature as Verify>::Signer;
803
    type Signature = Signature;
804
}
805

            
806
impl<C> frame_system::offchain::CreateTransactionBase<C> for Runtime
807
where
808
    RuntimeCall: From<C>,
809
{
810
    type Extrinsic = UncheckedExtrinsic;
811
    type RuntimeCall = RuntimeCall;
812
}
813

            
814
impl<LocalCall> frame_system::offchain::CreateBare<LocalCall> for Runtime
815
where
816
    RuntimeCall: From<LocalCall>,
817
{
818
    fn create_bare(call: RuntimeCall) -> UncheckedExtrinsic {
819
        UncheckedExtrinsic::new_bare(call)
820
    }
821
}
822

            
823
parameter_types! {
824
    // Minimum 100 bytes/STAR deposited (1 CENT/byte)
825
    pub const BasicDeposit: Balance = 1000 * CENTS;       // 258 bytes on-chain
826
    pub const ByteDeposit: Balance = deposit(0, 1);
827
    pub const UsernameDeposit: Balance = deposit(0, 32);
828
    pub const SubAccountDeposit: Balance = 200 * CENTS;   // 53 bytes on-chain
829
    pub const MaxSubAccounts: u32 = 100;
830
    pub const MaxAdditionalFields: u32 = 100;
831
    pub const MaxRegistrars: u32 = 20;
832
}
833

            
834
impl pallet_identity::Config for Runtime {
835
    type RuntimeEvent = RuntimeEvent;
836
    type Currency = Balances;
837
    type BasicDeposit = BasicDeposit;
838
    type ByteDeposit = ByteDeposit;
839
    type UsernameDeposit = UsernameDeposit;
840
    type SubAccountDeposit = SubAccountDeposit;
841
    type MaxSubAccounts = MaxSubAccounts;
842
    type IdentityInformation = IdentityInfo<MaxAdditionalFields>;
843
    type MaxRegistrars = MaxRegistrars;
844
    type Slashed = Treasury;
845
    type ForceOrigin = EitherOf<EnsureRoot<Self::AccountId>, GeneralAdmin>;
846
    type RegistrarOrigin = EitherOf<EnsureRoot<Self::AccountId>, GeneralAdmin>;
847
    type OffchainSignature = Signature;
848
    type SigningPublicKey = <Signature as Verify>::Signer;
849
    type UsernameAuthorityOrigin = EnsureRoot<Self::AccountId>;
850
    type PendingUsernameExpiration = ConstU32<{ 7 * DAYS }>;
851
    type UsernameGracePeriod = ConstU32<{ 30 * DAYS }>;
852
    type MaxSuffixLength = ConstU32<7>;
853
    type MaxUsernameLength = ConstU32<32>;
854
    #[cfg(feature = "runtime-benchmarks")]
855
    type BenchmarkHelper = ();
856
    type WeightInfo = weights::pallet_identity::SubstrateWeight<Runtime>;
857
}
858

            
859
impl pallet_utility::Config for Runtime {
860
    type RuntimeEvent = RuntimeEvent;
861
    type RuntimeCall = RuntimeCall;
862
    type PalletsOrigin = OriginCaller;
863
    type WeightInfo = weights::pallet_utility::SubstrateWeight<Runtime>;
864
}
865

            
866
parameter_types! {
867
    // One storage item; key size is 32; value is size 4+4+16+32 bytes = 56 bytes.
868
    pub const DepositBase: Balance = deposit(1, 88);
869
    // Additional storage item size of 32 bytes.
870
    pub const DepositFactor: Balance = deposit(0, 32);
871
    pub const MaxSignatories: u32 = 100;
872
}
873

            
874
impl pallet_multisig::Config for Runtime {
875
    type RuntimeEvent = RuntimeEvent;
876
    type RuntimeCall = RuntimeCall;
877
    type Currency = Balances;
878
    type DepositBase = DepositBase;
879
    type DepositFactor = DepositFactor;
880
    type MaxSignatories = MaxSignatories;
881
    type WeightInfo = weights::pallet_multisig::SubstrateWeight<Runtime>;
882
    type BlockNumberProvider = System;
883
}
884

            
885
parameter_types! {
886
    // One storage item; key size 32, value size 8; .
887
    pub const ProxyDepositBase: Balance = deposit(1, 8);
888
    // Additional storage item size of 33 bytes.
889
    pub const ProxyDepositFactor: Balance = deposit(0, 33);
890
    pub const MaxProxies: u16 = 32;
891
    pub const AnnouncementDepositBase: Balance = deposit(1, 8);
892
    pub const AnnouncementDepositFactor: Balance = deposit(0, 66);
893
    pub const MaxPending: u16 = 32;
894
}
895

            
896
/// The type used to represent the kinds of proxying allowed.
897
#[derive(
898
    Copy,
899
    Clone,
900
    Eq,
901
    PartialEq,
902
    Ord,
903
    PartialOrd,
904
    Encode,
905
    Decode,
906
    RuntimeDebug,
907
    MaxEncodedLen,
908
    DecodeWithMemTracking,
909
    TypeInfo,
910
)]
911
pub enum ProxyType {
912
    Any,
913
    NonTransfer,
914
    Governance,
915
    IdentityJudgement,
916
    CancelProxy,
917
    Auction,
918
    OnDemandOrdering,
919
    SudoRegistrar,
920
    SudoValidatorManagement,
921
    SessionKeyManagement,
922
    Staking,
923
    Balances,
924
}
925
impl Default for ProxyType {
926
    fn default() -> Self {
927
        Self::Any
928
    }
929
}
930
impl InstanceFilter<RuntimeCall> for ProxyType {
931
    fn filter(&self, c: &RuntimeCall) -> bool {
932
        match self {
933
            ProxyType::Any => true,
934
            ProxyType::NonTransfer => match c {
935
                RuntimeCall::Identity(
936
                    pallet_identity::Call::add_sub { .. } | pallet_identity::Call::set_subs { .. },
937
                ) => false,
938
                call => {
939
                    matches!(
940
                        call,
941
                        RuntimeCall::System(..) |
942
				RuntimeCall::Babe(..) |
943
				RuntimeCall::Timestamp(..) |
944
				// Specifically omitting Indices `transfer`, `force_transfer`
945
				// Specifically omitting the entire Balances pallet
946
				RuntimeCall::Session(..) |
947
				RuntimeCall::Grandpa(..) |
948
				RuntimeCall::Treasury(..) |
949
				RuntimeCall::ConvictionVoting(..) |
950
				RuntimeCall::Referenda(..) |
951
				RuntimeCall::FellowshipCollective(..) |
952
				RuntimeCall::FellowshipReferenda(..) |
953
				RuntimeCall::Whitelist(..) |
954
				RuntimeCall::Utility(..) |
955
				RuntimeCall::Identity(..) |
956
				RuntimeCall::Scheduler(..) |
957
				RuntimeCall::Proxy(..) |
958
                RuntimeCall::PooledStaking(..) |
959
				RuntimeCall::Multisig(..) |
960
				RuntimeCall::Registrar(paras_registrar::Call::register {..}) |
961
				RuntimeCall::Registrar(paras_registrar::Call::deregister {..}) |
962
				// Specifically omitting Registrar `swap`
963
				RuntimeCall::Registrar(paras_registrar::Call::reserve {..})
964
                    )
965
                }
966
            },
967
            ProxyType::Governance => matches!(
968
                c,
969
                RuntimeCall::Utility(..) |
970
					// OpenGov calls
971
					RuntimeCall::ConvictionVoting(..) |
972
					RuntimeCall::Referenda(..) |
973
					RuntimeCall::FellowshipCollective(..) |
974
					RuntimeCall::FellowshipReferenda(..) |
975
					RuntimeCall::Whitelist(..)
976
            ),
977
            ProxyType::IdentityJudgement => matches!(
978
                c,
979
                RuntimeCall::Identity(pallet_identity::Call::provide_judgement { .. })
980
                    | RuntimeCall::Utility(..)
981
            ),
982
            ProxyType::CancelProxy => {
983
                matches!(
984
                    c,
985
                    RuntimeCall::Proxy(pallet_proxy::Call::reject_announcement { .. })
986
                )
987
            }
988
            ProxyType::Auction => {
989
                matches!(c, RuntimeCall::Registrar { .. } | RuntimeCall::Multisig(..))
990
            }
991
            ProxyType::OnDemandOrdering => matches!(c, RuntimeCall::OnDemandAssignmentProvider(..)),
992
            ProxyType::SudoRegistrar => match c {
993
                RuntimeCall::Sudo(pallet_sudo::Call::sudo { call: ref x }) => {
994
                    matches!(
995
                        x.as_ref(),
996
                        &RuntimeCall::DataPreservers(..)
997
                            | &RuntimeCall::Registrar(..)
998
                            | &RuntimeCall::ContainerRegistrar(..)
999
                            | &RuntimeCall::Paras(..)
                            | &RuntimeCall::ParasSudoWrapper(..)
                    )
                }
                _ => false,
            },
            ProxyType::SudoValidatorManagement => match c {
                RuntimeCall::Sudo(pallet_sudo::Call::sudo { call: ref x }) => {
                    matches!(
                        x.as_ref(),
                        &RuntimeCall::ExternalValidators(..)
                            | &RuntimeCall::ExternalValidatorSlashes(..)
                    )
                }
                _ => false,
            },
            ProxyType::SessionKeyManagement => {
                matches!(c, RuntimeCall::Session(..))
            }
            ProxyType::Staking => {
                matches!(c, RuntimeCall::Session(..) | RuntimeCall::PooledStaking(..))
            }
            ProxyType::Balances => {
                matches!(c, RuntimeCall::Balances(..))
            }
        }
    }
    fn is_superset(&self, o: &Self) -> bool {
        match (self, o) {
            (x, y) if x == y => true,
            (ProxyType::Any, _) => true,
            (_, ProxyType::Any) => false,
            (ProxyType::NonTransfer, _) => true,
            _ => false,
        }
    }
}
impl pallet_proxy::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type RuntimeCall = RuntimeCall;
    type Currency = Balances;
    type ProxyType = ProxyType;
    type ProxyDepositBase = ProxyDepositBase;
    type ProxyDepositFactor = ProxyDepositFactor;
    type MaxProxies = MaxProxies;
    type WeightInfo = weights::pallet_proxy::SubstrateWeight<Runtime>;
    type MaxPending = MaxPending;
    type CallHasher = BlakeTwo256;
    type AnnouncementDepositBase = AnnouncementDepositBase;
    type AnnouncementDepositFactor = AnnouncementDepositFactor;
    type BlockNumberProvider = System;
}
impl parachains_origin::Config for Runtime {}
impl parachains_configuration::Config for Runtime {
    type WeightInfo = weights::runtime_parachains_configuration::SubstrateWeight<Runtime>;
}
impl parachains_shared::Config for Runtime {
    type DisabledValidators = Session;
}
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 MessageQueue = MessageQueueWrapper<
        ParaInclusionAggregateMessageOrigin,
        TanssiAggregateMessageOrigin,
        MessageQueue,
    >;
    type WeightInfo = weights::runtime_parachains_inclusion::SubstrateWeight<Runtime>;
}
parameter_types! {
    pub const ParasUnsignedPriority: TransactionPriority = TransactionPriority::MAX;
}
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 = ();
    type Fungible = Balances;
    // TODO: this could be set to 1 because we don't care, but benchmarks fail in that case
    // Per day the cooldown is removed earlier, it should cost 1000.
    type CooldownRemovalMultiplier = ConstUint<{ 1000 * UNITS / DAYS as u128 }>;
    type AuthorizeCurrentCodeOrigin = EnsureRoot<Self::AccountId>;
}
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 = TanssiAggregateMessageOrigin;
65
    fn process_message(
65
        message: &[u8],
65
        origin: Self::Origin,
65
        meter: &mut WeightMeter,
65
        id: &mut [u8; 32],
65
    ) -> Result<bool, ProcessMessageError> {
65
        match origin {
            TanssiAggregateMessageOrigin::Ump(UmpQueueId::Para(para)) => {
                xcm_builder::ProcessXcmMessage::<
                    Junction,
                    xcm_executor::XcmExecutor<xcm_config::XcmConfig>,
                    RuntimeCall,
                >::process_message(
                    message, Junction::Parachain(para.into()), meter, id
                )
            }
            TanssiAggregateMessageOrigin::Snowbridge(_) => {
12
                snowbridge_pallet_outbound_queue::Pallet::<Runtime>::process_message(
12
                    message, origin, meter, id,
                )
            }
            TanssiAggregateMessageOrigin::SnowbridgeTanssi(_) => {
53
                tp_bridge::TanssiOutboundEthMessageProcessorV1::<Runtime>::process_message(
53
                    message, origin, meter, id,
                )
            }
        }
65
    }
}
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<TanssiAggregateMessageOrigin>;
    type QueueChangeHandler = OnQueueChangedWrapper<
        TanssiAggregateMessageOrigin,
        ParaInclusionAggregateMessageOrigin,
        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
{
2792
    fn pop_assignment_for_core(core_idx: CoreIndex) -> Option<Assignment> {
2792
        let assigned_collators = TanssiCollatorAssignment::collator_container_chain();
2792
        let assigned_paras: Vec<ParaId> = assigned_collators
2792
            .container_chains
2792
            .iter()
2792
            .filter_map(|(&para_id, collators)| {
1294
                if Paras::is_parachain(para_id) && !collators.is_empty() {
678
                    Some(para_id)
                } else {
616
                    None
                }
1294
            })
2792
            .collect();
2792
        log::debug!("pop assigned collators {:?}", assigned_paras);
2792
        log::debug!("looking for core idx {:?}", core_idx);
2792
        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
5
            let assignment =
2722
                parachains_assigner_on_demand::Pallet::<Runtime>::pop_assignment_for_core(
2722
                    core_idx,
2717
                )?;
            // Let's check that we have collators before allowing an assignment
5
            if !assigned_collators
5
                .container_chains
5
                .get(&assignment.para_id())
5
                .unwrap_or(&vec![])
5
                .is_empty()
            {
4
                Some(assignment)
            } else {
1
                None
            }
        }
2792
    }
9
    fn report_processed(assignment: Assignment) {
9
        match assignment {
            Assignment::Pool {
4
                para_id,
4
                core_index,
4
            } => parachains_assigner_on_demand::Pallet::<Runtime>::report_processed(
4
                para_id, core_index,
            ),
5
            Assignment::Bulk(_) => {}
        }
9
    }
    /// 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 = 1000 * 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! {
    // 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 {
3773
    fn extra_data() -> LeafExtraData {
3773
        let mut para_heads: Vec<(u32, Vec<u8>)> = parachains_paras::Parachains::<Runtime>::get()
3773
            .into_iter()
3773
            .filter_map(|id| {
3240
                parachains_paras::Heads::<Runtime>::get(id).map(|head| (id.into(), head.0))
3240
            })
3773
            .collect();
3773
        para_heads.sort();
3773
        let para_heads_root = binary_merkle_tree::merkle_root::<mmr::Hashing, _>(
3773
            para_heads.into_iter().map(|pair| pair.encode()),
        );
3773
        let commitment_root =
3773
            OutboundMessageCommitmentRecorder::take_commitment_root().unwrap_or_default();
3773
        LeafExtraData {
3773
            para_heads_root,
3773
            commitment_root,
3773
        }
3773
    }
}
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, pallet_staking::SessionInterface};
pub struct StarlightSessionInterface;
impl SessionInterface<AccountId> for StarlightSessionInterface {
    fn report_offence(validator: AccountId, severity: OffenceSeverity) {
        Session::report_offence(validator, severity);
    }
    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: 4, fast: 3 };
    pub const SlashDeferDuration: EraIndex = { prod: 0, fast: 0 };
}
impl pallet_external_validators::Config for Runtime {
    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 Mainnet.
    // Output is: 204dfe37731e8e2b4866ad0da9a17c49f434542c3477c5f914a3349acd88ba1a
    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 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::TanssiEthMessageValidatorV1<Runtime>;
    type OutboundQueue =
        tp_bridge::TanssiEthMessageSenderV1<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 ValidatorId = AccountId;
    type ValidatorIdOf = ValidatorIdOf;
    type SlashDeferDuration = SlashDeferDuration;
    type BondingDuration = BondingDuration;
    type SlashId = u32;
    type SessionInterface = StarlightSessionInterface;
    type EraIndexProvider = ExternalValidators;
    type InvulnerablesProvider = ExternalValidators;
    type ValidateMessage = tp_bridge::TanssiEthMessageValidatorV1<Runtime>;
    type OutboundQueue =
        tp_bridge::TanssiEthMessageSenderV1<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 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.
1381
    fn session_index() -> SessionIndex {
1381
        Session::current_index()
1381
    }
    #[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 MigrationsList = (tanssi_runtime_common::migrations::StarlightMigrations<Runtime>,);
    type XcmExecutionManager = ();
}
parameter_types! {
    pub MbmServiceWeight: Weight = Perbill::from_percent(80) * BlockWeights::get().max_block;
}
impl pallet_multiblock_migrations::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    #[cfg(not(feature = "runtime-benchmarks"))]
    type Migrations = ();
    // Benchmarks need mocked migrations to guarantee that they succeed.
    #[cfg(feature = "runtime-benchmarks")]
    type Migrations = pallet_multiblock_migrations::mock_helpers::MockedMigrations;
    type CursorMaxLen = ConstU32<65_536>;
    type IdentifierMaxLen = ConstU32<256>;
    type MigrationStatusHandler = ();
    type FailedMigrationHandler = MaintenanceMode;
    type MaxServiceWeight = MbmServiceWeight;
    type WeightInfo = weights::pallet_multiblock_migrations::SubstrateWeight<Runtime>;
}
/// Maintenance mode Call filter
pub struct MaintenanceFilter;
impl Contains<RuntimeCall> for MaintenanceFilter {
    fn contains(c: &RuntimeCall) -> bool {
        !matches!(
            c,
            RuntimeCall::Balances(..)
                | RuntimeCall::Registrar(..)
                | RuntimeCall::Session(..)
                | RuntimeCall::System(..)
                | RuntimeCall::PooledStaking(..)
                | RuntimeCall::Utility(..)
                | RuntimeCall::Identity(..)
                | RuntimeCall::XcmPallet(..)
                | RuntimeCall::EthereumBeaconClient(..)
                | RuntimeCall::EthereumSystem(..)
                | RuntimeCall::EthereumTokenTransfers(..)
                | RuntimeCall::OnDemandAssignmentProvider(..)
                | RuntimeCall::ContainerRegistrar(..)
                | RuntimeCall::ServicesPayment(..)
                | RuntimeCall::DataPreservers(..)
                | RuntimeCall::Hrmp(..)
                | RuntimeCall::AssetRate(..)
                | RuntimeCall::StreamPayment(..)
        )
    }
}
/// Normal Call Filter
type NormalFilter = EverythingBut<(
    IsRelayRegister,
    IsParathreadRegistrar,
    IsDemocracyExtrinsics,
)>;
impl pallet_maintenance_mode::Config for Runtime {
    type NormalCallFilter = NormalFilter;
    type MaintenanceCallFilter = InsideBoth<MaintenanceFilter, NormalFilter>;
    type MaintenanceOrigin = EnsureRoot<AccountId>;
    type XcmExecutionManager = ();
}
pub const FIXED_BLOCK_PRODUCTION_COST: u128 = 30000 * MICROUNITS;
pub const FIXED_COLLATOR_ASSIGNMENT_COST: u128 = 50 * UNITS;
pub struct BlockProductionCost<Runtime>(PhantomData<Runtime>);
impl ProvideBlockProductionCost<Runtime> for BlockProductionCost<Runtime> {
811
    fn block_cost(_para_id: &ParaId) -> (u128, Weight) {
811
        (FIXED_BLOCK_PRODUCTION_COST, Weight::zero())
811
    }
}
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 {
    /// 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 =
        EitherOfDiverse<pallet_registrar::EnsureSignedByManager<Runtime>, 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 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 MaxNodeUrlCount: u32 = 4;
    #[derive(Clone)]
    pub const MaxStringLen: u32 = 200;
}
pub type DataPreserversProfileId = u64;
impl pallet_data_preservers::Config for Runtime {
    type RuntimeHoldReason = RuntimeHoldReason;
    type Currency = Balances;
    type WeightInfo = weights::pallet_data_preservers::SubstrateWeight<Runtime>;
    type ProfileId = DataPreserversProfileId;
    type ProfileDeposit = tp_traits::BytesDeposit<ProfileDepositBaseFee, ProfileDepositByteFee>;
    type AssignmentProcessor = tp_data_preservers_common::AssignmentProcessor<Runtime>;
    type AssignmentOrigin = pallet_registrar::EnsureSignedByManager<Runtime>;
    type ForceSetProfileOrigin = EnsureRoot<AccountId>;
    type MaxAssignmentsPerParaId = MaxAssignmentsPerParaId;
    type MaxNodeUrlCount = MaxNodeUrlCount;
    type MaxStringLen = MaxStringLen;
    type MaxParaIdsVecLen = MaxLengthParaIds;
}
parameter_types! {
    pub StarlightBondAccount: AccountId32 = PalletId(*b"StarBond").into_account_truncating();
    pub PendingRewardsAccount: AccountId32 = PalletId(*b"PENDREWD").into_account_truncating();
    // Parachain bond: 1.5% out of 100%, so staking gets 2% out of 100%,
    // so staking gets 2/3.5 fracion of rewards, so 4/7
    pub RewardsPortion: Perbill = Perbill::from_rational::<u32>(4, 7);
}
// 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(6), fast: Perbill::from_parts(6) };
    pub const ValidatorsInflationRatePerEra: Perbill = { prod: Perbill::from_parts(105679), fast: Perbill::from_parts(220) };
}
pub struct OnUnbalancedInflation;
impl frame_support::traits::OnUnbalanced<Credit<AccountId, Balances>> for OnUnbalancedInflation {
1579
    fn on_nonzero_unbalanced(credit: Credit<AccountId, Balances>) {
1579
        let _ = <Balances as Balanced<_>>::resolve(&StarlightBondAccount::get(), credit);
1579
    }
}
// Pallet to reward container chains collators.
impl pallet_inflation_rewards::Config for Runtime {
    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 CandidateHasRegisteredKeys;
impl IsCandidateEligible<AccountId> for CandidateHasRegisteredKeys {
31
    fn is_candidate_eligible(a: &AccountId) -> bool {
31
        <Session as ValidatorRegistration<AccountId>>::is_registered(a)
27
            && !InactivityTracking::is_node_offline(a)
31
    }
    #[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()));
        }
        if InactivityTracking::is_node_offline(a) {
            InactivityTracking::make_node_online(a);
        }
    }
}
parameter_types! {
    pub const MaxCandidatesBufferSize: u32 = 100;
}
impl pallet_pooled_staking::Config for Runtime {
    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<Runtime, StakingSessionDelay>;
    type LeavingRequestTimer = SessionTimer<Runtime, StakingSessionDelay>;
    type EligibleCandidatesBufferSize = MaxCandidatesBufferSize;
    type EligibleCandidatesFilter = CandidateHasRegisteredKeys;
    type WeightInfo = weights::pallet_pooled_staking::SubstrateWeight<Runtime>;
}
parameter_types! {
    pub const MaxInactiveSessions: u32 = 5;
    pub const CooldownLenghtInSessions: u32 = 2;
}
impl pallet_inactivity_tracking::Config for Runtime {
    type MaxInactiveSessions = MaxInactiveSessions;
    type MaxCollatorsPerSession = MaxCandidatesBufferSize;
    type MaxContainerChains = MaxLengthParaIds;
    type CurrentSessionIndex = CurrentSessionIndexGetter;
    type CurrentCollatorsFetcher = TanssiCollatorAssignment;
    type GetSelfChainBlockAuthor = ();
    type ParaFilter = tp_parathread_filter_common::ExcludeAllParathreadsFilter<Runtime>;
    type InvulnerablesFilter = tp_invulnerables_filter_common::InvulnerablesFilter<Runtime>;
    type CollatorStakeHelper = PooledStaking;
    type CooldownLength = CooldownLenghtInSessions;
    type WeightInfo = weights::pallet_inactivity_tracking::SubstrateWeight<Runtime>;
}
construct_runtime! {
    pub enum Runtime
    {
        // Basic stuff; balances is uncallable initially.
        System: frame_system = 0,
        // Babe must be before session.
        Babe: pallet_babe = 1,
        Timestamp: pallet_timestamp = 2,
        Balances: pallet_balances = 3,
        Parameters: pallet_parameters = 4,
        TransactionPayment: pallet_transaction_payment = 5,
        // Consensus support.
        // Authorship must be before session in order to note author in the correct session and era.
        Authorship: pallet_authorship = 6,
        Offences: pallet_offences = 7,
        Historical: session_historical = 8,
        // Container stuff should go before session
        // Container stuff starts at index 10
        ContainerRegistrar: pallet_registrar = 10,
        CollatorConfiguration: pallet_configuration = 11,
        TanssiInitializer: tanssi_initializer = 12,
        TanssiInvulnerables: pallet_invulnerables = 13,
        TanssiCollatorAssignment: pallet_collator_assignment = 14,
        TanssiAuthorityAssignment: pallet_authority_assignment = 15,
        TanssiAuthorityMapping: pallet_authority_mapping = 16,
        AuthorNoting: pallet_author_noting = 17,
        ServicesPayment: pallet_services_payment = 18,
        DataPreservers: pallet_data_preservers = 19,
        // Validator stuff
        ExternalValidators: pallet_external_validators = 20,
        ExternalValidatorSlashes: pallet_external_validator_slashes = 21,
        ExternalValidatorsRewards: pallet_external_validators_rewards = 22,
        // Bridging stuff - 1
        EthereumOutboundQueue: snowbridge_pallet_outbound_queue = 23,
        EthereumInboundQueue: snowbridge_pallet_inbound_queue = 24,
        EthereumSystem: snowbridge_pallet_system = 25,
        OutboundMessageCommitmentRecorder: pallet_outbound_message_commitment_recorder = 26,
        EthereumTokenTransfers: pallet_ethereum_token_transfers = 27,
        // Session management
        Session: pallet_session = 30,
        Grandpa: pallet_grandpa = 31,
        AuthorityDiscovery: pallet_authority_discovery = 32,
        // InflationRewards must be after Session
        InflationRewards: pallet_inflation_rewards = 33,
        PooledStaking: pallet_pooled_staking = 34,
        // Inactivity tracking
        InactivityTracking: pallet_inactivity_tracking = 35,
        // Governance stuff; uncallable initially.
        Treasury: pallet_treasury = 40,
        ConvictionVoting: pallet_conviction_voting = 41,
        Referenda: pallet_referenda = 42,
        //	pub type FellowshipCollectiveInstance = pallet_ranked_collective::Instance1;
        FellowshipCollective: pallet_ranked_collective::<Instance1> = 43,
        // pub type FellowshipReferendaInstance = pallet_referenda::Instance2;
        FellowshipReferenda: pallet_referenda::<Instance2> = 44,
        Origins: pallet_custom_origins = 45,
        Whitelist: pallet_whitelist = 46,
        // Parachains pallets. Start indices at 50 to leave room.
        ParachainsOrigin: parachains_origin = 50,
        Configuration: parachains_configuration = 51,
        ParasShared: parachains_shared = 52,
        ParaInclusion: parachains_inclusion = 53,
        ParaInherent: parachains_paras_inherent = 54,
        ParaScheduler: parachains_scheduler = 55,
        Paras: parachains_paras = 56,
        Initializer: parachains_initializer = 57,
        Dmp: parachains_dmp = 58,
        Hrmp: parachains_hrmp = 60,
        ParaSessionInfo: parachains_session_info = 61,
        ParasDisputes: parachains_disputes = 62,
        ParasSlashing: parachains_slashing = 63,
        MessageQueue: pallet_message_queue = 64,
        OnDemandAssignmentProvider: parachains_assigner_on_demand = 65,
        // Parachain Onboarding Pallets. Start indices at 70 to leave room.
        Registrar: paras_registrar = 70,
        // Utility module.
        Utility: pallet_utility = 80,
        // Less simple identity module.
        Identity: pallet_identity = 81,
        // System scheduler.
        Scheduler: pallet_scheduler = 82,
        // Proxy module. Late addition.
        Proxy: pallet_proxy = 83,
        // Multisig module. Late addition.
        Multisig: pallet_multisig = 84,
        // Preimage registrar.
        Preimage: pallet_preimage = 85,
        // Asset rate.
        AssetRate: pallet_asset_rate = 86,
        // Foreign assets.
        ForeignAssets: pallet_assets::<Instance1> = 87,
        ForeignAssetsCreator: pallet_foreign_asset_creator = 88,
        // Pallet for sending XCM.
        XcmPallet: pallet_xcm = 90,
        StreamPayment: pallet_stream_payment = 100,
        // Migration stuff
        Migrations: pallet_migrations = 120,
        MultiBlockMigrations: pallet_multiblock_migrations = 121,
        MaintenanceMode: pallet_maintenance_mode = 122,
        // BEEFY Bridges support.
        Beefy: pallet_beefy = 240,
        // MMR leaf construction must be after session in order to have a leaf's next_auth_set
        // refer to block<N>.
        Mmr: pallet_mmr = 241,
        BeefyMmrLeaf: pallet_beefy_mmr = 242,
        EthereumBeaconClient: snowbridge_pallet_ethereum_client = 243,
        ParasSudoWrapper: paras_sudo_wrapper = 250,
        // Root testing pallet.
        RootTesting: pallet_root_testing = 249,
        // Sudo.
        Sudo: pallet_sudo = 255,
    }
718603
}
/// 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>,
    frame_system::WeightReclaim<Runtime>,
);
/// Unchecked extrinsic type as expected by this runtime.
pub type UncheckedExtrinsic =
    generic::UncheckedExtrinsic<Address, RuntimeCall, Signature, TxExtension>;
/// Executive: handles dispatch to the various modules.
pub type Executive = frame_executive::Executive<
    Runtime,
    Block,
    frame_system::ChainContext<Runtime>,
    Runtime,
    AllPalletsWithSystem,
>;
/// 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 InnerStarlightRegistrar<Runtime, AccountId, RegistrarManager, RegistrarWeightInfo>(
    PhantomData<(Runtime, AccountId, RegistrarManager, RegistrarWeightInfo)>,
);
impl<Runtime, AccountId, RegistrarManager, RegistrarWeightInfo> RegistrarHandler<AccountId>
    for InnerStarlightRegistrar<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>,
{
37
    fn register(
37
        who: AccountId,
37
        id: ParaId,
37
        genesis_storage: &[ContainerChainGenesisDataItem],
37
        head_data: Option<HeadData>,
37
    ) -> DispatchResult {
        // Return early if head_data is not specified
37
        let genesis_head = match head_data {
37
            Some(data) => data,
            None => return Err(ContainerRegistrarError::<Runtime>::HeadDataNecessary.into()),
        };
        // Check if the wasm code is present in storage
37
        let validation_code = match genesis_storage
37
            .iter()
37
            .find(|item| item.key == StorageWellKnownKeys::CODE)
        {
37
            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.
37
        Registrar::register(
37
            RuntimeOrigin::signed(who.into()),
37
            id,
37
            genesis_head,
37
            validation_code,
        )
37
    }
23
    fn schedule_para_upgrade(id: ParaId) -> DispatchResult {
        // 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 {
        // 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 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 = StarlightRegistrarHooks;
    type RuntimeHoldReason = RuntimeHoldReason;
    type InnerRegistrar = InnerStarlightRegistrar<
        Runtime,
        AccountId,
        Registrar,
        weights::runtime_common_paras_registrar::SubstrateWeight<Runtime>,
    >;
    type WeightInfo = weights::pallet_registrar::SubstrateWeight<Runtime>;
    type DataDepositPerByte = DataDepositPerByte;
}
pub struct StarlightRegistrarHooks;
impl pallet_registrar::RegistrarHooks for StarlightRegistrarHooks {
23
    fn para_marked_valid_for_collating(para_id: ParaId) -> Weight {
        // 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
        ServicesPayment::para_deregistered(para_id);
8
        Weight::default()
8
    }
24
    fn check_valid_for_collating(para_id: ParaId) -> DispatchResult {
        // 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::{NodeType, ParaIdsFilter, Profile},
        };
        let profile = Profile {
            bootnode_url: Some(b"/ip4/127.0.0.1/tcp/33049/ws/p2p/12D3KooWHVMhQDHBpj9vQmssgyfspYecgV6e3hH1dQVDUkUbCYC9"
                .to_vec()
                .try_into()
                .expect("to fit in BoundedVec")),
            direct_rpc_urls: Default::default(),
            proxy_rpc_urls: Default::default(),
            para_ids: ParaIdsFilter::AnyParaId,
            node_type: NodeType::Substrate,
            assignment_request: tp_data_preservers_common::ProviderRequest::Free,
            additional_info: Default::default(),
        };
        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"
        );
    }
}
impl pallet_author_noting::Config for Runtime {
    type ContainerChains = TanssiCollatorAssignment;
    type SlotBeacon = BabeSlotBeacon<Runtime>;
    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_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_configuration, CollatorConfiguration]
        [pallet_stream_payment, StreamPayment]
        [pallet_inactivity_tracking, InactivityTracking]
        // Foreign Assets
        [pallet_foreign_asset_creator, ForeignAssetsCreator]
        [pallet_assets, ForeignAssets]
        // 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]
    );
}
sp_api::impl_runtime_apis! {
    impl sp_api::Core<Block> for Runtime {
        fn version() -> RuntimeVersion {
            VERSION
        }
        fn execute_block(block: Block) {
            Executive::execute_block(block);
        }
        fn initialize_block(header: &<Block as BlockT>::Header) -> sp_runtime::ExtrinsicInclusionMode {
            Executive::initialize_block(header)
        }
    }
    impl xcm_runtime_apis::dry_run::DryRunApi<Block, RuntimeCall, RuntimeEvent, OriginCaller> for Runtime {
        fn dry_run_call(origin: OriginCaller, call: RuntimeCall, result_xcms_version: XcmVersion) -> Result<CallDryRunEffects<RuntimeEvent>, XcmDryRunApiError> {
            XcmPallet::dry_run_call::<Runtime, xcm_config::XcmRouter, OriginCaller, RuntimeCall>(origin, call, result_xcms_version)
        }
        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)
        }
    }
    impl xcm_runtime_apis::fees::XcmPaymentApi<Block> for Runtime {
        fn query_acceptable_payment_assets(xcm_version: xcm::Version) -> Result<Vec<VersionedAssetId>, XcmPaymentApiError> {
            if !matches!(xcm_version, 3..=5) {
                return Err(XcmPaymentApiError::UnhandledXcmVersion);
            }
            Ok([VersionedAssetId::V5(xcm_config::TokenLocation::get().into())]
                .into_iter()
                .filter_map(|asset| asset.into_version(xcm_version).ok())
                .collect())
        }
        fn query_weight_to_asset_fee(weight: Weight, asset: VersionedAssetId) -> Result<u128, XcmPaymentApiError> {
            let local_asset = VersionedAssetId::V5(xcm_config::TokenLocation::get().into());
            let asset = asset
                .into_version(5)
                .map_err(|_| XcmPaymentApiError::VersionedConversionFailed)?;
            if  asset != local_asset { return Err(XcmPaymentApiError::AssetNotFound); }
            Ok(WeightToFee::weight_to_fee(&weight))
        }
        fn query_xcm_weight(message: VersionedXcm<()>) -> Result<Weight, XcmPaymentApiError> {
            XcmPallet::query_xcm_weight(message)
        }
        fn query_delivery_fees(destination: VersionedLocation, message: VersionedXcm<()>) -> Result<VersionedAssets, XcmPaymentApiError> {
            XcmPallet::query_delivery_fees(destination, message)
        }
    }
    impl xcm_runtime_apis::conversions::LocationToAccountApi<Block, AccountId> for Runtime {
        fn convert_location(location: VersionedLocation) -> Result<
            AccountId,
            xcm_runtime_apis::conversions::Error
        > {
            xcm_runtime_apis::conversions::LocationToAccountHelper::<
                AccountId,
                xcm_config::LocationConverter,
            >::convert_location(location)
        }
    }
    impl sp_api::Metadata<Block> for Runtime {
        fn metadata() -> OpaqueMetadata {
            OpaqueMetadata::new(Runtime::metadata().into())
        }
        fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
            Runtime::metadata_at_version(version)
        }
        fn metadata_versions() -> alloc::vec::Vec<u32> {
            Runtime::metadata_versions()
        }
    }
    impl block_builder_api::BlockBuilder<Block> for Runtime {
        fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
            Executive::apply_extrinsic(extrinsic)
        }
        fn finalize_block() -> <Block as BlockT>::Header {
            Executive::finalize_block()
        }
        fn inherent_extrinsics(data: inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
            data.create_extrinsics()
        }
        fn check_inherents(
            block: Block,
            data: inherents::InherentData,
        ) -> inherents::CheckInherentsResult {
            data.check_extrinsics(&block)
        }
    }
    impl tx_pool_api::runtime_api::TaggedTransactionQueue<Block> for Runtime {
        fn validate_transaction(
            source: TransactionSource,
            tx: <Block as BlockT>::Extrinsic,
            block_hash: <Block as BlockT>::Hash,
        ) -> TransactionValidity {
            Executive::validate_transaction(source, tx, block_hash)
        }
    }
    impl offchain_primitives::OffchainWorkerApi<Block> for Runtime {
        fn offchain_worker(header: &<Block as BlockT>::Header) {
            Executive::offchain_worker(header)
        }
    }
    #[api_version(13)]
    impl primitives::runtime_api::ParachainHost<Block> for Runtime {
        fn validators() -> Vec<ValidatorId> {
            parachains_runtime_api_impl::validators::<Runtime>()
        }
        fn validator_groups() -> (Vec<Vec<ValidatorIndex>>, GroupRotationInfo<BlockNumber>) {
            parachains_runtime_api_impl::validator_groups::<Runtime>()
        }
        fn availability_cores() -> Vec<CoreState<Hash, BlockNumber>> {
            parachains_runtime_api_impl::availability_cores::<Runtime>()
        }
        fn persisted_validation_data(para_id: ParaId, assumption: OccupiedCoreAssumption)
            -> Option<PersistedValidationData<Hash, BlockNumber>> {
            parachains_runtime_api_impl::persisted_validation_data::<Runtime>(para_id, assumption)
        }
        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,
            )
        }
        fn check_validation_outputs(
            para_id: ParaId,
            outputs: primitives::CandidateCommitments,
        ) -> bool {
            parachains_runtime_api_impl::check_validation_outputs::<Runtime>(para_id, outputs)
        }
        fn session_index_for_child() -> SessionIndex {
            parachains_runtime_api_impl::session_index_for_child::<Runtime>()
        }
        fn validation_code(para_id: ParaId, assumption: OccupiedCoreAssumption)
            -> Option<ValidationCode> {
            parachains_runtime_api_impl::validation_code::<Runtime>(para_id, assumption)
        }
        fn candidate_pending_availability(para_id: ParaId) -> Option<CommittedCandidateReceiptV2<Hash>> {
            #[allow(deprecated)]
            parachains_runtime_api_impl::candidate_pending_availability::<Runtime>(para_id)
        }
        fn candidate_events() -> Vec<CandidateEvent<Hash>> {
            parachains_runtime_api_impl::candidate_events::<Runtime, _>(|ev| {
                match ev {
                    RuntimeEvent::ParaInclusion(ev) => {
                        Some(ev)
                    }
                    _ => None,
                }
            })
        }
        fn session_info(index: SessionIndex) -> Option<SessionInfo> {
            parachains_runtime_api_impl::session_info::<Runtime>(index)
        }
        fn session_executor_params(session_index: SessionIndex) -> Option<ExecutorParams> {
            parachains_runtime_api_impl::session_executor_params::<Runtime>(session_index)
        }
100
        fn dmq_contents(recipient: ParaId) -> Vec<InboundDownwardMessage<BlockNumber>> {
100
            parachains_runtime_api_impl::dmq_contents::<Runtime>(recipient)
100
        }
        fn inbound_hrmp_channels_contents(
            recipient: ParaId
        ) -> BTreeMap<ParaId, Vec<InboundHrmpMessage<BlockNumber>>> {
            parachains_runtime_api_impl::inbound_hrmp_channels_contents::<Runtime>(recipient)
        }
        fn validation_code_by_hash(hash: ValidationCodeHash) -> Option<ValidationCode> {
            parachains_runtime_api_impl::validation_code_by_hash::<Runtime>(hash)
        }
        fn on_chain_votes() -> Option<ScrapedOnChainVotes<Hash>> {
            parachains_runtime_api_impl::on_chain_votes::<Runtime>()
        }
        fn submit_pvf_check_statement(
            stmt: primitives::PvfCheckStatement,
            signature: primitives::ValidatorSignature
        ) {
            parachains_runtime_api_impl::submit_pvf_check_statement::<Runtime>(stmt, signature)
        }
        fn pvfs_require_precheck() -> Vec<ValidationCodeHash> {
            parachains_runtime_api_impl::pvfs_require_precheck::<Runtime>()
        }
        fn validation_code_hash(para_id: ParaId, assumption: OccupiedCoreAssumption)
            -> Option<ValidationCodeHash>
        {
            parachains_runtime_api_impl::validation_code_hash::<Runtime>(para_id, assumption)
        }
        fn disputes() -> Vec<(SessionIndex, CandidateHash, DisputeState<BlockNumber>)> {
            parachains_runtime_api_impl::get_session_disputes::<Runtime>()
        }
        fn unapplied_slashes(
        ) -> Vec<(SessionIndex, CandidateHash, slashing::PendingSlashes)> {
            parachains_runtime_api_impl::unapplied_slashes::<Runtime>()
        }
        fn key_ownership_proof(
            validator_id: ValidatorId,
        ) -> Option<slashing::OpaqueKeyOwnershipProof> {
            use parity_scale_codec::Encode;
            Historical::prove((PARACHAIN_KEY_TYPE_ID, validator_id))
                .map(|p| p.encode())
                .map(slashing::OpaqueKeyOwnershipProof::new)
        }
        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,
            )
        }
        fn minimum_backing_votes() -> u32 {
            parachains_runtime_api_impl::minimum_backing_votes::<Runtime>()
        }
        fn para_backing_state(para_id: ParaId) -> Option<primitives::vstaging::async_backing::BackingState> {
            // TODO: the alternative is to use backing_constraints and candidates_pending_availability
            // but backing_constraints is private.
            #[allow(deprecated)]
            parachains_runtime_api_impl::backing_state::<Runtime>(para_id)
        }
        fn async_backing_params() -> primitives::AsyncBackingParams {
            #[allow(deprecated)]
            parachains_runtime_api_impl::async_backing_params::<Runtime>()
        }
        fn approval_voting_params() -> ApprovalVotingParams {
            parachains_runtime_api_impl::approval_voting_params::<Runtime>()
        }
        fn disabled_validators() -> Vec<ValidatorIndex> {
            parachains_runtime_api_impl::disabled_validators::<Runtime>()
        }
        fn node_features() -> NodeFeatures {
            parachains_runtime_api_impl::node_features::<Runtime>()
        }
        fn claim_queue() -> BTreeMap<CoreIndex, VecDeque<ParaId>> {
            parachains_runtime_api_impl::claim_queue::<Runtime>()
        }
4
        fn candidates_pending_availability(para_id: ParaId) -> Vec<CommittedCandidateReceiptV2<Hash>> {
4
            parachains_runtime_api_impl::candidates_pending_availability::<Runtime>(para_id)
4
        }
        fn backing_constraints(para_id: ParaId) -> Option<Constraints> {
            parachains_staging_runtime_api_impl::backing_constraints::<Runtime>(para_id)
        }
        fn scheduling_lookahead() -> u32 {
            parachains_staging_runtime_api_impl::scheduling_lookahead::<Runtime>()
        }
        fn validation_code_bomb_limit() -> u32 {
            parachains_staging_runtime_api_impl::validation_code_bomb_limit::<Runtime>()
        }
    }
    #[api_version(5)]
    impl beefy_primitives::BeefyApi<Block, BeefyId> for Runtime {
        fn beefy_genesis() -> Option<BlockNumber> {
            pallet_beefy::GenesisBlock::<Runtime>::get()
        }
        fn validator_set() -> Option<beefy_primitives::ValidatorSet<BeefyId>> {
            Beefy::validator_set()
        }
        fn submit_report_double_voting_unsigned_extrinsic(
            equivocation_proof: beefy_primitives::DoubleVotingProof<
                BlockNumber,
                BeefyId,
                BeefySignature,
            >,
            key_owner_proof: beefy_primitives::OpaqueKeyOwnershipProof,
        ) -> Option<()> {
            let key_owner_proof = key_owner_proof.decode()?;
            Beefy::submit_unsigned_double_voting_report(
                equivocation_proof,
                key_owner_proof,
            )
        }
        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()?,
                key_owner_proof.decode()?,
            )
        }
        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()?,
            )
        }
        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)
        }
        fn generate_ancestry_proof(
            prev_block_number: BlockNumber,
            best_known_block_number: Option<BlockNumber>,
        ) -> Option<sp_runtime::OpaqueValue> {
            use beefy_primitives::AncestryHelper;
            BeefyMmrLeaf::generate_proof(prev_block_number, best_known_block_number)
                .map(|p| p.encode())
                .map(sp_runtime::OpaqueValue::new)
        }
    }
    #[api_version(2)]
    impl mmr::MmrApi<Block, mmr::Hash, BlockNumber> for Runtime {
        fn mmr_root() -> Result<mmr::Hash, mmr::Error> {
            Ok(pallet_mmr::RootHash::<Runtime>::get())
        }
        fn mmr_leaf_count() -> Result<mmr::LeafIndex, mmr::Error> {
            Ok(pallet_mmr::NumberOfLeaves::<Runtime>::get())
        }
        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,
                    )
                },
            )
        }
        fn verify_proof(leaves: Vec<mmr::EncodableOpaqueLeaf>, proof: mmr::LeafProof<mmr::Hash>)
            -> Result<(), mmr::Error>
        {
            let leaves = leaves.into_iter().map(|leaf|
                leaf.into_opaque_leaf()
                .try_decode()
                .ok_or(mmr::Error::Verify)).collect::<Result<Vec<mmr::Leaf>, mmr::Error>>()?;
            Mmr::verify_leaves(leaves, proof)
        }
        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)
        }
    }
    impl fg_primitives::GrandpaApi<Block> for Runtime {
        fn grandpa_authorities() -> Vec<(GrandpaId, u64)> {
            Grandpa::grandpa_authorities()
        }
        fn current_set_id() -> fg_primitives::SetId {
            Grandpa::current_set_id()
        }
        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<()> {
            let key_owner_proof = key_owner_proof.decode()?;
            Grandpa::submit_unsigned_equivocation_report(
                equivocation_proof,
                key_owner_proof,
            )
        }
        fn generate_key_ownership_proof(
            _set_id: fg_primitives::SetId,
            authority_id: fg_primitives::AuthorityId,
        ) -> Option<fg_primitives::OpaqueKeyOwnershipProof> {
            use parity_scale_codec::Encode;
            Historical::prove((fg_primitives::KEY_TYPE, authority_id))
                .map(|p| p.encode())
                .map(fg_primitives::OpaqueKeyOwnershipProof::new)
        }
    }
    impl babe_primitives::BabeApi<Block> for Runtime {
        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,
            }
        }
        fn current_epoch_start() -> babe_primitives::Slot {
            Babe::current_epoch_start()
        }
        fn current_epoch() -> babe_primitives::Epoch {
            Babe::current_epoch()
        }
        fn next_epoch() -> babe_primitives::Epoch {
            Babe::next_epoch()
        }
        fn generate_key_ownership_proof(
            _slot: babe_primitives::Slot,
            authority_id: babe_primitives::AuthorityId,
        ) -> Option<babe_primitives::OpaqueKeyOwnershipProof> {
            use parity_scale_codec::Encode;
            Historical::prove((babe_primitives::KEY_TYPE, authority_id))
                .map(|p| p.encode())
                .map(babe_primitives::OpaqueKeyOwnershipProof::new)
        }
        fn submit_report_equivocation_unsigned_extrinsic(
            equivocation_proof: babe_primitives::EquivocationProof<<Block as BlockT>::Header>,
            key_owner_proof: babe_primitives::OpaqueKeyOwnershipProof,
        ) -> Option<()> {
            let key_owner_proof = key_owner_proof.decode()?;
            Babe::submit_unsigned_equivocation_report(
                equivocation_proof,
                key_owner_proof,
            )
        }
    }
    impl authority_discovery_primitives::AuthorityDiscoveryApi<Block> for Runtime {
        fn authorities() -> Vec<AuthorityDiscoveryId> {
            parachains_runtime_api_impl::relevant_authority_ids::<Runtime>()
        }
    }
    impl sp_session::SessionKeys<Block> for Runtime {
        fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {
            SessionKeys::generate(seed)
        }
        fn decode_session_keys(
            encoded: Vec<u8>,
        ) -> Option<Vec<(Vec<u8>, sp_core::crypto::KeyTypeId)>> {
            SessionKeys::decode_into_raw_public_keys(&encoded)
        }
    }
    impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Nonce> for Runtime {
        fn account_nonce(account: AccountId) -> Nonce {
            System::account_nonce(account)
        }
    }
    impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<
        Block,
        Balance,
    > for Runtime {
        fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {
            TransactionPayment::query_info(uxt, len)
        }
        fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {
            TransactionPayment::query_fee_details(uxt, len)
        }
        fn query_weight_to_fee(weight: Weight) -> Balance {
            TransactionPayment::weight_to_fee(weight)
        }
        fn query_length_to_fee(length: u32) -> Balance {
            TransactionPayment::length_to_fee(length)
        }
    }
    impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentCallApi<Block, Balance, RuntimeCall>
        for Runtime
    {
        fn query_call_info(call: RuntimeCall, len: u32) -> RuntimeDispatchInfo<Balance> {
            TransactionPayment::query_call_info(call, len)
        }
        fn query_call_fee_details(call: RuntimeCall, len: u32) -> FeeDetails<Balance> {
            TransactionPayment::query_call_fee_details(call, len)
        }
        fn query_weight_to_fee(weight: Weight) -> Balance {
            TransactionPayment::weight_to_fee(weight)
        }
        fn query_length_to_fee(length: u32) -> Balance {
            TransactionPayment::length_to_fee(length)
        }
    }
    impl pallet_beefy_mmr::BeefyMmrApi<Block, Hash> for RuntimeApi {
        fn authority_set_proof() -> beefy_primitives::mmr::BeefyAuthoritySet<Hash> {
            BeefyMmrLeaf::authority_set_proof()
        }
        fn next_authority_set_proof() -> beefy_primitives::mmr::BeefyNextAuthoritySet<Hash> {
            BeefyMmrLeaf::next_authority_set_proof()
        }
    }
    #[cfg(feature = "try-runtime")]
    impl frame_try_runtime::TryRuntime<Block> for Runtime {
        fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) {
            log::info!("try-runtime::on_runtime_upgrade starlight.");
            let weight = Executive::try_runtime_upgrade(checks).unwrap();
            (weight, BlockWeights::get().max_block)
        }
        fn execute_block(
            block: Block,
            state_root_check: bool,
            signature_check: bool,
            select: frame_try_runtime::TryStateSelect,
        ) -> Weight {
            // NOTE: intentional unwrap: we don't want to propagate the error backwards, and want to
            // have a backtrace here.
            Executive::try_execute_block(block, state_root_check, signature_check, select).unwrap()
        }
    }
    impl pallet_registrar_runtime_api::RegistrarApi<Block, ParaId> for Runtime {
        /// Return the registered para ids
10
        fn registered_paras() -> Vec<ParaId> {
            // We should return the container-chains for the session in which we are kicking in
            // We could potentially predict whether the next block will yield a session change as in dancebox but this
            // is innecesary: the Starlight blocks are being produced by validators, and therefore it should never
            // stall because of any collator-rotation. Therefore it suffices for collators to predict the chain in
            // 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
            para_ids
10
        }
        /// Fetch genesis data for this para id
18
        fn genesis_data(para_id: ParaId) -> Option<ContainerChainGenesisData> {
18
            ContainerRegistrar::para_genesis_data(para_id)
18
        }
        /// Fetch boot_nodes for this para id
        fn boot_nodes(para_id: ParaId) -> Vec<Vec<u8>> {
            DataPreservers::assignments_profiles(para_id)
                .filter_map(|profile| profile.bootnode_url.map(Into::into))
                .collect()
        }
    }
    impl pallet_registrar_runtime_api::OnDemandBlockProductionApi<Block, ParaId, Slot> for Runtime {
        /// Returns slot frequency for particular para thread. Slot frequency specifies amount of slot
        /// need to be passed between two parathread blocks. It is expressed as `(min, max)` pair where `min`
        /// indicates amount of slot must pass before we produce another block and `max` indicates amount of
        /// blocks before this parathread must produce the block.
        ///
        /// Simply put, parathread must produce a block after `min`  but before `(min+max)` slots.
        ///
        /// # Returns
        ///
        /// * `Some(slot_frequency)`.
        /// * `None` if the `para_id` is not a parathread.
        fn parathread_slot_frequency(para_id: ParaId) -> Option<SlotFrequency> {
            ContainerRegistrar::parathread_params(para_id).map(|params| {
                params.slot_frequency
            })
        }
    }
    impl pallet_author_noting_runtime_api::AuthorNotingApi<Block, AccountId, BlockNumber, ParaId> for Runtime
        where
        AccountId: parity_scale_codec::Codec,
        BlockNumber: parity_scale_codec::Codec,
        ParaId: parity_scale_codec::Codec,
    {
1
        fn latest_block_number(para_id: ParaId) -> Option<BlockNumber> {
1
            AuthorNoting::latest_author(para_id).map(|info| info.block_number)
1
        }
1
        fn latest_author(para_id: ParaId) -> Option<AccountId> {
1
            AuthorNoting::latest_author(para_id).map(|info| info.author)
1
        }
    }
    impl pallet_external_validators_rewards_runtime_api::ExternalValidatorsRewardsApi<Block, AccountId, EraIndex> for Runtime
        where
        EraIndex: parity_scale_codec::Codec,
    {
        fn generate_rewards_merkle_proof(account_id: AccountId, era_index: EraIndex) -> Option<MerkleProof> {
            ExternalValidatorsRewards::generate_rewards_merkle_proof(account_id, era_index)
        }
        fn verify_rewards_merkle_proof(merkle_proof: MerkleProof) -> bool {
            ExternalValidatorsRewards::verify_rewards_merkle_proof(merkle_proof)
        }
    }
    impl dp_consensus::TanssiAuthorityAssignmentApi<Block, NimbusId> for Runtime {
        /// Return the current authorities assigned to a given paraId
        fn para_id_authorities(para_id: ParaId) -> Option<Vec<NimbusId>> {
            let session_index = Session::current_index();
            let assigned_authorities = TanssiAuthorityAssignment::collator_container_chain(session_index)?;
            assigned_authorities.container_chains.get(&para_id).cloned()
        }
        /// Return the paraId assigned to a given authority
        fn check_para_id_assignment(authority: NimbusId) -> Option<ParaId> {
            let session_index = Session::current_index();
            let assigned_authorities = TanssiAuthorityAssignment::collator_container_chain(session_index)?;
            // This self_para_id is used to detect assignments to orchestrator, in this runtime the
            // orchestrator will always be empty so we can set it to any value
            let self_para_id = 0u32.into();
            assigned_authorities.para_id_of(&authority, self_para_id)
        }
        /// Return the paraId assigned to a given authority on the next session.
        /// On session boundary this returns the same as `check_para_id_assignment`.
        fn check_para_id_assignment_next_session(authority: NimbusId) -> Option<ParaId> {
            let session_index = Session::current_index() + 1;
            let assigned_authorities = TanssiAuthorityAssignment::collator_container_chain(session_index)?;
            // This self_para_id is used to detect assignments to orchestrator, in this runtime the
            // orchestrator will always be empty so we can set it to any value
            let self_para_id = 0u32.into();
            assigned_authorities.para_id_of(&authority, self_para_id)
        }
    }
    impl pallet_services_payment_runtime_api::ServicesPaymentApi<Block, Balance, ParaId> for Runtime {
        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
        }
        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
        }
    }
    impl snowbridge_outbound_queue_runtime_api::OutboundQueueApi<Block, Balance> for Runtime {
        fn prove_message(leaf_index: u64) -> Option<MerkleProof> {
            snowbridge_pallet_outbound_queue::api::prove_message::<Runtime>(leaf_index)
        }
        fn calculate_fee(command: Command, parameters: Option<PricingParameters<Balance>>) -> Fee<Balance> {
            snowbridge_pallet_outbound_queue::api::calculate_fee::<Runtime>(command, parameters)
        }
    }
    impl pallet_stream_payment_runtime_api::StreamPaymentApi<Block, StreamId, Balance, Balance>
    for Runtime {
        fn stream_payment_status(
            stream_id: StreamId,
            now: Option<Balance>,
        ) -> Result<StreamPaymentApiStatus<Balance>, StreamPaymentApiError> {
            match StreamPayment::stream_payment_status(stream_id, now) {
                Ok(pallet_stream_payment::StreamPaymentStatus {
                    payment, deposit_left, stalled
                }) => Ok(StreamPaymentApiStatus {
                    payment, deposit_left, stalled
                }),
                Err(pallet_stream_payment::Error::<Runtime>::UnknownStreamId)
                => Err(StreamPaymentApiError::UnknownStreamId),
                Err(e) => Err(StreamPaymentApiError::Other(alloc::format!("{e:?}")))
            }
        }
    }
    impl pallet_data_preservers_runtime_api::DataPreserversApi<Block, DataPreserversProfileId, ParaId> for Runtime {
        fn get_active_assignment(
            profile_id: DataPreserversProfileId,
        ) -> pallet_data_preservers_runtime_api::Assignment<ParaId> {
            use pallet_data_preservers_runtime_api::Assignment;
            use pallet_stream_payment::StreamPaymentStatus;
            let Some((para_id, witness)) = pallet_data_preservers::Profiles::<Runtime>::get(profile_id)
                .and_then(|x| x.assignment) else
            {
                return Assignment::NotAssigned;
            };
            match witness {
                tp_data_preservers_common::AssignmentWitness::Free => Assignment::Active(para_id),
                tp_data_preservers_common::AssignmentWitness::StreamPayment { stream_id } => {
                    // Error means no Stream exists with that ID or some issue occured when computing
                    // the status. In that case we cannot consider the assignment as active.
                    let Ok(StreamPaymentStatus { stalled, .. }) = StreamPayment::stream_payment_status( stream_id, None) else {
                        return Assignment::Inactive(para_id);
                    };
                    if stalled {
                        Assignment::Inactive(para_id)
                    } else {
                        Assignment::Active(para_id)
                    }
                },
            }
        }
    }
    #[cfg(feature = "runtime-benchmarks")]
    impl frame_benchmarking::Benchmark<Block> for Runtime {
        fn benchmark_metadata(extra: bool) -> (
            Vec<frame_benchmarking::BenchmarkList>,
            Vec<frame_support::traits::StorageInfo>,
        ) {
            use frame_benchmarking::{BenchmarkList};
            use frame_support::traits::StorageInfoTrait;
            use frame_system_benchmarking::Pallet as SystemBench;
            use frame_benchmarking::baseline::Pallet as Baseline;
            use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
            let mut list = Vec::<BenchmarkList>::new();
            list_benchmarks!(list, extra);
            let storage_info = AllPalletsWithSystem::storage_info();
            (list, storage_info)
        }
        #[allow(non_local_definitions)]
        fn dispatch_benchmark(
            config: frame_benchmarking::BenchmarkConfig,
        ) -> Result<
            Vec<frame_benchmarking::BenchmarkBatch>,
            alloc::string::String,
        > {
            use frame_support::traits::WhitelistedStorageKeys;
            use frame_benchmarking::{BenchmarkBatch, BenchmarkError};
            use frame_system_benchmarking::Pallet as SystemBench;
            use frame_benchmarking::baseline::Pallet as Baseline;
            use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
            use sp_storage::TrackedStorageKey;
            use xcm::latest::prelude::*;
            use xcm_config::{
                AssetHub, LocalCheckAccount, LocationConverter, TokenLocation, XcmConfig,
            };
            use alloc::boxed::Box;
            parameter_types! {
                pub ExistentialDepositAsset: Option<Asset> = Some((
                    TokenLocation::get(),
                    ExistentialDeposit::get()
                ).into());
                pub AssetHubParaId: ParaId = starlight_runtime_constants::system_parachain::ASSET_HUB_ID.into();
                pub const RandomParaId: ParaId = ParaId::new(43211234);
            }
            impl frame_system_benchmarking::Config for Runtime {}
            impl frame_benchmarking::baseline::Config for Runtime {}
            impl pallet_xcm::benchmarking::Config for Runtime {
                type DeliveryHelper = (
                    runtime_common::xcm_sender::ToParachainDeliveryHelper<
                        XcmConfig,
                        ExistentialDepositAsset,
                        xcm_config::PriceForChildParachainDelivery,
                        AssetHubParaId,
                        Dmp,
                    >,
                    runtime_common::xcm_sender::ToParachainDeliveryHelper<
                        XcmConfig,
                        ExistentialDepositAsset,
                        xcm_config::PriceForChildParachainDelivery,
                        RandomParaId,
                        Dmp,
                    >
                );
                fn reachable_dest() -> Option<Location> {
                    Some(crate::xcm_config::AssetHub::get())
                }
                fn teleportable_asset_and_dest() -> Option<(Asset, Location)> {
                    // Relay/native token can be teleported to/from AH.
                    Some((
                        Asset {
                            fun: Fungible(ExistentialDeposit::get()),
                            id: AssetId(Here.into())
                        },
                        crate::xcm_config::AssetHub::get(),
                    ))
                }
                fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> {
                    // Relay can reserve transfer native token to some random parachain.
                    Some((
                        Asset {
                            fun: Fungible(ExistentialDeposit::get()),
                            id: AssetId(Here.into())
                        },
                        Parachain(RandomParaId::get().into()).into(),
                    ))
                }
                fn set_up_complex_asset_transfer(
                ) -> Option<(Assets, u32, Location, Box<dyn FnOnce()>)> {
                    // Relay supports only native token, either reserve transfer it to non-system parachains,
                    // or teleport it to system parachain. Use the teleport case for benchmarking as it's
                    // slightly heavier.
                    // Relay/native token can be teleported to/from AH.
                    let native_location = Here.into();
                    let dest = crate::xcm_config::AssetHub::get();
                    pallet_xcm::benchmarking::helpers::native_teleport_as_asset_transfer::<Runtime>(
                        native_location,
                        dest
                    )
                }
                fn get_asset() -> Asset {
                    Asset {
                        id: AssetId(Location::here()),
                        fun: Fungible(ExistentialDeposit::get()),
                    }
                }
            }
            impl pallet_xcm_benchmarks::Config for Runtime {
                type XcmConfig = XcmConfig;
                type AccountIdConverter = LocationConverter;
                type DeliveryHelper = runtime_common::xcm_sender::ToParachainDeliveryHelper<
                    XcmConfig,
                    ExistentialDepositAsset,
                    xcm_config::PriceForChildParachainDelivery,
                    AssetHubParaId,
                    Dmp,
                >;
                fn valid_destination() -> Result<Location, BenchmarkError> {
                    Ok(AssetHub::get())
                }
                fn worst_case_holding(_depositable_count: u32) -> Assets {
                    // Starlight only knows about STAR
                    vec![Asset{
                        id: AssetId(TokenLocation::get()),
                        fun: Fungible(1_000_000 * UNITS),
                    }].into()
                }
            }
            parameter_types! {
                pub TrustedReserve: Option<(Location, Asset)> = Some(
                    (
                        EthereumLocation::get(),
                        Asset {
                            id: AssetId(EthereumLocation::get()),
                            fun: Fungible(ExistentialDeposit::get() * 100),
                        },
                    )
                );
            }
            impl pallet_xcm_benchmarks::fungible::Config for Runtime {
                type TransactAsset = Balances;
                type CheckedAccount = LocalCheckAccount;
                type TrustedTeleporter = ();
                type TrustedReserve = TrustedReserve;
                fn get_asset() -> Asset {
                    use frame_support::{assert_ok, traits::tokens::fungible::{Inspect, Mutate}};
                    let (account, _) = pallet_xcm_benchmarks::account_and_location::<Runtime>(1);
                    assert_ok!(<Balances as Mutate<_>>::mint_into(
                        &account,
                        <Balances as Inspect<_>>::minimum_balance(),
                    ));
                    let asset_id = 42u16;
                    let asset_location = Location {
                        parents: 1,
                        interior: X2([
                            GlobalConsensus(NetworkId::Ethereum { chain_id: 1 }),
                            AccountKey20 {
                                network: Some(NetworkId::Ethereum { chain_id: 1 }),
                                key: [0; 20],
                            },
                        ]
                        .into()),
                    };
                    assert_ok!(ForeignAssetsCreator::create_foreign_asset(
                        RuntimeOrigin::root(),
                        asset_location.clone(),
                        asset_id,
                        account.clone(),
                        true,
                        1u128,
                    ));
                    Asset {
                        id: AssetId(asset_location),
                        fun: Fungible(ExistentialDeposit::get() * 100),
                    }
                }
            }
            impl pallet_xcm_benchmarks::generic::Config for Runtime {
                type TransactAsset = Balances;
                type RuntimeCall = RuntimeCall;
                fn worst_case_response() -> (u64, Response) {
                    (0u64, Response::Version(Default::default()))
                }
                fn worst_case_asset_exchange() -> Result<(Assets, Assets), BenchmarkError> {
                    // Starlight doesn't support asset exchanges
                    Err(BenchmarkError::Skip)
                }
                fn universal_alias() -> Result<(Location, Junction), BenchmarkError> {
                    // The XCM executor of Starlight doesn't have a configured `UniversalAliases`
                    Err(BenchmarkError::Skip)
                }
                fn transact_origin_and_runtime_call() -> Result<(Location, RuntimeCall), BenchmarkError> {
                    Ok((AssetHub::get(), frame_system::Call::remark_with_event { remark: vec![] }.into()))
                }
                fn subscribe_origin() -> Result<Location, BenchmarkError> {
                    Ok(AssetHub::get())
                }
                fn claimable_asset() -> Result<(Location, Location, Assets), BenchmarkError> {
                    let origin = AssetHub::get();
                    let assets: Assets = (AssetId(TokenLocation::get()), 1_000 * UNITS).into();
                    let ticket = Location { parents: 0, interior: Here };
                    Ok((origin, ticket, assets))
                }
                fn worst_case_for_trader() -> Result<(Asset, WeightLimit), BenchmarkError> {
                    Ok((Asset {
                        id: AssetId(TokenLocation::get()),
                        fun: Fungible(1_000_000 * UNITS),
                    }, WeightLimit::Unlimited))
                }
                fn unlockable_asset() -> Result<(Location, Location, Asset), BenchmarkError> {
                    // Starlight doesn't support asset locking
                    Err(BenchmarkError::Skip)
                }
                fn export_message_origin_and_destination(
                ) -> Result<(Location, NetworkId, InteriorLocation), BenchmarkError> {
                    // Starlight doesn't support exporting messages
                    Err(BenchmarkError::Skip)
                }
                fn alias_origin() -> Result<(Location, Location), BenchmarkError> {
                    // The XCM executor of Starlight doesn't have a configured `Aliasers`
                    Err(BenchmarkError::Skip)
                }
            }
            pub struct SessionBenchValidators;
            impl pallet_alt_benchmarks::bench_parachains_slashing::Validators<AccountId> for SessionBenchValidators {
                /// Sets the validators to properly run a benchmark. Should take care of everything that
                /// will make pallet_session use those validators, such as them having a balance.
                fn set_validators(validators: &[AccountId]) {
                    use frame_support::traits::fungible::Mutate;
                    use tp_traits::ExternalIndexProvider;
                    ExternalValidators::set_external_validators_inner(
                        validators.to_vec(),
                        ExternalValidators::get_external_index()
                    ).expect("to set validators");
                    for v in validators {
                        Balances::set_balance(v, EXISTENTIAL_DEPOSIT);
                    }
                }
            }
            impl pallet_alt_benchmarks::bench_parachains_slashing::Config for Runtime {
                type Validators = SessionBenchValidators;
            }
            impl cumulus_pallet_session_benchmarking::Config for Runtime { }
            let mut whitelist: Vec<TrackedStorageKey> = AllPalletsWithSystem::whitelisted_storage_keys();
            let treasury_key = frame_system::Account::<Runtime>::hashed_key_for(Treasury::account_id());
            whitelist.push(treasury_key.to_vec().into());
            let mut batches = Vec::<BenchmarkBatch>::new();
            let params = (&config, &whitelist);
            add_benchmarks!(params, batches);
            Ok(batches)
        }
    }
    #[cfg(not(feature = "disable-genesis-builder"))]
    impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
        fn build_state(config: Vec<u8>) -> sp_genesis_builder::Result {
            build_state::<RuntimeGenesisConfig>(config)
        }
        fn get_preset(id: &Option<PresetId>) -> Option<Vec<u8>> {
            get_preset::<RuntimeGenesisConfig>(id, &genesis_config_presets::get_preset)
        }
        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"),
            ]
        }
    }
}
pub struct OwnApplySession;
impl tanssi_initializer::ApplyNewSession<Runtime> for OwnApplySession {
617
    fn apply_new_session(
617
        _changed: bool,
617
        session_index: u32,
617
        _all_validators: Vec<(AccountId, nimbus_primitives::NimbusId)>,
617
        _queued: Vec<(AccountId, nimbus_primitives::NimbusId)>,
617
    ) {
        // Order is same as in tanssi
        // 1.
        // We first initialize Configuration
617
        CollatorConfiguration::initializer_on_new_session(&session_index);
        // 2. Second, registrar
617
        ContainerRegistrar::initializer_on_new_session(&session_index);
617
        let invulnerables = TanssiInvulnerables::invulnerables().to_vec();
617
        let candidates_staking =
617
            pallet_pooled_staking::SortedEligibleCandidates::<Runtime>::get().to_vec();
        // Max number of collators is set in pallet_configuration
617
        let target_session_index = session_index.saturating_add(1);
617
        let max_collators = <CollatorConfiguration as GetHostConfiguration<u32>>::max_collators(
617
            target_session_index,
        );
617
        let next_collators: Vec<_> = invulnerables
617
            .iter()
617
            .cloned()
617
            .chain(candidates_staking.into_iter().filter_map(|elig| {
34
                let cand = elig.candidate;
34
                if invulnerables.contains(&cand) {
                    // If a candidate is both in pallet_invulnerables and pallet_staking, do not count it twice
26
                    None
                } else {
8
                    Some(cand)
                }
34
            }))
617
            .take(max_collators as usize)
617
            .collect();
        // Queue next session keys.
617
        let queued_amalgamated = next_collators
617
            .into_iter()
959
            .filter_map(|a| {
879
                let k = pallet_session::NextKeys::<Runtime>::get(&a)?;
879
                Some((a, k.nimbus))
879
            })
617
            .collect::<Vec<_>>();
959
        let next_collators_accounts = queued_amalgamated.iter().map(|(a, _)| a.clone()).collect();
        // 3. AuthorityMapping
617
        if session_index.is_zero() {
266
            // On the genesis sesion index we need to store current as well
266
            TanssiAuthorityMapping::initializer_on_new_session(&session_index, &queued_amalgamated);
431
        }
        // 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
617
        TanssiAuthorityMapping::initializer_on_new_session(
617
            &(session_index + 1),
617
            &queued_amalgamated,
        );
        // 4. CollatorAssignment
        // Unlike in tanssi, where the input to this function are the correct
        // queued keys & collators, here we get the input refers to the validators
        // and not the collators. Therefore we need to do a similar thing that
        // pallet-session does but in this function
        // This is, get the collators, fetch their respective keys, and queue the
        // assignment
        // CollatorAssignment
617
        let assignments = TanssiCollatorAssignment::initializer_on_new_session(
617
            &session_index,
617
            next_collators_accounts,
        );
        // 5. AuthorityAssignment
617
        let queued_id_to_nimbus_map = queued_amalgamated.iter().cloned().collect();
617
        TanssiAuthorityAssignment::initializer_on_new_session(
617
            &session_index,
617
            &queued_id_to_nimbus_map,
617
            &assignments.next_assignment,
        );
        // 6. InactivityTracking
617
        InactivityTracking::process_ended_session();
617
    }
351
    fn on_before_session_ending() {
351
        InactivityTracking::on_before_session_ending();
351
    }
}
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 {
1
    fn get_block_randomness() -> Option<[u8; 32]> {
        // In a relay context we get block randomness from Babe's AuthorVrfRandomness
1
        Babe::author_vrf_randomness()
1
    }
1
    fn get_block_randomness_mixed(subject: &[u8]) -> Option<Hash> {
1
        Self::get_block_randomness()
1
            .map(|random_hash| mix_randomness::<Runtime>(random_hash, subject))
1
    }
}
/// 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.
1
pub fn mix_randomness<T: frame_system::Config>(vrf_output: [u8; 32], subject: &[u8]) -> T::Hash {
1
    let mut digest = Vec::new();
1
    digest.extend_from_slice(vrf_output.as_ref());
1
    digest.extend_from_slice(subject);
1
    T::Hashing::hash(digest.as_slice())
1
}
/// Read full_rotation_period from pallet_configuration
pub struct ConfigurationCollatorRotationSessionPeriod;
impl Get<u32> for ConfigurationCollatorRotationSessionPeriod {
784
    fn get() -> u32 {
784
        CollatorConfiguration::config().full_rotation_period
784
    }
}
// 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 {
795
    fn charge_para_ids_internal(
795
        blocks_per_session: BlockNumber,
795
        para_id: ParaId,
795
        currently_assigned: &BTreeSet<ParaId>,
795
        maybe_tip: &Option<BalanceOf<Runtime>>,
795
    ) -> 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
788
        let maybe_assignment_imbalance =
795
            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,
                    WithdrawReasons::FEE,
15
                    ExistenceRequirement::KeepAlive,
7
                )?)
            } else {
780
                None
            };
788
        if let Some(tip) = maybe_tip {
515
            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);
514
            }
273
        }
787
        if let Some(assignment_imbalance) = maybe_assignment_imbalance {
8
            <Runtime as pallet_services_payment::Config>::OnChargeForCollatorAssignment::on_unbalanced(assignment_imbalance);
779
        }
        // If the para has been assigned collators for this session it must have enough block credits
        // for the current and the next session.
787
        let block_credits_needed = if currently_assigned.contains(&para_id) {
501
            blocks_per_session * 2
        } else {
286
            blocks_per_session
        };
        // Check if the container chain has enough credits for producing blocks
787
        let free_block_credits =
787
            pallet_services_payment::BlockProductionCredits::<Runtime>::get(para_id)
787
                .unwrap_or_default();
787
        let remaining_block_credits = block_credits_needed.saturating_sub(free_block_credits);
787
        let (block_production_costs, _) =
787
            <Runtime as pallet_services_payment::Config>::ProvideBlockProductionCost::block_cost(
787
                &para_id,
787
            );
        // Check if we can withdraw
787
        let remaining_block_credits_to_pay =
787
            u128::from(remaining_block_credits).saturating_mul(block_production_costs);
787
        let remaining_to_pay = remaining_block_credits_to_pay;
        // This should take into account whether we tank goes below ED
        // The true refers to keepAlive
787
        Balances::can_withdraw(
787
            &pallet_services_payment::Pallet::<Runtime>::parachain_tank(para_id),
787
            remaining_to_pay,
        )
787
        .into_result(true)?;
        // TODO: Have proper weight
773
        Ok(Weight::zero())
795
    }
}
impl<AC> ParaIdAssignmentHooks<BalanceOf<Runtime>, AC> for ParaIdAssignmentHooksImpl {
1234
    fn pre_assignment(para_ids: &mut Vec<ParaId>, currently_assigned: &BTreeSet<ParaId>) {
1234
        let blocks_per_session = EpochDurationInBlocks::get();
1234
        para_ids.retain(|para_id| {
490
            with_transaction(|| {
490
                let max_tip =
490
                    pallet_services_payment::MaxTip::<Runtime>::get(para_id).unwrap_or_default();
490
                TransactionOutcome::Rollback(Self::charge_para_ids_internal(
490
                    blocks_per_session,
490
                    *para_id,
490
                    currently_assigned,
490
                    &Some(max_tip),
490
                ))
490
            })
490
            .is_ok()
490
        });
1234
    }
617
    fn post_assignment(
617
        current_assigned: &BTreeSet<ParaId>,
617
        new_assigned: &mut BTreeMap<ParaId, Vec<AC>>,
617
        maybe_tip: &Option<BalanceOf<Runtime>>,
617
    ) -> Weight {
617
        let blocks_per_session = EpochDurationInBlocks::get();
617
        let mut total_weight = Weight::zero();
617
        new_assigned.retain(|&para_id, collators| {
            // Short-circuit in case collators are empty
452
            if collators.is_empty() {
147
                return true;
305
            }
305
            with_storage_layer(|| {
305
                Self::charge_para_ids_internal(
305
                    blocks_per_session,
305
                    para_id,
305
                    current_assigned,
305
                    maybe_tip,
                )
305
            })
305
            .inspect(|weight| {
305
                total_weight += *weight;
305
            })
305
            .is_ok()
452
        });
617
        total_weight
617
    }
    /// Make those para ids valid by giving them enough credits, for benchmarking.
    #[cfg(feature = "runtime-benchmarks")]
    fn make_valid_para_ids(para_ids: &[ParaId]) {
        use frame_support::assert_ok;
        let blocks_per_session = EpochDurationInBlocks::get();
        // Enough credits to run any benchmark
        let block_credits = 20 * blocks_per_session;
        let session_credits = 20;
        for para_id in para_ids {
            assert_ok!(ServicesPayment::set_block_production_credits(
                RuntimeOrigin::root(),
                *para_id,
                block_credits,
            ));
            assert_ok!(ServicesPayment::set_collator_assignment_credits(
                RuntimeOrigin::root(),
                *para_id,
                session_credits,
            ));
        }
    }
}
620
fn host_config_at_session(
620
    session_index_to_consider: SessionIndex,
620
) -> HostConfiguration<BlockNumber> {
620
    let pending_configs = runtime_parachains::configuration::PendingConfigs::<Runtime>::get();
    // We are not making any assumptions about number of configurations existing in pending config
    // storage item.
620
    pending_configs
620
        .into_iter()
        // First remove any pending configs greater than session index in consideration
620
        .filter(|element| element.0 <= session_index_to_consider)
        // Take the config for the highest (most recent) session
620
        .max_by_key(|(session, _config)| *session)
620
        .map(|(_session, config)| config)
        // If pending configs is empty after filter, read active config
620
        .unwrap_or_else(runtime_parachains::configuration::ActiveConfig::<Runtime>::get)
620
}
pub struct GetCoreAllocationConfigurationImpl;
impl Get<Option<CoreAllocationConfiguration>> for GetCoreAllocationConfigurationImpl {
620
    fn get() -> Option<CoreAllocationConfiguration> {
        // We do not have to check for session ending as new session always starts at block initialization which means
        // whenever this is called, we are either in old session or in start of a one
        // as on block initialization epoch index have been incremented and by extension session has been changed.
620
        let session_index_to_consider = Session::current_index() + 1;
620
        let max_parachain_percentage =
620
            CollatorConfiguration::max_parachain_cores_percentage(session_index_to_consider)
620
                .unwrap_or(Perbill::from_percent(50));
620
        let config_to_consider = host_config_at_session(session_index_to_consider);
620
        Some(CoreAllocationConfiguration {
620
            core_count: config_to_consider.scheduler_params.num_cores,
620
            max_parachain_percentage,
620
        })
620
    }
}
impl pallet_collator_assignment::Config for Runtime {
    type HostConfiguration = CollatorConfiguration;
    type ContainerChains = ContainerRegistrar;
    type SessionIndex = u32;
    type SelfParaId = MockParaId;
    type ShouldRotateAllCollators =
        RotateCollatorsEveryNSessions<ConfigurationCollatorRotationSessionPeriod>;
    type Randomness = pallet_collator_assignment::SolochainRandomness<
        BabeGetCollatorAssignmentRandomness<Runtime>,
    >;
    type RemoveInvulnerables = ();
    type ParaIdAssignmentHooks = ParaIdAssignmentHooksImpl;
    type CollatorAssignmentTip = ServicesPayment;
    type Currency = Balances;
    type ForceEmptyOrchestrator = ConstBool<true>;
    type CoreAllocationConfiguration = GetCoreAllocationConfigurationImpl;
    type WeightInfo = weights::pallet_collator_assignment::SubstrateWeight<Runtime>;
}
impl pallet_authority_assignment::Config for Runtime {
    type SessionIndex = u32;
    type AuthorityId = nimbus_primitives::NimbusId;
}
impl pallet_authority_mapping::Config for Runtime {
    type SessionIndex = u32;
    type SessionRemovalBoundary = ConstU32<3>;
    type AuthorityId = nimbus_primitives::NimbusId;
}
#[cfg(feature = "runtime-benchmarks")]
mod benchmark_helpers {
    use {
        super::*,
        babe_primitives::{
            digests::{PreDigest, SecondaryPlainPreDigest},
            BABE_ENGINE_ID,
        },
        frame_support::traits::Hooks,
        sp_runtime::{Digest, DigestItem},
    };
    fn end_block() {
        Babe::on_finalize(System::block_number());
        Session::on_finalize(System::block_number());
        Grandpa::on_finalize(System::block_number());
        TransactionPayment::on_finalize(System::block_number());
        Initializer::on_finalize(System::block_number());
        ContainerRegistrar::on_finalize(System::block_number());
        TanssiCollatorAssignment::on_finalize(System::block_number());
    }
    pub fn insert_authorities_and_slot_digests(slot: u64) {
        let pre_digest = Digest {
            logs: vec![DigestItem::PreRuntime(
                BABE_ENGINE_ID,
                PreDigest::SecondaryPlain(SecondaryPlainPreDigest {
                    slot: slot.into(),
                    authority_index: 0,
                })
                .encode(),
            )],
        };
        System::reset_events();
        System::initialize(
            &(System::block_number() + 1),
            &System::parent_hash(),
            &pre_digest,
        );
    }
    pub fn current_slot() -> u64 {
        Babe::current_slot().into()
    }
    fn start_block() {
        insert_authorities_and_slot_digests(current_slot() + 1);
        // Initialize the new block
        Babe::on_initialize(System::block_number());
        ContainerRegistrar::on_initialize(System::block_number());
        Session::on_initialize(System::block_number());
        Initializer::on_initialize(System::block_number());
        TanssiCollatorAssignment::on_initialize(System::block_number());
        InflationRewards::on_initialize(System::block_number());
    }
    pub fn session_to_block(n: u32) -> u32 {
        // let block_number = flashbox_runtime::Period::get() * n;
        let block_number = Babe::current_epoch().duration.saturated_into::<u32>() * n;
        // Add 1 because the block that emits the NewSession event cannot contain any extrinsics,
        // so this is the first block of the new session that can actually be used
        block_number + 1
    }
    pub fn run_to_block(n: u32) {
        while System::block_number() < n {
            run_block();
        }
    }
    pub fn run_block() {
        end_block();
        start_block()
    }
    pub fn run_to_session(n: u32) {
        run_to_block(session_to_block(n));
    }
}
#[cfg(all(test, feature = "try-runtime"))]
mod remote_tests {
    use {
        super::*,
        frame_try_runtime::{runtime_decl_for_try_runtime::TryRuntime, UpgradeCheckSelect},
        remote_externalities::{
            Builder, Mode, OfflineConfig, OnlineConfig, SnapshotConfig, Transport,
        },
        std::env::var,
    };
    #[tokio::test]
    async fn run_migrations() {
        if var("RUN_MIGRATION_TESTS").is_err() {
            return;
        }
        sp_tracing::try_init_simple();
        let transport: Transport = var("WS")
            .unwrap_or("wss://starlight-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));
    }
}