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
#![cfg_attr(not(feature = "std"), no_std)]
18
// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.
19
#![recursion_limit = "256"]
20

            
21
// Make the WASM binary available.
22
#[cfg(feature = "std")]
23
include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
24

            
25
pub mod xcm_config;
26

            
27
use polkadot_runtime_common::SlowAdjustingFeeUpdate;
28
#[cfg(feature = "std")]
29
use sp_version::NativeVersion;
30

            
31
#[cfg(any(feature = "std", test))]
32
pub use sp_runtime::BuildStorage;
33

            
34
pub mod weights;
35

            
36
#[cfg(test)]
37
mod tests;
38

            
39
use {
40
    cumulus_pallet_parachain_system::{
41
        RelayChainStateProof, RelayNumberMonotonicallyIncreases, RelaychainDataProvider,
42
        RelaychainStateProvider,
43
    },
44
    cumulus_primitives_core::{
45
        relay_chain::{self, SessionIndex},
46
        AggregateMessageOrigin, BodyId, ParaId,
47
    },
48
    frame_support::{
49
        construct_runtime,
50
        dispatch::{DispatchClass, DispatchErrorWithPostInfo},
51
        genesis_builder_helper::{build_state, get_preset},
52
        pallet_prelude::DispatchResult,
53
        parameter_types,
54
        traits::{
55
            fungible::{Balanced, Credit, Inspect, InspectHold, Mutate, MutateHold},
56
            tokens::{
57
                imbalance::ResolveTo, ConversionToAssetBalance, PayFromAccount, Precision,
58
                Preservation, UnityAssetBalanceConversion,
59
            },
60
            ConstBool, ConstU128, ConstU32, ConstU64, ConstU8, Contains, EitherOfDiverse,
61
            Imbalance, InsideBoth, InstanceFilter, OnUnbalanced, ValidatorRegistration,
62
        },
63
        weights::{
64
            constants::{
65
                BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight,
66
                WEIGHT_REF_TIME_PER_SECOND,
67
            },
68
            ConstantMultiplier, Weight, WeightToFee as _, WeightToFeeCoefficient,
69
            WeightToFeeCoefficients, WeightToFeePolynomial,
70
        },
71
        PalletId,
72
    },
73
    frame_system::{
74
        limits::{BlockLength, BlockWeights},
75
        EnsureRoot, EnsureSigned,
76
    },
77
    nimbus_primitives::{NimbusId, SlotBeacon},
78
    pallet_balances::NegativeImbalance,
79
    pallet_collator_assignment::{GetRandomnessForNextBlock, RotateCollatorsEveryNSessions},
80
    pallet_invulnerables::InvulnerableRewardDistribution,
81
    pallet_pooled_staking::traits::{IsCandidateEligible, Timer},
82
    pallet_registrar::RegistrarHooks,
83
    pallet_registrar_runtime_api::ContainerChainGenesisData,
84
    pallet_services_payment::{ProvideBlockProductionCost, ProvideCollatorAssignmentCost},
85
    pallet_session::{SessionManager, ShouldEndSession},
86
    pallet_stream_payment_runtime_api::{StreamPaymentApiError, StreamPaymentApiStatus},
87
    pallet_transaction_payment::FungibleAdapter,
88
    pallet_xcm_core_buyer::BuyingError,
89
    polkadot_runtime_common::BlockHashCount,
90
    scale_info::{prelude::format, TypeInfo},
91
    serde::{Deserialize, Serialize},
92
    smallvec::smallvec,
93
    sp_api::impl_runtime_apis,
94
    sp_consensus_aura::SlotDuration,
95
    sp_consensus_slots::Slot,
96
    sp_core::{
97
        crypto::KeyTypeId, Decode, Encode, Get, MaxEncodedLen, OpaqueMetadata, RuntimeDebug, H256,
98
    },
99
    sp_runtime::{
100
        create_runtime_str, generic, impl_opaque_keys,
101
        traits::{
102
            AccountIdConversion, AccountIdLookup, BlakeTwo256, Block as BlockT, Hash as HashT,
103
            IdentityLookup, Verify,
104
        },
105
        transaction_validity::{TransactionSource, TransactionValidity},
106
        AccountId32, ApplyExtrinsicResult,
107
    },
108
    sp_std::{collections::btree_set::BTreeSet, marker::PhantomData, prelude::*},
109
    sp_version::RuntimeVersion,
110
    staging_xcm::{
111
        IntoVersion, VersionedAssetId, VersionedAssets, VersionedLocation, VersionedXcm,
112
    },
113
    tp_traits::{
114
        apply, derive_storage_traits, GetContainerChainAuthor, GetHostConfiguration,
115
        GetSessionContainerChains, MaybeSelfChainBlockAuthor, RelayStorageRootProvider,
116
        RemoveInvulnerables, RemoveParaIdsWithNoCredits, SlotFrequency,
117
    },
118
    tp_xcm_core_buyer::BuyCoreCollatorProof,
119
    xcm_runtime_apis::{
120
        dry_run::{CallDryRunEffects, Error as XcmDryRunApiError, XcmDryRunEffects},
121
        fees::Error as XcmPaymentApiError,
122
    },
123
};
124
pub use {
125
    dp_core::{AccountId, Address, Balance, BlockNumber, Hash, Header, Index, Signature},
126
    sp_runtime::{MultiAddress, Perbill, Permill},
127
};
128

            
129
/// Block type as expected by this runtime.
130
pub type Block = generic::Block<Header, UncheckedExtrinsic>;
131
/// A Block signed with a Justification
132
pub type SignedBlock = generic::SignedBlock<Block>;
133
/// BlockId type as expected by this runtime.
134
pub type BlockId = generic::BlockId<Block>;
135

            
136
/// CollatorId type expected by this runtime.
137
pub type CollatorId = AccountId;
138

            
139
/// The SignedExtension to the basic transaction logic.
140
pub type SignedExtra = (
141
    frame_system::CheckNonZeroSender<Runtime>,
142
    frame_system::CheckSpecVersion<Runtime>,
143
    frame_system::CheckTxVersion<Runtime>,
144
    frame_system::CheckGenesis<Runtime>,
145
    frame_system::CheckEra<Runtime>,
146
    frame_system::CheckNonce<Runtime>,
147
    frame_system::CheckWeight<Runtime>,
148
    pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
149
    cumulus_primitives_storage_weight_reclaim::StorageWeightReclaim<Runtime>,
150
);
151

            
152
/// Unchecked extrinsic type as expected by this runtime.
153
pub type UncheckedExtrinsic =
154
    generic::UncheckedExtrinsic<Address, RuntimeCall, Signature, SignedExtra>;
155

            
156
/// Extrinsic type that has already been checked.
157
pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, RuntimeCall, SignedExtra>;
158

            
159
/// Executive: handles dispatch to the various modules.
160
pub type Executive = frame_executive::Executive<
161
    Runtime,
162
    Block,
163
    frame_system::ChainContext<Runtime>,
164
    Runtime,
165
    AllPalletsWithSystem,
166
>;
167

            
168
/// DANCE, the native token, uses 12 decimals of precision.
169
pub mod currency {
170
    use super::Balance;
171

            
172
    // Provide a common factor between runtimes based on a supply of 10_000_000 tokens.
173
    pub const SUPPLY_FACTOR: Balance = 100;
174

            
175
    pub const MICRODANCE: Balance = 1_000_000;
176
    pub const MILLIDANCE: Balance = 1_000_000_000;
177
    pub const DANCE: Balance = 1_000_000_000_000;
178
    pub const KILODANCE: Balance = 1_000_000_000_000_000;
179

            
180
    pub const STORAGE_BYTE_FEE: Balance = 100 * MICRODANCE * SUPPLY_FACTOR;
181
    pub const STORAGE_ITEM_FEE: Balance = 100 * MILLIDANCE * SUPPLY_FACTOR;
182

            
183
2361
    pub const fn deposit(items: u32, bytes: u32) -> Balance {
184
2361
        items as Balance * STORAGE_ITEM_FEE + (bytes as Balance) * STORAGE_BYTE_FEE
185
2361
    }
186
}
187

            
188
/// Handles converting a weight scalar to a fee value, based on the scale and granularity of the
189
/// node's balance type.
190
///
191
/// This should typically create a mapping between the following ranges:
192
///   - `[0, MAXIMUM_BLOCK_WEIGHT]`
193
///   - `[Balance::min, Balance::max]`
194
///
195
/// Yet, it can be used for any other sort of change to weight-fee. Some examples being:
196
///   - Setting it to `0` will essentially disable the weight fee.
197
///   - Setting it to `1` will cause the literal `#[weight = x]` values to be charged.
198
pub struct WeightToFee;
199
impl WeightToFeePolynomial for WeightToFee {
200
    type Balance = Balance;
201
7625
    fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {
202
7625
        // in Rococo, extrinsic base weight (smallest non-zero weight) is mapped to 1 MILLIUNIT:
203
7625
        // in our template, we map to 1/10 of that, or 1/10 MILLIUNIT
204
7625
        let p = MILLIUNIT / 10;
205
7625
        let q = 100 * Balance::from(ExtrinsicBaseWeight::get().ref_time());
206
7625
        smallvec![WeightToFeeCoefficient {
207
            degree: 1,
208
            negative: false,
209
            coeff_frac: Perbill::from_rational(p % q, q),
210
            coeff_integer: p / q,
211
        }]
212
7625
    }
213
}
214

            
215
/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know
216
/// the specifics of the runtime. They can then be made to be agnostic over specific formats
217
/// of data like extrinsics, allowing for them to continue syncing the network through upgrades
218
/// to even the core data structures.
219
pub mod opaque {
220
    use {
221
        super::*,
222
        sp_runtime::{
223
            generic,
224
            traits::{BlakeTwo256, Hash as HashT},
225
        },
226
    };
227

            
228
    pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;
229
    /// Opaque block header type.
230
    pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
231
    /// Opaque block type.
232
    pub type Block = generic::Block<Header, UncheckedExtrinsic>;
233
    /// Opaque block identifier type.
234
    pub type BlockId = generic::BlockId<Block>;
235
    /// Opaque block hash type.
236
    pub type Hash = <BlakeTwo256 as HashT>::Output;
237
    /// Opaque signature type.
238
    pub use super::Signature;
239
}
240

            
241
impl_opaque_keys! {
242
    pub struct SessionKeys {
243
        pub nimbus: Initializer,
244
    }
245
}
246

            
247
#[sp_version::runtime_version]
248
pub const VERSION: RuntimeVersion = RuntimeVersion {
249
    spec_name: create_runtime_str!("dancebox"),
250
    impl_name: create_runtime_str!("dancebox"),
251
    authoring_version: 1,
252
    spec_version: 900,
253
    impl_version: 0,
254
    apis: RUNTIME_API_VERSIONS,
255
    transaction_version: 1,
256
    state_version: 1,
257
};
258

            
259
/// This determines the average expected block time that we are targeting.
260
/// Blocks will be produced at a minimum duration defined by `SLOT_DURATION`.
261
/// `SLOT_DURATION` is picked up by `pallet_timestamp` which is in turn picked
262
/// up by `pallet_aura` to implement `fn slot_duration()`.
263
///
264
/// Change this to adjust the block time.
265
pub const MILLISECS_PER_BLOCK: u64 = 6000;
266

            
267
// NOTE: Currently it is not possible to change the slot duration after the chain has started.
268
//       Attempting to do so will brick block production.
269
pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;
270

            
271
// Time is measured by number of blocks.
272
pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);
273
pub const HOURS: BlockNumber = MINUTES * 60;
274
pub const DAYS: BlockNumber = HOURS * 24;
275

            
276
// Unit = the base number of indivisible units for balances
277
pub const UNIT: Balance = 1_000_000_000_000;
278
pub const MILLIUNIT: Balance = 1_000_000_000;
279
pub const MICROUNIT: Balance = 1_000_000;
280
/// The existential deposit. Set to 1/10 of the Connected Relay Chain.
281
pub const EXISTENTIAL_DEPOSIT: Balance = MILLIUNIT;
282

            
283
/// We assume that ~5% of the block weight is consumed by `on_initialize` handlers. This is
284
/// used to limit the maximal weight of a single extrinsic.
285
const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(5);
286

            
287
/// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used by
288
/// `Operational` extrinsics.
289
const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);
290

            
291
/// We allow for 2 seconds of compute with a 6 second average block time
292
const MAXIMUM_BLOCK_WEIGHT: Weight = Weight::from_parts(
293
    WEIGHT_REF_TIME_PER_SECOND.saturating_mul(2),
294
    cumulus_primitives_core::relay_chain::MAX_POV_SIZE as u64,
295
);
296

            
297
/// The version information used to identify this runtime when compiled natively.
298
#[cfg(feature = "std")]
299
1800
pub fn native_version() -> NativeVersion {
300
1800
    NativeVersion {
301
1800
        runtime_version: VERSION,
302
1800
        can_author_with: Default::default(),
303
1800
    }
304
1800
}
305

            
306
parameter_types! {
307
    pub const Version: RuntimeVersion = VERSION;
308

            
309
    // This part is copied from Substrate's `bin/node/runtime/src/lib.rs`.
310
    //  The `RuntimeBlockLength` and `RuntimeBlockWeights` exist here because the
311
    // `DeletionWeightLimit` and `DeletionQueueDepth` depend on those to parameterize
312
    // the lazy contract deletion.
313
    pub RuntimeBlockLength: BlockLength =
314
        BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);
315
    pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()
316
        .base_block(BlockExecutionWeight::get())
317
824784
        .for_class(DispatchClass::all(), |weights| {
318
824784
            weights.base_extrinsic = ExtrinsicBaseWeight::get();
319
824784
        })
320
274928
        .for_class(DispatchClass::Normal, |weights| {
321
274928
            weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);
322
274928
        })
