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

            
119
/// Block type as expected by this runtime.
120
pub type Block = generic::Block<Header, UncheckedExtrinsic>;
121
/// A Block signed with a Justification
122
pub type SignedBlock = generic::SignedBlock<Block>;
123
/// BlockId type as expected by this runtime.
124
pub type BlockId = generic::BlockId<Block>;
125

            
126
/// CollatorId type expected by this runtime.
127
pub type CollatorId = AccountId;
128

            
129
/// The SignedExtension to the basic transaction logic.
130
pub type SignedExtra = (
131
    frame_system::CheckNonZeroSender<Runtime>,
132
    frame_system::CheckSpecVersion<Runtime>,
133
    frame_system::CheckTxVersion<Runtime>,
134
    frame_system::CheckGenesis<Runtime>,
135
    frame_system::CheckEra<Runtime>,
136
    frame_system::CheckNonce<Runtime>,
137
    frame_system::CheckWeight<Runtime>,
138
    pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
139
    cumulus_primitives_storage_weight_reclaim::StorageWeightReclaim<Runtime>,
140
);
141

            
142
/// Unchecked extrinsic type as expected by this runtime.
143
pub type UncheckedExtrinsic =
144
    generic::UncheckedExtrinsic<Address, RuntimeCall, Signature, SignedExtra>;
145

            
146
/// Extrinsic type that has already been checked.
147
pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, RuntimeCall, SignedExtra>;
148

            
149
/// Executive: handles dispatch to the various modules.
150
pub type Executive = frame_executive::Executive<
151
    Runtime,
152
    Block,
153
    frame_system::ChainContext<Runtime>,
154
    Runtime,
155
    AllPalletsWithSystem,