323
274928
        .for_class(DispatchClass::Operational, |weights| {
324
274928
            weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);
325
274928
            // Operational transactions have some extra reserved space, so that they
326
274928
            // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.
327
274928
            weights.reserved = Some(
328
274928
                MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT
329
274928
            );
330
274928
        })
331
        .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)
332
        .build_or_panic();
333
    pub const SS58Prefix: u16 = 42;
334
}
335

            
336
// Configure FRAME pallets to include in runtime.
337

            
338
impl frame_system::Config for Runtime {
339
    /// The identifier used to distinguish between accounts.
340
    type AccountId = AccountId;
341
    /// The aggregated dispatch type that is available for extrinsics.
342
    type RuntimeCall = RuntimeCall;
343
    /// The lookup mechanism to get account ID from whatever is passed in dispatchers.
344
    type Lookup = AccountIdLookup<AccountId, ()>;
345
    /// The index type for storing how many extrinsics an account has signed.
346
    type Nonce = Index;
347
    /// The index type for blocks.
348
    type Block = Block;
349
    /// The type for hashing blocks and tries.
350
    type Hash = Hash;
351
    /// The hashing algorithm used.
352
    type Hashing = BlakeTwo256;
353
    /// The ubiquitous event type.
354
    type RuntimeEvent = RuntimeEvent;
355
    /// The ubiquitous origin type.
356
    type RuntimeOrigin = RuntimeOrigin;
357
    /// Maximum number of block number to block hash mappings to keep (oldest pruned first).
358
    type BlockHashCount = BlockHashCount;
359
    /// Runtime version.
360
    type Version = Version;
361
    /// Converts a module to an index of this module in the runtime.
362
    type PalletInfo = PalletInfo;
363
    /// The data to be stored in an account.
364
    type AccountData = pallet_balances::AccountData<Balance>;
365
    /// What to do if a new account is created.
366
    type OnNewAccount = ();
367
    /// What to do if an account is fully reaped from the system.
368
    type OnKilledAccount = ();
369
    /// The weight of database operations that the runtime can invoke.
370
    type DbWeight = RocksDbWeight;
371
    /// The basic call filter to use in dispatchable.
372
    type BaseCallFilter = InsideBoth<MaintenanceMode, TxPause>;
373
    /// Weight information for the extrinsics of this pallet.
374
    type SystemWeightInfo = weights::frame_system::SubstrateWeight<Runtime>;
375
    /// Block & extrinsics weights: base values and limits.
376
    type BlockWeights = RuntimeBlockWeights;
377
    /// The maximum length of a block (in bytes).
378
    type BlockLength = RuntimeBlockLength;
379
    /// This is used as an identifier of the chain. 42 is the generic substrate prefix.
380
    type SS58Prefix = SS58Prefix;
381
    /// The action to take on a Runtime Upgrade
382
    type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;
383
    type MaxConsumers = frame_support::traits::ConstU32<16>;
384
    type RuntimeTask = RuntimeTask;
385
    type SingleBlockMigrations = ();
386
    type MultiBlockMigrator = ();
387
    type PreInherents = ();
388
    type PostInherents = ();
389
    type PostTransactions = ();
390
}
391

            
392
impl pallet_timestamp::Config for Runtime {
393
    /// A timestamp: milliseconds since the unix epoch.
394
    type Moment = u64;
395
    type OnTimestampSet = dp_consensus::OnTimestampSet<
396
        <Self as pallet_author_inherent::Config>::SlotBeacon,
397
        ConstU64<{ SLOT_DURATION }>,
398
    >;
399
    type MinimumPeriod = ConstU64<{ SLOT_DURATION / 2 }>;
400
    type WeightInfo = weights::pallet_timestamp::SubstrateWeight<Runtime>;
401
}
402

            
403
pub struct CanAuthor;
404
impl nimbus_primitives::CanAuthor<NimbusId> for CanAuthor {
405
16220
    fn can_author(author: &NimbusId, slot: &u32) -> bool {
406
16220
        let authorities = AuthorityAssignment::collator_container_chain(Session::current_index())
407
16220
            .expect("authorities should be set")
408
16220
            .orchestrator_chain;
409
16220

            
410
16220
        if authorities.is_empty() {
411
            return false;
412
16220
        }
413
16220

            
414
16220
        let author_index = (*slot as usize) % authorities.len();
415
16220
        let expected_author = &authorities[author_index];
416
16220

            
417
16220
        expected_author == author
418
16220
    }
419
    #[cfg(feature = "runtime-benchmarks")]
420
    fn get_authors(_slot: &u32) -> Vec<NimbusId> {
421
        AuthorityAssignment::collator_container_chain(Session::current_index())
422
            .expect("authorities should be set")
423
            .orchestrator_chain
424
    }
425
}
426

            
427
impl pallet_author_inherent::Config for Runtime {
428
    type AuthorId = NimbusId;
429
    type AccountLookup = dp_consensus::NimbusLookUp;
430
    type CanAuthor = CanAuthor;
431
    type SlotBeacon = dp_consensus::AuraDigestSlotBeacon<Runtime>;
432
    type WeightInfo = weights::pallet_author_inherent::SubstrateWeight<Runtime>;
433
}
434

            
435
parameter_types! {
436
    pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT;
437
}
438

            
439
impl pallet_balances::Config for Runtime {
440
    type MaxLocks = ConstU32<50>;
441
    /// The type for recording an account's balance.
442
    type Balance = Balance;
443
    /// The ubiquitous event type.
444
    type RuntimeEvent = RuntimeEvent;
445
    type DustRemoval = ();
446
    type ExistentialDeposit = ExistentialDeposit;
447
    type AccountStore = System;
448
    type MaxReserves = ConstU32<50>;
449
    type ReserveIdentifier = [u8; 8];
450
    type FreezeIdentifier = RuntimeFreezeReason;
451
    type MaxFreezes = ConstU32<10>;
452
    type RuntimeHoldReason = RuntimeHoldReason;
453
    type RuntimeFreezeReason = RuntimeFreezeReason;
454
    type WeightInfo = weights::pallet_balances::SubstrateWeight<Runtime>;
455
}
456

            
457
pub struct DealWithFees<R>(sp_std::marker::PhantomData<R>);
458
impl<R> OnUnbalanced<Credit<R::AccountId, pallet_balances::Pallet<R>>> for DealWithFees<R>
459
where
460
    R: pallet_balances::Config + pallet_treasury::Config + frame_system::Config,
461
    pallet_treasury::NegativeImbalanceOf<R>: From<NegativeImbalance<R>>,
462
{
463
    // this seems to be called for substrate-based transactions
464
1484
    fn on_unbalanceds<B>(
465
1484
        mut fees_then_tips: impl Iterator<Item = Credit<R::AccountId, pallet_balances::Pallet<R>>>,
466
1484
    ) {
467
1484
        if let Some(fees) = fees_then_tips.next() {
468
            // 80% is burned, 20% goes to the treasury
469
            // Same policy applies for tips as well
470
1484
            let burn_percentage = 80;
471
1484
            let treasury_percentage = 20;
472
1484

            
473
1484
            let (_, to_treasury) = fees.ration(burn_percentage, treasury_percentage);
474
1484
            ResolveTo::<pallet_treasury::TreasuryAccountId<R>, pallet_balances::Pallet<R>>::on_unbalanced(to_treasury);
475
            // Balances pallet automatically burns dropped Negative Imbalances by decreasing total_supply accordingly
476
            // handle tip if there is one
477
1484
            if let Some(tip) = fees_then_tips.next() {
478
1484
                let (_, to_treasury) = tip.ration(burn_percentage, treasury_percentage);
479
1484
                ResolveTo::<pallet_treasury::TreasuryAccountId<R>, pallet_balances::Pallet<R>>::on_unbalanced(to_treasury);
480
1484
            }
481
        }
482
1484
    }
483

            
484
    // this is called from pallet_evm for Ethereum-based transactions
485
    // (technically, it calls on_unbalanced, which calls this when non-zero)
486
    fn on_nonzero_unbalanced(amount: Credit<R::AccountId, pallet_balances::Pallet<R>>) {
487
        // 80% is burned, 20% goes to the treasury
488
        let burn_percentage = 80;
489
        let treasury_percentage = 20;
490

            
491
        let (_, to_treasury) = amount.ration(burn_percentage, treasury_percentage);
492
        ResolveTo::<pallet_treasury::TreasuryAccountId<R>, pallet_balances::Pallet<R>>::on_unbalanced(to_treasury);
493
    }
494
}
495

            
496
parameter_types! {
497
    pub const TransactionByteFee: Balance = 1;
498
}
499

            
500
impl pallet_transaction_payment::Config for Runtime {
501
    type RuntimeEvent = RuntimeEvent;
502
    // This will burn 80% from fees & tips and deposit the remainder into the treasury
503
    type OnChargeTransaction = FungibleAdapter<Balances, DealWithFees<Runtime>>;
504
    type OperationalFeeMultiplier = ConstU8<5>;
505
    type WeightToFee = WeightToFee;
506
    type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;
507
    type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Self>;
508
}
509

            
510
parameter_types! {
511
    pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
512
    pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
513
    pub const RelayOrigin: AggregateMessageOrigin = AggregateMessageOrigin::Parent;
514
}
515

            
516
pub const RELAY_CHAIN_SLOT_DURATION_MILLIS: u32 = 6000;
517
pub const UNINCLUDED_SEGMENT_CAPACITY: u32 = 3;
518
pub const BLOCK_PROCESSING_VELOCITY: u32 = 1;
519

            
520
type ConsensusHook = pallet_async_backing::consensus_hook::FixedVelocityConsensusHook<
521
    Runtime,
522
    BLOCK_PROCESSING_VELOCITY,
523
    UNINCLUDED_SEGMENT_CAPACITY,
524
>;
525

            
526
impl cumulus_pallet_parachain_system::Config for Runtime {
527
    type WeightInfo = weights::cumulus_pallet_parachain_system::SubstrateWeight<Runtime>;
528
    type RuntimeEvent = RuntimeEvent;
529
    type OnSystemEvent = ();
530
    type SelfParaId = parachain_info::Pallet<Runtime>;
531
    type OutboundXcmpMessageSource = XcmpQueue;
532
    type DmpQueue = frame_support::traits::EnqueueWithOrigin<MessageQueue, RelayOrigin>;
533
    type ReservedDmpWeight = ReservedDmpWeight;
534
    type XcmpMessageHandler = XcmpQueue;
535
    type ReservedXcmpWeight = ReservedXcmpWeight;
536
    type CheckAssociatedRelayNumber = RelayNumberMonotonicallyIncreases;
537
    type ConsensusHook = ConsensusHook;
538
}
539
pub struct ParaSlotProvider;
540
impl Get<(Slot, SlotDuration)> for ParaSlotProvider {
541
14227
    fn get() -> (Slot, SlotDuration) {
542
14227
        let slot = u64::from(<Runtime as pallet_author_inherent::Config>::SlotBeacon::slot());
543
14227
        (Slot::from(slot), SlotDuration::from_millis(SLOT_DURATION))
544
14227
    }
545
}
546

            
547
parameter_types! {
548
    pub const ExpectedBlockTime: u64 = MILLISECS_PER_BLOCK;
549
}
550

            
551
impl pallet_async_backing::Config for Runtime {
552
    type AllowMultipleBlocksPerSlot = ConstBool<true>;
553
    type GetAndVerifySlot =
554
        pallet_async_backing::ParaSlot<RELAY_CHAIN_SLOT_DURATION_MILLIS, ParaSlotProvider>;
555
    type ExpectedBlockTime = ExpectedBlockTime;
556
}
557

            
558
/// Only callable after `set_validation_data` is called which forms this proof the same way
559
1548
fn relay_chain_state_proof() -> RelayChainStateProof {
560
1548
    let relay_storage_root =
561
1548
        RelaychainDataProvider::<Runtime>::current_relay_chain_state().state_root;
562
1548
    let relay_chain_state = cumulus_pallet_parachain_system::RelayStateProof::<Runtime>::get()
563
1548
        .expect("set in `set_validation_data`");
564
1548
    RelayChainStateProof::new(ParachainInfo::get(), relay_storage_root, relay_chain_state)
565
1548
        .expect("Invalid relay chain state proof, already constructed in `set_validation_data`")
566
1548
}
567

            
568
pub struct BabeCurrentBlockRandomnessGetter;
569
impl BabeCurrentBlockRandomnessGetter {
570
1548
    fn get_block_randomness() -> Option<Hash> {
571
1548
        if cfg!(feature = "runtime-benchmarks") {
572
            // storage reads as per actual reads
573
            let _relay_storage_root =
574
                RelaychainDataProvider::<Runtime>::current_relay_chain_state().state_root;
575

            
576
            let _relay_chain_state =
577
                cumulus_pallet_parachain_system::RelayStateProof::<Runtime>::get();
578
            let benchmarking_babe_output = Hash::default();
579
            return Some(benchmarking_babe_output);
580
1548
        }
581
1548

            
582
1548
        relay_chain_state_proof()
583
1548
            .read_optional_entry::<Option<Hash>>(
584
1548
                relay_chain::well_known_keys::CURRENT_BLOCK_RANDOMNESS,
585
1548
            )
586
1548
            .ok()
587
1548
            .flatten()
588
1548
            .flatten()
589
1548
    }
590

            
591
    /// Return the block randomness from the relay mixed with the provided subject.
592
    /// This ensures that the randomness will be different on different pallets, as long as the subject is different.
593
    // TODO: audit usage of randomness API
594
    // https://github.com/paritytech/polkadot/issues/2601
595
1548
    fn get_block_randomness_mixed(subject: &[u8]) -> Option<Hash> {
596
1548
        Self::get_block_randomness()
597
1548
            .map(|random_hash| mix_randomness::<Runtime>(random_hash, subject))
598
1548
    }
599
}
600

            
601
/// Combines the vrf output of the previous relay block with the provided subject.
602
/// This ensures that the randomness will be different on different pallets, as long as the subject is different.
603
26
fn mix_randomness<T: frame_system::Config>(vrf_output: Hash, subject: &[u8]) -> T::Hash {
604
26
    let mut digest = Vec::new();
605
26
    digest.extend_from_slice(vrf_output.as_ref());
606
26
    digest.extend_from_slice(subject);
607
26

            
608
26
    T::Hashing::hash(digest.as_slice())
609
26
}
610

            
611
// Randomness trait
612
impl frame_support::traits::Randomness<Hash, BlockNumber> for BabeCurrentBlockRandomnessGetter {
613
    fn random(subject: &[u8]) -> (Hash, BlockNumber) {
614
        let block_number = frame_system::Pallet::<Runtime>::block_number();
615
        let randomness = Self::get_block_randomness_mixed(subject).unwrap_or_default();
616

            
617
        (randomness, block_number)
618
    }
619
}
620

            
621
pub struct OwnApplySession;
622
impl pallet_initializer::ApplyNewSession<Runtime> for OwnApplySession {
623
1732
    fn apply_new_session(
624
1732
        _changed: bool,
625
1732
        session_index: u32,
626
1732
        all_validators: Vec<(AccountId, NimbusId)>,
627
1732
        queued: Vec<(AccountId, NimbusId)>,
628
1732
    ) {
629
1732
        // We first initialize Configuration
630
1732
        Configuration::initializer_on_new_session(&session_index);
631
1732
        // Next: Registrar
632
1732
        Registrar::initializer_on_new_session(&session_index);
633
1732
        // Next: AuthorityMapping
634
1732
        AuthorityMapping::initializer_on_new_session(&session_index, &all_validators);
635
1732

            
636
6494
        let next_collators = queued.iter().map(|(k, _)| k.clone()).collect();
637
1732

            
638
1732
        // Next: CollatorAssignment
639
1732
        let assignments =
640
1732
            CollatorAssignment::initializer_on_new_session(&session_index, next_collators);
641
1732

            
642
1732
        let queued_id_to_nimbus_map = queued.iter().cloned().collect();
643
1732
        AuthorityAssignment::initializer_on_new_session(
644
1732
            &session_index,
645
1732
            &queued_id_to_nimbus_map,
646
1732
            &assignments.next_assignment,
647
1732
        );
648
1732
    }
649
}
650

            
651
impl pallet_initializer::Config for Runtime {
652
    type SessionIndex = u32;
653

            
654
    /// The identifier type for an authority.
655
    type AuthorityId = NimbusId;
656

            
657
    type SessionHandler = OwnApplySession;
658
}
659

            
660
impl parachain_info::Config for Runtime {}
661

            
662
/// Returns a list of collators by combining pallet_invulnerables and pallet_pooled_staking.
663
pub struct CollatorsFromInvulnerablesAndThenFromStaking;
664

            
665
/// Play the role of the session manager.
666
impl SessionManager<CollatorId> for CollatorsFromInvulnerablesAndThenFromStaking {
667
1924
    fn new_session(index: SessionIndex) -> Option<Vec<CollatorId>> {
668
1924
        if <frame_system::Pallet<Runtime>>::block_number() == 0 {
669
            // Do not show this log in genesis
670
384
            log::debug!(
671
                "assembling new collators for new session {} at #{:?}",
672
                index,
673
                <frame_system::Pallet<Runtime>>::block_number(),
674
            );
675
        } else {
676
1540
            log::info!(
677
1328
                "assembling new collators for new session {} at #{:?}",
678
1328
                index,
679
1328
                <frame_system::Pallet<Runtime>>::block_number(),
680
            );
681
        }
682

            
683
1924
        let invulnerables = Invulnerables::invulnerables().to_vec();
684
1924
        let candidates_staking =
685
1924
            pallet_pooled_staking::SortedEligibleCandidates::<Runtime>::get().to_vec();
686
1924
        // Max number of collators is set in pallet_configuration
687
1924
        let target_session_index = index.saturating_add(1);
688
1924
        let max_collators =
689
1924
            <Configuration as GetHostConfiguration<u32>>::max_collators(target_session_index);
690
1924
        let collators = invulnerables
691
1924
            .iter()
692
1924
            .cloned()
693
1924
            .chain(candidates_staking.into_iter().filter_map(|elig| {
694
192
                let cand = elig.candidate;
695
192
                if invulnerables.contains(&cand) {
696
                    // If a candidate is both in pallet_invulnerables and pallet_staking, do not count it twice
697
48
                    None
698
                } else {
699
144
                    Some(cand)
700
                }
701
1924
            }))
702
1924
            .take(max_collators as usize)
703
1924
            .collect();
704
1924

            
705
1924
        // TODO: weight?
706
1924
        /*
707
1924
        frame_system::Pallet::<T>::register_extra_weight_unchecked(
708
1924
            T::WeightInfo::new_session(invulnerables.len() as u32),
709
1924
            DispatchClass::Mandatory,
710
1924
        );
711
1924
        */
712
1924
        Some(collators)
713
1924
    }
714
1732
    fn start_session(_: SessionIndex) {
715
1732
        // we don't care.
716
1732
    }
717
1540
    fn end_session(_: SessionIndex) {
718
1540
        // we don't care.
719
1540
    }
720
}
721

            
722
parameter_types! {
723
    pub const Period: u32 = prod_or_fast!(1 * HOURS, 1 * MINUTES);
724
    pub const Offset: u32 = 0;
725
}
726

            
727
impl pallet_session::Config for Runtime {
728
    type RuntimeEvent = RuntimeEvent;
729
    type ValidatorId = CollatorId;
730
    // we don't have stash and controller, thus we don't need the convert as well.
731
    type ValidatorIdOf = pallet_invulnerables::IdentityCollator;
732
    type ShouldEndSession = pallet_session::PeriodicSessions<Period, Offset>;
733
    type NextSessionRotation = pallet_session::PeriodicSessions<Period, Offset>;
734
    type SessionManager = CollatorsFromInvulnerablesAndThenFromStaking;
735
    // Essentially just Aura, but let's be pedantic.
736
    type SessionHandler = <SessionKeys as sp_runtime::traits::OpaqueKeys>::KeyTypeIdProviders;
737
    type Keys = SessionKeys;
738
    type WeightInfo = weights::pallet_session::SubstrateWeight<Runtime>;
739
}
740

            
741
/// Read full_rotation_period from pallet_configuration
742
pub struct ConfigurationCollatorRotationSessionPeriod;
743

            
744
impl Get<u32> for ConfigurationCollatorRotationSessionPeriod {
745
3376
    fn get() -> u32 {
746
3376
        Configuration::config().full_rotation_period
747
3376
    }
748
}
749

            
750
pub struct BabeGetRandomnessForNextBlock;
751

            
752
impl GetRandomnessForNextBlock<u32> for BabeGetRandomnessForNextBlock {
753
32326
    fn should_end_session(n: u32) -> bool {
754
32326
        <Runtime as pallet_session::Config>::ShouldEndSession::should_end_session(n)
755
32326
    }
756

            
757
1548
    fn get_randomness() -> [u8; 32] {
758
1548
        let block_number = System::block_number();
759
1548
        let random_seed = if block_number != 0 {
760
26
            if let Some(random_hash) =
761
1548
                BabeCurrentBlockRandomnessGetter::get_block_randomness_mixed(b"CollatorAssignment")
762
            {
763
                // Return random_hash as a [u8; 32] instead of a Hash
764
26
                let mut buf = [0u8; 32];
765
26
                let len = sp_std::cmp::min(32, random_hash.as_ref().len());
766
26
                buf[..len].copy_from_slice(&random_hash.as_ref()[..len]);
767
26

            
768
26
                buf
769
            } else {
770
                // If there is no randomness (e.g when running in dev mode), return [0; 32]
771
1522
                [0; 32]
772
            }
773
        } else {
774
            // In block 0 (genesis) there is no randomness
775
            [0; 32]
776
        };
777

            
778
1548
        random_seed
779
1548
    }
780
}
781

            
782
pub struct RemoveInvulnerablesImpl;
783

            
784
impl RemoveInvulnerables<CollatorId> for RemoveInvulnerablesImpl {
785
2236
    fn remove_invulnerables(
786
2236
        collators: &mut Vec<CollatorId>,
787
2236
        num_invulnerables: usize,
788
2236
    ) -> Vec<CollatorId> {
789
2236
        if num_invulnerables == 0 {
790
            return vec![];
791
2236
        }
792
2236
        // TODO: check if this works on session changes
793
2236
        let all_invulnerables = pallet_invulnerables::Invulnerables::<Runtime>::get();
794
2236
        if all_invulnerables.is_empty() {
795
96
            return vec![];
796
2140
        }
797
2140
        let mut invulnerables = vec![];
798
2140
        // TODO: use binary_search when invulnerables are sorted
799
2854
        collators.retain(|x| {
800
2854
            if invulnerables.len() < num_invulnerables && all_invulnerables.contains(x) {
801
2041
                invulnerables.push(x.clone());
802
2041
                false
803
            } else {
804
813
                true
805
            }
806
2854
        });
807
2140

            
808
2140
        invulnerables
809
2236
    }
810
}
811

            
812
pub struct RemoveParaIdsWithNoCreditsImpl;
813

            
814
impl RemoveParaIdsWithNoCredits for RemoveParaIdsWithNoCreditsImpl {
815
3464
    fn remove_para_ids_with_no_credits(
816
3464
        para_ids: &mut Vec<ParaId>,
817
3464
        currently_assigned: &BTreeSet<ParaId>,
818
3464
    ) {
819
3464
        let blocks_per_session = Period::get();
820
3464

            
821
3464
        para_ids.retain(|para_id| {
822
            // If the para has been assigned collators for this session it must have enough block credits
823
            // for the current and the next session.
824
3066
            let block_credits_needed = if currently_assigned.contains(para_id) {
825
2709
                blocks_per_session * 2
826
            } else {
827
357
                blocks_per_session
828
            };
829

            
830
            // Check if the container chain has enough credits for producing blocks
831
3066
            let free_block_credits = pallet_services_payment::BlockProductionCredits::<Runtime>::get(para_id)
832
3066
                .unwrap_or_default();
833
3066

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

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

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

            
847
264
            let remaining_block_credits = block_credits_needed.saturating_sub(free_block_credits);
848
264
            let remaining_session_credits = 1u32.saturating_sub(free_session_credits);
849
264

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

            
856
264
            let remaining_to_pay = remaining_block_credits_to_pay.saturating_add(remaining_session_credits_to_pay).saturating_add(max_tip);
857
264

            
858
264
            // This should take into account whether we tank goes below ED
859
264
            // The true refers to keepAlive
860
264
            Balances::can_withdraw(&pallet_services_payment::Pallet::<Runtime>::parachain_tank(*para_id), remaining_to_pay).into_result(true).is_ok()
861
3464
        });
862
3464
    }
863

            
864
    /// Make those para ids valid by giving them enough credits, for benchmarking.
865
    #[cfg(feature = "runtime-benchmarks")]
866
    fn make_valid_para_ids(para_ids: &[ParaId]) {
867
        use frame_support::assert_ok;
868

            
869
        let blocks_per_session = Period::get();
870
        // Enough credits to run any benchmark
871
        let block_credits = 20 * blocks_per_session;
872
        let session_credits = 20;
873

            
874
        for para_id in para_ids {
875
            assert_ok!(ServicesPayment::set_block_production_credits(
876
                RuntimeOrigin::root(),
877
                *para_id,
878
                block_credits,
879
            ));
880
            assert_ok!(ServicesPayment::set_collator_assignment_credits(
881
                RuntimeOrigin::root(),
882
                *para_id,
883
                session_credits,
884
            ));
885
        }
886
    }
887
}
888

            
889
impl pallet_collator_assignment::Config for Runtime {
890
    type RuntimeEvent = RuntimeEvent;
891
    type HostConfiguration = Configuration;
892
    type ContainerChains = Registrar;
893
    type SessionIndex = u32;
894
    type SelfParaId = ParachainInfo;
895
    type ShouldRotateAllCollators =
896
        RotateCollatorsEveryNSessions<ConfigurationCollatorRotationSessionPeriod>;
897
    type GetRandomnessForNextBlock = BabeGetRandomnessForNextBlock;
898
    type RemoveInvulnerables = RemoveInvulnerablesImpl;
899
    type RemoveParaIdsWithNoCredits = RemoveParaIdsWithNoCreditsImpl;
900
    type CollatorAssignmentHook = ServicesPayment;
901
    type CollatorAssignmentTip = ServicesPayment;
902
    type Currency = Balances;
903
    type ForceEmptyOrchestrator = ConstBool<false>;
904
    type CoreAllocationConfiguration = ();
905
    type WeightInfo = weights::pallet_collator_assignment::SubstrateWeight<Runtime>;
906
}
907

            
908
impl pallet_authority_assignment::Config for Runtime {
909
    type SessionIndex = u32;
910
    type AuthorityId = NimbusId;
911
}
912

            
913
pub const FIXED_BLOCK_PRODUCTION_COST: u128 = 1 * currency::MICRODANCE;
914
pub const FIXED_COLLATOR_ASSIGNMENT_COST: u128 = 100 * currency::MICRODANCE;
915

            
916
pub struct BlockProductionCost<Runtime>(PhantomData<Runtime>);
917
impl ProvideBlockProductionCost<Runtime> for BlockProductionCost<Runtime> {
918
542
    fn block_cost(_para_id: &ParaId) -> (u128, Weight) {
919
542
        (FIXED_BLOCK_PRODUCTION_COST, Weight::zero())
920
542
    }
921
}
922

            
923
pub struct CollatorAssignmentCost<Runtime>(PhantomData<Runtime>);
924
impl ProvideCollatorAssignmentCost<Runtime> for CollatorAssignmentCost<Runtime> {
925
288
    fn collator_assignment_cost(_para_id: &ParaId) -> (u128, Weight) {
926
288
        (FIXED_COLLATOR_ASSIGNMENT_COST, Weight::zero())
927
288
    }
928
}
929

            
930
parameter_types! {
931
    // 60 days worth of blocks
932
    pub const FreeBlockProductionCredits: BlockNumber = 60 * DAYS;
933
    // 60 days worth of blocks
934
    pub const FreeCollatorAssignmentCredits: u32 = FreeBlockProductionCredits::get()/Period::get();
935
}
936

            
937
impl pallet_services_payment::Config for Runtime {
938
    type RuntimeEvent = RuntimeEvent;
939
    /// Handler for fees
940
    type OnChargeForBlock = ();
941
    type OnChargeForCollatorAssignment = ();
942
    type OnChargeForCollatorAssignmentTip = ();
943
    /// Currency type for fee payment
944
    type Currency = Balances;
945
    /// Provider of a block cost which can adjust from block to block
946
    type ProvideBlockProductionCost = BlockProductionCost<Runtime>;
947
    /// Provider of a block cost which can adjust from block to block
948
    type ProvideCollatorAssignmentCost = CollatorAssignmentCost<Runtime>;
949
    /// The maximum number of block credits that can be accumulated
950
    type FreeBlockProductionCredits = FreeBlockProductionCredits;
951
    /// The maximum number of session credits that can be accumulated
952
    type FreeCollatorAssignmentCredits = FreeCollatorAssignmentCredits;
953
    type ManagerOrigin =
954
        EitherOfDiverse<pallet_registrar::EnsureSignedByManager<Runtime>, EnsureRoot<AccountId>>;
955
    type WeightInfo = weights::pallet_services_payment::SubstrateWeight<Runtime>;
956
}
957

            
958
parameter_types! {
959
    pub const ProfileDepositBaseFee: Balance = currency::STORAGE_ITEM_FEE;
960
    pub const ProfileDepositByteFee: Balance = currency::STORAGE_BYTE_FEE;
961
    #[derive(Clone)]
962
    pub const MaxAssignmentsPerParaId: u32 = 10;
963
    #[derive(Clone)]
964
    pub const MaxNodeUrlLen: u32 = 200;
965
}
966

            
967
#[apply(derive_storage_traits)]
968
#[derive(Copy, Serialize, Deserialize, MaxEncodedLen)]
969
pub enum PreserversAssignementPaymentRequest {
970
319
    Free,
971
    // TODO: Add Stream Payment (with config)
972
}
973

            
974
#[apply(derive_storage_traits)]
975
#[derive(Copy, Serialize, Deserialize)]
976
pub enum PreserversAssignementPaymentExtra {
977
80
    Free,
978
    // TODO: Add Stream Payment (with deposit)
979
}
980

            
981
#[apply(derive_storage_traits)]
982
#[derive(Copy, Serialize, Deserialize, MaxEncodedLen)]
983
pub enum PreserversAssignementPaymentWitness {
984
77
    Free,
985
    // TODO: Add Stream Payment (with stream id)
986
}
987

            
988
pub struct PreserversAssignementPayment;
989

            
990
impl pallet_data_preservers::AssignmentPayment<AccountId> for PreserversAssignementPayment {
991
    /// Providers requests which kind of payment it accepts.
992
    type ProviderRequest = PreserversAssignementPaymentRequest;
993
    /// Extra parameter the assigner provides.
994
    type AssignerParameter = PreserversAssignementPaymentExtra;
995
    /// Represents the succesful outcome of the assignment.
996
    type AssignmentWitness = PreserversAssignementPaymentWitness;
997

            
998
74
    fn try_start_assignment(
999
74
        _assigner: AccountId,
74
        _provider: AccountId,
74
        request: &Self::ProviderRequest,
74
        extra: Self::AssignerParameter,
74
    ) -> Result<Self::AssignmentWitness, DispatchErrorWithPostInfo> {
74
        let witness = match (request, extra) {
74
            (Self::ProviderRequest::Free, Self::AssignerParameter::Free) => {
74
                Self::AssignmentWitness::Free
74
            }
74
        };
74

            
74
        Ok(witness)
74
    }
8
    fn try_stop_assignment(
8
        _provider: AccountId,
8
        witness: Self::AssignmentWitness,
8
    ) -> Result<(), DispatchErrorWithPostInfo> {
8
        match witness {
8
            Self::AssignmentWitness::Free => (),
8
        }
8

            
8
        Ok(())
8
    }
    /// Return the values for a free assignment if it is supported.
    /// This is required to perform automatic migration from old Bootnodes storage.
1
    fn free_variant_values() -> Option<(
1
        Self::ProviderRequest,
1
        Self::AssignerParameter,
1
        Self::AssignmentWitness,
1
    )> {
1
        Some((
1
            Self::ProviderRequest::Free,
1
            Self::AssignerParameter::Free,
1
            Self::AssignmentWitness::Free,
1
        ))
1
    }
    // The values returned by the following functions should match with each other.
    #[cfg(feature = "runtime-benchmarks")]
    fn benchmark_provider_request() -> Self::ProviderRequest {
        PreserversAssignementPaymentRequest::Free
    }
    #[cfg(feature = "runtime-benchmarks")]
    fn benchmark_assigner_parameter() -> Self::AssignerParameter {
        PreserversAssignementPaymentExtra::Free
    }
    #[cfg(feature = "runtime-benchmarks")]
    fn benchmark_assignment_witness() -> Self::AssignmentWitness {
        PreserversAssignementPaymentWitness::Free
    }
}
pub type DataPreserversProfileId = u64;
impl pallet_data_preservers::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type RuntimeHoldReason = RuntimeHoldReason;
    type Currency = Balances;
    type WeightInfo = weights::pallet_data_preservers::SubstrateWeight<Runtime>;
    type ProfileId = DataPreserversProfileId;
    type ProfileDeposit = tp_traits::BytesDeposit<ProfileDepositBaseFee, ProfileDepositByteFee>;
    type AssignmentPayment = PreserversAssignementPayment;
    type AssignmentOrigin = pallet_registrar::EnsureSignedByManager<Runtime>;
    type ForceSetProfileOrigin = EnsureRoot<AccountId>;
    type MaxAssignmentsPerParaId = MaxAssignmentsPerParaId;
    type MaxNodeUrlLen = MaxNodeUrlLen;
    type MaxParaIdsVecLen = MaxLengthParaIds;
}
impl pallet_author_noting::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type ContainerChains = Registrar;
    type SlotBeacon = dp_consensus::AuraDigestSlotBeacon<Runtime>;
    type ContainerChainAuthor = CollatorAssignment;
    // We benchmark each hook individually, so for runtime-benchmarks this should be empty
    #[cfg(feature = "runtime-benchmarks")]
    type AuthorNotingHook = ();
    #[cfg(not(feature = "runtime-benchmarks"))]
    type AuthorNotingHook = (XcmCoreBuyer, InflationRewards, ServicesPayment);
    type RelayOrPara = pallet_author_noting::ParaMode<
        cumulus_pallet_parachain_system::RelaychainDataProvider<Self>,
    >;
    type WeightInfo = weights::pallet_author_noting::SubstrateWeight<Runtime>;
}
parameter_types! {
    pub const PotId: PalletId = PalletId(*b"PotStake");
    pub const MaxCandidates: u32 = 1000;
    pub const MinCandidates: u32 = 5;
    pub const SessionLength: BlockNumber = 5;
    pub const MaxInvulnerables: u32 = 100;
    pub const ExecutiveBody: BodyId = BodyId::Executive;
}
impl pallet_invulnerables::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type UpdateOrigin = EnsureRoot<AccountId>;
    type MaxInvulnerables = MaxInvulnerables;
    type CollatorId = <Self as frame_system::Config>::AccountId;
    type CollatorIdOf = pallet_invulnerables::IdentityCollator;
    type CollatorRegistration = Session;
    type WeightInfo = weights::pallet_invulnerables::SubstrateWeight<Runtime>;
    #[cfg(feature = "runtime-benchmarks")]
    type Currency = Balances;
}
parameter_types! {
    #[derive(Clone)]
    pub const MaxLengthParaIds: u32 = 100u32;
    pub const MaxEncodedGenesisDataSize: u32 = 5_000_000u32; // 5MB
}
pub struct CurrentSessionIndexGetter;
impl tp_traits::GetSessionIndex<u32> for CurrentSessionIndexGetter {
    /// Returns current session index.
177
    fn session_index() -> u32 {
177
        Session::current_index()
177
    }
}
impl pallet_configuration::Config for Runtime {
    type SessionDelay = ConstU32<2>;
    type SessionIndex = u32;
    type CurrentSessionIndex = CurrentSessionIndexGetter;
    type ForceEmptyOrchestrator = ConstBool<false>;
    type WeightInfo = weights::pallet_configuration::SubstrateWeight<Runtime>;
}
pub struct DanceboxRegistrarHooks;
impl RegistrarHooks for DanceboxRegistrarHooks {
57
    fn para_marked_valid_for_collating(para_id: ParaId) -> Weight {
57
        // Give free credits but only once per para id
57
        ServicesPayment::give_free_credits(&para_id)
57
    }
38
    fn para_deregistered(para_id: ParaId) -> Weight {
        // Clear pallet_author_noting storage
38
        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,
            );
38
        }
        // Remove bootnodes from pallet_data_preservers