156
>;
157

            
158
/// DANCE, the native token, uses 12 decimals of precision.
159
pub mod currency {
160
    use super::Balance;
161

            
162
    // Provide a common factor between runtimes based on a supply of 10_000_000 tokens.
163
    pub const SUPPLY_FACTOR: Balance = 100;
164

            
165
    pub const MICRODANCE: Balance = 1_000_000;
166
    pub const MILLIDANCE: Balance = 1_000_000_000;
167
    pub const DANCE: Balance = 1_000_000_000_000;
168
    pub const KILODANCE: Balance = 1_000_000_000_000_000;
169

            
170
    pub const STORAGE_BYTE_FEE: Balance = 100 * MICRODANCE * SUPPLY_FACTOR;
171
    pub const STORAGE_ITEM_FEE: Balance = 100 * MILLIDANCE * SUPPLY_FACTOR;
172

            
173
1074
    pub const fn deposit(items: u32, bytes: u32) -> Balance {
174
1074
        items as Balance * STORAGE_ITEM_FEE + (bytes as Balance) * STORAGE_BYTE_FEE
175
1074
    }
176
}
177

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

            
205
/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know
206
/// the specifics of the runtime. They can then be made to be agnostic over specific formats
207
/// of data like extrinsics, allowing for them to continue syncing the network through upgrades
208
/// to even the core data structures.
209
pub mod opaque {
210
    use {
211
        super::*,
212
        sp_runtime::{
213
            generic,
214
            traits::{BlakeTwo256, Hash as HashT},
215
        },
216
    };
217

            
218
    pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;
219
    /// Opaque block header type.
220
    pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
221
    /// Opaque block type.
222
    pub type Block = generic::Block<Header, UncheckedExtrinsic>;
223
    /// Opaque block identifier type.
224
    pub type BlockId = generic::BlockId<Block>;
225
    /// Opaque block hash type.
226
    pub type Hash = <BlakeTwo256 as HashT>::Output;
227
    /// Opaque signature type.
228
    pub use super::Signature;
229
}
230

            
231
impl_opaque_keys! {
232
    pub struct SessionKeys {
233
        pub nimbus: Initializer,
234
    }
235
}
236

            
237
#[sp_version::runtime_version]
238
pub const VERSION: RuntimeVersion = RuntimeVersion {
239
    spec_name: create_runtime_str!("dancebox"),
240
    impl_name: create_runtime_str!("dancebox"),
241
    authoring_version: 1,
242
    spec_version: 800,
243
    impl_version: 0,
244
    apis: RUNTIME_API_VERSIONS,
245
    transaction_version: 1,
246
    state_version: 1,
247
};
248

            
249
/// This determines the average expected block time that we are targeting.
250
/// Blocks will be produced at a minimum duration defined by `SLOT_DURATION`.
251
/// `SLOT_DURATION` is picked up by `pallet_timestamp` which is in turn picked
252
/// up by `pallet_aura` to implement `fn slot_duration()`.
253
///
254
/// Change this to adjust the block time.
255
pub const MILLISECS_PER_BLOCK: u64 = 6000;
256

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

            
261
// Time is measured by number of blocks.
262
pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);
263
pub const HOURS: BlockNumber = MINUTES * 60;
264
pub const DAYS: BlockNumber = HOURS * 24;
265

            
266
// Unit = the base number of indivisible units for balances
267
pub const UNIT: Balance = 1_000_000_000_000;
268
pub const MILLIUNIT: Balance = 1_000_000_000;
269
pub const MICROUNIT: Balance = 1_000_000;
270
/// The existential deposit. Set to 1/10 of the Connected Relay Chain.
271
pub const EXISTENTIAL_DEPOSIT: Balance = MILLIUNIT;
272

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

            
277
/// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used by
278
/// `Operational` extrinsics.
279
const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);
280

            
281
/// We allow for 0.5 of a second of compute with a 12 second average block time.
282
const MAXIMUM_BLOCK_WEIGHT: Weight = Weight::from_parts(
283
    WEIGHT_REF_TIME_PER_SECOND.saturating_div(2),
284
    cumulus_primitives_core::relay_chain::MAX_POV_SIZE as u64,
285
);
286

            
287
/// The version information used to identify this runtime when compiled natively.
288
#[cfg(feature = "std")]
289
664
pub fn native_version() -> NativeVersion {
290
664
    NativeVersion {
291
664
        runtime_version: VERSION,
292
664
        can_author_with: Default::default(),
293
664
    }
294
664
}
295

            
296
parameter_types! {
297
    pub const Version: RuntimeVersion = VERSION;
298

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

            
326
// Configure FRAME pallets to include in runtime.
327

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

            
382
impl pallet_timestamp::Config for Runtime {
383
    /// A timestamp: milliseconds since the unix epoch.
384
    type Moment = u64;
385
    type OnTimestampSet = dp_consensus::OnTimestampSet<
386
        <Self as pallet_author_inherent::Config>::SlotBeacon,
387
        ConstU64<{ SLOT_DURATION }>,
388
    >;
389
    type MinimumPeriod = ConstU64<{ SLOT_DURATION / 2 }>;
390
    type WeightInfo = weights::pallet_timestamp::SubstrateWeight<Runtime>;
391
}
392

            
393
pub struct CanAuthor;
394
impl nimbus_primitives::CanAuthor<NimbusId> for CanAuthor {
395
11064
    fn can_author(author: &NimbusId, slot: &u32) -> bool {
396
11064
        let authorities = AuthorityAssignment::collator_container_chain(Session::current_index())
397
11064
            .expect("authorities should be set")
398
11064
            .orchestrator_chain;
399
11064

            
400
11064
        if authorities.is_empty() {
401
            return false;
402
11064
        }
403
11064

            
404
11064
        let author_index = (*slot as usize) % authorities.len();
405
11064
        let expected_author = &authorities[author_index];
406
11064

            
407
11064
        expected_author == author
408
11064
    }
409
    #[cfg(feature = "runtime-benchmarks")]
410
    fn get_authors(_slot: &u32) -> Vec<NimbusId> {
411
        AuthorityAssignment::collator_container_chain(Session::current_index())
412
            .expect("authorities should be set")
413
            .orchestrator_chain
414
    }
415
}
416

            
417
impl pallet_author_inherent::Config for Runtime {
418
    type AuthorId = NimbusId;
419
    type AccountLookup = dp_consensus::NimbusLookUp;
420
    type CanAuthor = CanAuthor;
421
    type SlotBeacon = dp_consensus::AuraDigestSlotBeacon<Runtime>;
422
    type WeightInfo = weights::pallet_author_inherent::SubstrateWeight<Runtime>;
423
}
424

            
425
parameter_types! {
426
    pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT;
427
}
428

            
429
impl pallet_balances::Config for Runtime {
430
    type MaxLocks = ConstU32<50>;
431
    /// The type for recording an account's balance.
432
    type Balance = Balance;
433
    /// The ubiquitous event type.
434
    type RuntimeEvent = RuntimeEvent;
435
    type DustRemoval = ();
436
    type ExistentialDeposit = ExistentialDeposit;
437
    type AccountStore = System;
438
    type MaxReserves = ConstU32<50>;
439
    type ReserveIdentifier = [u8; 8];
440
    type FreezeIdentifier = RuntimeFreezeReason;
441
    type MaxFreezes = ConstU32<10>;
442
    type RuntimeHoldReason = RuntimeHoldReason;
443
    type RuntimeFreezeReason = RuntimeFreezeReason;
444
    type WeightInfo = weights::pallet_balances::SubstrateWeight<Runtime>;
445
}
446

            
447
pub struct DealWithFees<R>(sp_std::marker::PhantomData<R>);
448
impl<R> OnUnbalanced<Credit<R::AccountId, pallet_balances::Pallet<R>>> for DealWithFees<R>
449
where
450
    R: pallet_balances::Config + pallet_treasury::Config + frame_system::Config,
451
    pallet_treasury::NegativeImbalanceOf<R>: From<NegativeImbalance<R>>,
452
{
453
    // this seems to be called for substrate-based transactions
454
738
    fn on_unbalanceds<B>(
455
738
        mut fees_then_tips: impl Iterator<Item = Credit<R::AccountId, pallet_balances::Pallet<R>>>,
456
738
    ) {
457
738
        if let Some(fees) = fees_then_tips.next() {
458
            // 80% is burned, 20% goes to the treasury
459
            // Same policy applies for tips as well
460
738
            let burn_percentage = 80;
461
738
            let treasury_percentage = 20;
462
738

            
463
738
            let (_, to_treasury) = fees.ration(burn_percentage, treasury_percentage);
464
738
            ResolveTo::<pallet_treasury::TreasuryAccountId<R>, pallet_balances::Pallet<R>>::on_unbalanced(to_treasury);
465
            // Balances pallet automatically burns dropped Negative Imbalances by decreasing total_supply accordingly
466
            // handle tip if there is one
467
738
            if let Some(tip) = fees_then_tips.next() {
468
738
                let (_, to_treasury) = tip.ration(burn_percentage, treasury_percentage);
469
738
                ResolveTo::<pallet_treasury::TreasuryAccountId<R>, pallet_balances::Pallet<R>>::on_unbalanced(to_treasury);
470
738
            }
471
        }
472
738
    }
473

            
474
    // this is called from pallet_evm for Ethereum-based transactions
475
    // (technically, it calls on_unbalanced, which calls this when non-zero)
476
    fn on_nonzero_unbalanced(amount: Credit<R::AccountId, pallet_balances::Pallet<R>>) {
477
        // 80% is burned, 20% goes to the treasury
478
        let burn_percentage = 80;
479
        let treasury_percentage = 20;
480

            
481
        let (_, to_treasury) = amount.ration(burn_percentage, treasury_percentage);
482
        ResolveTo::<pallet_treasury::TreasuryAccountId<R>, pallet_balances::Pallet<R>>::on_unbalanced(to_treasury);
483
    }
484
}
485

            
486
parameter_types! {
487
    pub const TransactionByteFee: Balance = 1;
488
}
489

            
490
impl pallet_transaction_payment::Config for Runtime {
491
    type RuntimeEvent = RuntimeEvent;
492
    // This will burn 80% from fees & tips and deposit the remainder into the treasury
493
    type OnChargeTransaction = FungibleAdapter<Balances, DealWithFees<Runtime>>;
494
    type OperationalFeeMultiplier = ConstU8<5>;
495
    type WeightToFee = WeightToFee;
496
    type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;
497
    type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Self>;
498
}
499

            
500
parameter_types! {
501
    pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
502
    pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
503
    pub const RelayOrigin: AggregateMessageOrigin = AggregateMessageOrigin::Parent;
504
}
505

            
506
pub const RELAY_CHAIN_SLOT_DURATION_MILLIS: u32 = 6000;
507
pub const UNINCLUDED_SEGMENT_CAPACITY: u32 = 3;
508
pub const BLOCK_PROCESSING_VELOCITY: u32 = 1;
509

            
510
type ConsensusHook = pallet_async_backing::consensus_hook::FixedVelocityConsensusHook<
511
    Runtime,
512
    BLOCK_PROCESSING_VELOCITY,
513
    UNINCLUDED_SEGMENT_CAPACITY,
514
>;
515

            
516
impl cumulus_pallet_parachain_system::Config for Runtime {
517
    type WeightInfo = weights::cumulus_pallet_parachain_system::SubstrateWeight<Runtime>;
518
    type RuntimeEvent = RuntimeEvent;
519
    type OnSystemEvent = ();
520
    type SelfParaId = parachain_info::Pallet<Runtime>;
521
    type OutboundXcmpMessageSource = XcmpQueue;
522
    type DmpQueue = frame_support::traits::EnqueueWithOrigin<MessageQueue, RelayOrigin>;
523
    type ReservedDmpWeight = ReservedDmpWeight;
524
    type XcmpMessageHandler = XcmpQueue;
525
    type ReservedXcmpWeight = ReservedXcmpWeight;
526
    type CheckAssociatedRelayNumber = RelayNumberMonotonicallyIncreases;
527
    type ConsensusHook = ConsensusHook;
528
}
529
pub struct ParaSlotProvider;
530
impl Get<(Slot, SlotDuration)> for ParaSlotProvider {
531
7208
    fn get() -> (Slot, SlotDuration) {
532
7208
        let slot = u64::from(<Runtime as pallet_author_inherent::Config>::SlotBeacon::slot());
533
7208
        (Slot::from(slot), SlotDuration::from_millis(SLOT_DURATION))
534
7208
    }
535
}
536

            
537
parameter_types! {
538
    pub const ExpectedBlockTime: u64 = MILLISECS_PER_BLOCK;
539
}
540

            
541
impl pallet_async_backing::Config for Runtime {
542
    type AllowMultipleBlocksPerSlot = ConstBool<true>;
543
    type GetAndVerifySlot =
544
        pallet_async_backing::ParaSlot<RELAY_CHAIN_SLOT_DURATION_MILLIS, ParaSlotProvider>;
545
    type ExpectedBlockTime = ExpectedBlockTime;
546
}
547

            
548
/// Only callable after `set_validation_data` is called which forms this proof the same way
549
1048
fn relay_chain_state_proof() -> RelayChainStateProof {
550
1048
    let relay_storage_root =
551
1048
        RelaychainDataProvider::<Runtime>::current_relay_chain_state().state_root;
552
1048
    let relay_chain_state = RelaychainDataProvider::<Runtime>::current_relay_state_proof()
553
1048
        .expect("set in `set_validation_data`");
554
1048
    RelayChainStateProof::new(ParachainInfo::get(), relay_storage_root, relay_chain_state)
555
1048
        .expect("Invalid relay chain state proof, already constructed in `set_validation_data`")
556
1048
}
557

            
558
pub struct BabeCurrentBlockRandomnessGetter;
559
impl BabeCurrentBlockRandomnessGetter {
560
1048
    fn get_block_randomness() -> Option<Hash> {
561
1048
        if cfg!(feature = "runtime-benchmarks") {
562
            // storage reads as per actual reads
563
            let _relay_storage_root =
564
                RelaychainDataProvider::<Runtime>::current_relay_chain_state().state_root;
565

            
566
            let _relay_chain_state = RelaychainDataProvider::<Runtime>::current_relay_state_proof();
567
            let benchmarking_babe_output = Hash::default();
568
            return Some(benchmarking_babe_output);
569
1048
        }
570
1048

            
571
1048
        relay_chain_state_proof()
572
1048
            .read_optional_entry::<Option<Hash>>(
573
1048
                relay_chain::well_known_keys::CURRENT_BLOCK_RANDOMNESS,
574
1048
            )
575
1048
            .ok()
576
1048
            .flatten()
577
1048
            .flatten()
578
1048
    }
579

            
580
    /// Return the block randomness from the relay mixed with the provided subject.
581
    /// This ensures that the randomness will be different on different pallets, as long as the subject is different.
582
    // TODO: audit usage of randomness API
583
    // https://github.com/paritytech/polkadot/issues/2601
584
1048
    fn get_block_randomness_mixed(subject: &[u8]) -> Option<Hash> {
585
1048
        Self::get_block_randomness()
586
1048
            .map(|random_hash| mix_randomness::<Runtime>(random_hash, subject))
587
1048
    }
588
}
589

            
590
/// Combines the vrf output of the previous relay block with the provided subject.
591
/// This ensures that the randomness will be different on different pallets, as long as the subject is different.
592
52
fn mix_randomness<T: frame_system::Config>(vrf_output: Hash, subject: &[u8]) -> T::Hash {
593
52
    let mut digest = Vec::new();
594
52
    digest.extend_from_slice(vrf_output.as_ref());
595
52
    digest.extend_from_slice(subject);
596
52

            
597
52
    T::Hashing::hash(digest.as_slice())
598
52
}
599

            
600
// Randomness trait
601
impl frame_support::traits::Randomness<Hash, BlockNumber> for BabeCurrentBlockRandomnessGetter {
602
    fn random(subject: &[u8]) -> (Hash, BlockNumber) {
603
        let block_number = frame_system::Pallet::<Runtime>::block_number();
604
        let randomness = Self::get_block_randomness_mixed(subject).unwrap_or_default();
605

            
606
        (randomness, block_number)
607
    }
608
}
609

            
610
pub struct OwnApplySession;
611
impl pallet_initializer::ApplyNewSession<Runtime> for OwnApplySession {
612
1397
    fn apply_new_session(
613
1397
        _changed: bool,
614
1397
        session_index: u32,
615
1397
        all_validators: Vec<(AccountId, NimbusId)>,
616
1397
        queued: Vec<(AccountId, NimbusId)>,
617
1397
    ) {
618
1397
        // We first initialize Configuration
619
1397
        Configuration::initializer_on_new_session(&session_index);
620
1397
        // Next: Registrar
621
1397
        Registrar::initializer_on_new_session(&session_index);
622
1397
        // Next: AuthorityMapping
623
1397
        AuthorityMapping::initializer_on_new_session(&session_index, &all_validators);
624
1397

            
625
4917
        let next_collators = queued.iter().map(|(k, _)| k.clone()).collect();
626
1397

            
627
1397
        // Next: CollatorAssignment
628
1397
        let assignments =
629
1397
            CollatorAssignment::initializer_on_new_session(&session_index, next_collators);
630
1397

            
631
1397
        let queued_id_to_nimbus_map = queued.iter().cloned().collect();
632
1397
        AuthorityAssignment::initializer_on_new_session(
633
1397
            &session_index,
634
1397
            &queued_id_to_nimbus_map,
635
1397
            &assignments.next_assignment,
636
1397
        );
637
1397
    }
638
}
639

            
640
impl pallet_initializer::Config for Runtime {
641
    type SessionIndex = u32;
642

            
643
    /// The identifier type for an authority.
644
    type AuthorityId = NimbusId;
645

            
646
    type SessionHandler = OwnApplySession;
647
}
648

            
649
impl parachain_info::Config for Runtime {}
650

            
651
/// Returns a list of collators by combining pallet_invulnerables and pallet_pooled_staking.
652
pub struct CollatorsFromInvulnerablesAndThenFromStaking;
653

            
654
/// Play the role of the session manager.
655
impl SessionManager<CollatorId> for CollatorsFromInvulnerablesAndThenFromStaking {
656
1748
    fn new_session(index: SessionIndex) -> Option<Vec<CollatorId>> {
657
1748
        if <frame_system::Pallet<Runtime>>::block_number() == 0 {
658
            // Do not show this log in genesis
659
702
            log::debug!(
660
                "assembling new collators for new session {} at #{:?}",
661
                index,
662
                <frame_system::Pallet<Runtime>>::block_number(),
663
            );
664
        } else {
665
1046
            log::info!(
666
646
                "assembling new collators for new session {} at #{:?}",
667
646
                index,
668
646
                <frame_system::Pallet<Runtime>>::block_number(),
669
            );
670
        }
671

            
672
1748
        let invulnerables = Invulnerables::invulnerables().to_vec();
673
1748
        let candidates_staking =
674
1748
            pallet_pooled_staking::SortedEligibleCandidates::<Runtime>::get().to_vec();
675
1748
        // Max number of collators is set in pallet_configuration
676
1748
        let target_session_index = index.saturating_add(1);
677
1748
        let max_collators =
678
1748
            <Configuration as GetHostConfiguration<u32>>::max_collators(target_session_index);
679
1748
        let collators = invulnerables
680
1748
            .iter()
681
1748
            .cloned()
682
1748
            .chain(candidates_staking.into_iter().filter_map(|elig| {
683
228
                let cand = elig.candidate;
684
228
                if invulnerables.contains(&cand) {
685
                    // If a candidate is both in pallet_invulnerables and pallet_staking, do not count it twice
686
72
                    None
687
                } else {
688
156
                    Some(cand)
689
                }
690
1748
            }))
691
1748
            .take(max_collators as usize)
692
1748
            .collect();
693
1748

            
694
1748
        // TODO: weight?
695
1748
        /*
696
1748
        frame_system::Pallet::<T>::register_extra_weight_unchecked(
697
1748
            T::WeightInfo::new_session(invulnerables.len() as u32),
698
1748
            DispatchClass::Mandatory,
699
1748
        );
700
1748
        */
701
1748
        Some(collators)
702
1748
    }
703
1397
    fn start_session(_: SessionIndex) {
704
1397
        // we don't care.
705
1397
    }
706
1046
    fn end_session(_: SessionIndex) {
707
1046
        // we don't care.
708
1046
    }
709
}
710

            
711
parameter_types! {
712
    pub const Period: u32 = prod_or_fast!(1 * HOURS, 1 * MINUTES);
713
    pub const Offset: u32 = 0;
714
}
715

            
716
impl pallet_session::Config for Runtime {
717
    type RuntimeEvent = RuntimeEvent;
718
    type ValidatorId = CollatorId;
719
    // we don't have stash and controller, thus we don't need the convert as well.
720
    type ValidatorIdOf = pallet_invulnerables::IdentityCollator;
721
    type ShouldEndSession = pallet_session::PeriodicSessions<Period, Offset>;
722
    type NextSessionRotation = pallet_session::PeriodicSessions<Period, Offset>;
723
    type SessionManager = CollatorsFromInvulnerablesAndThenFromStaking;
724
    // Essentially just Aura, but let's be pedantic.
725
    type SessionHandler = <SessionKeys as sp_runtime::traits::OpaqueKeys>::KeyTypeIdProviders;
726
    type Keys = SessionKeys;
727
    type WeightInfo = weights::pallet_session::SubstrateWeight<Runtime>;
728
}
729

            
730
/// Read full_rotation_period from pallet_configuration
731
pub struct ConfigurationCollatorRotationSessionPeriod;
732

            
733
impl Get<u32> for ConfigurationCollatorRotationSessionPeriod {
734
2726
    fn get() -> u32 {
735
2726
        Configuration::config().full_rotation_period
736
2726
    }
737
}
738

            
739
pub struct BabeGetRandomnessForNextBlock;
740

            
741
impl GetRandomnessForNextBlock<u32> for BabeGetRandomnessForNextBlock {
742
21920
    fn should_end_session(n: u32) -> bool {
743
21920
        <Runtime as pallet_session::Config>::ShouldEndSession::should_end_session(n)
744
21920
    }
745

            
746
1048
    fn get_randomness() -> [u8; 32] {
747
1048
        let block_number = System::block_number();
748
1048
        let random_seed = if block_number != 0 {
749
52
            if let Some(random_hash) =
750
1048
                BabeCurrentBlockRandomnessGetter::get_block_randomness_mixed(b"CollatorAssignment")
751
            {
752
                // Return random_hash as a [u8; 32] instead of a Hash
753
52
                let mut buf = [0u8; 32];
754
52
                let len = sp_std::cmp::min(32, random_hash.as_ref().len());
755
52
                buf[..len].copy_from_slice(&random_hash.as_ref()[..len]);
756
52

            
757
52
                buf
758
            } else {
759
                // If there is no randomness (e.g when running in dev mode), return [0; 32]
760
                // TODO: smoke test to ensure this never happens in a live network
761
996
                [0; 32]
762
            }
763
        } else {
764
            // In block 0 (genesis) there is randomness
765
            [0; 32]
766
        };
767

            
768
1048
        random_seed
769
1048
    }
770
}
771

            
772
pub struct RemoveInvulnerablesImpl;
773

            
774
impl RemoveInvulnerables<CollatorId> for RemoveInvulnerablesImpl {
775
1952
    fn remove_invulnerables(
776
1952
        collators: &mut Vec<CollatorId>,
777
1952
        num_invulnerables: usize,
778
1952
    ) -> Vec<CollatorId> {
779
1952
        if num_invulnerables == 0 {
780
            return vec![];
781
1952
        }
782
1952
        // TODO: check if this works on session changes
783
1952
        let all_invulnerables = pallet_invulnerables::Invulnerables::<Runtime>::get();
784
1952
        if all_invulnerables.is_empty() {
785
48
            return vec![];
786
1904
        }
787
1904
        let mut invulnerables = vec![];
788
1904
        // TODO: use binary_search when invulnerables are sorted
789
2676
        collators.retain(|x| {
790
2676
            if invulnerables.len() < num_invulnerables && all_invulnerables.contains(x) {
791
2044
                invulnerables.push(x.clone());
792
2044
                false
793
            } else {
794
632
                true
795
            }
796
2676
        });
797
1904

            
798
1904
        invulnerables
799
1952
    }
800
}
801

            
802
pub struct RemoveParaIdsWithNoCreditsImpl;
803

            
804
impl RemoveParaIdsWithNoCredits for RemoveParaIdsWithNoCreditsImpl {
805
2794
    fn remove_para_ids_with_no_credits(
806
2794
        para_ids: &mut Vec<ParaId>,
807
2794
        currently_assigned: &BTreeSet<ParaId>,
808
2794
    ) {
809
2794
        let blocks_per_session = Period::get();
810
2794

            
811
2794
        para_ids.retain(|para_id| {
812
            // If the para has been assigned collators for this session it must have enough block credits
813
            // for the current and the next session.
814
2152
            let block_credits_needed = if currently_assigned.contains(para_id) {
815
1752
                blocks_per_session * 2
816
            } else {
817
400
                blocks_per_session
818
            };
819

            
820
            // Check if the container chain has enough credits for producing blocks
821
2152
            let free_block_credits = pallet_services_payment::BlockProductionCredits::<Runtime>::get(para_id)
822
2152
                .unwrap_or_default();
823
2152

            
824
2152
            // Check if the container chain has enough credits for a session assignments
825
2152
            let free_session_credits = pallet_services_payment::CollatorAssignmentCredits::<Runtime>::get(para_id)
826
2152
                .unwrap_or_default();
827
2152

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

            
831
2152
            // Return if we can survive with free credits
832
2152
            if free_block_credits >= block_credits_needed && free_session_credits >= 1 {
833
                // Max tip should always be checked, as it can be withdrawn even if free credits were used
834
1972
                return Balances::can_withdraw(&pallet_services_payment::Pallet::<Runtime>::parachain_tank(*para_id), max_tip).into_result(true).is_ok()
835
180
            }
836
180

            
837
180
            let remaining_block_credits = block_credits_needed.saturating_sub(free_block_credits);
838
180
            let remaining_session_credits = 1u32.saturating_sub(free_session_credits);
839
180

            
840
180
            let (block_production_costs, _) = <Runtime as pallet_services_payment::Config>::ProvideBlockProductionCost::block_cost(para_id);
841
180
            let (collator_assignment_costs, _) = <Runtime as pallet_services_payment::Config>::ProvideCollatorAssignmentCost::collator_assignment_cost(para_id);
842
180
            // let's check if we can withdraw
843
180
            let remaining_block_credits_to_pay = u128::from(remaining_block_credits).saturating_mul(block_production_costs);
844
180
            let remaining_session_credits_to_pay = u128::from(remaining_session_credits).saturating_mul(collator_assignment_costs);
845
180

            
846
180
            let remaining_to_pay = remaining_block_credits_to_pay.saturating_add(remaining_session_credits_to_pay).saturating_add(max_tip);
847
180

            
848
180
            // This should take into account whether we tank goes below ED
849
180
            // The true refers to keepAlive
850
180
            Balances::can_withdraw(&pallet_services_payment::Pallet::<Runtime>::parachain_tank(*para_id), remaining_to_pay).into_result(true).is_ok()
851
2794
        });
852
2794
    }
853

            
854
    /// Make those para ids valid by giving them enough credits, for benchmarking.
855
    #[cfg(feature = "runtime-benchmarks")]
856
    fn make_valid_para_ids(para_ids: &[ParaId]) {
857
        use frame_support::assert_ok;
858

            
859
        let blocks_per_session = Period::get();
860
        // Enough credits to run any benchmark
861
        let block_credits = 20 * blocks_per_session;
862
        let session_credits = 20;
863

            
864
        for para_id in para_ids {
865
            assert_ok!(ServicesPayment::set_block_production_credits(
866
                RuntimeOrigin::root(),
867
                *para_id,
868
                block_credits,
869
            ));
870
            assert_ok!(ServicesPayment::set_collator_assignment_credits(
871
                RuntimeOrigin::root(),
872
                *para_id,
873
                session_credits,
874
            ));
875
        }
876
    }
877
}
878

            
879
impl pallet_collator_assignment::Config for Runtime {
880
    type RuntimeEvent = RuntimeEvent;
881
    type HostConfiguration = Configuration;
882
    type ContainerChains = Registrar;
883
    type SessionIndex = u32;
884
    type SelfParaId = ParachainInfo;
885
    type ShouldRotateAllCollators =
886
        RotateCollatorsEveryNSessions<ConfigurationCollatorRotationSessionPeriod>;
887
    type GetRandomnessForNextBlock = BabeGetRandomnessForNextBlock;
888
    type RemoveInvulnerables = RemoveInvulnerablesImpl;
889
    type RemoveParaIdsWithNoCredits = RemoveParaIdsWithNoCreditsImpl;
890
    type CollatorAssignmentHook = ServicesPayment;
891
    type CollatorAssignmentTip = ServicesPayment;
892
    type Currency = Balances;
893
    type WeightInfo = weights::pallet_collator_assignment::SubstrateWeight<Runtime>;
894
}
895

            
896
impl pallet_authority_assignment::Config for Runtime {
897
    type SessionIndex = u32;
898
    type AuthorityId = NimbusId;
899
}
900

            
901
pub const FIXED_BLOCK_PRODUCTION_COST: u128 = 1 * currency::MICRODANCE;
902
pub const FIXED_COLLATOR_ASSIGNMENT_COST: u128 = 100 * currency::MICRODANCE;
903

            
904
pub struct BlockProductionCost<Runtime>(PhantomData<Runtime>);
905
impl ProvideBlockProductionCost<Runtime> for BlockProductionCost<Runtime> {
906
346
    fn block_cost(_para_id: &ParaId) -> (u128, Weight) {
907
346
        (FIXED_BLOCK_PRODUCTION_COST, Weight::zero())
908
346
    }
909
}
910

            
911
pub struct CollatorAssignmentCost<Runtime>(PhantomData<Runtime>);
912
impl ProvideCollatorAssignmentCost<Runtime> for CollatorAssignmentCost<Runtime> {
913
204
    fn collator_assignment_cost(_para_id: &ParaId) -> (u128, Weight) {
914
204
        (FIXED_COLLATOR_ASSIGNMENT_COST, Weight::zero())
915
204
    }
916
}
917

            
918
parameter_types! {
919
    // 60 days worth of blocks
920
    pub const FreeBlockProductionCredits: BlockNumber = 60 * DAYS;
921
    // 60 days worth of blocks
922
    pub const FreeCollatorAssignmentCredits: u32 = FreeBlockProductionCredits::get()/Period::get();
923
}
924

            
925
impl pallet_services_payment::Config for Runtime {
926
    type RuntimeEvent = RuntimeEvent;
927
    /// Handler for fees
928
    type OnChargeForBlock = ();
929
    type OnChargeForCollatorAssignment = ();
930
    type OnChargeForCollatorAssignmentTip = ();
931
    /// Currency type for fee payment
932
    type Currency = Balances;
933
    /// Provider of a block cost which can adjust from block to block
934
    type ProvideBlockProductionCost = BlockProductionCost<Runtime>;
935
    /// Provider of a block cost which can adjust from block to block
936
    type ProvideCollatorAssignmentCost = CollatorAssignmentCost<Runtime>;
937
    /// The maximum number of block credits that can be accumulated
938
    type FreeBlockProductionCredits = FreeBlockProductionCredits;
939
    /// The maximum number of session credits that can be accumulated
940
    type FreeCollatorAssignmentCredits = FreeCollatorAssignmentCredits;
941
    type ManagerOrigin =
942
        EitherOfDiverse<pallet_registrar::EnsureSignedByManager<Runtime>, EnsureRoot<AccountId>>;
943
    type WeightInfo = weights::pallet_services_payment::SubstrateWeight<Runtime>;
944
}
945

            
946
parameter_types! {
947
    pub const ProfileDepositBaseFee: Balance = currency::STORAGE_ITEM_FEE;
948
    pub const ProfileDepositByteFee: Balance = currency::STORAGE_BYTE_FEE;
949
    #[derive(Clone)]
950
    pub const MaxAssignmentsPerParaId: u32 = 10;
951
    #[derive(Clone)]
952
    pub const MaxNodeUrlLen: u32 = 200;
953
}
954

            
955
#[derive(
956
    RuntimeDebug,
957
    PartialEq,
958
    Eq,
959
    Encode,
960
    Decode,
961
    Copy,
962
    Clone,
963
352
    TypeInfo,
964
    serde::Serialize,
965
    serde::Deserialize,
966
)]
967
pub enum PreserversAssignementPaymentRequest {
968
205
    Free,
969
    // TODO: Add Stream Payment (with config)
970
}
971

            
972
#[derive(
973
    RuntimeDebug,