38
        DataPreservers::para_deregistered(para_id);
38

            
38
        ServicesPayment::para_deregistered(para_id);
38

            
38
        XcmCoreBuyer::para_deregistered(para_id);
38

            
38
        Weight::default()
38
    }
58
    fn check_valid_for_collating(para_id: ParaId) -> DispatchResult {
58
        // To be able to call mark_valid_for_collating, a container chain must have bootnodes
58
        DataPreservers::check_valid_for_collating(para_id)
58
    }
    #[cfg(feature = "runtime-benchmarks")]
    fn benchmarks_ensure_valid_for_collating(para_id: ParaId) {
        use {
            frame_support::traits::EnsureOriginWithArg,
            pallet_data_preservers::{ParaIdsFilter, Profile, ProfileMode},
        };
        let profile = Profile {
            url: b"/ip4/127.0.0.1/tcp/33049/ws/p2p/12D3KooWHVMhQDHBpj9vQmssgyfspYecgV6e3hH1dQVDUkUbCYC9"
                    .to_vec()
                    .try_into()
                    .expect("to fit in BoundedVec"),
            para_ids: ParaIdsFilter::AnyParaId,
            mode: ProfileMode::Bootnode,
            assignment_request: PreserversAssignementPaymentRequest::Free,
        };
        let profile_id = pallet_data_preservers::NextProfileId::<Runtime>::get();
        let profile_owner = AccountId::new([1u8; 32]);
        DataPreservers::force_create_profile(RuntimeOrigin::root(), profile, profile_owner)
            .expect("profile create to succeed");
        let para_manager =
            <Runtime as pallet_data_preservers::Config>::AssignmentOrigin::try_successful_origin(
                &para_id,
            )
            .expect("should be able to get para manager");
        DataPreservers::start_assignment(
            para_manager,
            profile_id,
            para_id,
            PreserversAssignementPaymentExtra::Free,
        )
        .expect("assignement to work");
        assert!(
            pallet_data_preservers::Assignments::<Runtime>::get(para_id).contains(&profile_id),
            "profile should be correctly assigned"
        );
    }
}
pub struct PalletRelayStorageRootProvider;
impl RelayStorageRootProvider for PalletRelayStorageRootProvider {
8
    fn get_relay_storage_root(relay_block_number: u32) -> Option<H256> {
8
        pallet_relay_storage_roots::pallet::RelayStorageRoot::<Runtime>::get(relay_block_number)
8
    }
    #[cfg(feature = "runtime-benchmarks")]
    fn set_relay_storage_root(relay_block_number: u32, storage_root: Option<H256>) {
        pallet_relay_storage_roots::pallet::RelayStorageRootKeys::<Runtime>::mutate(|x| {
            if storage_root.is_some() {
                if x.is_full() {
                    let key = x.remove(0);
                    pallet_relay_storage_roots::pallet::RelayStorageRoot::<Runtime>::remove(key);
                }
                let pos = x.iter().position(|x| *x >= relay_block_number);
                if let Some(pos) = pos {
                    if x[pos] != relay_block_number {
                        x.try_insert(pos, relay_block_number).unwrap();
                    }
                } else {
                    // Push at end
                    x.try_push(relay_block_number).unwrap();
                }
            } else {
                let pos = x.iter().position(|x| *x == relay_block_number);
                if let Some(pos) = pos {
                    x.remove(pos);
                }
            }
        });
        pallet_relay_storage_roots::pallet::RelayStorageRoot::<Runtime>::set(
            relay_block_number,
            storage_root,
        );
    }
}
parameter_types! {
    pub const DepositAmount: Balance = 100 * UNIT;
}
impl pallet_registrar::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type RegistrarOrigin = EnsureRoot<AccountId>;
    type MarkValidForCollatingOrigin = EnsureRoot<AccountId>;
    type MaxLengthParaIds = MaxLengthParaIds;
    type MaxGenesisDataSize = MaxEncodedGenesisDataSize;
    type RegisterWithRelayProofOrigin = EnsureSigned<AccountId>;
    type RelayStorageRootProvider = PalletRelayStorageRootProvider;
    type SessionDelay = ConstU32<2>;
    type SessionIndex = u32;
    type CurrentSessionIndex = CurrentSessionIndexGetter;
    type Currency = Balances;
    type DepositAmount = DepositAmount;
    type RegistrarHooks = DanceboxRegistrarHooks;
    type RuntimeHoldReason = RuntimeHoldReason;
    type InnerRegistrar = ();
    type WeightInfo = weights::pallet_registrar::SubstrateWeight<Runtime>;
}
impl pallet_authority_mapping::Config for Runtime {
    type SessionIndex = u32;
    type SessionRemovalBoundary = ConstU32<2>;
    type AuthorityId = NimbusId;
}
impl pallet_sudo::Config for Runtime {
    type RuntimeCall = RuntimeCall;
    type RuntimeEvent = RuntimeEvent;
    type WeightInfo = weights::pallet_sudo::SubstrateWeight<Runtime>;
}
impl pallet_utility::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type RuntimeCall = RuntimeCall;
    type PalletsOrigin = OriginCaller;
    type WeightInfo = weights::pallet_utility::SubstrateWeight<Runtime>;
}
/// The type used to represent the kinds of proxying allowed.
#[apply(derive_storage_traits)]
#[derive(Copy, Ord, PartialOrd, MaxEncodedLen)]
#[allow(clippy::unnecessary_cast)]
pub enum ProxyType {
97
    /// All calls can be proxied. This is the trivial/most permissive filter.
    Any = 0,
30
    /// Only extrinsics that do not transfer funds.
    NonTransfer = 1,
25
    /// Only extrinsics related to governance (democracy and collectives).
    Governance = 2,
21
    /// Only extrinsics related to staking.
    Staking = 3,
53
    /// Allow to veto an announced proxy call.
    CancelProxy = 4,
17
    /// Allow extrinsic related to Balances.
    Balances = 5,
17
    /// Allow extrinsics related to Registrar
    Registrar = 6,
13
    /// Allow extrinsics related to Registrar that needs to be called through Sudo
    SudoRegistrar = 7,
17
    /// Allow extrinsics from the Session pallet for key management.
    SessionKeyManagement = 8,
}
impl Default for ProxyType {
    fn default() -> Self {
        Self::Any
    }
}
impl InstanceFilter<RuntimeCall> for ProxyType {
66
    fn filter(&self, c: &RuntimeCall) -> bool {
66
        // Since proxy filters are respected in all dispatches of the Utility
66
        // pallet, it should never need to be filtered by any proxy.
66
        if let RuntimeCall::Utility(..) = c {
            return true;
66
        }
66

            
66
        match self {
17
            ProxyType::Any => true,
            ProxyType::NonTransfer => {
6
                matches!(
10
                    c,
                    RuntimeCall::System(..)
                        | RuntimeCall::ParachainSystem(..)
                        | RuntimeCall::Timestamp(..)
                        | RuntimeCall::Proxy(..)
                        | RuntimeCall::Registrar(..)
                )
            }
            // We don't have governance yet
1
            ProxyType::Governance => false,
            ProxyType::Staking => {
1
                matches!(c, RuntimeCall::Session(..) | RuntimeCall::PooledStaking(..))
            }
5
            ProxyType::CancelProxy => matches!(
4
                c,
                RuntimeCall::Proxy(pallet_proxy::Call::reject_announcement { .. })
            ),
            ProxyType::Balances => {
9
                matches!(c, RuntimeCall::Balances(..))
            }
            ProxyType::Registrar => {
1
                matches!(
9
                    c,
                    RuntimeCall::Registrar(..) | RuntimeCall::DataPreservers(..)
                )
            }
5
            ProxyType::SudoRegistrar => match c {
5
                RuntimeCall::Sudo(pallet_sudo::Call::sudo { call: ref x }) => {
1
                    matches!(
5
                        x.as_ref(),
                        &RuntimeCall::Registrar(..) | &RuntimeCall::DataPreservers(..)
                    )
                }
                _ => false,
            },
            ProxyType::SessionKeyManagement => {
5
                matches!(c, RuntimeCall::Session(..))
            }
        }
66
    }
    fn is_superset(&self, o: &Self) -> bool {
        match (self, o) {
            (x, y) if x == y => true,
            (ProxyType::Any, _) => true,
            (_, ProxyType::Any) => false,
            _ => false,
        }
    }
}
impl pallet_proxy::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type RuntimeCall = RuntimeCall;
    type Currency = Balances;
    type ProxyType = ProxyType;
    // One storage item; key size 32, value size 8
    type ProxyDepositBase = ConstU128<{ currency::deposit(1, 8) }>;
    // Additional storage item size of 33 bytes (32 bytes AccountId + 1 byte sizeof(ProxyType)).
    type ProxyDepositFactor = ConstU128<{ currency::deposit(0, 33) }>;
    type MaxProxies = ConstU32<32>;
    type MaxPending = ConstU32<32>;
    type CallHasher = BlakeTwo256;
    type AnnouncementDepositBase = ConstU128<{ currency::deposit(1, 8) }>;
    // Additional storage item size of 68 bytes:
    // - 32 bytes AccountId
    // - 32 bytes Hasher (Blake2256)
    // - 4 bytes BlockNumber (u32)
    type AnnouncementDepositFactor = ConstU128<{ currency::deposit(0, 68) }>;
    type WeightInfo = weights::pallet_proxy::SubstrateWeight<Runtime>;
}
pub struct XcmExecutionManager;
impl xcm_primitives::PauseXcmExecution for XcmExecutionManager {
20
    fn suspend_xcm_execution() -> DispatchResult {
20
        XcmpQueue::suspend_xcm_execution(RuntimeOrigin::root())
20
    }
20
    fn resume_xcm_execution() -> DispatchResult {
20
        XcmpQueue::resume_xcm_execution(RuntimeOrigin::root())
20
    }
}
impl pallet_migrations::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type MigrationsList = (tanssi_runtime_common::migrations::DanceboxMigrations<Runtime>,);
    type XcmExecutionManager = XcmExecutionManager;
}
/// Maintenance mode Call filter
pub struct MaintenanceFilter;
impl Contains<RuntimeCall> for MaintenanceFilter {
432
    fn contains(c: &RuntimeCall) -> bool {
420
        !matches!(
432
            c,
            RuntimeCall::Balances(..)
                | RuntimeCall::Registrar(..)
                | RuntimeCall::Session(..)
                | RuntimeCall::System(..)
                | RuntimeCall::PooledStaking(..)
                | RuntimeCall::Utility(..)
                | RuntimeCall::PolkadotXcm(..)
        )
432
    }
}
/// Normal Call Filter
pub struct NormalFilter;
impl Contains<RuntimeCall> for NormalFilter {
57208
    fn contains(_c: &RuntimeCall) -> bool {
57208
        true
57208
    }
}
impl pallet_maintenance_mode::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type NormalCallFilter = NormalFilter;
    type MaintenanceCallFilter = MaintenanceFilter;
    type MaintenanceOrigin = EnsureRoot<AccountId>;
    type XcmExecutionManager = XcmExecutionManager;
}
parameter_types! {
    pub const MaxStorageRoots: u32 = 10; // 1 minute of relay blocks
}
impl pallet_relay_storage_roots::Config for Runtime {
    type RelaychainStateProvider = cumulus_pallet_parachain_system::RelaychainDataProvider<Self>;
    type MaxStorageRoots = MaxStorageRoots;
    type WeightInfo = weights::pallet_relay_storage_roots::SubstrateWeight<Runtime>;
}
impl pallet_root_testing::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
}
parameter_types! {
    pub StakingAccount: AccountId32 = PalletId(*b"POOLSTAK").into_account_truncating();
    pub const InitialManualClaimShareValue: u128 = currency::MILLIDANCE;
    pub const InitialAutoCompoundingShareValue: u128 = currency::MILLIDANCE;
    pub const MinimumSelfDelegation: u128 = 10 * currency::KILODANCE;
    pub const RewardsCollatorCommission: Perbill = Perbill::from_percent(20);
    // Need to wait 2 sessions before being able to join or leave staking pools
    pub const StakingSessionDelay: u32 = 2;
}
pub struct SessionTimer<G>(PhantomData<G>);
impl<G> Timer for SessionTimer<G>
where
    G: Get<u32>,
{
    type Instant = u32;
163
    fn now() -> Self::Instant {
163
        Session::current_index()
163
    }
55
    fn is_elapsed(instant: &Self::Instant) -> bool {
55
        let delay = G::get();
55
        let Some(end) = instant.checked_add(delay) else {
            return false;
        };
55
        end <= Self::now()
55
    }
    #[cfg(feature = "runtime-benchmarks")]
    fn elapsed_instant() -> Self::Instant {
        let delay = G::get();
        Self::now()
            .checked_add(delay)
            .expect("overflow when computing valid elapsed instant")
    }
    #[cfg(feature = "runtime-benchmarks")]
    fn skip_to_elapsed() {
        let session_to_reach = Self::elapsed_instant();
        while Self::now() < session_to_reach {
            Session::rotate_session();
        }
    }
}
pub struct CandidateHasRegisteredKeys;
impl IsCandidateEligible<AccountId> for CandidateHasRegisteredKeys {
99
    fn is_candidate_eligible(a: &AccountId) -> bool {
99
        <Session as ValidatorRegistration<AccountId>>::is_registered(a)
99
    }
    #[cfg(feature = "runtime-benchmarks")]
    fn make_candidate_eligible(a: &AccountId, eligible: bool) {
        use sp_core::crypto::UncheckedFrom;
        if eligible {
            let account_slice: &[u8; 32] = a.as_ref();
            let _ = Session::set_keys(
                RuntimeOrigin::signed(a.clone()),
                SessionKeys {
                    nimbus: NimbusId::unchecked_from(*account_slice),
                },
                vec![],
            );
        } else {
            let _ = Session::purge_keys(RuntimeOrigin::signed(a.clone()));
        }
    }
}
impl pallet_pooled_staking::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type Currency = Balances;
    type Balance = Balance;
    type StakingAccount = StakingAccount;
    type InitialManualClaimShareValue = InitialManualClaimShareValue;
    type InitialAutoCompoundingShareValue = InitialAutoCompoundingShareValue;
    type MinimumSelfDelegation = MinimumSelfDelegation;
    type RuntimeHoldReason = RuntimeHoldReason;
    type RewardsCollatorCommission = RewardsCollatorCommission;
    type JoiningRequestTimer = SessionTimer<StakingSessionDelay>;
    type LeavingRequestTimer = SessionTimer<StakingSessionDelay>;
    type EligibleCandidatesBufferSize = ConstU32<100>;
    type EligibleCandidatesFilter = CandidateHasRegisteredKeys;
    type WeightInfo = weights::pallet_pooled_staking::SubstrateWeight<Runtime>;
}
parameter_types! {
    pub ParachainBondAccount: AccountId32 = PalletId(*b"ParaBond").into_account_truncating();
    pub PendingRewardsAccount: AccountId32 = PalletId(*b"PENDREWD").into_account_truncating();
    // The equation to solve is:
    // initial_supply * (1.05) = initial_supply * (1+x)^5_259_600
    // we should solve for x = (1.05)^(1/5_259_600) -1 -> 0.000000009 per block or 9/1_000_000_000
    // 1% in the case of dev mode
    // TODO: check if we can put the prod inflation for tests too
    // TODO: better calculus for going from annual to block inflation (if it can be done)
    pub const InflationRate: Perbill = prod_or_fast!(Perbill::from_parts(9), Perbill::from_percent(1));
    // 30% for parachain bond, so 70% for staking
    pub const RewardsPortion: Perbill = Perbill::from_percent(70);
}
pub struct GetSelfChainBlockAuthor;
impl MaybeSelfChainBlockAuthor<AccountId32> for GetSelfChainBlockAuthor {
32440
    fn get_block_author() -> Option<AccountId32> {
32440
        // TODO: we should do a refactor here, and use either authority-mapping or collator-assignemnt
32440
        // we should also make sure we actually account for the weight of these
32440
        // although most of these should be cached as they are read every block
32440
        let slot = u64::from(<Runtime as pallet_author_inherent::Config>::SlotBeacon::slot());
32440
        let self_para_id = ParachainInfo::get();
32440
        CollatorAssignment::author_for_slot(slot.into(), self_para_id)
32440
    }
}
pub struct OnUnbalancedInflation;
impl frame_support::traits::OnUnbalanced<Credit<AccountId, Balances>> for OnUnbalancedInflation {
16220
    fn on_nonzero_unbalanced(credit: Credit<AccountId, Balances>) {
16220
        let _ = <Balances as Balanced<_>>::resolve(&ParachainBondAccount::get(), credit);
16220
    }
}
impl pallet_inflation_rewards::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type Currency = Balances;
    type ContainerChains = Registrar;
    type GetSelfChainBlockAuthor = GetSelfChainBlockAuthor;
    type InflationRate = InflationRate;
    type OnUnbalanced = OnUnbalancedInflation;
    type PendingRewardsAccount = PendingRewardsAccount;
    type StakingRewardsDistributor = InvulnerableRewardDistribution<Self, Balances, PooledStaking>;
    type RewardsPortion = RewardsPortion;
}
impl pallet_tx_pause::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type RuntimeCall = RuntimeCall;
    type PauseOrigin = EnsureRoot<AccountId>;
    type UnpauseOrigin = EnsureRoot<AccountId>;
    type WhitelistedCalls = ();
    type MaxNameLen = ConstU32<256>;
    type WeightInfo = weights::pallet_tx_pause::SubstrateWeight<Runtime>;
}
388
#[derive(RuntimeDebug, PartialEq, Eq, Encode, Decode, Copy, Clone, TypeInfo, MaxEncodedLen)]
pub enum StreamPaymentAssetId {
117
    Native,
}
pub struct StreamPaymentAssets;
impl pallet_stream_payment::Assets<AccountId, StreamPaymentAssetId, Balance>
    for StreamPaymentAssets
{
26
    fn transfer_deposit(
26
        asset_id: &StreamPaymentAssetId,
26
        from: &AccountId,
26
        to: &AccountId,
26
        amount: Balance,
26
    ) -> frame_support::pallet_prelude::DispatchResult {
26
        match asset_id {
26
            StreamPaymentAssetId::Native => {
26
                // We remove the hold before transfering.
26
                Self::decrease_deposit(asset_id, from, amount)?;
26
                Balances::transfer(from, to, amount, Preservation::Preserve).map(|_| ())
            }
        }
26
    }
17
    fn increase_deposit(
17
        asset_id: &StreamPaymentAssetId,
17
        account: &AccountId,
17
        amount: Balance,
17
    ) -> frame_support::pallet_prelude::DispatchResult {
17
        match asset_id {
17
            StreamPaymentAssetId::Native => Balances::hold(
17
                &pallet_stream_payment::HoldReason::StreamPayment.into(),
17
                account,
17
                amount,
17
            ),
17
        }
17
    }
35
    fn decrease_deposit(
35
        asset_id: &StreamPaymentAssetId,
35
        account: &AccountId,
35
        amount: Balance,
35
    ) -> frame_support::pallet_prelude::DispatchResult {
35
        match asset_id {
35
            StreamPaymentAssetId::Native => Balances::release(
35
                &pallet_stream_payment::HoldReason::StreamPayment.into(),
35
                account,
35
                amount,
35
                Precision::Exact,
35
            )
35
            .map(|_| ()),
35
        }
35
    }
    fn get_deposit(asset_id: &StreamPaymentAssetId, account: &AccountId) -> Balance {
        match asset_id {
            StreamPaymentAssetId::Native => Balances::balance_on_hold(
                &pallet_stream_payment::HoldReason::StreamPayment.into(),
                account,
            ),
        }
    }
    /// Benchmarks: should return the asset id which has the worst performance when interacting
    /// with it.
    #[cfg(feature = "runtime-benchmarks")]
    fn bench_worst_case_asset_id() -> StreamPaymentAssetId {
        StreamPaymentAssetId::Native
    }
    /// Benchmarks: should return the another asset id which has the worst performance when interacting
    /// with it afther `bench_worst_case_asset_id`. This is to benchmark the worst case when changing config
    /// from one asset to another.
    #[cfg(feature = "runtime-benchmarks")]
    fn bench_worst_case_asset_id2() -> StreamPaymentAssetId {
        StreamPaymentAssetId::Native
    }
    /// Benchmarks: should set the balance for the asset id returned by `bench_worst_case_asset_id`.
    #[cfg(feature = "runtime-benchmarks")]
    fn bench_set_balance(asset_id: &StreamPaymentAssetId, account: &AccountId, amount: Balance) {
        // only one asset id
        let StreamPaymentAssetId::Native = asset_id;
        Balances::set_balance(account, amount);
    }
}
776
#[derive(RuntimeDebug, PartialEq, Eq, Encode, Decode, Copy, Clone, TypeInfo, MaxEncodedLen)]
pub enum TimeUnit {
117
    BlockNumber,
    Timestamp,
    // TODO: Container chains/relay block number.
}
pub struct TimeProvider;
impl pallet_stream_payment::TimeProvider<TimeUnit, Balance> for TimeProvider {
72
    fn now(unit: &TimeUnit) -> Option<Balance> {
72
        match *unit {
72
            TimeUnit::BlockNumber => Some(System::block_number().into()),
            TimeUnit::Timestamp => Some(Timestamp::get().into()),
        }
72
    }
    /// Benchmarks: should return the time unit which has the worst performance calling
    /// `TimeProvider::now(unit)` with.
    #[cfg(feature = "runtime-benchmarks")]
    fn bench_worst_case_time_unit() -> TimeUnit {
        // Both BlockNumber and Timestamp cost the same (1 db read), but overriding timestamp
        // doesn't work well in benches, while block number works fine.
        TimeUnit::BlockNumber
    }
    /// Benchmarks: sets the "now" time for time unit returned by `worst_case_time_unit`.
    #[cfg(feature = "runtime-benchmarks")]
    fn bench_set_now(instant: Balance) {
        System::set_block_number(instant as u32)
    }
}
type StreamId = u64;
parameter_types! {
    // 1 entry, storing 173 bytes on-chain
    pub const OpenStreamHoldAmount: Balance = currency::deposit(1, 173);
}
impl pallet_stream_payment::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type StreamId = StreamId;
    type TimeUnit = TimeUnit;
    type Balance = Balance;
    type AssetId = StreamPaymentAssetId;
    type Assets = StreamPaymentAssets;
    type Currency = Balances;
    type OpenStreamHoldAmount = OpenStreamHoldAmount;
    type RuntimeHoldReason = RuntimeHoldReason;
    type TimeProvider = TimeProvider;
    type WeightInfo = weights::pallet_stream_payment::SubstrateWeight<Runtime>;
}
parameter_types! {
    // 1 entry, storing 258 bytes on-chain
    pub const BasicDeposit: Balance = currency::deposit(1, 258);
    // 1 entry, storing 53 bytes on-chain
    pub const SubAccountDeposit: Balance = currency::deposit(1, 53);
    // Additional bytes adds 0 entries, storing 1 byte on-chain
    pub const ByteDeposit: Balance = currency::deposit(0, 1);
    pub const MaxSubAccounts: u32 = 100;
    pub const MaxAdditionalFields: u32 = 100;
    pub const MaxRegistrars: u32 = 20;
}
impl pallet_identity::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type Currency = Balances;
    type BasicDeposit = BasicDeposit;
    type ByteDeposit = ByteDeposit;
    type SubAccountDeposit = SubAccountDeposit;
    type MaxSubAccounts = MaxSubAccounts;
    type MaxRegistrars = MaxRegistrars;
    type IdentityInformation = pallet_identity::legacy::IdentityInfo<MaxAdditionalFields>;
    // Slashed balances are burnt
    type Slashed = ();
    type ForceOrigin = EnsureRoot<AccountId>;
    type RegistrarOrigin = EnsureRoot<AccountId>;
    type OffchainSignature = Signature;
    type SigningPublicKey = <Signature as Verify>::Signer;
    type UsernameAuthorityOrigin = EnsureRoot<Self::AccountId>;
    type PendingUsernameExpiration = ConstU32<{ 7 * DAYS }>;
    type MaxSuffixLength = ConstU32<7>;
    type MaxUsernameLength = ConstU32<32>;
    type WeightInfo = weights::pallet_identity::SubstrateWeight<Runtime>;
}
parameter_types! {
    pub const TreasuryId: PalletId = PalletId(*b"tns/tsry");
    pub const ProposalBond: Permill = Permill::from_percent(5);
    pub TreasuryAccount: AccountId = Treasury::account_id();
    pub const MaxBalance: Balance = Balance::max_value();
    // We allow it to be 1 minute in fast mode to be able to test it
    pub const SpendPeriod: BlockNumber = prod_or_fast!(6 * DAYS, 1 * MINUTES);
}
impl pallet_treasury::Config for Runtime {
    type PalletId = TreasuryId;
    type Currency = Balances;
    type RejectOrigin = EnsureRoot<AccountId>;
    type RuntimeEvent = RuntimeEvent;
    // If proposal gets rejected, bond goes to treasury
    type SpendPeriod = SpendPeriod;
    type Burn = ();
    type BurnDestination = ();
    type MaxApprovals = ConstU32<100>;
    type WeightInfo = weights::pallet_treasury::SubstrateWeight<Runtime>;
    type SpendFunds = ();
    type SpendOrigin =
        frame_system::EnsureWithSuccess<EnsureRoot<AccountId>, AccountId, MaxBalance>;
    type AssetKind = ();
    type Beneficiary = AccountId;
    type BeneficiaryLookup = IdentityLookup<AccountId>;
    type Paymaster = PayFromAccount<Balances, TreasuryAccount>;
    // TODO: implement pallet-asset-rate to allow the treasury to spend other assets
    type BalanceConverter = UnityAssetBalanceConversion;
    type PayoutPeriod = ConstU32<{ 30 * DAYS }>;
    #[cfg(feature = "runtime-benchmarks")]
    type BenchmarkHelper = tanssi_runtime_common::benchmarking::TreasuryBenchmarkHelper<Runtime>;
}
parameter_types! {
    // One storage item; key size 32; value is size 4+4+16+32. Total = 1 * (32 + 56)
    pub const DepositBase: Balance = currency::deposit(1, 88);
    // Additional storage item size of 32 bytes.
    pub const DepositFactor: Balance = currency::deposit(0, 32);
    pub const MaxSignatories: u32 = 100;
}
impl pallet_multisig::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type RuntimeCall = RuntimeCall;
    type Currency = Balances;
    type DepositBase = DepositBase;
    type DepositFactor = DepositFactor;
    type MaxSignatories = MaxSignatories;
    type WeightInfo = weights::pallet_multisig::SubstrateWeight<Runtime>;
}
// Create the runtime by composing the FRAME pallets that were previously configured.
6372415
construct_runtime!(
588728
    pub enum Runtime
588728
    {
588728
        // System support stuff.
588728
        System: frame_system = 0,
588728
        ParachainSystem: cumulus_pallet_parachain_system = 1,
588728
        Timestamp: pallet_timestamp = 2,
588728
        ParachainInfo: parachain_info = 3,
588728
        Sudo: pallet_sudo = 4,
588728
        Utility: pallet_utility = 5,
588728
        Proxy: pallet_proxy = 6,
588728
        Migrations: pallet_migrations = 7,
588728
        MaintenanceMode: pallet_maintenance_mode = 8,
588728
        TxPause: pallet_tx_pause = 9,
588728

            
588728
        // Monetary stuff.
588728
        Balances: pallet_balances = 10,
588728
        TransactionPayment: pallet_transaction_payment = 11,
588728
        StreamPayment: pallet_stream_payment = 12,
588728

            
588728
        // Other utilities
588728
        Identity: pallet_identity = 15,
588728
        Multisig: pallet_multisig = 16,
588728

            
588728
        // ContainerChain management. It should go before Session for Genesis
588728
        Registrar: pallet_registrar = 20,
588728
        Configuration: pallet_configuration = 21,
588728
        CollatorAssignment: pallet_collator_assignment = 22,
588728
        Initializer: pallet_initializer = 23,
588728
        AuthorNoting: pallet_author_noting = 24,
588728
        AuthorityAssignment: pallet_authority_assignment = 25,
588728
        ServicesPayment: pallet_services_payment = 26,
588728
        DataPreservers: pallet_data_preservers = 27,
588728

            
588728
        // Collator support. The order of these 6 are important and shall not change.
588728
        Invulnerables: pallet_invulnerables = 30,
588728
        Session: pallet_session = 31,
588728
        AuthorityMapping: pallet_authority_mapping = 32,
588728
        AuthorInherent: pallet_author_inherent = 33,
588728
        PooledStaking: pallet_pooled_staking = 34,
588728
        // InflationRewards must be after Session and AuthorInherent
588728
        InflationRewards: pallet_inflation_rewards = 35,
588728

            
588728
        // Treasury stuff.
588728
        Treasury: pallet_treasury::{Pallet, Storage, Config<T>, Event<T>, Call} = 40,
588728

            
588728
        //XCM
588728
        XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 50,
588728
        CumulusXcm: cumulus_pallet_xcm::{Pallet, Event<T>, Origin} = 51,
588728
        PolkadotXcm: pallet_xcm::{Pallet, Call, Storage, Event<T>, Origin, Config<T>} = 53,
588728
        ForeignAssets: pallet_assets::<Instance1>::{Pallet, Call, Storage, Event<T>} = 54,
588728
        ForeignAssetsCreator: pallet_foreign_asset_creator::{Pallet, Call, Storage, Event<T>} = 55,
588728
        AssetRate: pallet_asset_rate::{Pallet, Call, Storage, Event<T>} = 56,
588728
        MessageQueue: pallet_message_queue::{Pallet, Call, Storage, Event<T>} = 57,
588728
        XcmCoreBuyer: pallet_xcm_core_buyer = 58,
588728

            
588728
        // More system support stuff
588728
        RelayStorageRoots: pallet_relay_storage_roots = 60,
588728

            
588728
        RootTesting: pallet_root_testing = 100,
588728
        AsyncBacking: pallet_async_backing::{Pallet, Storage} = 110,
588728
    }
6593917
);
#[cfg(feature = "runtime-benchmarks")]
mod benches {
    frame_benchmarking::define_benchmarks!(
        [frame_system, frame_system_benchmarking::Pallet::<Runtime>]
        [cumulus_pallet_parachain_system, ParachainSystem]
        [pallet_timestamp, Timestamp]
        [pallet_sudo, Sudo]
        [pallet_utility, Utility]
        [pallet_proxy, Proxy]
        [pallet_tx_pause, TxPause]
        [pallet_balances, Balances]
        [pallet_stream_payment, StreamPayment]
        [pallet_identity, Identity]
        [pallet_multisig, Multisig]
        [pallet_registrar, Registrar]
        [pallet_configuration, Configuration]
        [pallet_collator_assignment, CollatorAssignment]
        [pallet_author_noting, AuthorNoting]
        [pallet_services_payment, ServicesPayment]
        [pallet_data_preservers, DataPreservers]
        [pallet_invulnerables, Invulnerables]
        [pallet_session, SessionBench::<Runtime>]
        [pallet_author_inherent, AuthorInherent]
        [pallet_pooled_staking, PooledStaking]
        [pallet_treasury, Treasury]
        [cumulus_pallet_xcmp_queue, XcmpQueue]
        [pallet_xcm, PalletXcmExtrinsicsBenchmark::<Runtime>]
        [pallet_xcm_benchmarks::generic, pallet_xcm_benchmarks::generic::Pallet::<Runtime>]
        [pallet_assets, ForeignAssets]
        [pallet_foreign_asset_creator, ForeignAssetsCreator]
        [pallet_asset_rate, AssetRate]
        [pallet_message_queue, MessageQueue]
        [pallet_xcm_core_buyer, XcmCoreBuyer]
        [pallet_relay_storage_roots, RelayStorageRoots]
    );
}
16258
pub fn get_para_id_authorities(para_id: ParaId) -> Option<Vec<NimbusId>> {
16258
    let parent_number = System::block_number();
16258

            
16258
    let should_end_session =
16258
        <Runtime as pallet_session::Config>::ShouldEndSession::should_end_session(
16258
            parent_number + 1,
16258
        );
16258
    let session_index = if should_end_session {
1544
        Session::current_index() + 1
    } else {
14714
        Session::current_index()
    };
16258
    let assigned_authorities = AuthorityAssignment::collator_container_chain(session_index)?;
16258
    let self_para_id = ParachainInfo::get();
16258

            
16258
    if para_id == self_para_id {
16228
        Some(assigned_authorities.orchestrator_chain)
    } else {
30
        assigned_authorities.container_chains.get(&para_id).cloned()
    }
16258
}
245396
impl_runtime_apis! {
38828
    impl sp_consensus_aura::AuraApi<Block, NimbusId> for Runtime {
45796
        fn slot_duration() -> sp_consensus_aura::SlotDuration {
14324
            sp_consensus_aura::SlotDuration::from_millis(SLOT_DURATION)
14324
        }
38828

            
38828
        fn authorities() -> Vec<NimbusId> {
            // Check whether we need to fetch the next authorities or current ones
            let parent_number = System::block_number();
            let should_end_session = <Runtime as pallet_session::Config>::ShouldEndSession::should_end_session(parent_number + 1);
38828

            
38828
            let session_index = if should_end_session {
38828
                Session::current_index() +1
38828
            }
38828
            else {
38828
                Session::current_index()
38828
            };
38828

            
38828
            pallet_authority_assignment::CollatorContainerChain::<Runtime>::get(session_index)
                .expect("authorities for current session should exist")
                .orchestrator_chain
        }
38828
    }
38828

            
38828
    impl sp_api::Core<Block> for Runtime {
38828
        fn version() -> RuntimeVersion {
            VERSION
        }
38828

            
38828
        fn execute_block(block: Block) {
            Executive::execute_block(block)
        }
38828

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

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

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

            
38828
        fn metadata_versions() -> Vec<u32> {
            Runtime::metadata_versions()
        }
38828
    }
38828

            
38828
    impl sp_block_builder::BlockBuilder<Block> for Runtime {
67368
        fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
57468
            Executive::apply_extrinsic(extrinsic)
57468
        }
38828

            
45626
        fn finalize_block() -> <Block as BlockT>::Header {
13984
            Executive::finalize_block()
13984
        }
38828

            
45626
        fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
13984
            data.create_extrinsics()
13984
        }