974
    PartialEq,
975
    Eq,
976
    Encode,
977
    Decode,
978
    Copy,
979
    Clone,
980
352
    TypeInfo,
981
    serde::Serialize,
982
    serde::Deserialize,
983
)]
984
pub enum PreserversAssignementPaymentExtra {
985
36
    Free,
986
    // TODO: Add Stream Payment (with deposit)
987
}
988

            
989
#[derive(
990
    RuntimeDebug,
991
    PartialEq,
992
    Eq,
993
    Encode,
994
    Decode,
995
    Copy,
996
    Clone,
997
352
    TypeInfo,
998
    serde::Serialize,
999
    serde::Deserialize,
)]
pub enum PreserversAssignementPaymentWitness {
78
    Free,
    // TODO: Add Stream Payment (with stream id)
}
pub struct PreserversAssignementPayment;
impl pallet_data_preservers::AssignmentPayment<AccountId> for PreserversAssignementPayment {
    /// Providers requests which kind of payment it accepts.
    type ProviderRequest = PreserversAssignementPaymentRequest;
    /// Extra parameter the assigner provides.
    type AssignerParameter = PreserversAssignementPaymentExtra;
    /// Represents the succesful outcome of the assignment.
    type AssignmentWitness = PreserversAssignementPaymentWitness;
72
    fn try_start_assignment(
72
        _assigner: AccountId,
72
        _provider: AccountId,
72
        request: &Self::ProviderRequest,
72
        extra: Self::AssignerParameter,
72
    ) -> Result<Self::AssignmentWitness, DispatchErrorWithPostInfo> {
72
        let witness = match (request, extra) {
72
            (Self::ProviderRequest::Free, Self::AssignerParameter::Free) => {
72
                Self::AssignmentWitness::Free
72
            }
72
        };
72

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

            
4
        Ok(())
4
    }
    /// Return the values for a free assignment if it is supported.
    /// This is required to perform automatic migration from old Bootnodes storage.
2
    fn free_variant_values() -> Option<(
2
        Self::ProviderRequest,
2
        Self::AssignerParameter,
2
        Self::AssignmentWitness,
2
    )> {
2
        Some((
2
            Self::ProviderRequest::Free,
2
            Self::AssignerParameter::Free,
2
            Self::AssignmentWitness::Free,
2
        ))
2
    }
    // 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
    }
}
impl pallet_data_preservers::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type RuntimeHoldReason = RuntimeHoldReason;
    type Currency = Balances;
    type WeightInfo = weights::pallet_data_preservers::SubstrateWeight<Runtime>;
    type ProfileId = u64;
    type ProfileDeposit = tp_traits::BytesDeposit<ProfileDepositBaseFee, ProfileDepositByteFee>;
    type AssignmentPayment = 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 SelfParaId = parachain_info::Pallet<Runtime>;
    type SlotBeacon = dp_consensus::AuraDigestSlotBeacon<Runtime>;
    type ContainerChainAuthor = CollatorAssignment;
    type RelayChainStateProvider = cumulus_pallet_parachain_system::RelaychainDataProvider<Self>;
    // 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 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.