38828

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

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

            
38828
    impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
45626
        fn offchain_worker(header: &<Block as BlockT>::Header) {
13984
            Executive::offchain_worker(header)
13984
        }
38828
    }
38828

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

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

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

            
38828
    impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {
38828
        fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {
            ParachainSystem::collect_collation_info(header)
        }
38828
    }
38828

            
38828
    impl async_backing_primitives::UnincludedSegmentApi<Block> for Runtime {
38828
        fn can_build_upon(
            included_hash: <Block as BlockT>::Hash,
            slot: async_backing_primitives::Slot,
        ) -> bool {
            ConsensusHook::can_build_upon(included_hash, slot)
        }
38828
    }
38828

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

            
38828
        fn get_preset(id: &Option<sp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
            get_preset::<RuntimeGenesisConfig>(id, |_| None)
        }
38828

            
38828
        fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
            vec![]
        }
38828
    }
38828

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

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

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

            
38828
        fn dispatch_benchmark(
38828
            config: frame_benchmarking::BenchmarkConfig,
38828
        ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {
38828
            use frame_benchmarking::{BenchmarkBatch, Benchmarking, BenchmarkError};
38828
            use sp_core::storage::TrackedStorageKey;
38828
            use cumulus_pallet_session_benchmarking::Pallet as SessionBench;
38828
            impl cumulus_pallet_session_benchmarking::Config for Runtime {}
38828

            
38828
            impl frame_system_benchmarking::Config for Runtime {
38828
                fn setup_set_code_requirements(code: &sp_std::vec::Vec<u8>) -> Result<(), BenchmarkError> {
38828
                    ParachainSystem::initialize_for_set_code_benchmark(code.len() as u32);
38828
                    Ok(())
38828
                }
38828

            
38828
                fn verify_set_code() {
38828
                    System::assert_last_event(cumulus_pallet_parachain_system::Event::<Runtime>::ValidationFunctionStored.into());
38828
                }
38828
            }
38828

            
38828
            use staging_xcm::latest::prelude::*;
38828
            use crate::xcm_config::SelfReserve;
38828
            parameter_types! {
38828
                pub ExistentialDepositAsset: Option<Asset> = Some((
38828
                    SelfReserve::get(),
38828
                    ExistentialDeposit::get()
38828
                ).into());
38828
            }
38828

            
38828
            impl pallet_xcm_benchmarks::Config for Runtime {
38828
                type XcmConfig = xcm_config::XcmConfig;
38828
                type AccountIdConverter = xcm_config::LocationToAccountId;
38828
                type DeliveryHelper = cumulus_primitives_utility::ToParentDeliveryHelper<
38828
                xcm_config::XcmConfig,
38828
                ExistentialDepositAsset,
38828
                xcm_config::PriceForParentDelivery,
38828
                >;
38828
                fn valid_destination() -> Result<Location, BenchmarkError> {
38828
                    Ok(Location::parent())
38828
                }
38828
                fn worst_case_holding(_depositable_count: u32) -> Assets {
38828
                    // We only care for native asset until we support others
38828
                    // TODO: refactor this case once other assets are supported
38828
                    vec![Asset{
38828
                        id: AssetId(SelfReserve::get()),
38828
                        fun: Fungible(u128::MAX),
38828
                    }].into()
38828
                }
38828
            }
38828

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

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

            
38828
                fn worst_case_asset_exchange() -> Result<(Assets, Assets), BenchmarkError> {
38828
                    Err(BenchmarkError::Skip)
38828
                }
38828

            
38828
                fn universal_alias() -> Result<(Location, Junction), BenchmarkError> {
38828
                    Err(BenchmarkError::Skip)
38828
                }
38828

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

            
38828
                fn subscribe_origin() -> Result<Location, BenchmarkError> {
38828
                    Ok(Location::parent())
38828
                }
38828

            
38828
                fn fee_asset() -> Result<Asset, BenchmarkError> {
38828
                    Ok(Asset {
38828
                        id: AssetId(SelfReserve::get()),
38828
                        fun: Fungible(ExistentialDeposit::get()*100),
38828
                    })
38828
                }
38828

            
38828
                fn claimable_asset() -> Result<(Location, Location, Assets), BenchmarkError> {
38828
                    let origin = Location::parent();
38828
                    let assets: Assets = (Location::parent(), 1_000u128).into();
38828
                    let ticket = Location { parents: 0, interior: Here };
38828
                    Ok((origin, ticket, assets))
38828
                }
38828

            
38828
                fn unlockable_asset() -> Result<(Location, Location, Asset), BenchmarkError> {
38828
                    Err(BenchmarkError::Skip)
38828
                }
38828

            
38828
                fn export_message_origin_and_destination(
38828
                ) -> Result<(Location, NetworkId, InteriorLocation), BenchmarkError> {
38828
                    Err(BenchmarkError::Skip)
38828
                }
38828

            
38828
                fn alias_origin() -> Result<(Location, Location), BenchmarkError> {
38828
                    Err(BenchmarkError::Skip)
38828
                }
38828
            }
38828

            
38828
            use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
38828
            impl pallet_xcm::benchmarking::Config for Runtime {
38828
                type DeliveryHelper = ();
38828
                fn get_asset() -> Asset {
38828
                    Asset {
38828
                        id: AssetId(SelfReserve::get()),
38828
                        fun: Fungible(ExistentialDeposit::get()),
38828
                    }
38828
                }
38828

            
38828
                fn reachable_dest() -> Option<Location> {
38828
                    Some(Parent.into())
38828
                }
38828

            
38828
                fn teleportable_asset_and_dest() -> Option<(Asset, Location)> {
38828
                    // Relay/native token can be teleported between AH and Relay.
38828
                    Some((
38828
                        Asset {
38828
                            fun: Fungible(EXISTENTIAL_DEPOSIT),
38828
                            id: Parent.into()
38828
                        },
38828
                        Parent.into(),
38828
                    ))
38828
                }
38828

            
38828
                fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> {
38828
                    use xcm_config::SelfReserve;
38828
                    // AH can reserve transfer native token to some random parachain.
38828
                    let random_para_id = 43211234;
38828
                    ParachainSystem::open_outbound_hrmp_channel_for_benchmarks_or_tests(
38828
                        random_para_id.into()
38828
                    );
38828
                    let who = frame_benchmarking::whitelisted_caller();
38828
                    // Give some multiple of the existential deposit
38828
                    let balance = EXISTENTIAL_DEPOSIT * 1000;
38828
                    let _ = <Balances as frame_support::traits::Currency<_>>::make_free_balance_be(
38828
                        &who, balance,
38828
                    );
38828
                    Some((
38828
                        Asset {
38828
                            fun: Fungible(EXISTENTIAL_DEPOSIT),
38828
                            id: AssetId(SelfReserve::get())
38828
                        },
38828
                        ParentThen(Parachain(random_para_id).into()).into(),
38828
                    ))
38828
                }
38828

            
38828
                fn set_up_complex_asset_transfer(
38828
                ) -> Option<(Assets, u32, Location, Box<dyn FnOnce()>)> {
38828
                    use xcm_config::SelfReserve;
38828
                    // Transfer to Relay some local AH asset (local-reserve-transfer) while paying
38828
                    // fees using teleported native token.
38828
                    // (We don't care that Relay doesn't accept incoming unknown AH local asset)
38828
                    let dest = Parent.into();
38828

            
38828
                    let fee_amount = EXISTENTIAL_DEPOSIT;
38828
                    let fee_asset: Asset = (SelfReserve::get(), fee_amount).into();
38828

            
38828
                    let who = frame_benchmarking::whitelisted_caller();
38828
                    // Give some multiple of the existential deposit
38828
                    let balance = fee_amount + EXISTENTIAL_DEPOSIT * 1000;
38828
                    let _ = <Balances as frame_support::traits::Currency<_>>::make_free_balance_be(
38828
                        &who, balance,
38828
                    );
38828

            
38828
                    // verify initial balance
38828
                    assert_eq!(Balances::free_balance(&who), balance);
38828

            
38828
                    // set up local asset
38828
                    let asset_amount = 10u128;
38828
                    let initial_asset_amount = asset_amount * 10;
38828

            
38828
                    // inject it into pallet-foreign-asset-creator.
38828
                    let (asset_id, asset_location) = pallet_foreign_asset_creator::benchmarks::create_default_minted_asset::<Runtime>(
38828
                        initial_asset_amount,
38828
                        who.clone()
38828
                    );
38828
                    let transfer_asset: Asset = (asset_location, asset_amount).into();
38828

            
38828
                    let assets: Assets = vec![fee_asset.clone(), transfer_asset].into();
38828
                    let fee_index = if assets.get(0).unwrap().eq(&fee_asset) { 0 } else { 1 };
38828

            
38828
                    // verify transferred successfully
38828
                    let verify = Box::new(move || {
38828
                        // verify native balance after transfer, decreased by transferred fee amount
38828
                        // (plus transport fees)
38828
                        assert!(Balances::free_balance(&who) <= balance - fee_amount);
38828
                        // verify asset balance decreased by exactly transferred amount
38828
                        assert_eq!(
38828
                            ForeignAssets::balance(asset_id, &who),
38828
                            initial_asset_amount - asset_amount,
38828
                        );
38828
                    });
38828
                    Some((assets, fee_index as u32, dest, verify))
38828
                }
38828
            }
38828

            
38828
            let whitelist: Vec<TrackedStorageKey> = vec![
38828
                // Block Number
38828
                hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac")
38828
                    .to_vec()
38828
                    .into(),
38828
                // Total Issuance
38828
                hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80")
38828
                    .to_vec()
38828
                    .into(),
38828
                // Execution Phase
38828
                hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a")
38828
                    .to_vec()
38828
                    .into(),
38828
                // Event Count
38828
                hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850")
38828
                    .to_vec()
38828
                    .into(),
38828
                // System Events
38828
                hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7")
38828
                    .to_vec()
38828
                    .into(),
38828
                // The transactional storage limit.
38828
                hex_literal::hex!("3a7472616e73616374696f6e5f6c6576656c3a")
38828
                    .to_vec()
38828
                    .into(),
38828

            
38828
                // ParachainInfo ParachainId
38828
                hex_literal::hex!(  "0d715f2646c8f85767b5d2764bb2782604a74d81251e398fd8a0a4d55023bb3f")
38828
                    .to_vec()
38828
                    .into(),
38828
            ];
38828

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

            
38828
            add_benchmarks!(params, batches);
38828

            
38828
            Ok(batches)
38828
        }
38828
    }
38828

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

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

            
38828
    impl pallet_collator_assignment_runtime_api::CollatorAssignmentApi<Block, AccountId, ParaId> for Runtime {
38828
        /// Return the parachain that the given `AccountId` is collating for.
38828
        /// Returns `None` if the `AccountId` is not collating.
38836
        fn current_collator_parachain_assignment(account: AccountId) -> Option<ParaId> {
8
            let assigned_collators = CollatorAssignment::collator_container_chain();
8
            let self_para_id = ParachainInfo::get();
8

            
8
            assigned_collators.para_id_of(&account, self_para_id)
8
        }
38828

            
38828
        /// Return the parachain that the given `AccountId` will be collating for
38828
        /// in the next session change.
38828
        /// Returns `None` if the `AccountId` will not be collating.
38834
        fn future_collator_parachain_assignment(account: AccountId) -> Option<ParaId> {
6
            let assigned_collators = CollatorAssignment::pending_collator_container_chain();
6

            
6
            match assigned_collators {
38832
                Some(assigned_collators) => {
4
                    let self_para_id = ParachainInfo::get();
4

            
4
                    assigned_collators.para_id_of(&account, self_para_id)
38828
                }
38828
                None => {
38830
                    Self::current_collator_parachain_assignment(account)
38828
                }
38828
            }
38828

            
38834
        }
38828

            
38828
        /// Return the list of collators of the given `ParaId`.
38828
        /// Returns `None` if the `ParaId` is not in the registrar.
38842
        fn parachain_collators(para_id: ParaId) -> Option<Vec<AccountId>> {
14
            let assigned_collators = CollatorAssignment::collator_container_chain();
14
            let self_para_id = ParachainInfo::get();
14

            
14
            if para_id == self_para_id {
38837
                Some(assigned_collators.orchestrator_chain)
38828
            } else {
38833
                assigned_collators.container_chains.get(&para_id).cloned()
38828
            }
38842
        }
38828
    }