156
    fn session_index() -> u32 {
156
        Session::current_index()
156
    }
}
impl pallet_configuration::Config for Runtime {
    type SessionDelay = ConstU32<2>;
    type SessionIndex = u32;
    type CurrentSessionIndex = CurrentSessionIndexGetter;
    type AuthorityId = NimbusId;
    type WeightInfo = weights::pallet_configuration::SubstrateWeight<Runtime>;
}
pub struct DanceboxRegistrarHooks;
impl RegistrarHooks for DanceboxRegistrarHooks {
66
    fn para_marked_valid_for_collating(para_id: ParaId) -> Weight {
66
        // Give free credits but only once per para id
66
        ServicesPayment::give_free_credits(&para_id)
66
    }
24
    fn para_deregistered(para_id: ParaId) -> Weight {
        // Clear pallet_author_noting storage
24
        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,
            );
24
        }
        // Remove bootnodes from pallet_data_preservers
24
        DataPreservers::para_deregistered(para_id);
24

            
24
        ServicesPayment::para_deregistered(para_id);
24

            
24
        XcmCoreBuyer::para_deregistered(para_id);
24

            
24
        Weight::default()
24
    }
68
    fn check_valid_for_collating(para_id: ParaId) -> DispatchResult {
68
        // To be able to call mark_valid_for_collating, a container chain must have bootnodes
68
        DataPreservers::check_valid_for_collating(para_id)
68
    }
    #[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 {
4
    fn get_relay_storage_root(relay_block_number: u32) -> Option<H256> {
4
        pallet_relay_storage_roots::pallet::RelayStorageRoot::<Runtime>::get(relay_block_number)
4
    }
    #[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;
    pub const MaxLengthTokenSymbol: u32 = 255;
}
impl pallet_registrar::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type RegistrarOrigin = EnsureRoot<AccountId>;
    type MarkValidForCollatingOrigin = EnsureRoot<AccountId>;
    type MaxLengthParaIds = MaxLengthParaIds;
    type MaxGenesisDataSize = MaxEncodedGenesisDataSize;
    type MaxLengthTokenSymbol = MaxLengthTokenSymbol;
    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 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.
#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))]
#[derive(
1760
    Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, Debug, MaxEncodedLen, TypeInfo,
)]
#[allow(clippy::unnecessary_cast)]
pub enum ProxyType {
49
    /// All calls can be proxied. This is the trivial/most permissive filter.
    Any = 0,
16
    /// Only extrinsics that do not transfer funds.
    NonTransfer = 1,
13
    /// Only extrinsics related to governance (democracy and collectives).
    Governance = 2,
11
    /// Only extrinsics related to staking.
    Staking = 3,
27
    /// Allow to veto an announced proxy call.
    CancelProxy = 4,
9
    /// Allow extrinsic related to Balances.
    Balances = 5,
9
    /// Allow extrinsics related to Registrar
    Registrar = 6,
7
    /// Allow extrinsics related to Registrar that needs to be called through Sudo
    SudoRegistrar = 7,
9
    /// 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 {
48
    fn filter(&self, c: &RuntimeCall) -> bool {
48
        // Since proxy filters are respected in all dispatches of the Utility
48
        // pallet, it should never need to be filtered by any proxy.
48
        if let RuntimeCall::Utility(..) = c {
            return true;
48
        }
48

            
48
        match self {
10
            ProxyType::Any => true,
            ProxyType::NonTransfer => {
6
                matches!(
8
                    c,
                    RuntimeCall::System(..)
                        | RuntimeCall::ParachainSystem(..)
                        | RuntimeCall::Timestamp(..)
                        | RuntimeCall::Proxy(..)
                        | RuntimeCall::Registrar(..)
                )
            }
            // We don't have governance yet
2
            ProxyType::Governance => false,
            ProxyType::Staking => {
2
                matches!(c, RuntimeCall::Session(..) | RuntimeCall::PooledStaking(..))
            }
4
            ProxyType::CancelProxy => matches!(
2
                c,
                RuntimeCall::Proxy(pallet_proxy::Call::reject_announcement { .. })
            ),
            ProxyType::Balances => {
6
                matches!(c, RuntimeCall::Balances(..))
            }
            ProxyType::Registrar => {
2
                matches!(
6
                    c,
                    RuntimeCall::Registrar(..) | RuntimeCall::DataPreservers(..)
                )
            }
4
            ProxyType::SudoRegistrar => match c {
4
                RuntimeCall::Sudo(pallet_sudo::Call::sudo { call: ref x }) => {
2
                    matches!(
4
                        x.as_ref(),
                        &RuntimeCall::Registrar(..) | &RuntimeCall::DataPreservers(..)
                    )
                }
                _ => false,
            },
            ProxyType::SessionKeyManagement => {
4
                matches!(c, RuntimeCall::Session(..))
            }
        }
48
    }
    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 {
10
    fn suspend_xcm_execution() -> DispatchResult {
10
        XcmpQueue::suspend_xcm_execution(RuntimeOrigin::root())
10
    }
10
    fn resume_xcm_execution() -> DispatchResult {
10
        XcmpQueue::resume_xcm_execution(RuntimeOrigin::root())
10
    }
}
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 {
216
    fn contains(c: &RuntimeCall) -> bool {
210
        !matches!(
216
            c,
            RuntimeCall::Balances(..)
                | RuntimeCall::Registrar(..)
                | RuntimeCall::Session(..)
                | RuntimeCall::System(..)
                | RuntimeCall::PooledStaking(..)
                | RuntimeCall::Utility(..)
                | RuntimeCall::PolkadotXcm(..)
        )
216
    }
}
/// Normal Call Filter
pub struct NormalFilter;
impl Contains<RuntimeCall> for NormalFilter {
28032
    fn contains(_c: &RuntimeCall) -> bool {
28032
        true
28032
    }
}
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;
113
    fn now() -> Self::Instant {
113
        Session::current_index()
113
    }
37
    fn is_elapsed(instant: &Self::Instant) -> bool {
37
        let delay = G::get();
37
        let Some(end) = instant.checked_add(delay) else {
            return false;
        };
37
        end <= Self::now()
37
    }
    #[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 {
114
    fn is_candidate_eligible(a: &AccountId) -> bool {
114
        <Session as ValidatorRegistration<AccountId>>::is_registered(a)
114
    }
    #[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 Get<AccountId32> for GetSelfChainBlockAuthor {
11064
    fn get() -> AccountId32 {
11064
        // TODO: we should do a refactor here, and use either authority-mapping or collator-assignemnt
11064
        // we should also make sure we actually account for the weight of these
11064
        // although most of these should be cached as they are read every block
11064
        let slot = u64::from(<Runtime as pallet_author_inherent::Config>::SlotBeacon::slot());
11064
        let self_para_id = ParachainInfo::get();
11064
        let author = CollatorAssignment::author_for_slot(slot.into(), self_para_id);
11064
        author.expect("author should be set")
11064
    }
}
pub struct OnUnbalancedInflation;
impl frame_support::traits::OnUnbalanced<Credit<AccountId, Balances>> for OnUnbalancedInflation {
11064
    fn on_nonzero_unbalanced(credit: Credit<AccountId, Balances>) {
11064
        let _ = <Balances as Balanced<_>>::resolve(&ParachainBondAccount::get(), credit);
11064
    }
}
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>;
}
352
#[derive(RuntimeDebug, PartialEq, Eq, Encode, Decode, Copy, Clone, TypeInfo, MaxEncodedLen)]
pub enum StreamPaymentAssetId {
57
    Native,
}
pub struct StreamPaymentAssets;
impl pallet_stream_payment::Assets<AccountId, StreamPaymentAssetId, Balance>
    for StreamPaymentAssets
{
12
    fn transfer_deposit(
12
        asset_id: &StreamPaymentAssetId,
12
        from: &AccountId,
12
        to: &AccountId,
12
        amount: Balance,
12
    ) -> frame_support::pallet_prelude::DispatchResult {
12
        match asset_id {
12
            StreamPaymentAssetId::Native => {
12
                // We remove the hold before transfering.
12
                Self::decrease_deposit(asset_id, from, amount)?;
12
                Balances::transfer(from, to, amount, Preservation::Preserve).map(|_| ())
            }
        }
12
    }
10
    fn increase_deposit(
10
        asset_id: &StreamPaymentAssetId,
10
        account: &AccountId,
10
        amount: Balance,
10
    ) -> frame_support::pallet_prelude::DispatchResult {
10
        match asset_id {
10
            StreamPaymentAssetId::Native => Balances::hold(
10
                &pallet_stream_payment::HoldReason::StreamPayment.into(),
10
                account,
10
                amount,
10
            ),
10
        }
10
    }
18
    fn decrease_deposit(
18
        asset_id: &StreamPaymentAssetId,
18
        account: &AccountId,
18
        amount: Balance,
18
    ) -> frame_support::pallet_prelude::DispatchResult {
18
        match asset_id {
18
            StreamPaymentAssetId::Native => Balances::release(
18
                &pallet_stream_payment::HoldReason::StreamPayment.into(),
18
                account,
18
                amount,
18
                Precision::Exact,
18
            )
18
            .map(|_| ()),
18
        }
18
    }
    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);
    }
}
528
#[derive(RuntimeDebug, PartialEq, Eq, Encode, Decode, Copy, Clone, TypeInfo, MaxEncodedLen)]
pub enum TimeUnit {
57
    BlockNumber,
    Timestamp,
    // TODO: Container chains/relay block number.
}
pub struct TimeProvider;
impl pallet_stream_payment::TimeProvider<TimeUnit, Balance> for TimeProvider {
36
    fn now(unit: &TimeUnit) -> Option<Balance> {
36
        match *unit {
36
            TimeUnit::BlockNumber => Some(System::block_number().into()),
            TimeUnit::Timestamp => Some(Timestamp::now().into()),
        }
36
    }
    /// 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();
}
impl pallet_treasury::Config for Runtime {
    type PalletId = TreasuryId;
    type Currency = Balances;
    type ApproveOrigin = EnsureRoot<AccountId>;
    type RejectOrigin = EnsureRoot<AccountId>;
    type RuntimeEvent = RuntimeEvent;
    // If proposal gets rejected, bond goes to treasury
    type OnSlash = Treasury;
    type ProposalBond = ProposalBond;
    type ProposalBondMinimum = ConstU128<{ 1 * currency::DANCE * currency::SUPPLY_FACTOR }>;
    type SpendPeriod = ConstU32<{ 6 * DAYS }>;
    type Burn = ();
    type BurnDestination = ();
    type MaxApprovals = ConstU32<100>;
    type WeightInfo = weights::pallet_treasury::SubstrateWeight<Runtime>;
    type SpendFunds = ();
    type ProposalBondMaximum = ();
    #[cfg(not(feature = "runtime-benchmarks"))]
    type SpendOrigin = frame_support::traits::NeverEnsureOrigin<Balance>; // Disabled, no spending
    #[cfg(feature = "runtime-benchmarks")]
    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::TreasurtBenchmarkHelper<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.
3394903
construct_runtime!(
385584
    pub enum Runtime
385584
    {
385584
        // System support stuff.
385584
        System: frame_system = 0,
385584
        ParachainSystem: cumulus_pallet_parachain_system = 1,
385584
        Timestamp: pallet_timestamp = 2,
385584
        ParachainInfo: parachain_info = 3,
385584
        Sudo: pallet_sudo = 4,
385584
        Utility: pallet_utility = 5,
385584
        Proxy: pallet_proxy = 6,
385584
        Migrations: pallet_migrations = 7,
385584
        MaintenanceMode: pallet_maintenance_mode = 8,
385584
        TxPause: pallet_tx_pause = 9,
385584

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

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

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

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

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

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

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

            
385584
        RootTesting: pallet_root_testing = 100,
385584
        AsyncBacking: pallet_async_backing::{Pallet, Storage} = 110,
385584
    }
3394903
);
#[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]
        [cumulus_pallet_dmp_queue, DmpQueue]
        [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]
    );
}
159276
impl_runtime_apis! {
37642
    impl sp_consensus_aura::AuraApi<Block, NimbusId> for Runtime {
37642
        fn slot_duration() -> sp_consensus_aura::SlotDuration {
6962
            sp_consensus_aura::SlotDuration::from_millis(SLOT_DURATION)
6962
        }
37642

            
37642
        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);
37642

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
37642
            add_benchmarks!(params, batches);
37642

            
37642
            Ok(batches)
37642
        }