38828

            
38828
    impl pallet_registrar_runtime_api::RegistrarApi<Block, ParaId> for Runtime {
38828
        /// Return the registered para ids
45631
        fn registered_paras() -> Vec<ParaId> {
13989
            // We should return the container-chains for the session in which we are kicking in
13989
            let parent_number = System::block_number();
13989
            let should_end_session = <Runtime as pallet_session::Config>::ShouldEndSession::should_end_session(parent_number + 1);
38828

            
45631
            let session_index = if should_end_session {
39298
                Session::current_index() +1
38828
            }
38828
            else {
44967
                Session::current_index()
38828
            };
38828

            
45631
            let container_chains = Registrar::session_container_chains(session_index);
13989
            let mut para_ids = vec![];
13989
            para_ids.extend(container_chains.parachains);
13989
            para_ids.extend(container_chains.parathreads.into_iter().map(|(para_id, _)| para_id));
13989

            
13989
            para_ids
13989
        }
38828

            
38828
        /// Fetch genesis data for this para id
38835
        fn genesis_data(para_id: ParaId) -> Option<ContainerChainGenesisData> {
7
            Registrar::para_genesis_data(para_id)
7
        }
38828

            
38828
        /// Fetch boot_nodes for this para id
38828
        fn boot_nodes(para_id: ParaId) -> Vec<Vec<u8>> {
            DataPreservers::assignments_profiles(para_id)
                .filter(|profile| profile.mode == pallet_data_preservers::ProfileMode::Bootnode)
                .map(|profile| profile.url.into())
                .collect()
        }
38828
    }
38828

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

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

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

            
38828
    impl dp_consensus::TanssiAuthorityAssignmentApi<Block, NimbusId> for Runtime {
38828
        /// Return the current authorities assigned to a given paraId
47878
        fn para_id_authorities(para_id: ParaId) -> Option<Vec<NimbusId>> {
16236
            get_para_id_authorities(para_id)
16236
        }
38828

            
38828
        /// Return the paraId assigned to a given authority
38860
        fn check_para_id_assignment(authority: NimbusId) -> Option<ParaId> {
32
            let parent_number = System::block_number();
32
            let should_end_session = <Runtime as pallet_session::Config>::ShouldEndSession::should_end_session(parent_number + 1);
38828

            
38860
            let session_index = if should_end_session {
38836
                Session::current_index() +1
38828
            }
38828
            else {
38852
                Session::current_index()
38828
            };
38860
            let assigned_authorities = AuthorityAssignment::collator_container_chain(session_index)?;
38860
            let self_para_id = ParachainInfo::get();
32

            
32
            assigned_authorities.para_id_of(&authority, self_para_id)
38860
        }
38828

            
38828
        /// Return the paraId assigned to a given authority on the next session.
38828
        /// On session boundary this returns the same as `check_para_id_assignment`.
38840
        fn check_para_id_assignment_next_session(authority: NimbusId) -> Option<ParaId> {
12
            let session_index = Session::current_index() + 1;
38840
            let assigned_authorities = AuthorityAssignment::collator_container_chain(session_index)?;
38840
            let self_para_id = ParachainInfo::get();
12

            
12
            assigned_authorities.para_id_of(&authority, self_para_id)
38840
        }
38828
    }
38828

            
38828
    impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>
38828
    for Runtime {
38828
        fn query_info(
16
            uxt: <Block as BlockT>::Extrinsic,
16
            len: u32,
16
        ) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo<Balance> {
16
            TransactionPayment::query_info(uxt, len)
16
        }
38828

            
38828
        fn query_fee_details(
8
            uxt: <Block as BlockT>::Extrinsic,
8
            len: u32,
8
        ) -> pallet_transaction_payment::FeeDetails<Balance> {
8
            TransactionPayment::query_fee_details(uxt, len)
8
        }
38828

            
38828
        fn query_weight_to_fee(weight: Weight) -> Balance {
40
            TransactionPayment::weight_to_fee(weight)
40
        }
38828

            
38828
        fn query_length_to_fee(length: u32) -> Balance {
12
            TransactionPayment::length_to_fee(length)
12
        }
38828
    }
38828

            
38828
    impl pallet_stream_payment_runtime_api::StreamPaymentApi<Block, StreamId, Balance, Balance>
38828
    for Runtime {
38828
        fn stream_payment_status(
36
            stream_id: StreamId,
36
            now: Option<Balance>,
36
        ) -> Result<StreamPaymentApiStatus<Balance>, StreamPaymentApiError> {
36
            match StreamPayment::stream_payment_status(stream_id, now) {
38828
                Ok(pallet_stream_payment::StreamPaymentStatus {
38828
                    payment, deposit_left, stalled
28
                }) => Ok(StreamPaymentApiStatus {
28
                    payment, deposit_left, stalled
28
                }),
38828
                Err(pallet_stream_payment::Error::<Runtime>::UnknownStreamId)
38828
                => Err(StreamPaymentApiError::UnknownStreamId),
38828
                Err(e) => Err(StreamPaymentApiError::Other(format!("{e:?}")))
38828
            }
38828
        }
38828
    }
38828

            
38828
    impl pallet_data_preservers_runtime_api::DataPreserversApi<Block, DataPreserversProfileId, ParaId> for Runtime {
38828
        fn get_active_assignment(
            profile_id: DataPreserversProfileId,
        ) -> pallet_data_preservers_runtime_api::Assignment<ParaId> {
38828
            use pallet_data_preservers_runtime_api::Assignment;
38828

            
38828
            let Some((para_id, witness)) = pallet_data_preservers::Profiles::<Runtime>::get(profile_id)
                .and_then(|x| x.assignment) else
38828
            {
38828
                return Assignment::NotAssigned;
38828
            };
38828

            
38828
            match witness {
                PreserversAssignementPaymentWitness::Free => Assignment::Active(para_id),
38828
                // TODO: Add Stream Payment. Stalled stream should return Inactive.
38828
            }
38828
        }
38828
    }
38828

            
38828
    impl dp_slot_duration_runtime_api::TanssiSlotDurationApi<Block> for Runtime {
38828
        fn slot_duration() -> u64 {
            SLOT_DURATION
        }
38828
    }
38828

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

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

            
38828
    impl pallet_xcm_core_buyer_runtime_api::XCMCoreBuyerApi<Block, BlockNumber, ParaId, NimbusId> for Runtime {
38828
        fn is_core_buying_allowed(para_id: ParaId, collator_public_key: NimbusId) -> Result<(), BuyingError<BlockNumber>> {
            XcmCoreBuyer::is_core_buying_allowed(para_id, Some(collator_public_key))
        }
38828

            
38828
        fn create_buy_core_unsigned_extrinsic(para_id: ParaId, proof: BuyCoreCollatorProof<NimbusId>) -> Box<<Block as BlockT>::Extrinsic> {
            let call = RuntimeCall::XcmCoreBuyer(pallet_xcm_core_buyer::Call::buy_core {
                para_id,
                proof
            });
            let unsigned_extrinsic = UncheckedExtrinsic::new_unsigned(call);
            Box::new(unsigned_extrinsic)
        }
38828

            
38828
        fn get_buy_core_signature_nonce(para_id: ParaId) -> u64 {
            pallet_xcm_core_buyer::CollatorSignatureNonce::<Runtime>::get(para_id)
        }
38828

            
38828
        fn get_buy_core_slot_drift() -> Slot {
            <Runtime as pallet_xcm_core_buyer::Config>::BuyCoreSlotDrift::get()
        }
38828
    }
38828

            
38828
    impl xcm_runtime_apis::fees::XcmPaymentApi<Block> for Runtime {
38828
        fn query_acceptable_payment_assets(xcm_version: staging_xcm::Version) -> Result<Vec<VersionedAssetId>, XcmPaymentApiError> {
38828
            if !matches!(xcm_version, 3 | 4) {
38828
                return Err(XcmPaymentApiError::UnhandledXcmVersion);
38828
            }
4

            
4
            Ok([VersionedAssetId::V4(xcm_config::SelfReserve::get().into())]
4
                .into_iter()
4
                .chain(
4
                    pallet_asset_rate::ConversionRateToNative::<Runtime>::iter_keys().filter_map(|asset_id_u16| {
4
                        pallet_foreign_asset_creator::AssetIdToForeignAsset::<Runtime>::get(asset_id_u16).map(|location| {
4
                            VersionedAssetId::V4(location.into())
4
                        }).or_else(|| {
                            log::warn!("Asset `{}` is present in pallet_asset_rate but not in pallet_foreign_asset_creator", asset_id_u16);
38828
                            None
4
                        })
4
                    })
4
                )
8
                .filter_map(|asset| asset.into_version(xcm_version).map_err(|e| {
                    log::warn!("Failed to convert asset to version {}: {:?}", xcm_version, e);
38828
                }).ok())
4
                .collect())
38828
        }
38828

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

            
38828
            if asset == local_asset {
38828
                Ok(WeightToFee::weight_to_fee(&weight))
38828
            } else {
38828
                let native_fee = WeightToFee::weight_to_fee(&weight);
38828
                let asset_v4: staging_xcm::opaque::lts::AssetId = asset.try_into().map_err(|_| XcmPaymentApiError::VersionedConversionFailed)?;
38828
                let location: staging_xcm::opaque::lts::Location = asset_v4.0;
38828
                let asset_id = pallet_foreign_asset_creator::ForeignAssetToAssetId::<Runtime>::get(location).ok_or(XcmPaymentApiError::AssetNotFound)?;
38828
                let asset_rate = AssetRate::to_asset_balance(native_fee, asset_id);
38828
                match asset_rate {
38828
                    Ok(x) => Ok(x),
38828
                    Err(pallet_asset_rate::Error::UnknownAssetKind) => Err(XcmPaymentApiError::AssetNotFound),
38828
                    // Error when converting native balance to asset balance, probably overflow
38828
                    Err(_e) => Err(XcmPaymentApiError::WeightNotComputable),
38828
                }
38828
            }
38828
        }
38828

            
38828
        fn query_xcm_weight(message: VersionedXcm<()>) -> Result<Weight, XcmPaymentApiError> {
4
            PolkadotXcm::query_xcm_weight(message)
4
        }
38828

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

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

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

            
38828
    impl xcm_runtime_apis::conversions::LocationToAccountApi<Block, AccountId> for Runtime {
38828
        fn convert_location(location: VersionedLocation) -> Result<
4
            AccountId,
4
            xcm_runtime_apis::conversions::Error
4
        > {
4
            xcm_runtime_apis::conversions::LocationToAccountHelper::<
4
                AccountId,
4
                xcm_config::LocationToAccountId,
4
            >::convert_location(location)
4
        }
38828
    }
245396
}
#[allow(dead_code)]
struct CheckInherents;
// TODO: this should be removed but currently if we remove it the relay does not check anything
// related to other inherents that are not parachain-system
#[allow(deprecated)]
impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {
    fn check_inherents(
        block: &Block,
        relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,
    ) -> sp_inherents::CheckInherentsResult {
        let relay_chain_slot = relay_state_proof
            .read_slot()
            .expect("Could not read the relay chain slot from the proof");
        let inherent_data =
            cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(
                relay_chain_slot,
                sp_std::time::Duration::from_secs(6),
            )
            .create_inherent_data()
            .expect("Could not create the timestamp inherent data");
        inherent_data.check_extrinsics(block)
    }
}
cumulus_pallet_parachain_system::register_validate_block! {
    Runtime = Runtime,
    CheckInherents = CheckInherents,
    BlockExecutor = pallet_author_inherent::BlockExecutor::<Runtime, Executive>,
}
#[macro_export]
macro_rules! prod_or_fast {
    ($prod:expr, $test:expr) => {
        if cfg!(feature = "fast-runtime") {
            $test
        } else {
            $prod
        }
    };
    ($prod:expr, $test:expr, $env:expr) => {
        if cfg!(feature = "fast-runtime") {
            core::option_env!($env)
                .map(|s| s.parse().ok())
                .flatten()
                .unwrap_or($test)
        } else {
            $prod
        }
    };
}