37642
    }
37642

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

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

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

            
16
            assigned_collators.para_id_of(&account, self_para_id)
16
        }
37642

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

            
12
            match assigned_collators {
37650
                Some(assigned_collators) => {
8
                    let self_para_id = ParachainInfo::get();
8

            
8
                    assigned_collators.para_id_of(&account, self_para_id)
37642
                }
37642
                None => {
37646
                    Self::current_collator_parachain_assignment(account)
37642
                }
37642
            }
37642

            
37654
        }
37642

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

            
28
            if para_id == self_para_id {
37660
                Some(assigned_collators.orchestrator_chain)
37642
            } else {
37652
                assigned_collators.container_chains.get(&para_id).cloned()
37642
            }
37670
        }
37642
    }
37642

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

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

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

            
6814
            para_ids
6814
        }
37642

            
37642
        /// Fetch genesis data for this para id
37656
        fn genesis_data(para_id: ParaId) -> Option<ContainerChainGenesisData<MaxLengthTokenSymbol>> {
14
            Registrar::para_genesis_data(para_id)
14
        }
37642

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

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

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

            
37644
        fn latest_author(para_id: ParaId) -> Option<AccountId> {
2
            AuthorNoting::latest_author(para_id).map(|info| info.author)
2
        }
37642
    }
37642

            
37642
    impl dp_consensus::TanssiAuthorityAssignmentApi<Block, NimbusId> for Runtime {
37642
        /// Return the current authorities assigned to a given paraId
41934
        fn para_id_authorities(para_id: ParaId) -> Option<Vec<NimbusId>> {
11096
            let parent_number = System::block_number();
11096

            
11096
            let should_end_session = <Runtime as pallet_session::Config>::ShouldEndSession::should_end_session(parent_number + 1);
37642

            
41934
            let session_index = if should_end_session {
38050
                Session::current_index() +1
37642
            }
37642
            else {
41526
                Session::current_index()
37642
            };
37642

            
41934
            let assigned_authorities = AuthorityAssignment::collator_container_chain(session_index)?;
37642

            
41934
            let self_para_id = ParachainInfo::get();
11096

            
11096
            if para_id == self_para_id {
41918
                Some(assigned_authorities.orchestrator_chain)
37642
            } else {
37658
                assigned_authorities.container_chains.get(&para_id).cloned()
37642
            }
41934
        }
37642

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

            
37706
            let session_index = if should_end_session {
37658
                Session::current_index() +1
37642
            }
37642
            else {
37690
                Session::current_index()
37642
            };
37706
            let assigned_authorities = AuthorityAssignment::collator_container_chain(session_index)?;
37706
            let self_para_id = ParachainInfo::get();
64

            
64
            assigned_authorities.para_id_of(&authority, self_para_id)
37706
        }
37642

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

            
24
            assigned_authorities.para_id_of(&authority, self_para_id)
37666
        }
37642
    }
37642

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

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

            
37642
        fn query_weight_to_fee(weight: Weight) -> Balance {
20
            TransactionPayment::weight_to_fee(weight)
20
        }
37642

            
37642
        fn query_length_to_fee(length: u32) -> Balance {
6
            TransactionPayment::length_to_fee(length)
6
        }
37642
    }
37642

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

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

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

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

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

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

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

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

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

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

            
37642
        fn query_delivery_fees(destination: VersionedLocation, message: VersionedXcm<()>) -> Result<VersionedAssets, XcmPaymentApiError> {
            PolkadotXcm::query_delivery_fees(destination, message)
        }
37642
    }
159276
}
#[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
        }
    };
}